hash
stringlengths
40
40
date
stringdate
2019-01-29 11:49:07
2025-03-22 03:23:55
author
stringclasses
79 values
commit_message
stringlengths
14
85
is_merge
bool
1 class
git_diff
stringlengths
210
1.63M
type
stringclasses
8 values
masked_commit_message
stringlengths
8
79
0f45cb4a4cc37f356c67540d8c6caf70645f2c21
2024-06-10 12:44:55
Tom Payne
feat: Add stub for removed remove command
false
diff --git a/assets/chezmoi.io/docs/reference/commands/remove.md b/assets/chezmoi.io/docs/reference/commands/remove.md new file mode 100644 index 00000000000..cd3c635abd5 --- /dev/null +++ b/assets/chezmoi.io/docs/reference/commands/remove.md @@ -0,0 +1,4 @@ +# `remove` + +The `remove` command has been removed. Use the [`forget` command](forget.md) or +the [`destroy` command](destroy.md) instead. diff --git a/assets/chezmoi.io/docs/reference/commands/rm.md b/assets/chezmoi.io/docs/reference/commands/rm.md index cd07ade8ffa..18d8019a23e 100644 --- a/assets/chezmoi.io/docs/reference/commands/rm.md +++ b/assets/chezmoi.io/docs/reference/commands/rm.md @@ -1,3 +1,4 @@ -# `rm` *target*... +# `rm` -`rm` is an alias for [`remove`](remove.md). +The `rm` command has been removed. Use the [`forget` command](forget.md) or the +[`destroy` command](destroy.md) instead. diff --git a/assets/chezmoi.io/mkdocs.yml b/assets/chezmoi.io/mkdocs.yml index 3033df82373..098df462b8d 100644 --- a/assets/chezmoi.io/mkdocs.yml +++ b/assets/chezmoi.io/mkdocs.yml @@ -168,6 +168,7 @@ nav: - merge-all: reference/commands/merge-all.md - purge: reference/commands/purge.md - re-add: reference/commands/re-add.md + - remove: reference/commands/remove.md - rm: reference/commands/rm.md - secret: reference/commands/secret.md - source-path: reference/commands/source-path.md diff --git a/internal/cmd/config.go b/internal/cmd/config.go index 94e998bbc51..88d92c73250 100644 --- a/internal/cmd/config.go +++ b/internal/cmd/config.go @@ -1667,6 +1667,7 @@ func (c *Config) newRootCmd() (*cobra.Command, error) { c.newMergeAllCmd(), c.newPurgeCmd(), c.newReAddCmd(), + c.newRemoveCmd(), c.newSecretCmd(), c.newSourcePathCmd(), c.newStateCmd(), diff --git a/internal/cmd/removecmd.go b/internal/cmd/removecmd.go new file mode 100644 index 00000000000..6d0b3813bf7 --- /dev/null +++ b/internal/cmd/removecmd.go @@ -0,0 +1,26 @@ +package cmd + +import ( + "github.com/spf13/cobra" + + "github.com/twpayne/chezmoi/v2/internal/chezmoi" +) + +func (c *Config) newRemoveCmd() *cobra.Command { + removeCmd := &cobra.Command{ + Deprecated: "remove has been removed, use forget or destroy instead", + Use: "remove", + Aliases: []string{"rm"}, + RunE: c.runRemoveCmd, + Long: mustLongHelp("remove"), + Annotations: newAnnotations( + doesNotRequireValidConfig, + ), + } + + return removeCmd +} + +func (c *Config) runRemoveCmd(cmd *cobra.Command, args []string) error { + return chezmoi.ExitCodeError(1) +} diff --git a/internal/cmd/testdata/scripts/remove.txtar b/internal/cmd/testdata/scripts/remove.txtar new file mode 100644 index 00000000000..a69485a99bd --- /dev/null +++ b/internal/cmd/testdata/scripts/remove.txtar @@ -0,0 +1,7 @@ +# test that chezmoi remove produces an error +! exec chezmoi remove +stderr 'remove has been removed, use forget or destroy instead' + +# test that chezmoi rm produces an error +! exec chezmoi rm +stderr 'remove has been removed, use forget or destroy instead'
feat
Add stub for removed remove command
65d7d924797594e016492730108f080014b0af15
2024-12-12 05:25:41
Tom Payne
chore: Run make format
false
diff --git a/internal/chezmoi/sourcestate.go b/internal/chezmoi/sourcestate.go index dd186addd20..ff56423cd6f 100644 --- a/internal/chezmoi/sourcestate.go +++ b/internal/chezmoi/sourcestate.go @@ -1713,7 +1713,8 @@ func (s *SourceState) getExternalData( var errs []error - if external.Checksum.Size != 0 && external.Checksum.SHA256 == nil && external.Checksum.SHA384 == nil && external.Checksum.SHA512 == nil { + if external.Checksum.Size != 0 && external.Checksum.SHA256 == nil && external.Checksum.SHA384 == nil && + external.Checksum.SHA512 == nil { s.warnFunc("%s: warning: insecure size check without secure hash will be removed\n", externalRelPath) if len(data) != external.Checksum.Size { err := fmt.Errorf("size mismatch: expected %d, got %d", external.Checksum.Size, len(data)) @@ -1722,7 +1723,10 @@ func (s *SourceState) getExternalData( } if external.Checksum.MD5 != nil { - s.warnFunc("%s: warning: insecure MD5 checksum will be removed, use a secure hash like SHA256 instead\n", externalRelPath) + s.warnFunc( + "%s: warning: insecure MD5 checksum will be removed, use a secure hash like SHA256 instead\n", + externalRelPath, + ) if gotMD5Sum := md5Sum(data); !bytes.Equal(gotMD5Sum, external.Checksum.MD5) { err := fmt.Errorf("MD5 mismatch: expected %s, got %s", external.Checksum.MD5, hex.EncodeToString(gotMD5Sum)) errs = append(errs, err) @@ -1730,7 +1734,10 @@ func (s *SourceState) getExternalData( } if external.Checksum.RIPEMD160 != nil { - s.warnFunc("%s: warning: insecure RIPEMD-160 checksum will be removed, use a secure hash like SHA256 instead\n", externalRelPath) + s.warnFunc( + "%s: warning: insecure RIPEMD-160 checksum will be removed, use a secure hash like SHA256 instead\n", + externalRelPath, + ) if gotRIPEMD160Sum := ripemd160Sum(data); !bytes.Equal(gotRIPEMD160Sum, external.Checksum.RIPEMD160) { format := "RIPEMD-160 mismatch: expected %s, got %s" err := fmt.Errorf(format, external.Checksum.RIPEMD160, hex.EncodeToString(gotRIPEMD160Sum)) @@ -1739,7 +1746,10 @@ func (s *SourceState) getExternalData( } if external.Checksum.SHA1 != nil { - s.warnFunc("%s: warning: insecure SHA1 checksum will be removed, use a secure hash like SHA256 instead\n", externalRelPath) + s.warnFunc( + "%s: warning: insecure SHA1 checksum will be removed, use a secure hash like SHA256 instead\n", + externalRelPath, + ) if gotSHA1Sum := sha1Sum(data); !bytes.Equal(gotSHA1Sum, external.Checksum.SHA1) { err := fmt.Errorf("SHA1 mismatch: expected %s, got %s", external.Checksum.SHA1, hex.EncodeToString(gotSHA1Sum)) errs = append(errs, err)
chore
Run make format
62f6c6fbe942b75f4195fe0a1fecec447d5de949
2024-12-23 23:43:47
Tom Payne
chore: Update dependencies
false
diff --git a/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubLatestRelease.md b/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubLatestRelease.md index 9d3a01e051d..d5ffb94f649 100644 --- a/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubLatestRelease.md +++ b/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubLatestRelease.md @@ -3,7 +3,7 @@ `gitHubLatestRelease` calls the GitHub API to retrieve the latest release about the given *owner-repo*, returning structured data as defined by the [GitHub Go API -bindings](https://pkg.go.dev/github.com/google/go-github/v63/github#RepositoryRelease). +bindings](https://pkg.go.dev/github.com/google/go-github/v68/github#RepositoryRelease). Calls to `gitHubLatestRelease` are cached so calling `gitHubLatestRelease` with the same *owner-repo* will only result in one call to the GitHub API. diff --git a/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubLatestReleaseAssetURL.md b/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubLatestReleaseAssetURL.md index 73e9c66e587..e8d3e4f6516 100644 --- a/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubLatestReleaseAssetURL.md +++ b/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubLatestReleaseAssetURL.md @@ -3,7 +3,7 @@ `gitHubLatestReleaseAssetURL` calls the GitHub API to retrieve the latest release about the given *owner-repo*, returning structured data as defined by the [GitHub Go API -bindings](https://pkg.go.dev/github.com/google/go-github/v63/github#RepositoryRelease). +bindings](https://pkg.go.dev/github.com/google/go-github/v68/github#RepositoryRelease). It then iterates through all the release's assets, returning the first one that matches *pattern*. *pattern* is a shell pattern as [described in `path.Match`](https://pkg.go.dev/path#Match). diff --git a/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubLatestTag.md b/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubLatestTag.md index d4f1454ea07..bfdaecd7019 100644 --- a/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubLatestTag.md +++ b/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubLatestTag.md @@ -2,7 +2,7 @@ `gitHubLatestTag` calls the GitHub API to retrieve the latest tag for the given *owner-repo*, returning structured data as defined by the [GitHub Go API -bindings](https://pkg.go.dev/github.com/google/go-github/v63/github#RepositoryTag). +bindings](https://pkg.go.dev/github.com/google/go-github/v68/github#RepositoryTag). Calls to `gitHubLatestTag` are cached the same as [`githubTags`](gitHubTags.md), so calling `gitHubLatestTag` with the same *owner-repo* will only result in one diff --git a/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubRelease.md b/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubRelease.md index cc2635b05ac..6dd3a277a09 100644 --- a/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubRelease.md +++ b/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubRelease.md @@ -5,7 +5,7 @@ the given *owner-repo*, It iterates through all the versions of the release, fetching the first entry equal to *version*. It then returns structured data as defined by the [GitHub Go API -bindings](https://pkg.go.dev/github.com/google/go-github/v63/github#RepositoryRelease). +bindings](https://pkg.go.dev/github.com/google/go-github/v68/github#RepositoryRelease). Calls to `gitHubRelease` are cached so calling `gitHubRelease` with the same *owner-repo* *version* will only result in one call to the GitHub API. diff --git a/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubReleaseAssetURL.md b/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubReleaseAssetURL.md index ed91b917a72..f627da77025 100644 --- a/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubReleaseAssetURL.md +++ b/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubReleaseAssetURL.md @@ -3,7 +3,7 @@ `gitHubReleaseAssetURL` calls the GitHub API to retrieve the latest releases about the given *owner-repo*, returning structured data as defined by the [GitHub Go API -bindings](https://pkg.go.dev/github.com/google/go-github/v63/github#RepositoryRelease). +bindings](https://pkg.go.dev/github.com/google/go-github/v68/github#RepositoryRelease). It iterates through all the versions of the release, returning the first entry equal to *version*. It then iterates through all the release's assets, returning the first one that matches *pattern*. *pattern* is a shell pattern as [described in diff --git a/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubReleases.md b/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubReleases.md index 3b6810b59b2..fe41ce6ecd3 100644 --- a/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubReleases.md +++ b/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubReleases.md @@ -3,7 +3,7 @@ `gitHubReleases` calls the GitHub API to retrieve the first page of releases for the given *owner-repo*, returning structured data as defined by the [GitHub Go API -bindings](https://pkg.go.dev/github.com/google/go-github/v63/github#RepositoryRelease). +bindings](https://pkg.go.dev/github.com/google/go-github/v68/github#RepositoryRelease). Calls to `gitHubReleases` are cached so calling `gitHubReleases` with the same *owner-repo* will only result in one call to the GitHub API. diff --git a/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubTags.md b/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubTags.md index a1627e8cac1..961497d143c 100644 --- a/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubTags.md +++ b/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubTags.md @@ -3,7 +3,7 @@ `gitHubTags` calls the GitHub API to retrieve the first page of tags for the given *owner-repo*, returning structured data as defined by the [GitHub Go API -bindings](https://pkg.go.dev/github.com/google/go-github/v63/github#RepositoryTag). +bindings](https://pkg.go.dev/github.com/google/go-github/v68/github#RepositoryTag). Calls to `gitHubTags` are cached so calling `gitHubTags` with the same *owner-repo* will only result in one call to the GitHub API. diff --git a/go.mod b/go.mod index 260709d8c60..fa0a550a41d 100644 --- a/go.mod +++ b/go.mod @@ -21,7 +21,7 @@ require ( github.com/coreos/go-semver v0.3.1 github.com/fsnotify/fsnotify v1.8.0 github.com/go-git/go-git/v5 v5.12.0 - github.com/google/go-github/v67 v67.0.0 + github.com/google/go-github/v68 v68.0.0 github.com/google/renameio/v2 v2.0.0 github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 github.com/itchyny/gojq v0.12.17 @@ -38,7 +38,7 @@ require ( github.com/tailscale/hujson v0.0.0-20241010212012-29efb4a0184b github.com/twpayne/go-expect v0.0.2-0.20241130000624-916db2914efd github.com/twpayne/go-pinentry/v4 v4.0.0 - github.com/twpayne/go-shell v0.4.0 + github.com/twpayne/go-shell v0.5.0 github.com/twpayne/go-vfs/v5 v5.0.4 github.com/twpayne/go-xdg/v6 v6.1.3 github.com/ulikunitz/xz v0.5.12 @@ -164,6 +164,6 @@ require ( golang.org/x/net v0.33.0 // indirect golang.org/x/text v0.21.0 // indirect golang.org/x/tools v0.28.0 // indirect - google.golang.org/protobuf v1.36.0 // indirect + google.golang.org/protobuf v1.36.1 // indirect gopkg.in/warnings.v0 v0.1.2 // indirect ) diff --git a/go.sum b/go.sum index 45295b4b155..eb54721bb14 100644 --- a/go.sum +++ b/go.sum @@ -223,8 +223,8 @@ github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl76 github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/google/go-github/v67 v67.0.0 h1:g11NDAmfaBaCO8qYdI9fsmbaRipHNWRIU/2YGvlh4rg= -github.com/google/go-github/v67 v67.0.0/go.mod h1:zH3K7BxjFndr9QSeFibx4lTKkYS3K9nDanoI1NjaOtY= +github.com/google/go-github/v68 v68.0.0 h1:ZW57zeNZiXTdQ16qrDiZ0k6XucrxZ2CGmoTvcCyQG6s= +github.com/google/go-github/v68 v68.0.0/go.mod h1:K9HAUBovM2sLwM408A18h+wd9vqdLOEqTUCbnRIcx68= github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8= github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU= github.com/google/renameio/v2 v2.0.0 h1:UifI23ZTGY8Tt29JbYFiuyIU3eX+RNFtUwefq9qAhxg= @@ -454,8 +454,8 @@ github.com/twpayne/go-expect v0.0.2-0.20241130000624-916db2914efd h1:/ekqcdG89eu github.com/twpayne/go-expect v0.0.2-0.20241130000624-916db2914efd/go.mod h1:Z1PlEHxKw23bid0pq2RhO4NMScxckEhBXZLebwJpjrk= github.com/twpayne/go-pinentry/v4 v4.0.0 h1:8WcNa+UDVRzz7y9OEEU/nRMX+UGFPCAvl5XsqWRxTY4= github.com/twpayne/go-pinentry/v4 v4.0.0/go.mod h1:aXvy+awVXqdH+GS0ddQ7AKHZ3tXM6fJ2NK+e16p47PI= -github.com/twpayne/go-shell v0.4.0 h1:RAAMbjEj7mcwDdwC7SiFHGUKR+WDAURU6mnyd3r2p2E= -github.com/twpayne/go-shell v0.4.0/go.mod h1:MP3aUA0TQ3IGoJc15ahjb+7A7wZH4NeGrvLZ/aFQsHc= +github.com/twpayne/go-shell v0.5.0 h1:Mgd2GReIHdsCRT9OqYCh/ywf7x9r9cJhsZMIqKSVjIU= +github.com/twpayne/go-shell v0.5.0/go.mod h1:MP3aUA0TQ3IGoJc15ahjb+7A7wZH4NeGrvLZ/aFQsHc= github.com/twpayne/go-vfs/v5 v5.0.4 h1:/ne3h+rW7f5YOyOFguz+3ztfUwzOLR0Vts3y0mMAitg= github.com/twpayne/go-vfs/v5 v5.0.4/go.mod h1:zTPFJUbgsEMFNSWnWQlLq9wh4AN83edZzx3VXbxrS1w= github.com/twpayne/go-xdg/v6 v6.1.3 h1:viM0S9v4KAc0IRW2xI3Zp8ZkqOCoCxmCmVZ7GTnG0y0= @@ -607,8 +607,8 @@ google.golang.org/genproto/googleapis/rpc v0.0.0-20241118233622-e639e219e697 h1: google.golang.org/genproto/googleapis/rpc v0.0.0-20241118233622-e639e219e697/go.mod h1:5uTbfoYQed2U9p3KIj2/Zzm02PYhndfdmML0qC3q3FU= google.golang.org/grpc v1.68.0 h1:aHQeeJbo8zAkAa3pRzrVjZlbz6uSfeOXlJNQM0RAbz0= google.golang.org/grpc v1.68.0/go.mod h1:fmSPC5AsjSBCK54MyHRx48kpOti1/jRfOlwEWywNjWA= -google.golang.org/protobuf v1.36.0 h1:mjIs9gYtt56AzC4ZaffQuh88TZurBGhIJMBZGSxNerQ= -google.golang.org/protobuf v1.36.0/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= +google.golang.org/protobuf v1.36.1 h1:yBPeRvTftaleIgM3PZ/WBIZ7XM/eEYAaEyCwvyjq/gk= +google.golang.org/protobuf v1.36.1/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= diff --git a/internal/chezmoi/github.go b/internal/chezmoi/github.go index bcd051aa612..ec22bfa14b1 100644 --- a/internal/chezmoi/github.go +++ b/internal/chezmoi/github.go @@ -5,7 +5,7 @@ import ( "net/http" "os" - "github.com/google/go-github/v67/github" + "github.com/google/go-github/v68/github" "golang.org/x/oauth2" ) diff --git a/internal/cmd/doctorcmd.go b/internal/cmd/doctorcmd.go index 5efba34a257..a52c62c29ba 100644 --- a/internal/cmd/doctorcmd.go +++ b/internal/cmd/doctorcmd.go @@ -20,7 +20,7 @@ import ( "time" "github.com/coreos/go-semver/semver" - "github.com/google/go-github/v67/github" + "github.com/google/go-github/v68/github" "github.com/spf13/cobra" "github.com/twpayne/go-shell" "github.com/twpayne/go-xdg/v6" diff --git a/internal/cmd/githubtemplatefuncs.go b/internal/cmd/githubtemplatefuncs.go index 8cfb40c96d6..94135ae6909 100644 --- a/internal/cmd/githubtemplatefuncs.go +++ b/internal/cmd/githubtemplatefuncs.go @@ -7,7 +7,7 @@ import ( "strings" "time" - "github.com/google/go-github/v67/github" + "github.com/google/go-github/v68/github" "github.com/twpayne/chezmoi/v2/internal/chezmoi" ) diff --git a/internal/cmd/upgradecmd.go b/internal/cmd/upgradecmd.go index dfd6bcd71c8..829160b4276 100644 --- a/internal/cmd/upgradecmd.go +++ b/internal/cmd/upgradecmd.go @@ -21,7 +21,7 @@ import ( "strings" "github.com/coreos/go-semver/semver" - "github.com/google/go-github/v67/github" + "github.com/google/go-github/v68/github" "github.com/spf13/cobra" "github.com/twpayne/chezmoi/v2/internal/chezmoi" diff --git a/internal/cmd/upgradecmd_unix.go b/internal/cmd/upgradecmd_unix.go index 2e43572114e..eb81092febc 100644 --- a/internal/cmd/upgradecmd_unix.go +++ b/internal/cmd/upgradecmd_unix.go @@ -15,7 +15,7 @@ import ( "strings" "github.com/coreos/go-semver/semver" - "github.com/google/go-github/v67/github" + "github.com/google/go-github/v68/github" vfs "github.com/twpayne/go-vfs/v5" "github.com/twpayne/chezmoi/v2/internal/chezmoi" diff --git a/internal/cmd/upgradecmd_windows.go b/internal/cmd/upgradecmd_windows.go index 355a3395f1f..6e3ab3b746f 100644 --- a/internal/cmd/upgradecmd_windows.go +++ b/internal/cmd/upgradecmd_windows.go @@ -10,7 +10,7 @@ import ( "path/filepath" "github.com/coreos/go-semver/semver" - "github.com/google/go-github/v67/github" + "github.com/google/go-github/v68/github" vfs "github.com/twpayne/go-vfs/v5" "github.com/twpayne/chezmoi/v2/internal/chezmoi" diff --git a/internal/cmds/execute-template/main.go b/internal/cmds/execute-template/main.go index 1b1541fccb3..c38b332a648 100644 --- a/internal/cmds/execute-template/main.go +++ b/internal/cmds/execute-template/main.go @@ -16,7 +16,7 @@ import ( "text/template" "github.com/Masterminds/sprig/v3" - "github.com/google/go-github/v67/github" + "github.com/google/go-github/v68/github" "github.com/google/renameio/v2/maybe" "gopkg.in/yaml.v3"
chore
Update dependencies
31b2060afb3efe8c24f8181548d8cf44ec3799da
2024-06-26 22:02:53
Tom Payne
feat: Embed fallback X.509 trusted roots
false
diff --git a/go.mod b/go.mod index 33d77ed2a4e..004ad1306ef 100644 --- a/go.mod +++ b/go.mod @@ -47,6 +47,7 @@ require ( github.com/zricethezav/gitleaks/v8 v8.18.4 go.etcd.io/bbolt v1.3.10 golang.org/x/crypto v0.24.0 + golang.org/x/crypto/x509roots/fallback v0.0.0-20240624163532-1c7450041f58 golang.org/x/oauth2 v0.21.0 golang.org/x/sync v0.7.0 golang.org/x/sys v0.21.0 diff --git a/go.sum b/go.sum index 798849cabe6..11e8c5fa2eb 100644 --- a/go.sum +++ b/go.sum @@ -498,6 +498,8 @@ golang.org/x/crypto v0.3.1-0.20221117191849-2c476679df9a/go.mod h1:hebNnKkNXi2Uz golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= golang.org/x/crypto v0.24.0 h1:mnl8DM0o513X8fdIkmyFE/5hTYxbwYOjDS/+rK6qpRI= golang.org/x/crypto v0.24.0/go.mod h1:Z1PMYSOR5nyMcyAVAIQSKCDwalqy85Aqn1x3Ws4L5DM= +golang.org/x/crypto/x509roots/fallback v0.0.0-20240624163532-1c7450041f58 h1:FQBNkSe29+6BkKYNIXZkLKylo2wpq7HGYfxUlv8bfEk= +golang.org/x/crypto/x509roots/fallback v0.0.0-20240624163532-1c7450041f58/go.mod h1:kNa9WdvYnzFwC79zRpLRMJbdEFlhyM5RPFBBZp/wWH8= golang.org/x/exp v0.0.0-20240613232115-7f521ea00fb8 h1:yixxcjnhBmY0nkL253HFVIm0JsFHwrHdT3Yh6szTnfY= golang.org/x/exp v0.0.0-20240613232115-7f521ea00fb8/go.mod h1:jj3sYF3dwk5D+ghuXyeI3r5MFf+NT2An6/9dOA95KSI= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= diff --git a/main.go b/main.go index cd01221e876..0994a462c96 100644 --- a/main.go +++ b/main.go @@ -10,6 +10,8 @@ package main import ( "os" + _ "golang.org/x/crypto/x509roots/fallback" // Embed fallback X.509 trusted roots + "github.com/twpayne/chezmoi/v2/internal/cmd" )
feat
Embed fallback X.509 trusted roots
ad72fa1f0c4b1466caadd50c7f02d59a7e8a2908
2024-05-20 13:54:11
Tom Payne
chore: Update dependencies
false
diff --git a/go.mod b/go.mod index 9e36cbf3375..a3bfc1c4158 100644 --- a/go.mod +++ b/go.mod @@ -10,11 +10,11 @@ require ( github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.1.0 github.com/Masterminds/sprig/v3 v3.2.3 github.com/Netflix/go-expect v0.0.0-20220104043353-73e0943537d2 - github.com/Shopify/ejson v1.5.0 + github.com/Shopify/ejson v1.5.1 github.com/alecthomas/assert/v2 v2.9.0 - github.com/aws/aws-sdk-go-v2 v1.26.1 - github.com/aws/aws-sdk-go-v2/config v1.27.13 - github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.28.7 + github.com/aws/aws-sdk-go-v2 v1.27.0 + github.com/aws/aws-sdk-go-v2/config v1.27.15 + github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.28.9 github.com/bmatcuk/doublestar/v4 v4.6.1 github.com/bradenhilton/mozillainstallhash v1.0.1 github.com/charmbracelet/bubbles v0.18.0 @@ -72,16 +72,16 @@ require ( github.com/alecthomas/repr v0.4.0 // indirect github.com/alessio/shellescape v1.4.2 // indirect github.com/atotto/clipboard v0.1.4 // indirect - github.com/aws/aws-sdk-go-v2/credentials v1.17.13 // indirect - github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.1 // indirect - github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.5 // indirect - github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.5 // indirect + github.com/aws/aws-sdk-go-v2/credentials v1.17.15 // indirect + github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.3 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.7 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.7 // indirect github.com/aws/aws-sdk-go-v2/internal/ini v1.8.0 // indirect github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.11.2 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.7 // indirect - github.com/aws/aws-sdk-go-v2/service/sso v1.20.6 // indirect - github.com/aws/aws-sdk-go-v2/service/ssooidc v1.24.0 // indirect - github.com/aws/aws-sdk-go-v2/service/sts v1.28.7 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.9 // indirect + github.com/aws/aws-sdk-go-v2/service/sso v1.20.8 // indirect + github.com/aws/aws-sdk-go-v2/service/ssooidc v1.24.2 // indirect + github.com/aws/aws-sdk-go-v2/service/sts v1.28.9 // indirect github.com/aws/smithy-go v1.20.2 // indirect github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect github.com/aymerick/douceur v0.2.0 // indirect diff --git a/go.sum b/go.sum index 138d6b00c7b..b60b97c4146 100644 --- a/go.sum +++ b/go.sum @@ -44,8 +44,8 @@ github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERo github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= github.com/ProtonMail/go-crypto v1.0.0 h1:LRuvITjQWX+WIfr930YHG2HNfjR1uOfyf5vE0kC2U78= github.com/ProtonMail/go-crypto v1.0.0/go.mod h1:EjAoLdwvbIOoOQr3ihjnSoLZRtE8azugULFRteWMNc0= -github.com/Shopify/ejson v1.5.0 h1:SDV5HmQlpn3hSUiw9HV0nOj9tpzup5i0OV71ioLYkpw= -github.com/Shopify/ejson v1.5.0/go.mod h1:a4+JLWuTe9+tTofPBGWZoqzf0af6eQKGmFqbxoMSARc= +github.com/Shopify/ejson v1.5.1 h1:LVphADjSUMao+VPux/2GE5CYVW9U30/XLmStmjKXCQI= +github.com/Shopify/ejson v1.5.1/go.mod h1:bVvQ3MaBCfMOkIp1rWZcot3TruYXCc7qUUbI1tjs/YM= github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d h1:licZJFw2RwpHMqeKTCYkitsPqHNxTmd4SNR5r94FGM8= github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d/go.mod h1:asat636LX7Bqt5lYEZ27JNDcqxfjdBQuJ/MM4CN/Lzo= github.com/alecthomas/assert/v2 v2.9.0 h1:ZcLG8ccMEtlMLkLW4gwGpBWBb0N8MUCmsy1lYBVd1xQ= @@ -64,32 +64,32 @@ github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPd github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= -github.com/aws/aws-sdk-go-v2 v1.26.1 h1:5554eUqIYVWpU0YmeeYZ0wU64H2VLBs8TlhRB2L+EkA= -github.com/aws/aws-sdk-go-v2 v1.26.1/go.mod h1:ffIFB97e2yNsv4aTSGkqtHnppsIJzw7G7BReUZ3jCXM= -github.com/aws/aws-sdk-go-v2/config v1.27.13 h1:WbKW8hOzrWoOA/+35S5okqO/2Ap8hkkFUzoW8Hzq24A= -github.com/aws/aws-sdk-go-v2/config v1.27.13/go.mod h1:XLiyiTMnguytjRER7u5RIkhIqS8Nyz41SwAWb4xEjxs= -github.com/aws/aws-sdk-go-v2/credentials v1.17.13 h1:XDCJDzk/u5cN7Aple7D/MiAhx1Rjo/0nueJ0La8mRuE= -github.com/aws/aws-sdk-go-v2/credentials v1.17.13/go.mod h1:FMNcjQrmuBYvOTZDtOLCIu0esmxjF7RuA/89iSXWzQI= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.1 h1:FVJ0r5XTHSmIHJV6KuDmdYhEpvlHpiSd38RQWhut5J4= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.1/go.mod h1:zusuAeqezXzAB24LGuzuekqMAEgWkVYukBec3kr3jUg= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.5 h1:aw39xVGeRWlWx9EzGVnhOR4yOjQDHPQ6o6NmBlscyQg= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.5/go.mod h1:FSaRudD0dXiMPK2UjknVwwTYyZMRsHv3TtkabsZih5I= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.5 h1:PG1F3OD1szkuQPzDw3CIQsRIrtTlUC3lP84taWzHlq0= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.5/go.mod h1:jU1li6RFryMz+so64PpKtudI+QzbKoIEivqdf6LNpOc= +github.com/aws/aws-sdk-go-v2 v1.27.0 h1:7bZWKoXhzI+mMR/HjdMx8ZCC5+6fY0lS5tr0bbgiLlo= +github.com/aws/aws-sdk-go-v2 v1.27.0/go.mod h1:ffIFB97e2yNsv4aTSGkqtHnppsIJzw7G7BReUZ3jCXM= +github.com/aws/aws-sdk-go-v2/config v1.27.15 h1:uNnGLZ+DutuNEkuPh6fwqK7LpEiPmzb7MIMA1mNWEUc= +github.com/aws/aws-sdk-go-v2/config v1.27.15/go.mod h1:7j7Kxx9/7kTmL7z4LlhwQe63MYEE5vkVV6nWg4ZAI8M= +github.com/aws/aws-sdk-go-v2/credentials v1.17.15 h1:YDexlvDRCA8ems2T5IP1xkMtOZ1uLJOCJdTr0igs5zo= +github.com/aws/aws-sdk-go-v2/credentials v1.17.15/go.mod h1:vxHggqW6hFNaeNC0WyXS3VdyjcV0a4KMUY4dKJ96buU= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.3 h1:dQLK4TjtnlRGb0czOht2CevZ5l6RSyRWAnKeGd7VAFE= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.3/go.mod h1:TL79f2P6+8Q7dTsILpiVST+AL9lkF6PPGI167Ny0Cjw= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.7 h1:lf/8VTF2cM+N4SLzaYJERKEWAXq8MOMpZfU6wEPWsPk= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.7/go.mod h1:4SjkU7QiqK2M9oozyMzfZ/23LmUY+h3oFqhdeP5OMiI= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.7 h1:4OYVp0705xu8yjdyoWix0r9wPIRXnIzzOoUpQVHIJ/g= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.7/go.mod h1:vd7ESTEvI76T2Na050gODNmNU7+OyKrIKroYTu4ABiI= github.com/aws/aws-sdk-go-v2/internal/ini v1.8.0 h1:hT8rVHwugYE2lEfdFE0QWVo81lF7jMrYJVDWI+f+VxU= github.com/aws/aws-sdk-go-v2/internal/ini v1.8.0/go.mod h1:8tu/lYfQfFe6IGnaOdrpVgEL2IrrDOf6/m9RQum4NkY= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.11.2 h1:Ji0DY1xUsUr3I8cHps0G+XM3WWU16lP6yG8qu1GAZAs= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.11.2/go.mod h1:5CsjAbs3NlGQyZNFACh+zztPDI7fU6eW9QsxjfnuBKg= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.7 h1:ogRAwT1/gxJBcSWDMZlgyFUM962F51A5CRhDLbxLdmo= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.7/go.mod h1:YCsIZhXfRPLFFCl5xxY+1T9RKzOKjCut+28JSX2DnAk= -github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.28.7 h1:4cziOtpDwtgcb+wTYRzz8C+GoH1XySy0p7j4oBbqPQE= -github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.28.7/go.mod h1:3Ba++UwWd154xtP4FRX5pUK3Gt4up5sDHCve6kVfE+g= -github.com/aws/aws-sdk-go-v2/service/sso v1.20.6 h1:o5cTaeunSpfXiLTIBx5xo2enQmiChtu1IBbzXnfU9Hs= -github.com/aws/aws-sdk-go-v2/service/sso v1.20.6/go.mod h1:qGzynb/msuZIE8I75DVRCUXw3o3ZyBmUvMwQ2t/BrGM= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.24.0 h1:Qe0r0lVURDDeBQJ4yP+BOrJkvkiCo/3FH/t+wY11dmw= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.24.0/go.mod h1:mUYPBhaF2lGiukDEjJX2BLRRKTmoUSitGDUgM4tRxak= -github.com/aws/aws-sdk-go-v2/service/sts v1.28.7 h1:et3Ta53gotFR4ERLXXHIHl/Uuk1qYpP5uU7cvNql8ns= -github.com/aws/aws-sdk-go-v2/service/sts v1.28.7/go.mod h1:FZf1/nKNEkHdGGJP/cI2MoIMquumuRK6ol3QQJNDxmw= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.9 h1:Wx0rlZoEJR7JwlSZcHnEa7CNjrSIyVxMFWGAaXy4fJY= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.9/go.mod h1:aVMHdE0aHO3v+f/iw01fmXV/5DbfQ3Bi9nN7nd9bE9Y= +github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.28.9 h1:qH8ovDAQkGLgYh/QEEKx/uSDL1vCIuVB2VIZJsVr4dA= +github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.28.9/go.mod h1:5mMk0DgUgaHlcqtN65fNyZI0ZDX3i9Cw+nwq75HKB3U= +github.com/aws/aws-sdk-go-v2/service/sso v1.20.8 h1:Kv1hwNG6jHC/sxMTe5saMjH6t6ZLkgfvVxyEjfWL1ks= +github.com/aws/aws-sdk-go-v2/service/sso v1.20.8/go.mod h1:c1qtZUWtygI6ZdvKppzCSXsDOq5I4luJPZ0Ud3juFCA= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.24.2 h1:nWBZ1xHCF+A7vv9sDzJOq4NWIdzFYm0kH7Pr4OjHYsQ= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.24.2/go.mod h1:9lmoVDVLz/yUZwLaQ676TK02fhCu4+PgRSmMaKR1ozk= +github.com/aws/aws-sdk-go-v2/service/sts v1.28.9 h1:Qp6Boy0cGDloOE3zI6XhNLNZgjNS8YmiFQFHe71SaW0= +github.com/aws/aws-sdk-go-v2/service/sts v1.28.9/go.mod h1:0Aqn1MnEuitqfsCNyKsdKLhDUOr4txD/g19EfiUqgws= github.com/aws/smithy-go v1.20.2 h1:tbp628ireGtzcHDDmLT/6ADHidqnwgF57XOXZe6tp4Q= github.com/aws/smithy-go v1.20.2/go.mod h1:krry+ya/rV9RDcV/Q16kpu6ypI4K2czasz0NC3qS14E= github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
chore
Update dependencies
635e4f28b5065fd3a3d9a091fdfac186db4ce264
2023-01-15 22:27:54
Tom Payne
chore: Use a different token to upload checksums.txt
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index c7086ce91f2..4283819233b 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -425,17 +425,21 @@ jobs: GITHUB_TOKEN: ${{ secrets.GORELEASER_GITHUB_TOKEN }} SCOOP_GITHUB_TOKEN: ${{ secrets.SCOOP_GITHUB_TOKEN }} SNAPCRAFT_STORE_CREDENTIALS: ${{ secrets.SNAPCRAFT_STORE_CREDENTIALS }} - # The following is needed because chezmoi upgrade and - # assets/scripts/install.sh have inconsistently looked for - # chezmoi_${VERSION}_checksums.txt and checksums.txt. To ensure - # compatibility with all versions, upload checksums.txt as well. + # The following is needed because chezmoi upgrade and + # assets/scripts/install.sh have inconsistently looked for + # chezmoi_${VERSION}_checksums.txt and checksums.txt. To ensure + # compatibility with all versions, upload checksums.txt as well. + # + # We need to use a different GitHub token as fine-grained personal access + # tokens do not allow access to the GraphQL API, which gh depends on. So, we + # use a normal PAT instead. - name: upload-checksums.txt run: | VERSION=${GITHUB_REF##*/v} cp dist/chezmoi_${VERSION}_checksums.txt dist/checksums.txt gh release upload v${VERSION} dist/checksums.txt env: - GITHUB_TOKEN: ${{ secrets.GORELEASER_GITHUB_TOKEN }} + GITHUB_TOKEN: ${{ secrets.RELEASE_GITHUB_TOKEN }} deploy-website: needs: - release
chore
Use a different token to upload checksums.txt
63d7d6b147cc27e540376af63c55832fbce63772
2022-09-17 00:14:59
Tom Payne
chore: Add quit option to state reset command
false
diff --git a/pkg/cmd/statecmd.go b/pkg/cmd/statecmd.go index 2316b1cd5d7..7c4f25f374e 100644 --- a/pkg/cmd/statecmd.go +++ b/pkg/cmd/statecmd.go @@ -221,11 +221,13 @@ func (c *Config) runStateResetCmd(cmd *cobra.Command, args []string) error { return err } if !c.force { - switch choice, err := c.promptChoice(fmt.Sprintf("Remove %s", persistentStateFileAbsPath), []string{"yes", "no"}); { + switch choice, err := c.promptChoice(fmt.Sprintf("Remove %s", persistentStateFileAbsPath), choicesYesNoQuit); { case err != nil: return err case choice == "yes": case choice == "no": + fallthrough + case choice == "quit": return nil } } diff --git a/pkg/cmd/util.go b/pkg/cmd/util.go index 42fd06c9662..e2865c56edb 100644 --- a/pkg/cmd/util.go +++ b/pkg/cmd/util.go @@ -20,6 +20,11 @@ var ( "all", "quit", } + choicesYesNoQuit = []string{ + "yes", + "no", + "quit", + } ) // englishList returns ss formatted as a list, including an Oxford comma.
chore
Add quit option to state reset command
33cc10c0365ed5b540dc5c3f05e92881b2ae402d
2022-02-25 04:26:23
Tom Payne
chore: Include docs changes in changelog
false
diff --git a/.goreleaser.yaml b/.goreleaser.yaml index 476578a7edb..6802192dade 100644 --- a/.goreleaser.yaml +++ b/.goreleaser.yaml @@ -105,7 +105,6 @@ changelog: exclude: - "^chore:" - "^chore\\(deps\\):" - - "^docs:" - "^test:" - Merge pull request - Merge branch
chore
Include docs changes in changelog
55b72c657874a8f24911449b11186038cf2097f4
2022-11-11 23:39:28
Tom Payne
docs: Document that modify templates must not have a .tmpl extension
false
diff --git a/assets/chezmoi.io/docs/user-guide/manage-different-types-of-file.md b/assets/chezmoi.io/docs/user-guide/manage-different-types-of-file.md index ba48b1e38fa..578f6a9b8d0 100644 --- a/assets/chezmoi.io/docs/user-guide/manage-different-types-of-file.md +++ b/assets/chezmoi.io/docs/user-guide/manage-different-types-of-file.md @@ -94,6 +94,10 @@ contents of the file. {{ fromJson .chezmoi.stdin | setValueAtPath "key.nestedKey" "value" | toPrettyJson }} ``` +!!! warning + + Modify templates must not have a `.tmpl` extension. + Secondly, if only a small part of the file changes then consider using a template to re-generate the full contents of the file from the current state. For example, Kubernetes configurations include a current context that can be
docs
Document that modify templates must not have a .tmpl extension
17d2f7148367870c1411aa33ae78e92585776b50
2022-09-12 22:54:21
Tom Payne
chore: Refine comment
false
diff --git a/pkg/chezmoi/realsystem_unix.go b/pkg/chezmoi/realsystem_unix.go index 27cee82fa01..00e35803431 100644 --- a/pkg/chezmoi/realsystem_unix.go +++ b/pkg/chezmoi/realsystem_unix.go @@ -137,7 +137,7 @@ func writeFile(fileSystem vfs.FS, filename AbsPath, data []byte, perm fs.FileMod // Set permissions after truncation but before writing any data, in case the // file contained private data before, but before writing the new contents, - // in case the contents contain private data after. + // in case the new contents contain private data after. if err = f.Chmod(perm); err != nil { return }
chore
Refine comment
817d3e7f7d74970fecd80e18a55de3bae006ebe9
2022-06-20 05:35:05
Tom Payne
feat: Stop building snaps
false
diff --git a/.goreleaser.yaml b/.goreleaser.yaml index dace2e7fa67..cfa7fd1b684 100644 --- a/.goreleaser.yaml +++ b/.goreleaser.yaml @@ -205,21 +205,6 @@ scoop: description: "Manage your dotfiles across multiple diverse machines, securely." license: MIT -snapcrafts: -- builds: - - chezmoi-cgo-glibc - - chezmoi-nocgo - summary: "Manage your dotfiles across multiple diverse machines, securely." - description: "Manage your dotfiles across multiple diverse machines, securely." - publish: true - grade: stable - confinement: classic - license: MIT - apps: - chezmoi: - command: chezmoi - completer: completions/chezmoi-completion.bash - source: enabled: true prefix_template: '{{ .ProjectName }}-{{ .Version }}/' diff --git a/assets/chezmoi.io/docs/developer/releases.md b/assets/chezmoi.io/docs/developer/releases.md index 6109dbd023e..76d803e811c 100644 --- a/assets/chezmoi.io/docs/developer/releases.md +++ b/assets/chezmoi.io/docs/developer/releases.md @@ -5,10 +5,10 @@ Releases are managed with [`goreleaser`](https://goreleaser.com/). ## Testing To build a test release, without publishing, (Ubuntu Linux only) first ensure -that the `musl-tools` and `snapcraft` packages are installed: +that the `musl-tools` packages is installed: ```console -$ sudo apt-get install musl-tools snapcraft +$ sudo apt-get install musl-tools ``` Then run: @@ -26,17 +26,11 @@ $ git tag v1.2.3 $ git push --tags ``` -This triggers a [GitHub Action](https://github.com/twpayne/chezmoi/actions) -that builds and publishes archives, packages, and snaps, creates a new [GitHub +This triggers a [GitHub Action](https://github.com/twpayne/chezmoi/actions) that +builds and publishes archives, packages, creates a new [GitHub Release](https://github.com/twpayne/chezmoi/releases), and deploys the [website](https://chezmoi.io). -!!! note - - Publishing [Snaps](https://snapcraft.io/) requires a - `SNAPCRAFT_LOGIN_CREDENTIALS` [repository - secret](https://github.com/twpayne/chezmoi/settings/secrets/actions). - !!! note [brew](https://brew.sh/) automation will automatically detect new releases diff --git a/assets/chezmoi.io/docs/install.md.tmpl b/assets/chezmoi.io/docs/install.md.tmpl index 80012ef46cf..456c06c8940 100644 --- a/assets/chezmoi.io/docs/install.md.tmpl +++ b/assets/chezmoi.io/docs/install.md.tmpl @@ -51,12 +51,6 @@ Install chezmoi with your package manager with a single command: === "Linux" - === "snap" - - ```sh - snap install chezmoi --classic - ``` - === "Linuxbrew" ```sh diff --git a/pkg/cmd/config.go b/pkg/cmd/config.go index 2b5d89bb717..e06f18529f4 100644 --- a/pkg/cmd/config.go +++ b/pkg/cmd/config.go @@ -1727,21 +1727,6 @@ func (c *Config) persistentPreRunRootE(cmd *cobra.Command, args []string) error } } - // Create the runtime directory if needed. - if boolAnnotation(cmd, runsCommands) { - if runtime.GOOS == "linux" && c.bds.RuntimeDir != "" { - // Snap sets the $XDG_RUNTIME_DIR environment variable to - // /run/user/$uid/snap.$snap_name, but does not create this - // directory. Consequently, any spawned processes that need - // $XDG_DATA_DIR will fail. As a work-around, create the directory - // if it does not exist. See - // https://forum.snapcraft.io/t/wayland-dconf-and-xdg-runtime-dir/186/13. - if err := chezmoi.MkdirAll(c.baseSystem, chezmoi.NewAbsPath(c.bds.RuntimeDir), 0o700); err != nil { - return err - } - } - } - // Determine the working tree directory if it is not configured. if c.WorkingTreeAbsPath.Empty() { workingTreeAbsPath := c.SourceDirAbsPath diff --git a/pkg/cmd/upgradecmd.go b/pkg/cmd/upgradecmd.go index d7312df2da2..fecd9f5dab4 100644 --- a/pkg/cmd/upgradecmd.go +++ b/pkg/cmd/upgradecmd.go @@ -32,7 +32,6 @@ import ( const ( upgradeMethodBrewUpgrade = "brew-upgrade" upgradeMethodReplaceExecutable = "replace-executable" - upgradeMethodSnapRefresh = "snap-refresh" upgradeMethodUpgradePackage = "upgrade-package" upgradeMethodSudoPrefix = "sudo-" @@ -173,10 +172,6 @@ func (c *Config) runUpgradeCmd(cmd *cobra.Command, args []string) error { if err := c.replaceExecutable(ctx, executableAbsPath, version, rr); err != nil { return err } - case upgradeMethodSnapRefresh: - if err := c.snapRefresh(); err != nil { - return err - } case upgradeMethodUpgradePackage: useSudo := false if err := c.upgradePackage(ctx, version, rr, useSudo); err != nil { @@ -376,10 +371,6 @@ func (c *Config) replaceExecutable( return } -func (c *Config) snapRefresh() error { - return c.run(chezmoi.EmptyAbsPath, "snap", []string{"refresh", c.upgrade.repo}) -} - func (c *Config) upgradePackage( ctx context.Context, version *semver.Version, rr *github.RepositoryRelease, useSudo bool, ) error { @@ -508,9 +499,6 @@ func getUpgradeMethod(fileSystem vfs.Stater, executableAbsPath chezmoi.AbsPath) case "freebsd": return upgradeMethodReplaceExecutable, nil case "linux": - if ok, _ := vfs.Contains(fileSystem, executableAbsPath.String(), "/snap"); ok { - return upgradeMethodSnapRefresh, nil - } fileInfo, err := fileSystem.Stat(executableAbsPath.String()) if err != nil { return "", err
feat
Stop building snaps
c5d6928c3ee59a698ce172ca8ddd355b868ed03e
2021-09-28 01:02:31
Tom Payne
chore: Fix matching of negative patterns
false
diff --git a/internal/chezmoi/patternset.go b/internal/chezmoi/patternset.go index 281f2f3c03b..92b54359059 100644 --- a/internal/chezmoi/patternset.go +++ b/internal/chezmoi/patternset.go @@ -2,6 +2,7 @@ package chezmoi import ( "fmt" + "path" "path/filepath" "sort" @@ -52,12 +53,12 @@ func (ps *patternSet) glob(fileSystem vfs.FS, prefix string) ([]string, error) { } for match := range allMatches { for excludePattern := range ps.excludePatterns { - exclude, err := doublestar.Match(prefix+excludePattern, match) + exclude, err := doublestar.Match(path.Clean(prefix+excludePattern), match) if err != nil { return nil, err } if exclude { - delete(allMatches, match) + allMatches.Delete(match) } } } @@ -104,6 +105,11 @@ func (s StringSet) Contains(element string) bool { return ok } +// Delete deletes element from s. +func (s StringSet) Delete(element string) { + delete(s, element) +} + // Element returns an arbitrary element from s or the empty string if s is // empty. func (s StringSet) Element() string { diff --git a/internal/chezmoi/patternset_test.go b/internal/chezmoi/patternset_test.go index cc3d960c4cd..a5bc5588fe3 100644 --- a/internal/chezmoi/patternset_test.go +++ b/internal/chezmoi/patternset_test.go @@ -128,9 +128,6 @@ func TestPatternSetGlob(t *testing.T) { }, }, } { - if tc.name != "simple" { - continue - } t.Run(tc.name, func(t *testing.T) { chezmoitest.WithTestFS(t, tc.root, func(fileSystem vfs.FS) { actualMatches, err := tc.ps.glob(fileSystem, "/") @@ -144,8 +141,8 @@ func TestPatternSetGlob(t *testing.T) { func mustNewPatternSet(t *testing.T, patterns map[string]bool) *patternSet { t.Helper() ps := newPatternSet() - for pattern, exclude := range patterns { - require.NoError(t, ps.add(pattern, exclude)) + for pattern, include := range patterns { + require.NoError(t, ps.add(pattern, include)) } return ps }
chore
Fix matching of negative patterns
d987eaa79e62d1e5245f5176f61e4b5fad421ab2
2022-08-08 02:41:16
Tom Payne
chore: Use bytes.Cut and strings.Cut
false
diff --git a/internal/cmds/execute-template/main.go b/internal/cmds/execute-template/main.go index cabba9e0b20..0e32f524c67 100644 --- a/internal/cmds/execute-template/main.go +++ b/internal/cmds/execute-template/main.go @@ -24,7 +24,7 @@ var ( ) func gitHubLatestRelease(userRepo string) string { - user, repo, ok := chezmoi.CutString(userRepo, "/") + user, repo, ok := strings.Cut(userRepo, "/") if !ok { panic(fmt.Errorf("%s: not a user/repo", userRepo)) } diff --git a/pkg/chezmoi/chezmoi.go b/pkg/chezmoi/chezmoi.go index 3ccd5f919c4..59734db6d7b 100644 --- a/pkg/chezmoi/chezmoi.go +++ b/pkg/chezmoi/chezmoi.go @@ -203,7 +203,7 @@ func etcHostnameFQDNHostname(fileSystem vfs.FS) (string, error) { s := bufio.NewScanner(bytes.NewReader(contents)) for s.Scan() { text := s.Text() - text, _, _ = CutString(text, "#") + text, _, _ = strings.Cut(text, "#") if hostname := strings.TrimSpace(text); hostname != "" { return hostname, nil } @@ -241,7 +241,7 @@ func etcHostsFQDNHostname(fileSystem vfs.FS) (string, error) { for s.Scan() { text := s.Text() text = strings.TrimSpace(text) - text, _, _ = CutString(text, "#") + text, _, _ = strings.Cut(text, "#") fields := whitespaceRx.Split(text, -1) if len(fields) >= 2 && fields[0] == "127.0.1.1" { return fields[1], nil diff --git a/pkg/chezmoi/chezmoi_go1.17.go b/pkg/chezmoi/chezmoi_go1.17.go deleted file mode 100644 index 587aa2f551e..00000000000 --- a/pkg/chezmoi/chezmoi_go1.17.go +++ /dev/null @@ -1,31 +0,0 @@ -//go:build !go1.18 -// +build !go1.18 - -package chezmoi - -import ( - "bytes" - "strings" -) - -// CutBytes slices s around the first instance of sep, returning the text before -// and after sep. The found result reports whether sep appears in s. If sep does -// not appear in s, cut returns s, nil, false. -// -// CutBytes returns slices of the original slice s, not copies. -func CutBytes(s, sep []byte) (before, after []byte, found bool) { - if i := bytes.Index(s, sep); i >= 0 { - return s[:i], s[i+len(sep):], true - } - return s, nil, false -} - -// CutString slices s around the first instance of sep, returning the text -// before and after sep. The found result reports whether sep appears in s. If -// sep does not appear in s, cut returns s, "", false. -func CutString(s, sep string) (before, after string, found bool) { - if i := strings.Index(s, sep); i >= 0 { - return s[:i], s[i+len(sep):], true - } - return s, "", false -} diff --git a/pkg/chezmoi/chezmoi_go1.18.go b/pkg/chezmoi/chezmoi_go1.18.go deleted file mode 100644 index 258ff5ebd3f..00000000000 --- a/pkg/chezmoi/chezmoi_go1.18.go +++ /dev/null @@ -1,16 +0,0 @@ -//go:build go1.18 -// +build go1.18 - -package chezmoi - -import ( - "bytes" - "strings" -) - -// FIXME when Go 1.18 is the minimum supported Go version, replace these with -// {strings,bytes}.Cut. -var ( - CutBytes = bytes.Cut - CutString = strings.Cut -) diff --git a/pkg/chezmoi/data.go b/pkg/chezmoi/data.go index fab27dab723..79f9a9c4615 100644 --- a/pkg/chezmoi/data.go +++ b/pkg/chezmoi/data.go @@ -94,7 +94,7 @@ func parseOSRelease(r io.Reader) (map[string]interface{}, error) { if len(token) == 0 || token[0] == '#' { continue } - key, value, ok := CutString(token, "=") + key, value, ok := strings.Cut(token, "=") if !ok { return nil, fmt.Errorf("%s: parse error", token) } diff --git a/pkg/chezmoi/sourcestate.go b/pkg/chezmoi/sourcestate.go index f9cb06b0fef..8e9112dc8ad 100644 --- a/pkg/chezmoi/sourcestate.go +++ b/pkg/chezmoi/sourcestate.go @@ -1229,7 +1229,7 @@ func (s *SourceState) addPatterns(patternSet *patternSet, sourceAbsPath AbsPath, for scanner.Scan() { lineNumber++ text := scanner.Text() - text, _, _ = CutString(text, "#") + text, _, _ = strings.Cut(text, "#") text = strings.TrimSpace(text) if text == "" { continue diff --git a/pkg/cmd/config.go b/pkg/cmd/config.go index f88448bf080..6c5fcc1d37a 100644 --- a/pkg/cmd/config.go +++ b/pkg/cmd/config.go @@ -1020,7 +1020,7 @@ func (c *Config) defaultTemplateData() map[string]interface{} { Err(err). Msg("chezmoi.FQDNHostname") } - hostname, _, _ := chezmoi.CutString(fqdnHostname, ".") + hostname, _, _ := strings.Cut(fqdnHostname, ".") kernel, err := chezmoi.Kernel(c.fileSystem) if err != nil { diff --git a/pkg/cmd/doctorcmd_windows.go b/pkg/cmd/doctorcmd_windows.go index 2afdc108246..735b97bae6b 100644 --- a/pkg/cmd/doctorcmd_windows.go +++ b/pkg/cmd/doctorcmd_windows.go @@ -31,7 +31,7 @@ func (systeminfoCheck) Run(system chezmoi.System, homeDirAbsPath chezmoi.AbsPath var osName, osVersion string s := bufio.NewScanner(bytes.NewReader(data)) for s.Scan() { - switch key, value, found := chezmoi.CutString(s.Text(), ":"); { + switch key, value, found := strings.Cut(s.Text(), ":"); { case !found: // Do nothing. case key == "OS Name": diff --git a/pkg/cmd/githubtemplatefuncs.go b/pkg/cmd/githubtemplatefuncs.go index 905f8d3bcdf..062c76593df 100644 --- a/pkg/cmd/githubtemplatefuncs.go +++ b/pkg/cmd/githubtemplatefuncs.go @@ -3,6 +3,7 @@ package cmd import ( "context" "fmt" + "strings" "github.com/google/go-github/v45/github" @@ -52,7 +53,7 @@ func (c *Config) gitHubKeysTemplateFunc(user string) []*github.Key { } func (c *Config) gitHubLatestReleaseTemplateFunc(userRepo string) *github.RepositoryRelease { - user, repo, ok := chezmoi.CutString(userRepo, "/") + user, repo, ok := strings.Cut(userRepo, "/") if !ok { panic(fmt.Errorf("%s: not a user/repo", userRepo)) } diff --git a/pkg/cmd/gopasstemplatefuncs.go b/pkg/cmd/gopasstemplatefuncs.go index 22d3b2d20f0..8582bdc266d 100644 --- a/pkg/cmd/gopasstemplatefuncs.go +++ b/pkg/cmd/gopasstemplatefuncs.go @@ -1,13 +1,13 @@ package cmd import ( + "bytes" "os" "os/exec" "regexp" "github.com/coreos/go-semver/semver" - "github.com/twpayne/chezmoi/v2/pkg/chezmoi" "github.com/twpayne/chezmoi/v2/pkg/chezmoilog" ) @@ -45,7 +45,7 @@ func (c *Config) gopassTemplateFunc(id string) string { panic(err) } - passwordBytes, _, _ := chezmoi.CutBytes(output, []byte{'\n'}) + passwordBytes, _, _ := bytes.Cut(output, []byte{'\n'}) password := string(passwordBytes) if c.Gopass.cache == nil { diff --git a/pkg/cmd/onepasswordtemplatefuncs.go b/pkg/cmd/onepasswordtemplatefuncs.go index 63631981b75..acfcc0841fa 100644 --- a/pkg/cmd/onepasswordtemplatefuncs.go +++ b/pkg/cmd/onepasswordtemplatefuncs.go @@ -10,7 +10,6 @@ import ( "github.com/coreos/go-semver/semver" - "github.com/twpayne/chezmoi/v2/pkg/chezmoi" "github.com/twpayne/chezmoi/v2/pkg/chezmoilog" ) @@ -439,7 +438,7 @@ func newOnepasswordArgs(baseArgs, userArgs []string) (*onepasswordArgs, error) { func onepasswordUniqueSessionToken(environ []string) string { var token string for _, env := range environ { - key, value, found := chezmoi.CutString(env, "=") + key, value, found := strings.Cut(env, "=") if found && strings.HasPrefix(key, "OP_SESSION_") { if token != "" { return "" diff --git a/pkg/cmd/passtemplatefuncs.go b/pkg/cmd/passtemplatefuncs.go index 63bdcdeb2c9..575852822ea 100644 --- a/pkg/cmd/passtemplatefuncs.go +++ b/pkg/cmd/passtemplatefuncs.go @@ -5,7 +5,6 @@ import ( "os" "os/exec" - "github.com/twpayne/chezmoi/v2/pkg/chezmoi" "github.com/twpayne/chezmoi/v2/pkg/chezmoilog" ) @@ -19,7 +18,7 @@ func (c *Config) passTemplateFunc(id string) string { if err != nil { panic(err) } - firstLine, _, _ := chezmoi.CutBytes(output, []byte{'\n'}) + firstLine, _, _ := bytes.Cut(output, []byte{'\n'}) return string(bytes.TrimSpace(firstLine)) } @@ -31,7 +30,7 @@ func (c *Config) passFieldsTemplateFunc(id string) map[string]string { result := make(map[string]string) for _, line := range bytes.Split(output, []byte{'\n'}) { - if key, value, ok := chezmoi.CutBytes(line, []byte{':'}); ok { + if key, value, ok := bytes.Cut(line, []byte{':'}); ok { result[string(bytes.TrimSpace(key))] = string(bytes.TrimSpace(value)) } }
chore
Use bytes.Cut and strings.Cut
a76c29f9586b8cf83804103a60cb3afc845598b3
2024-10-12 07:11:10
Tom Payne
chore: Update dependencies
false
diff --git a/go.mod b/go.mod index c16e43ed0a4..54a941f785a 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,7 @@ go 1.22.0 require ( filippo.io/age v1.2.0 - github.com/1password/onepassword-sdk-go v0.1.1 + github.com/1password/onepassword-sdk-go v0.1.2 github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.8.0 github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.1.0 github.com/Masterminds/sprig/v3 v3.3.0 @@ -14,7 +14,7 @@ require ( github.com/aws/aws-sdk-go-v2 v1.32.2 github.com/aws/aws-sdk-go-v2/config v1.27.43 github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.34.2 - github.com/bmatcuk/doublestar/v4 v4.6.1 + github.com/bmatcuk/doublestar/v4 v4.7.1 github.com/bradenhilton/mozillainstallhash v1.0.1 github.com/charmbracelet/bubbles v0.20.0 github.com/charmbracelet/bubbletea v1.1.1 @@ -22,11 +22,11 @@ require ( github.com/coreos/go-semver v0.3.1 github.com/fsnotify/fsnotify v1.7.0 github.com/go-git/go-git/v5 v5.12.0 - github.com/google/go-github/v65 v65.0.0 + github.com/google/go-github/v66 v66.0.0 github.com/google/renameio/v2 v2.0.0 github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 github.com/itchyny/gojq v0.12.16 - github.com/klauspost/compress v1.17.10 + github.com/klauspost/compress v1.17.11 github.com/mitchellh/copystructure v1.2.0 github.com/mitchellh/mapstructure v1.5.0 github.com/muesli/combinator v0.3.0 @@ -47,7 +47,7 @@ require ( go.etcd.io/bbolt v1.3.11 go.uber.org/automaxprocs v1.6.0 golang.org/x/crypto v0.28.0 - golang.org/x/crypto/x509roots/fallback v0.0.0-20241004205956-6c2174895805 + golang.org/x/crypto/x509roots/fallback v0.0.0-20241011170909-b61b08db44b8 golang.org/x/oauth2 v0.23.0 golang.org/x/sync v0.8.0 golang.org/x/sys v0.26.0 @@ -91,7 +91,7 @@ require ( github.com/charmbracelet/lipgloss v0.13.0 // indirect github.com/charmbracelet/x/ansi v0.3.2 // indirect github.com/charmbracelet/x/term v0.2.0 // indirect - github.com/cloudflare/circl v1.4.0 // indirect + github.com/cloudflare/circl v1.5.0 // indirect github.com/creack/pty/v2 v2.0.0-20231209135443-03db72c7b76c // indirect github.com/cyphar/filepath-securejoin v0.3.4 // indirect github.com/danieljoos/wincred v1.2.2 // indirect @@ -102,7 +102,7 @@ require ( github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect github.com/extism/go-sdk v1.5.0 // indirect github.com/fatih/semgroup v1.3.0 // indirect - github.com/gitleaks/go-gitdiff v0.9.0 // indirect + github.com/gitleaks/go-gitdiff v0.9.1 // indirect github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 // indirect github.com/go-git/go-billy/v5 v5.5.0 // indirect github.com/gobwas/glob v0.2.3 // indirect @@ -155,7 +155,7 @@ require ( github.com/yuin/goldmark-emoji v1.0.3 // indirect go.opentelemetry.io/proto/otlp v1.3.1 // indirect go.uber.org/multierr v1.11.0 // indirect - golang.org/x/exp v0.0.0-20241004190924-225e2abe05e6 // indirect + golang.org/x/exp v0.0.0-20241009180824-f66d83c29e7c // indirect golang.org/x/net v0.30.0 // indirect golang.org/x/text v0.19.0 // indirect golang.org/x/tools v0.26.0 // indirect @@ -163,7 +163,10 @@ require ( gopkg.in/warnings.v0 v0.1.2 // indirect ) -exclude github.com/microcosm-cc/bluemonday v1.0.26 // https://github.com/microcosm-cc/bluemonday/pull/195 +exclude ( + github.com/microcosm-cc/bluemonday v1.0.26 // https://github.com/microcosm-cc/bluemonday/pull/195 + github.com/tailscale/hujson v0.0.0-20241010212012-29efb4a0184b // Requires Go 1.23. +) // github.com/Netflix/go-expect is unmaintained. Use a temporary fork. replace github.com/Netflix/go-expect => github.com/twpayne/go-expect v0.0.1 diff --git a/go.sum b/go.sum index 923b82f9620..1073934595e 100644 --- a/go.sum +++ b/go.sum @@ -20,8 +20,8 @@ filippo.io/age v1.2.0 h1:vRDp7pUMaAJzXNIWJVAZnEf/Dyi4Vu4wI8S1LBzufhE= filippo.io/age v1.2.0/go.mod h1:JL9ew2lTN+Pyft4RiNGguFfOpewKwSHm5ayKD/A4004= filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= -github.com/1password/onepassword-sdk-go v0.1.1 h1:smvVI7OTTqFf6M7jOU7s+VbYbYHrStnT/GYZ9+hDy4o= -github.com/1password/onepassword-sdk-go v0.1.1/go.mod h1:7wEQynLBXBC4svNx3X82QmCy0Adhm4e+UkM9t9mSSWA= +github.com/1password/onepassword-sdk-go v0.1.2 h1:O5xoxaAvzRI4gXdGXmyFYoBlmsiv3l8qJEROmNeDIKo= +github.com/1password/onepassword-sdk-go v0.1.2/go.mod h1:nZEOzWFvodClltx8G0xtcNGqzNrrcfW589Rb9T82hE8= github.com/Azure/azure-sdk-for-go/sdk/azcore v1.14.0 h1:nyQWyZvwGTvunIMxi1Y9uXkcyr+I7TeNrr/foo4Kpk8= github.com/Azure/azure-sdk-for-go/sdk/azcore v1.14.0/go.mod h1:l38EPgmsp71HHLq9j7De57JcKOWPyhrsW1Awm1JS6K0= github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.8.0 h1:B/dfvscEQtew9dVuoxqxrUKKv8Ih2f55PydknDamU+g= @@ -105,8 +105,8 @@ github.com/aymanbagabas/go-udiff v0.2.0 h1:TK0fH4MteXUDspT88n8CKzvK0X9O2xu9yQjWp github.com/aymanbagabas/go-udiff v0.2.0/go.mod h1:RE4Ex0qsGkTAJoQdQQCA0uG+nAzJO/pI/QwceO5fgrA= github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk= github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4= -github.com/bmatcuk/doublestar/v4 v4.6.1 h1:FH9SifrbvJhnlQpztAx++wlkk70QBf0iBWDwNy7PA4I= -github.com/bmatcuk/doublestar/v4 v4.6.1/go.mod h1:xBQ8jztBU6kakFMg+8WGxn0c6z1fTSPVIjEY1Wr7jzc= +github.com/bmatcuk/doublestar/v4 v4.7.1 h1:fdDeAqgT47acgwd9bd9HxJRDmc9UAmPpc+2m0CXv75Q= +github.com/bmatcuk/doublestar/v4 v4.7.1/go.mod h1:xBQ8jztBU6kakFMg+8WGxn0c6z1fTSPVIjEY1Wr7jzc= github.com/bradenhilton/cityhash v1.0.0 h1:1QauDCwfxwIGwO2jBTJdEBqXgfCusAgQOSgdl4RsTMI= github.com/bradenhilton/cityhash v1.0.0/go.mod h1:Wmb8yW1egA9ulrsRX4mxfYx5zq4nBWOCZ+j63oK6uz8= github.com/bradenhilton/mozillainstallhash v1.0.1 h1:JVAVsItiWlLoudJX4L+tIuml+hoxjlzCwkhlENi9yS4= @@ -134,8 +134,8 @@ github.com/charmbracelet/x/exp/golden v0.0.0-20240815200342-61de596daa2b/go.mod github.com/charmbracelet/x/term v0.2.0 h1:cNB9Ot9q8I711MyZ7myUR5HFWL/lc3OpU8jZ4hwm0x0= github.com/charmbracelet/x/term v0.2.0/go.mod h1:GVxgxAbjUrmpvIINHIQnJJKpMlHiZ4cktEQCN6GWyF0= github.com/cloudflare/circl v1.3.3/go.mod h1:5XYMA4rFBvNIrhs50XuiBJ15vF2pZn4nnUKZrLbUZFA= -github.com/cloudflare/circl v1.4.0 h1:BV7h5MgrktNzytKmWjpOtdYrf0lkkbF8YMlBGPhJQrY= -github.com/cloudflare/circl v1.4.0/go.mod h1:PDRU+oXvdD7KCtgKxW95M5Z8BpSCJXQORiZFnBQS5QU= +github.com/cloudflare/circl v1.5.0 h1:hxIWksrX6XN5a1L2TI/h53AGPhNHoUBo+TD1ms9+pys= +github.com/cloudflare/circl v1.5.0/go.mod h1:uddAzsPgqdMAYatqJ0lsjX1oECcQLIlRpzZh3pJrofs= github.com/coreos/go-semver v0.3.1 h1:yi21YpKnrx1gt5R+la8n5WgS0kCrsPp33dmEyHReZr4= github.com/coreos/go-semver v0.3.1/go.mod h1:irMmmIw/7yzSRPWryHsK7EYSg09caPQL03VsM8rvUec= github.com/coreos/go-systemd/v22 v22.5.0 h1:RrqgGjYQKalulkV8NGVIfkXQf6YYmOyiJKk8iXXhfZs= @@ -184,8 +184,8 @@ github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHk github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= -github.com/gitleaks/go-gitdiff v0.9.0 h1:SHAU2l0ZBEo8g82EeFewhVy81sb7JCxW76oSPtR/Nqg= -github.com/gitleaks/go-gitdiff v0.9.0/go.mod h1:pKz0X4YzCKZs30BL+weqBIG7mx0jl4tF1uXV9ZyNvrA= +github.com/gitleaks/go-gitdiff v0.9.1 h1:ni6z6/3i9ODT685OLCTf+s/ERlWUNWQF4x1pvoNICw0= +github.com/gitleaks/go-gitdiff v0.9.1/go.mod h1:pKz0X4YzCKZs30BL+weqBIG7mx0jl4tF1uXV9ZyNvrA= github.com/gliderlabs/ssh v0.3.7 h1:iV3Bqi942d9huXnzEF2Mt+CY9gLu8DNM4Obd+8bODRE= github.com/gliderlabs/ssh v0.3.7/go.mod h1:zpHEXBstFnQYtGnB8k8kQLol82umzn/2/snG7alWVD8= github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 h1:+zs/tPmkDkHx3U66DAb0lQFJrpS6731Oaa12ikc+DiI= @@ -222,8 +222,8 @@ github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl76 github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/google/go-github/v65 v65.0.0 h1:pQ7BmO3DZivvFk92geC0jB0q2m3gyn8vnYPgV7GSLhQ= -github.com/google/go-github/v65 v65.0.0/go.mod h1:DvrqWo5hvsdhJvHd4WyVF9ttANN3BniqjP8uTFMNb60= +github.com/google/go-github/v66 v66.0.0 h1:ADJsaXj9UotwdgK8/iFZtv7MLc8E8WBl62WLd/D/9+M= +github.com/google/go-github/v66 v66.0.0/go.mod h1:+4SO9Zkuyf8ytMj0csN1NR/5OTR+MfqPp8P8dVlcvY4= github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8= github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU= github.com/google/renameio/v2 v2.0.0 h1:UifI23ZTGY8Tt29JbYFiuyIU3eX+RNFtUwefq9qAhxg= @@ -294,8 +294,8 @@ github.com/kevinburke/ssh_config v1.2.0 h1:x584FjTGwHzMwvHx18PXxbBVzfnxogHaAReU4 github.com/kevinburke/ssh_config v1.2.0/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM= github.com/keybase/go-keychain v0.0.0-20231219164618-57a3676c3af6 h1:IsMZxCuZqKuao2vNdfD82fjjgPLfyHLpR41Z88viRWs= github.com/keybase/go-keychain v0.0.0-20231219164618-57a3676c3af6/go.mod h1:3VeWNIJaW+O5xpRQbPp0Ybqu1vJd/pm7s2F473HRrkw= -github.com/klauspost/compress v1.17.10 h1:oXAz+Vh0PMUvJczoi+flxpnBEPxoER1IaAnU/NMPtT0= -github.com/klauspost/compress v1.17.10/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0= +github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc= +github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0= github.com/kr/fs v0.1.0 h1:Jskdu9ieNAYnjxsi0LbQp1ulIKZV1LAFgK1tWhpZgl8= github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= @@ -520,10 +520,10 @@ golang.org/x/crypto v0.3.1-0.20221117191849-2c476679df9a/go.mod h1:hebNnKkNXi2Uz golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= golang.org/x/crypto v0.28.0 h1:GBDwsMXVQi34v5CCYUm2jkJvu4cbtru2U4TN2PSyQnw= golang.org/x/crypto v0.28.0/go.mod h1:rmgy+3RHxRZMyY0jjAJShp2zgEdOqj2AO7U0pYmeQ7U= -golang.org/x/crypto/x509roots/fallback v0.0.0-20241004205956-6c2174895805 h1:AIMSJZAK3wyydsLu/9eGE03w+Kd1C1gAeC9MWBmustM= -golang.org/x/crypto/x509roots/fallback v0.0.0-20241004205956-6c2174895805/go.mod h1:kNa9WdvYnzFwC79zRpLRMJbdEFlhyM5RPFBBZp/wWH8= -golang.org/x/exp v0.0.0-20241004190924-225e2abe05e6 h1:1wqE9dj9NpSm04INVsJhhEUzhuDVjbcyKH91sVyPATw= -golang.org/x/exp v0.0.0-20241004190924-225e2abe05e6/go.mod h1:NQtJDoLvd6faHhE7m4T/1IY708gDefGGjR/iUW8yQQ8= +golang.org/x/crypto/x509roots/fallback v0.0.0-20241011170909-b61b08db44b8 h1:q5+DL82WOBCldKz929CSRwdxrCdUY0Occd8jVZEE8y8= +golang.org/x/crypto/x509roots/fallback v0.0.0-20241011170909-b61b08db44b8/go.mod h1:kNa9WdvYnzFwC79zRpLRMJbdEFlhyM5RPFBBZp/wWH8= +golang.org/x/exp v0.0.0-20241009180824-f66d83c29e7c h1:7dEasQXItcW1xKJ2+gg5VOiBnqWrJc+rq0DPKyvvdbY= +golang.org/x/exp v0.0.0-20241009180824-f66d83c29e7c/go.mod h1:NQtJDoLvd6faHhE7m4T/1IY708gDefGGjR/iUW8yQQ8= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.21.0 h1:vvrHzRwRfVKSiLrG+d4FMl/Qi4ukBCE6kZlTUkDYRT0= diff --git a/internal/chezmoi/github.go b/internal/chezmoi/github.go index 910d0877fcf..6d0c56e3c10 100644 --- a/internal/chezmoi/github.go +++ b/internal/chezmoi/github.go @@ -5,7 +5,7 @@ import ( "net/http" "os" - "github.com/google/go-github/v65/github" + "github.com/google/go-github/v66/github" "golang.org/x/oauth2" ) diff --git a/internal/cmd/doctorcmd.go b/internal/cmd/doctorcmd.go index 546adac9071..42454ffbc6b 100644 --- a/internal/cmd/doctorcmd.go +++ b/internal/cmd/doctorcmd.go @@ -20,7 +20,7 @@ import ( "time" "github.com/coreos/go-semver/semver" - "github.com/google/go-github/v65/github" + "github.com/google/go-github/v66/github" "github.com/spf13/cobra" "github.com/twpayne/go-shell" "github.com/twpayne/go-xdg/v6" diff --git a/internal/cmd/githubtemplatefuncs.go b/internal/cmd/githubtemplatefuncs.go index 934820548ae..7a93c668242 100644 --- a/internal/cmd/githubtemplatefuncs.go +++ b/internal/cmd/githubtemplatefuncs.go @@ -7,7 +7,7 @@ import ( "strings" "time" - "github.com/google/go-github/v65/github" + "github.com/google/go-github/v66/github" "github.com/twpayne/chezmoi/v2/internal/chezmoi" ) diff --git a/internal/cmd/upgradecmd.go b/internal/cmd/upgradecmd.go index d24378290e9..6fc39955a16 100644 --- a/internal/cmd/upgradecmd.go +++ b/internal/cmd/upgradecmd.go @@ -21,7 +21,7 @@ import ( "strings" "github.com/coreos/go-semver/semver" - "github.com/google/go-github/v65/github" + "github.com/google/go-github/v66/github" "github.com/spf13/cobra" "github.com/twpayne/chezmoi/v2/internal/chezmoi" diff --git a/internal/cmd/upgradecmd_unix.go b/internal/cmd/upgradecmd_unix.go index 6b5e7f44da8..d199cb2fe79 100644 --- a/internal/cmd/upgradecmd_unix.go +++ b/internal/cmd/upgradecmd_unix.go @@ -15,7 +15,7 @@ import ( "strings" "github.com/coreos/go-semver/semver" - "github.com/google/go-github/v65/github" + "github.com/google/go-github/v66/github" vfs "github.com/twpayne/go-vfs/v5" "github.com/twpayne/chezmoi/v2/internal/chezmoi" diff --git a/internal/cmd/upgradecmd_windows.go b/internal/cmd/upgradecmd_windows.go index 3980e7b5c69..d8dfa964561 100644 --- a/internal/cmd/upgradecmd_windows.go +++ b/internal/cmd/upgradecmd_windows.go @@ -10,7 +10,7 @@ import ( "path/filepath" "github.com/coreos/go-semver/semver" - "github.com/google/go-github/v65/github" + "github.com/google/go-github/v66/github" vfs "github.com/twpayne/go-vfs/v5" "github.com/twpayne/chezmoi/v2/internal/chezmoi" diff --git a/internal/cmds/execute-template/main.go b/internal/cmds/execute-template/main.go index 6d123afbb46..82810bcd8e8 100644 --- a/internal/cmds/execute-template/main.go +++ b/internal/cmds/execute-template/main.go @@ -16,7 +16,7 @@ import ( "text/template" "github.com/Masterminds/sprig/v3" - "github.com/google/go-github/v65/github" + "github.com/google/go-github/v66/github" "github.com/google/renameio/v2/maybe" "gopkg.in/yaml.v3"
chore
Update dependencies
3ad974381fe57aedbcffef4371aa80970a989aaf
2024-07-03 02:00:39
Tom Payne
chore: Build with Go 1.22.5
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 4639a59c623..3f8ee779ae9 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -16,7 +16,7 @@ env: CHOCOLATEY_VERSION: 2.2.2 # https://github.com/chocolatey/choco/releases EDITORCONFIG_CHECKER_VERSION: 3.0.1 # https://github.com/editorconfig-checker/editorconfig-checker/releases FIND_TYPOS_VERSION: 0.0.3 # https://github.com/twpayne/find-typos/tags - GO_VERSION: 1.22.4 # https://go.dev/doc/devel/release + GO_VERSION: 1.22.5 # https://go.dev/doc/devel/release GOFUMPT_VERSION: 0.6.0 # https://github.com/mvdan/gofumpt/releases GOLANGCI_LINT_VERSION: 1.59.1 # https://github.com/golangci/golangci-lint/releases GOLINES_VERSION: 0.12.2 # https://github.com/segmentio/golines/releases
chore
Build with Go 1.22.5
7fcda1094b457b0f506f84fc2344ac2e7f762542
2022-10-18 01:52:09
dependabot[bot]
chore(deps): bump actions/cache from 3.0.9 to 3.0.11
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 7b20eff0ad8..3cbd040e4ad 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -78,7 +78,7 @@ jobs: runs-on: macos-12 steps: - uses: actions/checkout@2541b1294d2704b0964813337f33b291d3f8596b - - uses: actions/cache@ac8075791e805656e71b4ba23325ace9e3421120 + - uses: actions/cache@9b0c1fce7a93df8e3bb8926b0d6e9d89e92f20a7 with: path: ~/.vagrant.d key: ${{ runner.os }}-vagrant-debian-i386-${{ hashFiles('assets/vagrant/debian11-i386.Vagrantfile') }} @@ -104,7 +104,7 @@ jobs: runs-on: macos-12 steps: - uses: actions/checkout@2541b1294d2704b0964813337f33b291d3f8596b - - uses: actions/cache@ac8075791e805656e71b4ba23325ace9e3421120 + - uses: actions/cache@9b0c1fce7a93df8e3bb8926b0d6e9d89e92f20a7 with: path: ~/.vagrant.d key: ${{ runner.os }}-vagrant-freebsd13-${{ hashFiles('assets/vagrant/freebsd13.Vagrantfile') }} @@ -290,7 +290,7 @@ jobs: with: cache: true go-version: ${{ env.GO_VERSION }} - - uses: actions/cache@ac8075791e805656e71b4ba23325ace9e3421120 + - uses: actions/cache@9b0c1fce7a93df8e3bb8926b0d6e9d89e92f20a7 with: path: ~/go/pkg/mod key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
chore
bump actions/cache from 3.0.9 to 3.0.11
9cbfdf6fde35daf9c67fcfdee2a07b98e82c09f4
2021-11-10 14:05:13
Tom Payne
feat: Add --persistent-state option for location of persistent state file
false
diff --git a/docs/REFERENCE.md b/docs/REFERENCE.md index 5d6b9b3e6df..29fb47fca2c 100644 --- a/docs/REFERENCE.md +++ b/docs/REFERENCE.md @@ -16,6 +16,7 @@ Manage your dotfiles across multiple machines, securely. * [`--no-pager`](#--no-pager) * [`--no-tty`](#--no-tty) * [`-o`, `--output` *filename*](#-o---output-filename) + * [`--persistent-state` *filename*](#--persistent-state-filename) * [`-R`, `--refresh-externals`](#-r---refresh-externals) * [`-S`, `--source` *directory*](#-s---source-directory) * [`--use-builtin-age` *value*](#--use-builtin-age-value) @@ -218,6 +219,12 @@ stdin. Write the output to *filename* instead of stdout. +### `--persistent-state` *filename* + +Read and write the persistent state from *filename*. By default, chezmoi stores +its persistent state in `chezmoistate.boltdb` in the same directory as its +configuration file. + ### `-R`, `--refresh-externals` Refresh externals cache. See `.chezmoiexternal.<format>`. diff --git a/internal/cmd/config.go b/internal/cmd/config.go index 4eebe19397b..ce96cd6d78e 100644 --- a/internal/cmd/config.go +++ b/internal/cmd/config.go @@ -151,14 +151,15 @@ type Config struct { versionStr string // Configuration. - fileSystem vfs.FS - bds *xdg.BaseDirectorySpecification - configFileAbsPath chezmoi.AbsPath - baseSystem chezmoi.System - sourceSystem chezmoi.System - destSystem chezmoi.System - persistentState chezmoi.PersistentState - logger *zerolog.Logger + fileSystem vfs.FS + bds *xdg.BaseDirectorySpecification + configFileAbsPath chezmoi.AbsPath + baseSystem chezmoi.System + sourceSystem chezmoi.System + destSystem chezmoi.System + persistentStateAbsPath chezmoi.AbsPath + persistentState chezmoi.PersistentState + logger *zerolog.Logger // Computed configuration. homeDirAbsPath chezmoi.AbsPath @@ -1178,20 +1179,22 @@ func (c *Config) newRootCmd() (*cobra.Command, error) { persistentFlags.Var(&c.Color, "color", "Colorize output") persistentFlags.VarP(&c.DestDirAbsPath, "destination", "D", "Set destination directory") persistentFlags.Var(&c.Mode, "mode", "Mode") + persistentFlags.Var(&c.persistentStateAbsPath, "persistent-state", "Set persistent state file") persistentFlags.BoolVar(&c.Safe, "safe", c.Safe, "Safely replace files and symlinks") persistentFlags.VarP(&c.SourceDirAbsPath, "source", "S", "Set source directory") persistentFlags.Var(&c.UseBuiltinAge, "use-builtin-age", "Use builtin age") persistentFlags.Var(&c.UseBuiltinGit, "use-builtin-git", "Use builtin git") persistentFlags.VarP(&c.WorkingTreeAbsPath, "working-tree", "W", "Set working tree directory") for viperKey, key := range map[string]string{ - "color": "color", - "destDir": "destination", - "mode": "mode", - "safe": "safe", - "sourceDir": "source", - "useBuiltinAge": "use-builtin-age", - "useBuiltinGit": "use-builtin-git", - "workingTree": "working-tree", + "color": "color", + "destDir": "destination", + "persistentState": "persistent-state", + "mode": "mode", + "safe": "safe", + "sourceDir": "source", + "useBuiltinAge": "use-builtin-age", + "useBuiltinGit": "use-builtin-git", + "workingTree": "working-tree", } { if err := viper.BindPFlag(viperKey, persistentFlags.Lookup(key)); err != nil { return nil, err @@ -1606,6 +1609,9 @@ func (c *Config) persistentPreRunRootE(cmd *cobra.Command, args []string) error // returning the first persistent file found, and returning the default path if // none are found. func (c *Config) persistentStateFile() (chezmoi.AbsPath, error) { + if !c.persistentStateAbsPath.Empty() { + return c.persistentStateAbsPath, nil + } if !c.configFileAbsPath.Empty() { return c.configFileAbsPath.Dir().Join(persistentStateFileRelPath), nil } diff --git a/internal/cmd/testdata/scripts/state_unix.txt b/internal/cmd/testdata/scripts/state_unix.txt index 77c8751de23..6f4e485b0e7 100644 --- a/internal/cmd/testdata/scripts/state_unix.txt +++ b/internal/cmd/testdata/scripts/state_unix.txt @@ -11,16 +11,28 @@ exists $CHEZMOICONFIGDIR/chezmoistate.boltdb # test that the persistent state records that script was run chezmoi state dump --format=yaml -stdout a8076d3d28d21e02012b20eaf7dbf75409a6277134439025f282e368e3305abf: +stdout 70396a619400b7f78dbb83ab8ddb76ffe0b8e31557e64bab2ca9677818a52135: stdout runAt: # test that chezmoi state reset removes the persistent state chezmoi --force state reset ! exists $CHEZMOICONFIGDIR/chezmoistate.boltdb +# test that the --persistent-state option sets the persistent state file +chezmoi apply --force +stdout script +chezmoi apply --force --persistent-state=$CHEZMOICONFIGDIR${/}chezmoistate2.boltdb +exists $CHEZMOICONFIGDIR${/}chezmoistate2.boltdb +stdout script +chezmoi state dump --format=yaml --persistent-state=$CHEZMOICONFIGDIR${/}chezmoistate2.boltdb +stdout 70396a619400b7f78dbb83ab8ddb76ffe0b8e31557e64bab2ca9677818a52135: +stdout runAt: + -- golden/dump -- configState: {} entryState: {} scriptState: {} -- home/user/.local/share/chezmoi/run_once_script -- #!/bin/sh + +echo script
feat
Add --persistent-state option for location of persistent state file
a2e6bfdd239005bc367ff5def8d9413761dfcb55
2023-10-01 13:09:55
dependabot[bot]
chore(deps): bump sigstore/cosign-installer from 3.1.1 to 3.1.2
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index bcb5facc4d9..378255fc951 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -408,7 +408,7 @@ jobs: - uses: actions/setup-go@93397bea11091df50f3d7e59dc26a7711a8bcfbe with: go-version: ${{ env.GO_VERSION }} - - uses: sigstore/cosign-installer@6e04d228eb30da1757ee4e1dd75a0ec73a653e06 + - uses: sigstore/cosign-installer@11086d25041f77fe8fe7b9ea4e48e3b9192b8f19 - name: create-syso run: | make create-syso
chore
bump sigstore/cosign-installer from 3.1.1 to 3.1.2
814f1f20543ca0f3b50b4ef3e21e83ed12d84eec
2022-06-07 14:42:57
Braden Hilton
docs: Refactor Windows chassisType template
false
diff --git a/assets/chezmoi.io/docs/user-guide/machines/general.md b/assets/chezmoi.io/docs/user-guide/machines/general.md index c5745f43f66..0340b1de9c8 100644 --- a/assets/chezmoi.io/docs/user-guide/machines/general.md +++ b/assets/chezmoi.io/docs/user-guide/machines/general.md @@ -16,6 +16,6 @@ The following template sets the `$chassisType` variable to `"desktop"` or {{- else if eq .chezmoi.os "linux" }} {{- $chassisType = (output "hostnamectl" "--json=short" | mustFromJson).Chassis }} {{- else if eq .chezmoi.os "windows" }} -{{- $chassisType = (output "powershell.exe" "-noprofile" "-command" "if (Get-WmiObject -Class win32_battery -ComputerName localhost) { echo laptop } else { echo desktop }") }} +{{- $chassisType = (output "powershell.exe" "-NoProfile" "-NonInteractive" "-Command" "if ((Get-CimInstance -Class Win32_Battery | Measure-Object).Count -gt 0) { Write-Output 'laptop' } else { Write-Output 'desktop' }") | trim }} {{- end }} ```
docs
Refactor Windows chassisType template
6786faa65121722bb71a47127e90d16dd6753a53
2023-02-17 16:49:43
Tom Payne
chore: Build with Go version 1.20.1
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index da0fa5420da..4319dc5bf13 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -10,7 +10,7 @@ on: - v* env: AGE_VERSION: 1.1.1 - GO_VERSION: '1.20' + GO_VERSION: '1.20.1' GOFUMPT_VERSION: 0.4.0 GOLANGCI_LINT_VERSION: 1.51.0 GOVERSIONINFO_VERSION: 1.4.0
chore
Build with Go version 1.20.1
3f8233b4c9b192f65982c41daeb25dde4fdc439d
2025-02-13 03:48:30
Tom Payne
chore: Update dependencies
false
diff --git a/go.mod b/go.mod index 0c57c85b16c..314c040d5c7 100644 --- a/go.mod +++ b/go.mod @@ -16,12 +16,12 @@ require ( github.com/bmatcuk/doublestar/v4 v4.8.1 github.com/bradenhilton/mozillainstallhash v1.0.1 github.com/charmbracelet/bubbles v0.20.0 - github.com/charmbracelet/bubbletea v1.3.0 + github.com/charmbracelet/bubbletea v1.3.3 github.com/charmbracelet/glamour v0.8.0 github.com/coreos/go-semver v0.3.1 github.com/fsnotify/fsnotify v1.8.0 github.com/go-git/go-git/v5 v5.13.2 - github.com/goccy/go-yaml v1.15.17 + github.com/goccy/go-yaml v1.15.22 github.com/google/go-github/v69 v69.0.0 github.com/google/renameio/v2 v2.0.0 github.com/gopasspw/gopass v1.15.15 @@ -50,8 +50,8 @@ require ( github.com/zricethezav/gitleaks/v8 v8.23.3 go.etcd.io/bbolt v1.4.0 go.uber.org/automaxprocs v1.6.0 - golang.org/x/crypto v0.32.0 - golang.org/x/crypto/x509roots/fallback v0.0.0-20250204190303-9290511cd23a + golang.org/x/crypto v0.33.0 + golang.org/x/crypto/x509roots/fallback v0.0.0-20250210163342-e47973b1c108 golang.org/x/oauth2 v0.26.0 golang.org/x/sync v0.11.0 golang.org/x/sys v0.30.0 @@ -102,13 +102,13 @@ require ( github.com/creack/pty/v2 v2.0.0-20231209135443-03db72c7b76c // indirect github.com/cyphar/filepath-securejoin v0.4.1 // indirect github.com/danieljoos/wincred v1.2.2 // indirect - github.com/dlclark/regexp2 v1.11.4 // indirect + github.com/dlclark/regexp2 v1.11.5 // indirect github.com/dustin/go-humanize v1.0.1 // indirect github.com/dustin/gojson v0.0.0-20160307161227-2e71ec9dd5ad // indirect github.com/dylibso/observe-sdk/go v0.0.0-20240828172851-9145d8ad07e1 // indirect github.com/emirpasic/gods v1.18.1 // indirect github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect - github.com/extism/go-sdk v1.6.1 // indirect + github.com/extism/go-sdk v1.7.0 // indirect github.com/fatih/color v1.18.0 // indirect github.com/fatih/semgroup v1.3.0 // indirect github.com/gitleaks/go-gitdiff v0.9.1 // indirect @@ -174,10 +174,10 @@ require ( github.com/yuin/goldmark-emoji v1.0.4 // indirect go.opentelemetry.io/proto/otlp v1.5.0 // indirect go.uber.org/multierr v1.11.0 // indirect - golang.org/x/exp v0.0.0-20250128182459-e0ece0dbea4c // indirect - golang.org/x/net v0.34.0 // indirect + golang.org/x/exp v0.0.0-20250210185358-939b2ce775ac // indirect + golang.org/x/net v0.35.0 // indirect golang.org/x/text v0.22.0 // indirect - golang.org/x/tools v0.29.0 // indirect + golang.org/x/tools v0.30.0 // indirect google.golang.org/protobuf v1.36.5 // indirect gopkg.in/warnings.v0 v0.1.2 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect diff --git a/go.sum b/go.sum index 27917707487..e15a000bbfc 100644 --- a/go.sum +++ b/go.sum @@ -145,8 +145,8 @@ github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UF github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/charmbracelet/bubbles v0.20.0 h1:jSZu6qD8cRQ6k9OMfR1WlM+ruM8fkPWkHvQWD9LIutE= github.com/charmbracelet/bubbles v0.20.0/go.mod h1:39slydyswPy+uVOHZ5x/GjwVAFkCsV8IIVy+4MhzwwU= -github.com/charmbracelet/bubbletea v1.3.0 h1:fPMyirm0u3Fou+flch7hlJN9krlnVURrkUVDwqXjoAc= -github.com/charmbracelet/bubbletea v1.3.0/go.mod h1:eTaHfqbIwvBhFQM/nlT1NsGc4kp8jhF8LfUK67XiTDM= +github.com/charmbracelet/bubbletea v1.3.3 h1:WpU6fCY0J2vDWM3zfS3vIDi/ULq3SYphZhkAGGvmEUY= +github.com/charmbracelet/bubbletea v1.3.3/go.mod h1:dtcUCyCGEX3g9tosuYiut3MXgY/Jsv9nKVdibKKRRXo= github.com/charmbracelet/glamour v0.8.0 h1:tPrjL3aRcQbn++7t18wOpgLyl8wrOHUEDS7IZ68QtZs= github.com/charmbracelet/glamour v0.8.0/go.mod h1:ViRgmKkf3u5S7uakt2czJ272WSg2ZenlYEZXT2x7Bjw= github.com/charmbracelet/harmonica v0.2.0 h1:8NxJWRWg/bzKqqEaaeFNipOu77YR5t8aSwG4pgaUBiQ= @@ -184,8 +184,8 @@ github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1 github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= -github.com/dlclark/regexp2 v1.11.4 h1:rPYF9/LECdNymJufQKmri9gV604RvvABwgOA8un7yAo= -github.com/dlclark/regexp2 v1.11.4/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= +github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ= +github.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/dustin/gojson v0.0.0-20160307161227-2e71ec9dd5ad h1:Qk76DOWdOp+GlyDKBAG3Klr9cn7N+LcYc82AZ2S7+cA= @@ -204,8 +204,8 @@ github.com/ergochat/readline v0.1.3 h1:/DytGTmwdUJcLAe3k3VJgowh5vNnsdifYT6uVaf4p github.com/ergochat/readline v0.1.3/go.mod h1:o3ux9QLHLm77bq7hDB21UTm6HlV2++IPDMfIfKDuOgY= github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4= github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM= -github.com/extism/go-sdk v1.6.1 h1:gkbkG5KzYKrv8mLggw5ojg/JulXfEbLIRVhbw9Ot7S0= -github.com/extism/go-sdk v1.6.1/go.mod h1:yRolc4PvIUQ9J/BBB3QZ5EY1MtXAN2jqBGDGR3Sk54M= +github.com/extism/go-sdk v1.7.0 h1:yHbSa2JbcF60kjGsYiGEOcClfbknqCJchyh9TRibFWo= +github.com/extism/go-sdk v1.7.0/go.mod h1:Dhuc1qcD0aqjdqJ3ZDyGdkZPEj/EHKVjbE4P+1XRMqc= github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM= github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU= github.com/fatih/semgroup v1.3.0 h1:pTEnmcEze/BUf4UmVn9f1ZT1OckkBTNRV9w9k/I2/y4= @@ -244,6 +244,8 @@ github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y= github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8= github.com/goccy/go-yaml v1.15.17 h1:dK4FbbTTEOZTLH/NW3/xBqg0JdC14YKVmYwS9GT3H60= github.com/goccy/go-yaml v1.15.17/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= +github.com/goccy/go-yaml v1.15.22 h1:iQI1hvCoiYYiVFq76P4AI8ImgDOfgiyKnl/AWjK8/gA= +github.com/goccy/go-yaml v1.15.22/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk= github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= @@ -634,24 +636,24 @@ go.uber.org/zap v1.21.0/go.mod h1:wjWOCqI0f2ZZrJF/UufIOkiC8ii6tm1iqIsLo76RfJw= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/crypto v0.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc= -golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc= -golang.org/x/crypto/x509roots/fallback v0.0.0-20250204190303-9290511cd23a h1:7InM1wOVdRir08zpJRVKvcnwMIIEV5Jde3g4YUOy43U= -golang.org/x/crypto/x509roots/fallback v0.0.0-20250204190303-9290511cd23a/go.mod h1:kNa9WdvYnzFwC79zRpLRMJbdEFlhyM5RPFBBZp/wWH8= -golang.org/x/exp v0.0.0-20250128182459-e0ece0dbea4c h1:KL/ZBHXgKGVmuZBZ01Lt57yE5ws8ZPSkkihmEyq7FXc= -golang.org/x/exp v0.0.0-20250128182459-e0ece0dbea4c/go.mod h1:tujkw807nyEEAamNbDrEGzRav+ilXA7PCRAd6xsmwiU= +golang.org/x/crypto v0.33.0 h1:IOBPskki6Lysi0lo9qQvbxiQ+FvsCC/YWOecCHAixus= +golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M= +golang.org/x/crypto/x509roots/fallback v0.0.0-20250210163342-e47973b1c108 h1:GiOI2rw2a9rM8uEVXiG+phdNIZRNiT3/ibJBBjdUYfk= +golang.org/x/crypto/x509roots/fallback v0.0.0-20250210163342-e47973b1c108/go.mod h1:kNa9WdvYnzFwC79zRpLRMJbdEFlhyM5RPFBBZp/wWH8= +golang.org/x/exp v0.0.0-20250210185358-939b2ce775ac h1:l5+whBCLH3iH2ZNHYLbAe58bo7yrN4mVcnkHDYz5vvs= +golang.org/x/exp v0.0.0-20250210185358-939b2ce775ac/go.mod h1:hH+7mtFmImwwcMvScyxUhjuVHR3HGaDPMn9rMSUUbxo= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.22.0 h1:D4nJWe9zXqHOmWqj4VMOJhvzj7bEZg4wEYa759z1pH4= -golang.org/x/mod v0.22.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY= +golang.org/x/mod v0.23.0 h1:Zb7khfcRGKk+kqfxFaP5tZqCnDZMjC5VtUBs87Hr6QM= +golang.org/x/mod v0.23.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.34.0 h1:Mb7Mrk043xzHgnRM88suvJFwzVrRfHEHJEl5/71CKw0= -golang.org/x/net v0.34.0/go.mod h1:di0qlW3YNM5oh6GqDGQr92MyTozJPmybPK4Ev/Gm31k= +golang.org/x/net v0.35.0 h1:T5GQRQb2y08kTAByq9L4/bz8cipCdA8FbRTXewonqY8= +golang.org/x/net v0.35.0/go.mod h1:EglIi67kWsHKlRzzVMUD93VMSWGFOMSZgxFjparz1Qk= golang.org/x/oauth2 v0.26.0 h1:afQXWNNaeC4nvZ0Ed9XvCCzXM6UHJG7iCg0W4fPqSBE= golang.org/x/oauth2 v0.26.0/go.mod h1:XYTD2NtWslqkgxebSiOHnXEap4TF09sJSc7H1sXbhtI= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -700,8 +702,8 @@ golang.org/x/tools v0.0.0-20190624222133-a101b041ded4/go.mod h1:/rFqwRUd4F7ZHNgw golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/tools v0.29.0 h1:Xx0h3TtM9rzQpQuR4dKLrdglAmCEN5Oi+P74JdhdzXE= -golang.org/x/tools v0.29.0/go.mod h1:KMQVMRsVxU6nHCFXrBPhDB8XncLNLM0lIy/F14RP588= +golang.org/x/tools v0.30.0 h1:BgcpHewrV5AUp2G9MebG4XPFI1E2W41zU1SaqVA9vJY= +golang.org/x/tools v0.30.0/go.mod h1:c347cR/OJfw5TI+GfX7RUPNMdDRRbjvYTS0jPyvsVtY= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da h1:noIWHXmPHxILtqtCOPIhSt0ABwskkZKjD3bXGnZGpNY= diff --git a/internal/cmd/autobool.go b/internal/cmd/autobool.go index 5271c9bac10..32ed474c181 100644 --- a/internal/cmd/autobool.go +++ b/internal/cmd/autobool.go @@ -87,13 +87,13 @@ func (b *autoBool) UnmarshalJSON(data []byte) error { return nil } -// UnmarshalYAML implements gopkg.in/yaml.Unmarshaler.UnmarshalYAML. -func (b *autoBool) UnmarshalYAML(data []byte) error { - if bytes.Equal(data, []byte("auto")) { +// UnmarshalText implements encoding.TextUnmarshaler.UnmarshalText. +func (b *autoBool) UnmarshalText(text []byte) error { + if bytes.Equal(text, []byte("auto")) { b.auto = true return nil } - boolValue, err := chezmoi.ParseBool(string(data)) + boolValue, err := chezmoi.ParseBool(string(text)) if err != nil { return err }
chore
Update dependencies
fa09effd125d5e12d149842ad2a8a64d59f5ffc7
2021-09-29 21:30:21
mhmdanas
docs: fix error in HOWTO guide
false
diff --git a/docs/HOWTO.md b/docs/HOWTO.md index a9b735fc25f..2274e14727d 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -775,12 +775,13 @@ a shared template. Create the common file in the `.chezmoitemplates` directory in the source state. For example, create `.chezmoitemplates/file.conf`. The contents of this file are -available in templates with the `template *name*` function where *name* is the -name of the file. +available in templates with the `template *name* .` function where *name* is the +name of the file (`.` passes the current data to the template code in `file.conf`; +see https://pkg.go.dev/text/template#hdr-Actions for details). Then create files for each system, for example `Library/Application Support/App/file.conf.tmpl` for macOS and `dot_config/app/file.conf.tmpl` for -Linux. Both template files should contain `{{- template "file.conf" -}}`. +Linux. Both template files should contain `{{- template "file.conf" . -}}`. Finally, tell chezmoi to ignore files where they are not needed by adding lines to your `.chezmoiignore` file, for example:
docs
fix error in HOWTO guide
2ae94bcae215382634d8e0766ac386a86af3ea0d
2023-11-20 06:11:46
Braden Hilton
chore(python): add ruff, use dependabot
false
diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 7971a4a13e4..4eb05363451 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -12,3 +12,9 @@ updates: interval: monthly labels: - enhancement +- package-ecosystem: pip + directory: /assets + schedule: + interval: monthly + labels: + - enhancement diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index ea0c9f2433d..50ed0ab5a12 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -18,7 +18,6 @@ env: GOLINES_VERSION: 0.11.0 GOVERSIONINFO_VERSION: 1.4.0 FIND_TYPOS_VERSION: 0.0.3 - MKDOCS_VERSION: 1.5.3 jobs: changes: runs-on: ubuntu-20.04 @@ -254,7 +253,6 @@ jobs: go-version: ${{ env.GO_VERSION }} - name: install-website-dependencies run: | - pip3 install mkdocs==${{ env.MKDOCS_VERSION }} pip3 install -r assets/chezmoi.io/requirements.txt - name: build-website run: mkdocs build -f assets/chezmoi.io/mkdocs.yml @@ -408,7 +406,6 @@ jobs: go-version: ${{ env.GO_VERSION }} - name: prepare-chezmoi.io run: | - pip3 install mkdocs==${{ env.MKDOCS_VERSION }} pip3 install -r assets/chezmoi.io/requirements.txt mkdocs build -f assets/chezmoi.io/mkdocs.yml env: diff --git a/assets/.gitignore b/assets/.gitignore new file mode 100644 index 00000000000..898765473d1 --- /dev/null +++ b/assets/.gitignore @@ -0,0 +1,6 @@ +__pycache__ + +.venv +.virtualenv +venv +virtualenv diff --git a/assets/chezmoi.io/.gitignore b/assets/chezmoi.io/.gitignore index a7a7a5db0fc..569b973d131 100644 --- a/assets/chezmoi.io/.gitignore +++ b/assets/chezmoi.io/.gitignore @@ -1,4 +1,3 @@ -__pycache__ /docs/index.md /docs/install.md /docs/links/articles.md @@ -7,8 +6,3 @@ __pycache__ /docs/reference/configuration-file/variables.md /docs/reference/release-history.md /site - -/.venv -/.virtualenv -/venv -/virtualenv diff --git a/assets/chezmoi.io/docs/hooks.py b/assets/chezmoi.io/docs/hooks.py index 30d7ab40ce3..313ce167018 100644 --- a/assets/chezmoi.io/docs/hooks.py +++ b/assets/chezmoi.io/docs/hooks.py @@ -1,27 +1,31 @@ +from __future__ import annotations + import subprocess +from pathlib import Path, PurePosixPath -from pathlib import PurePosixPath, Path from mkdocs import utils +from mkdocs.config.defaults import MkDocsConfig +from mkdocs.structure.files import Files non_website_paths = [ - "docs.go", - "hooks.py", - "reference/commands/commands.go", - "reference/commands/commands_test.go", + 'docs.go', + 'hooks.py', + 'reference/commands/commands.go', + 'reference/commands/commands_test.go', ] templates = [ - "index.md", - "install.md", - "links/articles.md", - "links/podcasts.md", - "links/videos.md", - "reference/configuration-file/variables.md", - "reference/release-history.md", + 'index.md', + 'install.md', + 'links/articles.md', + 'links/podcasts.md', + 'links/videos.md', + 'reference/configuration-file/variables.md', + 'reference/release-history.md', ] -def on_pre_build(config, **kwargs): +def on_pre_build(config: MkDocsConfig, **kwargs) -> None: config_dir = Path(config.config_file_path).parent docs_dir = PurePosixPath(config.docs_dir) for src_path in templates: @@ -32,10 +36,10 @@ def on_pre_build(config, **kwargs): if Path(data_path).exists(): args.extend(['-data', data_path]) args.extend(['-output', output_path, template_path]) - subprocess.run(args) + subprocess.run(args, check=False) -def on_files(files, config, **kwargs): +def on_files(files: Files, config: MkDocsConfig, **kwargs) -> Files: # remove non-website files for src_path in non_website_paths: files.remove(files.get_file_from_path(src_path)) @@ -50,7 +54,7 @@ def on_files(files, config, **kwargs): return files -def on_post_build(config, **kwargs): +def on_post_build(config: MkDocsConfig, **kwargs) -> None: config_dir = Path(config.config_file_path).parent site_dir = config.site_dir @@ -59,8 +63,17 @@ def on_post_build(config, **kwargs): # copy installation scripts utils.copy_file(Path(config_dir, '../scripts/install.sh'), Path(site_dir, 'get')) - utils.copy_file(Path(config_dir, '../scripts/install-local-bin.sh'), Path(site_dir, 'getlb')) - utils.copy_file(Path(config_dir, '../scripts/install.ps1'), Path(site_dir, 'get.ps1')) + utils.copy_file( + Path(config_dir, '../scripts/install-local-bin.sh'), + Path(site_dir, 'getlb'), + ) + utils.copy_file( + Path(config_dir, '../scripts/install.ps1'), + Path(site_dir, 'get.ps1'), + ) # copy cosign.pub - utils.copy_file(Path(config_dir, '../cosign/cosign.pub'), Path(site_dir, 'cosign.pub')) + utils.copy_file( + Path(config_dir, '../cosign/cosign.pub'), + Path(site_dir, 'cosign.pub'), + ) diff --git a/assets/chezmoi.io/requirements.txt b/assets/chezmoi.io/requirements.txt index a6a77222b57..f73583d77e2 100644 --- a/assets/chezmoi.io/requirements.txt +++ b/assets/chezmoi.io/requirements.txt @@ -1,2 +1,2 @@ -mkdocs-material -mkdocs-mermaid2-plugin +mkdocs-material==9.4.10 +mkdocs-mermaid2-plugin==1.1.1 diff --git a/assets/requirements.dev.txt b/assets/requirements.dev.txt new file mode 100644 index 00000000000..ef58a36c6ef --- /dev/null +++ b/assets/requirements.dev.txt @@ -0,0 +1 @@ +ruff==0.1.6 diff --git a/assets/requirements.txt b/assets/requirements.txt new file mode 100644 index 00000000000..163f97e2a9b --- /dev/null +++ b/assets/requirements.txt @@ -0,0 +1 @@ +ruamel.yaml==0.18.5 diff --git a/assets/ruff.toml b/assets/ruff.toml new file mode 100644 index 00000000000..e9419148290 --- /dev/null +++ b/assets/ruff.toml @@ -0,0 +1,20 @@ +[lint] +extend-select = [ + "A", + "B", + "E", + "F", + "I", + "W", + "ANN", + "COM", + "FA", + "UP", + "PL", + "PTH", + "SIM", +] +ignore = ["ANN003"] + +[format] +quote-style = "single" diff --git a/assets/scripts/format-yaml.py b/assets/scripts/format-yaml.py index e3385b4e5dc..c5487bcbe14 100755 --- a/assets/scripts/format-yaml.py +++ b/assets/scripts/format-yaml.py @@ -1,18 +1,22 @@ #!/usr/bin/env python3 +from __future__ import annotations + import sys +from pathlib import Path from ruamel.yaml import YAML -def main(): +def main() -> int: yaml = YAML() for filename in sys.argv[1:]: - with open(filename) as file: + with Path(filename).open('r') as file: data = yaml.load(file) - with open(filename, 'w') as file: + with Path(filename).open('w') as file: yaml.dump(data, file) + return 0 if __name__ == '__main__': - main() + raise SystemExit(main())
chore
add ruff, use dependabot
bec3d0a03a0ccdcd2f4be319568d764eff0c2777
2022-05-10 00:25:34
Tom Payne
chore: Pin Ubuntu versions in GitHub Actions
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 80b86c29023..ddff3553824 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -15,7 +15,7 @@ env: GOLANGCI_LINT_VERSION: 1.46.0 jobs: build-website: - runs-on: ubuntu-latest + runs-on: ubuntu-20.04 steps: - uses: actions/checkout@2541b1294d2704b0964813337f33b291d3f8596b - name: install-website-dependencies @@ -410,7 +410,7 @@ jobs: - test-ubuntu-go1-17 - test-voidlinux - test-windows - runs-on: ubuntu-18.04 + runs-on: ubuntu-20.04 steps: - name: install-build-dependencies run: |
chore
Pin Ubuntu versions in GitHub Actions
b8d9670902da85a8a48bfb535104231272d3beb6
2025-02-24 03:42:30
Tom Payne
fix: Fix handling of umask on macOS
false
diff --git a/internal/cmd/mackupcmd_test_darwin.go b/internal/cmd/mackupcmd_darwin_test.go similarity index 100% rename from internal/cmd/mackupcmd_test_darwin.go rename to internal/cmd/mackupcmd_darwin_test.go
fix
Fix handling of umask on macOS
991a6307e3bd50fd022eb0995c4109eeb59b671d
2022-06-19 22:12:55
Tomasz Cholewik
docs: Clarify what 'source state' means
false
diff --git a/assets/chezmoi.io/docs/reference/special-files-and-directories/chezmoiexternal-format.md b/assets/chezmoi.io/docs/reference/special-files-and-directories/chezmoiexternal-format.md index 55f30419e4b..4d9972ab091 100644 --- a/assets/chezmoi.io/docs/reference/special-files-and-directories/chezmoiexternal-format.md +++ b/assets/chezmoi.io/docs/reference/special-files-and-directories/chezmoiexternal-format.md @@ -1,6 +1,7 @@ # `.chezmoiexternal.$FORMAT` -If a file called `.chezmoiexternal.$FORMAT` exists in the source state, it is +If a file called `.chezmoiexternal.$FORMAT` exists in the source state (either +`~/.local/share/chezmoi` or directory defined inside `.chezmoiroot`), it is interpreted as a list of external files and archives to be included as if they were in the source state.
docs
Clarify what 'source state' means
4a3afada04f57129a5abba3f5a0e3b3236f36329
2022-09-19 08:29:26
Tom Payne
chore: Tidy up //nolint: directives
false
diff --git a/pkg/chezmoi/ageencryption.go b/pkg/chezmoi/ageencryption.go index 78c46bdafa8..12949ef6e4d 100644 --- a/pkg/chezmoi/ageencryption.go +++ b/pkg/chezmoi/ageencryption.go @@ -41,8 +41,7 @@ func (e *AgeEncryption) Decrypt(ciphertext []byte) ([]byte, error) { return e.builtinDecrypt(ciphertext) } - //nolint:gosec - cmd := exec.Command(e.Command, append(e.decryptArgs(), e.Args...)...) + cmd := exec.Command(e.Command, append(e.decryptArgs(), e.Args...)...) //nolint:gosec cmd.Stdin = bytes.NewReader(ciphertext) cmd.Stderr = os.Stderr return chezmoilog.LogCmdOutput(cmd) @@ -58,8 +57,8 @@ func (e *AgeEncryption) DecryptToFile(plaintextAbsPath AbsPath, ciphertext []byt return e.BaseSystem.WriteFile(plaintextAbsPath, plaintext, 0o644) } - //nolint:gosec - cmd := exec.Command(e.Command, append(append(e.decryptArgs(), "--output", plaintextAbsPath.String()), e.Args...)...) + args := append(append(e.decryptArgs(), "--output", plaintextAbsPath.String()), e.Args...) + cmd := exec.Command(e.Command, args...) //nolint:gosec cmd.Stdin = bytes.NewReader(ciphertext) cmd.Stderr = os.Stderr return chezmoilog.LogCmdRun(cmd) @@ -71,8 +70,7 @@ func (e *AgeEncryption) Encrypt(plaintext []byte) ([]byte, error) { return e.builtinEncrypt(plaintext) } - //nolint:gosec - cmd := exec.Command(e.Command, append(e.encryptArgs(), e.Args...)...) + cmd := exec.Command(e.Command, append(e.encryptArgs(), e.Args...)...) //nolint:gosec cmd.Stdin = bytes.NewReader(plaintext) cmd.Stderr = os.Stderr return chezmoilog.LogCmdOutput(cmd) @@ -88,8 +86,7 @@ func (e *AgeEncryption) EncryptFile(plaintextAbsPath AbsPath) ([]byte, error) { return e.builtinEncrypt(plaintext) } - //nolint:gosec - cmd := exec.Command(e.Command, append(append(e.encryptArgs(), e.Args...), plaintextAbsPath.String())...) + cmd := exec.Command(e.Command, append(append(e.encryptArgs(), e.Args...), plaintextAbsPath.String())...) //nolint:gosec cmd.Stderr = os.Stderr return chezmoilog.LogCmdOutput(cmd) } diff --git a/pkg/chezmoi/externaldiffsystem.go b/pkg/chezmoi/externaldiffsystem.go index e48c516d8c4..633f3718918 100644 --- a/pkg/chezmoi/externaldiffsystem.go +++ b/pkg/chezmoi/externaldiffsystem.go @@ -164,8 +164,7 @@ func (s *ExternalDiffSystem) RunScript(scriptname RelPath, dir AbsPath, data []b if err := os.MkdirAll(targetAbsPath.Dir().String(), 0o700); err != nil { return err } - //nolint:gosec - if err := os.WriteFile(targetAbsPath.String(), data, 0o700); err != nil { + if err := os.WriteFile(targetAbsPath.String(), data, 0o700); err != nil { //nolint:gosec return err } if err := s.runDiffCommand(devNullAbsPath, targetAbsPath); err != nil { @@ -291,8 +290,7 @@ func (s *ExternalDiffSystem) runDiffCommand(destAbsPath, targetAbsPath AbsPath) args = append(args, templateData.Destination, templateData.Target) } - //nolint:gosec - cmd := exec.Command(s.command, args...) + cmd := exec.Command(s.command, args...) //nolint:gosec cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr diff --git a/pkg/chezmoi/gpgencryption.go b/pkg/chezmoi/gpgencryption.go index 8cbf42d4d54..f15e2293249 100644 --- a/pkg/chezmoi/gpgencryption.go +++ b/pkg/chezmoi/gpgencryption.go @@ -139,8 +139,7 @@ func (e *GPGEncryption) encryptArgs(plaintextFilename, ciphertextFilename AbsPat // run runs the command with args. func (e *GPGEncryption) run(args []string) error { - //nolint:gosec - cmd := exec.Command(e.Command, args...) + cmd := exec.Command(e.Command, args...) //nolint:gosec cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr diff --git a/pkg/chezmoi/interpreter.go b/pkg/chezmoi/interpreter.go index 7e353c6fbf2..5116d6abac6 100644 --- a/pkg/chezmoi/interpreter.go +++ b/pkg/chezmoi/interpreter.go @@ -17,8 +17,7 @@ func (i *Interpreter) ExecCommand(name string) *exec.Cmd { if i.None() { return exec.Command(name) } - //nolint:gosec - return exec.Command(i.Command, append(i.Args, name)...) + return exec.Command(i.Command, append(i.Args, name)...) //nolint:gosec } // None returns if i represents no interpreter. diff --git a/pkg/chezmoi/sourcestate.go b/pkg/chezmoi/sourcestate.go index 69092b4e6cd..21b15d22abb 100644 --- a/pkg/chezmoi/sourcestate.go +++ b/pkg/chezmoi/sourcestate.go @@ -1360,8 +1360,7 @@ func (s *SourceState) getExternalData( } if external.Filter.Command != "" { - //nolint:gosec - cmd := exec.Command(external.Filter.Command, external.Filter.Args...) + cmd := exec.Command(external.Filter.Command, external.Filter.Args...) //nolint:gosec cmd.Stdin = bytes.NewReader(data) cmd.Stderr = os.Stderr data, err = chezmoilog.LogCmdOutput(cmd) diff --git a/pkg/chezmoi/system.go b/pkg/chezmoi/system.go index d5ca680c5ff..a9a05f56f60 100644 --- a/pkg/chezmoi/system.go +++ b/pkg/chezmoi/system.go @@ -14,9 +14,7 @@ import ( // A System reads from and writes to a filesystem, runs scripts, and persists // state. -// -//nolint:interfacebloat -type System interface { +type System interface { //nolint:interfacebloat Chmod(name AbsPath, mode fs.FileMode) error Glob(pattern string) ([]string, error) Link(oldname, newname AbsPath) error diff --git a/pkg/chezmoibubbles/chezmoibubbles_test.go b/pkg/chezmoibubbles/chezmoibubbles_test.go index b123694f057..c855ddf1557 100644 --- a/pkg/chezmoibubbles/chezmoibubbles_test.go +++ b/pkg/chezmoibubbles/chezmoibubbles_test.go @@ -13,8 +13,7 @@ var keyTypes = map[tea.KeyType]struct{}{ tea.KeyEsc: {}, } -//nolint:ireturn,nolintlint -func makeKeyMsg(r rune) tea.Msg { +func makeKeyMsg(r rune) tea.Msg { //nolint:ireturn,nolintlint key := tea.Key{ Type: tea.KeyRunes, Runes: []rune{r}, @@ -27,8 +26,7 @@ func makeKeyMsg(r rune) tea.Msg { return tea.KeyMsg(key) } -//nolint:ireturn,nolintlint -func makeKeyMsgs(s string) []tea.Msg { +func makeKeyMsgs(s string) []tea.Msg { //nolint:ireturn,nolintlint msgs := make([]tea.Msg, 0, len(s)) for _, r := range s { msgs = append(msgs, makeKeyMsg(r)) @@ -36,8 +34,7 @@ func makeKeyMsgs(s string) []tea.Msg { return msgs } -//nolint:ireturn,nolintlint -func testRunModelWithInput[M tea.Model](t *testing.T, model M, input string) M { +func testRunModelWithInput[M tea.Model](t *testing.T, model M, input string) M { //nolint:ireturn,nolintlint t.Helper() for _, msg := range makeKeyMsgs(input) { m, _ := model.Update(msg) diff --git a/pkg/chezmoitest/chezmoitest.go b/pkg/chezmoitest/chezmoitest.go index 947c95197a7..ef3c4a880f3 100644 --- a/pkg/chezmoitest/chezmoitest.go +++ b/pkg/chezmoitest/chezmoitest.go @@ -39,8 +39,7 @@ func AgeGenerateKey(identityFile string) (string, error) { // passphrase. func GPGGenerateKey(command, homeDir string) (key, passphrase string, err error) { key = "chezmoi-test-gpg-key" - //nolint:gosec - passphrase = "chezmoi-test-gpg-passphrase" + passphrase = "chezmoi-test-gpg-passphrase" //nolint:gosec cmd := exec.Command( command, "--batch", diff --git a/pkg/cmd/config.go b/pkg/cmd/config.go index 8fa87edc780..b0ebf630b60 100644 --- a/pkg/cmd/config.go +++ b/pkg/cmd/config.go @@ -2179,8 +2179,7 @@ func (c *Config) writeOutput(data []byte) error { _, err := c.stdout.Write(data) return err } - //nolint:gosec - return os.WriteFile(c.outputAbsPath.String(), data, 0o666) + return os.WriteFile(c.outputAbsPath.String(), data, 0o666) //nolint:gosec } // writeOutputString writes data to the configured output. diff --git a/pkg/cmd/doctorcmd.go b/pkg/cmd/doctorcmd.go index 142d686ddf3..1353f2a1e99 100644 --- a/pkg/cmd/doctorcmd.go +++ b/pkg/cmd/doctorcmd.go @@ -436,8 +436,7 @@ func (c *binaryCheck) Run(system chezmoi.System, homeDirAbsPath chezmoi.AbsPath) return checkResultOK, fmt.Sprintf("found %s", pathAbsPath) } - //nolint:gosec - cmd := exec.Command(pathAbsPath.String(), c.versionArgs...) + cmd := exec.Command(pathAbsPath.String(), c.versionArgs...) //nolint:gosec output, err := chezmoilog.LogCmdCombinedOutput(cmd) if err != nil { return checkResultFailed, err.Error() @@ -526,8 +525,7 @@ func (c *dirCheck) Run(system chezmoi.System, homeDirAbsPath chezmoi.AbsPath) (c if dirEntry.Name() != ".git" { continue } - //nolint:gosec - cmd := exec.Command("git", "-C", c.dirname.String(), "status", "--porcelain=v2") + cmd := exec.Command("git", "-C", c.dirname.String(), "status", "--porcelain=v2") //nolint:gosec output, err := cmd.Output() if err != nil { gitStatus = gitStatusError diff --git a/pkg/cmd/onepasswordtemplatefuncs.go b/pkg/cmd/onepasswordtemplatefuncs.go index f72b26b8b74..be9d6d83d80 100644 --- a/pkg/cmd/onepasswordtemplatefuncs.go +++ b/pkg/cmd/onepasswordtemplatefuncs.go @@ -267,8 +267,7 @@ func (c *Config) onepasswordGetOrRefreshSessionToken(args *onepasswordArgs) (str commandArgs = append([]string{"--session", sessionToken}, commandArgs...) } - //nolint:gosec - cmd := exec.Command(c.Onepassword.Command, commandArgs...) + cmd := exec.Command(c.Onepassword.Command, commandArgs...) //nolint:gosec cmd.Stdin = os.Stdin cmd.Stderr = os.Stderr output, err := chezmoilog.LogCmdOutput(cmd) @@ -340,8 +339,7 @@ func (c *Config) onepasswordOutput(args *onepasswordArgs, withSessionToken withS } } - //nolint:gosec - cmd := exec.Command(c.Onepassword.Command, commandArgs...) + cmd := exec.Command(c.Onepassword.Command, commandArgs...) //nolint:gosec cmd.Stdin = os.Stdin cmd.Stderr = os.Stderr output, err := chezmoilog.LogCmdOutput(cmd) diff --git a/pkg/cmd/passtemplatefuncs.go b/pkg/cmd/passtemplatefuncs.go index 575852822ea..6f6eeff4c6c 100644 --- a/pkg/cmd/passtemplatefuncs.go +++ b/pkg/cmd/passtemplatefuncs.go @@ -51,8 +51,7 @@ func (c *Config) passOutput(id string) ([]byte, error) { } args := []string{"show", id} - //nolint:gosec - cmd := exec.Command(c.Pass.Command, args...) + cmd := exec.Command(c.Pass.Command, args...) //nolint:gosec cmd.Stdin = os.Stdin cmd.Stderr = os.Stderr output, err := chezmoilog.LogCmdOutput(cmd) diff --git a/pkg/cmd/prompt.go b/pkg/cmd/prompt.go index a6450ecb9ce..af05841df7a 100644 --- a/pkg/cmd/prompt.go +++ b/pkg/cmd/prompt.go @@ -229,8 +229,7 @@ type cancelableModel interface { Canceled() bool } -//nolint:ireturn,nolintlint -func runCancelableModel[M cancelableModel](initModel M) (M, error) { +func runCancelableModel[M cancelableModel](initModel M) (M, error) { //nolint:ireturn,nolintlint switch finalModel, err := runModel(initModel); { case err != nil: return finalModel, err @@ -241,10 +240,8 @@ func runCancelableModel[M cancelableModel](initModel M) (M, error) { } } -//nolint:ireturn,nolintlint -func runModel[M tea.Model](initModel M) (M, error) { +func runModel[M tea.Model](initModel M) (M, error) { //nolint:ireturn,nolintlint program := tea.NewProgram(initModel) finalModel, err := program.StartReturningModel() - //nolint:forcetypeassert - return finalModel.(M), err + return finalModel.(M), err //nolint:forcetypeassert } diff --git a/pkg/cmd/secrettemplatefuncs.go b/pkg/cmd/secrettemplatefuncs.go index 9a71e387fff..6feae375b38 100644 --- a/pkg/cmd/secrettemplatefuncs.go +++ b/pkg/cmd/secrettemplatefuncs.go @@ -44,8 +44,7 @@ func (c *Config) secretOutput(args []string) ([]byte, error) { } args = append(c.Secret.Args, args...) - //nolint:gosec - cmd := exec.Command(c.Secret.Command, args...) + cmd := exec.Command(c.Secret.Command, args...) //nolint:gosec cmd.Stdin = os.Stdin cmd.Stderr = os.Stderr output, err := chezmoilog.LogCmdOutput(cmd) diff --git a/pkg/cmd/textconv.go b/pkg/cmd/textconv.go index 1024c89bbc8..f5a2d44f741 100644 --- a/pkg/cmd/textconv.go +++ b/pkg/cmd/textconv.go @@ -37,8 +37,7 @@ func (t textConv) convert(absPath chezmoi.AbsPath, data []byte) ([]byte, error) return data, nil } - //nolint:gosec - cmd := exec.Command(longestPatternElement.Command, longestPatternElement.Args...) + cmd := exec.Command(longestPatternElement.Command, longestPatternElement.Args...) //nolint:gosec cmd.Stdin = bytes.NewReader(data) cmd.Stderr = os.Stderr return chezmoilog.LogCmdOutput(cmd) diff --git a/pkg/cmd/util_unix.go b/pkg/cmd/util_unix.go index 22ef2ee4d30..d1cdf600e96 100644 --- a/pkg/cmd/util_unix.go +++ b/pkg/cmd/util_unix.go @@ -21,6 +21,5 @@ func enableVirtualTerminalProcessing(w io.Writer) (func() error, error) { } func fileInfoUID(info fs.FileInfo) int { - //nolint:forcetypeassert - return int(info.Sys().(*syscall.Stat_t).Uid) + return int(info.Sys().(*syscall.Stat_t).Uid) //nolint:forcetypeassert } diff --git a/pkg/cmd/vaulttemplatefuncs.go b/pkg/cmd/vaulttemplatefuncs.go index 37ec29808b0..460c69129b0 100644 --- a/pkg/cmd/vaulttemplatefuncs.go +++ b/pkg/cmd/vaulttemplatefuncs.go @@ -19,8 +19,7 @@ func (c *Config) vaultTemplateFunc(key string) any { } args := []string{"kv", "get", "-format=json", key} - //nolint:gosec - cmd := exec.Command(c.Vault.Command, args...) + cmd := exec.Command(c.Vault.Command, args...) //nolint:gosec cmd.Stdin = os.Stdin cmd.Stderr = os.Stderr output, err := chezmoilog.LogCmdOutput(cmd)
chore
Tidy up //nolint: directives
2c7ad91413ea1d24e24b149f240ff68c69ac6b40
2021-12-27 02:23:00
Tim Byrne
docs: Update comparison table formatting
false
diff --git a/docs/COMPARISON.md b/docs/COMPARISON.md index b07b8446142..a2b6970f807 100644 --- a/docs/COMPARISON.md +++ b/docs/COMPARISON.md @@ -21,35 +21,35 @@ [yadm]: https://yadm.io/ [bare git]: https://www.atlassian.com/git/tutorials/dotfiles "bare git" -| | [chezmoi] | [dotbot] | [rcm] | [homesick] | [vcsh] | [yadm] | [bare git] | -| -------------------------------------- | ------------- | ----------------- | ----------------- | ----------------- | ------------------------ | ------------- | ---------- | -| Distribution | Single binary | Python package | Multiple files | Ruby gem | Single script or package | Single script | - | -| Install method | Many | git submodule | Many | Ruby gem | Many | Many | Manual | -| Non-root install on bare system | ✅ | ⁉️ | ⁉️ | ⁉️ | ✅ | ✅ | ✅ | -| Windows support | ✅ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | -| Bootstrap requirements | None | Python, git | Perl, git | Ruby, git | sh, git | git | git | -| Source repos | Single | Single | Multiple | Single | Multiple | Single | Single | -| dotfiles are... | Files | Symlinks | Files | Symlinks | Files | Files | Files | -| Config file | Optional | Required | Optional | None | None | Optional | Optional | -| Private files | ✅ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | -| Show differences without applying | ✅ | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | -| Whole file encryption | ✅ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | -| Password manager integration | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | -| Machine-to-machine file differences | Templates | Alternative files | Alternative files | Alternative files | Branches | Alternative files, Templates | ⁉️ | -| Custom variables in templates | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | -| Executable files | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | -| File creation with initial contents | ✅ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | -| Externals | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | -| Manage partial files | ✅ | ❌ | ❌ | ❌ | ⁉️ | ✅ | ⁉️ | -| File removal | ✅ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | -| Directory creation | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | -| Run scripts | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ❌ | -| Run once scripts | ✅ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | -| Machine-to-machine symlink differences | ✅ | ❌ | ❌ | ❌ | ⁉️ | ✅ | ⁉️ | -| Shell completion | ✅ | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | -| Archive import | ✅ | ❌ | ❌ | ❌ | ✅ | ❌ | ✅ | -| Archive export | ✅ | ❌ | ❌ | ❌ | ✅ | ❌ | ✅ | -| Implementation language | Go | Python | Perl | Ruby | POSIX Shell | Bash | C | +| | [chezmoi] | [dotbot] | [rcm] | [homesick] | [vcsh] | [yadm] | [bare git] | +| -------------------------------------- | ------------- | ----------------- | ----------------- | ----------------- | ------------------------ | ------------- | ---------- | +| Distribution | Single binary | Python package | Multiple files | Ruby gem | Single script or package | Single script | - | +| Install method | Many | git submodule | Many | Ruby gem | Many | Many | Manual | +| Non-root install on bare system | ✅ | ⁉️ | ⁉️ | ⁉️ | ✅ | ✅ | ✅ | +| Windows support | ✅ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | +| Bootstrap requirements | None | Python, git | Perl, git | Ruby, git | sh, git | git | git | +| Source repos | Single | Single | Multiple | Single | Multiple | Single | Single | +| dotfiles are... | Files | Symlinks | Files | Symlinks | Files | Files | Files | +| Config file | Optional | Required | Optional | None | None | Optional | Optional | +| Private files | ✅ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | +| Show differences without applying | ✅ | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | +| Whole file encryption | ✅ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | +| Password manager integration | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | +| Machine-to-machine file differences | Templates | Alternative files | Alternative files | Alternative files | Branches | Alternative files, Templates | ⁉️ | +| Custom variables in templates | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | +| Executable files | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | +| File creation with initial contents | ✅ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | +| Externals | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | +| Manage partial files | ✅ | ❌ | ❌ | ❌ | ⁉️ | ✅ | ⁉️ | +| File removal | ✅ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | +| Directory creation | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | +| Run scripts | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ❌ | +| Run once scripts | ✅ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | +| Machine-to-machine symlink differences | ✅ | ❌ | ❌ | ❌ | ⁉️ | ✅ | ⁉️ | +| Shell completion | ✅ | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | +| Archive import | ✅ | ❌ | ❌ | ❌ | ✅ | ❌ | ✅ | +| Archive export | ✅ | ❌ | ❌ | ❌ | ✅ | ❌ | ✅ | +| Implementation language | Go | Python | Perl | Ruby | POSIX Shell | Bash | C | ✅ Supported, ⁉️ Possible with significant manual effort, ❌ Not supported
docs
Update comparison table formatting
aa36e8c71bdd3b2857489db49f4768cbec9f8f4a
2025-01-25 09:18:44
Tom Payne
chore: Update tools
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index aa51bb0d807..0f177e71c19 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -14,7 +14,7 @@ concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: true env: - ACTIONLINT_VERSION: 1.7.6 # https://github.com/rhysd/actionlint/releases + ACTIONLINT_VERSION: 1.7.7 # https://github.com/rhysd/actionlint/releases AGE_VERSION: 1.2.1 # https://github.com/FiloSottile/age/releases CHOCOLATEY_VERSION: 2.4.1 # https://github.com/chocolatey/choco/releases EDITORCONFIG_CHECKER_VERSION: 3.1.2 # https://github.com/editorconfig-checker/editorconfig-checker/releases @@ -23,11 +23,11 @@ env: GOFUMPT_VERSION: 0.7.0 # https://github.com/mvdan/gofumpt/releases GOLANGCI_LINT_VERSION: 1.63.4 # https://github.com/golangci/golangci-lint/releases GOLINES_VERSION: 0.12.2 # https://github.com/segmentio/golines/releases - GORELEASER_VERSION: 2.5.1 # https://github.com/goreleaser/goreleaser/releases + GORELEASER_VERSION: 2.6.1 # https://github.com/goreleaser/goreleaser/releases GOVERSIONINFO_VERSION: 1.4.1 # https://github.com/josephspurrier/goversioninfo/releases PYTHON_VERSION: '3.10' # https://www.python.org/downloads/ RAGE_VERSION: 0.11.1 # https://github.com/str4d/rage/releases - UV_VERSION: 0.5.20 # https://github.com/astral-sh/uv/releases + UV_VERSION: 0.5.24 # https://github.com/astral-sh/uv/releases jobs: changes: runs-on: ubuntu-22.04
chore
Update tools
2d1c383151213954fa2a11a31a6ed6742c67f112
2023-06-05 01:39:24
Tom Payne
feat: Add get.chezmoi.io/lb and chezmoi.io/getlb install scripts
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 36fda0cac69..cbbc812abb3 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -439,6 +439,7 @@ jobs: - name: prepare-get.chezmoi.io run: | cp assets/scripts/install.sh assets/get.chezmoi.io/index.html + cp assets/scripts/install-local-bin.sh assets/get.chezmoi.io/lb cp assets/scripts/install.ps1 assets/get.chezmoi.io/ps1 cp LICENSE assets/get.chezmoi.io/LICENSE - name: push-get.chezmoi.io @@ -451,3 +452,4 @@ jobs: destination-repository-name: get.chezmoi.io target-branch: gh-pages commit-message: 'chore: Update from ORIGIN_COMMIT' + user-email: [email protected] diff --git a/assets/chezmoi.io/docs/hooks.py b/assets/chezmoi.io/docs/hooks.py index 1210081bcc3..c5067f7b6ba 100644 --- a/assets/chezmoi.io/docs/hooks.py +++ b/assets/chezmoi.io/docs/hooks.py @@ -56,6 +56,7 @@ def on_post_build(config, **kwargs): # copy installation scripts utils.copy_file('../scripts/install.sh', os.path.join(site_dir, 'get')) + utils.copy_file('../scripts/install-local-bin.sh', os.path.join(site_dir, 'getlb')) utils.copy_file('../scripts/install.ps1', os.path.join(site_dir, 'get.ps1')) # copy cosign.pub diff --git a/assets/chezmoi.io/docs/install.md.tmpl b/assets/chezmoi.io/docs/install.md.tmpl index 6e2eaf310e6..c141073a3d8 100644 --- a/assets/chezmoi.io/docs/install.md.tmpl +++ b/assets/chezmoi.io/docs/install.md.tmpl @@ -168,6 +168,11 @@ with a single command: sh -c "$(curl -fsLS get.chezmoi.io)" -- init --apply [email protected]:$GITHUB_USERNAME/dotfiles.git ``` +!!! hint + + If you want to install chezmoi in `./.local/bin` instead of `./bin` you can + use `get.chezmoi.io/lb` or `chezmoi.io/getlb` instead. + !!! hint To install the chezmoi binary in a different directory, use the `-b` option, @@ -295,8 +300,9 @@ Verify the signature of the checksum file with cosign. cosign should print `Verified OK` -Verify the that the SHA256 sum of your downloads match the SHA256 sum in the -verified checksum file. All your downloads must be in the current directory. +Verify the that the SHA256 sum of your downloads matches the SHA256 sum in the +verified checksum file. All the downloaded files must be in the current +directory. === "Linux" diff --git a/assets/scripts/install-local-bin.sh b/assets/scripts/install-local-bin.sh new file mode 100644 index 00000000000..c39341eafcb --- /dev/null +++ b/assets/scripts/install-local-bin.sh @@ -0,0 +1,357 @@ +#!/bin/sh + +# chezmoi install script +# contains code from and inspired by +# https://github.com/client9/shlib +# https://github.com/goreleaser/godownloader + +set -e + +BINDIR="${BINDIR:-.local/bin}" +CHEZMOI_USER_REPO="${CHEZMOI_USER_REPO:-twpayne/chezmoi}" +TAGARG=latest +LOG_LEVEL=2 + +GITHUB_DOWNLOAD="https://github.com/${CHEZMOI_USER_REPO}/releases/download" + +tmpdir="$(mktemp -d)" +trap 'rm -rf -- "${tmpdir}"' EXIT +trap 'exit' INT TERM + +usage() { + this="${1}" + cat <<EOF +${this}: download chezmoi and optionally run chezmoi + +Usage: ${this} [-b bindir] [-d] [-t tag] [chezmoi-args] + -b sets the installation directory, default is ${BINDIR}. + -d enables debug logging. + -t sets the tag, default is ${TAG}. +If chezmoi-args are given, after install chezmoi is executed with chezmoi-args. +EOF + exit 2 +} + +main() { + parse_args "${@}" + shift "$((OPTIND - 1))" + + GOOS="$(get_goos)" + GOARCH="$(get_goarch)" + check_goos_goarch "${GOOS}/${GOARCH}" + + TAG="$(real_tag "${TAGARG}")" + VERSION="${TAG#v}" + + log_info "found version ${VERSION} for ${TAGARG}/${GOOS}/${GOARCH}" + + BINSUFFIX= + FORMAT=tar.gz + GOOS_EXTRA= + case "${GOOS}" in + linux) + case "${GOARCH}" in + amd64) + case "$(get_libc)" in + glibc) + GOOS_EXTRA="-glibc" + ;; + musl) + GOOS_EXTRA="-musl" + ;; + esac + ;; + esac + ;; + windows) + BINSUFFIX=.exe + FORMAT=zip + ;; + esac + case "${GOARCH}" in + 386) arch=i386 ;; + *) arch="${GOARCH}" ;; + esac + + # download tarball + NAME="chezmoi_${VERSION}_${GOOS}${GOOS_EXTRA}_${arch}" + TARBALL="${NAME}.${FORMAT}" + TARBALL_URL="${GITHUB_DOWNLOAD}/${TAG}/${TARBALL}" + http_download "${tmpdir}/${TARBALL}" "${TARBALL_URL}" || exit 1 + + # download checksums + CHECKSUMS="chezmoi_${VERSION}_checksums.txt" + CHECKSUMS_URL="${GITHUB_DOWNLOAD}/${TAG}/${CHECKSUMS}" + http_download "${tmpdir}/${CHECKSUMS}" "${CHECKSUMS_URL}" || exit 1 + + # verify checksums + hash_sha256_verify "${tmpdir}/${TARBALL}" "${tmpdir}/${CHECKSUMS}" + + (cd -- "${tmpdir}" && untar "${TARBALL}") + + # install binary + if [ ! -d "${BINDIR}" ]; then + install -d "${BINDIR}" + fi + BINARY="chezmoi${BINSUFFIX}" + install -- "${tmpdir}/${BINARY}" "${BINDIR}/" + log_info "installed ${BINDIR}/${BINARY}" + + if [ -n "${1+n}" ]; then + exec "${BINDIR}/${BINARY}" "${@}" + fi +} + +parse_args() { + while getopts "b:dh?t:" arg; do + case "${arg}" in + b) BINDIR="${OPTARG}" ;; + d) LOG_LEVEL=3 ;; + h | \?) usage "${0}" ;; + t) TAGARG="${OPTARG}" ;; + *) return 1 ;; + esac + done +} + +get_goos() { + os="$(uname -s | tr '[:upper:]' '[:lower:]')" + case "${os}" in + cygwin_nt*) goos="windows" ;; + mingw*) goos="windows" ;; + msys_nt*) goos="windows" ;; + sunos*) + kernel="$(uname -o | tr '[:upper:]' '[:lower:]')" + case "${kernel}" in + illumos*) goos="illumos" ;; + solaris*) goos="solaris" ;; + *) goos="${os}" ;; + esac + ;; + *) goos="${os}" ;; + esac + printf '%s' "${goos}" +} + +get_goarch() { + arch="$(uname -m)" + case "${arch}" in + aarch64) goarch="arm64" ;; + armv*) goarch="arm" ;; + i386) goarch="386" ;; + i686) goarch="386" ;; + i86pc) goarch="amd64" ;; + x86) goarch="386" ;; + x86_64) goarch="amd64" ;; + *) goarch="${arch}" ;; + esac + printf '%s' "${goarch}" +} + +check_goos_goarch() { + case "${1}" in + darwin/amd64) return 0 ;; + darwin/arm64) return 0 ;; + freebsd/386) return 0 ;; + freebsd/amd64) return 0 ;; + freebsd/arm) return 0 ;; + freebsd/arm64) return 0 ;; + freebsd/riscv64) return 0 ;; + illumos/amd64) return 0 ;; + linux/386) return 0 ;; + linux/amd64) return 0 ;; + linux/arm) return 0 ;; + linux/arm64) return 0 ;; + linux/loong64) return 0 ;; + linux/mips64) return 0 ;; + linux/mips64le) return 0 ;; + linux/ppc64) return 0 ;; + linux/ppc64le) return 0 ;; + linux/riscv64) return 0 ;; + linux/s390x) return 0 ;; + openbsd/386) return 0 ;; + openbsd/amd64) return 0 ;; + openbsd/arm) return 0 ;; + openbsd/arm64) return 0 ;; + openbsd/mips64) return 0 ;; + solaris/amd64) return 0 ;; + windows/386) return 0 ;; + windows/amd64) return 0 ;; + windows/arm) return 0 ;; + *) + printf '%s: unsupported platform\n' "${1}" 1>&2 + return 1 + ;; + esac +} + +get_libc() { + if is_command ldd; then + case "$(ldd --version 2>&1 | tr '[:upper:]' '[:lower:]')" in + *glibc* | *"gnu libc"*) + printf glibc + return + ;; + *musl*) + printf musl + return + ;; + esac + fi + if is_command getconf; then + case "$(getconf GNU_LIBC_VERSION 2>&1)" in + *glibc*) + printf glibc + return + ;; + esac + fi + log_crit "unable to determine libc" 1>&2 + exit 1 +} + +real_tag() { + tag="${1}" + log_debug "checking GitHub for tag ${tag}" + release_url="https://github.com/${CHEZMOI_USER_REPO}/releases/${tag}" + json="$(http_get "${release_url}" "Accept: application/json")" + if [ -z "${json}" ]; then + log_err "real_tag error retrieving GitHub release ${tag}" + return 1 + fi + real_tag="$(printf '%s\n' "${json}" | tr -s '\n' ' ' | sed 's/.*"tag_name":"//' | sed 's/".*//')" + if [ -z "${real_tag}" ]; then + log_err "real_tag error determining real tag of GitHub release ${tag}" + return 1 + fi + if [ -z "${real_tag}" ]; then + return 1 + fi + log_debug "found tag ${real_tag} for ${tag}" + printf '%s' "${real_tag}" +} + +http_get() { + tmpfile="$(mktemp)" + http_download "${tmpfile}" "${1}" "${2}" || return 1 + body="$(cat "${tmpfile}")" + rm -f "${tmpfile}" + printf '%s\n' "${body}" +} + +http_download_curl() { + local_file="${1}" + source_url="${2}" + header="${3}" + if [ -z "${header}" ]; then + code="$(curl -w '%{http_code}' -sL -o "${local_file}" "${source_url}")" + else + code="$(curl -w '%{http_code}' -sL -H "${header}" -o "${local_file}" "${source_url}")" + fi + if [ "${code}" != "200" ]; then + log_debug "http_download_curl received HTTP status ${code}" + return 1 + fi + return 0 +} + +http_download_wget() { + local_file="${1}" + source_url="${2}" + header="${3}" + if [ -z "${header}" ]; then + wget -q -O "${local_file}" "${source_url}" || return 1 + else + wget -q --header "${header}" -O "${local_file}" "${source_url}" || return 1 + fi +} + +http_download() { + log_debug "http_download ${2}" + if is_command curl; then + http_download_curl "${@}" || return 1 + return + elif is_command wget; then + http_download_wget "${@}" || return 1 + return + fi + log_crit "http_download unable to find wget or curl" + return 1 +} + +hash_sha256() { + target="${1}" + if is_command sha256sum; then + hash="$(sha256sum "${target}")" || return 1 + printf '%s' "${hash}" | cut -d ' ' -f 1 + elif is_command shasum; then + hash="$(shasum -a 256 "${target}" 2>/dev/null)" || return 1 + printf '%s' "${hash}" | cut -d ' ' -f 1 + elif is_command sha256; then + hash="$(sha256 -q "${target}" 2>/dev/null)" || return 1 + printf '%s' "${hash}" | cut -d ' ' -f 1 + elif is_command openssl; then + hash="$(openssl dgst -sha256 "${target}")" || return 1 + printf '%s' "${hash}" | cut -d ' ' -f a + else + log_crit "hash_sha256 unable to find command to compute SHA256 hash" + return 1 + fi +} + +hash_sha256_verify() { + target="${1}" + checksums="${2}" + basename="${target##*/}" + + want="$(grep "${basename}" "${checksums}" 2>/dev/null | tr '\t' ' ' | cut -d ' ' -f 1)" + if [ -z "${want}" ]; then + log_err "hash_sha256_verify unable to find checksum for ${target} in ${checksums}" + return 1 + fi + + got="$(hash_sha256 "${target}")" + if [ "${want}" != "${got}" ]; then + log_err "hash_sha256_verify checksum for ${target} did not verify ${want} vs ${got}" + return 1 + fi +} + +untar() { + tarball="${1}" + case "${tarball}" in + *.tar.gz | *.tgz) tar -xzf "${tarball}" ;; + *.tar) tar -xf "${tarball}" ;; + *.zip) unzip -- "${tarball}" ;; + *) + log_err "untar unknown archive format for ${tarball}" + return 1 + ;; + esac +} + +is_command() { + type "${1}" >/dev/null 2>&1 +} + +log_debug() { + [ 3 -le "${LOG_LEVEL}" ] || return 0 + printf 'debug %s\n' "${*}" 1>&2 +} + +log_info() { + [ 2 -le "${LOG_LEVEL}" ] || return 0 + printf 'info %s\n' "${*}" 1>&2 +} + +log_err() { + [ 1 -le "${LOG_LEVEL}" ] || return 0 + printf 'error %s\n' "${*}" 1>&2 +} + +log_crit() { + [ 0 -le "${LOG_LEVEL}" ] || return 0 + printf 'critical %s\n' "${*}" 1>&2 +} + +main "${@}" diff --git a/internal/cmds/generate-install.sh/install.sh.tmpl b/internal/cmds/generate-install.sh/install.sh.tmpl index 17c5e9c61f6..21fd08f470b 100644 --- a/internal/cmds/generate-install.sh/install.sh.tmpl +++ b/internal/cmds/generate-install.sh/install.sh.tmpl @@ -7,7 +7,7 @@ set -e -BINDIR="${BINDIR:-./bin}" +BINDIR="${BINDIR:-{{ .BinDir }}}" CHEZMOI_USER_REPO="${CHEZMOI_USER_REPO:-twpayne/chezmoi}" TAGARG=latest LOG_LEVEL=2 diff --git a/internal/cmds/generate-install.sh/main.go b/internal/cmds/generate-install.sh/main.go index 07b21b8462d..aa2e4bf6326 100644 --- a/internal/cmds/generate-install.sh/main.go +++ b/internal/cmds/generate-install.sh/main.go @@ -12,7 +12,10 @@ import ( "gopkg.in/yaml.v3" ) -var output = flag.String("o", "", "output") +var ( + binDir = flag.String("b", "./bin", "binary directory") + output = flag.String("o", "", "output") +) type platform struct { GOOS string @@ -128,8 +131,10 @@ func run() error { defer outputFile.Close() } return installShTemplate.ExecuteTemplate(outputFile, "install.sh.tmpl", struct { + BinDir string Platforms []platform }{ + BinDir: *binDir, Platforms: sortedPlatforms, }) } diff --git a/main.go b/main.go index b6c3fb7f428..b82aeeaaece 100644 --- a/main.go +++ b/main.go @@ -5,6 +5,7 @@ //go:generate go run . completion powershell -o completions/chezmoi.ps1 //go:generate go run . completion zsh -o completions/chezmoi.zsh //go:generate go run ./internal/cmds/generate-install.sh -o assets/scripts/install.sh +//go:generate go run ./internal/cmds/generate-install.sh -b .local/bin -o assets/scripts/install-local-bin.sh package main
feat
Add get.chezmoi.io/lb and chezmoi.io/getlb install scripts
3cdffde28eb5c4d537ed68590fa3b34801188c0b
2022-06-15 14:59:30
Tom Payne
chore: Drop flaky Void Linux tests
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 90cc2edae53..e4a1ae5a03f 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -338,17 +338,6 @@ jobs: if (Test-Path -Path bin/chezmoi.exe) { Remove-Item -Force bin/chezmoi.exe } (iwr -useb https://chezmoi.io/get.ps1).ToString() | powershell -c - bin/chezmoi.exe --version - test-voidlinux: - needs: changes - if: github.event_name == 'push' || needs.changes.outputs.code == 'true' - runs-on: ubuntu-20.04 - steps: - - uses: actions/checkout@2541b1294d2704b0964813337f33b291d3f8596b - - name: test - env: - CHEZMOI_GITHUB_TOKEN: ${{ secrets.CHEZMOI_GITHUB_TOKEN }} - run: | - ( cd assets/docker && ./test.sh voidlinux ) check: runs-on: ubuntu-18.04 steps: @@ -399,7 +388,6 @@ jobs: - test-openbsd - test-ubuntu - test-ubuntu-go1-17 - - test-voidlinux - test-windows runs-on: ubuntu-20.04 steps: diff --git a/Makefile b/Makefile index ad787c33c40..a0cf3767fd1 100644 --- a/Makefile +++ b/Makefile @@ -86,7 +86,7 @@ test: .PHONY: test-docker test-docker: - ( cd assets/docker && ./test.sh alpine archlinux fedora voidlinux ) + ( cd assets/docker && ./test.sh alpine archlinux fedora ) .PHONY: test-vagrant test-vagrant:
chore
Drop flaky Void Linux tests
d2d0c25407b500289b4aaff7c2f1ec5178b4ba1f
2022-10-22 14:47:22
Lawrence Chou
docs(bitwarden): Update outdated Bitwarden CLI link
false
diff --git a/assets/chezmoi.io/docs/reference/templates/bitwarden-functions/bitwarden.md b/assets/chezmoi.io/docs/reference/templates/bitwarden-functions/bitwarden.md index f35498a55ef..a599f1b642b 100644 --- a/assets/chezmoi.io/docs/reference/templates/bitwarden-functions/bitwarden.md +++ b/assets/chezmoi.io/docs/reference/templates/bitwarden-functions/bitwarden.md @@ -2,7 +2,7 @@ `bitwarden` returns structured data retrieved from [Bitwarden](https://bitwarden.com) using the [Bitwarden -CLI](https://github.com/bitwarden/cli) (`bw`). *arg*s are passed to `bw get` +CLI](https://bitwarden.com/help/cli) (`bw`). *arg*s are passed to `bw get` unchanged and the output from `bw get` is parsed as JSON. The output from `bw get` is cached so calling `bitwarden` multiple times with the same arguments will only invoke `bw` once. diff --git a/assets/chezmoi.io/docs/reference/templates/bitwarden-functions/bitwardenFields.md b/assets/chezmoi.io/docs/reference/templates/bitwarden-functions/bitwardenFields.md index b7e3f167404..17ed8252180 100644 --- a/assets/chezmoi.io/docs/reference/templates/bitwarden-functions/bitwardenFields.md +++ b/assets/chezmoi.io/docs/reference/templates/bitwarden-functions/bitwardenFields.md @@ -2,7 +2,7 @@ `bitwardenFields` returns structured data retrieved from [Bitwarden](https://bitwarden.com) using the [Bitwarden -CLI](https://github.com/bitwarden/cli) (`bw`). *arg*s are passed to `bw get` +CLI](https://bitwarden.com/help/cli) (`bw`). *arg*s are passed to `bw get` unchanged, the output from `bw get` is parsed as JSON, and elements of `fields` are returned as a map indexed by each field's `name`. diff --git a/assets/chezmoi.io/docs/user-guide/password-managers/bitwarden.md b/assets/chezmoi.io/docs/user-guide/password-managers/bitwarden.md index d2c1815079e..8b045f5bffb 100644 --- a/assets/chezmoi.io/docs/user-guide/password-managers/bitwarden.md +++ b/assets/chezmoi.io/docs/user-guide/password-managers/bitwarden.md @@ -1,7 +1,7 @@ # Bitwarden chezmoi includes support for [Bitwarden](https://bitwarden.com/) using the -[Bitwarden CLI](https://github.com/bitwarden/cli) to expose data as a template +[Bitwarden CLI](https://bitwarden.com/help/cli) to expose data as a template function. Log in to Bitwarden using:
docs
Update outdated Bitwarden CLI link
08e8ebde5d5b37252bd187c64afc84fe16b60c1d
2023-05-11 20:00:01
dependabot[bot]
chore(deps): bump reviewdog/action-misspell from 1.12.3 to 1.12.4
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index c13cddab1b8..f1971e4de5c 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -55,7 +55,7 @@ jobs: runs-on: ubuntu-22.04 steps: - uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab - - uses: reviewdog/action-misspell@fe8d5c98c3761ef40755a7bb95460b2a33f6b346 + - uses: reviewdog/action-misspell@ccb0441a34ac2a3ece1206c63d7b6dd757ffde4d with: locale: US test-alpine:
chore
bump reviewdog/action-misspell from 1.12.3 to 1.12.4
cfc900a941638ad5d93765ed205e54da2863d4c1
2024-03-01 08:16:05
dependabot[bot]
chore(deps): bump mkdocs-material from 9.5.6 to 9.5.12 in /assets
false
diff --git a/assets/chezmoi.io/requirements.txt b/assets/chezmoi.io/requirements.txt index 6c3cbcaa068..b2e3d9d2c80 100644 --- a/assets/chezmoi.io/requirements.txt +++ b/assets/chezmoi.io/requirements.txt @@ -1,3 +1,3 @@ mkdocs==1.5.3 -mkdocs-material==9.5.6 +mkdocs-material==9.5.12 mkdocs-mermaid2-plugin==1.1.1
chore
bump mkdocs-material from 9.5.6 to 9.5.12 in /assets
94e91c28cf35d20eb5b998c6b6e52ead366a9d19
2022-02-03 06:57:24
Tom Payne
docs: Add and update article links
false
diff --git a/assets/chezmoi.io/docs/links/articles-podcasts-and-videos.md b/assets/chezmoi.io/docs/links/articles-podcasts-and-videos.md index bf497f70c80..76e975c0c27 100644 --- a/assets/chezmoi.io/docs/links/articles-podcasts-and-videos.md +++ b/assets/chezmoi.io/docs/links/articles-podcasts-and-videos.md @@ -20,8 +20,10 @@ | 2022-01-12 | 2.9.5 | Text (IT) | [Come funzionano i miei Mac](https://correntedebole.com/come-funzionano-i-miei-mac/) | | 2021-12-23 | 2.9.3 | Text | [Use Chezmoi to guarantee idempotency of terminal](https://www.wazaterm.com/blog/advent-calendar-2021/use-chezmoi-to-guarantee-idempotency-of-terminal) | | 2021-12-20 | 2.9.3 | Text | [How chezmoi Implements Cross-Platform CI](https://gopheradvent.com/calendar/2021/how-chezmoi-implements-cross-platform-ci/) | +| 2021-12-13 | 2.9.3 | Text | [Managing Dotfiles With Chezmoi](https://budimanjojo.com/2021/12/13/managing-dotfiles-with-chezmoi/) | | 2021-12-08 | 2.9.3 | Video | [How Go makes chezmoi possible](https://www.youtube.com/watch?v=5XiewS8ZbH8&t=1044s) | | 2021-12-04 | 2.9.2 | Text | [Advanced features of Chezmoi](https://zerokspot.com/weblog/2021/12/04/advanced-chezmoi/) | +| 2021-12-01 | 2.9.1 | Text | [Chezmoi 2](https://johnmathews.is/chezmoi-2.html) | | 2021-11-27 | 2.8.0 | Video (TH) | [Command ไร 2021-11-27 : ย้าย dotfiles ไป chezmoi](https://www.youtube.com/watch?v=8ybNfCfnF2Y) | | 2021-11-26 | 2.8.0 | Text | [Weekly Journal 47 - chezmoi, neovim](https://scottbanwart.com/blog/2021/11/weekly-journal-47-chezmoi-neovim/) | | 2021-11-23 | 2.8.0 | Text | [chezmoi dotfile management](https://www.jacobbolda.com/chezmoi-dotfile-management) | @@ -40,7 +42,6 @@ | 2021-05-14 | 2.0.12 | Text | [A brief history of my dotfile management](https://jonathanbartlett.co.uk/2021/05/14/a-brief-history-of-my-dotfiles.html) | | 2021-05-12 | 2.0.12 | Text | [My Dotfiles Story: A Journey to Chezmoi](https://www.mikekasberg.com/blog/2021/05/12/my-dotfiles-story.html) | | 2021-05-10 | 2.0.11 | Text | [Development Environment (2021)](https://ideas.offby1.net/posts/development-environment-2021.html) | -| 2021-04-20 | 2.0.9 | Text | [ChezMoi](https://johnmathews.eu/chezmoi.html) | | 2021-04-08 | 2.0.9 | Text (FR) | [Bienvenue chez moi](https://blogduyax.madyanne.fr/2021/bienvenue-chez-moi/) | | 2021-04-01 | 2.0.7 | Text | [ChezMoi](https://johnmathews.is/chezmoi.html) | | 2021-02-17 | 1.8.11 | Text (JP) | [chezmoi で dotfiles を手軽に柔軟にセキュアに管理する](https://zenn.dev/ryo_kawamata/articles/introduce-chezmoi) | @@ -49,7 +50,7 @@ | 2021-01-29 | 1.8.10 | Text (CN) | [[归档] 用 Chezmoi 管理配置文件](https://axionl.me/p/%E5%BD%92%E6%A1%A3-%E7%94%A8-chezmoi-%E7%AE%A1%E7%90%86%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6/) | | 2021-01-12 | 1.8.10 | Text | [Automating the Setup of a New Mac With All Your Apps, Preferences, and Development Tools](https://www.moncefbelyamani.com/automating-the-setup-of-a-new-mac-with-all-your-apps-preferences-and-development-tools/) | | 2020-11-06 | 1.8.8 | Text | [Chezmoi – Securely Manage dotfiles across multiple machines](https://computingforgeeks.com/chezmoi-manage-dotfiles-across-multiple-machines/) | -| 2020-11-05 | 1.8.8 | Text | [Using chezmoi to manage dotfiles](https://pashinskikh.de/posts/chezmoi/) | +| 2020-11-05 | 1.8.8 | Text | [Using chezmoi to manage dotfiles](https://pashinskikh.com/posts/chezmoi/) | | 2020-10-05 | 1.8.6 | Text | [Dotfiles with Chezmoi](https://blog.lazkani.io/posts/backup/dotfiles-with-chezmoi/) | | 2020-10-03 | 1.8.6 | Text | [Chezmoi Merging](https://benoit.srht.site/2020-10-03-chezmoi-merging/) | | 2020-08-13 | 1.8.3 | Text | [Using BitWarden and Chezmoi to manage SSH keys](https://www.jx0.uk/chezmoi/bitwarden/unix/ssh/2020/08/13/bitwarden-chezmoi-ssh-key.html) |
docs
Add and update article links
5f8e79614b1765ae43adde996a78bc8cc645be1b
2025-03-13 22:05:08
Oleksandr Redko
chore: Remove typecheck linter
false
diff --git a/.golangci.yml b/.golangci.yml index ced4d027fb9..565bfb75a7c 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -69,7 +69,6 @@ linters: - testableexamples - testifylint - thelper - - typecheck - unconvert - unparam - unused
chore
Remove typecheck linter
bcb4520589afe9dad7a8238b667e4e8c07edd158
2021-11-07 22:34:07
Tom Payne
chore: Mock expensive invocation of ioreg in tests
false
diff --git a/internal/cmd/testdata/scripts/templatefuncs.txt b/internal/cmd/testdata/scripts/templatefuncs.txt index c4d9f234b70..471c382d0b1 100644 --- a/internal/cmd/testdata/scripts/templatefuncs.txt +++ b/internal/cmd/testdata/scripts/templatefuncs.txt @@ -1,5 +1,6 @@ [!windows] chmod 755 bin/chezmoi-output-test [!windows] chmod 755 bin/generate-color-formats +[!windows] chmod 755 bin/ioreg [windows] unix2dos bin/chezmoi-output-test.cmd # test ioreg template function @@ -100,6 +101,17 @@ EOF echo "Usage: $0 <hex-color>" ;; esac +-- bin/ioreg -- +#!/bin/sh + +echo '<?xml version="1.0" encoding="UTF-8"?>' +echo '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">' +echo '<plist version="1.0">' +echo '<dict>' +echo ' <key>IOKitBuildVersion</key>' +echo ' <string>Darwin Kernel Version 21.1.0: Wed Oct 13 17:33:24 PDT 2021; root:xnu-8019.41.5~1/RELEASE_ARM64_T8101</string>' +echo '</dict>' +echo '</plist>' -- golden/expected -- 255 -- golden/include-abspath --
chore
Mock expensive invocation of ioreg in tests
a8dda7867215a31251f33acbc96ed57e10ebd80f
2024-10-26 23:44:50
Ruslan Sayfutdinov
fix: Fix completion for 'archive --format'
false
diff --git a/internal/chezmoi/archive.go b/internal/chezmoi/archive.go index 83b549c7155..e140a692e9b 100644 --- a/internal/chezmoi/archive.go +++ b/internal/chezmoi/archive.go @@ -38,6 +38,18 @@ const ( ArchiveFormatZip ArchiveFormat = "zip" ) +var ArchiveFormatFlagCompletionFunc = FlagCompletionFunc([]string{ + ArchiveFormatTar.String(), + ArchiveFormatTarBz2.String(), + ArchiveFormatTarGz.String(), + ArchiveFormatTarXz.String(), + ArchiveFormatTarZst.String(), + ArchiveFormatTbz2.String(), + ArchiveFormatTgz.String(), + ArchiveFormatTxz.String(), + ArchiveFormatZip.String(), +}) + type UnknownArchiveFormatError string func (e UnknownArchiveFormatError) Error() string { diff --git a/internal/cmd/archivecmd.go b/internal/cmd/archivecmd.go index 6d7421532d0..a31367c69c4 100644 --- a/internal/cmd/archivecmd.go +++ b/internal/cmd/archivecmd.go @@ -44,6 +44,10 @@ func (c *Config) newArchiveCmd() *cobra.Command { archiveCmd.Flags().BoolVarP(&c.archive.parentDirs, "parent-dirs", "P", c.archive.parentDirs, "Archive parent directories") archiveCmd.Flags().BoolVarP(&c.archive.recursive, "recursive", "r", c.archive.recursive, "Recurse into subdirectories") + if err := archiveCmd.RegisterFlagCompletionFunc("format", chezmoi.ArchiveFormatFlagCompletionFunc); err != nil { + panic(err) + } + return archiveCmd } diff --git a/internal/cmd/config.go b/internal/cmd/config.go index a34f7cc0e4f..6dcc0b913dc 100644 --- a/internal/cmd/config.go +++ b/internal/cmd/config.go @@ -312,10 +312,11 @@ var ( whitespaceRx = regexp.MustCompile(`\s+`) commonFlagCompletionFuncs = map[string]func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective){ - "exclude": chezmoi.EntryTypeSetFlagCompletionFunc, - "format": writeDataFormatFlagCompletionFunc, - "include": chezmoi.EntryTypeSetFlagCompletionFunc, - "secrets": severityFlagCompletionFunc, + "exclude": chezmoi.EntryTypeSetFlagCompletionFunc, + "format": writeDataFormatFlagCompletionFunc, + "include": chezmoi.EntryTypeSetFlagCompletionFunc, + "path-style": chezmoi.PathStyleFlagCompletionFunc, + "secrets": severityFlagCompletionFunc, } ) @@ -2986,6 +2987,9 @@ func prependParentRelPaths(relPaths []chezmoi.RelPath) []chezmoi.RelPath { // common flags, recursively. It panics on any error. func registerCommonFlagCompletionFuncs(cmd *cobra.Command) { cmd.Flags().VisitAll(func(flag *pflag.Flag) { + if _, exist := cmd.GetFlagCompletionFunc(flag.Name); exist { + return + } if flagCompletionFunc, ok := commonFlagCompletionFuncs[flag.Name]; ok { if err := cmd.RegisterFlagCompletionFunc(flag.Name, flagCompletionFunc); err != nil { panic(err) diff --git a/internal/cmd/managedcmd.go b/internal/cmd/managedcmd.go index 0122c8d0365..51059b641ca 100644 --- a/internal/cmd/managedcmd.go +++ b/internal/cmd/managedcmd.go @@ -33,10 +33,6 @@ func (c *Config) newManagedCmd() *cobra.Command { managedCmd.Flags().VarP(&c.managed.pathStyle, "path-style", "p", "Path style") managedCmd.Flags().BoolVarP(&c.managed.tree, "tree", "t", c.managed.tree, "Print paths as a tree") - if err := managedCmd.RegisterFlagCompletionFunc("path-style", chezmoi.PathStyleFlagCompletionFunc); err != nil { - panic(err) - } - return managedCmd } diff --git a/internal/cmd/statuscmd.go b/internal/cmd/statuscmd.go index e15e58e71c0..84363f5c3d5 100644 --- a/internal/cmd/statuscmd.go +++ b/internal/cmd/statuscmd.go @@ -45,10 +45,6 @@ func (c *Config) newStatusCmd() *cobra.Command { BoolVarP(&c.Status.parentDirs, "parent-dirs", "P", c.Status.parentDirs, "Show status of all parent directories") statusCmd.Flags().BoolVarP(&c.Status.recursive, "recursive", "r", c.Status.recursive, "Recurse into subdirectories") - if err := statusCmd.RegisterFlagCompletionFunc("path-style", chezmoi.PathStyleFlagCompletionFunc); err != nil { - panic(err) - } - return statusCmd } diff --git a/internal/cmd/testdata/scripts/completion.txtar b/internal/cmd/testdata/scripts/completion.txtar index 2e94c0d63ef..0d94296081b 100644 --- a/internal/cmd/testdata/scripts/completion.txtar +++ b/internal/cmd/testdata/scripts/completion.txtar @@ -42,14 +42,41 @@ cmp stdout golden/path-style exec chezmoi __complete unmanaged --path-style '' cmp stdout golden/unmanaged-path-style -# test that write --format values are completed +# test that "state data --format" values are completed +exec chezmoi __complete state data --format '' +cmp stdout golden/output-format + +# test that "state dump --format" values are completed exec chezmoi __complete state dump --format '' -cmp stdout golden/write-data +cmp stdout golden/output-format -# test that write --format values are completed +# test that "data --format" values are completed exec chezmoi __complete data --format '' -cmp stdout golden/write-data +cmp stdout golden/output-format + +# test that "dump --format" values are completed +exec chezmoi __complete dump --format '' +cmp stdout golden/output-format + +# test that "dump-config --format" values are completed +exec chezmoi __complete dump-config --format '' +cmp stdout golden/output-format +# test that "archive --format" values are completed +exec chezmoi __complete archive --format '' +cmp stdout golden/archive-format + +-- golden/archive-format -- +tar +tar.bz2 +tar.gz +tar.xz +tar.zst +tbz2 +tgz +txz +zip +:4 -- golden/auto-bool-t -- t true @@ -80,6 +107,10 @@ templates file symlink :4 +-- golden/output-format -- +json +yaml +:4 -- golden/path-style -- absolute relative @@ -95,7 +126,3 @@ relative --use-builtin-diff Use builtin diff --use-builtin-git Use builtin git :4 --- golden/write-data -- -json -yaml -:4
fix
Fix completion for 'archive --format'
0cd223b2fad4833c977ec5f0b8a2e726f57f3afb
2024-07-15 04:03:24
Tom Payne
chore: Rename variables to satisfy spell checker
false
diff --git a/internal/chezmoi/chezmoi_windows.go b/internal/chezmoi/chezmoi_windows.go index 39d4dac7b22..f196e3fc9c7 100644 --- a/internal/chezmoi/chezmoi_windows.go +++ b/internal/chezmoi/chezmoi_windows.go @@ -56,12 +56,12 @@ func UserHomeDir() (string, error) { } // isPrivate returns false on Windows. -func isPrivate(fileInfo fs.FileInfo) bool { +func isPrivate(_ fs.FileInfo) bool { return false } // isReadOnly returns false on Windows. -func isReadOnly(fileInfo fs.FileInfo) bool { +func isReadOnly(_ fs.FileInfo) bool { return false } diff --git a/internal/chezmoi/debugsystem.go b/internal/chezmoi/debugsystem.go index edc03d5b41e..ab540ab47f0 100644 --- a/internal/chezmoi/debugsystem.go +++ b/internal/chezmoi/debugsystem.go @@ -57,11 +57,11 @@ func (s *DebugSystem) Glob(name string) ([]string, error) { } // Link implements System.Link. -func (s *DebugSystem) Link(oldpath, newpath AbsPath) error { - err := s.system.Link(oldpath, newpath) +func (s *DebugSystem) Link(oldPath, newPath AbsPath) error { + err := s.system.Link(oldPath, newPath) chezmoilog.InfoOrError(s.logger, "Link", err, - chezmoilog.Stringer("oldpath", oldpath), - chezmoilog.Stringer("newpath", newpath), + chezmoilog.Stringer("oldPath", oldPath), + chezmoilog.Stringer("newPath", newPath), ) return err } @@ -138,11 +138,11 @@ func (s *DebugSystem) RemoveAll(name AbsPath) error { } // Rename implements System.Rename. -func (s *DebugSystem) Rename(oldpath, newpath AbsPath) error { - err := s.system.Rename(oldpath, newpath) +func (s *DebugSystem) Rename(oldPath, newPath AbsPath) error { + err := s.system.Rename(oldPath, newPath) chezmoilog.InfoOrError(s.logger, "RemoveAll", err, - chezmoilog.Stringer("oldpath", oldpath), - chezmoilog.Stringer("newpath", newpath), + chezmoilog.Stringer("oldPath", oldPath), + chezmoilog.Stringer("newPath", newPath), ) return err } @@ -161,10 +161,10 @@ func (s *DebugSystem) RunCmd(cmd *exec.Cmd) error { } // RunScript implements System.RunScript. -func (s *DebugSystem) RunScript(scriptname RelPath, dir AbsPath, data []byte, options RunScriptOptions) error { - err := s.system.RunScript(scriptname, dir, data, options) +func (s *DebugSystem) RunScript(scriptName RelPath, dir AbsPath, data []byte, options RunScriptOptions) error { + err := s.system.RunScript(scriptName, dir, data, options) attrs := []slog.Attr{ - chezmoilog.Stringer("scriptname", scriptname), + chezmoilog.Stringer("scriptName", scriptName), chezmoilog.Stringer("dir", dir), chezmoilog.FirstFewBytes("data", data), slog.Any("interpreter", options.Interpreter), @@ -202,11 +202,11 @@ func (s *DebugSystem) WriteFile(name AbsPath, data []byte, perm fs.FileMode) err } // WriteSymlink implements System.WriteSymlink. -func (s *DebugSystem) WriteSymlink(oldname string, newname AbsPath) error { - err := s.system.WriteSymlink(oldname, newname) +func (s *DebugSystem) WriteSymlink(oldName string, newName AbsPath) error { + err := s.system.WriteSymlink(oldName, newName) chezmoilog.InfoOrError(s.logger, "WriteSymlink", err, - slog.String("oldname", oldname), - chezmoilog.Stringer("newname", newname), + slog.String("oldName", oldName), + chezmoilog.Stringer("newName", newName), ) return err } diff --git a/internal/chezmoi/dryrunsystem.go b/internal/chezmoi/dryrunsystem.go index 97fbbad9cff..c4151353a71 100644 --- a/internal/chezmoi/dryrunsystem.go +++ b/internal/chezmoi/dryrunsystem.go @@ -40,7 +40,7 @@ func (s *DryRunSystem) Glob(pattern string) ([]string, error) { } // Link implements System.Link. -func (s *DryRunSystem) Link(oldname, newname AbsPath) error { +func (s *DryRunSystem) Link(oldName, newName AbsPath) error { s.setModified() return nil } @@ -95,7 +95,7 @@ func (s *DryRunSystem) RemoveAll(AbsPath) error { } // Rename implements System.Rename. -func (s *DryRunSystem) Rename(oldpath, newpath AbsPath) error { +func (s *DryRunSystem) Rename(oldPath, newPath AbsPath) error { s.setModified() return nil } @@ -107,7 +107,7 @@ func (s *DryRunSystem) RunCmd(cmd *exec.Cmd) error { } // RunScript implements System.RunScript. -func (s *DryRunSystem) RunScript(scriptname RelPath, dir AbsPath, data []byte, options RunScriptOptions) error { +func (s *DryRunSystem) RunScript(scriptName RelPath, dir AbsPath, data []byte, options RunScriptOptions) error { s.setModified() return nil } diff --git a/internal/chezmoi/dumpsystem.go b/internal/chezmoi/dumpsystem.go index 001bd4b13b3..e793103e1d4 100644 --- a/internal/chezmoi/dumpsystem.go +++ b/internal/chezmoi/dumpsystem.go @@ -98,11 +98,11 @@ func (s *DumpSystem) RunCmd(cmd *exec.Cmd) error { } // RunScript implements System.RunScript. -func (s *DumpSystem) RunScript(scriptname RelPath, dir AbsPath, data []byte, options RunScriptOptions) error { - scriptnameStr := scriptname.String() +func (s *DumpSystem) RunScript(scriptName RelPath, dir AbsPath, data []byte, options RunScriptOptions) error { + scriptNameStr := scriptName.String() scriptData := &scriptData{ Type: dataTypeScript, - Name: NewAbsPath(scriptnameStr), + Name: NewAbsPath(scriptNameStr), Contents: string(data), } if options.Condition != ScriptConditionNone { @@ -111,7 +111,7 @@ func (s *DumpSystem) RunScript(scriptname RelPath, dir AbsPath, data []byte, opt if !options.Interpreter.None() { scriptData.Interpreter = options.Interpreter } - return s.setData(scriptnameStr, scriptData) + return s.setData(scriptNameStr, scriptData) } // UnderlyingFS implements System.UnderlyingFS. @@ -130,11 +130,11 @@ func (s *DumpSystem) WriteFile(filename AbsPath, data []byte, perm fs.FileMode) } // WriteSymlink implements System.WriteSymlink. -func (s *DumpSystem) WriteSymlink(oldname string, newname AbsPath) error { - return s.setData(newname.String(), &symlinkData{ +func (s *DumpSystem) WriteSymlink(oldName string, newName AbsPath) error { + return s.setData(newName.String(), &symlinkData{ Type: dataTypeSymlink, - Name: newname, - Linkname: oldname, + Name: newName, + Linkname: oldName, }) } diff --git a/internal/chezmoi/erroronwritesystem.go b/internal/chezmoi/erroronwritesystem.go index 9a9528803e8..bd4562bdb89 100644 --- a/internal/chezmoi/erroronwritesystem.go +++ b/internal/chezmoi/erroronwritesystem.go @@ -40,7 +40,7 @@ func (s *ErrorOnWriteSystem) Glob(pattern string) ([]string, error) { } // Link implements System.Link. -func (s *ErrorOnWriteSystem) Link(oldname, newname AbsPath) error { +func (s *ErrorOnWriteSystem) Link(oldName, newName AbsPath) error { return s.err } @@ -85,7 +85,7 @@ func (s *ErrorOnWriteSystem) RemoveAll(AbsPath) error { } // Rename implements System.Rename. -func (s *ErrorOnWriteSystem) Rename(oldpath, newpath AbsPath) error { +func (s *ErrorOnWriteSystem) Rename(oldPath, newPath AbsPath) error { return s.err } @@ -95,7 +95,7 @@ func (s *ErrorOnWriteSystem) RunCmd(cmd *exec.Cmd) error { } // RunScript implements System.RunScript. -func (s *ErrorOnWriteSystem) RunScript(scriptname RelPath, dir AbsPath, data []byte, options RunScriptOptions) error { +func (s *ErrorOnWriteSystem) RunScript(scriptName RelPath, dir AbsPath, data []byte, options RunScriptOptions) error { return s.err } diff --git a/internal/chezmoi/externaldiffsystem.go b/internal/chezmoi/externaldiffsystem.go index bc6123e583a..5a3b96415e2 100644 --- a/internal/chezmoi/externaldiffsystem.go +++ b/internal/chezmoi/externaldiffsystem.go @@ -83,9 +83,9 @@ func (s *ExternalDiffSystem) Glob(pattern string) ([]string, error) { } // Link implements System.Link. -func (s *ExternalDiffSystem) Link(oldname, newname AbsPath) error { +func (s *ExternalDiffSystem) Link(oldName, newName AbsPath) error { // FIXME generate suitable inputs for s.command - return s.system.Link(oldname, newname) + return s.system.Link(oldName, newName) } // Lstat implements System.Lstat. @@ -170,9 +170,9 @@ func (s *ExternalDiffSystem) RemoveAll(name AbsPath) error { } // Rename implements System.Rename. -func (s *ExternalDiffSystem) Rename(oldpath, newpath AbsPath) error { +func (s *ExternalDiffSystem) Rename(oldPath, newPath AbsPath) error { // FIXME generate suitable inputs for s.command - return s.system.Rename(oldpath, newpath) + return s.system.Rename(oldPath, newPath) } // RunCmd implements System.RunCmd. @@ -181,7 +181,7 @@ func (s *ExternalDiffSystem) RunCmd(cmd *exec.Cmd) error { } // RunScript implements System.RunScript. -func (s *ExternalDiffSystem) RunScript(scriptname RelPath, dir AbsPath, data []byte, options RunScriptOptions) error { +func (s *ExternalDiffSystem) RunScript(scriptName RelPath, dir AbsPath, data []byte, options RunScriptOptions) error { bits := EntryTypeScripts if options.Condition == ScriptConditionAlways { bits |= EntryTypeAlways @@ -191,7 +191,7 @@ func (s *ExternalDiffSystem) RunScript(scriptname RelPath, dir AbsPath, data []b if err != nil { return err } - targetAbsPath := tempDirAbsPath.Join(scriptname) + targetAbsPath := tempDirAbsPath.Join(scriptName) if err := os.MkdirAll(targetAbsPath.Dir().String(), 0o700); err != nil { return err } @@ -206,7 +206,7 @@ func (s *ExternalDiffSystem) RunScript(scriptname RelPath, dir AbsPath, data []b return err } } - return s.system.RunScript(scriptname, dir, data, options) + return s.system.RunScript(scriptName, dir, data, options) } // Stat implements System.Stat. @@ -257,9 +257,9 @@ func (s *ExternalDiffSystem) WriteFile(filename AbsPath, data []byte, perm fs.Fi } // WriteSymlink implements System.WriteSymlink. -func (s *ExternalDiffSystem) WriteSymlink(oldname string, newname AbsPath) error { +func (s *ExternalDiffSystem) WriteSymlink(oldName string, newName AbsPath) error { // FIXME generate suitable inputs for s.command - return s.system.WriteSymlink(oldname, newname) + return s.system.WriteSymlink(oldName, newName) } // tempDir creates a temporary directory for s if it does not already exist and diff --git a/internal/chezmoi/gitdiffsystem.go b/internal/chezmoi/gitdiffsystem.go index 075c2fe6c43..7189ac80e93 100644 --- a/internal/chezmoi/gitdiffsystem.go +++ b/internal/chezmoi/gitdiffsystem.go @@ -90,9 +90,9 @@ func (s *GitDiffSystem) Glob(pattern string) ([]string, error) { } // Link implements System.Link. -func (s *GitDiffSystem) Link(oldname, newname AbsPath) error { +func (s *GitDiffSystem) Link(oldName, newName AbsPath) error { // LATER generate a diff - return s.system.Link(oldname, newname) + return s.system.Link(oldName, newName) } // Lstat implements System.Lstat. @@ -149,8 +149,8 @@ func (s *GitDiffSystem) RemoveAll(name AbsPath) error { } // Rename implements System.Rename. -func (s *GitDiffSystem) Rename(oldpath, newpath AbsPath) error { - fromFileInfo, err := s.Stat(oldpath) +func (s *GitDiffSystem) Rename(oldPath, newPath AbsPath) error { + fromFileInfo, err := s.Stat(oldPath) if err != nil { return err } @@ -161,7 +161,7 @@ func (s *GitDiffSystem) Rename(oldpath, newpath AbsPath) error { case fromFileInfo.Mode().IsDir(): hash = plumbing.ZeroHash // LATER be more intelligent here case fromFileInfo.Mode().IsRegular(): - data, err := s.system.ReadFile(oldpath) + data, err := s.system.ReadFile(oldPath) if err != nil { return err } @@ -169,7 +169,7 @@ func (s *GitDiffSystem) Rename(oldpath, newpath AbsPath) error { default: fileMode = filemode.FileMode(fromFileInfo.Mode()) } - fromPath, toPath := s.trimPrefix(oldpath), s.trimPrefix(newpath) + fromPath, toPath := s.trimPrefix(oldPath), s.trimPrefix(newPath) if s.reverse { fromPath, toPath = toPath, fromPath } @@ -192,7 +192,7 @@ func (s *GitDiffSystem) Rename(oldpath, newpath AbsPath) error { return err } } - return s.system.Rename(oldpath, newpath) + return s.system.Rename(oldPath, newPath) } // RunCmd implements System.RunCmd. @@ -201,7 +201,7 @@ func (s *GitDiffSystem) RunCmd(cmd *exec.Cmd) error { } // RunScript implements System.RunScript. -func (s *GitDiffSystem) RunScript(scriptname RelPath, dir AbsPath, data []byte, options RunScriptOptions) error { +func (s *GitDiffSystem) RunScript(scriptName RelPath, dir AbsPath, data []byte, options RunScriptOptions) error { bits := EntryTypeScripts if options.Condition == ScriptConditionAlways { bits |= EntryTypeAlways @@ -216,7 +216,7 @@ func (s *GitDiffSystem) RunScript(scriptname RelPath, dir AbsPath, data []byte, fromData, toData = toData, fromData fromMode, toMode = toMode, fromMode } - diffPatch, err := DiffPatch(scriptname, fromData, fromMode, toData, toMode) + diffPatch, err := DiffPatch(scriptName, fromData, fromMode, toData, toMode) if err != nil { return err } @@ -224,7 +224,7 @@ func (s *GitDiffSystem) RunScript(scriptname RelPath, dir AbsPath, data []byte, return err } } - return s.system.RunScript(scriptname, dir, data, options) + return s.system.RunScript(scriptName, dir, data, options) } // Stat implements System.Stat. @@ -248,18 +248,18 @@ func (s *GitDiffSystem) WriteFile(filename AbsPath, data []byte, perm fs.FileMod } // WriteSymlink implements System.WriteSymlink. -func (s *GitDiffSystem) WriteSymlink(oldname string, newname AbsPath) error { +func (s *GitDiffSystem) WriteSymlink(oldName string, newName AbsPath) error { if s.filter.IncludeEntryTypeBits(EntryTypeSymlinks) { - toData := append([]byte(normalizeLinkname(oldname)), '\n') + toData := append([]byte(normalizeLinkname(oldName)), '\n') toMode := fs.ModeSymlink if runtime.GOOS == "windows" { toMode |= 0o666 } - if err := s.encodeDiff(newname, toData, toMode); err != nil { + if err := s.encodeDiff(newName, toData, toMode); err != nil { return err } } - return s.system.WriteSymlink(oldname, newname) + return s.system.WriteSymlink(oldName, newName) } // encodeDiff encodes the diff between the actual state of absPath and the diff --git a/internal/chezmoi/realsystem.go b/internal/chezmoi/realsystem.go index 7d6969b4747..11e8b41b298 100644 --- a/internal/chezmoi/realsystem.go +++ b/internal/chezmoi/realsystem.go @@ -30,8 +30,8 @@ func (s *RealSystem) Glob(pattern string) ([]string, error) { } // Link implements System.Link. -func (s *RealSystem) Link(oldname, newname AbsPath) error { - return s.fileSystem.Link(oldname.String(), newname.String()) +func (s *RealSystem) Link(oldName, newName AbsPath) error { + return s.fileSystem.Link(oldName.String(), newName.String()) } // Lstat implements System.Lstat. @@ -74,8 +74,8 @@ func (s *RealSystem) RemoveAll(name AbsPath) error { } // Rename implements System.Rename. -func (s *RealSystem) Rename(oldpath, newpath AbsPath) error { - return s.fileSystem.Rename(oldpath.String(), newpath.String()) +func (s *RealSystem) Rename(oldPath, newPath AbsPath) error { + return s.fileSystem.Rename(oldPath.String(), newPath.String()) } // RunCmd implements System.RunCmd. @@ -84,7 +84,7 @@ func (s *RealSystem) RunCmd(cmd *exec.Cmd) error { } // RunScript implements System.RunScript. -func (s *RealSystem) RunScript(scriptname RelPath, dir AbsPath, data []byte, options RunScriptOptions) (err error) { +func (s *RealSystem) RunScript(scriptName RelPath, dir AbsPath, data []byte, options RunScriptOptions) (err error) { // Create the script temporary directory, if needed. s.createScriptTempDirOnce.Do(func() { if !s.scriptTempDir.Empty() { @@ -98,7 +98,7 @@ func (s *RealSystem) RunScript(scriptname RelPath, dir AbsPath, data []byte, opt // Write the temporary script file. Put the randomness at the front of the // filename to preserve any file extension for Windows scripts. var f *os.File - f, err = os.CreateTemp(s.scriptTempDir.String(), "*."+scriptname.Base()) + f, err = os.CreateTemp(s.scriptTempDir.String(), "*."+scriptName.Base()) if err != nil { return } diff --git a/internal/chezmoi/realsystem_unix.go b/internal/chezmoi/realsystem_unix.go index d8cf4805e4e..8527fa9ae64 100644 --- a/internal/chezmoi/realsystem_unix.go +++ b/internal/chezmoi/realsystem_unix.go @@ -108,16 +108,16 @@ func (s *RealSystem) WriteFile(filename AbsPath, data []byte, perm fs.FileMode) } // WriteSymlink implements System.WriteSymlink. -func (s *RealSystem) WriteSymlink(oldname string, newname AbsPath) error { +func (s *RealSystem) WriteSymlink(oldName string, newName AbsPath) error { // Special case: if writing to the real filesystem in safe mode, use // github.com/google/renameio. if s.safe && s.fileSystem == vfs.OSFS { - return renameio.Symlink(oldname, newname.String()) + return renameio.Symlink(oldName, newName.String()) } - if err := s.fileSystem.RemoveAll(newname.String()); err != nil && !errors.Is(err, fs.ErrNotExist) { + if err := s.fileSystem.RemoveAll(newName.String()); err != nil && !errors.Is(err, fs.ErrNotExist) { return err } - return s.fileSystem.Symlink(oldname, newname.String()) + return s.fileSystem.Symlink(oldName, newName.String()) } // writeFile is like os.WriteFile but always sets perm before writing data. diff --git a/internal/chezmoi/realsystem_windows.go b/internal/chezmoi/realsystem_windows.go index 844c1947df1..dff144edeb5 100644 --- a/internal/chezmoi/realsystem_windows.go +++ b/internal/chezmoi/realsystem_windows.go @@ -60,9 +60,9 @@ func (s *RealSystem) WriteFile(filename AbsPath, data []byte, perm fs.FileMode) } // WriteSymlink implements System.WriteSymlink. -func (s *RealSystem) WriteSymlink(oldname string, newname AbsPath) error { - if err := s.fileSystem.RemoveAll(newname.String()); err != nil && !errors.Is(err, fs.ErrNotExist) { +func (s *RealSystem) WriteSymlink(oldName string, newName AbsPath) error { + if err := s.fileSystem.RemoveAll(newName.String()); err != nil && !errors.Is(err, fs.ErrNotExist) { return err } - return s.fileSystem.Symlink(filepath.FromSlash(oldname), newname.String()) + return s.fileSystem.Symlink(filepath.FromSlash(oldName), newName.String()) } diff --git a/internal/chezmoi/sourcestate.go b/internal/chezmoi/sourcestate.go index 9a72d2d17eb..083737f9991 100644 --- a/internal/chezmoi/sourcestate.go +++ b/internal/chezmoi/sourcestate.go @@ -1945,7 +1945,7 @@ func (s *SourceState) newModifyTargetStateEntryFunc( // newRemoveTargetStateEntryFunc returns a targetStateEntryFunc that removes a // target. -func (s *SourceState) newRemoveTargetStateEntryFunc(sourceRelPath SourceRelPath, fileAttr FileAttr) targetStateEntryFunc { +func (s *SourceState) newRemoveTargetStateEntryFunc() targetStateEntryFunc { return func(destSystem System, destAbsPath AbsPath) (TargetStateEntry, error) { return &TargetStateRemove{}, nil } @@ -2064,7 +2064,7 @@ func (s *SourceState) newSourceStateFile( targetStateEntryFunc = s.newModifyTargetStateEntryFunc(sourceRelPath, fileAttr, sourceLazyContents, nil) } case SourceFileTypeRemove: - targetStateEntryFunc = s.newRemoveTargetStateEntryFunc(sourceRelPath, fileAttr) + targetStateEntryFunc = s.newRemoveTargetStateEntryFunc() case SourceFileTypeScript: // If the script has an extension, determine if it indicates an // interpreter to use. diff --git a/internal/chezmoi/system.go b/internal/chezmoi/system.go index 31547db8ced..c01aa5c998c 100644 --- a/internal/chezmoi/system.go +++ b/internal/chezmoi/system.go @@ -25,7 +25,7 @@ type System interface { //nolint:interfacebloat Chmod(name AbsPath, mode fs.FileMode) error Chtimes(name AbsPath, atime, mtime time.Time) error Glob(pattern string) ([]string, error) - Link(oldname, newname AbsPath) error + Link(oldName, newName AbsPath) error Lstat(filename AbsPath) (fs.FileInfo, error) Mkdir(name AbsPath, perm fs.FileMode) error RawPath(absPath AbsPath) (AbsPath, error) @@ -34,13 +34,13 @@ type System interface { //nolint:interfacebloat Readlink(name AbsPath) (string, error) Remove(name AbsPath) error RemoveAll(name AbsPath) error - Rename(oldpath, newpath AbsPath) error + Rename(oldPath, newPath AbsPath) error RunCmd(cmd *exec.Cmd) error - RunScript(scriptname RelPath, dir AbsPath, data []byte, options RunScriptOptions) error + RunScript(scriptName RelPath, dir AbsPath, data []byte, options RunScriptOptions) error Stat(name AbsPath) (fs.FileInfo, error) UnderlyingFS() vfs.FS WriteFile(filename AbsPath, data []byte, perm fs.FileMode) error - WriteSymlink(oldname string, newname AbsPath) error + WriteSymlink(oldName string, newName AbsPath) error } // A emptySystemMixin simulates an empty system. @@ -66,7 +66,7 @@ func (noUpdateSystemMixin) Chtimes(name AbsPath, atime, mtime time.Time) error { panic("update to no update system") } -func (noUpdateSystemMixin) Link(oldname, newname AbsPath) error { +func (noUpdateSystemMixin) Link(oldName, newName AbsPath) error { panic("update to no update system") } @@ -82,7 +82,7 @@ func (noUpdateSystemMixin) RemoveAll(name AbsPath) error { panic("update to no update system") } -func (noUpdateSystemMixin) Rename(oldpath, newpath AbsPath) error { +func (noUpdateSystemMixin) Rename(oldPath, newPath AbsPath) error { panic("update to no update system") } @@ -90,7 +90,7 @@ func (noUpdateSystemMixin) RunCmd(cmd *exec.Cmd) error { panic("update to no update system") } -func (noUpdateSystemMixin) RunScript(scriptname RelPath, dir AbsPath, data []byte, options RunScriptOptions) error { +func (noUpdateSystemMixin) RunScript(scriptName RelPath, dir AbsPath, data []byte, options RunScriptOptions) error { panic("update to no update system") } @@ -98,7 +98,7 @@ func (noUpdateSystemMixin) WriteFile(filename AbsPath, data []byte, perm fs.File panic("update to no update system") } -func (noUpdateSystemMixin) WriteSymlink(oldname string, newname AbsPath) error { +func (noUpdateSystemMixin) WriteSymlink(oldName string, newName AbsPath) error { panic("update to no update system") } diff --git a/internal/chezmoi/tarwritersystem.go b/internal/chezmoi/tarwritersystem.go index 65a5d1f0d5b..e36d545d20e 100644 --- a/internal/chezmoi/tarwritersystem.go +++ b/internal/chezmoi/tarwritersystem.go @@ -43,8 +43,8 @@ func (s *TarWriterSystem) RunCmd(cmd *exec.Cmd) error { } // RunScript implements System.RunScript. -func (s *TarWriterSystem) RunScript(scriptname RelPath, dir AbsPath, data []byte, options RunScriptOptions) error { - return s.WriteFile(NewAbsPath(scriptname.String()), data, 0o700) +func (s *TarWriterSystem) RunScript(scriptName RelPath, dir AbsPath, data []byte, options RunScriptOptions) error { + return s.WriteFile(NewAbsPath(scriptName.String()), data, 0o700) } // WriteFile implements System.WriteFile. @@ -62,10 +62,10 @@ func (s *TarWriterSystem) WriteFile(filename AbsPath, data []byte, perm fs.FileM } // WriteSymlink implements System.WriteSymlink. -func (s *TarWriterSystem) WriteSymlink(oldname string, newname AbsPath) error { +func (s *TarWriterSystem) WriteSymlink(oldName string, newName AbsPath) error { header := s.headerTemplate header.Typeflag = tar.TypeSymlink - header.Name = newname.String() - header.Linkname = oldname + header.Name = newName.String() + header.Linkname = oldName return s.tarWriter.WriteHeader(&header) } diff --git a/internal/chezmoi/zipwritersystem.go b/internal/chezmoi/zipwritersystem.go index 609952781ad..b93c20807d5 100644 --- a/internal/chezmoi/zipwritersystem.go +++ b/internal/chezmoi/zipwritersystem.go @@ -48,8 +48,8 @@ func (s *ZIPWriterSystem) RunCmd(cmd *exec.Cmd) error { } // RunScript implements System.RunScript. -func (s *ZIPWriterSystem) RunScript(scriptname RelPath, dir AbsPath, data []byte, options RunScriptOptions) error { - return s.WriteFile(NewAbsPath(scriptname.String()), data, 0o700) +func (s *ZIPWriterSystem) RunScript(scriptName RelPath, dir AbsPath, data []byte, options RunScriptOptions) error { + return s.WriteFile(NewAbsPath(scriptName.String()), data, 0o700) } // WriteFile implements System.WriteFile. @@ -70,10 +70,10 @@ func (s *ZIPWriterSystem) WriteFile(filename AbsPath, data []byte, perm fs.FileM } // WriteSymlink implements System.WriteSymlink. -func (s *ZIPWriterSystem) WriteSymlink(oldname string, newname AbsPath) error { - data := []byte(oldname) +func (s *ZIPWriterSystem) WriteSymlink(oldName string, newName AbsPath) error { + data := []byte(oldName) fileHeader := zip.FileHeader{ - Name: newname.String(), + Name: newName.String(), Modified: s.modified, UncompressedSize64: uint64(len(data)), } diff --git a/internal/cmd/config_tags_test.go b/internal/cmd/config_tags_test.go index 4497e6df49e..a4128ed25a9 100644 --- a/internal/cmd/config_tags_test.go +++ b/internal/cmd/config_tags_test.go @@ -10,9 +10,9 @@ import ( var expectedTags = []string{"json", "yaml", "mapstructure"} func TestExportedFieldsHaveMatchingMarshalTags(t *testing.T) { - failed, errmsg := verifyTagsArePresentAndMatch(reflect.TypeFor[ConfigFile]()) + failed, errMsg := verifyTagsArePresentAndMatch(reflect.TypeFor[ConfigFile]()) if failed { - t.Error(errmsg) + t.Error(errMsg) } } @@ -33,11 +33,11 @@ func fieldTypesNeedsVerification(ft reflect.Type) []reflect.Type { case reflect.Map: return append(fieldTypesNeedsVerification(ft.Key()), fieldTypesNeedsVerification(ft.Elem())...) default: - return []reflect.Type{} // ... we'll assume interface types, funcs, chans are okay. + return []reflect.Type{} // ... we'll assume interface types, funcs, channels are okay. } } -func verifyTagsArePresentAndMatch(structType reflect.Type) (failed bool, errmsg string) { +func verifyTagsArePresentAndMatch(structType reflect.Type) (failed bool, errMsg string) { name := structType.Name() fields := reflect.VisibleFields(structType) failed = false @@ -83,10 +83,10 @@ func verifyTagsArePresentAndMatch(structType reflect.Type) (failed bool, errmsg verifyTypes := fieldTypesNeedsVerification(f.Type) for _, ft := range verifyTypes { - subFailed, suberrs := verifyTagsArePresentAndMatch(ft) + subFailed, subErrs := verifyTagsArePresentAndMatch(ft) if subFailed { errs.WriteString(fmt.Sprintf("\n In %s.%s:", name, f.Name)) - errs.WriteString(strings.ReplaceAll(suberrs, "\n", "\n ")) + errs.WriteString(strings.ReplaceAll(subErrs, "\n", "\n ")) failed = true } } diff --git a/internal/cmd/doctorcmd.go b/internal/cmd/doctorcmd.go index ced281aaa6a..b29692788c3 100644 --- a/internal/cmd/doctorcmd.go +++ b/internal/cmd/doctorcmd.go @@ -81,7 +81,7 @@ type argsCheck struct { // least version minVersion. type binaryCheck struct { name string - binaryname string + binaryName string ifNotSet checkResult ifNotExist checkResult versionArgs []string @@ -224,7 +224,7 @@ func (c *Config) runDoctorCmd(cmd *cobra.Command, args []string) error { umaskCheck{}, &binaryCheck{ name: "cd-command", - binaryname: cdCommand, + binaryName: cdCommand, ifNotSet: checkResultError, ifNotExist: checkResultError, }, @@ -235,13 +235,13 @@ func (c *Config) runDoctorCmd(cmd *cobra.Command, args []string) error { }, &binaryCheck{ name: "diff-command", - binaryname: c.Diff.Command, + binaryName: c.Diff.Command, ifNotSet: checkResultInfo, ifNotExist: checkResultWarning, }, &binaryCheck{ name: "edit-command", - binaryname: editCommand, + binaryName: editCommand, ifNotSet: checkResultWarning, ifNotExist: checkResultWarning, }, @@ -252,7 +252,7 @@ func (c *Config) runDoctorCmd(cmd *cobra.Command, args []string) error { }, &binaryCheck{ name: "git-command", - binaryname: c.Git.Command, + binaryName: c.Git.Command, ifNotSet: checkResultWarning, ifNotExist: checkResultWarning, versionArgs: []string{"--version"}, @@ -260,13 +260,13 @@ func (c *Config) runDoctorCmd(cmd *cobra.Command, args []string) error { }, &binaryCheck{ name: "merge-command", - binaryname: c.Merge.Command, + binaryName: c.Merge.Command, ifNotSet: checkResultWarning, ifNotExist: checkResultWarning, }, &binaryCheck{ name: "shell-command", - binaryname: shellCommand, + binaryName: shellCommand, ifNotSet: checkResultError, ifNotExist: checkResultError, }, @@ -277,7 +277,7 @@ func (c *Config) runDoctorCmd(cmd *cobra.Command, args []string) error { }, &binaryCheck{ name: "age-command", - binaryname: c.Age.Command, + binaryName: c.Age.Command, versionArgs: []string{"--version"}, versionRx: regexp.MustCompile(`(\d+\.\d+\.\d+\S*)`), ifNotSet: checkResultWarning, @@ -285,7 +285,7 @@ func (c *Config) runDoctorCmd(cmd *cobra.Command, args []string) error { }, &binaryCheck{ name: "gpg-command", - binaryname: c.GPG.Command, + binaryName: c.GPG.Command, versionArgs: []string{"--version"}, versionRx: regexp.MustCompile(`(?m)^gpg\s+\(.*?\)\s+(\d+\.\d+\.\d+)`), ifNotSet: checkResultWarning, @@ -293,7 +293,7 @@ func (c *Config) runDoctorCmd(cmd *cobra.Command, args []string) error { }, &binaryCheck{ name: "pinentry-command", - binaryname: c.PINEntry.Command, + binaryName: c.PINEntry.Command, versionArgs: []string{"--version"}, versionRx: regexp.MustCompile(`^\S+\s+\(pinentry\)\s+(\d+\.\d+\.\d+)`), ifNotSet: checkResultInfo, @@ -301,7 +301,7 @@ func (c *Config) runDoctorCmd(cmd *cobra.Command, args []string) error { }, &binaryCheck{ name: "1password-command", - binaryname: c.Onepassword.Command, + binaryName: c.Onepassword.Command, ifNotSet: checkResultWarning, ifNotExist: checkResultInfo, versionArgs: []string{"--version"}, @@ -310,7 +310,7 @@ func (c *Config) runDoctorCmd(cmd *cobra.Command, args []string) error { }, &binaryCheck{ name: "bitwarden-command", - binaryname: c.Bitwarden.Command, + binaryName: c.Bitwarden.Command, ifNotSet: checkResultWarning, ifNotExist: checkResultInfo, versionArgs: []string{"--version"}, @@ -318,7 +318,7 @@ func (c *Config) runDoctorCmd(cmd *cobra.Command, args []string) error { }, &binaryCheck{ name: "bitwarden-secrets-command", - binaryname: c.BitwardenSecrets.Command, + binaryName: c.BitwardenSecrets.Command, ifNotSet: checkResultWarning, ifNotExist: checkResultInfo, versionArgs: []string{"--version"}, @@ -326,7 +326,7 @@ func (c *Config) runDoctorCmd(cmd *cobra.Command, args []string) error { }, &binaryCheck{ name: "dashlane-command", - binaryname: c.Dashlane.Command, + binaryName: c.Dashlane.Command, ifNotSet: checkResultWarning, ifNotExist: checkResultInfo, versionArgs: []string{"--version"}, @@ -334,7 +334,7 @@ func (c *Config) runDoctorCmd(cmd *cobra.Command, args []string) error { }, &binaryCheck{ name: "doppler-command", - binaryname: c.Doppler.Command, + binaryName: c.Doppler.Command, ifNotSet: checkResultWarning, ifNotExist: checkResultInfo, versionArgs: []string{"--version"}, @@ -342,7 +342,7 @@ func (c *Config) runDoctorCmd(cmd *cobra.Command, args []string) error { }, &binaryCheck{ name: "gopass-command", - binaryname: c.Gopass.Command, + binaryName: c.Gopass.Command, ifNotSet: checkResultWarning, ifNotExist: checkResultInfo, versionArgs: gopassVersionArgs, @@ -351,7 +351,7 @@ func (c *Config) runDoctorCmd(cmd *cobra.Command, args []string) error { }, &binaryCheck{ name: "keepassxc-command", - binaryname: c.Keepassxc.Command, + binaryName: c.Keepassxc.Command, ifNotSet: checkResultWarning, ifNotExist: checkResultInfo, versionArgs: []string{"--version"}, @@ -366,7 +366,7 @@ func (c *Config) runDoctorCmd(cmd *cobra.Command, args []string) error { }, &binaryCheck{ name: "keeper-command", - binaryname: c.Keeper.Command, + binaryName: c.Keeper.Command, ifNotSet: checkResultWarning, ifNotExist: checkResultInfo, versionArgs: []string{"version"}, @@ -374,7 +374,7 @@ func (c *Config) runDoctorCmd(cmd *cobra.Command, args []string) error { }, &binaryCheck{ name: "lastpass-command", - binaryname: c.Lastpass.Command, + binaryName: c.Lastpass.Command, ifNotSet: checkResultWarning, ifNotExist: checkResultInfo, versionArgs: lastpassVersionArgs, @@ -383,7 +383,7 @@ func (c *Config) runDoctorCmd(cmd *cobra.Command, args []string) error { }, &binaryCheck{ name: "pass-command", - binaryname: c.Pass.Command, + binaryName: c.Pass.Command, ifNotSet: checkResultWarning, ifNotExist: checkResultInfo, versionArgs: []string{"version"}, @@ -391,7 +391,7 @@ func (c *Config) runDoctorCmd(cmd *cobra.Command, args []string) error { }, &binaryCheck{ name: "passhole-command", - binaryname: c.Passhole.Command, + binaryName: c.Passhole.Command, ifNotSet: checkResultWarning, ifNotExist: checkResultInfo, versionArgs: []string{"--version"}, @@ -400,7 +400,7 @@ func (c *Config) runDoctorCmd(cmd *cobra.Command, args []string) error { }, &binaryCheck{ name: "rbw-command", - binaryname: c.RBW.Command, + binaryName: c.RBW.Command, ifNotSet: checkResultWarning, ifNotExist: checkResultInfo, versionArgs: []string{"--version"}, @@ -409,7 +409,7 @@ func (c *Config) runDoctorCmd(cmd *cobra.Command, args []string) error { }, &binaryCheck{ name: "vault-command", - binaryname: c.Vault.Command, + binaryName: c.Vault.Command, ifNotSet: checkResultWarning, ifNotExist: checkResultInfo, versionArgs: []string{"version"}, @@ -417,7 +417,7 @@ func (c *Config) runDoctorCmd(cmd *cobra.Command, args []string) error { }, &binaryCheck{ name: "vlt-command", - binaryname: c.HCPVaultSecrets.Command, + binaryName: c.HCPVaultSecrets.Command, ifNotSet: checkResultWarning, ifNotExist: checkResultInfo, versionArgs: []string{"version"}, @@ -426,7 +426,7 @@ func (c *Config) runDoctorCmd(cmd *cobra.Command, args []string) error { }, &binaryCheck{ name: "secret-command", - binaryname: c.Secret.Command, + binaryName: c.Secret.Command, ifNotSet: checkResultInfo, ifNotExist: checkResultInfo, }, @@ -471,14 +471,14 @@ func (c *binaryCheck) Name() string { } func (c *binaryCheck) Run(system chezmoi.System, homeDirAbsPath chezmoi.AbsPath) (checkResult, string) { - if c.binaryname == "" { + if c.binaryName == "" { return c.ifNotSet, "not set" } var pathAbsPath chezmoi.AbsPath - switch path, err := chezmoi.LookPath(c.binaryname); { + switch path, err := chezmoi.LookPath(c.binaryName); { case errors.Is(err, exec.ErrNotFound): - return c.ifNotExist, c.binaryname + " not found in $PATH" + return c.ifNotExist, c.binaryName + " not found in $PATH" case err != nil: return checkResultFailed, err.Error() default: diff --git a/internal/cmd/upgradecmd_windows.go b/internal/cmd/upgradecmd_windows.go index 5b44ca8cb32..1f14c235cf9 100644 --- a/internal/cmd/upgradecmd_windows.go +++ b/internal/cmd/upgradecmd_windows.go @@ -85,12 +85,7 @@ func (c *Config) snapRefresh() error { return errUnsupportedUpgradeMethod } -func (c *Config) upgradeUNIXPackage( - ctx context.Context, - version *semver.Version, - rr *github.RepositoryRelease, - useSudo bool, -) error { +func (c *Config) upgradeUNIXPackage(_ context.Context, _ *semver.Version, _ *github.RepositoryRelease, _ bool) error { return errUnsupportedUpgradeMethod }
chore
Rename variables to satisfy spell checker
57f3d054c76b625388ddf2bd7cba98c0b720c08d
2023-01-31 01:10:48
Tom Payne
chore: Update action-shellcheck config
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 50e75cdc65f..46c0e510762 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -350,7 +350,7 @@ jobs: git diff --exit-code - uses: ludeeus/action-shellcheck@00cae500b08a931fb5698e11e79bfbd38e612a38 with: - ignore: completions + ignore_paths: completions - name: lint-whitespace run: | go run ./internal/cmds/lint-whitespace
chore
Update action-shellcheck config
8dd6c86912f8fced971265e3a57054e526425107
2024-01-24 20:11:56
Daniel Possenriede
docs: combine testing and debugging templates
false
diff --git a/assets/chezmoi.io/docs/user-guide/templating.md b/assets/chezmoi.io/docs/user-guide/templating.md index 570ed3c179e..07c5368dd5e 100644 --- a/assets/chezmoi.io/docs/user-guide/templating.md +++ b/assets/chezmoi.io/docs/user-guide/templating.md @@ -93,22 +93,30 @@ $ chezmoi edit --apply ~/.zshrc ## Testing templates -Templates can be tested with the `chezmoi execute-template` command which treats -each of its arguments as a template and executes it. This can be useful for -testing small fragments of templates, for example: +Templates can be tested and debugged with `chezmoi execute-template`, +which treats each of its arguments as a template and executes it. +The templates are interpreted and the results are output to standard +output, making it useful for testing small template fragments: ```console $ chezmoi execute-template '{{ .chezmoi.hostname }}' ``` -If there are no arguments, `chezmoi execute-template` will read the template -from the standard input. This can be useful for testing whole files, for example: +Without arguments, `chezmoi execute-template` will read the template from +standard input, which is useful for testing whole files: ```console $ chezmoi cd $ chezmoi execute-template < dot_zshrc.tmpl ``` +If file redirection does not work (as when using PowerShell), the contents +of a file can be piped into `chezmoi execute-template`: + +```console +$ cat foo.txt | chezmoi execute-template +``` + ## Template syntax Template actions are written inside double curly brackets, `{{` and `}}`. @@ -160,29 +168,6 @@ HOSTNAME=myhostname Notice that this will remove any number of tabs, spaces and even newlines and carriage returns. -## Debugging templates - -If there is a mistake in one of your templates and you want to debug it, chezmoi -can help you. You can use this subcommand to test and play with the examples in -these docs as well. - -There is a very handy subcommand called `execute-template`. chezmoi will -interpret any data coming from stdin or at the end of the command. It will then -interpret all templates and output the result to stdout. For example with the -command: - -```console -$ chezmoi execute-template '{{ .chezmoi.os }}/{{ .chezmoi.arch }}' -``` - -chezmoi will output the current OS and architecture to stdout. - -You can also feed the contents of a file to this command by typing: - -```console -$ cat foo.txt | chezmoi execute-template -``` - ## Simple logic A very useful feature of chezmoi templates is the ability to perform logical
docs
combine testing and debugging templates
295306e94236b6b0f798d1fc0998582e697475b8
2025-03-04 22:37:25
Tom Payne
chore: Add test for multiple evaluation of templates
false
diff --git a/internal/cmd/testdata/scripts/issue4315.txtar b/internal/cmd/testdata/scripts/issue4315.txtar new file mode 100644 index 00000000000..30b1fa52045 --- /dev/null +++ b/internal/cmd/testdata/scripts/issue4315.txtar @@ -0,0 +1,20 @@ +[windows] skip 'UNIX only' + +exec chmod a+x bin/prog + +# test that templates are only executed once +exec chezmoi apply +cmp $HOME/.file golden/.file +cmp count golden/count + +-- bin/prog -- +#!/bin/sh + +echo a >> count +echo 1 +-- golden/.file -- +1 +-- golden/count -- +a +-- home/user/.local/share/chezmoi/dot_file.tmpl -- +{{- output "prog" -}}
chore
Add test for multiple evaluation of templates
4c2aa8fc5516deff2a6ae23a52552938b07c44b1
2023-12-25 20:43:23
Tom Payne
chore: Update dependencies
false
diff --git a/go.mod b/go.mod index c34ea842cb7..15a075aad7a 100644 --- a/go.mod +++ b/go.mod @@ -10,8 +10,8 @@ require ( github.com/Shopify/ejson v1.4.1 github.com/alecthomas/assert/v2 v2.4.1 github.com/aws/aws-sdk-go-v2 v1.24.0 - github.com/aws/aws-sdk-go-v2/config v1.26.1 - github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.25.5 + github.com/aws/aws-sdk-go-v2/config v1.26.2 + github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.26.0 github.com/bmatcuk/doublestar/v4 v4.6.1 github.com/bradenhilton/mozillainstallhash v1.0.1 github.com/charmbracelet/bubbles v0.17.1 @@ -45,7 +45,7 @@ require ( github.com/zalando/go-keyring v0.2.3 go.etcd.io/bbolt v1.3.8 golang.org/x/crypto v0.17.0 - golang.org/x/exp v0.0.0-20231214170342-aacd6d4b4611 + golang.org/x/exp v0.0.0-20231219180239-dc181d75b848 golang.org/x/oauth2 v0.15.0 golang.org/x/sync v0.5.0 golang.org/x/sys v0.15.0 @@ -70,7 +70,7 @@ require ( github.com/alecthomas/repr v0.3.0 // indirect github.com/alessio/shellescape v1.4.2 // indirect github.com/atotto/clipboard v0.1.4 // indirect - github.com/aws/aws-sdk-go-v2/credentials v1.16.12 // indirect + github.com/aws/aws-sdk-go-v2/credentials v1.16.13 // indirect github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.14.10 // indirect github.com/aws/aws-sdk-go-v2/internal/configsources v1.2.9 // indirect github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.5.9 // indirect @@ -79,7 +79,7 @@ require ( github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.10.9 // indirect github.com/aws/aws-sdk-go-v2/service/sso v1.18.5 // indirect github.com/aws/aws-sdk-go-v2/service/ssooidc v1.21.5 // indirect - github.com/aws/aws-sdk-go-v2/service/sts v1.26.5 // indirect + github.com/aws/aws-sdk-go-v2/service/sts v1.26.6 // indirect github.com/aws/smithy-go v1.19.0 // indirect github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect github.com/aymerick/douceur v0.2.0 // indirect @@ -138,7 +138,7 @@ require ( golang.org/x/text v0.14.0 // indirect golang.org/x/tools v0.16.1 // indirect google.golang.org/appengine v1.6.8 // indirect - google.golang.org/protobuf v1.31.0 // indirect + google.golang.org/protobuf v1.32.0 // indirect gopkg.in/warnings.v0 v0.1.2 // indirect ) diff --git a/go.sum b/go.sum index 00e86709d45..683c91a0397 100644 --- a/go.sum +++ b/go.sum @@ -50,10 +50,10 @@ github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= github.com/aws/aws-sdk-go-v2 v1.24.0 h1:890+mqQ+hTpNuw0gGP6/4akolQkSToDJgHfQE7AwGuk= github.com/aws/aws-sdk-go-v2 v1.24.0/go.mod h1:LNh45Br1YAkEKaAqvmE1m8FUx6a5b/V0oAKV7of29b4= -github.com/aws/aws-sdk-go-v2/config v1.26.1 h1:z6DqMxclFGL3Zfo+4Q0rLnAZ6yVkzCRxhRMsiRQnD1o= -github.com/aws/aws-sdk-go-v2/config v1.26.1/go.mod h1:ZB+CuKHRbb5v5F0oJtGdhFTelmrxd4iWO1lf0rQwSAg= -github.com/aws/aws-sdk-go-v2/credentials v1.16.12 h1:v/WgB8NxprNvr5inKIiVVrXPuuTegM+K8nncFkr1usU= -github.com/aws/aws-sdk-go-v2/credentials v1.16.12/go.mod h1:X21k0FjEJe+/pauud82HYiQbEr9jRKY3kXEIQ4hXeTQ= +github.com/aws/aws-sdk-go-v2/config v1.26.2 h1:+RWLEIWQIGgrz2pBPAUoGgNGs1TOyF4Hml7hCnYj2jc= +github.com/aws/aws-sdk-go-v2/config v1.26.2/go.mod h1:l6xqvUxt0Oj7PI/SUXYLNyZ9T/yBPn3YTQcJLLOdtR8= +github.com/aws/aws-sdk-go-v2/credentials v1.16.13 h1:WLABQ4Cp4vXtXfOWOS3MEZKr6AAYUpMczLhgKtAjQ/8= +github.com/aws/aws-sdk-go-v2/credentials v1.16.13/go.mod h1:Qg6x82FXwW0sJHzYruxGiuApNo31UEtJvXVSZAXeWiw= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.14.10 h1:w98BT5w+ao1/r5sUuiH6JkVzjowOKeOJRHERyy1vh58= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.14.10/go.mod h1:K2WGI7vUvkIv1HoNbfBA1bvIZ+9kL3YVmWxeKuLQsiw= github.com/aws/aws-sdk-go-v2/internal/configsources v1.2.9 h1:v+HbZaCGmOwnTTVS86Fleq0vPzOd7tnJGbFhP0stNLs= @@ -66,14 +66,14 @@ github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.10.4 h1:/b31bi3 github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.10.4/go.mod h1:2aGXHFmbInwgP9ZfpmdIfOELL79zhdNYNmReK8qDfdQ= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.10.9 h1:Nf2sHxjMJR8CSImIVCONRi4g0Su3J+TSTbS7G0pUeMU= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.10.9/go.mod h1:idky4TER38YIjr2cADF1/ugFMKvZV7p//pVeV5LZbF0= -github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.25.5 h1:qYi/BfDrWXZxlmRjlKCyFmtI4HKJwW8OKDKhKRAOZQI= -github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.25.5/go.mod h1:4Ae1NCLK6ghmjzd45Tc33GgCKhUWD2ORAlULtMO1Cbs= +github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.26.0 h1:dPCRgAL4WD9tSMaDglRNGOiAtSTjkwNiUW5GDpWFfHA= +github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.26.0/go.mod h1:4Ae1NCLK6ghmjzd45Tc33GgCKhUWD2ORAlULtMO1Cbs= github.com/aws/aws-sdk-go-v2/service/sso v1.18.5 h1:ldSFWz9tEHAwHNmjx2Cvy1MjP5/L9kNoR0skc6wyOOM= github.com/aws/aws-sdk-go-v2/service/sso v1.18.5/go.mod h1:CaFfXLYL376jgbP7VKC96uFcU8Rlavak0UlAwk1Dlhc= github.com/aws/aws-sdk-go-v2/service/ssooidc v1.21.5 h1:2k9KmFawS63euAkY4/ixVNsYYwrwnd5fIvgEKkfZFNM= github.com/aws/aws-sdk-go-v2/service/ssooidc v1.21.5/go.mod h1:W+nd4wWDVkSUIox9bacmkBP5NMFQeTJ/xqNabpzSR38= -github.com/aws/aws-sdk-go-v2/service/sts v1.26.5 h1:5UYvv8JUvllZsRnfrcMQ+hJ9jNICmcgKPAO1CER25Wg= -github.com/aws/aws-sdk-go-v2/service/sts v1.26.5/go.mod h1:XX5gh4CB7wAs4KhcF46G6C8a2i7eupU19dcAAE+EydU= +github.com/aws/aws-sdk-go-v2/service/sts v1.26.6 h1:HJeiuZ2fldpd0WqngyMR6KW7ofkXNLyOaHwEIGm39Cs= +github.com/aws/aws-sdk-go-v2/service/sts v1.26.6/go.mod h1:XX5gh4CB7wAs4KhcF46G6C8a2i7eupU19dcAAE+EydU= github.com/aws/smithy-go v1.19.0 h1:KWFKQV80DpP3vJrrA9sVAHQ5gc2z8i4EzrLhLlWXcBM= github.com/aws/smithy-go v1.19.0/go.mod h1:NukqUGpCZIILqqiV0NIjeFh24kd/FAa4beRb6nbIUPE= github.com/aymanbagabas/go-osc52 v1.0.3 h1:DTwqENW7X9arYimJrPeGZcV0ln14sGMt3pHZspWD+Mg= @@ -367,8 +367,8 @@ golang.org/x/crypto v0.3.1-0.20221117191849-2c476679df9a/go.mod h1:hebNnKkNXi2Uz golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= golang.org/x/crypto v0.17.0 h1:r8bRNjWL3GshPW3gkd+RpvzWrZAwPS49OmTGZ/uhM4k= golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4= -golang.org/x/exp v0.0.0-20231214170342-aacd6d4b4611 h1:qCEDpW1G+vcj3Y7Fy52pEM1AWm3abj8WimGYejI3SC4= -golang.org/x/exp v0.0.0-20231214170342-aacd6d4b4611/go.mod h1:iRJReGqOEeBhDZGkGbynYwcHlctCvnjTYIamk7uXpHI= +golang.org/x/exp v0.0.0-20231219180239-dc181d75b848 h1:+iq7lrkxmFNBM7xx+Rae2W6uyPfhPeDWD+n+JgppptE= +golang.org/x/exp v0.0.0-20231219180239-dc181d75b848/go.mod h1:iRJReGqOEeBhDZGkGbynYwcHlctCvnjTYIamk7uXpHI= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.14.0 h1:dGoOF9QVLYng8IHTm7BAyWqCqSheQ5pYWGhzW00YJr0= @@ -440,8 +440,8 @@ google.golang.org/appengine v1.6.8 h1:IhEN5q69dyKagZPYMSdIjS2HqprW324FRQZJcGqPAs google.golang.org/appengine v1.6.8/go.mod h1:1jJ3jBArFh5pcgW8gCtRJnepW8FzD1V44FJffLiz/Ds= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8= -google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +google.golang.org/protobuf v1.32.0 h1:pPC6BG5ex8PDFnkbrGU3EixyhKcQ2aDuBS36lqK/C7I= +google.golang.org/protobuf v1.32.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
chore
Update dependencies
d36ceaf01877e2812702f1754ea7e4b5753dfa14
2023-06-29 00:43:04
Tom Payne
chore: Update dependencies
false
diff --git a/go.mod b/go.mod index 42e3014dfd3..0c78d9c069f 100644 --- a/go.mod +++ b/go.mod @@ -25,7 +25,7 @@ require ( github.com/klauspost/compress v1.16.6 github.com/mitchellh/mapstructure v1.5.0 github.com/muesli/combinator v0.3.0 - github.com/muesli/termenv v0.15.1 + github.com/muesli/termenv v0.15.2 github.com/pelletier/go-toml/v2 v2.0.8 github.com/rogpeppe/go-internal v1.10.1-0.20230524175051-ec119421bb97 github.com/rs/zerolog v1.29.1 @@ -42,7 +42,7 @@ require ( go.etcd.io/bbolt v1.3.7 go.uber.org/multierr v1.11.0 golang.org/x/crypto v0.10.0 - golang.org/x/exp v0.0.0-20230522175609-2e198f4a06a1 + golang.org/x/exp v0.0.0-20230626212559-97b1e661b5df golang.org/x/oauth2 v0.9.0 golang.org/x/sync v0.3.0 golang.org/x/sys v0.9.0 @@ -57,7 +57,7 @@ require ( github.com/Masterminds/goutils v1.1.1 // indirect github.com/Masterminds/semver/v3 v3.2.1 // indirect github.com/Microsoft/go-winio v0.6.1 // indirect - github.com/ProtonMail/go-crypto v0.0.0-20230619160724-3fbb1f12458c // indirect + github.com/ProtonMail/go-crypto v0.0.0-20230626094100-7e9e0395ebec // indirect github.com/acomagu/bufpipe v1.0.4 // indirect github.com/alecthomas/chroma v0.10.0 // indirect github.com/alecthomas/repr v0.2.0 // indirect @@ -127,7 +127,7 @@ require ( golang.org/x/text v0.10.0 // indirect golang.org/x/tools v0.10.0 // indirect google.golang.org/appengine v1.6.7 // indirect - google.golang.org/protobuf v1.30.0 // indirect + google.golang.org/protobuf v1.31.0 // indirect gopkg.in/warnings.v0 v0.1.2 // indirect ) diff --git a/go.sum b/go.sum index 098461a2fc3..d506588b6f5 100644 --- a/go.sum +++ b/go.sum @@ -14,8 +14,8 @@ github.com/Masterminds/sprig/v3 v3.2.3/go.mod h1:rXcFaZ2zZbLRJv/xSysmlgIM1u11eBa github.com/Microsoft/go-winio v0.5.2/go.mod h1:WpS1mjBmmwHBEWmogvA2mj8546UReBk4v8QkMxJ6pZY= github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migciow= github.com/Microsoft/go-winio v0.6.1/go.mod h1:LRdKpFKfdobln8UmuiYcKPot9D2v6svN5+sAH+4kjUM= -github.com/ProtonMail/go-crypto v0.0.0-20230619160724-3fbb1f12458c h1:figwFwYep1Qnl64Y+Rc8tyQWE0xvYAN+5EX+rD40pTU= -github.com/ProtonMail/go-crypto v0.0.0-20230619160724-3fbb1f12458c/go.mod h1:EjAoLdwvbIOoOQr3ihjnSoLZRtE8azugULFRteWMNc0= +github.com/ProtonMail/go-crypto v0.0.0-20230626094100-7e9e0395ebec h1:vV3RryLxt42+ZIVOFbYJCH1jsZNTNmj2NYru5zfx+4E= +github.com/ProtonMail/go-crypto v0.0.0-20230626094100-7e9e0395ebec/go.mod h1:EjAoLdwvbIOoOQr3ihjnSoLZRtE8azugULFRteWMNc0= github.com/Shopify/ejson v1.4.0 h1:RvvWSOjDdInbMNtR97eJ5GEd6njjDNSbvbFHoQjJAXo= github.com/Shopify/ejson v1.4.0/go.mod h1:VZMUtDzvBW/PAXRUF5fzp1ffb1ucT8MztrZXXLYZurw= github.com/acomagu/bufpipe v1.0.4 h1:e3H4WUzM3npvo5uv95QuJM3cQspFNtFBzvJ2oNjKIDQ= @@ -247,8 +247,8 @@ github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKt github.com/muesli/termenv v0.11.1-0.20220204035834-5ac8409525e0/go.mod h1:Bd5NYQ7pd+SrtBSrSNoBBmXlcY8+Xj4BMJgh8qcZrvs= github.com/muesli/termenv v0.13.0/go.mod h1:sP1+uffeLaEYpyOTb8pLCUctGcGLnoFjSn4YJK5e2bc= github.com/muesli/termenv v0.14.0/go.mod h1:kG/pF1E7fh949Xhe156crRUrHNyK221IuGO7Ez60Uc8= -github.com/muesli/termenv v0.15.1 h1:UzuTb/+hhlBugQz28rpzey4ZuKcZ03MeKsoG7IJZIxs= -github.com/muesli/termenv v0.15.1/go.mod h1:HeAQPTzpfs016yGtA4g00CsdYnVLJvxsS4ANqrZs2sQ= +github.com/muesli/termenv v0.15.2 h1:GohcuySI0QmI3wN8Ok9PtKGkgkFIk7y6Vpb5PvrY+Wo= +github.com/muesli/termenv v0.15.2/go.mod h1:Epx+iuz8sNs7mNKhxzH4fWXGNpZwUaJKRS1noLXviQ8= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= @@ -355,8 +355,8 @@ golang.org/x/crypto v0.3.1-0.20221117191849-2c476679df9a/go.mod h1:hebNnKkNXi2Uz golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= golang.org/x/crypto v0.10.0 h1:LKqV2xt9+kDzSTfOhx4FrkEBcMrAgHSYgzywV9zcGmM= golang.org/x/crypto v0.10.0/go.mod h1:o4eNf7Ede1fv+hwOwZsTHl9EsPFO6q6ZvYR8vYfY45I= -golang.org/x/exp v0.0.0-20230522175609-2e198f4a06a1 h1:k/i9J1pBpvlfR+9QsetwPyERsqu1GIbi967PQMq3Ivc= -golang.org/x/exp v0.0.0-20230522175609-2e198f4a06a1/go.mod h1:V1LtkGg67GoY2N1AnLN78QLrzxkLyJw7RJb1gzOOz9w= +golang.org/x/exp v0.0.0-20230626212559-97b1e661b5df h1:UA2aFVmmsIlefxMk29Dp2juaUSth8Pyn3Tq5Y5mJGME= +golang.org/x/exp v0.0.0-20230626212559-97b1e661b5df/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.11.0 h1:bUO06HqtnRcc/7l71XBe4WcqTZ+3AH1J59zWDDwLKgU= @@ -430,8 +430,8 @@ google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6 google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng= -google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8= +google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
chore
Update dependencies
216b5a268135fcee91c8eb882a14b0f8f1a88e5a
2022-03-17 05:54:30
Tom Payne
chore: Update dependencies
false
diff --git a/go.mod b/go.mod index afce457e98e..c15e5dfb2c9 100644 --- a/go.mod +++ b/go.mod @@ -34,27 +34,27 @@ require ( github.com/rs/zerolog v1.26.1 github.com/sergi/go-diff v1.1.0 github.com/shopspring/decimal v1.3.1 // indirect - github.com/spf13/afero v1.8.1 - github.com/spf13/cobra v1.3.0 + github.com/spf13/afero v1.8.2 + github.com/spf13/cobra v1.4.0 github.com/spf13/viper v1.10.1 github.com/stretchr/objx v0.3.0 // indirect - github.com/stretchr/testify v1.7.0 + github.com/stretchr/testify v1.7.1 github.com/twpayne/go-pinentry v0.2.0 github.com/twpayne/go-shell v0.3.1 github.com/twpayne/go-vfs/v4 v4.1.0 github.com/twpayne/go-xdg/v6 v6.0.0 github.com/ulikunitz/xz v0.5.10 github.com/xanzy/ssh-agent v0.3.1 // indirect - github.com/yuin/goldmark v1.4.8 // indirect + github.com/yuin/goldmark v1.4.10 // indirect github.com/zalando/go-keyring v0.2.0 go.etcd.io/bbolt v1.3.6 go.uber.org/atomic v1.9.0 // indirect go.uber.org/multierr v1.8.0 - golang.org/x/crypto v0.0.0-20220214200702-86341886e292 // indirect + golang.org/x/crypto v0.0.0-20220315160706-3147a52a75dd // indirect golang.org/x/net v0.0.0-20220225172249-27dd8689420f // indirect - golang.org/x/oauth2 v0.0.0-20220223155221-ee480838109b + golang.org/x/oauth2 v0.0.0-20220309155454-6242fa91716a golang.org/x/sync v0.0.0-20210220032951-036812b2e83c - golang.org/x/sys v0.0.0-20220227234510-4e6760a101f9 + golang.org/x/sys v0.0.0-20220315194320-039c03cc5b86 golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 gopkg.in/ini.v1 v1.66.4 // indirect gopkg.in/yaml.v2 v2.4.0 diff --git a/go.sum b/go.sum index 62d03375e2f..fdf2f2aea0b 100644 --- a/go.sum +++ b/go.sum @@ -27,7 +27,6 @@ cloud.google.com/go v0.90.0/go.mod h1:kRX0mNRHe0e2rC6oNakvwQqzyDmg57xJ+SZU1eT2aD cloud.google.com/go v0.93.3/go.mod h1:8utlLll2EF5XMAV15woO4lSbWQlk8rer9aLOfLh7+YI= cloud.google.com/go v0.94.1/go.mod h1:qAlAugsXlC+JWO+Bke5vCtc9ONxjQT3drlTTnAplMW4= cloud.google.com/go v0.97.0/go.mod h1:GF7l59pYBVlXQIBLx3a761cZ41F9bBH3JUlihCt2Udc= -cloud.google.com/go v0.98.0/go.mod h1:ua6Ush4NALrHk5QXDWnjvZHN93OuF0HfuEPq9I1X0cM= cloud.google.com/go v0.99.0 h1:y/cM2iqGgGi5D5DQZl6D9STN/3dR/Vx5Mp8s752oJTY= cloud.google.com/go v0.99.0/go.mod h1:w0Xx2nLzqWJPuozYQX+hFfCSI8WioryfRDzkoI/Y2ZA= cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= @@ -345,7 +344,6 @@ github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 h1:+ngKgrYPPJr github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= github.com/grpc-ecosystem/grpc-gateway v1.16.0 h1:gmcG1KaJ57LophUzW0Hy8NmPhnMZb4M0+kPpLofRdBo= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= -github.com/hashicorp/consul/api v1.11.0/go.mod h1:XjsvQN+RJGWI2TWy1/kqaE16HrR2J/FWgkYjdZQsX9M= github.com/hashicorp/consul/api v1.12.0 h1:k3y1FYv6nuKyNTqj6w9gXOx5r5CfLj/k/euUeBXj1OY= github.com/hashicorp/consul/api v1.12.0/go.mod h1:6pVBMo0ebnYdt2S3H87XhekM/HHrUoTD2XXb/VrZVy0= github.com/hashicorp/consul/sdk v0.8.0 h1:OJtKBtEjboEZvG6AOUdh4Z1Zbyu0WcxQ0qatRrZHTVU= @@ -386,13 +384,10 @@ github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= github.com/hashicorp/logutils v1.0.0 h1:dLEQVugN8vlakKOUE3ihGLTZJRB4j+M2cdTm/ORI65Y= github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= -github.com/hashicorp/mdns v1.0.1/go.mod h1:4gW7WsVCke5TE7EPeYliwHlRUyBtfCwuFwuMg2DmyNY= github.com/hashicorp/mdns v1.0.4 h1:sY0CMhFmjIPDMlTB+HfymFHCaYLhgifZ0QhjaYKD/UQ= github.com/hashicorp/mdns v1.0.4/go.mod h1:mtBihi+LeNXGtG8L9dX59gAEa12BDtBQSp4v/YAJqrc= -github.com/hashicorp/memberlist v0.2.2/go.mod h1:MS2lj3INKhZjWNqd3N0m3J+Jxf3DAOnAH9VT3Sh9MUE= github.com/hashicorp/memberlist v0.3.0 h1:8+567mCcFDnS5ADl7lrpxPMWiFCElyUEeW0gtj34fMA= github.com/hashicorp/memberlist v0.3.0/go.mod h1:MS2lj3INKhZjWNqd3N0m3J+Jxf3DAOnAH9VT3Sh9MUE= -github.com/hashicorp/serf v0.9.5/go.mod h1:UWDWwZeL5cuWDJdl0C6wrvrUwEqtQ4ZKBKKENpqIUyk= github.com/hashicorp/serf v0.9.6 h1:uuEX1kLR6aoda1TBttmJQKDLZE1Ob7KN0NPdE7EtCDc= github.com/hashicorp/serf v0.9.6/go.mod h1:TXZNMjZQijwlDvp+r0b63xZ45H7JmCmgg4gpTwn9UV4= github.com/huandu/xstrings v1.3.1/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= @@ -479,7 +474,6 @@ github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5 github.com/microcosm-cc/bluemonday v1.0.17/go.mod h1:Z0r70sCuXHig8YpBzCc5eGHAap2K7e/u082ZUpDRRqM= github.com/microcosm-cc/bluemonday v1.0.18 h1:6HcxvXDAi3ARt3slx6nTesbvorIc3QeTzBNRvWktHBo= github.com/microcosm-cc/bluemonday v1.0.18/go.mod h1:Z0r70sCuXHig8YpBzCc5eGHAap2K7e/u082ZUpDRRqM= -github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= github.com/miekg/dns v1.1.26/go.mod h1:bPDLeHnStXmXAq1m/Ch/hvfNHr14JKNPMBo3VZKjuso= github.com/miekg/dns v1.1.41 h1:WMszZWJG0XmzbK9FEmzH2TVcqYzFesusSIB41b8KHxY= github.com/miekg/dns v1.1.41/go.mod h1:p6aan82bvRIyn+zDIv9xYNUpwa73JcSh9BKwknJysuI= @@ -573,7 +567,6 @@ github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f h1:UFr9zpz4xgTnIE5yIMtWAMngCdZ9p/+q6lTbgelo80M= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= -github.com/sagikazarmark/crypt v0.3.0/go.mod h1:uD/D+6UF4SrIR1uGEv7bBNkNqLGqUr43MRiaGWX1Nig= github.com/sagikazarmark/crypt v0.4.0 h1:Rqcx6Sf/bWQUmmfGQhcFx3wQQEfb2UZWhAKvGRairm0= github.com/sagikazarmark/crypt v0.4.0/go.mod h1:ALv2SRj7GxYV4HO9elxH9nS6M9gW+xDNxqmyJ6RfDFM= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529 h1:nn5Wsu0esKSJiIVhscUtVbo7ada43DJhG55ua/hjS5I= @@ -594,18 +587,17 @@ github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72 h1:qLC7fQah7D6K1 github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spf13/afero v1.3.3/go.mod h1:5KUK8ByomD5Ti5Artl0RtHeI5pTF7MIDuXL3yY520V4= github.com/spf13/afero v1.6.0/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I= -github.com/spf13/afero v1.8.1 h1:izYHOT71f9iZ7iq37Uqjael60/vYC6vMtzedudZ0zEk= -github.com/spf13/afero v1.8.1/go.mod h1:CtAatgMJh6bJEIs48Ay/FOnkljP3WeGUG0MC1RfAqwo= +github.com/spf13/afero v1.8.2 h1:xehSyVa0YnHWsJ49JFljMpg1HX19V6NDZ1fkm1Xznbo= +github.com/spf13/afero v1.8.2/go.mod h1:CtAatgMJh6bJEIs48Ay/FOnkljP3WeGUG0MC1RfAqwo= github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= github.com/spf13/cast v1.4.1 h1:s0hze+J0196ZfEMTs80N7UlFt0BDuQ7Q+JDnHiMWKdA= github.com/spf13/cast v1.4.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= -github.com/spf13/cobra v1.3.0 h1:R7cSvGu+Vv+qX0gW5R/85dx2kmmJT5z5NM8ifdYjdn0= -github.com/spf13/cobra v1.3.0/go.mod h1:BrRVncBjOJa/eUcVVm9CE+oC6as8k+VYr4NY7WCi9V4= +github.com/spf13/cobra v1.4.0 h1:y+wJpx64xcgO1V+RcnwW0LEHxTKRi2ZDPSBjWnrg88Q= +github.com/spf13/cobra v1.4.0/go.mod h1:Wo4iy3BUC+X2Fybo0PDqwJIv3dNRiZLHQymsfxlB84g= github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -github.com/spf13/viper v1.10.0/go.mod h1:SoyBPwAtKDzypXNDFKN5kzH7ppppbGZtls1UpIy5AsM= github.com/spf13/viper v1.10.1 h1:nuJZuYpG7gTj/XqiUwg8bA0cp1+M2mC3J4g5luUYBKk= github.com/spf13/viper v1.10.1/go.mod h1:IGlFPqhNAPKRxohIzWpI5QEy4kuI7tcl5WvR+8qy1rU= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= @@ -617,8 +609,9 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= github.com/tklauser/go-sysconf v0.3.9 h1:JeUVdAOWhhxVcU6Eqr/ATFHgXk/mmiItdKeJPev3vTo= @@ -651,8 +644,8 @@ github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9dec github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark v1.4.4/go.mod h1:rmuwmfZ0+bvzB24eSC//bk1R1Zp3hM0OXYv/G2LIilg= -github.com/yuin/goldmark v1.4.8 h1:zHPiabbIRssZOI0MAzJDHsyvG4MXCGqVaMOwR+HeoQQ= -github.com/yuin/goldmark v1.4.8/go.mod h1:rmuwmfZ0+bvzB24eSC//bk1R1Zp3hM0OXYv/G2LIilg= +github.com/yuin/goldmark v1.4.10 h1:+WgKGo8CQrlMTRJpGCFCyNddOhW801TKC2QijVV9QVg= +github.com/yuin/goldmark v1.4.10/go.mod h1:rmuwmfZ0+bvzB24eSC//bk1R1Zp3hM0OXYv/G2LIilg= github.com/yuin/goldmark-emoji v1.0.1 h1:ctuWEyzGBwiucEqxzwe0SOYDXPAucOrE9NQC18Wa1os= github.com/yuin/goldmark-emoji v1.0.1/go.mod h1:2w1E6FEWLcDQkoTE+7HU6QF1F6SLlNGjRIBbIZQFqkQ= github.com/zalando/go-keyring v0.2.0 h1:IZOFhp3Gw5WeaGTVpKtKD2o/s+BeeqQkKUhtMDTQ190= @@ -685,7 +678,6 @@ go.uber.org/multierr v1.8.0/go.mod h1:7EAYxJLBy9rStEaz58O2t4Uvip6FSURkq8/ppBp95a go.uber.org/zap v1.17.0 h1:MTjgFu6ZLKvY6Pvaqk97GlxNBuMpV4Hy/3P6tRGlI2U= go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= -golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190219172222-a4c6cb3142f2/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= @@ -701,8 +693,8 @@ golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5y golang.org/x/crypto v0.0.0-20210817164053-32db794688a5/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20211215165025-cf75a172585e/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8= -golang.org/x/crypto v0.0.0-20220214200702-86341886e292 h1:f+lwQ+GtmgoY+A2YaQxlSOnDjXcQ7ZRLWOHbC6HtRqE= -golang.org/x/crypto v0.0.0-20220214200702-86341886e292/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.0.0-20220315160706-3147a52a75dd h1:XcWmESyNjXJMLahc3mqVQJcgSTDxFxhETVlfk9uGc38= +golang.org/x/crypto v0.0.0-20220315160706-3147a52a75dd/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -746,7 +738,6 @@ golang.org/x/mod v0.5.0 h1:UG21uOlmZabA4fW5i7ZX6bjw1xELEGg/ZLgZq9auk/Q= golang.org/x/mod v0.5.0/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -810,8 +801,8 @@ golang.org/x/oauth2 v0.0.0-20210805134026-6f1e6394065a/go.mod h1:KelEdhl1UZF7XfJ golang.org/x/oauth2 v0.0.0-20210819190943-2bc19b11175f/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20211005180243-6b3c2da341f1/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20211104180415-d3ed0bb246c8/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20220223155221-ee480838109b h1:clP8eMhB30EHdc0bd2Twtq6kgU7yl5ub2cQLSdrv1Dg= -golang.org/x/oauth2 v0.0.0-20220223155221-ee480838109b/go.mod h1:DAh4E804XQdzx2j+YRIaUnCqCV2RuMz24cGBJ5QYIrc= +golang.org/x/oauth2 v0.0.0-20220309155454-6242fa91716a h1:qfl7ob3DIEs3Ml9oLuPwY2N04gymzAW04WsUQHIClgM= +golang.org/x/oauth2 v0.0.0-20220309155454-6242fa91716a/go.mod h1:DAh4E804XQdzx2j+YRIaUnCqCV2RuMz24cGBJ5QYIrc= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -827,7 +818,6 @@ golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -900,11 +890,10 @@ golang.org/x/sys v0.0.0-20210908233432-aa78b53d3365/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211124211545-fe61309f8881/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211205182925-97ca703d548d/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211210111614-af8b64212486/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220227234510-4e6760a101f9 h1:nhht2DYV/Sn3qOayu8lM+cU1ii9sTLUeBQwQQfUHtrs= -golang.org/x/sys v0.0.0-20220227234510-4e6760a101f9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220315194320-039c03cc5b86 h1:A9i04dxx7Cribqbs8jf3FQLogkL/CV2YN7hj9KWJCkc= +golang.org/x/sys v0.0.0-20220315194320-039c03cc5b86/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 h1:JGgROgKl9N8DuW20oFS5gxc+lE67/N3FcwmBPMe7ArY= @@ -1016,7 +1005,6 @@ google.golang.org/api v0.56.0/go.mod h1:38yMfeP1kfjsl8isn0tliTjIb1rJXcQi4UXlbqiv google.golang.org/api v0.57.0/go.mod h1:dVPlbZyBo2/OjBpmvNdpn2GRm6rPy75jyU7bmhdrMgI= google.golang.org/api v0.59.0/go.mod h1:sT2boj7M9YJxZzgeZqXogmhfmRWDtPzT31xkieUbuZU= google.golang.org/api v0.61.0/go.mod h1:xQRti5UdCmoCEqFxcz93fTl338AVqDgyaDRuOZ3hg9I= -google.golang.org/api v0.62.0/go.mod h1:dKmwPCydfsad4qCH08MSdgWjfHOyfpd4VtDGgRFdavw= google.golang.org/api v0.63.0 h1:n2bqqK895ygnBpdPDYetfy23K7fJ22wsrZKCyfuRkkA= google.golang.org/api v0.63.0/go.mod h1:gs4ij2ffTRXwuzzgJl/56BdwJaA194ijkfn++9tDuPo= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= @@ -1088,8 +1076,6 @@ google.golang.org/genproto v0.0.0-20210924002016-3dee208752a0/go.mod h1:5CzLGKJ6 google.golang.org/genproto v0.0.0-20211008145708-270636b82663/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= google.golang.org/genproto v0.0.0-20211028162531-8db9c33dc351/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= google.golang.org/genproto v0.0.0-20211118181313-81c1377c94b1/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= -google.golang.org/genproto v0.0.0-20211129164237-f09f9a12af12/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= -google.golang.org/genproto v0.0.0-20211203200212-54befc351ae9/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= google.golang.org/genproto v0.0.0-20211206160659-862468c7d6e0/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= google.golang.org/genproto v0.0.0-20211208223120-3a66f561d7aa h1:I0YcKz0I7OAhddo7ya8kMnvprhcWM045PmkBdMO9zN0= google.golang.org/genproto v0.0.0-20211208223120-3a66f561d7aa/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= @@ -1119,7 +1105,6 @@ google.golang.org/grpc v1.39.0/go.mod h1:PImNr+rS9TWYb2O4/emRugxiyHZ5JyHW5F+RPnD google.golang.org/grpc v1.39.1/go.mod h1:PImNr+rS9TWYb2O4/emRugxiyHZ5JyHW5F+RPnDzfrE= google.golang.org/grpc v1.40.0/go.mod h1:ogyxbiOoUXAkP+4+xa6PZSE9DZgIHtSpzjDTB9KAK34= google.golang.org/grpc v1.40.1/go.mod h1:ogyxbiOoUXAkP+4+xa6PZSE9DZgIHtSpzjDTB9KAK34= -google.golang.org/grpc v1.42.0/go.mod h1:k+4IHHFw41K8+bbowsex27ge2rCb65oeWqe4jJ590SU= google.golang.org/grpc v1.43.0 h1:Eeu7bZtDZ2DpRCsLhUlcrLnvYaMK1Gz86a+hMVvELmM= google.golang.org/grpc v1.43.0/go.mod h1:k+4IHHFw41K8+bbowsex27ge2rCb65oeWqe4jJ590SU= google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.1.0 h1:M1YKkFIboKNieVO5DLUEVzQfGwJD30Nv2jfUgzb5UcE=
chore
Update dependencies
36273e78c6a5992963b05168f43ce281bbfb7aae
2024-11-27 00:44:52
Tom Payne
chore: Update GitHub Actions
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index f7efde3778a..0d2b6923615 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -329,7 +329,7 @@ jobs: with: cache-prefix: website-go go-version: ${{ env.GO_VERSION }} - - uses: astral-sh/setup-uv@e779db74266a80753577425b0f4ee823649f251d + - uses: astral-sh/setup-uv@d8db0a86d3d88f3017a4e6b8a1e2b234e7a0a1b5 with: enable-cache: true version: ${{ env.UV_VERSION }} @@ -512,7 +512,7 @@ jobs: with: cache-prefix: website-go go-version: ${{ env.GO_VERSION }} - - uses: astral-sh/setup-uv@e779db74266a80753577425b0f4ee823649f251d + - uses: astral-sh/setup-uv@d8db0a86d3d88f3017a4e6b8a1e2b234e7a0a1b5 with: enable-cache: true version: ${{ env.UV_VERSION }}
chore
Update GitHub Actions
afad92a5d371da739b23dfc3043a506a54893792
2022-08-08 02:41:16
Tom Payne
chore: Use set[string] instead of stringSet
false
diff --git a/pkg/chezmoi/chezmoi.go b/pkg/chezmoi/chezmoi.go index 59734db6d7b..fc0f7722860 100644 --- a/pkg/chezmoi/chezmoi.go +++ b/pkg/chezmoi/chezmoi.go @@ -80,7 +80,7 @@ var ( ) // knownPrefixedFiles is a set of known filenames with the .chezmoi prefix. -var knownPrefixedFiles = newStringSet( +var knownPrefixedFiles = newSet( Prefix+".json"+TemplateSuffix, Prefix+".toml"+TemplateSuffix, Prefix+".yaml"+TemplateSuffix, @@ -97,14 +97,14 @@ var knownPrefixedFiles = newStringSet( ) // knownPrefixedDirs is a set of known dirnames with the .chezmoi prefix. -var knownPrefixedDirs = newStringSet( +var knownPrefixedDirs = newSet( scriptsDirName, templatesDirName, ) // knownTargetFiles is a set of known target files that should not be managed // directly. -var knownTargetFiles = newStringSet( +var knownTargetFiles = newSet( "chezmoi.json", "chezmoi.toml", "chezmoi.yaml", diff --git a/pkg/chezmoi/patternset.go b/pkg/chezmoi/patternset.go index 3e2b3fdddde..ddff79ed7bb 100644 --- a/pkg/chezmoi/patternset.go +++ b/pkg/chezmoi/patternset.go @@ -28,15 +28,15 @@ const ( // An patternSet is a set of patterns. type patternSet struct { - includePatterns stringSet - excludePatterns stringSet + includePatterns set[string] + excludePatterns set[string] } // newPatternSet returns a new patternSet. func newPatternSet() *patternSet { return &patternSet{ - includePatterns: newStringSet(), - excludePatterns: newStringSet(), + includePatterns: newSet[string](), + excludePatterns: newSet[string](), } } @@ -66,7 +66,7 @@ func (ps *patternSet) add(pattern string, include patternSetIncludeType) error { // glob returns all matches in fileSystem. func (ps *patternSet) glob(fileSystem vfs.FS, prefix string) ([]string, error) { - allMatches := newStringSet() + allMatches := newSet[string]() for includePattern := range ps.includePatterns { matches, err := doublestar.Glob(fileSystem, filepath.ToSlash(prefix+includePattern)) if err != nil { diff --git a/pkg/chezmoi/set.go b/pkg/chezmoi/set.go new file mode 100644 index 00000000000..a6680508825 --- /dev/null +++ b/pkg/chezmoi/set.go @@ -0,0 +1,38 @@ +package chezmoi + +// A set is a set of elements. +type set[T comparable] map[T]struct{} + +// newSet returns a new StringSet containing elements. +func newSet[T comparable](elements ...T) set[T] { + s := make(set[T]) + s.add(elements...) + return s +} + +// add adds elements to s. +func (s set[T]) add(elements ...T) { + for _, element := range elements { + s[element] = struct{}{} + } +} + +// contains returns true if s contains element. +func (s set[T]) contains(element T) bool { + _, ok := s[element] + return ok +} + +// elements returns all the elements of s. +func (s set[T]) elements() []T { + elements := make([]T, 0, len(s)) + for element := range s { + elements = append(elements, element) + } + return elements +} + +// remove removes an element from s. +func (s set[T]) remove(element T) { + delete(s, element) +} diff --git a/pkg/chezmoi/stringset.go b/pkg/chezmoi/stringset.go deleted file mode 100644 index 9e43f9f7cb3..00000000000 --- a/pkg/chezmoi/stringset.go +++ /dev/null @@ -1,38 +0,0 @@ -package chezmoi - -// A stringSet is a set of strings. -type stringSet map[string]struct{} - -// newStringSet returns a new StringSet containing elements. -func newStringSet(elements ...string) stringSet { - s := make(stringSet) - s.add(elements...) - return s -} - -// add adds elements to s. -func (s stringSet) add(elements ...string) { - for _, element := range elements { - s[element] = struct{}{} - } -} - -// contains returns true if s contains element. -func (s stringSet) contains(element string) bool { - _, ok := s[element] - return ok -} - -// elements returns all the elements of s. -func (s stringSet) elements() []string { - elements := make([]string, 0, len(s)) - for element := range s { - elements = append(elements, element) - } - return elements -} - -// remove removes an element from s. -func (s stringSet) remove(element string) { - delete(s, element) -}
chore
Use set[string] instead of stringSet
1b789a69f047f55c71228648f323e2fe3ffd3af2
2024-10-12 07:11:10
Tom Payne
chore: Update GitHub Actions
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index c8bc1366fad..7d29f1de31c 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -204,31 +204,31 @@ jobs: args: release --skip=sign --snapshot --timeout=1h - name: upload-artifact-chezmoi-darwin-amd64 if: github.event_name == 'push' || needs.changes.outputs.code == 'true' - uses: actions/upload-artifact@84480863f228bb9747b473957fcc9e309aa96097 + uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 with: name: chezmoi-darwin-amd64 path: dist/chezmoi-nocgo_darwin_amd64_v1/chezmoi - name: upload-artifact-chezmoi-darwin-arm64 if: github.event_name == 'push' || needs.changes.outputs.code == 'true' - uses: actions/upload-artifact@84480863f228bb9747b473957fcc9e309aa96097 + uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 with: name: chezmoi-darwin-arm64 path: dist/chezmoi-nocgo_darwin_arm64/chezmoi - name: upload-artifact-chezmoi-linux-amd64 if: github.event_name == 'push' || needs.changes.outputs.code == 'true' - uses: actions/upload-artifact@84480863f228bb9747b473957fcc9e309aa96097 + uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 with: name: chezmoi-linux-amd64 path: dist/chezmoi-cgo-glibc_linux_amd64_v1/chezmoi - name: upload-artifact-chezmoi-linux-musl-amd64 if: github.event_name == 'push' || needs.changes.outputs.code == 'true' - uses: actions/upload-artifact@84480863f228bb9747b473957fcc9e309aa96097 + uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 with: name: chezmoi-linux-amd64-musl path: dist/chezmoi-cgo-musl_linux_amd64_v1/chezmoi - name: upload-artifact-chezmoi-windows-amd64.exe if: github.event_name == 'push' || needs.changes.outputs.code == 'true' - uses: actions/upload-artifact@84480863f228bb9747b473957fcc9e309aa96097 + uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 with: name: chezmoi-windows-amd64 path: dist/chezmoi-nocgo_windows_amd64_v1/chezmoi.exe
chore
Update GitHub Actions
60cc3147f16d2728341a388e6d10fd53e8c6ccd3
2024-03-30 05:09:54
Tom Payne
chore: Update GitHub Actions
false
diff --git a/.github/workflows/govulncheck.yml b/.github/workflows/govulncheck.yml index 3e4dfa9dfe2..f2b3aa78727 100644 --- a/.github/workflows/govulncheck.yml +++ b/.github/workflows/govulncheck.yml @@ -21,6 +21,6 @@ jobs: id: go-version run: | echo go-version="$(awk '/GO_VERSION:/ { print $2 }' .github/workflows/main.yml | tr -d \')" >> "${GITHUB_OUTPUT}" - - uses: golang/govulncheck-action@3a32958c2706f7048305d5a2e53633d7e37e97d0 + - uses: golang/govulncheck-action@7da72f730e37eeaad891fcff0a532d27ed737cd4 with: go-version-input: ${{ steps.go-version.outputs.go-version }} diff --git a/.github/workflows/installer.yml b/.github/workflows/installer.yml index cb56fbeca85..a48376be63a 100644 --- a/.github/workflows/installer.yml +++ b/.github/workflows/installer.yml @@ -37,7 +37,7 @@ jobs: contents: read steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 - - uses: reviewdog/action-misspell@32cdac969bc45951d79b89420a60c9b0102cf6ed + - uses: reviewdog/action-misspell@5bd7be2fc7ae56a517184f5c4bbcf2fd7afe3927 with: locale: US test-install-sh: diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index e3996bac075..1b5a5474642 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -69,7 +69,7 @@ jobs: contents: read steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 - - uses: reviewdog/action-misspell@32cdac969bc45951d79b89420a60c9b0102cf6ed + - uses: reviewdog/action-misspell@5bd7be2fc7ae56a517184f5c4bbcf2fd7afe3927 with: locale: US test-alpine: @@ -302,7 +302,7 @@ jobs: - uses: actions/setup-go@0c52d547c9bc32b1aa3301fd7a9cb496313a4491 with: go-version: ${{ env.GO_VERSION }} - - uses: actions/cache@ab5e6d0c87105b4c9c2047343972218f562e4319 + - uses: actions/cache@0c45773b623bea8c8e75f6c82b208c3cf94ea4f9 with: path: ~/go/pkg/mod key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
chore
Update GitHub Actions
7a5b1fcec7f85a8edfe0ecac130d0d99756cbfec
2023-03-12 04:19:49
Oleksandr Redko
chore: Use run.go instead of deprecated lang-version
false
diff --git a/.golangci.yml b/.golangci.yml index 883ae4cd54d..e5696974cc0 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,3 +1,6 @@ +run: + go: '1.18' + linters: enable: - asciicheck @@ -110,7 +113,6 @@ linters-settings: - prefix(github.com/twpayne/chezmoi) gofumpt: extra-rules: true - lang-version: '1.18' module-path: github.com/twpayne/chezmoi goimports: local-prefixes: github.com/twpayne/chezmoi
chore
Use run.go instead of deprecated lang-version
9dea4ea9d0d1e13e4bd8d46bc9355519ca3d4d8f
2022-07-15 04:12:03
Tom Payne
feat: Add fromToml and toToml template functions
false
diff --git a/assets/chezmoi.io/docs/reference/templates/functions/fromToml.md b/assets/chezmoi.io/docs/reference/templates/functions/fromToml.md new file mode 100644 index 00000000000..20f7154391b --- /dev/null +++ b/assets/chezmoi.io/docs/reference/templates/functions/fromToml.md @@ -0,0 +1,9 @@ +# `fromToml` *tomltext* + +`fromToml` returns the parsed value of *tomltext*. + +!!! example + + ``` + {{ (fromToml "[section]\nkey = \"value\"").section.key }} + ``` diff --git a/assets/chezmoi.io/docs/reference/templates/functions/toToml.md b/assets/chezmoi.io/docs/reference/templates/functions/toToml.md new file mode 100644 index 00000000000..337b4eb3281 --- /dev/null +++ b/assets/chezmoi.io/docs/reference/templates/functions/toToml.md @@ -0,0 +1,9 @@ +# `toToml` *value* + +`toToml` returns the TOML representation of *value*. + +!!! example + + ``` + {{ dict "key" "value" | toToml }} + ``` diff --git a/assets/chezmoi.io/mkdocs.yml b/assets/chezmoi.io/mkdocs.yml index 3304d314e13..5880bc8e0ae 100644 --- a/assets/chezmoi.io/mkdocs.yml +++ b/assets/chezmoi.io/mkdocs.yml @@ -152,6 +152,7 @@ nav: - reference/templates/functions/index.md - decrypt: reference/templates/functions/decrypt.md - encrypt: reference/templates/functions/encrypt.md + - fromToml: reference/templates/functions/fromToml.md - fromYaml: reference/templates/functions/fromYaml.md - glob: reference/templates/functions/glob.md - include: reference/templates/functions/include.md @@ -162,6 +163,7 @@ nav: - output: reference/templates/functions/output.md - quoteList: reference/templates/functions/quoteList.md - stat: reference/templates/functions/stat.md + - toToml: reference/templates/functions/toToml.md - toYaml: reference/templates/functions/toYaml.md - GitHub functions: - reference/templates/github-functions/index.md diff --git a/pkg/cmd/config.go b/pkg/cmd/config.go index 0c5e73a88d0..ebffe92da8b 100644 --- a/pkg/cmd/config.go +++ b/pkg/cmd/config.go @@ -433,6 +433,7 @@ func newConfig(options ...configOption) (*Config, error) { "bitwardenFields": c.bitwardenFieldsTemplateFunc, "decrypt": c.decryptTemplateFunc, "encrypt": c.encryptTemplateFunc, + "fromToml": c.fromTomlTemplateFunc, "fromYaml": c.fromYamlTemplateFunc, "gitHubKeys": c.gitHubKeysTemplateFunc, "gitHubLatestRelease": c.gitHubLatestReleaseTemplateFunc, @@ -465,6 +466,7 @@ func newConfig(options ...configOption) (*Config, error) { "secret": c.secretTemplateFunc, "secretJSON": c.secretJSONTemplateFunc, "stat": c.statTemplateFunc, + "toToml": c.toTomlTemplateFunc, "toYaml": c.toYamlTemplateFunc, "vault": c.vaultTemplateFunc, } { diff --git a/pkg/cmd/templatefuncs.go b/pkg/cmd/templatefuncs.go index 478b666037a..8dfe931f155 100644 --- a/pkg/cmd/templatefuncs.go +++ b/pkg/cmd/templatefuncs.go @@ -22,6 +22,14 @@ type ioregData struct { value map[string]interface{} } +func (c *Config) fromTomlTemplateFunc(s string) interface{} { + var data interface{} + if err := chezmoi.FormatTOML.Unmarshal([]byte(s), &data); err != nil { + panic(err) + } + return data +} + func (c *Config) fromYamlTemplateFunc(s string) interface{} { var data interface{} if err := chezmoi.FormatYAML.Unmarshal([]byte(s), &data); err != nil { @@ -177,6 +185,14 @@ func (c *Config) statTemplateFunc(name string) interface{} { } } +func (c *Config) toTomlTemplateFunc(data interface{}) string { + toml, err := chezmoi.FormatTOML.Marshal(data) + if err != nil { + panic(err) + } + return string(toml) +} + func (c *Config) toYamlTemplateFunc(data interface{}) string { yaml, err := chezmoi.FormatYAML.Marshal(data) if err != nil { diff --git a/pkg/cmd/testdata/scripts/templatefuncs.txt b/pkg/cmd/testdata/scripts/templatefuncs.txt index da20d2304ff..64d848933ec 100644 --- a/pkg/cmd/testdata/scripts/templatefuncs.txt +++ b/pkg/cmd/testdata/scripts/templatefuncs.txt @@ -59,6 +59,14 @@ stdout arg # test that the output template function fails if the command fails ! chezmoi execute-template '{{ output "false" }}' +# test fromToml template function +chezmoi execute-template '{{ (fromToml "[section]\nkey = \"value\"").section.key }}' +stdout '^value$' + +# test toToml template function +chezmoi execute-template '{{ dict "key" "value" | toToml }}' +stdout '^key = .value.$' + # test fromYaml chezmoi execute-template '{{ (fromYaml "key1: value1\nkey2: value2").key2 }}' stdout '^value2$'
feat
Add fromToml and toToml template functions
10ff148113d4d5ffb8343e7c35b62ff702a83df1
2024-10-01 02:26:29
Tom Payne
chore: Add missing conjunction
false
diff --git a/assets/chezmoi.io/docs/reference/commands/edit.md b/assets/chezmoi.io/docs/reference/commands/edit.md index 2312424ada3..0627dab3a50 100644 --- a/assets/chezmoi.io/docs/reference/commands/edit.md +++ b/assets/chezmoi.io/docs/reference/commands/edit.md @@ -9,8 +9,8 @@ file is re-encrypted and replaces the original file in the source state. If the operating system supports hard links, then the edit command invokes the editor with filenames which match the target filename, unless the -`edit.hardlink` configuration variable is set to `false` the `--hardlink=false` -command line flag is set. +`edit.hardlink` configuration variable is set to `false` or the +`--hardlink=false` command line flag is set. ## `-a`, `--apply`
chore
Add missing conjunction
07dd8baa1afff30409a05cbb3349e8a67239f59d
2025-01-02 03:41:48
Tom Payne
chore: Update copyright year
false
diff --git a/LICENSE b/LICENSE index ea8e16df597..a05440ff954 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2018-2024 Tom Payne +Copyright (c) 2018-2025 Tom Payne Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/assets/chezmoi.io/docs/license.md b/assets/chezmoi.io/docs/license.md index 712852afa3e..97a4ebbbec0 100644 --- a/assets/chezmoi.io/docs/license.md +++ b/assets/chezmoi.io/docs/license.md @@ -2,7 +2,7 @@ The MIT License (MIT) -Copyright (c) 2018-2024 Tom Payne +Copyright (c) 2018-2025 Tom Payne Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/assets/chezmoi.io/mkdocs.yml b/assets/chezmoi.io/mkdocs.yml index 6a8e2197aac..77651857153 100644 --- a/assets/chezmoi.io/mkdocs.yml +++ b/assets/chezmoi.io/mkdocs.yml @@ -2,7 +2,7 @@ site_name: chezmoi site_url: https://chezmoi.io site_description: Manage your dotfiles across multiple machines, securely. site_author: Tom Payne -copyright: Copyright © Tom Payne 2018-2024 +copyright: Copyright © Tom Payne 2018-2025 repo_name: twpayne/chezmoi repo_url: https://github.com/twpayne/chezmoi edit_uri: edit/master/assets/chezmoi.io/docs/
chore
Update copyright year
4b0e0780e0e22a38f2cab93f6a1ed8f27baf6b72
2022-07-08 22:48:30
Braden Hilton
chore: Ignore virtualenv in website directory
false
diff --git a/assets/chezmoi.io/.gitignore b/assets/chezmoi.io/.gitignore index 2c32b330738..b3c4a477d01 100644 --- a/assets/chezmoi.io/.gitignore +++ b/assets/chezmoi.io/.gitignore @@ -2,3 +2,8 @@ __pycache__ /docs/install.md /docs/links/articles-podcasts-and-videos.md /site + +/.venv +/.virtualenv +/venv +/virtualenv
chore
Ignore virtualenv in website directory
4d3848e8e878ea285bbdec607baa31ba673d857a
2023-03-05 15:07:47
Luke Karrys
docs: Fix `onePassword` typo
false
diff --git a/assets/chezmoi.io/docs/user-guide/password-managers/1password.md b/assets/chezmoi.io/docs/user-guide/password-managers/1password.md index 87663b13002..fb249509ccd 100644 --- a/assets/chezmoi.io/docs/user-guide/password-managers/1password.md +++ b/assets/chezmoi.io/docs/user-guide/password-managers/1password.md @@ -156,7 +156,7 @@ allows the fields to be queried by key: {{- (onepasswordDetailsFields "$UUID").password.value }} ``` -Additional fields may be obtained with `onePasswordItemFields`; not all objects +Additional fields may be obtained with `onepasswordItemFields`; not all objects in 1Password have item fields. This can be tested with: ```console
docs
Fix `onePassword` typo
949056d7a8707d221a0ffcc7794c0fc5d981e9ec
2021-12-10 20:38:09
Tom Payne
chore: Build with Go 1.17.5
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 846f0d0daa4..8111ae279a6 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -10,7 +10,7 @@ on: - v* env: AGE_VERSION: 1.0.0 - GO_VERSION: 1.17.4 + GO_VERSION: 1.17.5 GOLANGCI_LINT_VERSION: 1.43.0 jobs: changes:
chore
Build with Go 1.17.5
0931bdf88544038bfc1f1cee00033c54f10ee040
2023-06-17 05:19:33
dependabot[bot]
chore(deps): bump goreleaser/goreleaser-action from 4.2.0 to 4.3.0
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 67859aad65b..222bf4ab12c 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -201,7 +201,7 @@ jobs: make create-syso - name: build-release if: github.event_name == 'push' || needs.changes.outputs.code == 'true' - uses: goreleaser/goreleaser-action@f82d6c1c344bcacabba2c841718984797f664a6b + uses: goreleaser/goreleaser-action@336e29918d653399e599bfca99fadc1d7ffbc9f7 with: version: latest args: release --skip-publish --skip-sign --snapshot --timeout=1h @@ -407,7 +407,7 @@ jobs: - name: create-syso run: | make create-syso - - uses: goreleaser/goreleaser-action@f82d6c1c344bcacabba2c841718984797f664a6b + - uses: goreleaser/goreleaser-action@336e29918d653399e599bfca99fadc1d7ffbc9f7 with: version: latest args: release --timeout=1h
chore
bump goreleaser/goreleaser-action from 4.2.0 to 4.3.0
e220a25355b75be1f6732dc4bd7e29fd62c6b16c
2023-03-16 07:45:48
Tom Payne
chore: Rename variable for clarity
false
diff --git a/pkg/cmd/unmanagedcmd.go b/pkg/cmd/unmanagedcmd.go index d856d974fa6..6c42ce591a8 100644 --- a/pkg/cmd/unmanagedcmd.go +++ b/pkg/cmd/unmanagedcmd.go @@ -81,8 +81,8 @@ func (c *Config) runUnmanagedCmd(cmd *cobra.Command, args []string, sourceState case ignored: return vfs.SkipDir case sourceStateEntry != nil: - if origin, ok := sourceStateEntry.Origin().(*chezmoi.External); ok { - if origin.Type == chezmoi.ExternalTypeGitRepo { + if external, ok := sourceStateEntry.Origin().(*chezmoi.External); ok { + if external.Type == chezmoi.ExternalTypeGitRepo { return vfs.SkipDir } }
chore
Rename variable for clarity
de8efad77f0d9b94bf6009a8567e64a7030be953
2024-12-29 17:28:55
Tom Payne
feat: Add chezmoi:template:format-indent template directive
false
diff --git a/assets/chezmoi.io/docs/reference/templates/directives.md b/assets/chezmoi.io/docs/reference/templates/directives.md index 75531dc8677..c0e0322ed94 100644 --- a/assets/chezmoi.io/docs/reference/templates/directives.md +++ b/assets/chezmoi.io/docs/reference/templates/directives.md @@ -37,6 +37,33 @@ inherited by templates called from the file. # [[ "true" ]] ``` +## Format indent + +By default, chezmoi's `toJson`, `toToml`, and `toYaml` template functions use +the default indent of two spaces. The indent can be overidden with: + + chezmoi:template:format-indent=$STRING + +to set the indent to be the literal `$STRING`, or + + chezmoi:template:format-indent-width=$WIDTH + +to set the indent to be `$WIDTH` spaces. + +!!! example + + ``` + {{/* chezmoi:template:format-indent="\t" */}} + {{ dict "key" "value" | toJson }} + ``` + +!!! example + + ``` + {{/* chezmoi:template:format-indent-width=4 */}} + {{ dict "key" "value" | toYaml }} + ``` + ## Line endings Many of the template functions available in chezmoi primarily use UNIX-style diff --git a/go.mod b/go.mod index f876d45c885..2c477108c6a 100644 --- a/go.mod +++ b/go.mod @@ -26,6 +26,7 @@ require ( github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 github.com/itchyny/gojq v0.12.17 github.com/klauspost/compress v1.17.11 + github.com/mattn/go-runewidth v0.0.16 github.com/mitchellh/copystructure v1.2.0 github.com/mitchellh/mapstructure v1.5.0 github.com/muesli/combinator v0.3.0 @@ -132,7 +133,6 @@ require ( github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-localereader v0.0.1 // indirect - github.com/mattn/go-runewidth v0.0.16 // indirect github.com/microcosm-cc/bluemonday v1.0.27 // indirect github.com/mitchellh/reflectwalk v1.0.2 // indirect github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect diff --git a/internal/chezmoi/sourcestate_test.go b/internal/chezmoi/sourcestate_test.go index 84912064d52..e8dda2f619a 100644 --- a/internal/chezmoi/sourcestate_test.go +++ b/internal/chezmoi/sourcestate_test.go @@ -1798,6 +1798,7 @@ func TestTemplateOptionsParseDirectives(t *testing.T) { name string dataStr string expected TemplateOptions + expectedErr string expectedDataStr string }{ { @@ -1957,12 +1958,36 @@ func TestTemplateOptionsParseDirectives(t *testing.T) { LineEnding: "\n", }, }, + { + name: "format_indent_string", + dataStr: `chezmoi:template:format-indent="\t"`, + expected: TemplateOptions{ + FormatIndent: "\t", + }, + }, + { + name: "format_indent_width_number", + dataStr: `chezmoi:template:format-indent-width=2`, + expected: TemplateOptions{ + FormatIndent: " ", + }, + }, + { + name: "format_indent_width_number_error", + dataStr: `chezmoi:template:format-indent-width=x`, + expectedErr: `strconv.Atoi: parsing "x": invalid syntax`, + }, } { t.Run(tc.name, func(t *testing.T) { var actual TemplateOptions - actualData := actual.parseAndRemoveDirectives([]byte(tc.dataStr)) - assert.Equal(t, tc.expected, actual) - assert.Equal(t, tc.expectedDataStr, string(actualData)) + actualData, err := actual.parseAndRemoveDirectives([]byte(tc.dataStr)) + if tc.expectedErr != "" { + assert.EqualError(t, err, tc.expectedErr) + } else { + assert.NoError(t, err) + assert.Equal(t, tc.expected, actual) + assert.Equal(t, tc.expectedDataStr, string(actualData)) + } }) } } diff --git a/internal/chezmoi/template.go b/internal/chezmoi/template.go index 325df2dd6a7..a08a5373303 100644 --- a/internal/chezmoi/template.go +++ b/internal/chezmoi/template.go @@ -2,10 +2,16 @@ package chezmoi import ( "bytes" + "encoding/json" + "maps" + "strconv" "strings" "text/template" + "github.com/mattn/go-runewidth" "github.com/mitchellh/copystructure" + "github.com/pelletier/go-toml/v2" + "gopkg.in/yaml.v3" ) // A Template extends text/template.Template with support for directives. @@ -18,6 +24,7 @@ type Template struct { // TemplateOptions are template options that can be set with directives. type TemplateOptions struct { Funcs template.FuncMap + FormatIndent string LeftDelimiter string LineEnding string RightDelimiter string @@ -27,11 +34,45 @@ type TemplateOptions struct { // ParseTemplate parses a template named name from data with the given funcs and // templateOptions. func ParseTemplate(name string, data []byte, options TemplateOptions) (*Template, error) { - contents := options.parseAndRemoveDirectives(data) + contents, err := options.parseAndRemoveDirectives(data) + if err != nil { + return nil, err + } + funcs := options.Funcs + if options.FormatIndent != "" { + funcs = maps.Clone(funcs) + funcs["toJson"] = func(data any) string { + var builder strings.Builder + encoder := json.NewEncoder(&builder) + encoder.SetIndent("", options.FormatIndent) + if err := encoder.Encode(data); err != nil { + panic(err) + } + return builder.String() + } + funcs["toToml"] = func(data any) string { + var builder strings.Builder + encoder := toml.NewEncoder(&builder) + encoder.SetIndentSymbol(options.FormatIndent) + if err := encoder.Encode(data); err != nil { + panic(err) + } + return builder.String() + } + funcs["toYaml"] = func(data any) string { + var builder strings.Builder + encoder := yaml.NewEncoder(&builder) + encoder.SetIndent(runewidth.StringWidth(options.FormatIndent)) + if err := encoder.Encode(data); err != nil { + panic(err) + } + return builder.String() + } + } tmpl, err := template.New(name). Option(options.Options...). Delims(options.LeftDelimiter, options.RightDelimiter). - Funcs(options.Funcs). + Funcs(funcs). Parse(string(contents)) if err != nil { return nil, err @@ -71,10 +112,10 @@ func (t *Template) Execute(data any) ([]byte, error) { // parseAndRemoveDirectives updates o by parsing all template directives in data // and returns data with the lines containing directives removed. The lines are // removed so that any delimiters do not break template parsing. -func (o *TemplateOptions) parseAndRemoveDirectives(data []byte) []byte { +func (o *TemplateOptions) parseAndRemoveDirectives(data []byte) ([]byte, error) { directiveMatches := templateDirectiveRx.FindAllSubmatchIndex(data, -1) if directiveMatches == nil { - return data + return data, nil } // Parse options from directives. @@ -84,6 +125,14 @@ func (o *TemplateOptions) parseAndRemoveDirectives(data []byte) []byte { key := string(keyValuePairMatch[1]) value := maybeUnquote(string(keyValuePairMatch[2])) switch key { + case "format-indent": + o.FormatIndent = value + case "format-indent-width": + width, err := strconv.Atoi(value) + if err != nil { + return nil, err + } + o.FormatIndent = strings.Repeat(" ", width) case "left-delimiter": o.LeftDelimiter = value case "line-ending", "line-endings": @@ -105,7 +154,7 @@ func (o *TemplateOptions) parseAndRemoveDirectives(data []byte) []byte { } } - return removeMatches(data, directiveMatches) + return removeMatches(data, directiveMatches), nil } // removeMatches returns data with matchesIndexes removed. diff --git a/internal/cmd/catcmd_test.go b/internal/cmd/catcmd_test.go index d4744236194..35cee55873a 100644 --- a/internal/cmd/catcmd_test.go +++ b/internal/cmd/catcmd_test.go @@ -36,6 +36,43 @@ func TestCatCmd(t *testing.T) { "ok", ), }, + { + name: "json_indent", + root: map[string]any{ + "/home/user/.local/share/chezmoi/dot_template.tmpl": chezmoitest.JoinLines( + `# chezmoi:template:format-indent-width=3`, + `{{ dict "a" (dict "b" "c") | toJson }}`, + ), + }, + args: []string{ + "/home/user/.template", + }, + expectedStr: chezmoitest.JoinLines( + `{`, + ` "a": {`, + ` "b": "c"`, + ` }`, + `}`, + ``, + ), + }, + { + name: "yaml_indent", + root: map[string]any{ + "/home/user/.local/share/chezmoi/dot_template.tmpl": chezmoitest.JoinLines( + `# chezmoi:template:format-indent-width=3`, + `{{ dict "a" (dict "b" "c") | toYaml }}`, + ), + }, + args: []string{ + "/home/user/.template", + }, + expectedStr: chezmoitest.JoinLines( + `a:`, + ` b: c`, + ``, + ), + }, } { t.Run(tc.name, func(t *testing.T) { chezmoitest.WithTestFS(t, tc.root, func(fileSystem vfs.FS) {
feat
Add chezmoi:template:format-indent template directive
8e7bbde2c42cf26ca48096193851892506d86d7f
2022-04-04 00:34:04
Tom Payne
docs: Factor out GitHub template functions into a separate section
false
diff --git a/assets/chezmoi.io/docs/reference/templates/functions/gitHubKeys.md b/assets/chezmoi.io/docs/reference/templates/functions/gitHubKeys.md deleted file mode 100644 index 01fbbc9e469..00000000000 --- a/assets/chezmoi.io/docs/reference/templates/functions/gitHubKeys.md +++ /dev/null @@ -1,37 +0,0 @@ -# `gitHubKeys` *user* - -`gitHubKeys` returns *user*'s public SSH keys from GitHub using the GitHub API. -The returned value is a slice of structs with `.ID` and `.Key` fields. - -!!! warning - - If you use this function to populate your `~/.ssh/authorized_keys` file - then you potentially open SSH access to anyone who is able to modify or add - to your GitHub public SSH keys, possibly including certain GitHub - employees. You should not use this function on publicly-accessible machines - and should always verify that no unwanted keys have been added, for example - by using the `-v` / `--verbose` option when running `chezmoi apply` or - `chezmoi update`. - -By default, an anonymous GitHub API request will be made, which is subject to -[GitHub's rate -limits](https://docs.github.com/en/rest/overview/resources-in-the-rest-api#rate-limiting) -(currently 60 requests per hour per source IP address). If any of the -environment variables `$CHEZMOI_GITHUB_ACCESS_TOKEN`, `$GITHUB_ACCESS_TOKEN`, -or `$GITHUB_TOKEN` are found, then the first one found will be used to -authenticate the GitHub API request, with a higher rate limit (currently 5,000 -requests per hour per user). - -In practice, GitHub API rate limits are high enough that you should rarely need -to set a token, unless you are sharing a source IP address with many other -GitHub users. If needed, the GitHub documentation describes how to [create a -personal access -token](https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token). - -!!! example - - ``` - {{ range gitHubKeys "user" }} - {{- .Key }} - {{ end }} - ``` diff --git a/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubKeys.md b/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubKeys.md new file mode 100644 index 00000000000..2348b8a29ac --- /dev/null +++ b/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubKeys.md @@ -0,0 +1,22 @@ +# `gitHubKeys` *user* + +`gitHubKeys` returns *user*'s public SSH keys from GitHub using the GitHub API. +The returned value is a slice of structs with `.ID` and `.Key` fields. + +!!! warning + + If you use this function to populate your `~/.ssh/authorized_keys` file + then you potentially open SSH access to anyone who is able to modify or add + to your GitHub public SSH keys, possibly including certain GitHub + employees. You should not use this function on publicly-accessible machines + and should always verify that no unwanted keys have been added, for example + by using the `-v` / `--verbose` option when running `chezmoi apply` or + `chezmoi update`. + +!!! example + + ``` + {{ range gitHubKeys "user" }} + {{- .Key }} + {{ end }} + ``` diff --git a/assets/chezmoi.io/docs/reference/templates/functions/gitHubLatestRelease.md b/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubLatestRelease.md similarity index 87% rename from assets/chezmoi.io/docs/reference/templates/functions/gitHubLatestRelease.md rename to assets/chezmoi.io/docs/reference/templates/github-functions/gitHubLatestRelease.md index ff02288479c..ef8ce87b3e9 100644 --- a/assets/chezmoi.io/docs/reference/templates/functions/gitHubLatestRelease.md +++ b/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubLatestRelease.md @@ -8,8 +8,6 @@ bindings](https://pkg.go.dev/github.com/google/go-github/v41/github#RepositoryRe Calls to `gitHubLatestRelease` are cached so calling `gitHubLatestRelease` with the same *user-repo* will only result in one call to the GitHub API. -`gitHubLatestRelease` uses the same API request mechanism as `gitHubKeys`. - !!! example ``` diff --git a/assets/chezmoi.io/docs/reference/templates/github-functions/index.md b/assets/chezmoi.io/docs/reference/templates/github-functions/index.md new file mode 100644 index 00000000000..d707581e04e --- /dev/null +++ b/assets/chezmoi.io/docs/reference/templates/github-functions/index.md @@ -0,0 +1,18 @@ +# GitHub functions + +The `gitHub*` template functions return data from the GitHub API. + +By default, an anonymous GitHub API request will be made, which is subject to +[GitHub's rate +limits](https://docs.github.com/en/rest/overview/resources-in-the-rest-api#rate-limiting) +(currently 60 requests per hour per source IP address). If any of the +environment variables `$CHEZMOI_GITHUB_ACCESS_TOKEN`, `$GITHUB_ACCESS_TOKEN`, or +`$GITHUB_TOKEN` are found, then the first one found will be used to authenticate +the GitHub API request, with a higher rate limit (currently 5,000 requests per +hour per user). + +In practice, GitHub API rate limits are high enough that you should rarely need +to set a token, unless you are sharing a source IP address with many other +GitHub users. If needed, the GitHub documentation describes how to [create a +personal access +token](https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token). diff --git a/assets/chezmoi.io/mkdocs.yml b/assets/chezmoi.io/mkdocs.yml index 7f60163b49e..7e33da067d8 100644 --- a/assets/chezmoi.io/mkdocs.yml +++ b/assets/chezmoi.io/mkdocs.yml @@ -151,8 +151,6 @@ nav: - decrypt: reference/templates/functions/decrypt.md - encrypt: reference/templates/functions/encrypt.md - fromYaml: reference/templates/functions/fromYaml.md - - gitHubKeys: reference/templates/functions/gitHubKeys.md - - gitHubLatestRelease: reference/templates/functions/gitHubLatestRelease.md - include: reference/templates/functions/include.md - ioreg: reference/templates/functions/ioreg.md - joinPath: reference/templates/functions/joinPath.md @@ -161,6 +159,10 @@ nav: - output: reference/templates/functions/output.md - stat: reference/templates/functions/stat.md - toYaml: reference/templates/functions/toYaml.md + - GitHub functions: + - reference/templates/github-functions/index.md + - gitHubKeys: reference/templates/github-functions/gitHubKeys.md + - gitHubLatestRelease: reference/templates/github-functions/gitHubLatestRelease.md - Init functions: - reference/templates/init-functions/index.md - exit: reference/templates/init-functions/exit.md
docs
Factor out GitHub template functions into a separate section
c56244f28f502ae36a9657248e3614a03f2df392
2021-10-08 05:29:46
Tom Payne
chore: Add link to blog post
false
diff --git a/docs/MEDIA.md b/docs/MEDIA.md index 3ac5b54915d..9cf422bcf6f 100644 --- a/docs/MEDIA.md +++ b/docs/MEDIA.md @@ -13,6 +13,7 @@ Recommended podcast: [Managing Dot Files and an Introduction to Chezmoi](https:/ | Date | Version | Format | Link | | ---------- | ------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 2021-09-18 | 2.1.2 | Audio/text | [PBS 125 of X — Chezmoi on Multiple Computers](https://pbs.bartificer.net/pbs125) | +| 2021-09-14 | 2.2.0 | Text | [Managing preference plists under Chezmoi](https://zacwe.st/2021/09/14/managing-preference-plists-under-chezmoi/) | | 2021-09-06 | 2.2.0 | Video | [chezmoi: Organize your dotfiles across multiple computers \| Let's Code](https://www.youtube.com/watch?v=L_Y3s0PS_Cg) | | 2021-09-06 | 2.2.0 | Text | [chezmoi dotfile management](https://www.jacobbolda.com/chezmoi-dotfile-management) | | 2021-09-04 | 2.2.0 | Text | [Configuration Management](https://cj.rs/blog/my-setup/chezmoi/) |
chore
Add link to blog post
ec9e8f60db220637ae96b833f0695ee916ccc07d
2021-12-24 03:09:22
Tom Payne
docs: Improve FAQs on use of chezmoi edit
false
diff --git a/docs/FAQ.md b/docs/FAQ.md index f3e4b39e7a4..bf77401c191 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -69,35 +69,43 @@ There are four popular approaches: ## Do I have to use `chezmoi edit` to edit my dotfiles? No. `chezmoi edit` is a convenience command that has a couple of useful -features, but you don't have to use it. You can also run `chezmoi cd` and then -just edit the files in the source state directly. After saving an edited file -you can run `chezmoi diff` to check what effect the changes would have, and run -`chezmoi apply` if you're happy with them. +features, but you don't have to use it. + +You can also run `chezmoi cd` and then just edit the files in the source state +directly. After saving an edited file you can run `chezmoi diff` to check what +effect the changes would have, and run `chezmoi apply` if you're happy with +them. If there are inconsistencies that you want to keep, then `chezmoi +merge-all` will help you resolve any differences. `chezmoi edit` provides the following useful features: -* It opens the correct file in the source state for you with a filename matching - the target filename, so your editor's syntax highlighting will work and you - don't have to know anything about source state attributes. +* The arguments to `chezmoi edit` are the files in their target location, so you + don't have to think about source state attributes and your editor's syntax + highlighting will work. * If the dotfile is encrypted in the source state, then `chezmoi edit` will decrypt it to a private directory, open that file in your `$EDITOR`, and then - re-encrypt the file when you quit your editor. That makes encryption more - transparent to the user. With the `--diff` and `--apply` options you can see - what would change and apply those changes without having to run `chezmoi diff` - or `chezmoi apply`. Note also that the arguments to `chezmoi edit` are the - files in their target location. + re-encrypt the file when you quit your editor. That makes encryption + transparent. +* With the `--diff` and `--apply` options you can see what would change and + apply those changes without having to run `chezmoi diff` or `chezmoi apply`. + +If you chose to edit files in the source state and you're using VIM then then +[`github.com/alker0/chezmoi.vim`](https://github.com/alker0/chezmoi.vim) gives +you syntax highlighting, however you edit your files. --- ## Why do I get a blank buffer when running `chezmoi edit`? -The problem here is that your editor is forking, detaching, and terminating the -original process, which chezmoi cannot distinguish from the editor terminating -normally. +What's happening here is that your editor is forking, detaching, and terminating +the original process, which chezmoi cannot distinguish from the editor +terminating normally. You have two options: -1. Configure your editor command to remain in the foreground by passing the `-f` - flag to `mvim`, e.g. by setting the `edit.flags` configuration variable to - `["-f"]`, or by setting the `EDITOR` environment variable to `mvim -f`. +1. Configure your editor command to remain in the foreground. For `vim`, this + means passing the `-f` flag, e.g. by setting the `edit.flags` configuration + variable to `["-f"]`, or by setting the `EDITOR` environment variable to + include the `-f` flag, e.g. `export EDITOR="mvim -f"`. For VSCode, pass the + `--wait` flag. 2. Set the `edit.hardlink` configuration variable to `false`. ---
docs
Improve FAQs on use of chezmoi edit
304f52ab4c3fabf3c71b8593549ffaaa947c7979
2022-06-30 06:31:04
Tom Payne
fix: Fix merge command for encrypted files in subdirectories
false
diff --git a/pkg/cmd/mergecmd.go b/pkg/cmd/mergecmd.go index ded86217bcc..722e52578f3 100644 --- a/pkg/cmd/mergecmd.go +++ b/pkg/cmd/mergecmd.go @@ -79,6 +79,9 @@ func (c *Config) doMerge(targetRelPath chezmoi.RelPath, sourceStateEntry chezmoi if plaintext, err = sourceStateFile.Contents(); err != nil { return } + if err = chezmoi.MkdirAll(c.baseSystem, plaintextAbsPath.Dir(), 0o700); err != nil { + return + } if err = c.baseSystem.WriteFile(plaintextAbsPath, plaintext, 0o600); err != nil { return } diff --git a/pkg/cmd/testdata/scripts/mergeencryptedage_unix.txt b/pkg/cmd/testdata/scripts/mergeencryptedage_unix.txt index 44840cd578b..ab181264edc 100644 --- a/pkg/cmd/testdata/scripts/mergeencryptedage_unix.txt +++ b/pkg/cmd/testdata/scripts/mergeencryptedage_unix.txt @@ -6,17 +6,16 @@ appendline $CHEZMOICONFIGDIR/chezmoi.toml '[merge]' appendline $CHEZMOICONFIGDIR/chezmoi.toml ' command = "cat"' # test that chezmoi merge works on files encrypted with age -exec cat $CHEZMOICONFIGDIR/chezmoi.toml -chezmoi add --encrypt $HOME${/}.file -exists $CHEZMOISOURCEDIR/encrypted_dot_file.age -edit $HOME${/}.file -chezmoi merge $HOME${/}.file +chezmoi add --encrypt $HOME${/}.dir/file +exists $CHEZMOISOURCEDIR/dot_dir/encrypted_file.age +edit $HOME${/}.dir/file +chezmoi merge $HOME${/}.dir/file cmp stdout golden/merge -- golden/merge -- -# contents of .file +# contents of .dir/file # edited -# contents of .file -# contents of .file --- home/user/.file -- -# contents of .file +# contents of .dir/file +# contents of .dir/file +-- home/user/.dir/file -- +# contents of .dir/file
fix
Fix merge command for encrypted files in subdirectories
6e87b936dfd400267a9aa457c18aff29e924ff79
2022-02-16 05:15:55
Tom Payne
docs: Remove unnecessary parentheses
false
diff --git a/assets/chezmoi.io/docs/links/articles-podcasts-and-videos.md.tmpl b/assets/chezmoi.io/docs/links/articles-podcasts-and-videos.md.tmpl index 0431a5834ad..27eda7ff169 100644 --- a/assets/chezmoi.io/docs/links/articles-podcasts-and-videos.md.tmpl +++ b/assets/chezmoi.io/docs/links/articles-podcasts-and-videos.md.tmpl @@ -14,7 +14,7 @@ | Date | Version | Format | Link | | ---- | ------- | ------ | ---- | -{{- range (mustReverse .articles) }} +{{- range mustReverse .articles }} {{- $format := index . "format" | default "Text" }} {{- $lang := index . "lang" | default "EN" }} {{- if ne $lang "EN" }} diff --git a/assets/chezmoi.io/docs/reference/templates/functions/bitwarden.md b/assets/chezmoi.io/docs/reference/templates/functions/bitwarden.md index 52b75ca1293..07b99e5c8fa 100644 --- a/assets/chezmoi.io/docs/reference/templates/functions/bitwarden.md +++ b/assets/chezmoi.io/docs/reference/templates/functions/bitwarden.md @@ -10,6 +10,6 @@ will only invoke `bw` once. !!! example ``` - username = {{ (bitwarden "item" "<itemid>").login.username }} - password = {{ (bitwarden "item" "<itemid>").login.password }} + username = {{ bitwarden "item" "<itemid>".login.username }} + password = {{ bitwarden "item" "<itemid>".login.password }} ``` diff --git a/assets/chezmoi.io/docs/reference/templates/functions/bitwardenAttachment.md b/assets/chezmoi.io/docs/reference/templates/functions/bitwardenAttachment.md index b6e56f008b1..72c9082849c 100644 --- a/assets/chezmoi.io/docs/reference/templates/functions/bitwardenAttachment.md +++ b/assets/chezmoi.io/docs/reference/templates/functions/bitwardenAttachment.md @@ -11,5 +11,5 @@ only invoke `bw` once. !!! example ``` - {{- (bitwardenAttachment "<filename>" "<itemid>") -}} + {{- bitwardenAttachment "<filename>" "<itemid>" -}} ``` diff --git a/assets/chezmoi.io/docs/reference/templates/functions/gitHubKeys.md b/assets/chezmoi.io/docs/reference/templates/functions/gitHubKeys.md index e38e69e316f..01fbbc9e469 100644 --- a/assets/chezmoi.io/docs/reference/templates/functions/gitHubKeys.md +++ b/assets/chezmoi.io/docs/reference/templates/functions/gitHubKeys.md @@ -31,7 +31,7 @@ token](https://docs.github.com/en/github/authenticating-to-github/creating-a-per !!! example ``` - {{ range (gitHubKeys "user") }} + {{ range gitHubKeys "user" }} {{- .Key }} {{ end }} ``` diff --git a/assets/chezmoi.io/docs/reference/templates/functions/ioreg.md b/assets/chezmoi.io/docs/reference/templates/functions/ioreg.md index ec62c0cb5f7..dc290d76ed4 100644 --- a/assets/chezmoi.io/docs/reference/templates/functions/ioreg.md +++ b/assets/chezmoi.io/docs/reference/templates/functions/ioreg.md @@ -11,7 +11,7 @@ will only execute the `ioreg -a -l` command once. !!! example ``` - {{ if (eq .chezmoi.os "darwin") }} - {{ $serialNumber := index ioreg "IORegistryEntryChildren" 0 "IOPlatformSerialNumber" }} + {{ if (q .chezmoi.os "darwin" }} + {{ $serialNumber := index ioreg "IORegistryEntryChildren" 0 "IOPlatformSerialNumber" }} {{ end }} ``` diff --git a/assets/chezmoi.io/docs/user-guide/machines/general.md b/assets/chezmoi.io/docs/user-guide/machines/general.md index 50680c72bb6..c5745f43f66 100644 --- a/assets/chezmoi.io/docs/user-guide/machines/general.md +++ b/assets/chezmoi.io/docs/user-guide/machines/general.md @@ -7,15 +7,15 @@ The following template sets the `$chassisType` variable to `"desktop"` or ``` {{- $chassisType := "desktop" }} -{{- if (eq .chezmoi.os "darwin") }} +{{- if eq .chezmoi.os "darwin" }} {{- if contains "MacBook" (output "sysctl" "-n" "hw.model") }} {{- $chassisType = "laptop" }} {{- else }} {{- $chassisType = "desktop" }} {{- end }} -{{- else if (eq .chezmoi.os "linux") }} +{{- else if eq .chezmoi.os "linux" }} {{- $chassisType = (output "hostnamectl" "--json=short" | mustFromJson).Chassis }} -{{- else if (eq .chezmoi.os "windows") }} +{{- else if eq .chezmoi.os "windows" }} {{- $chassisType = (output "powershell.exe" "-noprofile" "-command" "if (Get-WmiObject -Class win32_battery -ComputerName localhost) { echo laptop } else { echo desktop }") }} {{- end }} ``` diff --git a/assets/chezmoi.io/docs/user-guide/machines/macos.md b/assets/chezmoi.io/docs/user-guide/machines/macos.md index 67b2fd8c75e..7a39df3c5a6 100644 --- a/assets/chezmoi.io/docs/user-guide/machines/macos.md +++ b/assets/chezmoi.io/docs/user-guide/machines/macos.md @@ -10,7 +10,7 @@ source directory called `run_once_before_install-packages-darwin.sh.tmpl` containing: ``` -{{- if (eq .chezmoi.os "darwin") -}} +{{- if eq .chezmoi.os "darwin" -}} #!/bin/bash brew bundle --no-lock --file=/dev/stdin <<EOF @@ -26,9 +26,9 @@ EOF document. chezmoi will run this script whenever its contents change, i.e. when you add or remove brews or casks. -### Determine the hostname +## Determine the hostname -The result of the command `hostname` on macOS depends on the network that the +The result of the `hostname` command on macOS depends on the network that the machine is connected to. For a stable result, use the `scutil` command: ``` diff --git a/assets/chezmoi.io/docs/user-guide/machines/windows.md b/assets/chezmoi.io/docs/user-guide/machines/windows.md index 292b6984fa3..f289241bade 100644 --- a/assets/chezmoi.io/docs/user-guide/machines/windows.md +++ b/assets/chezmoi.io/docs/user-guide/machines/windows.md @@ -7,7 +7,7 @@ WSL can be detected by looking for the string `Microsoft` or `microsoft` in `.chezmoi.kernel.osrelease`, for example: ``` -{{ if (eq .chezmoi.os "linux") }} +{{ if eq .chezmoi.os "linux" }} {{ if (.chezmoi.kernel.osrelease | lower | contains "microsoft") }} # WSL-specific code {{ end }} diff --git a/assets/chezmoi.io/docs/user-guide/manage-different-types-of-file.md b/assets/chezmoi.io/docs/user-guide/manage-different-types-of-file.md index 27bdf81f76a..72a6c8837c3 100644 --- a/assets/chezmoi.io/docs/user-guide/manage-different-types-of-file.md +++ b/assets/chezmoi.io/docs/user-guide/manage-different-types-of-file.md @@ -143,7 +143,7 @@ populating your `~/.ssh/authorized_keys`. Put the following in your GitHub username: ``` -{{ range (gitHubKeys "username") -}} +{{ range gitHubKeys "username" -}} {{ .Key }} {{ end -}} ``` diff --git a/assets/chezmoi.io/docs/user-guide/setup.md b/assets/chezmoi.io/docs/user-guide/setup.md index d900f864a7e..4b4fa8a38ed 100644 --- a/assets/chezmoi.io/docs/user-guide/setup.md +++ b/assets/chezmoi.io/docs/user-guide/setup.md @@ -119,7 +119,7 @@ example template logic: ``` {{- $email := "" -}} -{{- if (hasKey . "email") -}} +{{- if hasKey . "email" -}} {{- $email = .email -}} {{- else -}} {{- $email = promptString "email" -}} diff --git a/assets/chezmoi.io/docs/user-guide/templating.md b/assets/chezmoi.io/docs/user-guide/templating.md index a4da9ff5d7b..0f419c1b223 100644 --- a/assets/chezmoi.io/docs/user-guide/templating.md +++ b/assets/chezmoi.io/docs/user-guide/templating.md @@ -133,9 +133,9 @@ Conditional expressions can be written using `if`, `else if`, `else`, and `end`, for example: ``` -{{ if (eq .chezmoi.os "darwin") }} +{{ if eq .chezmoi.os "darwin" }} # darwin -{{ else if (eq .chezmoi.os "linux" ) }} +{{ else if eq .chezmoi.os "linux" }} # linux {{ else }} # other operating system
docs
Remove unnecessary parentheses
f72bac8f8110ba489fd15d6ee6406950f54705d2
2022-06-24 22:10:16
Tom Payne
chore: Add test for merge command with age-encrypted file
false
diff --git a/pkg/cmd/testdata/scripts/mergeencryptedage_unix.txt b/pkg/cmd/testdata/scripts/mergeencryptedage_unix.txt new file mode 100644 index 00000000000..44840cd578b --- /dev/null +++ b/pkg/cmd/testdata/scripts/mergeencryptedage_unix.txt @@ -0,0 +1,22 @@ +[windows] skip 'UNIX only' +[!exec:age] skip 'age not found in $PATH' + +mkageconfig +appendline $CHEZMOICONFIGDIR/chezmoi.toml '[merge]' +appendline $CHEZMOICONFIGDIR/chezmoi.toml ' command = "cat"' + +# test that chezmoi merge works on files encrypted with age +exec cat $CHEZMOICONFIGDIR/chezmoi.toml +chezmoi add --encrypt $HOME${/}.file +exists $CHEZMOISOURCEDIR/encrypted_dot_file.age +edit $HOME${/}.file +chezmoi merge $HOME${/}.file +cmp stdout golden/merge + +-- golden/merge -- +# contents of .file +# edited +# contents of .file +# contents of .file +-- home/user/.file -- +# contents of .file diff --git a/pkg/cmd/testdata/scripts/mergeencrypted_unix.txt b/pkg/cmd/testdata/scripts/mergeencryptedgpg_unix.txt similarity index 100% rename from pkg/cmd/testdata/scripts/mergeencrypted_unix.txt rename to pkg/cmd/testdata/scripts/mergeencryptedgpg_unix.txt
chore
Add test for merge command with age-encrypted file
d47526b61c5e96960ab157db554bc0f859f14fda
2021-10-20 21:29:20
Tom Payne
chore: Remove gops
false
diff --git a/docs/REFERENCE.md b/docs/REFERENCE.md index d9ee3ec1c2c..d410b5091c2 100644 --- a/docs/REFERENCE.md +++ b/docs/REFERENCE.md @@ -31,7 +31,6 @@ Manage your dotfiles across multiple machines, securely. * [Developer command line flags](#developer-command-line-flags) * [`--cpu-profile` *filename*](#--cpu-profile-filename) * [`--debug`](#--debug) - * [`--gops`](#--gops) * [Configuration file](#configuration-file) * [Variables](#variables) * [Examples](#examples) @@ -303,12 +302,7 @@ Write a [Go CPU profile](https://blog.golang.org/pprof) to *filename*. Log information helpful for debugging. -### `--gops` - -Enable the [gops](https://github.com/google/gops) agent. - - - --- +--- ## Configuration file diff --git a/go.mod b/go.mod index 3de04ac5b3b..807259b1b66 100644 --- a/go.mod +++ b/go.mod @@ -14,7 +14,6 @@ require ( github.com/danieljoos/wincred v1.1.2 // indirect github.com/go-git/go-git/v5 v5.4.2 github.com/google/go-github/v39 v39.2.0 - github.com/google/gops v0.3.21 github.com/google/renameio/v2 v2.0.0 github.com/google/uuid v1.3.0 // indirect github.com/huandu/xstrings v1.3.2 // indirect diff --git a/go.sum b/go.sum index b446bb0d1c8..28400cecc96 100644 --- a/go.sum +++ b/go.sum @@ -63,7 +63,6 @@ github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAE github.com/ProtonMail/go-crypto v0.0.0-20210428141323-04723f9f07d7/go.mod h1:z4/9nQmJSSwwds7ejkxaJwO37dru3geImFUdJlaLzQo= github.com/ProtonMail/go-crypto v0.0.0-20210920160938-87db9fbc61c7 h1:DSqTh6nEes/uO8BlNcGk8PzZsxY2sN9ZL//veWBdTRI= github.com/ProtonMail/go-crypto v0.0.0-20210920160938-87db9fbc61c7/go.mod h1:z4/9nQmJSSwwds7ejkxaJwO37dru3geImFUdJlaLzQo= -github.com/StackExchange/wmi v1.2.1/go.mod h1:rcmrprowKIVzvc+NUiLncP2uuArMWLCbu9SBzvHz7e8= github.com/acomagu/bufpipe v1.0.3 h1:fxAGrHZTgQ9w5QqVItgzwj235/uYZYgbXitB+dLupOk= github.com/acomagu/bufpipe v1.0.3/go.mod h1:mxdxdup/WdsKVreO5GpW4+M/1CE2sMG4jeGJ2sYmHc4= github.com/alecthomas/assert v0.0.0-20170929043011-405dbfeb8e38/go.mod h1:r7bzyVFMNntcxPZXK3/+KdruV1H5KSlyVY0gc+NgInI= @@ -150,8 +149,6 @@ github.com/go-git/go-git/v5 v5.4.2/go.mod h1:gQ1kArt6d+n+BGd+/B/I74HwRTLhth2+zti github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= -github.com/go-ole/go-ole v1.2.5/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= -github.com/go-ole/go-ole v1.2.6-0.20210915003542-8b1f7f90f6b1/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= github.com/godbus/dbus/v5 v5.0.3/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/godbus/dbus/v5 v5.0.5 h1:9Eg0XUhQxtkV8ykTMKtMMYY72g4NgxtRq4jgh4Ih5YM= @@ -209,8 +206,6 @@ github.com/google/go-github/v39 v39.2.0/go.mod h1:C1s8C5aCC9L+JXIYpJM5GYytdX52vC github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8= github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/gops v0.3.21 h1:SmULDdFdSLaPZHR3FgPJfNFfrrohoHUgC9DenFuGrUE= -github.com/google/gops v0.3.21/go.mod h1:7diIdLsqpCihPSX3fQagksT/Ku/y4RL9LHTlKyEUDl8= github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= github.com/google/martian/v3 v3.1.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= @@ -294,7 +289,6 @@ github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfV github.com/kevinburke/ssh_config v0.0.0-20201106050909-4977a11b4351/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM= github.com/kevinburke/ssh_config v1.1.0 h1:pH/t1WS9NzT8go394IqZeJTMHVm6Cr6ZJ6AQ+mdNo/o= github.com/kevinburke/ssh_config v1.1.0/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM= -github.com/keybase/go-ps v0.0.0-20190827175125-91aafc93ba19/go.mod h1:hY+WOq6m2FpbvyrI93sMaypsttvaIL5nhVR92dTMUcQ= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= @@ -399,7 +393,6 @@ github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0= github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= -github.com/shirou/gopsutil/v3 v3.21.9/go.mod h1:YWp/H8Qs5fVmf17v7JNZzA0mPJ+mS2e9JdiUF9LlKzQ= github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= github.com/shopspring/decimal v1.3.0 h1:KK3gWIXskZ2O1U/JNTisNcvH+jveJxZYrjbTsrbbnh8= github.com/shopspring/decimal v1.3.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= @@ -436,8 +429,6 @@ github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5Cc github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= -github.com/tklauser/go-sysconf v0.3.9/go.mod h1:11DU/5sG7UexIrp/O6g35hrWzu0JxlwQ3LSFUzyeuhs= -github.com/tklauser/numcpus v0.3.0/go.mod h1:yFGUr7TUHQRAhyqBcEg0Ge34zDBAsIvJJcyE6boqnA8= github.com/twpayne/go-shell v0.3.0 h1:nhDM9cQTqWwA0jGPOnqzsw8lke2jcKpvxDgnDO8Lq9o= github.com/twpayne/go-shell v0.3.0/go.mod h1:H/gzux0DOH5jsjQSHXs6rs2Onxy+V4j6ycZTOulC0l8= github.com/twpayne/go-vfs/v3 v3.0.0 h1:rMFBISZVhSowKeX1BxL8utM64V7CuUw9/rfekPdS7to= @@ -449,7 +440,6 @@ github.com/twpayne/go-xdg/v6 v6.0.0/go.mod h1:XlfiGBU0iBxudVRWh+SXF+I1Cfb7rMq1IF github.com/xanzy/ssh-agent v0.3.0/go.mod h1:3s9xbODqPuuhK9JV1R321M/FlMZSBvE5aY6eAcqrDh0= github.com/xanzy/ssh-agent v0.3.1 h1:AmzO1SSWxw73zxFZPRwaMN1MohDw8UyHnmuxyceTEGo= github.com/xanzy/ssh-agent v0.3.1/go.mod h1:QIE4lCeL7nkC25x+yA3LBIYfwCc1TFziCtG7cBAac6w= -github.com/xlab/treeprint v1.1.0/go.mod h1:gj5Gd3gPdKtR1ikdDK6fnFLdmIS0X30kTTuNd/WEJu0= github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= @@ -667,11 +657,9 @@ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210816074244-15123e1e1f71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210816183151-1e6c022a8912/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210819135213-f52c844e1c1c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210823070655-63515b42dcdf/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210902050250-f475640dd07b/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210903071746-97244b99971b/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211019181941-9d821ace8654 h1:id054HUawV2/6IGm2IV8KZQjqtwAOo2CYlOToYqa0d0= golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -915,6 +903,5 @@ honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9 howett.net/plist v0.0.0-20201203080718-1454fab16a06 h1:QDxUo/w2COstK1wIBYpzQlHX/NqaQTcf9jyz347nI58= howett.net/plist v0.0.0-20201203080718-1454fab16a06/go.mod h1:vMygbs4qMhSZSc4lCUl2OEE+rDiIIJAIdR4m7MiMcm0= rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= -rsc.io/goversion v1.2.0/go.mod h1:Eih9y/uIBS3ulggl7KNJ09xGSLcuNaLgmvvqa07sgfo= rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= diff --git a/internal/cmd/config.go b/internal/cmd/config.go index 6b331c8c805..8cc7f239791 100644 --- a/internal/cmd/config.go +++ b/internal/cmd/config.go @@ -27,7 +27,6 @@ import ( "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/mitchellh/mapstructure" "github.com/rs/zerolog" "github.com/rs/zerolog/log" @@ -85,7 +84,6 @@ type Config struct { debug bool dryRun bool force bool - gops bool homeDir string keepGoing bool noPager bool @@ -576,7 +574,6 @@ func (c *Config) close() error { err = multierr.Append(err, err2) } pprof.StopCPUProfile() - agent.Close() return err } @@ -1194,7 +1191,6 @@ func (c *Config) newRootCmd() (*cobra.Command, error) { persistentFlags.BoolVar(&c.debug, "debug", c.debug, "Include debug information in output") persistentFlags.BoolVarP(&c.dryRun, "dry-run", "n", c.dryRun, "Do not make any modifications to the destination directory") persistentFlags.BoolVar(&c.force, "force", c.force, "Make all changes without prompting") - persistentFlags.BoolVar(&c.gops, "gops", c.gops, "Enable gops agent") persistentFlags.BoolVarP(&c.keepGoing, "keep-going", "k", c.keepGoing, "Keep going as far as possible after an error") persistentFlags.BoolVar(&c.noPager, "no-pager", c.noPager, "Do not use the pager") persistentFlags.BoolVar(&c.noTTY, "no-tty", c.noTTY, "Do not attempt to get a TTY for reading passwords") @@ -1208,7 +1204,6 @@ func (c *Config) newRootCmd() (*cobra.Command, error) { rootCmd.MarkPersistentFlagFilename("cpu-profile"), persistentFlags.MarkHidden("cpu-profile"), rootCmd.MarkPersistentFlagDirname("destination"), - persistentFlags.MarkHidden("gops"), rootCmd.MarkPersistentFlagFilename("output"), persistentFlags.MarkHidden("safe"), rootCmd.MarkPersistentFlagDirname("source"), @@ -1377,13 +1372,6 @@ func (c *Config) persistentPreRunRootE(cmd *cobra.Command, args []string) error } } - // Enable gops if configured. - if c.gops { - if err := agent.Listen(agent.Options{}); err != nil { - return err - } - } - // Read the config file. if err := c.readConfig(); err != nil { if !boolAnnotation(cmd, doesNotRequireValidConfig) {
chore
Remove gops
fc9c384a2b0019df4e05c453c5e34c9173b2be4f
2022-10-10 17:33:48
Tom Payne
chore: Automatically deploy website after release
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 3828f1209eb..d0d182b89c5 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -416,6 +416,21 @@ jobs: gh release upload v${VERSION} dist/checksums.txt env: GITHUB_TOKEN: ${{ secrets.GORELEASER_GITHUB_TOKEN }} + deploy-website: + needs: + - release + runs-on: ubuntu-20.04 + steps: + - uses: actions/checkout@2541b1294d2704b0964813337f33b291d3f8596b + with: + fetch-depth: 0 + - name: prepare-chezmoi.io + run: | + pip3 install mkdocs-material mkdocs-mermaid2-plugin mkdocs-redirects mkdocs-simple-hooks + ( cd assets/chezmoi.io && mkdocs build ) + - name: push-chezmoi.io + run: | + ( cd assets/chezmoi.io && mkdocs gh-deploy ) - name: prepare-get.chezmoi.io run: | cp assets/scripts/install.sh assets/get.chezmoi.io/index.html
chore
Automatically deploy website after release
82900a6f1c51d20800886e8db6f6b31c4b2273df
2021-10-22 01:43:17
Tom Payne
chore: Fix GitHub Actions runs-on to specific OS versions
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 97867a3b3fa..7c87f3e98bc 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -12,7 +12,7 @@ env: GOLANGCI_LINT_VERSION: 1.42.1 jobs: test-archlinux: - runs-on: ubuntu-latest + runs-on: ubuntu-20.04 steps: - name: Checkout uses: actions/checkout@v2 @@ -20,7 +20,7 @@ jobs: run: | ( cd assets/docker && ./test.sh archlinux ) test-debian-i386: - runs-on: macos-latest + runs-on: macos-10.15 env: VAGRANT_BOX: debian11-i386 steps: @@ -37,7 +37,7 @@ jobs: run: | ( cd assets/vagrant && ./test.sh debian11-i386 ) test-fedora: - runs-on: ubuntu-latest + runs-on: ubuntu-20.04 steps: - name: Checkout uses: actions/checkout@v2 @@ -45,7 +45,7 @@ jobs: run: | ( cd assets/docker && ./test.sh fedora ) test-freebsd: - runs-on: macos-latest + runs-on: macos-10.15 env: VAGRANT_BOX: freebsd13 steps: @@ -62,7 +62,7 @@ jobs: run: | ( cd assets/vagrant && ./test.sh freebsd13 ) test-macos: - runs-on: macos-latest + runs-on: macos-11 steps: - name: Set up Go uses: actions/setup-go@v2 @@ -92,7 +92,7 @@ jobs: - name: Test run: go test -race ./... test-openbsd: - runs-on: macos-latest + runs-on: macos-10.15 env: VAGRANT_BOX: openbsd6 steps: @@ -109,7 +109,7 @@ jobs: run: | ( cd assets/vagrant && ./test.sh openbsd6 ) test-openindiana: - runs-on: macos-latest + runs-on: macos-10.15 env: VAGRANT_BOX: openindiana steps: @@ -237,7 +237,7 @@ jobs: - name: Test run: go test ./... test-windows: - runs-on: windows-latest + runs-on: windows-2019 steps: - name: Set up Go uses: actions/setup-go@v2 @@ -278,7 +278,7 @@ jobs: - name: Test run: go test -race ./... test-voidlinux: - runs-on: ubuntu-latest + runs-on: ubuntu-20.04 steps: - name: Checkout uses: actions/checkout@v2
chore
Fix GitHub Actions runs-on to specific OS versions
bb771a0fc8b035ddf3b6bcea838e7a7e8a02e0ab
2022-01-29 04:58:13
Tom Payne
chore: Add systeminfo check to doctor command
false
diff --git a/pkg/cmd/doctorcmd.go b/pkg/cmd/doctorcmd.go index ae10359e1ee..10c57abc33b 100644 --- a/pkg/cmd/doctorcmd.go +++ b/pkg/cmd/doctorcmd.go @@ -142,6 +142,7 @@ func (c *Config) runDoctorCmd(cmd *cobra.Command, args []string) error { }, osArchCheck{}, unameCheck{}, + systeminfoCheck{}, goVersionCheck{}, executableCheck{}, upgradeMethodCheck{}, diff --git a/pkg/cmd/doctorcmd_unix.go b/pkg/cmd/doctorcmd_unix.go index f8e480447ab..3aea646afd5 100644 --- a/pkg/cmd/doctorcmd_unix.go +++ b/pkg/cmd/doctorcmd_unix.go @@ -15,8 +15,9 @@ import ( ) type ( - umaskCheck struct{} - unameCheck struct{} + systeminfoCheck struct{ skippedCheck } + umaskCheck struct{} + unameCheck struct{} ) func (umaskCheck) Name() string { diff --git a/pkg/cmd/doctorcmd_windows.go b/pkg/cmd/doctorcmd_windows.go index a236b9aef2e..2803987bbaf 100644 --- a/pkg/cmd/doctorcmd_windows.go +++ b/pkg/cmd/doctorcmd_windows.go @@ -1,6 +1,43 @@ package cmd +import ( + "bufio" + "bytes" + "fmt" + "os/exec" + "strings" + + "github.com/twpayne/chezmoi/v2/pkg/chezmoi" +) + type ( - umaskCheck struct{ skippedCheck } - unameCheck struct{ skippedCheck } + systeminfoCheck struct{} + umaskCheck struct{ skippedCheck } + unameCheck struct{ skippedCheck } ) + +func (systeminfoCheck) Name() string { + return "systeminfo" +} + +func (systeminfoCheck) Run(system chezmoi.System, homeDirAbsPath chezmoi.AbsPath) (checkResult, string) { + cmd := exec.Command("systeminfo") + data, err := system.IdempotentCmdOutput(cmd) + if err != nil { + return checkResultFailed, err.Error() + } + + var osName, osVersion string + s := bufio.NewScanner(bytes.NewReader(data)) + for s.Scan() { + switch key, value, found := chezmoi.CutString(s.Text(), ":"); { + case !found: + // Do nothing. + case key == "OS Name": + osName = strings.TrimSpace(value) + case key == "OS Version": + osVersion = strings.TrimSpace(value) + } + } + return checkResultOK, fmt.Sprintf("%s (%s)", osName, osVersion) +} diff --git a/pkg/cmd/testdata/scripts/doctor_unix.txt b/pkg/cmd/testdata/scripts/doctor_unix.txt index 140c4878b90..861976749ea 100644 --- a/pkg/cmd/testdata/scripts/doctor_unix.txt +++ b/pkg/cmd/testdata/scripts/doctor_unix.txt @@ -21,6 +21,7 @@ mksourcedir chezmoi doctor stdout '^ok\s+version\s+' stdout '^ok\s+os-arch\s+' +! stdout '^\S+\s+systeminfo\s+' stdout '^ok\s+uname\s+' stdout '^warning\s+config-file\s+.*multiple config files' stdout '^ok\s+source-dir\s+' diff --git a/pkg/cmd/testdata/scripts/doctor_windows.txt b/pkg/cmd/testdata/scripts/doctor_windows.txt new file mode 100644 index 00000000000..fabe181743f --- /dev/null +++ b/pkg/cmd/testdata/scripts/doctor_windows.txt @@ -0,0 +1,7 @@ +[!windows] skip 'Windows only' + +mksourcedir + +# test chezmoi doctor +chezmoi doctor +stdout '^ok\s+systeminfo\s+'
chore
Add systeminfo check to doctor command
8552a4c839078281bfe13db86c2fc0c1aef6ba20
2022-04-28 04:08:19
Tom Payne
docs: Add links to blog and video
false
diff --git a/assets/chezmoi.io/docs/links/articles-podcasts-and-videos.md.yaml b/assets/chezmoi.io/docs/links/articles-podcasts-and-videos.md.yaml index ccdd3bbcf2c..af8c7ade2b0 100644 --- a/assets/chezmoi.io/docs/links/articles-podcasts-and-videos.md.yaml +++ b/assets/chezmoi.io/docs/links/articles-podcasts-and-videos.md.yaml @@ -274,3 +274,12 @@ articles: version: '2.14.0' title: 'Tools I love: Chezmoi' url: 'https://messmore.org/post/chezmoi/' +- date: '2022-04-25' + version: '2.15.1' + title: 'Easily moving Linux installs' + url: 'https://christitus.com/chezmoi/' +- date: '2022-04-27' + version: '2.15.1' + format: Video + title: 'Easily moving Linux installs' + url: 'https://www.youtube.com/watch?v=x6063EuxfEA'
docs
Add links to blog and video
6021caceaee532e5c5c684c84c62d5773496ae28
2021-10-06 05:51:23
Tom Payne
chore: Tidy up switch statement
false
diff --git a/internal/chezmoi/sourcestate.go b/internal/chezmoi/sourcestate.go index 23efb5fde56..f670cdf507d 100644 --- a/internal/chezmoi/sourcestate.go +++ b/internal/chezmoi/sourcestate.go @@ -1187,8 +1187,7 @@ func (s *SourceState) newSourceStateDir(sourceRelPath SourceRelPath, dirAttr Dir func (s *SourceState) newCreateTargetStateEntryFunc(sourceRelPath SourceRelPath, fileAttr FileAttr, sourceLazyContents *lazyContents) targetStateEntryFunc { return func(destSystem System, destAbsPath AbsPath) (TargetStateEntry, error) { var lazyContents *lazyContents - contents, err := destSystem.ReadFile(destAbsPath) - switch { + switch contents, err := destSystem.ReadFile(destAbsPath); { case err == nil: lazyContents = newLazyContents(contents) case errors.Is(err, fs.ErrNotExist):
chore
Tidy up switch statement
03ff35c49c9e2b8813589ce223f48c78e61a95a7
2023-07-06 05:05:17
Tom Payne
fix: Never consider localhost.localdomain in /etc/hosts as the FQDN
false
diff --git a/pkg/chezmoi/chezmoi.go b/pkg/chezmoi/chezmoi.go index bc47b0026ec..fb02c1b4d16 100644 --- a/pkg/chezmoi/chezmoi.go +++ b/pkg/chezmoi/chezmoi.go @@ -297,10 +297,26 @@ func etcHostsFQDNHostname(fileSystem vfs.FS) (string, error) { text = strings.TrimSpace(text) text, _, _ = strings.Cut(text, "#") fields := whitespaceRx.Split(text, -1) - if len(fields) > 1 && net.ParseIP(fields[0]).IsLoopback() && - strings.Contains(fields[1], ".") { - return fields[1], nil + if len(fields) < 2 { + continue + } + if !net.ParseIP(fields[0]).IsLoopback() { + continue + } + hostname, domainname, found := strings.Cut(fields[1], ".") + if !found { + continue + } + if hostname == "localhost" { + continue + } + if domainname == "localdomain" { + continue + } + if runtime.GOOS == "darwin" && domainname == "local" { + continue } + return fields[1], nil } return "", s.Err() } diff --git a/pkg/chezmoi/chezmoi_test.go b/pkg/chezmoi/chezmoi_test.go index ee713b771cd..5879f059e9a 100644 --- a/pkg/chezmoi/chezmoi_test.go +++ b/pkg/chezmoi/chezmoi_test.go @@ -65,6 +65,17 @@ func TestEtcHostsFQDNHostname(t *testing.T) { f: etcHostsFQDNHostname, expected: "host.example.com", }, + { + name: "etc_hosts_loopback_ipv4_localhost_dot_localdomain", + root: map[string]any{ + "/etc/hosts": chezmoitest.JoinLines( + `127.0.0.1 localhost.localdomain`, + `127.0.0.2 host.example.com host`, + ), + }, + f: etcHostsFQDNHostname, + expected: "host.example.com", + }, { name: "etc_hosts_loopback_ipv6", root: map[string]any{
fix
Never consider localhost.localdomain in /etc/hosts as the FQDN
7cefcdfd599fb68c1ba695067bb4358f598c5aae
2021-11-21 01:22:48
Tom Payne
chore: Rename fs.FileInfo variables for consistency
false
diff --git a/internal/chezmoi/actualstateentry.go b/internal/chezmoi/actualstateentry.go index 1536ea76478..4437fb511b2 100644 --- a/internal/chezmoi/actualstateentry.go +++ b/internal/chezmoi/actualstateentry.go @@ -39,9 +39,9 @@ type ActualStateSymlink struct { // NewActualStateEntry returns a new ActualStateEntry populated with absPath // from system. -func NewActualStateEntry(system System, absPath AbsPath, info fs.FileInfo, err error) (ActualStateEntry, error) { - if info == nil { - info, err = system.Lstat(absPath) +func NewActualStateEntry(system System, absPath AbsPath, fileInfo fs.FileInfo, err error) (ActualStateEntry, error) { + if fileInfo == nil { + fileInfo, err = system.Lstat(absPath) } switch { case errors.Is(err, fs.ErrNotExist): @@ -51,11 +51,11 @@ func NewActualStateEntry(system System, absPath AbsPath, info fs.FileInfo, err e case err != nil: return nil, err } - switch info.Mode().Type() { + switch fileInfo.Mode().Type() { case 0: return &ActualStateFile{ absPath: absPath, - perm: info.Mode().Perm(), + perm: fileInfo.Mode().Perm(), lazyContents: newLazyContentsFunc(func() ([]byte, error) { return system.ReadFile(absPath) }), @@ -63,7 +63,7 @@ func NewActualStateEntry(system System, absPath AbsPath, info fs.FileInfo, err e case fs.ModeDir: return &ActualStateDir{ absPath: absPath, - perm: info.Mode().Perm(), + perm: fileInfo.Mode().Perm(), }, nil case fs.ModeSymlink: return &ActualStateSymlink{ @@ -79,7 +79,7 @@ func NewActualStateEntry(system System, absPath AbsPath, info fs.FileInfo, err e default: return nil, &unsupportedFileTypeError{ absPath: absPath, - mode: info.Mode(), + mode: fileInfo.Mode(), } } } diff --git a/internal/chezmoi/archivereadersystem.go b/internal/chezmoi/archivereadersystem.go index d577360306b..11abd01dc92 100644 --- a/internal/chezmoi/archivereadersystem.go +++ b/internal/chezmoi/archivereadersystem.go @@ -39,7 +39,7 @@ func (e InvalidArchiveFormatError) Error() string { } // An walkArchiveFunc is called once for each entry in an archive. -type walkArchiveFunc func(name string, info fs.FileInfo, r io.Reader, linkname string) error +type walkArchiveFunc func(name string, fileInfo fs.FileInfo, r io.Reader, linkname string) error // A ArchiveReaderSystem a system constructed from reading an archive. type ArchiveReaderSystem struct { @@ -69,7 +69,7 @@ func NewArchiveReaderSystem(archivePath string, data []byte, format ArchiveForma format = GuessArchiveFormat(archivePath, data) } - if err := walkArchive(data, format, func(name string, info fs.FileInfo, r io.Reader, linkname string) error { + if err := walkArchive(data, format, func(name string, fileInfo fs.FileInfo, r io.Reader, linkname string) error { if options.StripComponents > 0 { components := strings.Split(name, "/") if len(components) <= options.StripComponents { @@ -82,19 +82,19 @@ func NewArchiveReaderSystem(archivePath string, data []byte, format ArchiveForma } nameAbsPath := options.RootAbsPath.JoinString(name) - s.fileInfos[nameAbsPath] = info + s.fileInfos[nameAbsPath] = fileInfo switch { - case info.IsDir(): - case info.Mode()&fs.ModeType == 0: + case fileInfo.IsDir(): + case fileInfo.Mode()&fs.ModeType == 0: contents, err := io.ReadAll(r) if err != nil { return fmt.Errorf("%s: %w", name, err) } s.contents[nameAbsPath] = contents - case info.Mode()&fs.ModeType == fs.ModeSymlink: + case fileInfo.Mode()&fs.ModeType == fs.ModeSymlink: s.linkname[nameAbsPath] = linkname default: - return fmt.Errorf("%s: unsupported mode %o", name, info.Mode()&fs.ModeType) + return fmt.Errorf("%s: unsupported mode %o", name, fileInfo.Mode()&fs.ModeType) } return nil }); err != nil { diff --git a/internal/chezmoi/chezmoi.go b/internal/chezmoi/chezmoi.go index 4a2aac0d70e..ccad7110126 100644 --- a/internal/chezmoi/chezmoi.go +++ b/internal/chezmoi/chezmoi.go @@ -133,8 +133,8 @@ func SHA256Sum(data []byte) []byte { } // SuspiciousSourceDirEntry returns true if base is a suspicious dir entry. -func SuspiciousSourceDirEntry(base string, info fs.FileInfo) bool { - switch info.Mode().Type() { +func SuspiciousSourceDirEntry(base string, fileInfo fs.FileInfo) bool { + switch fileInfo.Mode().Type() { case 0: return strings.HasPrefix(base, Prefix) && !knownPrefixedFiles.contains(base) case fs.ModeDir: diff --git a/internal/chezmoi/chezmoi_unix.go b/internal/chezmoi/chezmoi_unix.go index 3032578c242..653e5f80f0c 100644 --- a/internal/chezmoi/chezmoi_unix.go +++ b/internal/chezmoi/chezmoi_unix.go @@ -72,17 +72,17 @@ func etcHostsFQDNHostname(fileSystem vfs.FS) (string, error) { return "", s.Err() } -// isExecutable returns if info is executable. -func isExecutable(info fs.FileInfo) bool { - return info.Mode().Perm()&0o111 != 0 +// isExecutable returns if fileInfo is executable. +func isExecutable(fileInfo fs.FileInfo) bool { + return fileInfo.Mode().Perm()&0o111 != 0 } -// isPrivate returns if info is private. -func isPrivate(info fs.FileInfo) bool { - return info.Mode().Perm()&0o77 == 0 +// isPrivate returns if fileInfo is private. +func isPrivate(fileInfo fs.FileInfo) bool { + return fileInfo.Mode().Perm()&0o77 == 0 } -// isReadOnly returns if info is read-only. -func isReadOnly(info fs.FileInfo) bool { - return info.Mode().Perm()&0o222 == 0 +// isReadOnly returns if fileInfo is read-only. +func isReadOnly(fileInfo fs.FileInfo) bool { + return fileInfo.Mode().Perm()&0o222 == 0 } diff --git a/internal/chezmoi/chezmoi_windows.go b/internal/chezmoi/chezmoi_windows.go index 3a155029cdc..d350e77373a 100644 --- a/internal/chezmoi/chezmoi_windows.go +++ b/internal/chezmoi/chezmoi_windows.go @@ -26,17 +26,17 @@ func FQDNHostname(fileSystem vfs.FS) string { } // isExecutable returns false on Windows. -func isExecutable(info fs.FileInfo) bool { +func isExecutable(fileInfo fs.FileInfo) bool { return false } // isPrivate returns false on Windows. -func isPrivate(info fs.FileInfo) bool { +func isPrivate(fileInfo fs.FileInfo) bool { return false } // isReadOnly returns false on Windows. -func isReadOnly(info fs.FileInfo) bool { +func isReadOnly(fileInfo fs.FileInfo) bool { return false } diff --git a/internal/chezmoi/data.go b/internal/chezmoi/data.go index ff30acf46ef..75901ec5480 100644 --- a/internal/chezmoi/data.go +++ b/internal/chezmoi/data.go @@ -19,14 +19,14 @@ import ( func Kernel(fileSystem vfs.FS) (map[string]interface{}, error) { const procSysKernel = "/proc/sys/kernel" - switch info, err := fileSystem.Stat(procSysKernel); { + switch fileInfo, err := fileSystem.Stat(procSysKernel); { case errors.Is(err, fs.ErrNotExist): return nil, nil case errors.Is(err, fs.ErrPermission): return nil, nil case err != nil: return nil, err - case !info.Mode().IsDir(): + case !fileInfo.Mode().IsDir(): return nil, nil } diff --git a/internal/chezmoi/debugsystem.go b/internal/chezmoi/debugsystem.go index 9d58d446684..360811766a4 100644 --- a/internal/chezmoi/debugsystem.go +++ b/internal/chezmoi/debugsystem.go @@ -78,11 +78,11 @@ func (s *DebugSystem) Link(oldpath, newpath AbsPath) error { // Lstat implements System.Lstat. func (s *DebugSystem) Lstat(name AbsPath) (fs.FileInfo, error) { - info, err := s.system.Lstat(name) + fileInfo, err := s.system.Lstat(name) s.logger.Err(err). Stringer("name", name). Msg("Lstat") - return info, err + return fileInfo, err } // Mkdir implements System.Mkdir. @@ -183,11 +183,11 @@ func (s *DebugSystem) RunScript(scriptname RelPath, dir AbsPath, data []byte, in // Stat implements System.Stat. func (s *DebugSystem) Stat(name AbsPath) (fs.FileInfo, error) { - info, err := s.system.Stat(name) + fileInfo, err := s.system.Stat(name) s.logger.Err(err). Stringer("name", name). Msg("Stat") - return info, err + return fileInfo, err } // UnderlyingFS implements System.UnderlyingFS. diff --git a/internal/chezmoi/entrytypeset.go b/internal/chezmoi/entrytypeset.go index e41639f3873..ff64a92c122 100644 --- a/internal/chezmoi/entrytypeset.go +++ b/internal/chezmoi/entrytypeset.go @@ -58,14 +58,14 @@ func (s *EntryTypeSet) IncludeEncrypted() bool { return s.bits&EntryTypeEncrypted != 0 } -// IncludeFileInfo returns true if the type of info is a member. -func (s *EntryTypeSet) IncludeFileInfo(info fs.FileInfo) bool { +// IncludeFileInfo returns true if the type of fileInfo is a member. +func (s *EntryTypeSet) IncludeFileInfo(fileInfo fs.FileInfo) bool { switch { - case info.IsDir(): + case fileInfo.IsDir(): return s.bits&EntryTypeDirs != 0 - case info.Mode().IsRegular(): + case fileInfo.Mode().IsRegular(): return s.bits&EntryTypeFiles != 0 - case info.Mode().Type() == fs.ModeSymlink: + case fileInfo.Mode().Type() == fs.ModeSymlink: return s.bits&EntryTypeSymlinks != 0 default: return false diff --git a/internal/chezmoi/realsystem.go b/internal/chezmoi/realsystem.go index 0b803a2a97b..62feb5a8561 100644 --- a/internal/chezmoi/realsystem.go +++ b/internal/chezmoi/realsystem.go @@ -142,8 +142,8 @@ func (s *RealSystem) getScriptWorkingDir(dir AbsPath) (string, error) { // This should always terminate because dir will eventually become ".", i.e. // the current directory. for { - switch info, err := s.Stat(dir); { - case err == nil && info.IsDir(): + switch fileInfo, err := s.Stat(dir); { + case err == nil && fileInfo.IsDir(): // dir exists and is a directory. Use it. dirRawAbsPath, err := s.RawPath(dir) if err != nil { diff --git a/internal/chezmoi/realsystem_unix.go b/internal/chezmoi/realsystem_unix.go index c9f4a1b28cf..f0a879939e8 100644 --- a/internal/chezmoi/realsystem_unix.go +++ b/internal/chezmoi/realsystem_unix.go @@ -61,12 +61,12 @@ func (s *RealSystem) WriteFile(filename AbsPath, data []byte, perm fs.FileMode) dir := filename.Dir() dev, ok := s.devCache[dir] if !ok { - var info fs.FileInfo - info, err = s.Stat(dir) + var fileInfo fs.FileInfo + fileInfo, err = s.Stat(dir) if err != nil { return err } - statT, ok := info.Sys().(*syscall.Stat_t) + statT, ok := fileInfo.Sys().(*syscall.Stat_t) if !ok { err = errors.New("fs.FileInfo.Sys() cannot be converted to a *syscall.Stat_t") return diff --git a/internal/chezmoi/sourcestate.go b/internal/chezmoi/sourcestate.go index b39a62f96cb..93d962ca1a9 100644 --- a/internal/chezmoi/sourcestate.go +++ b/internal/chezmoi/sourcestate.go @@ -427,7 +427,7 @@ DESTABSPATH: // 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, info fs.FileInfo) error { +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 @@ -437,14 +437,14 @@ func (s *SourceState) AddDestAbsPathInfos(destAbsPathInfos map[AbsPath]fs.FileIn return nil } - if info == nil { + if fileInfo == nil { var err error - info, err = system.Lstat(destAbsPath) + fileInfo, err = system.Lstat(destAbsPath) if err != nil { return err } } - destAbsPathInfos[destAbsPath] = info + destAbsPathInfos[destAbsPath] = fileInfo parentAbsPath := destAbsPath.Dir() if parentAbsPath == s.destDirAbsPath { @@ -456,7 +456,7 @@ func (s *SourceState) AddDestAbsPathInfos(destAbsPathInfos map[AbsPath]fs.FileIn } destAbsPath = parentAbsPath - info = nil + fileInfo = nil } } @@ -682,18 +682,18 @@ type ReadOptions struct { // Read reads the source state from the source directory. func (s *SourceState) Read(ctx context.Context, options *ReadOptions) error { - switch info, err := s.system.Stat(s.sourceDirAbsPath); { + switch fileInfo, err := s.system.Stat(s.sourceDirAbsPath); { case errors.Is(err, fs.ErrNotExist): return nil case err != nil: return err - case !info.IsDir(): + case !fileInfo.IsDir(): return fmt.Errorf("%s: not a directory", s.sourceDirAbsPath) } // Read all source entries. allSourceStateEntries := make(map[RelPath][]SourceStateEntry) - if err := WalkSourceDir(s.system, s.sourceDirAbsPath, func(sourceAbsPath AbsPath, info fs.FileInfo, err error) error { + if err := WalkSourceDir(s.system, s.sourceDirAbsPath, func(sourceAbsPath AbsPath, fileInfo fs.FileInfo, err error) error { if err != nil { return err } @@ -702,34 +702,34 @@ func (s *SourceState) Read(ctx context.Context, options *ReadOptions) error { } sourceRelPath := SourceRelPath{ relPath: sourceAbsPath.MustTrimDirPrefix(s.sourceDirAbsPath), - isDir: info.IsDir(), + isDir: fileInfo.IsDir(), } parentSourceRelPath, sourceName := sourceRelPath.Split() // Follow symlinks in the source directory. - if info.Mode().Type() == fs.ModeSymlink { + 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(info.Name(), ignorePrefix) && !strings.HasPrefix(info.Name(), Prefix) { + if strings.HasPrefix(fileInfo.Name(), ignorePrefix) && !strings.HasPrefix(fileInfo.Name(), Prefix) { return nil } - info, err = s.system.Stat(s.sourceDirAbsPath.Join(sourceRelPath.RelPath())) + fileInfo, err = s.system.Stat(s.sourceDirAbsPath.Join(sourceRelPath.RelPath())) if err != nil { return err } } switch { - case strings.HasPrefix(info.Name(), dataName): + case strings.HasPrefix(fileInfo.Name(), dataName): if !s.readTemplateData { return nil } return s.addTemplateData(sourceAbsPath) - case strings.HasPrefix(info.Name(), externalName): + case strings.HasPrefix(fileInfo.Name(), externalName): return s.addExternal(sourceAbsPath) - case info.Name() == ignoreName: + case fileInfo.Name() == ignoreName: return s.addPatterns(s.ignore, sourceAbsPath, parentSourceRelPath) - case info.Name() == removeName: + case fileInfo.Name() == removeName: removePatterns := newPatternSet() if err := s.addPatterns(removePatterns, sourceAbsPath, sourceRelPath); err != nil { return err @@ -755,21 +755,21 @@ func (s *SourceState) Read(ctx context.Context, options *ReadOptions) error { allSourceStateEntries[targetRelPath] = append(allSourceStateEntries[targetRelPath], sourceStateEntry) } return nil - case info.Name() == templatesDirName: + case fileInfo.Name() == templatesDirName: if err := s.addTemplatesDir(sourceAbsPath); err != nil { return err } return vfs.SkipDir - case info.Name() == versionName: + case fileInfo.Name() == versionName: return s.addVersionFile(sourceAbsPath) - case strings.HasPrefix(info.Name(), Prefix): + case strings.HasPrefix(fileInfo.Name(), Prefix): fallthrough - case strings.HasPrefix(info.Name(), ignorePrefix): - if info.IsDir() { + case strings.HasPrefix(fileInfo.Name(), ignorePrefix): + if fileInfo.IsDir() { return vfs.SkipDir } return nil - case info.IsDir(): + case fileInfo.IsDir(): da := parseDirAttr(sourceName.String()) targetRelPath := parentSourceRelPath.Dir().TargetRelPath(s.encryption.EncryptedSuffix()).JoinString(da.TargetName) if s.Ignore(targetRelPath) { @@ -778,7 +778,7 @@ func (s *SourceState) Read(ctx context.Context, options *ReadOptions) error { sourceStateEntry := s.newSourceStateDir(sourceRelPath, da) allSourceStateEntries[targetRelPath] = append(allSourceStateEntries[targetRelPath], sourceStateEntry) return nil - case info.Mode().IsRegular(): + case fileInfo.Mode().IsRegular(): fa := parseFileAttr(sourceName.String(), s.encryption.EncryptedSuffix()) targetRelPath := parentSourceRelPath.Dir().TargetRelPath(s.encryption.EncryptedSuffix()).JoinString(fa.TargetName) if s.Ignore(targetRelPath) { @@ -791,7 +791,7 @@ func (s *SourceState) Read(ctx context.Context, options *ReadOptions) error { default: return &unsupportedFileTypeError{ absPath: sourceAbsPath, - mode: info.Mode(), + mode: fileInfo.Mode(), } } }); err != nil { @@ -849,10 +849,10 @@ func (s *SourceState) Read(ctx context.Context, options *ReadOptions) error { continue } - switch infos, err := s.system.ReadDir(s.destDirAbsPath.Join(targetRelPath)); { + switch fileInfos, err := s.system.ReadDir(s.destDirAbsPath.Join(targetRelPath)); { case err == nil: - for _, info := range infos { - name := info.Name() + for _, fileInfo := range fileInfos { + name := fileInfo.Name() if name == "." || name == ".." { continue } @@ -1040,11 +1040,11 @@ func (s *SourceState) addTemplateData(sourceAbsPath AbsPath) error { // addTemplatesDir adds all templates in templateDir to s. func (s *SourceState) addTemplatesDir(templatesDirAbsPath AbsPath) error { - return WalkSourceDir(s.system, templatesDirAbsPath, func(templateAbsPath AbsPath, info fs.FileInfo, err error) error { + return WalkSourceDir(s.system, templatesDirAbsPath, func(templateAbsPath AbsPath, fileInfo fs.FileInfo, err error) error { switch { case err != nil: return err - case info.Mode().IsRegular(): + case fileInfo.Mode().IsRegular(): contents, err := s.system.ReadFile(templateAbsPath) if err != nil { return err @@ -1060,12 +1060,12 @@ func (s *SourceState) addTemplatesDir(templatesDirAbsPath AbsPath) error { } s.templates[name] = tmpl return nil - case info.IsDir(): + case fileInfo.IsDir(): return nil default: return &unsupportedFileTypeError{ absPath: templateAbsPath, - mode: info.Mode(), + mode: fileInfo.Mode(), } } }) @@ -1463,12 +1463,12 @@ func (s *SourceState) newSourceStateFile(sourceRelPath SourceRelPath, fileAttr F // // We return a SourceStateEntry rather than a *SourceStateDir to simplify nil // checks later. -func (s *SourceState) newSourceStateDirEntry(info fs.FileInfo, parentSourceRelPath SourceRelPath, options *AddOptions) (SourceStateEntry, error) { +func (s *SourceState) newSourceStateDirEntry(fileInfo fs.FileInfo, parentSourceRelPath SourceRelPath, options *AddOptions) (SourceStateEntry, error) { dirAttr := DirAttr{ - TargetName: info.Name(), + TargetName: fileInfo.Name(), Exact: options.Exact, - Private: isPrivate(info), - ReadOnly: isReadOnly(info), + Private: isPrivate(fileInfo), + ReadOnly: isReadOnly(fileInfo), } sourceRelPath := parentSourceRelPath.Join(NewSourceRelDirPath(dirAttr.SourceName())) return &SourceStateDir{ @@ -1486,14 +1486,14 @@ func (s *SourceState) newSourceStateDirEntry(info fs.FileInfo, parentSourceRelPa // // We return a SourceStateEntry rather than a *SourceStateFile to simplify nil // checks later. -func (s *SourceState) newSourceStateFileEntryFromFile(actualStateFile *ActualStateFile, info fs.FileInfo, parentSourceRelPath SourceRelPath, options *AddOptions) (SourceStateEntry, error) { +func (s *SourceState) newSourceStateFileEntryFromFile(actualStateFile *ActualStateFile, fileInfo fs.FileInfo, parentSourceRelPath SourceRelPath, options *AddOptions) (SourceStateEntry, error) { fileAttr := FileAttr{ - TargetName: info.Name(), + TargetName: fileInfo.Name(), Empty: options.Empty, Encrypted: options.Encrypt, - Executable: isExecutable(info), - Private: isPrivate(info), - ReadOnly: isReadOnly(info), + Executable: isExecutable(fileInfo), + Private: isPrivate(fileInfo), + ReadOnly: isReadOnly(fileInfo), Template: options.Template, } if options.Create { @@ -1541,7 +1541,7 @@ func (s *SourceState) newSourceStateFileEntryFromFile(actualStateFile *ActualSta // // We return a SourceStateEntry rather than a *SourceStateFile to simplify nil // checks later. -func (s *SourceState) newSourceStateFileEntryFromSymlink(actualStateSymlink *ActualStateSymlink, info fs.FileInfo, parentSourceRelPath SourceRelPath, options *AddOptions) (SourceStateEntry, error) { +func (s *SourceState) newSourceStateFileEntryFromSymlink(actualStateSymlink *ActualStateSymlink, fileInfo fs.FileInfo, parentSourceRelPath SourceRelPath, options *AddOptions) (SourceStateEntry, error) { linkname, err := actualStateSymlink.Linkname() if err != nil { return nil, err @@ -1566,7 +1566,7 @@ func (s *SourceState) newSourceStateFileEntryFromSymlink(actualStateSymlink *Act contents = append(contents, '\n') lazyContents := newLazyContents(contents) fileAttr := FileAttr{ - TargetName: info.Name(), + TargetName: fileInfo.Name(), Type: SourceFileTypeSymlink, Template: template, } @@ -1632,7 +1632,7 @@ func (s *SourceState) readExternalArchive(ctx context.Context, externalRelPath R } sourceRelPaths := make(map[RelPath]SourceRelPath) - if err := walkArchive(data, format, func(name string, info fs.FileInfo, r io.Reader, linkname string) error { + if err := walkArchive(data, format, func(name string, fileInfo fs.FileInfo, r io.Reader, linkname string) error { if external.StripComponents > 0 { components := strings.Split(name, "/") if len(components) <= external.StripComponents { @@ -1654,15 +1654,15 @@ func (s *SourceState) readExternalArchive(ctx context.Context, externalRelPath R var sourceStateEntry SourceStateEntry switch { - case info.IsDir(): + case fileInfo.IsDir(): targetStateEntry := &TargetStateDir{ - perm: info.Mode().Perm() &^ s.umask, + perm: fileInfo.Mode().Perm() &^ s.umask, } dirAttr := DirAttr{ - TargetName: info.Name(), + TargetName: fileInfo.Name(), Exact: external.Exact, - Private: isPrivate(info), - ReadOnly: isReadOnly(info), + Private: isPrivate(fileInfo), + ReadOnly: isReadOnly(fileInfo), } sourceStateEntry = &SourceStateDir{ Attr: dirAttr, @@ -1670,19 +1670,19 @@ func (s *SourceState) readExternalArchive(ctx context.Context, externalRelPath R sourceRelPath: parentSourceRelPath.Join(dirSourceRelPath, NewSourceRelPath(dirAttr.SourceName())), targetStateEntry: targetStateEntry, } - case info.Mode()&fs.ModeType == 0: + case fileInfo.Mode()&fs.ModeType == 0: contents, err := io.ReadAll(r) if err != nil { return fmt.Errorf("%s: %w", name, err) } lazyContents := newLazyContents(contents) fileAttr := FileAttr{ - TargetName: info.Name(), + TargetName: fileInfo.Name(), Type: SourceFileTypeFile, - Empty: info.Size() == 0, - Executable: isExecutable(info), - Private: isPrivate(info), - ReadOnly: isReadOnly(info), + Empty: fileInfo.Size() == 0, + Executable: isExecutable(fileInfo), + Private: isPrivate(fileInfo), + ReadOnly: isReadOnly(fileInfo), } targetStateEntry := &TargetStateFile{ lazyContents: lazyContents, @@ -1696,12 +1696,12 @@ func (s *SourceState) readExternalArchive(ctx context.Context, externalRelPath R sourceRelPath: parentSourceRelPath.Join(dirSourceRelPath, NewSourceRelPath(fileAttr.SourceName(s.encryption.EncryptedSuffix()))), targetStateEntry: targetStateEntry, } - case info.Mode()&fs.ModeType == fs.ModeSymlink: + case fileInfo.Mode()&fs.ModeType == fs.ModeSymlink: targetStateEntry := &TargetStateSymlink{ lazyLinkname: newLazyLinkname(linkname), } fileAttr := FileAttr{ - TargetName: info.Name(), + TargetName: fileInfo.Name(), Type: SourceFileTypeSymlink, } sourceStateEntry = &SourceStateFile{ @@ -1711,7 +1711,7 @@ func (s *SourceState) readExternalArchive(ctx context.Context, externalRelPath R targetStateEntry: targetStateEntry, } default: - return fmt.Errorf("%s: unsupported mode %o", name, info.Mode()&fs.ModeType) + return fmt.Errorf("%s: unsupported mode %o", name, fileInfo.Mode()&fs.ModeType) } sourceStateEntries[targetRelPath] = append(sourceStateEntries[targetRelPath], sourceStateEntry) return nil @@ -1747,16 +1747,16 @@ func (s *SourceState) readExternalFile(ctx context.Context, externalRelPath RelP } // sourceStateEntry returns a new SourceStateEntry based on actualStateEntry. -func (s *SourceState) sourceStateEntry(actualStateEntry ActualStateEntry, destAbsPath AbsPath, info fs.FileInfo, parentSourceRelPath SourceRelPath, options *AddOptions) (SourceStateEntry, error) { +func (s *SourceState) sourceStateEntry(actualStateEntry ActualStateEntry, destAbsPath AbsPath, fileInfo fs.FileInfo, parentSourceRelPath SourceRelPath, options *AddOptions) (SourceStateEntry, error) { switch actualStateEntry := actualStateEntry.(type) { case *ActualStateAbsent: return nil, fmt.Errorf("%s: not found", destAbsPath) case *ActualStateDir: - return s.newSourceStateDirEntry(info, parentSourceRelPath, options) + return s.newSourceStateDirEntry(fileInfo, parentSourceRelPath, options) case *ActualStateFile: - return s.newSourceStateFileEntryFromFile(actualStateEntry, info, parentSourceRelPath, options) + return s.newSourceStateFileEntryFromFile(actualStateEntry, fileInfo, parentSourceRelPath, options) case *ActualStateSymlink: - return s.newSourceStateFileEntryFromSymlink(actualStateEntry, info, parentSourceRelPath, options) + return s.newSourceStateFileEntryFromSymlink(actualStateEntry, fileInfo, parentSourceRelPath, options) default: panic(fmt.Sprintf("%T: unsupported type", actualStateEntry)) } diff --git a/internal/chezmoi/sourcestate_test.go b/internal/chezmoi/sourcestate_test.go index f9249576768..a21e6fcb9e2 100644 --- a/internal/chezmoi/sourcestate_test.go +++ b/internal/chezmoi/sourcestate_test.go @@ -1548,7 +1548,7 @@ func TestWalkSourceDir(t *testing.T) { var actualAbsPaths []AbsPath chezmoitest.WithTestFS(t, root, func(fileSystem vfs.FS) { system := NewRealSystem(fileSystem) - require.NoError(t, WalkSourceDir(system, sourceDirAbsPath, func(absPath AbsPath, info fs.FileInfo, err error) error { + require.NoError(t, WalkSourceDir(system, sourceDirAbsPath, func(absPath AbsPath, fileInfo fs.FileInfo, err error) error { if err != nil { return err } diff --git a/internal/chezmoi/system.go b/internal/chezmoi/system.go index 327bf832e07..2ba966caac3 100644 --- a/internal/chezmoi/system.go +++ b/internal/chezmoi/system.go @@ -104,11 +104,11 @@ func MkdirAll(system System, absPath AbsPath, perm fs.FileMode) error { // between "path already exists and is already a directory" and "path // already exists and is not a directory". Between the call to Mkdir and // the call to Stat path might have changed. - info, statErr := system.Stat(absPath) + fileInfo, statErr := system.Stat(absPath) if statErr != nil { return statErr } - if !info.IsDir() { + if !fileInfo.IsDir() { return err } return nil @@ -135,9 +135,9 @@ func MkdirAll(system System, absPath AbsPath, perm fs.FileMode) error { // the tree, including rootAbsPath. // // Walk does not follow symlinks. -func Walk(system System, rootAbsPath AbsPath, walkFunc func(absPath AbsPath, info fs.FileInfo, err error) error) error { - return vfs.Walk(system.UnderlyingFS(), rootAbsPath.String(), func(absPath string, info fs.FileInfo, err error) error { - return walkFunc(NewAbsPath(absPath).ToSlash(), info, err) +func Walk(system System, rootAbsPath AbsPath, walkFunc func(absPath AbsPath, fileInfo fs.FileInfo, err error) error) error { + return vfs.Walk(system.UnderlyingFS(), rootAbsPath.String(), func(absPath string, fileInfo fs.FileInfo, err error) error { + return walkFunc(NewAbsPath(absPath).ToSlash(), fileInfo, err) }) } @@ -155,11 +155,11 @@ type WalkSourceDirFunc func(AbsPath, fs.FileInfo, error) error // before all other entries. All other entries are visited in alphabetical // order. func WalkSourceDir(system System, sourceDirAbsPath AbsPath, walkFunc WalkSourceDirFunc) error { - info, err := system.Stat(sourceDirAbsPath) + fileInfo, err := system.Stat(sourceDirAbsPath) if err != nil { err = walkFunc(sourceDirAbsPath, nil, err) } else { - err = walkSourceDir(system, sourceDirAbsPath, info, walkFunc) + err = walkSourceDir(system, sourceDirAbsPath, fileInfo, walkFunc) } if errors.Is(err, fs.SkipDir) { return nil @@ -178,19 +178,19 @@ var sourceDirEntryOrder = map[string]int{ } // walkSourceDir is a helper function for WalkSourceDir. -func walkSourceDir(system System, name AbsPath, info fs.FileInfo, walkFunc WalkSourceDirFunc) error { - switch err := walkFunc(name, info, nil); { - case info.IsDir() && errors.Is(err, fs.SkipDir): +func walkSourceDir(system System, name AbsPath, fileInfo fs.FileInfo, walkFunc WalkSourceDirFunc) error { + switch err := walkFunc(name, fileInfo, nil); { + case fileInfo.IsDir() && errors.Is(err, fs.SkipDir): return nil case err != nil: return err - case !info.IsDir(): + case !fileInfo.IsDir(): return nil } dirEntries, err := system.ReadDir(name) if err != nil { - err = walkFunc(name, info, err) + err = walkFunc(name, fileInfo, err) if err != nil { return err } @@ -212,14 +212,14 @@ func walkSourceDir(system System, name AbsPath, info fs.FileInfo, walkFunc WalkS }) for _, dirEntry := range dirEntries { - info, err := dirEntry.Info() + fileInfo, err := dirEntry.Info() if err != nil { err = walkFunc(name, nil, err) if err != nil { return err } } - if err := walkSourceDir(system, name.JoinString(dirEntry.Name()), info, walkFunc); err != nil { + if err := walkSourceDir(system, name.JoinString(dirEntry.Name()), fileInfo, walkFunc); err != nil { if errors.Is(err, fs.SkipDir) { break } diff --git a/internal/cmd/config.go b/internal/cmd/config.go index 203257ca589..71a9a49780f 100644 --- a/internal/cmd/config.go +++ b/internal/cmd/config.go @@ -945,29 +945,29 @@ func (c *Config) destAbsPathInfos(sourceState *chezmoi.SourceState, args []strin return nil, err } if options.recursive { - if err := chezmoi.Walk(c.destSystem, destAbsPath, func(destAbsPath chezmoi.AbsPath, info fs.FileInfo, err error) error { + if err := chezmoi.Walk(c.destSystem, destAbsPath, 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 && info.Mode().Type() == fs.ModeSymlink { - info, err = c.destSystem.Stat(destAbsPath) + if options.follow && fileInfo.Mode().Type() == fs.ModeSymlink { + fileInfo, err = c.destSystem.Stat(destAbsPath) if err != nil { return err } } - return sourceState.AddDestAbsPathInfos(destAbsPathInfos, c.destSystem, destAbsPath, info) + return sourceState.AddDestAbsPathInfos(destAbsPathInfos, c.destSystem, destAbsPath, fileInfo) }); err != nil { return nil, err } } else { - var info fs.FileInfo + var fileInfo fs.FileInfo if options.follow { - info, err = c.destSystem.Stat(destAbsPath) + fileInfo, err = c.destSystem.Stat(destAbsPath) } else { - info, err = c.destSystem.Lstat(destAbsPath) + fileInfo, err = c.destSystem.Lstat(destAbsPath) } switch { case options.ignoreNotExist && errors.Is(err, fs.ErrNotExist): @@ -975,7 +975,7 @@ func (c *Config) destAbsPathInfos(sourceState *chezmoi.SourceState, args []strin case err != nil: return nil, err } - if err := sourceState.AddDestAbsPathInfos(destAbsPathInfos, c.destSystem, destAbsPath, info); err != nil { + if err := sourceState.AddDestAbsPathInfos(destAbsPathInfos, c.destSystem, destAbsPath, fileInfo); err != nil { return nil, err } } @@ -1601,7 +1601,7 @@ func (c *Config) persistentPreRunRootE(cmd *cobra.Command, args []string) error workingTreeAbsPath := c.SourceDirAbsPath FOR: for { - if info, err := c.baseSystem.Stat(workingTreeAbsPath.JoinString(gogit.GitDirName)); err == nil && info.IsDir() { + if fileInfo, err := c.baseSystem.Stat(workingTreeAbsPath.JoinString(gogit.GitDirName)); err == nil && fileInfo.IsDir() { c.WorkingTreeAbsPath = workingTreeAbsPath break FOR } diff --git a/internal/cmd/doctorcmd.go b/internal/cmd/doctorcmd.go index 45873cf20f5..39733598a5c 100644 --- a/internal/cmd/doctorcmd.go +++ b/internal/cmd/doctorcmd.go @@ -475,11 +475,11 @@ func (c *suspiciousEntriesCheck) Name() string { func (c *suspiciousEntriesCheck) Run(system chezmoi.System, homeDirAbsPath chezmoi.AbsPath) (checkResult, string) { // FIXME check that config file templates are in root var suspiciousEntries []string - switch err := chezmoi.WalkSourceDir(system, c.dirname, func(absPath chezmoi.AbsPath, info fs.FileInfo, err error) error { + switch err := chezmoi.WalkSourceDir(system, c.dirname, func(absPath chezmoi.AbsPath, fileInfo fs.FileInfo, err error) error { if err != nil { return err } - if chezmoi.SuspiciousSourceDirEntry(absPath.Base(), info) { + if chezmoi.SuspiciousSourceDirEntry(absPath.Base(), fileInfo) { suspiciousEntries = append(suspiciousEntries, absPath.String()) } return nil diff --git a/internal/cmd/initcmd.go b/internal/cmd/initcmd.go index 338c6eba197..077e7370a89 100644 --- a/internal/cmd/initcmd.go +++ b/internal/cmd/initcmd.go @@ -134,9 +134,9 @@ func (c *Config) runInitCmd(cmd *cobra.Command, args []string) error { // If we're not in a working tree then init it or clone it. gitDirAbsPath := c.WorkingTreeAbsPath.JoinString(git.GitDirName) - switch info, err := c.baseSystem.Stat(gitDirAbsPath); { - case err == nil && info.IsDir(): - case err == nil && !info.IsDir(): + switch fileInfo, err := c.baseSystem.Stat(gitDirAbsPath); { + case err == nil && fileInfo.IsDir(): + case err == nil && !fileInfo.IsDir(): return fmt.Errorf("%s: not a directory", gitDirAbsPath) case errors.Is(err, fs.ErrNotExist): workingTreeRawPath, err := c.baseSystem.RawPath(c.WorkingTreeAbsPath) diff --git a/internal/cmd/main_test.go b/internal/cmd/main_test.go index d20be00a657..59a0d0c525b 100644 --- a/internal/cmd/main_test.go +++ b/internal/cmd/main_test.go @@ -150,16 +150,16 @@ func cmdCmpMod(ts *testscript.TestScript, neg bool, args []string) { if runtime.GOOS == "windows" { return } - info, err := os.Stat(args[1]) + fileInfo, err := os.Stat(args[1]) if err != nil { ts.Fatalf("%s: %v", args[1], err) } - equal := info.Mode().Perm() == fs.FileMode(mode64)&^chezmoitest.Umask + equal := fileInfo.Mode().Perm() == fs.FileMode(mode64)&^chezmoitest.Umask if neg && equal { - ts.Fatalf("%s unexpectedly has mode %03o", args[1], info.Mode().Perm()) + ts.Fatalf("%s unexpectedly has mode %03o", args[1], fileInfo.Mode().Perm()) } if !neg && !equal { - ts.Fatalf("%s has mode %03o, expected %03o", args[1], info.Mode().Perm(), fs.FileMode(mode64)&^chezmoitest.Umask) + ts.Fatalf("%s has mode %03o, expected %03o", args[1], fileInfo.Mode().Perm(), fs.FileMode(mode64)&^chezmoitest.Umask) } } @@ -199,11 +199,11 @@ func cmdHTTPD(ts *testscript.TestScript, neg bool, args []string) { func cmdIsSymlink(ts *testscript.TestScript, neg bool, args []string) { for _, arg := range args { filename := ts.MkAbs(arg) - info, err := os.Lstat(filename) + fileInfo, err := os.Lstat(filename) if err != nil { ts.Fatalf("%s: %v", arg, err) } - switch isSymlink := info.Mode().Type() == fs.ModeSymlink; { + switch isSymlink := fileInfo.Mode().Type() == fs.ModeSymlink; { case isSymlink && neg: ts.Fatalf("%s is a symlink", arg) case !isSymlink && !neg: diff --git a/internal/cmd/templatefuncs.go b/internal/cmd/templatefuncs.go index c6da07ac675..23f47baa2b1 100644 --- a/internal/cmd/templatefuncs.go +++ b/internal/cmd/templatefuncs.go @@ -102,15 +102,15 @@ func (c *Config) outputTemplateFunc(name string, args ...string) string { } func (c *Config) statTemplateFunc(name string) interface{} { - switch info, err := c.fileSystem.Stat(name); { + switch fileInfo, err := c.fileSystem.Stat(name); { case err == nil: return map[string]interface{}{ - "name": info.Name(), - "size": info.Size(), - "mode": int(info.Mode()), - "perm": int(info.Mode().Perm()), - "modTime": info.ModTime().Unix(), - "isDir": info.IsDir(), + "name": fileInfo.Name(), + "size": fileInfo.Size(), + "mode": int(fileInfo.Mode()), + "perm": int(fileInfo.Mode().Perm()), + "modTime": fileInfo.ModTime().Unix(), + "isDir": fileInfo.IsDir(), } case errors.Is(err, fs.ErrNotExist): return nil diff --git a/internal/cmd/unmanagedcmd.go b/internal/cmd/unmanagedcmd.go index 3ec179c7077..a83baa6ec8d 100644 --- a/internal/cmd/unmanagedcmd.go +++ b/internal/cmd/unmanagedcmd.go @@ -25,7 +25,7 @@ func (c *Config) newUnmanagedCmd() *cobra.Command { func (c *Config) runUnmanagedCmd(cmd *cobra.Command, args []string, sourceState *chezmoi.SourceState) error { builder := strings.Builder{} - if err := chezmoi.WalkSourceDir(c.destSystem, c.DestDirAbsPath, func(destAbsPath chezmoi.AbsPath, info fs.FileInfo, err error) error { + if err := chezmoi.WalkSourceDir(c.destSystem, c.DestDirAbsPath, func(destAbsPath chezmoi.AbsPath, fileInfo fs.FileInfo, err error) error { if err != nil { return err } @@ -39,7 +39,7 @@ func (c *Config) runUnmanagedCmd(cmd *cobra.Command, args []string, sourceState builder.WriteString(targeRelPath.String()) builder.WriteByte('\n') } - if info.IsDir() && (!managed || ignored) { + if fileInfo.IsDir() && (!managed || ignored) { return vfs.SkipDir } return nil diff --git a/internal/cmd/upgradecmd.go b/internal/cmd/upgradecmd.go index fd0489c6595..49900e15387 100644 --- a/internal/cmd/upgradecmd.go +++ b/internal/cmd/upgradecmd.go @@ -485,12 +485,12 @@ func getUpgradeMethod(fileSystem vfs.Stater, executableAbsPath chezmoi.AbsPath) return upgradeMethodSnapRefresh, nil } - info, err := fileSystem.Stat(executableAbsPath.String()) + fileInfo, err := fileSystem.Stat(executableAbsPath.String()) if err != nil { return "", err } //nolint:forcetypeassert - executableStat := info.Sys().(*syscall.Stat_t) + executableStat := fileInfo.Sys().(*syscall.Stat_t) uid := os.Getuid() switch int(executableStat.Uid) { case 0:
chore
Rename fs.FileInfo variables for consistency
222aef87f6489be50223795d78dc0dd14668186e
2024-09-27 06:11:39
Tom Payne
docs: Improve developer documentation
false
diff --git a/Makefile b/Makefile index 5b578d29059..64d15b8dd05 100644 --- a/Makefile +++ b/Makefile @@ -27,8 +27,8 @@ PREFIX?=/usr/local .PHONY: default default: build -.PHONY: smoketest -smoketest: run build-all test lint shellcheck format +.PHONY: smoke-test +smoke-test: run build-all test lint shellcheck format .PHONY: build build: diff --git a/assets/chezmoi.io/docs/developer-guide/architecture.md b/assets/chezmoi.io/docs/developer-guide/architecture.md index 07a370921ea..477f5c7437a 100644 --- a/assets/chezmoi.io/docs/developer-guide/architecture.md +++ b/assets/chezmoi.io/docs/developer-guide/architecture.md @@ -101,8 +101,8 @@ target state with the entry state in the persistent state. ## `internal/cmd/` directory -`internal/cmd/*cmd.go` contains the code for each individual command and -`internal/cmd/*templatefuncs.go` contain the template functions. +`internal/cmd/*cmd.go` files contain the code for each individual command. +`internal/cmd/*templatefuncs.go` files contain the template functions. Commands are defined as methods on the `Config` struct. The `Config` struct is large, containing all configuration values read from the config file, command @@ -117,8 +117,8 @@ system and persistent state. chezmoi uses separate types for absolute paths (`AbsPath`) and relative paths (`RelPath`) to avoid errors where paths are combined (e.g. joining two absolute -paths). A further type `SourceRelPath` is a relative path within the source -directory and handles file and directory attributes. +paths is an error). The type `SourceRelPath` is a relative path within the +source directory and handles file and directory attributes. Internally, chezmoi normalizes all paths to use forward slashes with an optional upper-cased Windows volume so they can be compared with string diff --git a/assets/chezmoi.io/docs/developer-guide/building-on-top-of-chezmoi.md b/assets/chezmoi.io/docs/developer-guide/building-on-top-of-chezmoi.md index 13804c27813..6bb12bb085f 100644 --- a/assets/chezmoi.io/docs/developer-guide/building-on-top-of-chezmoi.md +++ b/assets/chezmoi.io/docs/developer-guide/building-on-top-of-chezmoi.md @@ -2,6 +2,6 @@ chezmoi is designed with UNIX-style composability in mind, and the command line tool is semantically versioned. Building on top of chezmoi should primarily be -done by executing the binary with arguments and the standard input and output -configured appropriately. The `chezmoi dump` and `chezmoi state` commands +done by executing the `chezmoi` binary with arguments and the standard input and +output configured appropriately. The `chezmoi dump` and `chezmoi state` commands allows the inspection of chezmoi's internal state. diff --git a/assets/chezmoi.io/docs/developer-guide/index.md b/assets/chezmoi.io/docs/developer-guide/index.md index d5ebabb5f86..b25adca406e 100644 --- a/assets/chezmoi.io/docs/developer-guide/index.md +++ b/assets/chezmoi.io/docs/developer-guide/index.md @@ -35,10 +35,16 @@ Run chezmoi: $ go run . ``` -Run a set of smoketests, including cross-compilation, tests, and linting: +Run a set of smoke tests, including cross-compilation, tests, and linting: ```console -$ make smoketest +$ make smoke-test +``` + +Test building chezmoi for all architectures: + +```console +$ make test-release ``` !!! hint @@ -57,6 +63,6 @@ $ make smoketest ```console $ SHELL=bash make test - $ SHELL=zsh make smoketest + $ SHELL=zsh make smoke-test $ SHELL=bash go test ./... ```
docs
Improve developer documentation
f02d356d7801420c827746a864974d71ca38b5df
2021-12-05 22:37:18
Tom Payne
chore: Make capitalization of tar more consistent
false
diff --git a/internal/chezmoi/archivereadersystem_test.go b/internal/chezmoi/archivereadersystem_test.go index c5c73a87606..3da1e9b5873 100644 --- a/internal/chezmoi/archivereadersystem_test.go +++ b/internal/chezmoi/archivereadersystem_test.go @@ -11,7 +11,7 @@ import ( "github.com/stretchr/testify/require" ) -func TestArchiveReaderSystemTAR(t *testing.T) { +func TestArchiveReaderSystemTar(t *testing.T) { buffer := &bytes.Buffer{} tarWriter := tar.NewWriter(buffer) assert.NoError(t, tarWriter.WriteHeader(&tar.Header{ diff --git a/internal/chezmoi/sourcestate_test.go b/internal/chezmoi/sourcestate_test.go index 2f56972f38c..98b47123d5e 100644 --- a/internal/chezmoi/sourcestate_test.go +++ b/internal/chezmoi/sourcestate_test.go @@ -549,7 +549,7 @@ func TestSourceStateAdd(t *testing.T) { func TestSourceStateAddInExternal(t *testing.T) { buffer := &bytes.Buffer{} - tarWriterSystem := NewTARWriterSystem(buffer, tar.Header{}) + tarWriterSystem := NewTarWriterSystem(buffer, tar.Header{}) require.NoError(t, tarWriterSystem.Mkdir(NewAbsPath("dir"), 0o777)) require.NoError(t, tarWriterSystem.WriteFile(NewAbsPath("dir/file"), []byte("# contents of dir/file\n"), 0o666)) require.NoError(t, tarWriterSystem.Close()) @@ -1374,7 +1374,7 @@ func TestSourceStateReadExternal(t *testing.T) { func TestSourceStateReadExternalCache(t *testing.T) { buffer := &bytes.Buffer{} - tarWriterSystem := NewTARWriterSystem(buffer, tar.Header{}) + tarWriterSystem := NewTarWriterSystem(buffer, tar.Header{}) require.NoError(t, tarWriterSystem.WriteFile(NewAbsPath("file"), []byte("# contents of file\n"), 0o666)) require.NoError(t, tarWriterSystem.Close()) archiveData := buffer.Bytes() diff --git a/internal/chezmoi/tarwritersystem.go b/internal/chezmoi/tarwritersystem.go index 5577b9ac4b8..b55325c14c4 100644 --- a/internal/chezmoi/tarwritersystem.go +++ b/internal/chezmoi/tarwritersystem.go @@ -6,29 +6,29 @@ import ( "io/fs" ) -// A TARWriterSystem is a System that writes to a TAR archive. -type TARWriterSystem struct { +// A TarWriterSystem is a System that writes to a tar archive. +type TarWriterSystem struct { emptySystemMixin noUpdateSystemMixin tarWriter *tar.Writer headerTemplate tar.Header } -// NewTARWriterSystem returns a new TARWriterSystem that writes a TAR file to w. -func NewTARWriterSystem(w io.Writer, headerTemplate tar.Header) *TARWriterSystem { - return &TARWriterSystem{ +// NewTarWriterSystem returns a new TarWriterSystem that writes a tar file to w. +func NewTarWriterSystem(w io.Writer, headerTemplate tar.Header) *TarWriterSystem { + return &TarWriterSystem{ tarWriter: tar.NewWriter(w), headerTemplate: headerTemplate, } } // Close closes m. -func (s *TARWriterSystem) Close() error { +func (s *TarWriterSystem) Close() error { return s.tarWriter.Close() } // Mkdir implements System.Mkdir. -func (s *TARWriterSystem) Mkdir(name AbsPath, perm fs.FileMode) error { +func (s *TarWriterSystem) Mkdir(name AbsPath, perm fs.FileMode) error { header := s.headerTemplate header.Typeflag = tar.TypeDir header.Name = name.String() + "/" @@ -37,12 +37,12 @@ func (s *TARWriterSystem) Mkdir(name AbsPath, perm fs.FileMode) error { } // RunScript implements System.RunScript. -func (s *TARWriterSystem) RunScript(scriptname RelPath, dir AbsPath, data []byte, interpreter *Interpreter) error { +func (s *TarWriterSystem) RunScript(scriptname RelPath, dir AbsPath, data []byte, interpreter *Interpreter) error { return s.WriteFile(NewAbsPath(scriptname.String()), data, 0o700) } // WriteFile implements System.WriteFile. -func (s *TARWriterSystem) WriteFile(filename AbsPath, data []byte, perm fs.FileMode) error { +func (s *TarWriterSystem) WriteFile(filename AbsPath, data []byte, perm fs.FileMode) error { header := s.headerTemplate header.Typeflag = tar.TypeReg header.Name = filename.String() @@ -56,7 +56,7 @@ func (s *TARWriterSystem) WriteFile(filename AbsPath, data []byte, perm fs.FileM } // WriteSymlink implements System.WriteSymlink. -func (s *TARWriterSystem) WriteSymlink(oldname string, newname AbsPath) error { +func (s *TarWriterSystem) WriteSymlink(oldname string, newname AbsPath) error { header := s.headerTemplate header.Typeflag = tar.TypeSymlink header.Name = newname.String() diff --git a/internal/chezmoi/tarwritersystem_test.go b/internal/chezmoi/tarwritersystem_test.go index 7a7ca9da922..31f817506b0 100644 --- a/internal/chezmoi/tarwritersystem_test.go +++ b/internal/chezmoi/tarwritersystem_test.go @@ -15,9 +15,9 @@ import ( "github.com/twpayne/chezmoi/v2/internal/chezmoitest" ) -var _ System = &TARWriterSystem{} +var _ System = &TarWriterSystem{} -func TestTARWriterSystem(t *testing.T) { +func TestTarWriterSystem(t *testing.T) { chezmoitest.WithTestFS(t, map[string]interface{}{ "/home/user/.local/share/chezmoi": map[string]interface{}{ ".chezmoiignore": "README.md\n", @@ -50,7 +50,7 @@ func TestTARWriterSystem(t *testing.T) { requireEvaluateAll(t, s, system) b := &bytes.Buffer{} - tarWriterSystem := NewTARWriterSystem(b, tar.Header{}) + tarWriterSystem := NewTarWriterSystem(b, tar.Header{}) persistentState := NewMockPersistentState() require.NoError(t, s.applyAll(tarWriterSystem, system, persistentState, EmptyAbsPath, ApplyOptions{ Include: NewEntryTypeSet(EntryTypesAll), diff --git a/internal/cmd/archivecmd.go b/internal/cmd/archivecmd.go index 6715b86b3ad..313799ca88f 100644 --- a/internal/cmd/archivecmd.go +++ b/internal/cmd/archivecmd.go @@ -66,7 +66,7 @@ func (c *Config) runArchiveCmd(cmd *cobra.Command, args []string) error { } switch format { case chezmoi.ArchiveFormatTar, chezmoi.ArchiveFormatTarGz, chezmoi.ArchiveFormatTgz: - archiveSystem = chezmoi.NewTARWriterSystem(&output, tarHeaderTemplate()) + archiveSystem = chezmoi.NewTarWriterSystem(&output, tarHeaderTemplate()) case chezmoi.ArchiveFormatZip: archiveSystem = chezmoi.NewZIPWriterSystem(&output, time.Now().UTC()) default:
chore
Make capitalization of tar more consistent
27016cfa2127b0813463a8c131cc3fac124262f7
2021-02-22 01:34:39
Tom Payne
megacommit: move to Go 1.16 and replace chezmoi with v2
false
diff --git a/.cirrus.yml b/.cirrus.yml index 36be043ba9b..9b03273165b 100644 --- a/.cirrus.yml +++ b/.cirrus.yml @@ -4,6 +4,9 @@ env: freebsd_12_task: freebsd_instance: image: freebsd-12-1-release-amd64 - install_script: pkg install -y git go - build_script: go build -v ./... - test_script: go test -race ./... + install_script: | + pkg install -y git go + GOBIN=$PWD/bin go get golang.org/dl/go1.16 + bin/go1.16 download + build_script: bin/go1.16 build -v ./... + test_script: bin/go1.16 test -race ./... diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index 2b048cded19..949562b3e30 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -1,10 +1,11 @@ # [Choice] Go version: 1, 1.15, 1.14 -ARG VARIANT=1.14 -FROM mcr.microsoft.com/vscode/devcontainers/go:0-${VARIANT} +# FIXME remove dev- when 1.16 container is published +ARG VARIANT=dev-1.16 +FROM mcr.microsoft.com/vscode/devcontainers/go:${VARIANT} # [Optional] Uncomment this section to install additional OS packages. RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ - && apt-get -y install --no-install-recommends acl musl-tools snapcraft + && apt-get -y install --no-install-recommends acl musl-tools # [Optional] Uncomment the next line to use go get to install anything else you need RUN go get -x mvdan.cc/gofumpt diff --git a/.gitattributes b/.gitattributes index 900ac495777..d9e289a0fe5 100644 --- a/.gitattributes +++ b/.gitattributes @@ -2,5 +2,4 @@ # Make GitHub language breakdown more accurate, see https://github.com/github/linguist *.gen.go linguist-generated -chezmoi2/completions/* linguist-generated completions/* linguist-generated diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 845bd196e44..7092b3dda9b 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -20,9 +20,8 @@ jobs: - name: Set up Go uses: actions/setup-go@v2 with: - go-version: 1.15.x + go-version: 1.16.0 - name: Cache Go modules - if: runner.os != 'macos' # FIXME re-enable uses: actions/cache@v2 with: path: ~/go/pkg/mod @@ -42,7 +41,6 @@ jobs: - name: Run run: | go run . --version - go run ./chezmoi2 --version - name: Test run: go test -race ./... test-release: @@ -55,7 +53,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v2 with: - go-version: 1.15.x + go-version: 1.16.0 - name: Cache Go modules uses: actions/cache@v2 with: @@ -78,11 +76,6 @@ jobs: ./dist/chezmoi-cgo-glibc_linux_amd64/chezmoi --version | tee /dev/stderr | grep -q "chezmoi version v" ./dist/chezmoi-cgo-musl_linux_amd64/chezmoi --version | tee /dev/stderr | grep -q "chezmoi version v" ./dist/chezmoi-nocgo_linux_386/chezmoi --version | tee /dev/stderr | grep -q "chezmoi version v" - file ./dist/chezmoi2-cgo-glibc_linux_amd64/chezmoi2 | tee /dev/stderr | grep -q "dynamically linked" - file ./dist/chezmoi2-cgo-musl_linux_amd64/chezmoi2 | tee /dev/stderr | grep -q "statically linked" - ./dist/chezmoi2-cgo-glibc_linux_amd64/chezmoi2 --version | tee /dev/stderr | grep -q "chezmoi2 version v" - ./dist/chezmoi2-cgo-musl_linux_amd64/chezmoi2 --version | tee /dev/stderr | grep -q "chezmoi2 version v" - ./dist/chezmoi2-nocgo_linux_386/chezmoi2 --version | tee /dev/stderr | grep -q "chezmoi2 version v" - name: Artifact chezmoi-linux-amd64 uses: actions/upload-artifact@v2 with: @@ -103,33 +96,13 @@ jobs: with: name: chezmoi-windows-amd64 path: dist/chezmoi-nocgo_windows_amd64/chezmoi.exe - - name: Artifact chezmoi2-linux-amd64 - uses: actions/upload-artifact@v2 - with: - name: chezmoi2-linux-amd64 - path: dist/chezmoi2-cgo-glibc_linux_amd64/chezmoi2 - - name: Artifact chezmoi2-linux-musl-amd64 - uses: actions/upload-artifact@v2 - with: - name: chezmoi2-linux-musl-amd64 - path: dist/chezmoi2-cgo-musl_linux_amd64/chezmoi2 - - name: Artifact chezmoi2-macos-amd64 - uses: actions/upload-artifact@v2 - with: - name: chezmoi2-macos-amd64 - path: dist/chezmoi2-nocgo_darwin_amd64/chezmoi2 - - name: Artifact chezmoi2-windows-amd64 - uses: actions/upload-artifact@v2 - with: - name: chezmoi2-windows-amd64 - path: dist/chezmoi2-nocgo_windows_amd64/chezmoi2.exe generate: runs-on: ubuntu-18.04 steps: - name: Set up Go uses: actions/setup-go@v2 with: - go-version: 1.15.x + go-version: 1.16.0 - name: Cache Go modules uses: actions/cache@v2 with: @@ -141,25 +114,35 @@ jobs: uses: actions/checkout@v2 - name: Generate run: | - go generate - go generate ./chezmoi2 + make completions git diff --exit-code lint: runs-on: ubuntu-18.04 steps: - - name: Checkout - uses: actions/checkout@v2 - - name: Lint - uses: golangci/golangci-lint-action@v2 - with: - version: v1.36.0 - - name: ShellCheck - uses: ludeeus/[email protected] - with: - scandir: ./assets/scripts - - name: Whitespace - run: - go run ./internal/cmd/lint-whitespace + - name: Set up Go + uses: actions/setup-go@v2 + with: + go-version: 1.16.0 + - name: Cache Go modules + uses: actions/cache@v2 + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go- + - name: Checkout + uses: actions/checkout@v2 + - name: Lint + uses: golangci/golangci-lint-action@v2 + with: + version: v1.37.0 + - name: ShellCheck + uses: ludeeus/[email protected] + with: + scandir: ./assets/scripts + - name: Whitespace + run: + go run ./internal/cmd/lint-whitespace release: if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') needs: @@ -176,7 +159,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v2 with: - go-version: 1.15.x + go-version: 1.16.0 - name: Cache Go modules uses: actions/cache@v2 with: diff --git a/.golangci.yml b/.golangci.yml index 05a55459b2a..f8bd21671f3 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -6,6 +6,7 @@ linters: - depguard - dogsled - dupl + - durationcheck - errcheck - errorlint - exhaustive @@ -24,13 +25,15 @@ linters: - gosec - gosimple - govet - - ifshort - ineffassign - interfacer - makezero - misspell + - noctx + - nolintlint - prealloc - predeclared + - revive - rowserrcheck - scopelint - sqlclosecheck @@ -47,6 +50,7 @@ linters: disable: - exhaustivestruct - funlen + - ifshort # FIXME re-enable when bugs in ifshort are fixed - gochecknoglobals - gochecknoinits - gocognit @@ -60,8 +64,6 @@ linters: - nakedret - nestif - nlreturn - - noctx - - nolintlint # FIXME re-enable - paralleltest - testpackage - tparallel @@ -69,6 +71,10 @@ linters: - wsl linters-settings: + forbidigo: + forbid: + - ^fmt\.Print.*$ + - ^ioutil\. gofumpt: extra-rules: true goimports: @@ -81,12 +87,6 @@ issues: - linters: - goerr113 text: "do not define dynamic errors, use wrapped static errors instead" - - linters: - - dupl - path: "^cmd/secret(go)?pass\\.go$" - - linters: - - forbidigo - path: ^cmd/ - linters: - forbidigo - gosec diff --git a/.goreleaser.yaml b/.goreleaser.yaml index c4ace2af88b..546d4773168 100644 --- a/.goreleaser.yaml +++ b/.goreleaser.yaml @@ -52,59 +52,6 @@ builds: goarch: 386 - goos: linux goarch: amd64 -- id: chezmoi2-cgo-glibc - binary: chezmoi2 - main: ./chezmoi2/main.go - env: - - CGO_ENABLED=1 - goos: - - linux - goarch: - - amd64 -- id: chezmoi2-cgo-musl - binary: chezmoi2 - main: ./chezmoi2/main.go - env: - - CC=/usr/bin/musl-gcc - - CGO_ENABLED=1 - goos: - - linux - goarch: - - amd64 - ldflags: - - '-s' - - '-w' - - '-X main.version={{.Version}}' - - '-X main.commit={{.Commit}}' - - '-X main.date={{.Date}}' - - '-X main.builtBy=goreleaser' - - '-linkmode external' - - '--extldflags "-static"' -- id: chezmoi2-nocgo - binary: chezmoi2 - main: ./chezmoi2/main.go - env: - - CGO_ENABLED=0 - goos: - - linux - - darwin - - freebsd - - openbsd - - windows - goarch: - - 386 - - amd64 - - arm - - arm64 - - ppc64 - - ppc64le - goarm: - - "" - ignore: - - goos: darwin - goarch: 386 - - goos: linux - goarch: amd64 archives: - builds: diff --git a/Makefile b/Makefile index 9ae8003902f..d5764ecf2e7 100644 --- a/Makefile +++ b/Makefile @@ -1,51 +1,51 @@ -GOLANGCI_LINT_VERSION=1.36.0 +GO?=go +GOLANGCI_LINT_VERSION=1.37.0 .PHONY: default -default: generate build run test lint format +default: build run test lint format .PHONY: build build: build-darwin build-linux build-windows .PHONY: build-darwin -build-darwin: generate - GOOS=darwin GOARCH=amd64 go build -o /dev/null . - GOOS=darwin GOARCH=amd64 go build -o /dev/null ./chezmoi2 +build-darwin: + GOOS=darwin GOARCH=amd64 $(GO) build -o /dev/null . + GOOS=darwin GOARCH=arm64 $(GO) build -o /dev/null . .PHONY: build-linux -build-linux: generate - GOOS=linux GOARCH=amd64 go build -o /dev/null . - GOOS=linux GOARCH=amd64 go build -o /dev/null ./chezmoi2 +build-linux: + GOOS=linux GOARCH=amd64 $(GO) build -o /dev/null . .PHONY: build-windows -build-windows: generate - GOOS=windows GOARCH=amd64 go build -o /dev/null . - GOOS=windows GOARCH=amd64 go build -o /dev/null ./chezmoi2 +build-windows: + GOOS=windows GOARCH=amd64 $(GO) build -o /dev/null . .PHONY: run -run: generate - go run . --version - go run ./chezmoi2 --version - -.PHONY: generate -generate: - go generate - go generate ./chezmoi2 +run: + $(GO) run . --version .PHONY: test -test: generate - go test ./... +test: + $(GO) test ./... + +.PHONY: completions +completions: + $(GO) run . completion bash -o completions/chezmoi-completion.bash + $(GO) run . completion fish -o completions/chezmoi.fish + $(GO) run . completion powershell -o completions/chezmoi.ps1 + $(GO) run . completion zsh -o completions/chezmoi.zsh .PHONY: generate-install.sh generate-install.sh: - go run ./internal/cmd/generate-install.sh > assets/scripts/install.sh + $(GO) run ./internal/cmd/generate-install.sh > assets/scripts/install.sh .PHONY: lint -lint: ensure-golangci-lint generate +lint: ensure-golangci-lint ./bin/golangci-lint run - go run ./internal/cmd/lint-whitespace + $(GO) run ./internal/cmd/lint-whitespace .PHONY: format -format: ensure-gofumports generate +format: ensure-gofumports find . -name \*.go | xargs ./bin/gofumports -local github.com/twpayne/chezmoi -w .PHONY: ensure-tools @@ -55,7 +55,7 @@ ensure-tools: ensure-gofumports ensure-golangci-lint ensure-gofumports: if [ ! -x bin/gofumports ] ; then \ mkdir -p bin ; \ - ( cd $$(mktemp -d) && go mod init tmp && GOBIN=$(shell pwd)/bin go get mvdan.cc/gofumpt/gofumports ) ; \ + GOBIN=$(shell pwd)/bin $(GO) install mvdan.cc/gofumpt/gofumports@latest ; \ fi .PHONY: ensure-golangci-lint diff --git a/README.md b/README.md index d521d5f2e04..86a3f08532f 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,7 @@ Manage your dotfiles across multiple diverse machines, securely. +* [Go to chezmoi.io](#go-to-chezmoiio) * [How do I start with chezmoi now?](#how-do-i-start-with-chezmoi-now) * [What does chezmoi do and why should I use it?](#what-does-chezmoi-do-and-why-should-i-use-it) * [What are chezmoi's key features?](#what-are-chezmois-key-features) @@ -19,6 +20,14 @@ Manage your dotfiles across multiple diverse machines, securely. * [What documentation is available?](#what-documentation-is-available) * [License](#license) +## Go to chezmoi.io + +Documentation for the current version of chezmoi is at +[chezmoi.io](https://chezmoi.io/). + +This repository contains documentation for version 2, which hasn't been released +yet. + ## How do I start with chezmoi now? [Install chezmoi](docs/INSTALL.md) then read the [quick start diff --git a/assets/templates/templates.go b/assets/templates/templates.go new file mode 100644 index 00000000000..a3c900004fc --- /dev/null +++ b/assets/templates/templates.go @@ -0,0 +1,8 @@ +// Package templates contains chezmoi's templates. +package templates + +import "embed" + +// FS contains all templates. +//go:embed *.tmpl +var FS embed.FS diff --git a/chezmoi2/cmd/cmd.go b/chezmoi2/cmd/cmd.go deleted file mode 100644 index 6e6c5af8f9c..00000000000 --- a/chezmoi2/cmd/cmd.go +++ /dev/null @@ -1,109 +0,0 @@ -package cmd - -import ( - "errors" - "fmt" - "os" - "strconv" - - "github.com/spf13/cobra" -) - -// Command annotations. -const ( - doesNotRequireValidConfig = "chezmoi_does_not_require_valid_config" - modifiesConfigFile = "chezmoi_modifies_config_file" - modifiesDestinationDirectory = "chezmoi_modifies_destination_directory" - modifiesSourceDirectory = "chezmoi_modifies_source_directory" - persistentStateMode = "chezmoi_persistent_state_mode" - requiresConfigDirectory = "chezmoi_requires_config_directory" - requiresSourceDirectory = "chezmoi_requires_source_directory" - runsCommands = "chezmoi_runs_commands" -) - -// Persistent state modes. -const ( - persistentStateModeEmpty = "empty" - persistentStateModeReadOnly = "read-only" - persistentStateModeReadMockWrite = "read-mock-write" - persistentStateModeReadWrite = "read-write" -) - -var noArgs = []string(nil) - -// An ErrExitCode indicates the the main program should exit with the given -// code. -type ErrExitCode int - -func (e ErrExitCode) Error() string { return "" } - -// A VersionInfo contains a version. -type VersionInfo struct { - Version string - Commit string - Date string - BuiltBy string -} - -// Main runs chezmoi and returns an exit code. -func Main(versionInfo VersionInfo, args []string) int { - if err := runMain(versionInfo, args); err != nil { - if s := err.Error(); s != "" { - fmt.Fprintf(os.Stderr, "chezmoi: %s\n", s) - } - errExitCode := ErrExitCode(1) - _ = errors.As(err, &errExitCode) - return int(errExitCode) - } - return 0 -} - -func asset(name string) ([]byte, error) { - asset, ok := assets[name] - if !ok { - return nil, fmt.Errorf("%s: not found", name) - } - return asset, nil -} - -func boolAnnotation(cmd *cobra.Command, key string) bool { - value, ok := cmd.Annotations[key] - if !ok { - return false - } - boolValue, err := strconv.ParseBool(value) - if err != nil { - panic(err) - } - return boolValue -} - -func example(command string) string { - return helps[command].example -} - -func mustLongHelp(command string) string { - help, ok := helps[command] - if !ok { - panic(fmt.Sprintf("%s: no long help", command)) - } - return help.long -} - -func markPersistentFlagsRequired(cmd *cobra.Command, flags ...string) { - for _, flag := range flags { - if err := cmd.MarkPersistentFlagRequired(flag); err != nil { - panic(err) - } - } -} - -func runMain(versionInfo VersionInfo, args []string) error { - config, err := newConfig( - withVersionInfo(versionInfo), - ) - if err != nil { - return err - } - return config.execute(args) -} diff --git a/chezmoi2/cmd/cmd_test.go b/chezmoi2/cmd/cmd_test.go deleted file mode 100644 index c1f05a9f533..00000000000 --- a/chezmoi2/cmd/cmd_test.go +++ /dev/null @@ -1,23 +0,0 @@ -package cmd - -import ( - "testing" - - "github.com/stretchr/testify/assert" - - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoitest" -) - -func init() { - // github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi reads the umask - // before github.com/twpayne/chezmoi/chezmoi2/internal/chezmoitest sets it, - // so update it. - chezmoi.Umask = chezmoitest.Umask -} - -func TestMustGetLongHelpPanics(t *testing.T) { - assert.Panics(t, func() { - mustLongHelp("non-existent-command") - }) -} diff --git a/chezmoi2/cmd/config.go b/chezmoi2/cmd/config.go deleted file mode 100644 index d07699bb67e..00000000000 --- a/chezmoi2/cmd/config.go +++ /dev/null @@ -1,1477 +0,0 @@ -package cmd - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "io" - "os" - "os/exec" - "os/user" - "regexp" - "runtime" - "runtime/pprof" - "sort" - "strings" - "text/template" - "time" - "unicode" - - "github.com/Masterminds/sprig/v3" - "github.com/coreos/go-semver/semver" - "github.com/go-git/go-git/v5/plumbing/format/diff" - "github.com/rs/zerolog" - "github.com/rs/zerolog/log" - "github.com/spf13/cobra" - "github.com/spf13/viper" - "github.com/twpayne/go-shell" - "github.com/twpayne/go-vfs" - vfsafero "github.com/twpayne/go-vfsafero" - "github.com/twpayne/go-xdg/v3" - "golang.org/x/term" - - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" - "github.com/twpayne/chezmoi/internal/git" -) - -var defaultFormat = "json" - -type purgeOptions struct { - binary bool -} - -type templateConfig struct { - Options []string `mapstructure:"options"` -} - -// A Config represents a configuration. -type Config struct { - version *semver.Version - versionInfo VersionInfo - versionStr string - - bds *xdg.BaseDirectorySpecification - - fs vfs.FS - configFile string - baseSystem chezmoi.System - sourceSystem chezmoi.System - destSystem chezmoi.System - persistentState chezmoi.PersistentState - color bool - - // Global configuration, settable in the config file. - SourceDir string `mapstructure:"sourceDir"` - DestDir string `mapstructure:"destDir"` - Umask os.FileMode `mapstructure:"umask"` - Remove bool `mapstructure:"remove"` - Color string `mapstructure:"color"` - Data map[string]interface{} `mapstructure:"data"` - Template templateConfig `mapstructure:"template"` - UseBuiltinGit string `mapstructure:"useBuiltinGit"` - - // Global configuration, not settable in the config file. - cpuProfile string - debug bool - dryRun bool - force bool - homeDir string - keepGoing bool - noPager bool - noTTY bool - outputStr string - verbose 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. - CD cdCmdConfig `mapstructure:"cd"` - Diff diffCmdConfig `mapstructure:"diff"` - Edit editCmdConfig `mapstructure:"edit"` - Git gitCmdConfig `mapstructure:"git"` - Merge mergeCmdConfig `mapstructure:"merge"` - - // Command configurations, not settable in the config file. - add addCmdConfig - apply applyCmdConfig - archive archiveCmdConfig - data dataCmdConfig - dump dumpCmdConfig - executeTemplate executeTemplateCmdConfig - _import importCmdConfig - init initCmdConfig - managed managedCmdConfig - purge purgeCmdConfig - secretKeyring secretKeyringCmdConfig - state stateCmdConfig - status statusCmdConfig - update updateCmdConfig - verify verifyCmdConfig - - // Computed configuration. - configFileAbsPath chezmoi.AbsPath - homeDirAbsPath chezmoi.AbsPath - sourceDirAbsPath chezmoi.AbsPath - destDirAbsPath chezmoi.AbsPath - encryption chezmoi.Encryption - - stdin io.Reader - stdout io.Writer - stderr io.Writer - - 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"` -} - -var ( - persistentStateFilename = chezmoi.RelPath("chezmoistate.boltdb") - configStateKey = []byte("configState") - commitMessageTemplateAsset = "assets/templates/COMMIT_MESSAGE.tmpl" - - identifierRx = regexp.MustCompile(`\A[\pL_][\pL\p{Nd}_]*\z`) - whitespaceRx = regexp.MustCompile(`\s+`) - - assets = make(map[string][]byte) -) - -// newConfig creates a new Config with the given options. -func newConfig(options ...configOption) (*Config, error) { - homeDir, err := os.UserHomeDir() - if err != nil { - return nil, err - } - normalizedHomeDir, err := chezmoi.NormalizePath(homeDir) - if err != nil { - return nil, err - } - - bds, err := xdg.NewBaseDirectorySpecification() - if err != nil { - return nil, err - } - - c := &Config{ - bds: bds, - fs: vfs.OSFS, - homeDir: homeDir, - DestDir: homeDir, - Umask: chezmoi.Umask, - Color: "auto", - Diff: diffCmdConfig{ - Pager: firstNonEmptyString(os.Getenv("PAGER"), "less"), - include: chezmoi.NewIncludeSet(chezmoi.IncludeAll &^ chezmoi.IncludeScripts), - }, - Edit: editCmdConfig{ - include: chezmoi.NewIncludeSet(chezmoi.IncludeDirs | chezmoi.IncludeFiles | chezmoi.IncludeSymlinks), - }, - Git: gitCmdConfig{ - Command: "git", - }, - Merge: mergeCmdConfig{ - Command: "vimdiff", - }, - Template: templateConfig{ - Options: chezmoi.DefaultTemplateOptions, - }, - templateFuncs: sprig.TxtFuncMap(), - Bitwarden: bitwardenConfig{ - Command: "bw", - }, - Gopass: gopassConfig{ - Command: "gopass", - }, - Keepassxc: keepassxcConfig{ - Command: "keepassxc-cli", - }, - Lastpass: lastpassConfig{ - Command: "lpass", - }, - Onepassword: onepasswordConfig{ - Command: "op", - }, - Pass: passConfig{ - Command: "pass", - }, - Vault: vaultConfig{ - Command: "vault", - }, - AGE: chezmoi.AGEEncryption{ - Command: "age", - Suffix: ".age", - }, - GPG: chezmoi.GPGEncryption{ - Command: "gpg", - Suffix: ".asc", - }, - add: addCmdConfig{ - include: chezmoi.NewIncludeSet(chezmoi.IncludeAll), - recursive: true, - }, - apply: applyCmdConfig{ - include: chezmoi.NewIncludeSet(chezmoi.IncludeAll), - recursive: true, - }, - archive: archiveCmdConfig{ - include: chezmoi.NewIncludeSet(chezmoi.IncludeAll), - recursive: true, - }, - data: dataCmdConfig{ - format: defaultFormat, - }, - dump: dumpCmdConfig{ - format: defaultFormat, - include: chezmoi.NewIncludeSet(chezmoi.IncludeAll), - recursive: true, - }, - _import: importCmdConfig{ - include: chezmoi.NewIncludeSet(chezmoi.IncludeAll), - }, - managed: managedCmdConfig{ - include: chezmoi.NewIncludeSet(chezmoi.IncludeDirs | chezmoi.IncludeFiles | chezmoi.IncludeSymlinks), - }, - state: stateCmdConfig{ - dump: stateDumpCmdConfig{ - format: defaultFormat, - }, - }, - status: statusCmdConfig{ - include: chezmoi.NewIncludeSet(chezmoi.IncludeAll), - recursive: true, - }, - update: updateCmdConfig{ - apply: true, - include: chezmoi.NewIncludeSet(chezmoi.IncludeAll), - recursive: true, - }, - verify: verifyCmdConfig{ - include: chezmoi.NewIncludeSet(chezmoi.IncludeAll &^ chezmoi.IncludeScripts), - recursive: true, - }, - - stdin: os.Stdin, - stdout: os.Stdout, - stderr: os.Stderr, - - homeDirAbsPath: normalizedHomeDir, - } - - for key, value := range map[string]interface{}{ - "bitwarden": c.bitwardenTemplateFunc, - "bitwardenAttachment": c.bitwardenAttachmentTemplateFunc, - "bitwardenFields": c.bitwardenFieldsTemplateFunc, - "gitHubKeys": c.gitHubKeysTemplateFunc, - "gopass": c.gopassTemplateFunc, - "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, - "onepassword": c.onepasswordTemplateFunc, - "onepasswordDetailsFields": c.onepasswordDetailsFieldsTemplateFunc, - "onepasswordDocument": c.onepasswordDocumentTemplateFunc, - "pass": c.passTemplateFunc, - "secret": c.secretTemplateFunc, - "secretJSON": c.secretJSONTemplateFunc, - "stat": c.statTemplateFunc, - "vault": c.vaultTemplateFunc, - } { - c.addTemplateFunc(key, value) - } - - for _, option := range options { - if err := option(c); err != nil { - return nil, err - } - } - - c.configFile = string(defaultConfigFile(c.fs, c.bds)) - c.SourceDir = string(defaultSourceDir(c.fs, c.bds)) - - c.homeDirAbsPath, err = chezmoi.NormalizePath(c.homeDir) - if err != nil { - return nil, err - } - c._import.destination = string(c.homeDirAbsPath) - - return c, nil -} - -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.IncludeSet - recursive bool - skipEncrypted bool - sourcePath bool - umask os.FileMode - preApplyFunc chezmoi.PreApplyFunc -} - -func (c *Config) applyArgs(targetSystem chezmoi.System, targetDirAbsPath chezmoi.AbsPath, args []string, options applyArgsOptions) error { - sourceState, err := c.sourceState() - if err != nil { - return err - } - - var currentConfigTemplateContentsSHA256 []byte - _, _, configTemplateContents, err := c.findConfigTemplate() - if err != nil { - return err - } - 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) - } - configTemplateContentsUnchanged := (currentConfigTemplateContentsSHA256 == nil && previousConfigTemplateContentsSHA256 == nil) || - bytes.Equal(currentConfigTemplateContentsSHA256, previousConfigTemplateContentsSHA256) - if !configTemplateContentsUnchanged { - if c.force { - 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") - } - } - - applyOptions := chezmoi.ApplyOptions{ - Include: options.include, - PreApplyFunc: options.preApplyFunc, - SkipEncrypted: options.skipEncrypted, - Umask: options.umask, - } - - var targetRelPaths chezmoi.RelPaths - switch { - case len(args) == 0: - targetRelPaths = sourceState.TargetRelPaths() - case options.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 - } - } - - 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", err) - keptGoingAfterErr = true - case err != nil: - return err - } - } - if keptGoingAfterErr { - return ErrExitCode(1) - } - - return nil -} - -func (c *Config) cmdOutput(dirAbsPath chezmoi.AbsPath, name string, args []string) ([]byte, error) { - cmd := exec.Command(name, args...) - if dirAbsPath != "" { - dirRawAbsPath, err := c.baseSystem.RawPath(dirAbsPath) - if err != nil { - return nil, err - } - cmd.Dir = string(dirRawAbsPath) - } - return c.baseSystem.IdempotentCmdOutput(cmd) -} - -func (c *Config) defaultPreApplyFunc(targetRelPath chezmoi.RelPath, targetEntryState, lastWrittenEntryState, actualEntryState *chezmoi.EntryState) error { - switch { - case targetEntryState.Type == chezmoi.EntryStateTypeScript: - return nil - case c.force: - return nil - case lastWrittenEntryState == nil: - return nil - case lastWrittenEntryState.Equivalent(actualEntryState): - return nil - } - - // LATER add merge option - var choices []string - actualContents := actualEntryState.Contents() - targetContents := targetEntryState.Contents() - if actualContents != nil || targetContents != nil { - choices = append(choices, "diff") - } - choices = append(choices, "overwrite", "all-overwite", "skip", "quit") - for { - switch choice, err := c.promptChoice(fmt.Sprintf("%s has changed since chezmoi last wrote it", targetRelPath), 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 ErrExitCode(1) - default: - return nil - } - } -} - -func (c *Config) defaultTemplateData() map[string]interface{} { - data := map[string]interface{}{ - "arch": runtime.GOARCH, - "homeDir": c.homeDir, - "os": runtime.GOOS, - "sourceDir": c.sourceDirAbsPath, - "version": map[string]interface{}{ - "builtBy": c.versionInfo.BuiltBy, - "commit": c.versionInfo.Commit, - "date": c.versionInfo.Date, - "version": c.versionInfo.Version, - }, - } - - // 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. - if currentUser, err := user.Current(); err == nil { - data["username"] = currentUser.Username - if runtime.GOOS != "windows" { - if group, err := user.LookupGroupId(currentUser.Gid); err == nil { - data["group"] = group.Name - } else { - log.Debug(). - Str("gid", currentUser.Gid). - Err(err). - Msg("user.LookupGroupId") - } - } - } else { - log.Debug(). - Err(err). - Msg("user.Current") - user, ok := os.LookupEnv("USER") - if ok { - data["username"] = user - } else { - log.Debug(). - Str("key", "USER"). - Bool("ok", ok). - Msg("os.LookupEnv") - } - } - - if fqdnHostname, err := chezmoi.FQDNHostname(c.fs); err == nil && fqdnHostname != "" { - data["fqdnHostname"] = fqdnHostname - } else { - log.Debug(). - Err(err). - Msg("chezmoi.EtcHostsFQDNHostname") - } - - if hostname, err := os.Hostname(); err == nil { - data["hostname"] = strings.SplitN(hostname, ".", 2)[0] - } else { - log.Debug(). - Err(err). - Msg("os.Hostname") - } - - if kernelInfo, err := chezmoi.KernelInfo(c.fs); err == nil { - data["kernel"] = kernelInfo - } else { - log.Debug(). - Err(err). - Msg("chezmoi.KernelInfo") - } - - if osRelease, err := chezmoi.OSRelease(c.fs); err == nil { - data["osRelease"] = upperSnakeCaseToCamelCaseMap(osRelease) - } else { - log.Debug(). - Err(err). - Msg("chezmoi.OSRelease") - } - - return map[string]interface{}{ - "chezmoi": data, - } -} - -func (c *Config) destAbsPathInfos(sourceState *chezmoi.SourceState, args []string, recursive, follow bool) (map[chezmoi.AbsPath]os.FileInfo, error) { - destAbsPathInfos := make(map[chezmoi.AbsPath]os.FileInfo) - for _, arg := range args { - 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 recursive { - if err := chezmoi.Walk(c.destSystem, destAbsPath, func(destAbsPath chezmoi.AbsPath, info os.FileInfo, err error) error { - if err != nil { - return err - } - if follow && info.Mode()&os.ModeType == os.ModeSymlink { - info, err = c.destSystem.Stat(destAbsPath) - if err != nil { - return err - } - } - return sourceState.AddDestAbsPathInfos(destAbsPathInfos, c.destSystem, destAbsPath, info) - }); err != nil { - return nil, err - } - } else { - var info os.FileInfo - if follow { - info, err = c.destSystem.Stat(destAbsPath) - } else { - info, err = c.destSystem.Lstat(destAbsPath) - } - if err != nil { - return nil, err - } - if err := sourceState.AddDestAbsPathInfos(destAbsPathInfos, c.destSystem, destAbsPath, info); err != nil { - return nil, err - } - } - } - return destAbsPathInfos, nil -} - -func (c *Config) diffFile(path chezmoi.RelPath, fromData []byte, fromMode os.FileMode, toData []byte, toMode os.FileMode) error { - var sb strings.Builder - unifiedEncoder := diff.NewUnifiedEncoder(&sb, diff.DefaultContextLines) - if c.color { - unifiedEncoder.SetColor(diff.NewColorConfig()) - } - diffPatch, err := chezmoi.DiffPatch(path, fromData, fromMode, toData, toMode) - if err != nil { - return err - } - if err := unifiedEncoder.Encode(diffPatch); err != nil { - return err - } - return c.diffPager(sb.String()) -} - -func (c *Config) diffPager(output string) error { - if c.noPager || c.Diff.Pager == "" { - return c.writeOutputString(output) - } - - // If the pager command contains any spaces, assume that it is a full - // shell command to be executed via the user's shell. Otherwise, execute - // it directly. - var pagerCmd *exec.Cmd - if strings.IndexFunc(c.Diff.Pager, unicode.IsSpace) != -1 { - shell, _ := shell.CurrentUserShell() - pagerCmd = exec.Command(shell, "-c", c.Diff.Pager) - } else { - //nolint:gosec - pagerCmd = exec.Command(c.Diff.Pager) - } - pagerCmd.Stdin = bytes.NewBufferString(output) - pagerCmd.Stdout = c.stdout - pagerCmd.Stderr = c.stderr - return pagerCmd.Run() -} - -func (c *Config) doPurge(purgeOptions *purgeOptions) error { - if c.persistentState != nil { - if err := c.persistentState.Close(); err != nil { - return err - } - } - - absSlashPersistentStateFile := c.persistentStateFile() - absPaths := chezmoi.AbsPaths{ - c.configFileAbsPath.Dir(), - c.configFileAbsPath, - absSlashPersistentStateFile, - c.sourceDirAbsPath, - } - if purgeOptions != nil && purgeOptions.binary { - executable, err := os.Executable() - if err == nil { - absPaths = append(absPaths, chezmoi.AbsPath(executable)) - } - } - - // Remove all paths that exist. - for _, absPath := range absPaths { - switch _, err := c.destSystem.Stat(absPath); { - case os.IsNotExist(err): - continue - case err != nil: - return err - } - - if !c.force { - switch choice, err := c.promptChoice(fmt.Sprintf("Remove %s", absPath), yesNoAllQuit); { - case err != nil: - return err - case choice == "yes": - case choice == "no": - continue - case choice == "all": - c.force = true - case choice == "quit": - return nil - } - } - - switch err := c.destSystem.RemoveAll(absPath); { - case os.IsPermission(err): - continue - case err != nil: - return err - } - } - - return nil -} - -// editor returns the path to the user's editor and any extra arguments. -func (c *Config) editor() (string, []string) { - // If the user has set and edit command then use it. - if c.Edit.Command != "" { - return c.Edit.Command, c.Edit.Args - } - - // Prefer $VISUAL over $EDITOR and fallback to vi. - editor := firstNonEmptyString( - os.Getenv("VISUAL"), - os.Getenv("EDITOR"), - "vi", - ) - - // If editor is found, return it. - if path, err := exec.LookPath(editor); err == nil { - return path, nil - } - - // Otherwise, if editor contains spaces, then assume that the first word is - // the editor and the rest are arguments. - components := whitespaceRx.Split(editor, -1) - if len(components) > 1 { - if path, err := exec.LookPath(components[0]); err == nil { - return path, components[1:] - } - } - - // Fallback to editor only. - return editor, nil -} - -func (c *Config) errorf(format string, args ...interface{}) { - fmt.Fprintf(c.stderr, "chezmoi: "+format, args...) -} - -func (c *Config) execute(args []string) error { - rootCmd, err := c.newRootCmd() - if err != nil { - return err - } - rootCmd.SetArgs(args) - return rootCmd.Execute() -} - -func (c *Config) findConfigTemplate() (chezmoi.RelPath, string, []byte, error) { - for _, ext := range viper.SupportedExts { - filename := chezmoi.RelPath(chezmoi.Prefix + "." + ext + chezmoi.TemplateSuffix) - contents, err := c.baseSystem.ReadFile(c.sourceDirAbsPath.Join(filename)) - switch { - case os.IsNotExist(err): - continue - case err != nil: - return "", "", nil, err - } - return chezmoi.RelPath("chezmoi." + ext), ext, contents, nil - } - return "", "", nil, nil -} - -func (c *Config) gitAutoAdd() (*git.Status, error) { - if err := c.run(c.sourceDirAbsPath, c.Git.Command, []string{"add", "."}); err != nil { - return nil, err - } - output, err := c.cmdOutput(c.sourceDirAbsPath, c.Git.Command, []string{"status", "--porcelain=v2"}) - if err != nil { - return nil, err - } - return git.ParseStatusPorcelainV2(output) -} - -func (c *Config) gitAutoCommit(status *git.Status) error { - if status.Empty() { - return nil - } - commitMessageText, err := asset(commitMessageTemplateAsset) - if err != nil { - return err - } - commitMessageTmpl, err := template.New("commit_message").Funcs(c.templateFuncs).Parse(string(commitMessageText)) - if err != nil { - return err - } - commitMessage := strings.Builder{} - if err := commitMessageTmpl.Execute(&commitMessage, status); err != nil { - return err - } - return c.run(c.sourceDirAbsPath, c.Git.Command, []string{"commit", "--message", commitMessage.String()}) -} - -func (c *Config) gitAutoPush(status *git.Status) error { - if status.Empty() { - return nil - } - return c.run(c.sourceDirAbsPath, c.Git.Command, []string{"push"}) -} - -func (c *Config) makeRunEWithSourceState(runE func(*cobra.Command, []string, *chezmoi.SourceState) error) func(*cobra.Command, []string) error { - return func(cmd *cobra.Command, args []string) error { - sourceState, err := c.sourceState() - if err != nil { - return err - } - return runE(cmd, args, sourceState) - } -} - -func (c *Config) marshal(formatStr string, data interface{}) error { - var format chezmoi.Format - switch formatStr { - case "json": - format = chezmoi.JSONFormat - case "yaml": - format = chezmoi.YAMLFormat - default: - return fmt.Errorf("%s: unknown format", formatStr) - } - marshaledData, err := format.Marshal(data) - if err != nil { - return err - } - return c.writeOutput(marshaledData) -} - -func (c *Config) newRootCmd() (*cobra.Command, error) { - rootCmd := &cobra.Command{ - Use: "chezmoi2", - Short: "Manage your dotfiles across multiple diverse machines, securely", - Version: c.versionStr, - PersistentPreRunE: c.persistentPreRunRootE, - PersistentPostRunE: c.persistentPostRunRootE, - SilenceErrors: true, - SilenceUsage: true, - } - - persistentFlags := rootCmd.PersistentFlags() - - persistentFlags.StringVar(&c.Color, "color", c.Color, "colorize diffs") - persistentFlags.StringVarP(&c.DestDir, "destination", "D", c.DestDir, "destination directory") - persistentFlags.BoolVar(&c.Remove, "remove", c.Remove, "remove targets") - persistentFlags.StringVarP(&c.SourceDir, "source", "S", c.SourceDir, "source directory") - persistentFlags.StringVar(&c.UseBuiltinGit, "use-builtin-git", c.UseBuiltinGit, "use builtin git") - for _, key := range []string{ - "color", - "destination", - "remove", - "source", - } { - if err := viper.BindPFlag(key, persistentFlags.Lookup(key)); err != nil { - return nil, err - } - } - - persistentFlags.StringVarP(&c.configFile, "config", "c", c.configFile, "config file") - persistentFlags.StringVar(&c.cpuProfile, "cpu-profile", c.cpuProfile, "write CPU profile to file") - persistentFlags.BoolVarP(&c.dryRun, "dry-run", "n", c.dryRun, "dry run") - persistentFlags.BoolVar(&c.force, "force", c.force, "force") - persistentFlags.BoolVarP(&c.keepGoing, "keep-going", "k", c.keepGoing, "keep going as far as possible after an error") - persistentFlags.BoolVar(&c.noPager, "no-pager", c.noPager, "do not use the pager") - persistentFlags.BoolVar(&c.noTTY, "no-tty", c.noTTY, "don't attempt to get a TTY for reading passwords") - persistentFlags.BoolVarP(&c.verbose, "verbose", "v", c.verbose, "verbose") - persistentFlags.StringVarP(&c.outputStr, "output", "o", c.outputStr, "output file") - persistentFlags.BoolVar(&c.debug, "debug", c.debug, "write debug logs") - - for _, err := range []error{ - rootCmd.MarkPersistentFlagFilename("config"), - rootCmd.MarkPersistentFlagFilename("cpu-profile"), - rootCmd.MarkPersistentFlagDirname("destination"), - rootCmd.MarkPersistentFlagFilename("output"), - rootCmd.MarkPersistentFlagDirname("source"), - } { - if err != nil { - return nil, err - } - } - - rootCmd.SetHelpCommand(c.newHelpCmd()) - for _, newCmdFunc := range []func() *cobra.Command{ - c.newAddCmd, - c.newApplyCmd, - c.newArchiveCmd, - c.newCatCmd, - c.newCDCmd, - c.newChattrCmd, - c.newCompletionCmd, - c.newDataCmd, - c.newDiffCmd, - c.newDocsCmd, - c.newDoctorCmd, - c.newDumpCmd, - c.newEditCmd, - c.newEditConfigCmd, - c.newExecuteTemplateCmd, - c.newForgetCmd, - c.newGitCmd, - c.newImportCmd, - c.newInitCmd, - c.newManagedCmd, - c.newMergeCmd, - c.newPurgeCmd, - c.newRemoveCmd, - c.newSecretCmd, - c.newSourcePathCmd, - c.newStateCmd, - c.newStatusCmd, - c.newUnmanagedCmd, - c.newUpdateCmd, - c.newVerifyCmd, - } { - rootCmd.AddCommand(newCmdFunc()) - } - - return rootCmd, nil -} - -func (c *Config) persistentPostRunRootE(cmd *cobra.Command, args []string) error { - defer pprof.StopCPUProfile() - - if c.persistentState != nil { - if err := c.persistentState.Close(); err != nil { - return err - } - } - - if boolAnnotation(cmd, modifiesConfigFile) { - // Warn the user of any errors reading the config file. - v := viper.New() - v.SetFs(vfsafero.NewAferoFS(c.fs)) - v.SetConfigFile(string(c.configFileAbsPath)) - err := v.ReadInConfig() - if err == nil { - err = v.Unmarshal(&Config{}) - } - if err != nil { - cmd.Printf("warning: %s: %v\n", c.configFileAbsPath, err) - } - } - - if boolAnnotation(cmd, modifiesSourceDirectory) { - var status *git.Status - if c.Git.AutoAdd || c.Git.AutoCommit || c.Git.AutoPush { - var err error - status, err = c.gitAutoAdd() - if err != nil { - return err - } - } - if c.Git.AutoCommit || c.Git.AutoPush { - if err := c.gitAutoCommit(status); err != nil { - return err - } - } - if c.Git.AutoPush { - if err := c.gitAutoPush(status); err != nil { - return err - } - } - } - - return nil -} - -func (c *Config) persistentPreRunRootE(cmd *cobra.Command, args []string) error { - if c.cpuProfile != "" { - f, err := os.Create(c.cpuProfile) - if err != nil { - return err - } - if err := pprof.StartCPUProfile(f); err != nil { - return err - } - } - - var err error - c.configFileAbsPath, err = chezmoi.NewAbsPathFromExtPath(c.configFile, c.homeDirAbsPath) - if err != nil { - return err - } - - if err := c.readConfig(); err != nil { - if !boolAnnotation(cmd, doesNotRequireValidConfig) { - return fmt.Errorf("invalid config: %s: %w", c.configFile, err) - } - cmd.Printf("warning: %s: %v\n", c.configFile, err) - } - - if c.Color == "" || strings.ToLower(c.Color) == "auto" { - if _, ok := os.LookupEnv("NO_COLOR"); ok { - c.color = false - } else if stdout, ok := c.stdout.(*os.File); ok { - c.color = term.IsTerminal(int(stdout.Fd())) - } else { - c.color = false - } - } else if color, err := parseBool(c.Color); err == nil { - c.color = color - } else if !boolAnnotation(cmd, doesNotRequireValidConfig) { - return fmt.Errorf("%s: invalid color value", c.Color) - } - - if c.color { - if err := enableVirtualTerminalProcessing(c.stdout); err != nil { - return err - } - } - - if c.sourceDirAbsPath, err = chezmoi.NewAbsPathFromExtPath(c.SourceDir, c.homeDirAbsPath); err != nil { - return err - } - if c.destDirAbsPath, err = chezmoi.NewAbsPathFromExtPath(c.DestDir, c.homeDirAbsPath); err != nil { - return err - } - - log.Logger = log.Output(zerolog.NewConsoleWriter( - func(w *zerolog.ConsoleWriter) { - w.Out = c.stderr - w.NoColor = !c.color - w.TimeFormat = time.RFC3339 - }, - )) - if !c.debug { - zerolog.SetGlobalLevel(zerolog.InfoLevel) - } - - c.baseSystem = chezmoi.NewRealSystem(c.fs) - if c.debug { - c.baseSystem = chezmoi.NewDebugSystem(c.baseSystem) - } - - switch { - case cmd.Annotations[persistentStateMode] == persistentStateModeEmpty: - c.persistentState = chezmoi.NewMockPersistentState() - case cmd.Annotations[persistentStateMode] == persistentStateModeReadOnly: - persistentStateFile := c.persistentStateFile() - c.persistentState, err = chezmoi.NewBoltPersistentState(c.baseSystem, persistentStateFile, chezmoi.BoltPersistentStateReadOnly) - if err != nil { - return err - } - case cmd.Annotations[persistentStateMode] == persistentStateModeReadMockWrite: - fallthrough - case cmd.Annotations[persistentStateMode] == persistentStateModeReadWrite && c.dryRun: - persistentStateFile := c.persistentStateFile() - persistentState, err := chezmoi.NewBoltPersistentState(c.baseSystem, persistentStateFile, chezmoi.BoltPersistentStateReadOnly) - if err != nil { - return err - } - dryRunPeristentState := chezmoi.NewMockPersistentState() - if err := persistentState.CopyTo(dryRunPeristentState); err != nil { - return err - } - if err := persistentState.Close(); err != nil { - return err - } - c.persistentState = dryRunPeristentState - case cmd.Annotations[persistentStateMode] == persistentStateModeReadWrite: - persistentStateFile := c.persistentStateFile() - c.persistentState, err = chezmoi.NewBoltPersistentState(c.baseSystem, persistentStateFile, chezmoi.BoltPersistentStateReadWrite) - if err != nil { - return err - } - default: - c.persistentState = nil - } - if c.debug && c.persistentState != nil { - c.persistentState = chezmoi.NewDebugPersistentState(c.persistentState) - } - - c.sourceSystem = c.baseSystem - c.destSystem = c.baseSystem - if !boolAnnotation(cmd, modifiesDestinationDirectory) { - c.destSystem = chezmoi.NewReadOnlySystem(c.destSystem) - } - if !boolAnnotation(cmd, modifiesSourceDirectory) { - c.sourceSystem = chezmoi.NewReadOnlySystem(c.sourceSystem) - } - if c.dryRun { - c.sourceSystem = chezmoi.NewDryRunSystem(c.sourceSystem) - c.destSystem = chezmoi.NewDryRunSystem(c.destSystem) - } - if c.verbose { - c.sourceSystem = chezmoi.NewGitDiffSystem(c.sourceSystem, c.stdout, c.sourceDirAbsPath, c.color) - c.destSystem = chezmoi.NewGitDiffSystem(c.destSystem, c.stdout, c.destDirAbsPath, c.color) - } - - switch c.Encryption { - case "age": - c.encryption = &c.AGE - case "gpg": - c.encryption = &c.GPG - case "": - c.encryption = chezmoi.NoEncryption{} - default: - return fmt.Errorf("%s: unknown encryption", c.Encryption) - } - if c.debug { - c.encryption = chezmoi.NewDebugEncryption(c.encryption) - } - - if boolAnnotation(cmd, requiresConfigDirectory) { - if err := chezmoi.MkdirAll(c.baseSystem, c.configFileAbsPath.Dir(), 0o777); err != nil { - return err - } - } - - if boolAnnotation(cmd, requiresSourceDirectory) { - if err := chezmoi.MkdirAll(c.baseSystem, c.sourceDirAbsPath, 0o777); err != nil { - return err - } - } - - if boolAnnotation(cmd, runsCommands) { - if runtime.GOOS == "linux" && c.bds.RuntimeDir != "" { - // Snap sets the $XDG_RUNTIME_DIR environment variable to - // /run/user/$uid/snap.$snap_name, but does not create this - // directory. Consequently, any spawned processes that need - // $XDG_DATA_DIR will fail. As a work-around, create the directory - // if it does not exist. See - // https://forum.snapcraft.io/t/wayland-dconf-and-xdg-runtime-dir/186/13. - if err := chezmoi.MkdirAll(c.baseSystem, chezmoi.AbsPath(c.bds.RuntimeDir), 0o700); err != nil { - return err - } - } - } - - return nil -} - -func (c *Config) persistentStateFile() chezmoi.AbsPath { - if c.configFile != "" { - return chezmoi.AbsPath(c.configFile).Dir().Join(persistentStateFilename) - } - for _, configDir := range c.bds.ConfigDirs { - configDirAbsPath := chezmoi.AbsPath(configDir) - persistentStateFile := configDirAbsPath.Join(chezmoi.RelPath("chezmoi"), persistentStateFilename) - if _, err := os.Stat(string(persistentStateFile)); err == nil { - return persistentStateFile - } - } - return defaultConfigFile(c.fs, c.bds).Dir().Join(persistentStateFilename) -} - -func (c *Config) promptChoice(prompt string, choices []string) (string, error) { - promptWithChoices := fmt.Sprintf("%s [%s]? ", prompt, strings.Join(choices, ",")) - abbreviations := uniqueAbbreviations(choices) - for { - line, err := c.readLine(promptWithChoices) - if err != nil { - return "", err - } - if value, ok := abbreviations[strings.TrimSpace(line)]; ok { - return value, nil - } - } -} - -func (c *Config) readConfig() error { - v := viper.New() - v.SetConfigFile(string(c.configFileAbsPath)) - v.SetFs(vfsafero.NewAferoFS(c.fs)) - switch err := v.ReadInConfig(); { - case os.IsNotExist(err): - return nil - case err != nil: - return err - } - // FIXME calling v.Unmarshal here overwrites values set with command line flags - if err := v.Unmarshal(c); err != nil { - return err - } - if err := c.validateData(); err != nil { - return err - } - return nil -} - -func (c *Config) readLine(prompt string) (string, error) { - var line string - if err := c.withTerminal(prompt, func(t terminal) error { - var err error - line, err = t.ReadLine() - return err - }); err != nil { - return "", err - } - return line, nil -} - -func (c *Config) readPassword(prompt string) (string, error) { - var password string - if err := c.withTerminal("", func(t terminal) error { - var err error - password, err = t.ReadPassword(prompt) - return err - }); err != nil { - return "", err - } - return password, nil -} - -func (c *Config) run(dir chezmoi.AbsPath, name string, args []string) error { - cmd := exec.Command(name, args...) - if dir != "" { - dirRawAbsPath, err := c.baseSystem.RawPath(dir) - if err != nil { - return err - } - cmd.Dir = string(dirRawAbsPath) - } - cmd.Stdin = c.stdin - cmd.Stdout = c.stdout - cmd.Stderr = c.stderr - return c.baseSystem.RunCmd(cmd) -} - -func (c *Config) runEditor(args []string) error { - editor, editorArgs := c.editor() - return c.run("", editor, append(editorArgs, args...)) -} - -func (c *Config) sourceAbsPaths(sourceState *chezmoi.SourceState, args []string) (chezmoi.AbsPaths, error) { - targetRelPaths, err := c.targetRelPaths(sourceState, args, targetRelPathsOptions{ - mustBeInSourceState: true, - }) - if err != nil { - return nil, err - } - sourceAbsPaths := make(chezmoi.AbsPaths, 0, len(targetRelPaths)) - for _, targetRelPath := range targetRelPaths { - sourceAbsPath := c.sourceDirAbsPath.Join(sourceState.MustEntry(targetRelPath).SourceRelPath().RelPath()) - sourceAbsPaths = append(sourceAbsPaths, sourceAbsPath) - } - return sourceAbsPaths, nil -} - -func (c *Config) sourceState() (*chezmoi.SourceState, error) { - s := chezmoi.NewSourceState( - chezmoi.WithDefaultTemplateDataFunc(c.defaultTemplateData), - chezmoi.WithDestDir(c.destDirAbsPath), - chezmoi.WithEncryption(c.encryption), - chezmoi.WithPriorityTemplateData(c.Data), - chezmoi.WithSourceDir(c.sourceDirAbsPath), - chezmoi.WithSystem(c.sourceSystem), - chezmoi.WithTemplateFuncs(c.templateFuncs), - chezmoi.WithTemplateOptions(c.Template.Options), - ) - - if err := s.Read(); err != nil { - return nil, err - } - - if minVersion := s.MinVersion(); c.version != nil && !isDevVersion(c.version) && c.version.LessThan(minVersion) { - return nil, fmt.Errorf("source state requires version %s or later, chezmoi is version %s", minVersion, c.version) - } - - return s, nil -} - -type targetRelPathsOptions struct { - mustBeInSourceState bool - recursive bool -} - -func (c *Config) targetRelPaths(sourceState *chezmoi.SourceState, args []string, options targetRelPathsOptions) (chezmoi.RelPaths, error) { - targetRelPaths := make(chezmoi.RelPaths, 0, len(args)) - for _, arg := range args { - argAbsPath, err := chezmoi.NewAbsPathFromExtPath(arg, c.homeDirAbsPath) - if err != nil { - return nil, err - } - targetRelPath, err := argAbsPath.TrimDirPrefix(c.destDirAbsPath) - if err != nil { - return nil, err - } - if err != nil { - return nil, err - } - if options.mustBeInSourceState { - if _, ok := sourceState.Entry(targetRelPath); !ok { - return nil, fmt.Errorf("%s: not in source state", arg) - } - } - targetRelPaths = append(targetRelPaths, targetRelPath) - if options.recursive { - parentRelPath := targetRelPath - // FIXME we should not call s.TargetRelPaths() here - risk of accidentally quadratic - for _, targetRelPath := range sourceState.TargetRelPaths() { - if _, err := targetRelPath.TrimDirPrefix(parentRelPath); err == nil { - targetRelPaths = append(targetRelPaths, targetRelPath) - } - } - } - } - - if len(targetRelPaths) == 0 { - return nil, nil - } - - // Sort and de-duplicate targetRelPaths in place. - sort.Sort(targetRelPaths) - n := 1 - for i := 1; i < len(targetRelPaths); i++ { - if targetRelPaths[i] != targetRelPaths[i-1] { - targetRelPaths[n] = targetRelPaths[i] - n++ - } - } - return targetRelPaths[:n], nil -} - -func (c *Config) targetRelPathsBySourcePath(sourceState *chezmoi.SourceState, args []string) (chezmoi.RelPaths, error) { - targetRelPaths := make(chezmoi.RelPaths, 0, len(args)) - targetRelPathsBySourceRelPath := make(map[chezmoi.RelPath]chezmoi.RelPath) - for targetRelPath, sourceStateEntry := range sourceState.Entries() { - sourceRelPath := sourceStateEntry.SourceRelPath().RelPath() - targetRelPathsBySourceRelPath[sourceRelPath] = targetRelPath - } - for _, arg := range args { - argAbsPath, err := chezmoi.NewAbsPathFromExtPath(arg, c.homeDirAbsPath) - if err != nil { - return nil, err - } - sourceRelPath, err := argAbsPath.TrimDirPrefix(c.sourceDirAbsPath) - if err != nil { - return nil, err - } - targetRelPath, ok := targetRelPathsBySourceRelPath[sourceRelPath] - if !ok { - return nil, fmt.Errorf("%s: not in source state", arg) - } - targetRelPaths = append(targetRelPaths, targetRelPath) - } - return targetRelPaths, nil -} - -func (c *Config) useBuiltinGit() (bool, error) { - if c.UseBuiltinGit == "" || strings.ToLower(c.UseBuiltinGit) == "auto" { - if _, err := exec.LookPath(c.Git.Command); err == nil { - return false, nil - } - return true, nil - } - return parseBool(c.UseBuiltinGit) -} - -func (c *Config) validateData() error { - return validateKeys(c.Data, identifierRx) -} - -func (c *Config) withTerminal(prompt string, f func(terminal) error) error { - if c.noTTY { - return f(newNullTerminal(c.stdin)) - } - - if stdinFile, ok := c.stdin.(*os.File); ok && term.IsTerminal(int(stdinFile.Fd())) { - fd := int(stdinFile.Fd()) - width, height, err := term.GetSize(fd) - if err != nil { - return err - } - oldState, err := term.MakeRaw(fd) - if err != nil { - return err - } - defer func() { - _ = term.Restore(fd, oldState) - }() - t := term.NewTerminal(struct { - io.Reader - io.Writer - }{ - Reader: c.stdin, - Writer: c.stdout, - }, prompt) - if err := t.SetSize(width, height); err != nil { - return err - } - return f(t) - } - - if runtime.GOOS == "windows" { - return f(newDumbTerminal(c.stdin, c.stdout, prompt)) - } - - devTTY, err := os.OpenFile("/dev/tty", os.O_RDWR, 0) - if err != nil { - return err - } - defer devTTY.Close() - fd := int(devTTY.Fd()) - width, height, err := term.GetSize(fd) - if err != nil { - return err - } - oldState, err := term.MakeRaw(fd) - if err != nil { - return err - } - defer func() { - _ = term.Restore(fd, oldState) - }() - t := term.NewTerminal(devTTY, prompt) - if err := t.SetSize(width, height); err != nil { - return err - } - return f(t) -} - -func (c *Config) writeOutput(data []byte) error { - if c.outputStr == "" || c.outputStr == "-" { - _, err := c.stdout.Write(data) - return err - } - return c.baseSystem.WriteFile(chezmoi.AbsPath(c.outputStr), data, 0o666) -} - -func (c *Config) writeOutputString(data string) error { - return c.writeOutput([]byte(data)) -} - -// isDevVersion returns true if version is a development version (i.e. that the -// major, minor, and patch version numbers are all zero). -func isDevVersion(v *semver.Version) bool { - return v.Major == 0 && v.Minor == 0 && v.Patch == 0 -} - -// withVersionInfo sets the version information. -func withVersionInfo(versionInfo VersionInfo) configOption { - return func(c *Config) error { - var version *semver.Version - var versionElems []string - if versionInfo.Version != "" { - var err error - version, err = semver.NewVersion(strings.TrimPrefix(versionInfo.Version, "v")) - if err != nil { - return err - } - versionElems = append(versionElems, "v"+version.String()) - } else { - versionElems = append(versionElems, "dev") - } - if versionInfo.Commit != "" { - versionElems = append(versionElems, "commit "+versionInfo.Commit) - } - if versionInfo.Date != "" { - versionElems = append(versionElems, "built at "+versionInfo.Date) - } - if versionInfo.BuiltBy != "" { - versionElems = append(versionElems, "built by "+versionInfo.BuiltBy) - } - c.version = version - c.versionInfo = versionInfo - c.versionStr = strings.Join(versionElems, ", ") - return nil - } -} diff --git a/chezmoi2/cmd/config_test.go b/chezmoi2/cmd/config_test.go deleted file mode 100644 index 2ceb7ac03a7..00000000000 --- a/chezmoi2/cmd/config_test.go +++ /dev/null @@ -1,257 +0,0 @@ -package cmd - -import ( - "io" - "os" - "path/filepath" - "runtime" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - vfs "github.com/twpayne/go-vfs" - xdg "github.com/twpayne/go-xdg/v3" - - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoitest" -) - -func TestAddTemplateFuncPanic(t *testing.T) { - chezmoitest.WithTestFS(t, nil, func(fs vfs.FS) { - c := newTestConfig(t, fs) - assert.NotPanics(t, func() { - c.addTemplateFunc("func", nil) - }) - assert.Panics(t, func() { - c.addTemplateFunc("func", nil) - }) - }) -} - -func TestParseConfig(t *testing.T) { - for _, tc := range []struct { - name string - filename string - contents string - expectedColor bool - }{ - { - name: "json_bool", - filename: "chezmoi.json", - contents: chezmoitest.JoinLines( - `{`, - ` "color":true`, - `}`, - ), - expectedColor: true, - }, - { - name: "json_string", - filename: "chezmoi.json", - contents: chezmoitest.JoinLines( - `{`, - ` "color":"on"`, - `}`, - ), - expectedColor: true, - }, - { - name: "toml_bool", - filename: "chezmoi.toml", - contents: chezmoitest.JoinLines( - `color = true`, - ), - expectedColor: true, - }, - { - name: "toml_string", - filename: "chezmoi.toml", - contents: chezmoitest.JoinLines( - `color = "y"`, - ), - expectedColor: true, - }, - { - name: "yaml_bool", - filename: "chezmoi.yaml", - contents: chezmoitest.JoinLines( - `color: true`, - ), - expectedColor: true, - }, - { - name: "yaml_string", - filename: "chezmoi.yaml", - contents: chezmoitest.JoinLines( - `color: "yes"`, - ), - expectedColor: true, - }, - } { - t.Run(tc.name, func(t *testing.T) { - chezmoitest.WithTestFS(t, map[string]interface{}{ - "/home/user/.config/chezmoi/" + tc.filename: tc.contents, - }, func(fs vfs.FS) { - c := newTestConfig(t, fs) - require.NoError(t, c.execute([]string{"init"})) - assert.Equal(t, tc.expectedColor, c.color) - }) - }) - } -} - -func TestUpperSnakeCaseToCamelCase(t *testing.T) { - for s, expected := range map[string]string{ - "BUG_REPORT_URL": "bugReportURL", - "ID": "id", - "ID_LIKE": "idLike", - "NAME": "name", - "VERSION_CODENAME": "versionCodename", - "VERSION_ID": "versionID", - } { - assert.Equal(t, expected, upperSnakeCaseToCamelCase(s)) - } -} - -func TestValidateKeys(t *testing.T) { - for _, tc := range []struct { - data interface{} - expectedErr bool - }{ - { - data: nil, - expectedErr: false, - }, - { - data: map[string]interface{}{ - "foo": "bar", - "a": 0, - "_x9": false, - "ThisVariableIsExported": nil, - "αβ": "", - }, - expectedErr: false, - }, - { - data: map[string]interface{}{ - "foo-foo": "bar", - }, - expectedErr: true, - }, - { - data: map[string]interface{}{ - "foo": map[string]interface{}{ - "bar-bar": "baz", - }, - }, - expectedErr: true, - }, - { - data: map[string]interface{}{ - "foo": []interface{}{ - map[string]interface{}{ - "bar-bar": "baz", - }, - }, - }, - expectedErr: true, - }, - } { - if tc.expectedErr { - assert.Error(t, validateKeys(tc.data, identifierRx)) - } else { - assert.NoError(t, validateKeys(tc.data, identifierRx)) - } - } -} - -func newTestConfig(t *testing.T, fs vfs.FS, options ...configOption) *Config { - t.Helper() - system := chezmoi.NewRealSystem(fs) - c, err := newConfig( - append([]configOption{ - withBaseSystem(system), - withDestSystem(system), - withSourceSystem(system), - withTestFS(fs), - withTestUser("user"), - withUmask(chezmoitest.Umask), - }, options...)..., - ) - require.NoError(t, err) - return c -} - -func withBaseSystem(baseSystem chezmoi.System) configOption { - return func(c *Config) error { - c.baseSystem = baseSystem - return nil - } -} - -func withDestSystem(destSystem chezmoi.System) configOption { - return func(c *Config) error { - c.destSystem = destSystem - return nil - } -} - -func withSourceSystem(sourceSystem chezmoi.System) configOption { - return func(c *Config) error { - c.sourceSystem = sourceSystem - return nil - } -} - -func withStdin(stdin io.Reader) configOption { - return func(c *Config) error { - c.stdin = stdin - return nil - } -} - -func withStdout(stdout io.Writer) configOption { - return func(c *Config) error { - c.stdout = stdout - return nil - } -} - -func withTestFS(fs vfs.FS) configOption { - return func(c *Config) error { - c.fs = fs - return nil - } -} - -func withTestUser(username string) configOption { - return func(c *Config) error { - switch runtime.GOOS { - case "windows": - c.homeDir = `c:\home\user` - default: - c.homeDir = "/home/user" - } - c.SourceDir = filepath.Join(c.homeDir, ".local", "share", "chezmoi") - c.DestDir = c.homeDir - c.Umask = 0o22 - configHome := filepath.Join(c.homeDir, ".config") - dataHome := filepath.Join(c.homeDir, ".local", "share") - c.bds = &xdg.BaseDirectorySpecification{ - ConfigHome: configHome, - ConfigDirs: []string{configHome}, - DataHome: dataHome, - DataDirs: []string{dataHome}, - CacheHome: filepath.Join(c.homeDir, ".cache"), - RuntimeDir: filepath.Join(c.homeDir, ".run"), - } - return nil - } -} - -func withUmask(umask os.FileMode) configOption { - return func(c *Config) error { - c.Umask = umask - return nil - } -} diff --git a/chezmoi2/cmd/docs.gen.go b/chezmoi2/cmd/docs.gen.go deleted file mode 100644 index 896f13b81c2..00000000000 --- a/chezmoi2/cmd/docs.gen.go +++ /dev/null @@ -1,2057 +0,0 @@ -// Code generated by github.com/twpayne/chezmoi/internal/cmd/generate-assets. DO NOT EDIT. -// +build !noembeddocs - -package cmd - -func init() { - assets["docs/CHANGES.md"] = []byte("" + - "# chezmoi Changes\n" + - "\n" + - "<!--- toc --->\n" + - "* [Upcoming](#upcoming)\n" + - " * [Default diff format changing from `chezmoi` to `git`.](#default-diff-format-changing-from-chezmoi-to-git)\n" + - " * [`gpgRecipient` config variable changing to `gpg.recipient`](#gpgrecipient-config-variable-changing-to-gpgrecipient)\n" + - "\n" + - "## Upcoming\n" + - "\n" + - "### Default diff format changing from `chezmoi` to `git`.\n" + - "\n" + - "Currently chezmoi outputs diffs in its own format, containing a mix of unified\n" + - "diffs and shell commands. This will be replaced with a [git format\n" + - "diff](https://git-scm.com/docs/diff-format) in version 2.0.0.\n" + - "\n" + - "### `gpgRecipient` config variable changing to `gpg.recipient`\n" + - "\n" + - "The `gpgRecipient` config variable is changing to `gpg.recipient`. To update,\n" + - "change your config from:\n" + - "\n" + - " gpgRecipient = \"...\"\n" + - "\n" + - "to:\n" + - "\n" + - " [gpg]\n" + - " recipient = \"...\"\n" + - "\n" + - "Support for the `gpgRecipient` config variable will be removed in version 2.0.0.\n" + - "\n") - assets["docs/COMPARISON.md"] = []byte("" + - "# chezmoi Comparison guide\n" + - "\n" + - "<!--- toc --->\n" + - "* [Comparison table](#comparison-table)\n" + - "* [I already have a system to manage my dotfiles, why should I use chezmoi?](#i-already-have-a-system-to-manage-my-dotfiles-why-should-i-use-chezmoi)\n" + - " * [...if coping with differences between machines requires special care](#if-coping-with-differences-between-machines-requires-special-care)\n" + - " * [...if you need to think for a moment before giving anyone access to your dotfiles](#if-you-need-to-think-for-a-moment-before-giving-anyone-access-to-your-dotfiles)\n" + - " * [...if your needs are outgrowing your current tool](#if-your-needs-are-outgrowing-your-current-tool)\n" + - " * [...if setting up your dotfiles requires more than two short commands](#if-setting-up-your-dotfiles-requires-more-than-two-short-commands)\n" + - "\n" + - "## Comparison table\n" + - "\n" + - "[chezmoi]: https://chezmoi.io/\n" + - "[dotbot]: https://github.com/anishathalye/dotbot\n" + - "[rcm]: https://github.com/thoughtbot/rcm\n" + - "[homesick]: https://github.com/technicalpickles/homesick\n" + - "[yadm]: https://yadm.io/\n" + - "[bare git]: https://www.atlassian.com/git/tutorials/dotfiles \"bare git\"\n" + - "\n" + - "| | [chezmoi] | [dotbot] | [rcm] | [homesick] | [yadm] | [bare git] |\n" + - "| -------------------------------------- | ------------- | ----------------- | ----------------- | ----------------- | ------------- | ---------- |\n" + - "| Implementation language | Go | Python | Perl | Ruby | Bash | C |\n" + - "| Distribution | Single binary | Python package | Multiple files | Ruby gem | Single script | n/a |\n" + - "| Install method | Multiple | git submodule | Multiple | Ruby gem | Multiple | n/a |\n" + - "| Non-root install on bare system | Yes | Difficult | Difficult | Difficult | Yes | Yes |\n" + - "| Windows support | Yes | No | No | No | No | Yes |\n" + - "| Bootstrap requirements | git | Python, git | Perl, git | Ruby, git | git | git |\n" + - "| Source repos | Single | Single | Multiple | Single | Single | Single |\n" + - "| Method | File | Symlink | File | Symlink | File | File |\n" + - "| Config file | Optional | Required | Optional | None | None | No |\n" + - "| Private files | Yes | No | No | No | No | No |\n" + - "| Show differences without applying | Yes | No | No | No | Yes | Yes |\n" + - "| Whole file encryption | Yes | No | No | No | Yes | No |\n" + - "| Password manager integration | Yes | No | No | No | No | No |\n" + - "| Machine-to-machine file differences | Templates | Alternative files | Alternative files | Alternative files | Templates | Manual |\n" + - "| Custom variables in templates | Yes | n/a | n/a | n/a | No | No |\n" + - "| Executable files | Yes | Yes | Yes | Yes | No | Yes |\n" + - "| File creation with initial contents | Yes | No | No | No | No | No |\n" + - "| File removal | Yes | Manual | No | No | No | No |\n" + - "| Directory creation | Yes | Yes | Yes | No | No | Yes |\n" + - "| Run scripts | Yes | Yes | Yes | No | No | No |\n" + - "| Run once scripts | Yes | No | No | No | Manual | No |\n" + - "| Machine-to-machine symlink differences | Yes | No | No | No | Yes | No |\n" + - "| Shell completion | Yes | No | No | No | Yes | Yes |\n" + - "| Archive import | Yes | No | No | No | No | No |\n" + - "| Archive export | Yes | No | No | No | No | Yes |\n" + - "\n" + - "## I already have a system to manage my dotfiles, why should I use chezmoi?\n" + - "\n" + - "If you're using any of the following methods:\n" + - "\n" + - "* A custom shell script.\n" + - "* An existing dotfile manager like\n" + - " [homeshick](https://github.com/andsens/homeshick),\n" + - " [homesick](https://github.com/technicalpickles/homesick),\n" + - " [rcm](https://github.com/thoughtbot/rcm), [GNU\n" + - " Stow](https://www.gnu.org/software/stow/), or [yadm](https://yadm.io/).\n" + - "* A [bare git repo](https://www.atlassian.com/git/tutorials/dotfiles).\n" + - "\n" + - "Then you've probably run into at least one of the following problems.\n" + - "\n" + - "### ...if coping with differences between machines requires special care\n" + - "\n" + - "If you want to synchronize your dotfiles across multiple operating systems or\n" + - "distributions, then you may need to manually perform extra steps to cope with\n" + - "differences from machine to machine. You might need to run different commands on\n" + - "different machines, maintain separate per-machine files or branches (with the\n" + - "associated hassle of merging, rebasing, or copying each change), or hope that\n" + - "your custom logic handles the differences correctly.\n" + - "\n" + - "chezmoi uses a single source of truth (a single branch) and a single command\n" + - "that works on every machine. Individual files can be templates to handle machine\n" + - "to machine differences, if needed.\n" + - "\n" + - "### ...if you need to think for a moment before giving anyone access to your dotfiles\n" + - "\n" + - "If your system stores secrets in plain text, then you must be very careful about\n" + - "where you clone your dotfiles. If you clone them on your work machine then\n" + - "anyone with access to your work machine (e.g. your IT department) will have\n" + - "access to your home secrets. If you clone it on your home machine then you risk\n" + - "leaking work secrets.\n" + - "\n" + - "With chezmoi you can store secrets in your password manager or encrypt them, and\n" + - "even store passwords in different ways on different machines. You can clone your\n" + - "dotfiles repository anywhere, and even make your dotfiles repo public, without\n" + - "leaving personal secrets on your work machine or work secrets on your personal\n" + - "machine.\n" + - "\n" + - "### ...if your needs are outgrowing your current tool\n" + - "\n" + - "If your system was written by you for your personal use, then it probably has\n" + - "the minimum functionality that you needed when you wrote it. If you need more\n" + - "functionality then you have to implement it yourself.\n" + - "\n" + - "chezmoi includes a huge range of battle-tested functionality out-of-the-box,\n" + - "including dry-run and diff modes, script execution, conflict resolution, Windows\n" + - "support, and much, much more. chezmoi is [used by thousands of\n" + - "people](https://github.com/twpayne/chezmoi/stargazers), so it is likely that\n" + - "when you hit the limits of your existing dotfile management system, chezmoi\n" + - "already has a tried-and-tested solution ready for you to use.\n" + - "\n" + - "### ...if setting up your dotfiles requires more than two short commands\n" + - "\n" + - "If your system is written in a scripting language like Python, Perl, or Ruby,\n" + - "then you also need to install a compatible version of that language's runtime\n" + - "before you can use your system.\n" + - "\n" + - "chezmoi is distributed as a single stand-alone statically-linked binary with no\n" + - "dependencies that you can simply copy onto your machine and run. chezmoi\n" + - "provides one-line installs, pre-built binaries, packages for Linux and BSD\n" + - "distributions, Homebrew formulae, Scoop and Chocolatey support on Windows, and a\n" + - "initial config file generation mechanism to make installing your dotfiles on a\n" + - "new machine as painless as possible.\n" + - "\n" + - "\n") - assets["docs/CONTRIBUTING.md"] = []byte("" + - "# chezmoi Contributing Guide\n" + - "\n" + - "<!--- toc --->\n" + - "* [Getting started](#getting-started)\n" + - "* [Developing locally](#developing-locally)\n" + - "* [Generated code](#generated-code)\n" + - "* [Contributing changes](#contributing-changes)\n" + - "* [Managing releases](#managing-releases)\n" + - "* [Packaging](#packaging)\n" + - "* [Updating the website](#updating-the-website)\n" + - "\n" + - "## Getting started\n" + - "\n" + - "chezmoi is written in [Go](https://golang.org) and development happens on\n" + - "[GitHub](https://github.com). The rest of this document assumes that you've\n" + - "checked out chezmoi locally.\n" + - "\n" + - "## Developing locally\n" + - "\n" + - "chezmoi requires Go 1.14 or later and Go modules enabled. Enable Go modules by\n" + - "setting the environment variable `GO111MODULE=on`.\n" + - "\n" + - "chezmoi is a standard Go project, using standard Go tooling, with a few extra\n" + - "tools. Ensure that these extra tools are installed with:\n" + - "\n" + - " make ensure-tools\n" + - "\n" + - "Build chezmoi:\n" + - "\n" + - " go build .\n" + - "\n" + - "Run all tests:\n" + - "\n" + - " go test ./...\n" + - "\n" + - "Run chezmoi:\n" + - "\n" + - " go run .\n" + - "\n" + - "## Generated code\n" + - "\n" + - "chezmoi generates help text, shell completions, embedded files, and the website\n" + - "from a single source of truth. You must run\n" + - "\n" + - " go generate\n" + - "\n" + - "if you change includes any of the following:\n" + - "\n" + - "* Modify any documentation in the `docs/` directory.\n" + - "* Modify any files in the `assets/templates/` directory.\n" + - "* Add or modify a command.\n" + - "* Add or modify a command's flags.\n" + - "\n" + - "chezmoi's continuous integration verifies that all generated files are up to\n" + - "date. Changes to generated files should be included in the commit that modifies\n" + - "the source of truth.\n" + - "\n" + - "## Contributing changes\n" + - "\n" + - "Bug reports, bug fixes, and documentation improvements are always welcome.\n" + - "Please [open an issue](https://github.com/twpayne/chezmoi/issues/new/choose) or\n" + - "[create a pull\n" + - "request](https://help.github.com/en/articles/creating-a-pull-request) with your\n" + - "report, fix, or improvement.\n" + - "\n" + - "If you want to make a more significant change, please first [open an\n" + - "issue](https://github.com/twpayne/chezmoi/issues/new/choose) to discuss the\n" + - "change that you want to make. Dave Cheney gives a [good\n" + - "rationale](https://dave.cheney.net/2019/02/18/talk-then-code) as to why this is\n" + - "important.\n" + - "\n" + - "All changes are made via pull requests. In your pull request, please make sure\n" + - "that:\n" + - "\n" + - "* All existing tests pass.\n" + - "\n" + - "* There are appropriate additional tests that demonstrate that your PR works as\n" + - " intended.\n" + - "\n" + - "* The documentation is updated, if necessary. For new features you should add an\n" + - " entry in `docs/HOWTO.md` and a complete description in `docs/REFERENCE.md`.\n" + - "\n" + - "* All generated files are up to date. You can ensure this by running `go\n" + - " generate` and including any modified files in your commit.\n" + - "\n" + - "* The code is correctly formatted, according to\n" + - " [`gofumports`](https://mvdan.cc/gofumpt/gofumports). You can ensure this by\n" + - " running `make format`.\n" + - "\n" + - "* The code passes [`golangci-lint`](https://github.com/golangci/golangci-lint).\n" + - " You can ensure this by running `make lint`.\n" + - "\n" + - "* The commit messages match chezmoi's convention, specifically that they begin\n" + - " with a capitalized verb in the imperative and give a short description of what\n" + - " the commit does. Detailed information or justification can be optionally\n" + - " included in the body of the commit message.\n" + - "\n" + - "* Commits are logically separate, with no merge or \"fixup\" commits.\n" + - "\n" + - "* The branch applies cleanly to `master`.\n" + - "\n" + - "## Managing releases\n" + - "\n" + - "Releases are managed with [`goreleaser`](https://goreleaser.com/).\n" + - "\n" + - "To build a test release, without publishing, (Linux only) run:\n" + - "\n" + - " make test-release\n" + - "\n" + - "Publish a new release by creating and pushing a tag, e.g.:\n" + - "\n" + - " git tag v1.2.3\n" + - " git push --tags\n" + - "\n" + - "This triggers a [GitHub Action](https://github.com/twpayne/chezmoi/actions) that\n" + - "builds and publishes archives, packages, and snaps, and creates a new [GitHub\n" + - "Release](https://github.com/twpayne/chezmoi/releases).\n" + - "\n" + - "Publishing [Snaps](https://snapcraft.io/) requires a `SNAPCRAFT_LOGIN`\n" + - "[repository\n" + - "secret](https://github.com/twpayne/chezmoi/settings/secrets/actions). Snapcraft\n" + - "logins periodically expire. Create a new snapcraft login by running:\n" + - "\n" + - " snapcraft export-login --snaps=chezmoi --channels=stable --acls=package_upload -\n" + - "\n" + - "[brew](https://brew.sh/) formula must be updated manually with the command:\n" + - "\n" + - " brew bump-formula-pr --tag=v1.2.3 chezmoi\n" + - "\n" + - "## Packaging\n" + - "\n" + - "If you're packaging chezmoi for an operating system or distribution:\n" + - "\n" + - "* chezmoi has no build or install dependencies other than the standard Go\n" + - " toolchain.\n" + - "\n" + - "* Please set the version number, git commit, and build time in the binary. This\n" + - " greatly assists debugging when end users report problems or ask for help. You\n" + - " can do this by passing the following flags to the Go linker:\n" + - "\n" + - " ```\n" + - " -X main.version=$VERSION\n" + - " -X main.commit=$COMMIT\n" + - " -X main.date=$DATE\n" + - " -X main.builtBy=$BUILT_BY\n" + - " ```\n" + - "\n" + - " `$VERSION` should be the chezmoi version, e.g. `1.7.3`. Any `v` prefix is\n" + - " optional and will be stripped, so you can pass the git tag in directly.\n" + - "\n" + - " `$COMMIT` should be the full git commit hash at which chezmoi is built, e.g.\n" + - " `4d678ce6850c9d81c7ab2fe0d8f20c1547688b91`.\n" + - "\n" + - " `$DATE` should be the date of the build in RFC3339 format, e.g.\n" + - " `2019-11-23T18:29:25Z`.\n" + - "\n" + - " `$BUILT_BY` should be a string indicating what mechanism was used to build the\n" + - " binary, e.g. `goreleaser`.\n" + - "\n" + - "* Please enable cgo, if possible. chezmoi can be built and run without cgo, but\n" + - " the `.chezmoi.username` and `.chezmoi.group` template variables may not be set\n" + - " correctly on some systems.\n" + - "\n" + - "* chezmoi includes a `docs` command which prints its documentation. By default,\n" + - " the docs are embedded in the binary. You can disable this behavior, and have\n" + - " chezmoi read its docs from the filesystem by building with the `noembeddocs`\n" + - " build tag and setting the directory where chezmoi can find them with the `-X\n" + - " github.com/twpayne/chezmoi/cmd.DocDir=$DOCDIR` linker flag. For example:\n" + - "\n" + - " ```\n" + - " go build -tags noembeddocs -ldflags \"-X github.com/twpayne/chezmoi/cmd.DocsDir=/usr/share/doc/chezmoi\" .\n" + - " ```\n" + - "\n" + - " To remove the `docs` command completely, use the `nodocs` build tag.\n" + - "\n" + - "* chezmoi includes an `upgrade` command which attempts to self-upgrade. You can\n" + - " remove this command completely by building chezmoi with the `noupgrade` build\n" + - " tag.\n" + - "\n" + - "* chezmoi includes shell completions in the `completions` directory. Please\n" + - " include these in the package and install them in the shell-appropriate\n" + - " directory, if possible.\n" + - "\n" + - "* If the instructions for installing chezmoi in chezmoi's [install\n" + - " guide](https://github.com/twpayne/chezmoi/blob/master/docs/INSTALL.md) are\n" + - " absent or incorrect, please open an issue or submit a PR to correct them.\n" + - "\n" + - "## Updating the website\n" + - "\n" + - "[The website](https://chezmoi.io) is generated with [Hugo](https://gohugo.io/)\n" + - "and served with [GitHub pages](https://pages.github.com/) from the [`gh-pages`\n" + - "branch](https://github.com/twpayne/chezmoi/tree/gh-pages) to GitHub.\n" + - "\n" + - "Before building the website, you must download the [Hugo Book\n" + - "Theme](https://github.com/alex-shpak/hugo-book) by running:\n" + - "\n" + - " git submodule update --init\n" + - "\n" + - "Test the website locally by running:\n" + - "\n" + - " ( cd chezmoi.io && hugo serve )\n" + - "\n" + - "and visit http://localhost:1313/.\n" + - "\n" + - "To build the website in a temporary directory, run:\n" + - "\n" + - " ( cd chezmoi.io && make )\n" + - "\n" + - "From here you can run\n" + - "\n" + - " git show\n" + - "\n" + - "to show changes and\n" + - "\n" + - " git push\n" + - "\n" + - "to push them. You can only push changes if you have write permissions to the\n" + - "chezmoi GitHub repo.\n" + - "\n") - assets["docs/FAQ.md"] = []byte("" + - "# chezmoi Frequently Asked Questions\n" + - "\n" + - "<!--- toc --->\n" + - "* [How can I quickly check for problems with chezmoi on my machine?](#how-can-i-quickly-check-for-problems-with-chezmoi-on-my-machine)\n" + - "* [What are the consequences of \"bare\" modifications to the target files? If my `.zshrc` is managed by chezmoi and I edit `~/.zshrc` without using `chezmoi edit`, what happens?](#what-are-the-consequences-of-bare-modifications-to-the-target-files-if-my-zshrc-is-managed-by-chezmoi-and-i-edit-zshrc-without-using-chezmoi-edit-what-happens)\n" + - "* [How can I tell what dotfiles in my home directory aren't managed by chezmoi? Is there an easy way to have chezmoi manage a subset of them?](#how-can-i-tell-what-dotfiles-in-my-home-directory-arent-managed-by-chezmoi-is-there-an-easy-way-to-have-chezmoi-manage-a-subset-of-them)\n" + - "* [How can I tell what dotfiles in my home directory are currently managed by chezmoi?](#how-can-i-tell-what-dotfiles-in-my-home-directory-are-currently-managed-by-chezmoi)\n" + - "* [If there's a mechanism in place for the above, is there also a way to tell chezmoi to ignore specific files or groups of files (e.g. by directory name or by glob)?](#if-theres-a-mechanism-in-place-for-the-above-is-there-also-a-way-to-tell-chezmoi-to-ignore-specific-files-or-groups-of-files-eg-by-directory-name-or-by-glob)\n" + - "* [If the target already exists, but is \"behind\" the source, can chezmoi be configured to preserve the target version before replacing it with one derived from the source?](#if-the-target-already-exists-but-is-behind-the-source-can-chezmoi-be-configured-to-preserve-the-target-version-before-replacing-it-with-one-derived-from-the-source)\n" + - "* [Once I've made a change to the source directory, how do I commit it?](#once-ive-made-a-change-to-the-source-directory-how-do-i-commit-it)\n" + - "* [How do I only run a script when a file has changed?](#how-do-i-only-run-a-script-when-a-file-has-changed)\n" + - "* [I've made changes to both the destination state and the source state that I want to keep. How can I keep them both?](#ive-made-changes-to-both-the-destination-state-and-the-source-state-that-i-want-to-keep-how-can-i-keep-them-both)\n" + - "* [Why does chezmoi convert all my template variables to lowercase?](#why-does-chezmoi-convert-all-my-template-variables-to-lowercase)\n" + - "* [chezmoi makes `~/.ssh/config` group writeable. How do I stop this?](#chezmoi-makes-sshconfig-group-writeable-how-do-i-stop-this)\n" + - "* [Why doesn't chezmoi use symlinks like GNU Stow?](#why-doesnt-chezmoi-use-symlinks-like-gnu-stow)\n" + - "* [Do I have to use `chezmoi edit` to edit my dotfiles?](#do-i-have-to-use-chezmoi-edit-to-edit-my-dotfiles)\n" + - "* [Can I change how chezmoi's source state is represented on disk?](#can-i-change-how-chezmois-source-state-is-represented-on-disk)\n" + - "* [gpg encryption fails. What could be wrong?](#gpg-encryption-fails-what-could-be-wrong)\n" + - "* [chezmoi reports \"user: lookup userid NNNNN: input/output error\"](#chezmoi-reports-user-lookup-userid-nnnnn-inputoutput-error)\n" + - "* [I'm getting errors trying to build chezmoi from source](#im-getting-errors-trying-to-build-chezmoi-from-source)\n" + - "* [What inspired chezmoi?](#what-inspired-chezmoi)\n" + - "* [Why not use Ansible/Chef/Puppet/Salt, or similar to manage my dotfiles instead?](#why-not-use-ansiblechefpuppetsalt-or-similar-to-manage-my-dotfiles-instead)\n" + - "* [Can I use chezmoi to manage files outside my home directory?](#can-i-use-chezmoi-to-manage-files-outside-my-home-directory)\n" + - "* [Where does the name \"chezmoi\" come from?](#where-does-the-name-chezmoi-come-from)\n" + - "* [What other questions have been asked about chezmoi?](#what-other-questions-have-been-asked-about-chezmoi)\n" + - "* [Where do I ask a question that isn't answered here?](#where-do-i-ask-a-question-that-isnt-answered-here)\n" + - "* [I like chezmoi. How do I say thanks?](#i-like-chezmoi-how-do-i-say-thanks)\n" + - "\n" + - "## How can I quickly check for problems with chezmoi on my machine?\n" + - "\n" + - "Run:\n" + - "\n" + - " chezmoi doctor\n" + - "\n" + - "Anything `ok` is fine, anything `warning` is only a problem if you want to use\n" + - "the related feature, and anything `error` indicates a definite problem.\n" + - "\n" + - "## What are the consequences of \"bare\" modifications to the target files? If my `.zshrc` is managed by chezmoi and I edit `~/.zshrc` without using `chezmoi edit`, what happens?\n" + - "\n" + - "chezmoi will overwrite the file the next time you run `chezmoi apply`. Until you\n" + - "run `chezmoi apply` your modified `~/.zshrc` will remain in place.\n" + - "\n" + - "## How can I tell what dotfiles in my home directory aren't managed by chezmoi? Is there an easy way to have chezmoi manage a subset of them?\n" + - "\n" + - "`chezmoi unmanaged` will list everything not managed by chezmoi. You can add\n" + - "entire directories with `chezmoi add -r`.\n" + - "\n" + - "## How can I tell what dotfiles in my home directory are currently managed by chezmoi?\n" + - "\n" + - "`chezmoi managed` will list everything managed by chezmoi.\n" + - "\n" + - "## If there's a mechanism in place for the above, is there also a way to tell chezmoi to ignore specific files or groups of files (e.g. by directory name or by glob)?\n" + - "\n" + - "By default, chezmoi ignores everything that you haven't explicitly `chezmoi\n" + - "add`'ed. If you have files in your source directory that you don't want added to\n" + - "your destination directory when you run `chezmoi apply` add their names to a\n" + - "file called `.chezmoiignore` in the source state.\n" + - "\n" + - "Patterns are supported, and you can change what's ignored from machine to\n" + - "machine. The full usage and syntax is described in the [reference\n" + - "manual](https://github.com/twpayne/chezmoi/blob/master/docs/REFERENCE.md#chezmoiignore).\n" + - "\n" + - "## If the target already exists, but is \"behind\" the source, can chezmoi be configured to preserve the target version before replacing it with one derived from the source?\n" + - "\n" + - "Yes. Run `chezmoi add` will update the source state with the target. To see\n" + - "diffs of what would change, without actually changing anything, use `chezmoi\n" + - "diff`.\n" + - "\n" + - "## Once I've made a change to the source directory, how do I commit it?\n" + - "\n" + - "You have several options:\n" + - "\n" + - "* `chezmoi cd` opens a shell in the source directory, where you can run your\n" + - " usual version control commands, like `git add` and `git commit`.\n" + - "* `chezmoi git` and `chezmoi hg` run `git` and `hg` respectively in the source\n" + - " directory and pass extra arguments to the command. If you're passing any\n" + - " flags, you'll need to use `--` to prevent chezmoi from consuming them, for\n" + - " example `chezmoi git -- commit -m \"Update dotfiles\"`.\n" + - "* `chezmoi source` runs your configured version control system in your source\n" + - " directory. It works in the same way as the `chezmoi git` and `chezmoi hg`\n" + - " commands, but uses `sourceVCS.command`.\n" + - "\n" + - "## How do I only run a script when a file has changed?\n" + - "\n" + - "A common example of this is that you're using [Homebrew](https://brew.sh/) and\n" + - "have `.Brewfile` listing all the packages that you want installed and only want\n" + - "to run `brew bundle --global` when the contents of `.Brewfile` have changed.\n" + - "\n" + - "chezmoi has two types of scripts: scripts that run every time, and scripts that\n" + - "only run when their contents change. chezmoi does not have a mechanism to run a\n" + - "script when an arbitrary file has changed, but there are some ways to achieve\n" + - "the desired behavior:\n" + - "\n" + - "1. Have the script create `.Brewfile` instead of chezmoi, e.g. in your\n" + - " `run_once_install-packages`:\n" + - "\n" + - " ```sh\n" + - " #!/bin/sh\n" + - "\n" + - " cat > $HOME/.Brewfile <<EOF\n" + - " brew \"imagemagick\"\n" + - " brew \"openssl\"\n" + - " EOF\n" + - "\n" + - " brew bundle --global\n" + - " ```\n" + - "\n" + - "2. Don't use `.Brewfile`, and instead install the packages explicitly in\n" + - " `run_once_install-packages`:\n" + - "\n" + - " ```sh\n" + - " #!/bin/sh\n" + - "\n" + - " brew install imagemagick || true\n" + - " brew install openssl || true\n" + - " ```\n" + - "\n" + - " The `|| true` is necessary because `brew install` exits with failure if the\n" + - " package is already installed.\n" + - "\n" + - "3. Use a script that runs every time (not just once) and rely on `brew bundle\n" + - " --global` being idempotent.\n" + - "\n" + - "4. Use a script that runs every time, records a checksum of `.Brewfile` in\n" + - " another file, and only runs `brew bundle --global` if the checksum has\n" + - " changed, and updates the recorded checksum after.\n" + - "\n" + - "## I've made changes to both the destination state and the source state that I want to keep. How can I keep them both?\n" + - "\n" + - "`chezmoi merge` will open a merge tool to resolve differences between the source\n" + - "state, target state, and destination state. Copy the changes you want to keep in\n" + - "to the source state.\n" + - "\n" + - "## Why does chezmoi convert all my template variables to lowercase?\n" + - "\n" + - "This is due to a feature in\n" + - "[`github.com/spf13/viper`](https://github.com/spf13/viper), the library that\n" + - "chezmoi uses to read its configuration file. For more information see [this\n" + - "GitHub issue](https://github.com/twpayne/chezmoi/issues/463).\n" + - "\n" + - "## chezmoi makes `~/.ssh/config` group writeable. How do I stop this?\n" + - "\n" + - "By default, chezmoi uses your system's umask when creating files. On most\n" + - "systems the default umask is `022` but some systems use `002`, which means\n" + - "that files and directories are group writeable by default.\n" + - "\n" + - "You can override this for chezmoi by setting the `umask` configuration variable\n" + - "in your configuration file, for example:\n" + - "\n" + - " umask = 0o022\n" + - "\n" + - "Note that this will apply to all files and directories that chezmoi manages and\n" + - "will ensure that none of them are group writeable. It is not currently possible\n" + - "to control group write permissions for individual files or directories. Please\n" + - "[open an issue on\n" + - "GitHub](https://github.com/twpayne/chezmoi/issues/new?assignees=&labels=enhancement&template=02_feature_request.md&title=)\n" + - "if you need this.\n" + - "\n" + - "## Why doesn't chezmoi use symlinks like GNU Stow?\n" + - "\n" + - "Symlinks are first class citizens in chezmoi: chezmoi supports creating them,\n" + - "updating them, removing them, and even more advanced features not found\n" + - "elsewhere like having the same symlink point to different targets on different\n" + - "machines by using templates.\n" + - "\n" + - "With chezmoi, you only use symlinks where you really need a symlink, in contrast\n" + - "to some other dotfile managers (e.g. GNU Stow) which require the use of symlinks\n" + - "as a layer of indirection between a dotfile's location (which can be anywhere in\n" + - "your home directory) and a dotfile's content (which needs to be in a centralized\n" + - "directory that you manage with version control). chezmoi solves this problem in\n" + - "a different way.\n" + - "\n" + - "Instead of using a symlink to redirect from the dotfile's location to the\n" + - "centralized directory, chezmoi generates the dotfile in its final location from\n" + - "the contents of the centralized directory. Not only is no symlink is needed,\n" + - "this has the advantages that chezmoi is better able to cope with differences\n" + - "from machine to machine (as a dotfile's contents can be unique to that machine)\n" + - "and the dotfiles that chezmoi creates are just regular files. There's nothing\n" + - "special about dotfiles managed by chezmoi, whereas dotfiles managed with GNU\n" + - "Stow are special because they're actually symlinks to somewhere else.\n" + - "\n" + - "The only advantage to using GNU Stow-style symlinks is that changes that you\n" + - "make to the dotfile's contents in the centralized directory are immediately\n" + - "visible, whereas chezmoi currently requires you to run `chezmoi apply` or\n" + - "`chezmoi edit --apply`. chezmoi will likely get an alternative solution to this\n" + - "too, see [#752](https://github.com/twpayne/chezmoi/issues/752).\n" + - "\n" + - "You can configure chezmoi to work like GNU Stow and have it create a set of\n" + - "symlinks back to a central directory, but this currently requires a bit of\n" + - "manual work (as described in\n" + - "[#167](https://github.com/twpayne/chezmoi/issues/167)). chezmoi might get some\n" + - "automation to help (see [#886](https://github.com/twpayne/chezmoi/issues/886)\n" + - "for example) but it does need some convincing use cases that demonstrate that a\n" + - "symlink from a dotfile's location to its contents in a central directory is\n" + - "better than just having the correct dotfile contents.\n" + - "\n" + - "## Do I have to use `chezmoi edit` to edit my dotfiles?\n" + - "\n" + - "No. `chezmoi edit` is a convenience command that has a couple of useful\n" + - "features, but you don't have to use it. You can also run `chezmoi cd` and then\n" + - "just edit the files in the source state directly. After saving an edited file\n" + - "you can run `chezmoi diff` to check what effect the changes would have, and run\n" + - "`chezmoi apply` if you're happy with them.\n" + - "\n" + - "`chezmoi edit` provides the following useful features:\n" + - "* It opens the correct file in the source state for you, so you don't have to\n" + - " know anything about source state attributes.\n" + - "* If the dotfille is encrypted in the source state, then `chezmoi edit` will\n" + - " decrypt it to a private directory, open that file in your `$EDITOR`, and then\n" + - " re-encrypt the file when you quit your editor. That makes encryption more\n" + - " transparent to the user. With the `--diff` and `--apply` options you can see what\n" + - " would change and apply those changes without having to run `chezmoi diff` or\n" + - " `chezmoi apply`. Note also that the arguments to `chezmoi edit` are the files in\n" + - " their target location.\n" + - "\n" + - "## Can I change how chezmoi's source state is represented on disk?\n" + - "\n" + - "There are a number of criticisms of how chezmoi's source state is represented on\n" + - "disk:\n" + - "\n" + - "1. The source file naming system cannot handle all possible filenames.\n" + - "2. Not all possible file permissions can be represented.\n" + - "3. The long source file names are verbose.\n" + - "4. Everything is in a single directory, which can end up containing many entries.\n" + - "\n" + - "chezmoi's source state representation is a deliberate, practical compromise.\n" + - "\n" + - "Certain target filenames, for example `~/dot_example`, are incompatible with\n" + - "chezmoi's\n" + - "[attributes](https://github.com/twpayne/chezmoi/blob/master/docs/REFERENCE.md#source-state-attributes)\n" + - "used in the source state. In practice, dotfile filenames are unlikely to\n" + - "conflict with chezmoi's attributes. If this does cause a genuine problem for\n" + - "you, please [open an issue on\n" + - "GitHub](https://github.com/twpayne/chezmoi/issues/new/choose).\n" + - "\n" + - "The `dot_` attribute makes it transparent which dotfiles are managed by chezmoi\n" + - "and which files are ignored by chezmoi. chezmoi ignores all files and\n" + - "directories that start with `.` so no special whitelists are needed for version\n" + - "control systems and their control files (e.g. `.git` and `.gitignore`).\n" + - "\n" + - "chezmoi needs per-file metadata to know how to interpret the source file's\n" + - "contents, for example to know when the source file is a template or if the\n" + - "file's contents are encrypted. By storing this metadata in the filename, the\n" + - "metadata is unambiguously associated with a single file and adding, updating, or\n" + - "removing a single file touches only a single file in the source state. Changes\n" + - "to the metadata (e.g. `chezmoi chattr +template *target*`) are simple file\n" + - "renames and isolated to the affected file.\n" + - "\n" + - "If chezmoi were to, say, use a common configuration file listing which files\n" + - "were templates and/or encrypted, then changes to any file would require updates\n" + - "to the common configuration file. Automating updates to configuration files\n" + - "requires a round trip (read config file, update config, write config) and it is\n" + - "not always possible preserve comments and formatting.\n" + - "\n" + - "chezmoi's attributes of `executable_` and `private_` only allow a the file\n" + - "permissions `0o644`, `0o755`, `0o600`, and `0o700` to be represented.\n" + - "Directories can only have permissions `0o755` or `0o700`. In practice, these\n" + - "cover all permissions typically used for dotfiles. If this does cause a genuine\n" + - "problem for you, please [open an issue on\n" + - "GitHub](https://github.com/twpayne/chezmoi/issues/new/choose).\n" + - "\n" + - "File permissions and modes like `executable_`, `private_`, and `symlink_` could\n" + - "also be stored in the filesystem, rather than in the filename. However, this\n" + - "requires the permissions to be preserved and handled by the underlying version\n" + - "control system and filesystem. chezmoi provides first-class support for Windows,\n" + - "where the `executable_` and `private_` attributes have no direct equivalents and\n" + - "symbolic links are not always permitted. Some version control systems do not\n" + - "preserve file permissions or handle symbolic links. By using regular files and\n" + - "directories, chezmoi avoids variations in the operating system, version control\n" + - "system, and filesystem making it both more robust and more portable.\n" + - "\n" + - "chezmoi uses a 1:1 mapping between entries in the source state and entries in\n" + - "the target state. This mapping is bi-directional and unambiguous.\n" + - "\n" + - "However, this also means that dotfiles that in the same directory in the target\n" + - "state must be in the same directory in the source state. In particular, every\n" + - "entry managed by chezmoi in the root of your home directory has a corresponding\n" + - "entry in the root of your source directory, which can mean that you end up with\n" + - "a lot of entries in the root of your source directory.\n" + - "\n" + - "If chezmoi were to permit, say, multiple separate source directories (so you\n" + - "could, say, put `dot_bashrc` in a `bash/` subdirectory, and `dot_vimrc` in a\n" + - "`vim/` subdirectory, but have `chezmoi apply` map these to `~/.bashrc` and\n" + - "`~/.vimrc` in the root of your home directory) then the mapping between source\n" + - "and target states is no longer bidirectional nor unambiguous, which\n" + - "significantly increases complexity and requires more user interaction. For\n" + - "example, if both `bash/dot_bashrc` and `vim/dot_bashrc` exist, what should be\n" + - "the contents of `~/.bashrc`? If you run `chezmoi add ~/.zshrc`, should\n" + - "`dot_zshrc` be stored in the source `bash/` directory, the source `vim/`\n" + - "directory, or somewhere else? How does the user communicate their preferences?\n" + - "\n" + - "chezmoi has many users and any changes to the source state representation must\n" + - "be backwards-compatible.\n" + - "\n" + - "In summary, chezmoi's source state representation is a compromise with both\n" + - "advantages and disadvantages. Changes to the representation will be considered,\n" + - "but must meet the following criteria, in order of importance:\n" + - "\n" + - "1. Be fully backwards-compatible for existing users.\n" + - "2. Fix a genuine problem encountered in practice.\n" + - "3. Be independent of the underlying operating system, version control system, and\n" + - " filesystem.\n" + - "4. Not add significant extra complexity to the user interface or underlying\n" + - " implementation.\n" + - "\n" + - "## gpg encryption fails. What could be wrong?\n" + - "\n" + - "The `gpg.recipient` key should be ultimately trusted, otherwise encryption will\n" + - "fail because gpg will prompt for input, which chezmoi does not handle. You can\n" + - "check the trust level by running:\n" + - "\n" + - " gpg --export-ownertrust\n" + - "\n" + - "The trust level for the recipient's key should be `6`. If it is not, you can\n" + - "change the trust level by running:\n" + - "\n" + - " gpg --edit-key $recipient\n" + - "\n" + - "Enter `trust` at the prompt and chose `5 = I trust ultimately`.\n" + - "\n" + - "## chezmoi reports \"user: lookup userid NNNNN: input/output error\"\n" + - "\n" + - "This is likely because the chezmoi binary you are using was statically compiled\n" + - "with [musl](https://musl.libc.org/) and the machine you are running on uses\n" + - "LDAP or NIS.\n" + - "\n" + - "The immediate fix is to use a package built for your distriubtion (e.g a `.deb`\n" + - "or `.rpm`) which is linked against glibc and includes LDAP/NIS support instead\n" + - "of the statically-compiled binary.\n" + - "\n" + - "If the problem still persists, then please [open an issue on\n" + - "GitHub](https://github.com/twpayne/chezmoi/issues/new/choose).\n" + - "\n" + - "## I'm getting errors trying to build chezmoi from source\n" + - "\n" + - "chezmoi requires Go version 1.14 or later and Go modules enabled. You can check\n" + - "the version of Go with:\n" + - "\n" + - " go version\n" + - "\n" + - "Enable Go modules by setting `GO111MODULE=on` when running `go get`:\n" + - "\n" + - " GO111MODULE=on go get -u github.com/twpayne/chezmoi\n" + - "\n" + - "For more details on building chezmoi, see the [Contributing\n" + - "Guide](CONTRIBUTING.md).\n" + - "\n" + - "## What inspired chezmoi?\n" + - "\n" + - "chezmoi was inspired by [Puppet](https://puppet.com/), but created because\n" + - "Puppet is a slow overkill for managing your personal configuration files. The\n" + - "focus of chezmoi will always be personal home directory management. If your\n" + - "needs grow beyond that, switch to a whole system configuration management tool.\n" + - "\n" + - "## Why not use Ansible/Chef/Puppet/Salt, or similar to manage my dotfiles instead?\n" + - "\n" + - "Whole system management tools are more than capable of managing your dotfiles,\n" + - "but are large systems that entail several disadvantages. Compared to whole\n" + - "system management tools, chezmoi offers:\n" + - "\n" + - "* Small, focused feature set designed for dotfiles. There's simply less to learn\n" + - " with chezmoi compared to whole system management tools.\n" + - "* Easy installation and execution on every platform, without root access.\n" + - " Installing chezmoi requires only copying a single binary file with no external\n" + - " dependencies. Executing chezmoi just involves running the binary. In contrast,\n" + - " installing and running a whole system management tools typically requires\n" + - " installing a scripting language runtime, several packages, and running a\n" + - " system service, all typically requiring root access.\n" + - "\n" + - "chezmoi's focus and simple installation means that it runs almost everywhere:\n" + - "from tiny ARM-based Linux systems to Windows desktops, from inside lightweight\n" + - "containers to FreeBSD-based virtual machines in the cloud.\n" + - "\n" + - "## Can I use chezmoi to manage files outside my home directory?\n" + - "\n" + - "In practice, yes, you can, but this is strongly discouraged beyond using your\n" + - "system's package manager to install the packages you need.\n" + - "\n" + - "chezmoi is designed to operate on your home directory, and is explicitly not a\n" + - "full system configuration management tool. That said, there are some ways to\n" + - "have chezmoi manage a few files outside your home directory.\n" + - "\n" + - "chezmoi's scripts can execute arbitrary commands, so you can use a `run_` script\n" + - "that is run every time you run `chezmoi apply`, to, for example:\n" + - "\n" + - "* Make the target file outside your home directory a symlink to a file managed\n" + - " by chezmoi in your home directory.\n" + - "* Copy a file managed by chezmoi inside your home directory to the target file.\n" + - "* Execute a template with `chezmoi execute-template --output=filename template`\n" + - " where `filename` is outside the target directory.\n" + - "\n" + - "chezmoi executes all scripts as the user executing chezmoi, so you may need to\n" + - "add extra privilege elevation commands like `sudo` or `PowerShell start -verb\n" + - "runas -wait` to your script.\n" + - "\n" + - "chezmoi, by default, operates on your home directory but this can be overridden\n" + - "with the `--destination` command line flag or by specifying `destDir` in your\n" + - "config file, and could even be the root directory (`/` or `C:\\`). This allows\n" + - "you, in theory, to use chezmoi to manage any file in your filesystem, but this\n" + - "usage is extremely strongly discouraged.\n" + - "\n" + - "If your needs extend beyond modifying a handful of files outside your target\n" + - "system, then existing configuration management tools like\n" + - "[Puppet](https://puppet.com/), [Chef](https://chef.io/),\n" + - "[Ansible](https://www.ansible.com/), and [Salt](https://www.saltstack.com/) are\n" + - "much better suited - and of course can be called from a chezmoi `run_` script.\n" + - "Put your Puppet Manifests, Chef Recipes, Ansible Modules, and Salt Modules in a\n" + - "directory ignored by `.chezmoiignore` so they do not pollute your home\n" + - "directory.\n" + - "\n" + - "## Where does the name \"chezmoi\" come from?\n" + - "\n" + - "\"chezmoi\" splits to \"chez moi\" and pronounced /ʃeɪ mwa/ (shay-moi) meaning \"at\n" + - "my house\" in French. It's seven letters long, which is an appropriate length for\n" + - "a command that is only run occasionally.\n" + - "\n" + - "## What other questions have been asked about chezmoi?\n" + - "\n" + - "See the [issues on\n" + - "GitHub](https://github.com/twpayne/chezmoi/issues?utf8=%E2%9C%93&q=is%3Aissue+sort%3Aupdated-desc+label%3Asupport).\n" + - "\n" + - "## Where do I ask a question that isn't answered here?\n" + - "\n" + - "Please [open an issue on GitHub](https://github.com/twpayne/chezmoi/issues/new/choose).\n" + - "\n" + - "## I like chezmoi. How do I say thanks?\n" + - "\n" + - "Thank you! chezmoi was written to scratch a personal itch, and I'm very happy\n" + - "that it's useful to you. Please give [chezmoi a star on\n" + - "GitHub](https://github.com/twpayne/chezmoi/stargazers), and if you're happy to\n" + - "share your public dotfile repo then [tag it with\n" + - "`chezmoi`](https://github.com/topics/chezmoi?o=desc&s=updated). [Contributions\n" + - "are very\n" + - "welcome](https://github.com/twpayne/chezmoi/blob/master/docs/CONTRIBUTING.md)\n" + - "and every [bug report, support request, and feature\n" + - "request](https://github.com/twpayne/chezmoi/issues/new/choose) helps make\n" + - "chezmoi better. Thank you :)\n" + - "\n") - assets["docs/HOWTO.md"] = []byte("" + - "# chezmoi How-To Guide\n" + - "\n" + - "<!--- toc --->\n" + - "* [Use a hosted repo to manage your dotfiles across multiple machines](#use-a-hosted-repo-to-manage-your-dotfiles-across-multiple-machines)\n" + - "* [Pull the latest changes from your repo and apply them](#pull-the-latest-changes-from-your-repo-and-apply-them)\n" + - "* [Pull the latest changes from your repo and see what would change, without actually applying the changes](#pull-the-latest-changes-from-your-repo-and-see-what-would-change-without-actually-applying-the-changes)\n" + - "* [Automatically commit and push changes to your repo](#automatically-commit-and-push-changes-to-your-repo)\n" + - "* [Use templates to manage files that vary from machine to machine](#use-templates-to-manage-files-that-vary-from-machine-to-machine)\n" + - "* [Use completely separate config files on different machines](#use-completely-separate-config-files-on-different-machines)\n" + - " * [Without using symlinks](#without-using-symlinks)\n" + - "* [Create a config file on a new machine automatically](#create-a-config-file-on-a-new-machine-automatically)\n" + - "* [Have chezmoi create a directory, but ignore its contents](#have-chezmoi-create-a-directory-but-ignore-its-contents)\n" + - "* [Ensure that a target is removed](#ensure-that-a-target-is-removed)\n" + - "* [Include a subdirectory from another repository, like Oh My Zsh](#include-a-subdirectory-from-another-repository-like-oh-my-zsh)\n" + - "* [Handle configuration files which are externally modified](#handle-configuration-files-which-are-externally-modified)\n" + - "* [Handle different file locations on different systems with the same contents](#handle-different-file-locations-on-different-systems-with-the-same-contents)\n" + - "* [Keep data private](#keep-data-private)\n" + - " * [Use Bitwarden to keep your secrets](#use-bitwarden-to-keep-your-secrets)\n" + - " * [Use gopass to keep your secrets](#use-gopass-to-keep-your-secrets)\n" + - " * [Use gpg to keep your secrets](#use-gpg-to-keep-your-secrets)\n" + - " * [Use KeePassXC to keep your secrets](#use-keepassxc-to-keep-your-secrets)\n" + - " * [Use a keyring to keep your secrets](#use-a-keyring-to-keep-your-secrets)\n" + - " * [Use LastPass to keep your secrets](#use-lastpass-to-keep-your-secrets)\n" + - " * [Use 1Password to keep your secrets](#use-1password-to-keep-your-secrets)\n" + - " * [Use pass to keep your secrets](#use-pass-to-keep-your-secrets)\n" + - " * [Use Vault to keep your secrets](#use-vault-to-keep-your-secrets)\n" + - " * [Use a generic tool to keep your secrets](#use-a-generic-tool-to-keep-your-secrets)\n" + - " * [Use templates variables to keep your secrets](#use-templates-variables-to-keep-your-secrets)\n" + - "* [Use scripts to perform actions](#use-scripts-to-perform-actions)\n" + - " * [Understand how scripts work](#understand-how-scripts-work)\n" + - " * [Install packages with scripts](#install-packages-with-scripts)\n" + - "* [Use chezmoi with GitHub Codespaces, Visual Studio Codespaces, Visual Studio Code Remote - Containers](#use-chezmoi-with-github-codespaces-visual-studio-codespaces-visual-studio-code-remote---containers)\n" + - "* [Detect Windows Subsystem for Linux (WSL)](#detect-windows-subsystem-for-linux-wsl)\n" + - "* [Run a PowerShell script as admin on Windows](#run-a-powershell-script-as-admin-on-windows)\n" + - "* [Import archives](#import-archives)\n" + - "* [Export archives](#export-archives)\n" + - "* [Use a non-git version control system](#use-a-non-git-version-control-system)\n" + - "* [Customize the `diff` command](#customize-the-diff-command)\n" + - "* [Use a merge tool other than vimdiff](#use-a-merge-tool-other-than-vimdiff)\n" + - "* [Migrate from a dotfile manager that uses symlinks](#migrate-from-a-dotfile-manager-that-uses-symlinks)\n" + - "\n" + - "## Use a hosted repo to manage your dotfiles across multiple machines\n" + - "\n" + - "chezmoi relies on your version control system and hosted repo to share changes\n" + - "across multiple machines. You should create a repo on the source code repository\n" + - "of your choice (e.g. [Bitbucket](https://bitbucket.org),\n" + - "[GitHub](https://github.com/), or [GitLab](https://gitlab.com), many people call\n" + - "their repo `dotfiles`) and push the repo in the source directory here. For\n" + - "example:\n" + - "\n" + - " chezmoi cd\n" + - " git remote add origin https://github.com/username/dotfiles.git\n" + - " git push -u origin master\n" + - " exit\n" + - "\n" + - "On another machine you can checkout this repo:\n" + - "\n" + - " chezmoi init https://github.com/username/dotfiles.git\n" + - "\n" + - "You can then see what would be changed:\n" + - "\n" + - " chezmoi diff\n" + - "\n" + - "If you're happy with the changes then apply them:\n" + - "\n" + - " chezmoi apply\n" + - "\n" + - "The above commands can be combined into a single init, checkout, and apply:\n" + - "\n" + - " chezmoi init --apply --verbose https://github.com/username/dotfiles.git\n" + - "\n" + - "## Pull the latest changes from your repo and apply them\n" + - "\n" + - "You can pull the changes from your repo and apply them in a single command:\n" + - "\n" + - " chezmoi update\n" + - "\n" + - "This runs `git pull --rebase` in your source directory and then `chezmoi apply`.\n" + - "\n" + - "## Pull the latest changes from your repo and see what would change, without actually applying the changes\n" + - "\n" + - "Run:\n" + - "\n" + - " chezmoi source pull -- --rebase && chezmoi diff\n" + - "\n" + - "This runs `git pull --rebase` in your source directory and `chezmoi\n" + - "diff` then shows the difference between the target state computed from your\n" + - "source directory and the actual state.\n" + - "\n" + - "If you're happy with the changes, then you can run\n" + - "\n" + - " chezmoi apply\n" + - "\n" + - "to apply them.\n" + - "\n" + - "## Automatically commit and push changes to your repo\n" + - "\n" + - "chezmoi can automatically commit and push changes to your source directory to\n" + - "your repo. This feature is disabled by default. To enable it, add the following\n" + - "to your config file:\n" + - "\n" + - " [sourceVCS]\n" + - " autoCommit = true\n" + - " autoPush = true\n" + - "\n" + - "Whenever a change is made to your source directory, chezmoi will commit the\n" + - "changes with an automatically-generated commit message (if `autoCommit` is true)\n" + - "and push them to your repo (if `autoPush` is true). `autoPush` implies\n" + - "`autoCommit`, i.e. if `autoPush` is true then chezmoi will auto-commit your\n" + - "changes. If you only set `autoCommit` to true then changes will be committed but\n" + - "not pushed.\n" + - "\n" + - "Be careful when using `autoPush`. If your dotfiles repo is public and you\n" + - "accidentally add a secret in plain text, that secret will be pushed to your\n" + - "public repo.\n" + - "\n" + - "## Use templates to manage files that vary from machine to machine\n" + - "\n" + - "The primary goal of chezmoi is to manage configuration files across multiple\n" + - "machines, for example your personal macOS laptop, your work Ubuntu desktop, and\n" + - "your work Linux laptop. You will want to keep much configuration the same across\n" + - "these, but also need machine-specific configurations for email addresses,\n" + - "credentials, etc. chezmoi achieves this functionality by using\n" + - "[`text/template`](https://pkg.go.dev/text/template) for the source state where\n" + - "needed.\n" + - "\n" + - "For example, your home `~/.gitconfig` on your personal machine might look like:\n" + - "\n" + - " [user]\n" + - " email = \"[email protected]\"\n" + - "\n" + - "Whereas at work it might be:\n" + - "\n" + - " [user]\n" + - " email = \"[email protected]\"\n" + - "\n" + - "To handle this, on each machine create a configuration file called\n" + - "`~/.config/chezmoi/chezmoi.toml` defining variables that might vary from machine\n" + - "to machine. For example, for your home machine:\n" + - "\n" + - " [data]\n" + - " email = \"[email protected]\"\n" + - "\n" + - "Note that all variable names will be converted to lowercase. This is due to a\n" + - "feature of a library used by chezmoi.\n" + - "\n" + - "If you intend to store private data (e.g. access tokens) in\n" + - "`~/.config/chezmoi/chezmoi.toml`, make sure it has permissions `0600`.\n" + - "\n" + - "If you prefer, you can use any format supported by\n" + - "[Viper](https://github.com/spf13/viper) for your configuration file. This\n" + - "includes JSON, YAML, and TOML. Variable names must start with a letter and be\n" + - "followed by zero or more letters or digits.\n" + - "\n" + - "Then, add `~/.gitconfig` to chezmoi using the `--autotemplate` flag to turn it\n" + - "into a template and automatically detect variables from the `data` section\n" + - "of your `~/.config/chezmoi/chezmoi.toml` file:\n" + - "\n" + - " chezmoi add --autotemplate ~/.gitconfig\n" + - "\n" + - "You can then open the template (which will be saved in the file\n" + - "`~/.local/share/chezmoi/dot_gitconfig.tmpl`):\n" + - "\n" + - " chezmoi edit ~/.gitconfig\n" + - "\n" + - "The file should look something like:\n" + - "\n" + - " [user]\n" + - " email = \"{{ .email }}\"\n" + - "\n" + - "To disable automatic variable detection, use the `--template` or `-T` option to\n" + - "`chezmoi add` instead of `--autotemplate`.\n" + - "\n" + - "Templates are often used to capture machine-specific differences. For example,\n" + - "in your `~/.local/share/chezmoi/dot_bashrc.tmpl` you might have:\n" + - "\n" + - " # common config\n" + - " export EDITOR=vi\n" + - "\n" + - " # machine-specific configuration\n" + - " {{- if eq .chezmoi.hostname \"work-laptop\" }}\n" + - " # this will only be included in ~/.bashrc on work-laptop\n" + - " {{- end }}\n" + - "\n" + - "For a full list of variables, run:\n" + - "\n" + - " chezmoi data\n" + - "\n" + - "For more advanced usage, you can use the full power of the\n" + - "[`text/template`](https://pkg.go.dev/text/template) language. chezmoi includes\n" + - "all of the text functions from [sprig](http://masterminds.github.io/sprig/) and\n" + - "its own [functions for interacting with password\n" + - "managers](https://github.com/twpayne/chezmoi/blob/master/docs/REFERENCE.md#template-functions).\n" + - "\n" + - "Templates can be executed directly from the command line, without the need to\n" + - "create a file on disk, with the `execute-template` command, for example:\n" + - "\n" + - " chezmoi execute-template '{{ .chezmoi.os }}/{{ .chezmoi.arch }}'\n" + - "\n" + - "This is useful when developing or debugging templates.\n" + - "\n" + - "Some password managers allow you to store complete files. The files can be\n" + - "retrieved with chezmoi's template functions. For example, if you have a file\n" + - "stored in 1Password with the UUID `uuid` then you can retrieve it with the\n" + - "template:\n" + - "\n" + - " {{- onepasswordDocument \"uuid\" -}}\n" + - "\n" + - "The `-`s inside the brackets remove any whitespace before or after the template\n" + - "expression, which is useful if your editor has added any newlines.\n" + - "\n" + - "If, after executing the template, the file contents are empty, the target file\n" + - "will be removed. This can be used to ensure that files are only present on\n" + - "certain machines. If you want an empty file to be created anyway, you will need\n" + - "to give it an `empty_` prefix.\n" + - "\n" + - "For coarser-grained control of files and entire directories managed on different\n" + - "machines, or to exclude certain files completely, you can create\n" + - "`.chezmoiignore` files in the source directory. These specify a list of patterns\n" + - "that chezmoi should ignore, and are interpreted as templates. An example\n" + - "`.chezmoiignore` file might look like:\n" + - "\n" + - " README.md\n" + - " {{- if ne .chezmoi.hostname \"work-laptop\" }}\n" + - " .work # only manage .work on work-laptop\n" + - " {{- end }}\n" + - "\n" + - "The use of `ne` (not equal) is deliberate. What we want to achieve is \"only\n" + - "install `.work` if hostname is `work-laptop`\" but chezmoi installs everything by\n" + - "default, so we have to turn the logic around and instead write \"ignore `.work`\n" + - "unless the hostname is `work-laptop`\".\n" + - "\n" + - "Patterns can be excluded by prefixing them with a `!`, for example:\n" + - "\n" + - " f*\n" + - " !foo\n" + - "\n" + - "will ignore all files beginning with an `f` except `foo`.\n" + - "\n" + - "## Use completely separate config files on different machines\n" + - "\n" + - "chezmoi's template functionality allows you to change a file's contents based on\n" + - "any variable. For example, if you want `~/.bashrc` to be different on Linux and\n" + - "macOS you would create a file in the source state called `dot_bashrc.tmpl`\n" + - "containing:\n" + - "\n" + - "```\n" + - "{{ if eq .chezmoi.os \"darwin\" -}}\n" + - "# macOS .bashrc contents\n" + - "{{ else if eq .chezmoi.os \"linux\" -}}\n" + - "# Linux .bashrc contents\n" + - "{{ end -}}\n" + - "```\n" + - "\n" + - "However, if the differences between the two versions are so large that you'd\n" + - "prefer to use completely separate files in the source state, you can achieve\n" + - "this using a symbolic link template. Create the following files:\n" + - "\n" + - "`symlink_dot_bashrc.tmpl`:\n" + - "\n" + - "```\n" + - ".bashrc_{{ .chezmoi.os }}\n" + - "```\n" + - "\n" + - "`dot_bashrc_darwin`:\n" + - "\n" + - "```\n" + - "# macOS .bashrc contents\n" + - "```\n" + - "\n" + - "`dot_bashrc_linux`:\n" + - "\n" + - "```\n" + - "# Linux .bashrc contents\n" + - "```\n" + - "\n" + - "`.chezmoiignore`\n" + - "\n" + - "```\n" + - "{{ if ne .chezmoi.os \"darwin\" }}\n" + - ".bashrc_darwin\n" + - "{{ end }}\n" + - "{{ if ne .chezmoi.os \"linux\" }}\n" + - ".bashrc_linux\n" + - "{{ end }}\n" + - "```\n" + - "\n" + - "This will make `~/.bashrc` a symlink to `.bashrc_darwin` on `darwin` and to\n" + - "`.bashrc_linux` on `linux`. The `.chezmoiignore` configuration ensures that only\n" + - "the OS-specific `.bashrc_os` file will be installed on each OS.\n" + - "\n" + - "### Without using symlinks\n" + - "\n" + - "The same thing can be achieved using the include function.\n" + - "\n" + - "`dot_bashrc.tmpl`\n" + - "\n" + - "\t{{ if eq .chezmoi.os \"darwin\" }}\n" + - "\t{{ include \".bashrc_darwin\" }}\n" + - "\t{{ end }}\n" + - "\t{{ if eq .chezmoi.os \"linux\" }}\n" + - "\t{{ include \".bashrc_linux\" }}\n" + - "\t{{ end }}\n" + - "\n" + - "\n" + - "## Create a config file on a new machine automatically\n" + - "\n" + - "`chezmoi init` can also create a config file automatically, if one does not\n" + - "already exist. If your repo contains a file called `.chezmoi.<format>.tmpl`\n" + - "where *format* is one of the supported config file formats (e.g. `json`, `toml`,\n" + - "or `yaml`) then `chezmoi init` will execute that template to generate your\n" + - "initial config file.\n" + - "\n" + - "Specifically, if you have `.chezmoi.toml.tmpl` that looks like this:\n" + - "\n" + - " {{- $email := promptString \"email\" -}}\n" + - " [data]\n" + - " email = \"{{ $email }}\"\n" + - "\n" + - "Then `chezmoi init` will create an initial `chezmoi.toml` using this template.\n" + - "`promptString` is a special function that prompts the user (you) for a value.\n" + - "\n" + - "To test this template, use `chezmoi execute-template` with the `--init` and\n" + - "`--promptString` flags, for example:\n" + - "\n" + - " chezmoi execute-template --init --promptString [email protected] < ~/.local/share/chezmoi/.chezmoi.toml.tmpl\n" + - "\n" + - "## Have chezmoi create a directory, but ignore its contents\n" + - "\n" + - "If you want chezmoi to create a directory, but ignore its contents, say `~/src`,\n" + - "first run:\n" + - "\n" + - " mkdir -p $(chezmoi source-path)/src\n" + - "\n" + - "This creates the directory in the source state, which means that chezmoi will\n" + - "create it (if it does not already exist) when you run `chezmoi apply`.\n" + - "\n" + - "However, as this is an empty directory it will be ignored by git. So, create a\n" + - "file in the directory in the source state that will be seen by git (so git does\n" + - "not ignore the directory) but ignored by chezmoi (so chezmoi does not include it\n" + - "in the target state):\n" + - "\n" + - " touch $(chezmoi source-path)/src/.keep\n" + - "\n" + - "chezmoi automatically creates `.keep` files when you add an empty directory with\n" + - "`chezmoi add`.\n" + - "\n" + - "## Ensure that a target is removed\n" + - "\n" + - "Create a file called `.chezmoiremove` in the source directory containing a list\n" + - "of patterns of files to remove. When you run\n" + - "\n" + - " chezmoi apply --remove\n" + - "\n" + - "chezmoi will remove anything in the target directory that matches the pattern.\n" + - "As this command is potentially dangerous, you should run chezmoi in verbose,\n" + - "dry-run mode beforehand to see what would be removed:\n" + - "\n" + - " chezmoi apply --remove --dry-run --verbose\n" + - "\n" + - "`.chezmoiremove` is interpreted as a template, so you can remove different files\n" + - "on different machines. Negative matches (patterns prefixed with a `!`) or\n" + - "targets listed in `.chezmoiignore` will never be removed.\n" + - "\n" + - "## Include a subdirectory from another repository, like Oh My Zsh\n" + - "\n" + - "To include a subdirectory from another repository, e.g. [Oh My\n" + - "Zsh](https://github.com/robbyrussell/oh-my-zsh), you cannot use git submodules\n" + - "because chezmoi uses its own format for the source state and Oh My Zsh is not\n" + - "distributed in this format. Instead, you can use the `import` command to import\n" + - "a snapshot from a tarball:\n" + - "\n" + - " curl -s -L -o oh-my-zsh-master.tar.gz https://github.com/robbyrussell/oh-my-zsh/archive/master.tar.gz\n" + - " chezmoi import --strip-components 1 --destination ${HOME}/.oh-my-zsh oh-my-zsh-master.tar.gz\n" + - "\n" + - "Add `oh-my-zsh-master.tar.gz` to `.chezmoiignore` if you run these commands in\n" + - "your source directory so that chezmoi doesn't try to copy the tarball anywhere.\n" + - "\n" + - "Disable Oh My Zsh auto-updates by setting `DISABLE_AUTO_UPDATE=\"true\"` in\n" + - "`~/.zshrc`. Auto updates will cause the `~/.oh-my-zsh` directory to drift out of\n" + - "sync with chezmoi's source state. To update Oh My Zsh, re-run the `curl` and\n" + - "`chezmoi import` commands above.\n" + - "\n" + - "## Handle configuration files which are externally modified\n" + - "\n" + - "Some programs modify their configuration files. When you next run `chezmoi\n" + - "apply`, any modifications made by the program will be lost.\n" + - "\n" + - "You can track changes to these files by replacing with a symlink back to a file\n" + - "in your source directory, which is under version control. Here is a worked\n" + - "example for VSCode's `settings.json` on Linux:\n" + - "\n" + - "Copy the configuration file to your source directory:\n" + - "\n" + - " cp ~/.config/Code/User/settings.json $(chezmoi source-path)\n" + - "\n" + - "Tell chezmoi to ignore this file:\n" + - "\n" + - " echo settings.json >> $(chezmoi source-path)/.chezmoiignore\n" + - "\n" + - "Tell chezmoi that `~/.config/Code/User/settings.json` should be a symlink to the\n" + - "file in your source directory:\n" + - "\n" + - " mkdir -p $(chezmoi source-path)/private_dot_config/private_Code/User\n" + - " echo -n \"{{ .chezmoi.sourceDir }}/settings.json\" > $(chezmoi source-path)/private_dot_config/private_Code/User/symlink_settings.json.tmpl\n" + - "\n" + - "The prefix `private_` is used because the `~/.config` and `~/.config/Code`\n" + - "directories are private by default.\n" + - "\n" + - "Apply the changes:\n" + - "\n" + - " chezmoi apply -v\n" + - "\n" + - "Now, when the program modifies its configuration file it will modify the file in\n" + - "the source state instead.\n" + - "\n" + - "## Handle different file locations on different systems with the same contents\n" + - "\n" + - "If you want to have the same file contents in different locations on different\n" + - "systems, but maintain only a single file in your source state, you can use\n" + - "a shared template.\n" + - "\n" + - "Create the common file in the `.chezmoitemplates` directory in the source state. For\n" + - "example, create `.chezmoitemplates/file.conf`. The contents of this file are\n" + - "available in templates with the `template *name*` function where *name* is the\n" + - "name of the file.\n" + - "\n" + - "Then create files for each system, for example `Library/Application\n" + - "Support/App/file.conf.tmpl` for macOS and `dot_config/app/file.conf.tmpl` for\n" + - "Linux. Both template files should contain `{{- template \"file.conf\" -}}`.\n" + - "\n" + - "Finally, tell chezmoi to ignore files where they are not needed by adding lines\n" + - "to your `.chezmoiignore` file, for example:\n" + - "\n" + - "```\n" + - "{{ if ne .chezmoi.os \"darwin\" }}\n" + - "Library/Application Support/App/file.conf\n" + - "{{ end }}\n" + - "{{ if ne .chezmoi.os \"linux\" }}\n" + - ".config/app/file.conf\n" + - "{{ end }}\n" + - "```\n" + - "\n" + - "## Keep data private\n" + - "\n" + - "chezmoi automatically detects when files and directories are private when adding\n" + - "them by inspecting their permissions. Private files and directories are stored\n" + - "in `~/.local/share/chezmoi` as regular, public files with permissions `0644` and\n" + - "the name prefix `private_`. For example:\n" + - "\n" + - " chezmoi add ~/.netrc\n" + - "\n" + - "will create `~/.local/share/chezmoi/private_dot_netrc` (assuming `~/.netrc` is\n" + - "not world- or group- readable, as it should be). This file is still private\n" + - "because `~/.local/share/chezmoi` is not group- or world- readable or executable.\n" + - "chezmoi checks that the permissions of `~/.local/share/chezmoi` are `0700` on\n" + - "every run and will print a warning if they are not.\n" + - "\n" + - "It is common that you need to store access tokens in config files, e.g. a\n" + - "[GitHub access\n" + - "token](https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/).\n" + - "There are several ways to keep these tokens secure, and to prevent them leaving\n" + - "your machine.\n" + - "\n" + - "### Use Bitwarden to keep your secrets\n" + - "\n" + - "chezmoi includes support for [Bitwarden](https://bitwarden.com/) using the\n" + - "[Bitwarden CLI](https://github.com/bitwarden/cli) to expose data as a template\n" + - "function.\n" + - "\n" + - "Log in to Bitwarden using:\n" + - "\n" + - " bw login <bitwarden-email>\n" + - "\n" + - "Unlock your Bitwarden vault:\n" + - "\n" + - " bw unlock\n" + - "\n" + - "Set the `BW_SESSION` environment variable, as instructed.\n" + - "\n" + - "The structured data from `bw get` is available as the `bitwarden` template\n" + - "function in your config files, for example:\n" + - "\n" + - " username = {{ (bitwarden \"item\" \"example.com\").login.username }}\n" + - " password = {{ (bitwarden \"item\" \"example.com\").login.password }}\n" + - "\n" + - "Custom fields can be accessed with the `bitwardenFields` template function. For\n" + - "example, if you have a custom field named `token` you can retrieve its value\n" + - "with:\n" + - "\n" + - " {{ (bitwardenFields \"item\" \"example.com\").token.value }}\n" + - "\n" + - "### Use gopass to keep your secrets\n" + - "\n" + - "chezmoi includes support for [gopass](https://www.gopass.pw/) using the gopass CLI.\n" + - "\n" + - "The first line of the output of `gopass show <pass-name>` is available as the\n" + - "`gopass` template function, for example:\n" + - "\n" + - " {{ gopass \"<pass-name>\" }}\n" + - "\n" + - "### Use gpg to keep your secrets\n" + - "\n" + - "chezmoi supports encrypting files with [gpg](https://www.gnupg.org/). Encrypted\n" + - "files are stored in the source state and automatically be decrypted when\n" + - "generating the target state or printing a file's contents with `chezmoi cat`.\n" + - "`chezmoi edit` will transparently decrypt the file before editing and re-encrypt\n" + - "it afterwards.\n" + - "\n" + - "#### Asymmetric (private/public-key) encryption\n" + - "\n" + - "Specify the encryption key to use in your configuration file (`chezmoi.toml`)\n" + - "with the `gpg.recipient` key:\n" + - "\n" + - " [gpg]\n" + - " recipient = \"...\"\n" + - "\n" + - "Add files to be encrypted with the `--encrypt` flag, for example:\n" + - "\n" + - " chezmoi add --encrypt ~/.ssh/id_rsa\n" + - "\n" + - "chezmoi will encrypt the file with:\n" + - "\n" + - " gpg --armor --recipient ${gpg.recipient} --encrypt\n" + - "\n" + - "and store the encrypted file in the source state. The file will automatically be\n" + - "decrypted when generating the target state.\n" + - "\n" + - "#### Symmetric encryption\n" + - "\n" + - "Specify symmetric encryption in your configuration file:\n" + - "\n" + - " [gpg]\n" + - " symmetric = true\n" + - "\n" + - "Add files to be encrypted with the `--encrypt` flag, for example:\n" + - "\n" + - " chezmoi add --encrypt ~/.ssh/id_rsa\n" + - "\n" + - "chezmoi will encrypt the file with:\n" + - "\n" + - " gpg --armor --symmetric\n" + - "\n" + - "### Use KeePassXC to keep your secrets\n" + - "\n" + - "chezmoi includes support for [KeePassXC](https://keepassxc.org) using the\n" + - "KeePassXC CLI (`keepassxc-cli`) to expose data as a template function.\n" + - "\n" + - "Provide the path to your KeePassXC database in your configuration file:\n" + - "\n" + - " [keepassxc]\n" + - " database = \"/home/user/Passwords.kdbx\"\n" + - "\n" + - "The structured data from `keepassxc-cli show $database` is available as the\n" + - "`keepassxc` template function in your config files, for example:\n" + - "\n" + - " username = {{ (keepassxc \"example.com\").UserName }}\n" + - " password = {{ (keepassxc \"example.com\").Password }}\n" + - "\n" + - "Additional attributes are available through the `keepassxcAttribute` function.\n" + - "For example, if you have an entry called `SSH Key` with an additional attribute\n" + - "called `private-key`, its value is available as:\n" + - "\n" + - " {{ keepassxcAttribute \"SSH Key\" \"private-key\" }}\n" + - "\n" + - "### Use a keyring to keep your secrets\n" + - "\n" + - "chezmoi includes support for Keychain (on macOS), GNOME Keyring (on Linux), and\n" + - "Windows Credentials Manager (on Windows) via the\n" + - "[`zalando/go-keyring`](https://github.com/zalando/go-keyring) library.\n" + - "\n" + - "Set values with:\n" + - "\n" + - " $ chezmoi keyring set --service=<service> --user=<user>\n" + - " Value: xxxxxxxx\n" + - "\n" + - "The value can then be used in templates using the `keyring` function which takes\n" + - "the service and user as arguments.\n" + - "\n" + - "For example, save a GitHub access token in keyring with:\n" + - "\n" + - " $ chezmoi keyring set --service=github --user=<github-username>\n" + - " Value: xxxxxxxx\n" + - "\n" + - "and then include it in your `~/.gitconfig` file with:\n" + - "\n" + - " [github]\n" + - " user = \"{{ .github.user }}\"\n" + - " token = \"{{ keyring \"github\" .github.user }}\"\n" + - "\n" + - "You can query the keyring from the command line:\n" + - "\n" + - " chezmoi keyring get --service=github --user=<github-username>\n" + - "\n" + - "### Use LastPass to keep your secrets\n" + - "\n" + - "chezmoi includes support for [LastPass](https://lastpass.com) using the\n" + - "[LastPass CLI](https://lastpass.github.io/lastpass-cli/lpass.1.html) to expose\n" + - "data as a template function.\n" + - "\n" + - "Log in to LastPass using:\n" + - "\n" + - " lpass login <lastpass-username>\n" + - "\n" + - "Check that `lpass` is working correctly by showing password data:\n" + - "\n" + - " lpass show --json <lastpass-entry-id>\n" + - "\n" + - "where `<lastpass-entry-id>` is a [LastPass Entry\n" + - "Specification](https://lastpass.github.io/lastpass-cli/lpass.1.html#_entry_specification).\n" + - "\n" + - "The structured data from `lpass show --json id` is available as the `lastpass`\n" + - "template function. The value will be an array of objects. You can use the\n" + - "`index` function and `.Field` syntax of the `text/template` language to extract\n" + - "the field you want. For example, to extract the `password` field from first the\n" + - "\"GitHub\" entry, use:\n" + - "\n" + - " githubPassword = \"{{ (index (lastpass \"GitHub\") 0).password }}\"\n" + - "\n" + - "chezmoi automatically parses the `note` value of the Lastpass entry as\n" + - "colon-separated key-value pairs, so, for example, you can extract a private SSH\n" + - "key like this:\n" + - "\n" + - " {{ (index (lastpass \"SSH\") 0).note.privateKey }}\n" + - "\n" + - "Keys in the `note` section written as `CamelCase Words` are converted to\n" + - "`camelCaseWords`.\n" + - "\n" + - "If the `note` value does not contain colon-separated key-value pairs, then you\n" + - "can use `lastpassRaw` to get its raw value, for example:\n" + - "\n" + - " {{ (index (lastpassRaw \"SSH Private Key\") 0).note }}\n" + - "\n" + - "### Use 1Password to keep your secrets\n" + - "\n" + - "chezmoi includes support for [1Password](https://1password.com/) using the\n" + - "[1Password CLI](https://support.1password.com/command-line-getting-started/) to\n" + - "expose data as a template function.\n" + - "\n" + - "Log in and get a session using:\n" + - "\n" + - " eval $(op signin <subdomain>.1password.com <email>)\n" + - "\n" + - "The output of `op get item <uuid>` is available as the `onepassword` template\n" + - "function. chezmoi parses the JSON output and returns it as structured data. For\n" + - "example, if the output of `op get item \"<uuid>\"` is:\n" + - "\n" + - " {\n" + - " \"uuid\": \"<uuid>\",\n" + - " \"details\": {\n" + - " \"password\": \"xxx\"\n" + - " }\n" + - " }\n" + - "\n" + - "Then you can access `details.password` with the syntax:\n" + - "\n" + - " {{ (onepassword \"<uuid>\").details.password }}\n" + - "\n" + - "Login details fields can be retrieved with the `onepasswordDetailsFields`\n" + - "function, for example:\n" + - "\n" + - " {{- (onepasswordDetailsFields \"uuid\").password.value }}\n" + - "\n" + - "Documents can be retrieved with:\n" + - "\n" + - " {{- onepasswordDocument \"uuid\" -}}\n" + - "\n" + - "Note the extra `-` after the opening `{{` and before the closing `}}`. This\n" + - "instructs the template language to remove and whitespace before and after the\n" + - "substitution. This removes any trailing newline added by your editor when saving\n" + - "the template.\n" + - "\n" + - "### Use pass to keep your secrets\n" + - "\n" + - "chezmoi includes support for [pass](https://www.passwordstore.org/) using the\n" + - "pass CLI.\n" + - "\n" + - "The first line of the output of `pass show <pass-name>` is available as the\n" + - "`pass` template function, for example:\n" + - "\n" + - " {{ pass \"<pass-name>\" }}\n" + - "\n" + - "### Use Vault to keep your secrets\n" + - "\n" + - "chezmoi includes support for [Vault](https://www.vaultproject.io/) using the\n" + - "[Vault CLI](https://www.vaultproject.io/docs/commands/) to expose data as a\n" + - "template function.\n" + - "\n" + - "The vault CLI needs to be correctly configured on your machine, e.g. the\n" + - "`VAULT_ADDR` and `VAULT_TOKEN` environment variables must be set correctly.\n" + - "Verify that this is the case by running:\n" + - "\n" + - " vault kv get -format=json <key>\n" + - "\n" + - "The structured data from `vault kv get -format=json` is available as the `vault`\n" + - "template function. You can use the `.Field` syntax of the `text/template`\n" + - "language to extract the data you want. For example:\n" + - "\n" + - " {{ (vault \"<key>\").data.data.password }}\n" + - "\n" + - "### Use a generic tool to keep your secrets\n" + - "\n" + - "You can use any command line tool that outputs secrets either as a string or in\n" + - "JSON format. Choose the binary by setting `genericSecret.command` in your\n" + - "configuration file. You can then invoke this command with the `secret` and\n" + - "`secretJSON` template functions which return the raw output and JSON-decoded\n" + - "output respectively. All of the above secret managers can be supported in this\n" + - "way:\n" + - "\n" + - "| Secret Manager | `genericSecret.command` | Template skeleton |\n" + - "| --------------- | ----------------------- | ------------------------------------------------- |\n" + - "| 1Password | `op` | `{{ secretJSON \"get\" \"item\" <id> }}` |\n" + - "| Bitwarden | `bw` | `{{ secretJSON \"get\" <id> }}` |\n" + - "| Hashicorp Vault | `vault` | `{{ secretJSON \"kv\" \"get\" \"-format=json\" <id> }}` |\n" + - "| LastPass | `lpass` | `{{ secretJSON \"show\" \"--json\" <id> }}` |\n" + - "| KeePassXC | `keepassxc-cli` | Not possible (interactive command only) |\n" + - "| pass | `pass` | `{{ secret \"show\" <id> }}` |\n" + - "\n" + - "### Use templates variables to keep your secrets\n" + - "\n" + - "Typically, `~/.config/chezmoi/chezmoi.toml` is not checked in to version control\n" + - "and has permissions 0600. You can store tokens as template values in the `data`\n" + - "section. For example, if your `~/.config/chezmoi/chezmoi.toml` contains:\n" + - "\n" + - " [data]\n" + - " [data.github]\n" + - " user = \"<github-username>\"\n" + - " token = \"<github-token>\"\n" + - "\n" + - "Your `~/.local/share/chezmoi/private_dot_gitconfig.tmpl` can then contain:\n" + - "\n" + - " {{- if (index . \"github\") }}\n" + - " [github]\n" + - " user = \"{{ .github.user }}\"\n" + - " token = \"{{ .github.token }}\"\n" + - " {{- end }}\n" + - "\n" + - "Any config files containing tokens in plain text should be private (permissions\n" + - "`0600`).\n" + - "\n" + - "## Use scripts to perform actions\n" + - "\n" + - "### Understand how scripts work\n" + - "\n" + - "chezmoi supports scripts, which are executed when you run `chezmoi apply`. The\n" + - "scripts can either run every time you run `chezmoi apply`, or only when their\n" + - "contents have changed.\n" + - "\n" + - "In verbose mode, the script's contents will be printed before executing it. In\n" + - "dry-run mode, the script is not executed.\n" + - "\n" + - "Scripts are any file in the source directory with the prefix `run_`, and are\n" + - "executed in alphabetical order. Scripts that should only be run when their\n" + - "contents change have the prefix `run_once_`.\n" + - "\n" + - "Scripts break chezmoi's declarative approach, and as such should be used\n" + - "sparingly. Any script should be idempotent, even `run_once_` scripts.\n" + - "\n" + - "Scripts must be created manually in the source directory, typically by running\n" + - "`chezmoi cd` and then creating a file with a `run_` prefix. Scripts are executed\n" + - "directly using `exec` and must include a shebang line or be executable binaries.\n" + - "There is no need to set the executable bit on the script.\n" + - "\n" + - "Scripts with the suffix `.tmpl` are treated as templates, with the usual\n" + - "template variables available. If, after executing the template, the result is\n" + - "only whitespace or an empty string, then the script is not executed. This is\n" + - "useful for disabling scripts.\n" + - "\n" + - "### Install packages with scripts\n" + - "\n" + - "Change to the source directory and create a file called\n" + - "`run_once_install-packages.sh`:\n" + - "\n" + - " chezmoi cd\n" + - " $EDITOR run_once_install-packages.sh\n" + - "\n" + - "In this file create your package installation script, e.g.\n" + - "\n" + - " #!/bin/sh\n" + - " sudo apt install ripgrep\n" + - "\n" + - "The next time you run `chezmoi apply` or `chezmoi update` this script will be\n" + - "run. As it has the `run_once_` prefix, it will not be run again unless its\n" + - "contents change, for example if you add more packages to be installed.\n" + - "\n" + - "This script can also be a template. For example, if you create\n" + - "`run_once_install-packages.sh.tmpl` with the contents:\n" + - "\n" + - " {{ if eq .chezmoi.os \"linux\" -}}\n" + - " #!/bin/sh\n" + - " sudo apt install ripgrep\n" + - " {{ else if eq .chezmoi.os \"darwin\" -}}\n" + - " #!/bin/sh\n" + - " brew install ripgrep\n" + - " {{ end -}}\n" + - "\n" + - "This will install `ripgrep` on both Debian/Ubuntu Linux systems and macOS.\n" + - "\n" + - "## Use chezmoi with GitHub Codespaces, Visual Studio Codespaces, Visual Studio Code Remote - Containers\n" + - "\n" + - "The following assumes you are using chezmoi 1.8.4 or later. It does not work\n" + - "with earlier versions of chezmoi.\n" + - "\n" + - "You can use chezmoi to manage your dotfiles in [GitHub\n" + - "Codespaces](https://docs.github.com/en/github/developing-online-with-codespaces/personalizing-codespaces-for-your-account),\n" + - "[Visual Studio\n" + - "Codespaces](https://docs.microsoft.com/en/visualstudio/codespaces/reference/personalizing),\n" + - "and [Visual Studio Code Remote -\n" + - "Containers](https://code.visualstudio.com/docs/remote/containers#_personalizing-with-dotfile-repositories).\n" + - "\n" + - "For a quick start, you can clone the [`chezmoi/dotfiles`\n" + - "repository](https://github.com/chezmoi/dotfiles) which supports Codespaces out\n" + - "of the box.\n" + - "\n" + - "The workflow is different to using chezmoi on a new machine, notably:\n" + - "* These systems will automatically clone your `dotfiles` repo to `~/dotfiles`,\n" + - " so there is no need to clone your repo yourself.\n" + - "* The installation script must be non-interactive.\n" + - "* When running in a Codespace, the environment variable `CODESPACES` will be set\n" + - " to `true`. You can read its value with the [`env` template\n" + - " function](http://masterminds.github.io/sprig/os.html).\n" + - "\n" + - "First, if you are using a chezmoi configuration file template, ensure that it is\n" + - "non-interactive when running in codespaces, for example, `.chezmoi.toml.tmpl`\n" + - "might contain:\n" + - "\n" + - "```\n" + - "{{- $codespaces:= env \"CODESPACES\" | not | not -}}\n" + - "sourceDir = \"{{ .chezmoi.sourceDir }}\"\n" + - "\n" + - "[data]\n" + - " name = \"Your name\"\n" + - " codespaces = {{ $codespaces }}\n" + - "{{- if $codespaces }}{{/* Codespaces dotfiles setup is non-interactive, so set an email address */}}\n" + - " email = \"[email protected]\"\n" + - "{{- else }}{{/* Interactive setup, so prompt for an email address */}}\n" + - " email = \"{{ promptString \"email\" }}\"\n" + - "{{- end }}\n" + - "```\n" + - "\n" + - "This sets the `codespaces` template variable, so you don't have to repeat `(env\n" + - "\"CODESPACES\")` in your templates. It also sets the `sourceDir` configuration to\n" + - "the `--source` argument passed in `chezmoi init`.\n" + - "\n" + - "Second, create an `install.sh` script that installs chezmoi and your dotfiles:\n" + - "\n" + - "```sh\n" + - "#!/bin/sh\n" + - "\n" + - "set -e # -e: exit on error\n" + - "\n" + - "if [ ! \"$(command -v chezmoi)\" ]; then\n" + - " bin_dir=\"$HOME/.local/bin\"\n" + - " chezmoi=\"$bin_dir/chezmoi\"\n" + - " if [ \"$(command -v curl)\" ]; then\n" + - " sh -c \"$(curl -fsSL https://git.io/chezmoi)\" -- -b \"$bin_dir\"\n" + - " elif [ \"$(command -v wget)\" ]; then\n" + - " sh -c \"$(wget -qO- https://git.io/chezmoi)\" -- -b \"$bin_dir\"\n" + - " else\n" + - " echo \"To install chezmoi, you must have curl or wget installed.\" >&2\n" + - " exit 1\n" + - " fi\n" + - "else\n" + - " chezmoi=chezmoi\n" + - "fi\n" + - "\n" + - "# POSIX way to get script's dir: https://stackoverflow.com/a/29834779/12156188\n" + - "script_dir=\"$(cd -P -- \"$(dirname -- \"$(command -v -- \"$0\")\")\" && pwd -P)\"\n" + - "# exec: replace current process with chezmoi init\n" + - "exec \"$chezmoi\" init --apply \"--source=$script_dir\"\n" + - "```\n" + - "\n" + - "Ensure that this file is executable (`chmod a+x install.sh`), and add\n" + - "`install.sh` to your `.chezmoiignore` file.\n" + - "\n" + - "It installs the latest version of chezmoi in `~/.local/bin` if needed, and then\n" + - "`chezmoi init ...` invokes chezmoi to create its configuration file and\n" + - "initialize your dotfiles. `--apply` tells chezmoi to apply the changes\n" + - "immediately, and `--source=...` tells chezmoi where to find the cloned\n" + - "`dotfiles` repo, which in this case is the same folder in which the script is\n" + - "running from.\n" + - "\n" + - "If you do not use a chezmoi configuration file template you can use `chezmoi\n" + - "apply --source=$HOME/dotfiles` instead of `chezmoi init ...` in `install.sh`.\n" + - "\n" + - "Finally, modify any of your templates to use the `codespaces` variable if\n" + - "needed. For example, to install `vim-gtk` on Linux but not in Codespaces, your\n" + - "`run_once_install-packages.sh.tmpl` might contain:\n" + - "\n" + - "```\n" + - "{{- if (and (eq .chezmoi.os \"linux\")) (not .codespaces))) -}}\n" + - "#!/bin/sh\n" + - "sudo apt install -y vim-gtk\n" + - "{{- end -}}\n" + - "```\n" + - "\n" + - "## Detect Windows Subsystem for Linux (WSL)\n" + - "\n" + - "WSL can be detected by looking for the string `Microsoft` in\n" + - "`/proc/kernel/osrelease`, which is available in the template variable\n" + - "`.chezmoi.kernel.osrelease`, for example:\n" + - "\n" + - "WSL 1:\n" + - "```\n" + - "{{ if (contains \"Microsoft\" .chezmoi.kernel.osrelease) }}\n" + - "# WSL-specific code\n" + - "{{ end }}\n" + - "```\n" + - "\n" + - "WSL 2:\n" + - "```\n" + - "{{ if (contains \"microsoft\" .chezmoi.kernel.osrelease) }}\n" + - "# WSL-specific code\n" + - "{{ end }}\n" + - "```\n" + - "\n" + - "WSL 2 since version 4.19.112:\n" + - "```\n" + - "{{ if (contains \"microsoft-WSL2\" .chezmoi.kernel.osrelease) }}\n" + - "# WSL-specific code\n" + - "{{ end }}\n" + - "```\n" + - "\n" + - "## Run a PowerShell script as admin on Windows\n" + - "\n" + - "Put the following at the top of your script:\n" + - "\n" + - "```powershell\n" + - "# Self-elevate the script if required\n" + - "if (-Not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')) {\n" + - " if ([int](Get-CimInstance -Class Win32_OperatingSystem | Select-Object -ExpandProperty BuildNumber) -ge 6000) {\n" + - " $CommandLine = \"-NoExit -File `\"\" + $MyInvocation.MyCommand.Path + \"`\" \" + $MyInvocation.UnboundArguments\n" + - " Start-Process -FilePath PowerShell.exe -Verb Runas -ArgumentList $CommandLine\n" + - " Exit\n" + - " }\n" + - "}\n" + - "```\n" + - "\n" + - "## Import archives\n" + - "\n" + - "It is occasionally useful to import entire archives of configuration into your\n" + - "source state. The `import` command does this. For example, to import the latest\n" + - "version\n" + - "[`github.com/robbyrussell/oh-my-zsh`](https://github.com/robbyrussell/oh-my-zsh)\n" + - "to `~/.oh-my-zsh` run:\n" + - "\n" + - " curl -s -L -o oh-my-zsh-master.tar.gz https://github.com/robbyrussell/oh-my-zsh/archive/master.tar.gz\n" + - " chezmoi import --strip-components 1 --destination ~/.oh-my-zsh oh-my-zsh-master.tar.gz\n" + - "\n" + - "Note that this only updates the source state. You will need to run\n" + - "\n" + - " chezmoi apply\n" + - "\n" + - "to update your destination directory.\n" + - "\n" + - "## Export archives\n" + - "\n" + - "chezmoi can create an archive containing the target state. This can be useful\n" + - "for generating target state on a different machine or for simply inspecting the\n" + - "target state. A particularly useful command is:\n" + - "\n" + - " chezmoi archive | tar tvf -\n" + - "\n" + - "which lists all the targets in the target state.\n" + - "\n" + - "## Use a non-git version control system\n" + - "\n" + - "By default, chezmoi uses git, but you can use any version control system of your\n" + - "choice. In your config file, specify the command to use. For example, to use\n" + - "Mercurial specify:\n" + - "\n" + - " [sourceVCS]\n" + - " command = \"hg\"\n" + - "\n" + - "The source VCS command is used in the chezmoi commands `init`, `source`, and\n" + - "`update`, and support for VCSes other than git is limited but easy to add. If\n" + - "you'd like to see your VCS better supported, please [open an issue on\n" + - "GitHub](https://github.com/twpayne/chezmoi/issues/new/choose).\n" + - "\n" + - "## Customize the `diff` command\n" + - "\n" + - "By default, chezmoi uses a built-in diff. You can change the format, and/or pipe\n" + - "the output into a pager of your choice. For example, to use\n" + - "[`diff-so-fancy`](https://github.com/so-fancy/diff-so-fancy) specify:\n" + - "\n" + - " [diff]\n" + - " format = \"git\"\n" + - " pager = \"diff-so-fancy\"\n" + - "\n" + - "The format can also be set with the `--format` option to the `diff` command, and\n" + - "the pager can be disabled using `--no-pager`.\n" + - "\n" + - "## Use a merge tool other than vimdiff\n" + - "\n" + - "By default, chezmoi uses vimdiff, but you can use any merge tool of your choice.\n" + - "In your config file, specify the command and args to use. For example, to use\n" + - "neovim's diff mode specify:\n" + - "\n" + - " [merge]\n" + - " command = \"nvim\"\n" + - " args = \"-d\"\n" + - "\n" + - "## Migrate from a dotfile manager that uses symlinks\n" + - "\n" + - "Many dotfile managers replace dotfiles with symbolic links to files in a common\n" + - "directory. If you `chezmoi add` such a symlink, chezmoi will add the symlink,\n" + - "not the file. To assist with migrating from symlink-based systems, use the\n" + - "`--follow` option to `chezmoi add`, for example:\n" + - "\n" + - " chezmoi add --follow ~/.bashrc\n" + - "\n" + - "This will tell `chezmoi add` that the target state of `~/.bashrc` is the target\n" + - "of the `~/.bashrc` symlink, rather than the symlink itself. When you run\n" + - "`chezmoi apply`, chezmoi will replace the `~/.bashrc` symlink with the file\n" + - "contents.\n" + - "\n") - assets["docs/INSTALL.md"] = []byte("" + - "# chezmoi Install Guide\n" + - "\n" + - "<!--- toc --->\n" + - "* [One-line binary install](#one-line-binary-install)\n" + - "* [One-line package install](#one-line-package-install)\n" + - "* [Pre-built Linux packages](#pre-built-linux-packages)\n" + - "* [Pre-built binaries](#pre-built-binaries)\n" + - "* [All pre-built Linux packages and binaries](#all-pre-built-linux-packages-and-binaries)\n" + - "* [From source](#from-source)\n" + - "* [Upgrading](#upgrading)\n" + - "\n" + - "## One-line binary install\n" + - "\n" + - "Install the correct binary for your operating system and architecture in `./bin`\n" + - "with a single command.\n" + - "\n" + - " curl -sfL https://git.io/chezmoi | sh\n" + - "\n" + - "Or on systems with Powershell, you can use this command:\n" + - "\n" + - " # To install in ./bin\n" + - " (iwr https://git.io/chezmoi.ps1).Content | powershell -c -\n" + - "\n" + - " # To install in another location\n" + - " '$params = \"-BinDir ~/other\"', (iwr https://git.io/chezmoi.ps1).Content | powershell -c -\n" + - "\n" + - " # For information about other options, try this:\n" + - " '$params = \"-?\"', (iwr https://git.io/chezmoi.ps1).Content | powershell -c -\n" + - "\n" + - "## One-line package install\n" + - "\n" + - "Install chezmoi with a single command.\n" + - "\n" + - "| OS | Method | Command |\n" + - "| ------------ | ---------- | ------------------------------------------------------------------------------------------- |\n" + - "| Linux | snap | `snap install chezmoi --classic` |\n" + - "| Linux | Linuxbrew | `brew install chezmoi` |\n" + - "| Alpine Linux | apk | `apk add chezmoi` |\n" + - "| Arch Linux | pacman | `pacman -S chezmoi` |\n" + - "| Guix Linux | guix | `guix install chezmoi` |\n" + - "| NixOS Linux | nix-env | `nix-env -i chezmoi` |\n" + - "| Void Linux | xbps | `xbps-install -S chezmoi` |\n" + - "| macOS | Homebrew | `brew install chezmoi` |\n" + - "| macOS | MacPorts | `sudo port install chezmoi` |\n" + - "| Windows | Scoop | `scoop bucket add twpayne https://github.com/twpayne/scoop-bucket && scoop install chezmoi` |\n" + - "| Windows | Chocolatey | `choco install chezmoi` |\n" + - "\n" + - "## Pre-built Linux packages\n" + - "\n" + - "Download a package for your operating system and architecture and install it\n" + - "with your package manager.\n" + - "\n" + - "| Distribution | Architectures | Package |\n" + - "| ------------ | --------------------------------------------------------- | ----------------------------------------------------------- |\n" + - "| Alpine | `386`, `amd64`, `arm64`, `arm`, `ppc64`, `ppc64le` | [`apk`](https://github.com/twpayne/chezmoi/releases/latest) |\n" + - "| Debian | `amd64`, `arm64`, `armel`, `i386`, `ppc64`, `ppc64le` | [`deb`](https://github.com/twpayne/chezmoi/releases/latest) |\n" + - "| RedHat | `aarch64`, `armhfp`, `i686`, `ppc64`, `ppc64le`, `x86_64` | [`rpm`](https://github.com/twpayne/chezmoi/releases/latest) |\n" + - "| OpenSUSE | `aarch64`, `armhfp`, `i686`, `ppc64`, `ppc64le`, `x86_64` | [`rpm`](https://github.com/twpayne/chezmoi/releases/latest) |\n" + - "| Ubuntu | `amd64`, `arm64`, `armel`, `i386`, `ppc64`, `ppc64le` | [`deb`](https://github.com/twpayne/chezmoi/releases/latest) |\n" + - "\n" + - "## Pre-built binaries\n" + - "\n" + - "Download an archive for your operating system containing a pre-built binary,\n" + - "documentation, and shell completions.\n" + - "\n" + - "| OS | Architectures | Archive |\n" + - "| ---------- | --------------------------------------------------- | -------------------------------------------------------------- |\n" + - "| FreeBSD | `amd64`, `arm`, `arm64`, `i386` | [`tar.gz`](https://github.com/twpayne/chezmoi/releases/latest) |\n" + - "| Linux | `amd64`, `arm`, `arm64`, `i386`, `ppc64`, `ppc64le` | [`tar.gz`](https://github.com/twpayne/chezmoi/releases/latest) |\n" + - "| macOS | `amd64` | [`tar.gz`](https://github.com/twpayne/chezmoi/releases/latest) |\n" + - "| OpenBSD | `amd64`, `arm`, `arm64`, `i386` | [`tar.gz`](https://github.com/twpayne/chezmoi/releases/latest) |\n" + - "| Windows | `amd64`, `i386` | [`zip`](https://github.com/twpayne/chezmoi/releases/latest) |\n" + - "\n" + - "## All pre-built Linux packages and binaries\n" + - "\n" + - "All pre-built binaries and packages can be found on the [chezmoi GitHub releases\n" + - "page](https://github.com/twpayne/chezmoi/releases/latest).\n" + - "\n" + - "## From source\n" + - "\n" + - "Download, build, and install chezmoi for your system:\n" + - "\n" + - " cd $(mktemp -d)\n" + - " git clone --depth=1 https://github.com/twpayne/chezmoi.git\n" + - " cd chezmoi\n" + - " go install\n" + - "\n" + - "Building chezmoi requires Go 1.14 or later.\n" + - "\n" + - "## Upgrading\n" + - "\n" + - "If you have installed a pre-built binary of chezmoi, you can upgrade it to the\n" + - "latest release with:\n" + - "\n" + - " chezmoi upgrade\n" + - "\n" + - "This will re-use whichever mechanism you used to install chezmoi to install the\n" + - "latest release.\n" + - "\n") - assets["docs/MEDIA.md"] = []byte("" + - "# chezmoi in the media\n" + - "\n" + - "<!--- toc --->\n" + - "\n" + - "Recommended article: [Fedora Magazine: Take back your dotfiles with Chezmoi](https://fedoramagazine.org/take-back-your-dotfiles-with-chezmoi/)\n" + - "\n" + - "Recommended video: [Conf42: chezmoi: Manage your dotfiles across multiple machines, securely](https://www.youtube.com/watch?v=JrCMCdvoMAw)\n" + - "\n" + - "Recommended podcast: [FLOSS weekly episode 556: chezmoi](https://twit.tv/shows/floss-weekly/episodes/556)\n" + - "\n" + - "| Date | Version | Format | Link |\n" + - "| ---------- | ------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n" + - "| 2021-02-06 | 1.8.10 | Video | [chezmoi: manage your dotfiles across multiple, diverse machines, securely](https://fosdem.org/2021/schedule/event/chezmoi/) |\n" + - "| 2021-01-12 | 1.8.10 | Text | [Automating the Setup of a New Mac With All Your Apps, Preferences, and Development Tools](https://www.moncefbelyamani.com/automating-the-setup-of-a-new-mac-with-all-your-apps-preferences-and-development-tools/) |\n" + - "| 2020-11-06 | 1.8.8 | Text | [Chezmoi – Securely Manage dotfiles across multiple machines](https://computingforgeeks.com/chezmoi-manage-dotfiles-across-multiple-machines/) |\n" + - "| 2020-11-05 | 1.8.8 | Text | [Using chezmoi to manage dotfiles](https://pashinskikh.de/posts/chezmoi/) |\n" + - "| 2020-10-05 | 1.8.6 | Text | [Dotfiles with /Chezmoi/](https://blog.lazkani.io/posts/backup/dotfiles-with-chezmoi/) |\n" + - "| 2020-08-13 | 1.8.3 | Text | [Using BitWarden and Chezmoi to manage SSH keys](https://www.jx0.uk/chezmoi/bitwarden/unix/ssh/2020/08/13/bitwarden-chezmoi-ssh-key.html) |\n" + - "| 2020-08-09 | 1.8.3 | Text | [Automating and testing dotfiles](https://seds.nl/posts/automating-and-testing-dotfiles/) |\n" + - "| 2020-08-03 | 1.8.3 | Text | [Automating a Linux in Windows Dev Setup](https://matt.aimonetti.net/posts/2020-08-automating-a-linux-in-windows-dev-setup/) |\n" + - "| 2020-07-06 | 1.8.3 | Video | [Conf42: chezmoi: Manage your dotfiles across multiple machines, securely](https://www.youtube.com/watch?v=JrCMCdvoMAw) |\n" + - "| 2020-07-03 | 1.8.3 | Text | [Feeling at home in a LXD container](https://ubuntu.com/blog/feeling-at-home-in-a-lxd-container) |\n" + - "| 2020-06-15 | 1.8.2 | Text | [Dotfiles management using chezmoi - How I Use Linux Desktop at Work Part5](https://blog.benoitj.ca/2020-06-15-how-i-use-linux-desktop-at-work-part5-dotfiles/) |\n" + - "| 2020-04-27 | 1.8.0 | Text | [Managing my dotfiles with chezmoi](http://blog.emilieschario.com/post/managing-my-dotfiles-with-chezmoi/) |\n" + - "| 2020-04-20 | 1.8.0 | Text (FR) | [Gestion des dotfiles et des secrets avec chezmoi](https://blog.arkey.fr/2020/04/01/manage_dotfiles_with_chezmoi.fr/) |\n" + - "| 2020-04-19 | 1.7.19 | Text (FR) | [Git & dotfiles : versionner ses fichiers de configuration](https://www.armandphilippot.com/dotfiles-git-fichiers-configuration/) |\n" + - "| 2020-04-16 | 1.7.19 | Text (FR) | [Chezmoi, visite guidée](https://blog.wescale.fr/2020/04/16/chezmoi-visite-guidee/) |\n" + - "| 2020-04-03 | 1.7.17 | Text | [Fedora Magazine: Take back your dotfiles with Chezmoi](https://fedoramagazine.org/take-back-your-dotfiles-with-chezmoi/) |\n" + - "| 2020-04-01 | 1.7.17 | Text | [Managing dotfiles and secret with chezmoi](https://blog.arkey.fr/2020/04/01/manage_dotfiles_with_chezmoi/) |\n" + - "| 2020-03-12 | 1.7.16 | Video | [Managing Dotfiles with ChezMoi](https://www.youtube.com/watch?v=HXx6ugA98Qo) |\n" + - "| 2019-11-20 | 1.7.2 | Audio/video | [FLOSS weekly episode 556: chezmoi](https://twit.tv/shows/floss-weekly/episodes/556) |\n" + - "| 2019-01-10 | 0.0.11 | Text | [Linux Fu: The kitchen sync](https://hackaday.com/2019/01/10/linux-fu-the-kitchen-sync/) |\n" + - "\n" + - "To add your article to this page please either [open an\n" + - "issue](https://github.com/twpayne/chezmoi/issues/new/choose) or submit a pull\n" + - "request that modifies this file\n" + - "([`docs/MEDIA.md`](https://github.com/twpayne/chezmoi/blob/master/docs/MEDIA.md)).\n" + - "\n") - assets["docs/QUICKSTART.md"] = []byte("" + - "# chezmoi Quick Start Guide\n" + - "\n" + - "<!--- toc --->\n" + - "* [Concepts](#concepts)\n" + - "* [Start using chezmoi on your current machine](#start-using-chezmoi-on-your-current-machine)\n" + - "* [Using chezmoi across multiple machines](#using-chezmoi-across-multiple-machines)\n" + - "* [Next steps](#next-steps)\n" + - "\n" + - "## Concepts\n" + - "\n" + - "chezmoi stores the desired state of your dotfiles in the directory\n" + - "`~/.local/share/chezmoi`. When you run `chezmoi apply`, chezmoi calculates the\n" + - "desired contents and permissions for each dotfile and then makes any changes\n" + - "necessary so that your dotfiles match that state.\n" + - "\n" + - "## Start using chezmoi on your current machine\n" + - "\n" + - "Initialize chezmoi:\n" + - "\n" + - " chezmoi init\n" + - "\n" + - "This will create a new git repository in `~/.local/share/chezmoi` with\n" + - "permissions `0700` where chezmoi will store the source state. chezmoi only\n" + - "modifies files in the working copy. It is your responsibility to commit changes.\n" + - "\n" + - "Manage an existing file with chezmoi:\n" + - "\n" + - " chezmoi add ~/.bashrc\n" + - "\n" + - "This will copy `~/.bashrc` to `~/.local/share/chezmoi/dot_bashrc`. If you want\n" + - "to add a whole folder to chezmoi, you have to add the `-r` argument after `add`.\n" + - "\n" + - "Edit the source state:\n" + - "\n" + - " chezmoi edit ~/.bashrc\n" + - "\n" + - "This will open `~/.local/share/chezmoi/dot_bashrc` in your `$EDITOR`. Make some\n" + - "changes and save them.\n" + - "\n" + - "See what changes chezmoi would make:\n" + - "\n" + - " chezmoi diff\n" + - "\n" + - "Apply the changes:\n" + - "\n" + - " chezmoi -v apply\n" + - "\n" + - "All chezmoi commands accept the `-v` (verbose) flag to print out exactly what\n" + - "changes they will make to the file system, and the `-n` (dry run) flag to not\n" + - "make any actual changes. The combination `-n` `-v` is very useful if you want to\n" + - "see exactly what changes would be made.\n" + - "\n" + - "Finally, open a shell in the source directory, commit your changes, and return\n" + - "to where you were:\n" + - "\n" + - " chezmoi cd\n" + - " git add dot_bashrc\n" + - " git commit -m \"Add .bashrc\"\n" + - " exit\n" + - "\n" + - "## Using chezmoi across multiple machines\n" + - "\n" + - "Clone the git repo in `~/.local/share/chezmoi` to a hosted Git service, e.g.\n" + - "[GitHub](https://github.com), [GitLab](https://gitlab.com), or\n" + - "[BitBucket](https://bitbucket.org). Many people call their dotfiles repo\n" + - "`dotfiles`. You can then setup chezmoi on a second machine:\n" + - "\n" + - " chezmoi init https://github.com/username/dotfiles.git\n" + - "\n" + - "This will check out the repo and any submodules and optionally create a chezmoi\n" + - "config file for you. It won't make any changes to your home directory until you\n" + - "run:\n" + - "\n" + - " chezmoi apply\n" + - "\n" + - "On any machine, you can pull and apply the latest changes from your repo with:\n" + - "\n" + - " chezmoi update\n" + - "\n" + - "## Next steps\n" + - "\n" + - "For a full list of commands run:\n" + - "\n" + - " chezmoi help\n" + - "\n" + - "chezmoi has much more functionality. Read the [how-to\n" + - "guide](https://github.com/twpayne/chezmoi/blob/master/docs/HOWTO.md) to explore.\n" + - "\n") -} diff --git a/chezmoi2/cmd/docs_embeddocs.go b/chezmoi2/cmd/docs_embeddocs.go deleted file mode 100644 index b812bc048eb..00000000000 --- a/chezmoi2/cmd/docs_embeddocs.go +++ /dev/null @@ -1,27 +0,0 @@ -// +build !nodocs -// +build !noembeddocs - -package cmd - -import ( - "strings" -) - -// DocsDir is unused when chezmoi is built with embedded docs. -var DocsDir = "" - -var docsPrefix = "docs/" - -func doc(filename string) ([]byte, error) { - return asset(docsPrefix + filename) -} - -func docsFilenames() ([]string, error) { - var docsFilenames []string - for name := range assets { - if strings.HasPrefix(name, docsPrefix) { - docsFilenames = append(docsFilenames, strings.TrimPrefix(name, docsPrefix)) - } - } - return docsFilenames, nil -} diff --git a/chezmoi2/cmd/docs_noembeddocs.go b/chezmoi2/cmd/docs_noembeddocs.go deleted file mode 100644 index 2d79e1d736b..00000000000 --- a/chezmoi2/cmd/docs_noembeddocs.go +++ /dev/null @@ -1,27 +0,0 @@ -// +build !nodocs -// +build noembeddocs - -package cmd - -import ( - "io/ioutil" - "os" - "path/filepath" -) - -// DocsDir is the directory containing docs when chezmoi is built without -// embedded docs. It should be an absolute path. -var DocsDir = "docs" - -func doc(filename string) ([]byte, error) { - return ioutil.ReadFile(filepath.Join(DocsDir, filename)) -} - -func docsFilenames() ([]string, error) { - f, err := os.Open(DocsDir) - if err != nil { - return nil, err - } - defer f.Close() - return f.Readdirnames(-1) -} diff --git a/chezmoi2/cmd/helps.gen.go b/chezmoi2/cmd/helps.gen.go deleted file mode 100644 index e3efb89d40c..00000000000 --- a/chezmoi2/cmd/helps.gen.go +++ /dev/null @@ -1,570 +0,0 @@ -// Code generated by github.com/twpayne/chezmoi/internal/cmd/generate-helps. DO NOT EDIT. - -package cmd - -type help struct { - long string - example string -} - -var helps = map[string]help{ - "add": { - long: "" + - "Description:\n" + - " Add *targets* to the source state. If any target is already in the source\n" + - " state, then its source state is replaced with its current state in the\n" + - " destination directory. The `add` command accepts additional flags:\n" + - "\n" + - " `--autotemplate`\n" + - "\n" + - " Automatically generate a template by replacing strings with variable names\n" + - " from the `data` section of the config file. Longer substitutions occur\n" + - " before shorter ones. This implies the `--template` option.\n" + - "\n" + - " `-e`, `--empty`\n" + - "\n" + - " Set the `empty` attribute on added files.\n" + - "\n" + - " `-f`, `--force`\n" + - "\n" + - " Add *targets*, even if doing so would cause a source template to be\n" + - " overwritten.\n" + - "\n" + - " `--follow`\n" + - "\n" + - " If the last part of a target is a symlink, add the target of the symlink\n" + - " instead of the symlink itself.\n" + - "\n" + - " `-x`, `--exact`\n" + - "\n" + - " Set the `exact` attribute on added directories.\n" + - "\n" + - " `-i`, `--include` *types*\n" + - "\n" + - " Only add entries of type *types*.\n" + - "\n" + - " `-p`, `--prompt`\n" + - "\n" + - " Interactively prompt before adding each file.\n" + - "\n" + - " `-r`, `--recursive`\n" + - "\n" + - " Recursively add all files, directories, and symlinks.\n" + - "\n" + - " `-T`, `--template`\n" + - "\n" + - " Set the `template` attribute on added files and symlinks.", - example: "" + - " chezmoi add ~/.bashrc\n" + - " chezmoi add ~/.gitconfig --template\n" + - " chezmoi add ~/.vim --recursive\n" + - " chezmoi add ~/.oh-my-zsh --exact --recursive", - }, - "apply": { - long: "" + - "Description:\n" + - " Ensure that *targets* are in the target state, updating them if necessary.\n" + - " If no targets are specified, the state of all targets are ensured. If a\n" + - " target has been modified since chezmoi last wrote it then the user will be\n" + - " prompted if they want to overwrite the file.\n" + - "\n" + - " `-i`, `--include` *types*\n" + - "\n" + - " Only add entries of type *types*.\n" + - "\n" + - " `--source-path`\n" + - "\n" + - " Specify targets by source path, rather than target path. This is useful for\n" + - " applying changes after editing.", - example: "" + - " chezmoi apply\n" + - " chezmoi apply --dry-run --verbose\n" + - " chezmoi apply ~/.bashrc\n" + - "\n" + - "In `~/.vimrc`:\n" + - "\n" + - " autocmd BufWritePost ~/.local/share/chezmoi/* ! chezmoi apply --source-path %", - }, - "archive": { - long: "" + - "Description:\n" + - " Generate a tar archive of the target state. This can be piped into `tar` to\n" + - " inspect the target state.\n" + - "\n" + - " `--format` *format*\n" + - "\n" + - " Write the archive in *format*. *format* can be either `tar` (the default) or\n" + - " `zip`.\n" + - "\n" + - " `-i`, `--include` *types*\n" + - "\n" + - " Only include entries of type *types*.\n" + - "\n" + - " `-z`, `--gzip`\n" + - "\n" + - " Compress the output with gzip.", - example: "" + - " chezmoi archive | tar tvf -\n" + - " chezmoi archive --output=dotfiles.tar\n" + - " chezmoi archive --format=zip --output=dotfiles.zip", - }, - "cat": { - long: "" + - "Description:\n" + - " Write the target state of *targets* to stdout. *targets* must be files or\n" + - " symlinks. For files, the target file contents are written. For symlinks, the\n" + - " target target is written.", - example: "" + - " chezmoi cat ~/.bashrc", - }, - "cd": { - long: "" + - "Description:\n" + - " Launch a shell in the source directory. chezmoi will launch the command set\n" + - " by the `cd.command` configuration variable with any extra arguments\n" + - " specified by `cd.args`. If this is not set, chezmoi will attempt to detect\n" + - " your shell and will finally fall back to an OS-specific default.", - example: "" + - " chezmoi cd", - }, - "chattr": { - long: "" + - "Description:\n" + - " Change the attributes of *targets*. *attributes* specifies which attributes\n" + - " to modify. Add attributes by specifying them or their abbreviations\n" + - " directly, optionally prefixed with a plus sign (`+`). Remove attributes by\n" + - " prefixing them or their attributes with the string `no` or a minus sign (`-\n" + - " `). The available attributes and their abbreviations are:\n" + - "\n" + - " ATTRIBUTE | ABBREVIATION\n" + - " -------------+---------------\n" + - " empty | e\n" + - " encrypted | none\n" + - " exact | none\n" + - " executable | x\n" + - " private | p\n" + - " template | t\n" + - "\n" + - " Multiple attributes modifications may be specified by separating them with a\n" + - " comma (`,`).", - example: "" + - " chezmoi chattr template ~/.bashrc\n" + - " chezmoi chattr noempty ~/.profile\n" + - " chezmoi chattr private,template ~/.netrc", - }, - "completion": { - long: "" + - "Description:\n" + - " Generate shell completion code for the specified shell (`bash`, `fish`,\n" + - " `powershell`, or `zsh`).", - example: "" + - " chezmoi completion bash\n" + - " chezmoi completion fish --output=~/.config/fish/completions/chezmoi.fish", - }, - "data": { - long: "" + - "Description:\n" + - " Write the computed template data to stdout.", - example: "" + - " chezmoi data\n" + - " chezmoi data --format=yaml", - }, - "diff": { - long: "" + - "Description:\n" + - " Print the difference between the target state and the destination state for\n" + - " *targets*. If no targets are specified, print the differences for all\n" + - " targets.\n" + - "\n" + - " If a `diff.pager` command is set in the configuration file then the output\n" + - " will be piped into it.", - example: "" + - " chezmoi diff\n" + - " chezmoi diff ~/.bashrc", - }, - "docs": { - long: "" + - "Description:\n" + - " Print the documentation page matching the regular expression *regexp*.\n" + - " Matching is case insensitive. If no pattern is given, print `REFERENCE.md`.", - example: "" + - " chezmoi docs\n" + - " chezmoi docs faq\n" + - " chezmoi docs howto", - }, - "doctor": { - long: "" + - "Description:\n" + - " Check for potential problems.", - example: "" + - " chezmoi doctor", - }, - "dump": { - long: "" + - "Description:\n" + - " Dump the target state. If no targets are specified, then the entire target\n" + - " state.\n" + - "\n" + - " `-i`, `--include` *types*\n" + - "\n" + - " Only include entries of type *types*.", - example: "" + - " chezmoi dump ~/.bashrc\n" + - " chezmoi dump --format=yaml", - }, - "edit": { - long: "" + - "Description:\n" + - " Edit the source state of *targets*, which must be files or symlinks. If no\n" + - " targets are given the the source directory itself is opened with `$EDITOR`.\n" + - " The `edit` command accepts additional arguments:\n" + - "\n" + - " `-a`, `--apply`\n" + - "\n" + - " Apply target immediately after editing. Ignored if there are no targets.", - example: "" + - " chezmoi edit ~/.bashrc\n" + - " chezmoi edit ~/.bashrc --apply\n" + - " chezmoi edit", - }, - "edit-config": { - long: "" + - "Description:\n" + - " Edit the configuration file.\n" + - "\n" + - " `edit-config` examples\n" + - "\n" + - " chezmoi edit-config", - }, - "execute-template": { - long: "" + - "Description:\n" + - " Execute *templates*. This is useful for testing templates or for calling\n" + - " chezmoi from other scripts. *templates* are interpreted as literal\n" + - " templates, with no whitespace added to the output between arguments. If no\n" + - " templates are specified, the template is read from stdin.\n" + - "\n" + - " `--init`, `-i`\n" + - "\n" + - " Include simulated functions only available during `chezmoi init`.\n" + - "\n" + - " `--promptBool` *pairs*\n" + - "\n" + - " Simulate the `promptBool` function with a function that returns values from\n" + - " *pairs*. *pairs* is a comma-separated list of *prompt*`=`*value* pairs. If\n" + - " `promptBool` is called with a *prompt* that does not match any of *pairs*,\n" + - " then it returns false.\n" + - "\n" + - " `--promptInt`, `-p` *pairs*\n" + - "\n" + - " Simulate the `promptInt` function with a function that returns values from\n" + - " *pairs*. *pairs* is a comma-separated list of *prompt*`=`*value* pairs. If\n" + - " `promptInt` is called with a *prompt* that does not match any of *pairs*,\n" + - " then it returns zero.\n" + - "\n" + - " `--promptString`, `-p` *pairs*\n" + - "\n" + - " Simulate the `promptString` function with a function that returns values\n" + - " from *pairs*. *pairs* is a comma-separated list of *prompt*`=`*value* pairs.\n" + - " If `promptString` is called with a *prompt* that does not match any of\n" + - " *pairs*, then it returns *prompt* unchanged.\n" + - "\n" + - " `execute-template` examples\n" + - "\n" + - " chezmoi execute-template '{{ .chezmoi.sourceDir }}'\n" + - " chezmoi execute-template '{{ .chezmoi.os }}' / '{{ .chezmoi.arch }}'\n" + - " echo '{{ .chezmoi | toJson }}' | chezmoi execute-template\n" + - " chezmoi execute-template --init --promptString [email protected] <\n" + - " ~/.local/share/chezmoi/.chezmoi.toml.tmpl", - }, - "forget": { - long: "" + - "Description:\n" + - " Remove *targets* from the source state, i.e. stop managing them.", - example: "" + - " chezmoi forget ~/.bashrc", - }, - "git": { - long: "" + - "Description:\n" + - " Run `git` *arguments* in the source directory. Note that flags in\n" + - " *arguments* must occur after `--` to prevent chezmoi from interpreting them.", - example: "" + - " chezmoi git add .\n" + - " chezmoi git add dot_gitconfig\n" + - " chezmoi git -- commit -m \"Add .gitconfig\"", - }, - "help": { - long: "" + - "Description:\n" + - " Print the help associated with *command*.", - }, - "import": { - long: "" + - "Description:\n" + - " Import the source state from an archive file in to a directory in the source\n" + - " state. This is primarily used to make subdirectories of your home directory\n" + - " exactly match the contents of a downloaded archive. You will generally\n" + - " always want to set the `--destination`, `--exact`, and `--remove-destination`\n" + - " flags.\n" + - "\n" + - " The only supported archive format is `.tar.gz`.\n" + - "\n" + - " `--destination` *directory*\n" + - "\n" + - " Set the destination (in the source state) where the archive will be\n" + - " imported.\n" + - "\n" + - " `-x`, `--exact`\n" + - "\n" + - " Set the `exact` attribute on all imported directories.\n" + - "\n" + - " `-r`, `--remove-destination`\n" + - "\n" + - " Remove destination (in the source state) before importing.\n" + - "\n" + - " `--strip-components` *n*\n" + - "\n" + - " Strip *n* leading components from paths.", - example: "" + - " curl -s -L -o oh-my-zsh-master.tar.gz https://github.com/robbyrussell/oh-my-\n" + - "zsh/archive/master.tar.gz\n" + - " chezmoi import --strip-components 1 --destination ~/.oh-my-zsh oh-my-zsh-master.tar.gz", - }, - "init": { - long: "" + - "Description:\n" + - " Setup the source directory and update the destination directory to match the\n" + - " target state. *repo* is expanded to a full git repo URL using the following\n" + - " rules:\n" + - "\n" + - " PATTERN | REPO\n" + - " -------------------+---------------------------------------\n" + - " user | https://github.com/user/dotfiles.git\n" + - " user/repo | https://github.com/user/repo.git\n" + - " site/user/repo | https://site/user/repo.git\n" + - " ~sr.ht/user | https://git.sr.ht/~user/dotfiles\n" + - " ~sr.ht/user/repo | https://git.sr.ht/~user/repo\n" + - "\n" + - " First, if the source directory is not already contain a repository, then if\n" + - " *repo* is given it is checked out into the source directory, otherwise a new\n" + - " repository is initialized in the source directory.\n" + - "\n" + - " Second, if a file called `.chezmoi.<format>.tmpl` exists, where `<format>`\n" + - " is one of the supported file formats (e.g. `json`, `toml`, or `yaml`) then a\n" + - " new configuration file is created using that file as a template.\n" + - "\n" + - " Then, if the `--apply` flag is passed, `chezmoi apply` is run.\n" + - "\n" + - " Then, if the `--purge` flag is passed, chezmoi will remove the source\n" + - " directory and its config directory.\n" + - "\n" + - " Finally, if the `--purge-binary` is passed, chezmoi will attempt to remove its\n" + - " own binary.\n" + - "\n" + - " `--apply`\n" + - "\n" + - " Run `chezmoi apply` after checking out the repo and creating the config\n" + - " file.\n" + - "\n" + - " `--depth` *depth*\n" + - "\n" + - " Clone the repo with depth *depth*.\n" + - "\n" + - " `--one-shot`\n" + - "\n" + - " `--one-shot` is the equivalent of `--apply`, `--depth=1`, `--purge`, `--purge-binary`.\n" + - " It attempts to install your dotfiles with chezmoi and then remove all traces\n" + - " of chezmoi from the system. This is useful for setting up temporary\n" + - " environments (e.g. Docker containers).\n" + - "\n" + - " `--purge`\n" + - "\n" + - " Remove the source and config directories after applying.\n" + - "\n" + - " `--purge-binary`\n" + - "\n" + - " Attempt to remove the chezmoi binary after applying.\n" + - "\n" + - " `--skip-encrypted`\n" + - "\n" + - " Skip encrypted files. This is useful for setting up machines with an inital\n" + - " set of dotfiles before private decryption keys are available.", - example: "" + - " chezmoi init user\n" + - " chezmoi init user --apply\n" + - " chezmoi init user --apply --purge\n" + - " chezmoi init user/dots\n" + - " chezmoi init gitlab.com/user", - }, - "manage": { - long: "" + - "Description:\n" + - " `manage` is an alias for `add` for symmetry with `unmanage`.", - }, - "managed": { - long: "" + - "Description:\n" + - " List all managed entries in the destination directory in alphabetical order.\n" + - "\n" + - " `-i`, `--include` *types*\n" + - "\n" + - " Only include entries of type *types*.", - example: "" + - " chezmoi managed\n" + - " chezmoi managed --include=files\n" + - " chezmoi managed --include=files,symlinks\n" + - " chezmoi managed -i d\n" + - " chezmoi managed -i d,f", - }, - "merge": { - long: "" + - "Description:\n" + - " Perform a three-way merge between the destination state, the target state,\n" + - " and the source state. The merge tool is defined by the `merge.command`\n" + - " configuration variable, and defaults to `vimdiff`. If multiple targets are\n" + - " specified the merge tool is invoked for each target. If the target state\n" + - " cannot be computed (for example if source is a template containing errors or\n" + - " an encrypted file that cannot be decrypted) a two-way merge is performed\n" + - " instead.", - example: "" + - " chezmoi merge ~/.bashrc", - }, - "purge": { - long: "" + - "Description:\n" + - " Remove chezmoi's configuration, state, and source directory, but leave the\n" + - " target state intact.\n" + - "\n" + - " `-f`, `--force`\n" + - "\n" + - " Remove without prompting.", - example: "" + - " chezmoi purge\n" + - " chezmoi purge --force", - }, - "remove": { - long: "" + - "Description:\n" + - " Remove *targets* from both the source state and the destination directory.\n" + - "\n" + - " `-f`, `--force`\n" + - "\n" + - " Remove without prompting.", - }, - "rm": { - long: "" + - "Description:\n" + - " `rm` is an alias for `remove`.", - }, - "secret": { - long: "" + - "Description:\n" + - " Run a secret manager's CLI, passing any extra arguments to the secret\n" + - " manager's CLI. This is primarily for verifying chezmoi's integration with\n" + - " your secret manager. Normally you would use template functions to retrieve\n" + - " secrets. Note that if you want to pass flags to the secret manager's CLI you\n" + - " will need to separate them with `--` to prevent chezmoi from interpreting\n" + - " them.\n" + - "\n" + - " To get a full list of available commands run:\n" + - "\n" + - " chezmoi secret help", - example: "" + - " chezmoi secret keyring set --service=service --user=user --value=password\n" + - " chezmoi secret keyring get --service=service --user=user", - }, - "source-path": { - long: "" + - "Description:\n" + - " Print the path to each target's source state. If no targets are specified\n" + - " then print the source directory.\n" + - "\n" + - " `source-path` examples\n" + - "\n" + - " chezmoi source-path\n" + - " chezmoi source-path ~/.bashrc", - }, - "state": { - long: "" + - "Description:\n" + - " Manipulate the persistent state.", - example: "" + - " chezmoi state dump\n" + - " chemzoi state reset", - }, - "status": { - long: "" + - "Description:\n" + - " Print the status of the files and scripts managed by chezmoi in a format\n" + - " similar to git status https://git-scm.com/docs/git-status.\n" + - "\n" + - " The first column of output indicates the difference between the last state\n" + - " written by chezmoi and the actual state. The second column indicates the\n" + - " difference between the actual state and the target state.\n" + - "\n" + - " `-i`, `--include` *types*\n" + - "\n" + - " Only include entries of type *types*.", - example: "" + - " chezmoi status", - }, - "unmanage": { - long: "" + - "Description:\n" + - " `unmanage` is an alias for `forget` for symmetry with `manage`.", - }, - "unmanaged": { - long: "" + - "Description:\n" + - " List all unmanaged files in the destination directory.", - example: "" + - " chezmoi unmanaged", - }, - "update": { - long: "" + - "Description:\n" + - " Pull changes from the source VCS and apply any changes.\n" + - "\n" + - " `-i`, `--include` *types*\n" + - "\n" + - " Only update entries of type *types*.", - example: "" + - " chezmoi update", - }, - "upgrade": { - long: "" + - "Description:\n" + - " Upgrade chezmoi by downloading and installing the latest released version.\n" + - " This will call the GitHub API to determine if there is a new version of\n" + - " chezmoi available, and if so, download and attempt to install it in the same\n" + - " way as chezmoi was previously installed.\n" + - "\n" + - " If chezmoi was installed with a package manager (`dpkg` or `rpm`) then\n" + - " `upgrade` will download a new package and install it, using `sudo` if it is\n" + - " installed. Otherwise, chezmoi will download the latest executable and\n" + - " replace the existing executable with the new version.\n" + - "\n" + - " If the `CHEZMOI_GITHUB_API_TOKEN` environment variable is set, then its\n" + - " value will be used to authenticate requests to the GitHub API, otherwise\n" + - " unauthenticated requests are used which are subject to stricter rate\n" + - " limiting https://developer.github.com/v3/#rate-limiting. Unauthenticated\n" + - " requests should be sufficient for most cases.", - example: "" + - " chezmoi upgrade", - }, - "verify": { - long: "" + - "Description:\n" + - " Verify that all *targets* match their target state. chezmoi exits with code\n" + - " 0 (success) if all targets match their target state, or 1 (failure)\n" + - " otherwise. If no targets are specified then all targets are checked.\n" + - "\n" + - " `-i`, `--include` *types*\n" + - "\n" + - " Only include entries of type *types*.", - example: "" + - " chezmoi verify\n" + - " chezmoi verify ~/.bashrc", - }, -} diff --git a/chezmoi2/cmd/reference.gen.go b/chezmoi2/cmd/reference.gen.go deleted file mode 100644 index 2cba5f82ab6..00000000000 --- a/chezmoi2/cmd/reference.gen.go +++ /dev/null @@ -1,1595 +0,0 @@ -// Code generated by github.com/twpayne/chezmoi/internal/cmd/generate-assets. DO NOT EDIT. -// +build !noembeddocs - -package cmd - -func init() { - assets["docs/REFERENCE.md"] = []byte("" + - "# chezmoi Reference Manual\n" + - "\n" + - "Manage your dotfiles securely across multiple machines.\n" + - "\n" + - "<!--- toc --->\n" + - "* [Concepts](#concepts)\n" + - "* [Global command line flags](#global-command-line-flags)\n" + - " * [`--color` *value*](#--color-value)\n" + - " * [`-c`, `--config` *filename*](#-c---config-filename)\n" + - " * [`--cpu-profile` *filename*](#--cpu-profile-filename)\n" + - " * [`--debug`](#--debug)\n" + - " * [`-D`, `--destination` *directory*](#-d---destination-directory)\n" + - " * [`-n`, `--dry-run`](#-n---dry-run)\n" + - " * [`--force`](#--force)\n" + - " * [`-h`, `--help`](#-h---help)\n" + - " * [`-k`, `--keep-going`](#-k---keep-going)\n" + - " * [`--no-pager`](#--no-pager)\n" + - " * [`--no-tty`](#--no-tty)\n" + - " * [`-o`, `--output` *filename*](#-o---output-filename)\n" + - " * [`-r`. `--remove`](#-r---remove)\n" + - " * [`-S`, `--source` *directory*](#-s---source-directory)\n" + - " * [`--use-builtin-git` *value*](#--use-builtin-git-value)\n" + - " * [`-v`, `--verbose`](#-v---verbose)\n" + - " * [`--version`](#--version)\n" + - "* [Common command line flags](#common-command-line-flags)\n" + - " * [`--format` *format*](#--format-format)\n" + - " * [`--include` *types*](#--include-types)\n" + - " * [`-r`, `--recursive`](#-r---recursive)\n" + - "* [Configuration file](#configuration-file)\n" + - " * [Variables](#variables)\n" + - " * [Examples](#examples)\n" + - "* [Source state attributes](#source-state-attributes)\n" + - "* [Target types](#target-types)\n" + - " * [Files](#files)\n" + - " * [Directories](#directories)\n" + - " * [Symbolic links](#symbolic-links)\n" + - " * [Scripts](#scripts)\n" + - "* [Special files and directories](#special-files-and-directories)\n" + - " * [`.chezmoi.<format>.tmpl`](#chezmoiformattmpl)\n" + - " * [`.chezmoiignore`](#chezmoiignore)\n" + - " * [`.chezmoiremove`](#chezmoiremove)\n" + - " * [`.chezmoitemplates`](#chezmoitemplates)\n" + - " * [`.chezmoiversion`](#chezmoiversion)\n" + - "* [Commands](#commands)\n" + - " * [`add` *targets*](#add-targets)\n" + - " * [`apply` [*targets*]](#apply-targets)\n" + - " * [`archive`](#archive)\n" + - " * [`cat` *targets*](#cat-targets)\n" + - " * [`cd`](#cd)\n" + - " * [`chattr` *attributes* *targets*](#chattr-attributes-targets)\n" + - " * [`completion` *shell*](#completion-shell)\n" + - " * [`data`](#data)\n" + - " * [`diff` [*targets*]](#diff-targets)\n" + - " * [`docs` [*regexp*]](#docs-regexp)\n" + - " * [`doctor`](#doctor)\n" + - " * [`dump` [*targets*]](#dump-targets)\n" + - " * [`edit` [*targets*]](#edit-targets)\n" + - " * [`edit-config`](#edit-config)\n" + - " * [`execute-template` [*templates*]](#execute-template-templates)\n" + - " * [`forget` *targets*](#forget-targets)\n" + - " * [`git` [*arguments*]](#git-arguments)\n" + - " * [`help` *command*](#help-command)\n" + - " * [`init` [*repo*]](#init-repo)\n" + - " * [`import` *filename*](#import-filename)\n" + - " * [`manage` *targets*](#manage-targets)\n" + - " * [`managed`](#managed)\n" + - " * [`merge` *targets*](#merge-targets)\n" + - " * [`purge`](#purge)\n" + - " * [`remove` *targets*](#remove-targets)\n" + - " * [`rm` *targets*](#rm-targets)\n" + - " * [`secret`](#secret)\n" + - " * [`source-path` [*targets*]](#source-path-targets)\n" + - " * [`state`](#state)\n" + - " * [`status`](#status)\n" + - " * [`unmanage` *targets*](#unmanage-targets)\n" + - " * [`unmanaged`](#unmanaged)\n" + - " * [`update`](#update)\n" + - " * [`upgrade`](#upgrade)\n" + - " * [`verify` [*targets*]](#verify-targets)\n" + - "* [Editor configuration](#editor-configuration)\n" + - "* [Umask configuration](#umask-configuration)\n" + - "* [Template execution](#template-execution)\n" + - "* [Template variables](#template-variables)\n" + - "* [Template functions](#template-functions)\n" + - " * [`bitwarden` [*args*]](#bitwarden-args)\n" + - " * [`bitwardenAttachment` *filename* *itemid*](#bitwardenattachment-filename-itemid)\n" + - " * [`bitwardenFields` [*args*]](#bitwardenfields-args)\n" + - " * [`gitHubKeys` *user*](#githubkeys-user)\n" + - " * [`gopass` *gopass-name*](#gopass-gopass-name)\n" + - " * [`include` *filename*](#include-filename)\n" + - " * [`ioreg`](#ioreg)\n" + - " * [`joinPath` *elements*](#joinpath-elements)\n" + - " * [`keepassxc` *entry*](#keepassxc-entry)\n" + - " * [`keepassxcAttribute` *entry* *attribute*](#keepassxcattribute-entry-attribute)\n" + - " * [`keyring` *service* *user*](#keyring-service-user)\n" + - " * [`lastpass` *id*](#lastpass-id)\n" + - " * [`lastpassRaw` *id*](#lastpassraw-id)\n" + - " * [`lookPath` *file*](#lookpath-file)\n" + - " * [`onepassword` *uuid* [*vault-uuid*]](#onepassword-uuid-vault-uuid)\n" + - " * [`onepasswordDocument` *uuid* [*vault-uuid*]](#onepassworddocument-uuid-vault-uuid)\n" + - " * [`onepasswordDetailsFields` *uuid* [*vault-uuid*]](#onepassworddetailsfields-uuid-vault-uuid)\n" + - " * [`pass` *pass-name*](#pass-pass-name)\n" + - " * [`promptBool` *prompt*](#promptbool-prompt)\n" + - " * [`promptInt` *prompt*](#promptint-prompt)\n" + - " * [`promptString` *prompt*](#promptstring-prompt)\n" + - " * [`secret` [*args*]](#secret-args)\n" + - " * [`secretJSON` [*args*]](#secretjson-args)\n" + - " * [`stat` *name*](#stat-name)\n" + - " * [`vault` *key*](#vault-key)\n" + - "\n" + - "## Concepts\n" + - "\n" + - "chezmoi evaluates the source state for the current machine and then updates the\n" + - "destination directory, where:\n" + - "\n" + - "* The *source state* declares the desired state of your home directory,\n" + - " including templates and machine-specific configuration.\n" + - "\n" + - "* The *source directory* is where chezmoi stores the source state, by default\n" + - " `~/.local/share/chezmoi`.\n" + - "\n" + - "* The *target state* is the source state computed for the current machine.\n" + - "\n" + - "* The *destination directory* is the directory that chezmoi manages, by default\n" + - " `~`, your home directory.\n" + - "\n" + - "* A *target* is a file, directory, or symlink in the destination directory.\n" + - "\n" + - "* The *destination state* is the current state of all the targets in the\n" + - " destination directory.\n" + - "\n" + - "* The *config file* contains machine-specific configuration, by default it is\n" + - " `~/.config/chezmoi/chezmoi.toml`.\n" + - "\n" + - "## Global command line flags\n" + - "\n" + - "Command line flags override any values set in the configuration file.\n" + - "\n" + - "### `--color` *value*\n" + - "\n" + - "Colorize diffs, *value* can be `on`, `off`, `auto`, or any boolean-like value\n" + - "recognized by `parseBool`. The default is `auto` which will colorize diffs only\n" + - "if the the environment variable `NO_COLOR` is not set and stdout is a terminal.\n" + - "\n" + - "### `-c`, `--config` *filename*\n" + - "\n" + - "Read the configuration from *filename*.\n" + - "\n" + - "### `--cpu-profile` *filename*\n" + - "\n" + - "Write a [CPU profile](https://blog.golang.org/pprof) to *filename*.\n" + - "\n" + - "### `--debug`\n" + - "\n" + - "Log information helpful for debugging.\n" + - "\n" + - "### `-D`, `--destination` *directory*\n" + - "\n" + - "Use *directory* as the destination directory.\n" + - "\n" + - "### `-n`, `--dry-run`\n" + - "\n" + - "Set dry run mode. In dry run mode, the destination directory is never modified.\n" + - "This is most useful in combination with the `-v` (verbose) flag to print changes\n" + - "that would be made without making them.\n" + - "\n" + - "### `--force`\n" + - "\n" + - "Make changes without prompting.\n" + - "\n" + - "### `-h`, `--help`\n" + - "\n" + - "Print help.\n" + - "\n" + - "### `-k`, `--keep-going`\n" + - "\n" + - "Keep going as far as possible after a encountering an error.\n" + - "\n" + - "### `--no-pager`\n" + - "\n" + - "Do not use the pager.\n" + - "\n" + - "### `--no-tty`\n" + - "\n" + - "Do not attempt to get a TTY to read input and passwords. Instead, read them from\n" + - "stdin.\n" + - "\n" + - "### `-o`, `--output` *filename*\n" + - "\n" + - "Write the output to *filename* instead of stdout.\n" + - "\n" + - "### `-r`. `--remove`\n" + - "\n" + - "Also remove targets according to `.chezmoiremove`.\n" + - "\n" + - "### `-S`, `--source` *directory*\n" + - "\n" + - "Use *directory* as the source directory.\n" + - "\n" + - "### `--use-builtin-git` *value*\n" + - "\n" + - "Use chezmoi's builtin git instead of `git.command` for the `init` and `update`\n" + - "commands. *value* can be `on`, `off`, `auto`, or any boolean-like value\n" + - "recognized by `parseBool`. The default is `auto` which will only use the builtin\n" + - "git if `git.command` cannot be found in `$PATH`.\n" + - "\n" + - "### `-v`, `--verbose`\n" + - "\n" + - "Set verbose mode. In verbose mode, chezmoi prints the changes that it is making\n" + - "as approximate shell commands, and any differences in files between the target\n" + - "state and the destination set are printed as unified diffs.\n" + - "\n" + - "### `--version`\n" + - "\n" + - "Print the version of chezmoi, the commit at which it was built, and the build\n" + - "timestamp.\n" + - "\n" + - "## Common command line flags\n" + - "\n" + - "The following flags apply to multiple commands where they are relevant.\n" + - "\n" + - "### `--format` *format*\n" + - "\n" + - "Set the output format. *format* can be `json` or `yaml`.\n" + - "\n" + - "### `--include` *types*\n" + - "\n" + - "Only operate on target state entries of type *types*. *types* is a\n" + - "comma-separated list of target states (`all`, `dirs`, `files`, `remove`,\n" + - "`scripts`, `symlinks`) and can be excluded by preceeding them with a `!`. For\n" + - "example, `--include=all,!scripts` will cause the command to apply to all target\n" + - "state entries except scripts.\n" + - "\n" + - "### `-r`, `--recursive`\n" + - "\n" + - "Recurse into subdirectories, `true` by default.\n" + - "\n" + - "## Configuration file\n" + - "\n" + - "chezmoi searches for its configuration file according to the [XDG Base Directory\n" + - "Specification](https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html)\n" + - "and supports all formats supported by\n" + - "[`github.com/spf13/viper`](https://github.com/spf13/viper), namely\n" + - "[JSON](https://www.json.org/json-en.html),\n" + - "[TOML](https://github.com/toml-lang/toml), [YAML](https://yaml.org/), macOS\n" + - "property file format, and [HCL](https://github.com/hashicorp/hcl). The basename\n" + - "of the config file is `chezmoi`, and the first config file found is used.\n" + - "\n" + - "### Variables\n" + - "\n" + - "The following configuration variables are available:\n" + - "\n" + - "| Section | Variable | Type | Default value | Description |\n" + - "| ------------- | ----------------- | -------- | ------------------------- | ------------------------------------------------------ |\n" + - "| Top level | `color` | string | `auto` | Colorize output |\n" + - "| | `data` | any | *none* | Template data |\n" + - "| | `destDir` | string | `~` | Destination directory |\n" + - "| | `encryption` | string | *none* | Encryption tool, either `age` or `gpg` |\n" + - "| | `format` | string | `json` | Format for data output, either `json` or `yaml` |\n" + - "| | `remove` | bool | `false` | Remove targets |\n" + - "| | `sourceDir` | string | `~/.local/share/chezmoi` | Source directory |\n" + - "| | `umask` | int | *from system* | Umask |\n" + - "| | `useBuiltinGit` | string | `auto` | Use builtin git if `git` command is not found in $PATH |\n" + - "| `age` | `args` | []string | *none* | Extra args to age CLI command |\n" + - "| | `command` | string | `age` | age CLI command |\n" + - "| | `identity` | string | *none* | age identity file |\n" + - "| | `identities` | []string | *none* | age identity files |\n" + - "| | `recipient` | string | *none* | age recipient |\n" + - "| | `recipients` | []string | *none* | age recipients |\n" + - "| | `recipientsFile` | []string | *none* | age recipients file |\n" + - "| | `recipientsFiles` | []string | *none* | age receipients files |\n" + - "| | `suffix` | string | `.age` | Suffix appended to age-encrypted files |\n" + - "| `bitwarden` | `command` | string | `bw` | Bitwarden CLI command |\n" + - "| `cd` | `args` | []string | *none* | Extra args to shell in `cd` command |\n" + - "| | `command` | string | *none* | Shell to run in `cd` command |\n" + - "| `diff` | `pager` | string | `$PAGER` / `less` | Pager |\n" + - "| `edit` | `args` | []string | *none* | Extra args to edit command |\n" + - "| | `command` | string | `$EDITOR` / `$VISUAL` | Edit command |\n" + - "| `secret` | `command` | string | *none* | Generic secret command |\n" + - "| `git` | `autoAdd ` | bool | `false` | Add changes to the source state after any change |\n" + - "| | `autoCommit` | bool | `false` | Commit changes to the source state after any change |\n" + - "| | `autoPush` | bool | `false` | Push changes to the source state after any change |\n" + - "| | `command` | string | `git` | Source version control system |\n" + - "| `gopass` | `command` | string | `gopass` | gopass CLI command |\n" + - "| `gpg` | `args` | []string | *none* | Extra args to GPG CLI command |\n" + - "| | `command` | string | `gpg` | GPG CLI command |\n" + - "| | `recipient` | string | *none* | GPG recipient |\n" + - "| | `suffix` | string | `.asc` | Suffix appended to GPG-encrypted files |\n" + - "| | `symmetric` | bool | `false` | Use symmetric GPG encryption |\n" + - "| `keepassxc` | `args` | []string | *none* | Extra args to KeePassXC CLI command |\n" + - "| | `command` | string | `keepassxc-cli` | KeePassXC CLI command |\n" + - "| | `database` | string | *none* | KeePassXC database |\n" + - "| `lastpass` | `command` | string | `lpass` | Lastpass CLI command |\n" + - "| `merge` | `args` | []string | *none* | Extra args to 3-way merge command |\n" + - "| | `command` | string | `vimdiff` | 3-way merge command |\n" + - "| `onepassword` | `cache` | bool | `true` | Enable optional caching provided by `op` |\n" + - "| | `command` | string | `op` | 1Password CLI command |\n" + - "| `pass` | `command` | string | `pass` | Pass CLI command |\n" + - "| `template` | `options` | []string | `[\"missingkey=error\"]` | Template options |\n" + - "| `vault` | `command` | string | `vault` | Vault CLI command |\n" + - "\n" + - "### Examples\n" + - "\n" + - "#### JSON\n" + - "\n" + - "```json\n" + - "{\n" + - " \"sourceDir\": \"/home/user/.dotfiles\",\n" + - " \"git\": {\n" + - " \"autoPush\": true\n" + - " }\n" + - "}\n" + - "```\n" + - "\n" + - "#### TOML\n" + - "\n" + - "```toml\n" + - "sourceDir = \"/home/user/.dotfiles\"\n" + - "[git]\n" + - " autoPush = true\n" + - "```\n" + - "\n" + - "#### YAML\n" + - "\n" + - "```yaml\n" + - "sourceDir: /home/user/.dotfiles\n" + - "git:\n" + - " autoPush: true\n" + - "```\n" + - "\n" + - "## Source state attributes\n" + - "\n" + - "chezmoi stores the source state of files, symbolic links, and directories in\n" + - "regular files and directories in the source directory (`~/.local/share/chezmoi`\n" + - "by default). This location can be overridden with the `-S` flag or by giving a\n" + - "value for `sourceDir` in `~/.config/chezmoi/chezmoi.toml`. Some state is\n" + - "encoded in the source names. chezmoi ignores all files and directories in the\n" + - "source directory that begin with a `.`. The following prefixes and suffixes are\n" + - "special, and are collectively referred to as \"attributes\":\n" + - "\n" + - "| Prefix | Effect |\n" + - "| ------------ | ------------------------------------------------------------------------------ |\n" + - "| `after_` | Run script after updating the destination. |\n" + - "| `before_` | Run script before updating the desintation. |\n" + - "| `create_` | Ensure that the file exists, and create it with contents if it does not. |\n" + - "| `dot_` | Rename to use a leading dot, e.g. `dot_foo` becomes `.foo`. |\n" + - "| `empty_` | Ensure the file exists, even if is empty. By default, empty files are removed. |\n" + - "| `encrypted_` | Encrypt the file in the source state. |\n" + - "| `exact_` | Remove anything not managed by chezmoi. |\n" + - "| `executable_`| Add executable permissions to the target file. |\n" + - "| `modify_` | Treat the contents as a script that modifies an existing file. |\n" + - "| `once_` | Run script once. |\n" + - "| `private_` | Remove all group and world permissions from the target file or directory. |\n" + - "| `run_` | Treat the contents as a script to run. |\n" + - "| `symlink_` | Create a symlink instead of a regular file. |\n" + - "\n" + - "| Suffix | Effect |\n" + - "| ------- | ---------------------------------------------------- |\n" + - "| `.tmpl` | Treat the contents of the source file as a template. |\n" + - "\n" + - "The order of prefixes is important, the order is `run_`, `create_`, `modify_`,\n" + - "`before_`, `after_`, `exact_`, `private_`, `empty_`, `executable_`, `symlink_`,\n" + - "`once_`, `dot_`.\n" + - "\n" + - "Different target types allow different prefixes and suffixes:\n" + - "\n" + - "| Target type | Allowed prefixes | Allowed suffixes |\n" + - "| ------------- | --------------------------------------------------------------------- | ---------------- |\n" + - "| Directory | `exact_`, `private_`, `dot_` | *none* |\n" + - "| Regular file | `encrypted_`, `private_`, `executable_`, `dot_` | `.tmpl` |\n" + - "| Create file | `create_`, `encrypted_`, `private_`, `executable_`, `dot_` | `.tmpl` |\n" + - "| Modify file | `modify_`, `encrypted_`, `private_`, `executable_`, `dot_` | `.tmpl` |\n" + - "| Script | `run_`, `once_`, `before_` or `after_` | `.tmpl` |\n" + - "| Symbolic link | `symlink_`, `dot_`, | `.tmpl` |\n" + - "\n" + - "## Target types\n" + - "\n" + - "chezmoi will create, update, and delete files, directories, and symbolic links\n" + - "in the destination directory, and run scripts. chezmoi deterministically\n" + - "performs actions in ASCII order of their target name. For example, given a file\n" + - "`dot_a`, a script `run_z`, and a directory `exact_dot_c`, chezmoi will first\n" + - "create `.a`, create `.c`, and then execute `run_z`.\n" + - "\n" + - "### Files\n" + - "\n" + - "Files are represented by regular files in the source state. The `encrypted_`\n" + - "attribute determines whether the file in the source state is encrypted. The\n" + - "`executable_` attribute will set the executable bits when the file is written to\n" + - "the target state, and the `private_` attribute will clear all group and world\n" + - "permissions. Files with the `.tmpl` suffix will be interpreted as templates.\n" + - "\n" + - "#### Create file\n" + - "\n" + - "Files with the `create_` prefix will be created in the target state with the\n" + - "contents of the file in the source state if they do not already exist. If the\n" + - "file in the destination state already exists then its contents will be left\n" + - "unchanged.\n" + - "\n" + - "#### Modify file\n" + - "\n" + - "Files with the `modify_` prefix are treated as scripts that modify an existing\n" + - "file. The contents of the existing file (which maybe empty if the existing file\n" + - "does not exist or is empty) are passed to the script's standard input, and the\n" + - "new contents are read from the scripts standard output.\n" + - "\n" + - "### Directories\n" + - "\n" + - "Directories are represented by regular directories in the source state. The\n" + - "`exact_` attribute causes chezmoi to remove any entries in the target state that\n" + - "are not explicitly specified in the source state, and the `private_` attribute\n" + - "causes chezmoi to clear all group and world permssions.\n" + - "\n" + - "### Symbolic links\n" + - "\n" + - "Symbolic links are represented by regular files in the source state with the\n" + - "prefix `symlink_`. The contents of the file will have a trailing newline\n" + - "stripped, and the result be interpreted as the target of the symbolic link.\n" + - "Symbolic links with the `.tmpl` suffix in the source state are interpreted as\n" + - "templates.\n" + - "\n" + - "### Scripts\n" + - "\n" + - "Scripts are represented as regular files in the source state with prefix `run_`.\n" + - "The file's contents (after being interpreted as a template if it has a `.tmpl`\n" + - "suffix) are executed. Scripts are executed on every `chezmoi apply`, unless they\n" + - "have the `once_` attribute, in which case they are only executed when they are\n" + - "first found or when their contents have changed.\n" + - "\n" + - "Scripts with the `before_` attribute are executed before any files, directories,\n" + - "or symlinks are updated. Scripts with the `after_` attribute are executed after\n" + - "all files, directories, and symlinks have been updated. Scripts without an\n" + - "`before_` or `after_` attribute are executed in ASCII order of their target\n" + - "names with respect to files, directories, and symlinks.\n" + - "\n" + - "## Special files and directories\n" + - "\n" + - "All files and directories in the source state whose name begins with `.` are\n" + - "ignored by default, unless they are one of the special files listed here.\n" + - "\n" + - "### `.chezmoi.<format>.tmpl`\n" + - "\n" + - "If a file called `.chezmoi.<format>.tmpl` exists then `chezmoi init` will use it\n" + - "to create an initial config file. *format* must be one of the the supported\n" + - "config file formats.\n" + - "\n" + - "#### `.chezmoi.<format>.tmpl` examples\n" + - "\n" + - " {{ $email := promptString \"email\" -}}\n" + - " data:\n" + - " email: \"{{ $email }}\"\n" + - "\n" + - "### `.chezmoiignore`\n" + - "\n" + - "If a file called `.chezmoiignore` exists in the source state then it is\n" + - "interpreted as a set of patterns to ignore. Patterns are matched using\n" + - "[`doublestar.PathMatch`](https://pkg.go.dev/github.com/bmatcuk/doublestar?tab=doc#PathMatch)\n" + - "and match against the target path, not the source path.\n" + - "\n" + - "Patterns can be excluded by prefixing them with a `!` character. All excludes\n" + - "take priority over all includes.\n" + - "\n" + - "Comments are introduced with the `#` character and run until the end of the\n" + - "line.\n" + - "\n" + - "`.chezmoiignore` is interpreted as a template. This allows different files to be\n" + - "ignored on different machines.\n" + - "\n" + - "`.chezmoiignore` files in subdirectories apply only to that subdirectory.\n" + - "\n" + - "#### `.chezmoiignore` examples\n" + - "\n" + - " README.md\n" + - "\n" + - " *.txt # ignore *.txt in the target directory\n" + - " */*.txt # ignore *.txt in subdirectories of the target directory\n" + - " backups/** # ignore backups folder in chezmoi directory and all its contents\n" + - " # but not in subdirectories of subdirectories;\n" + - " # so a/b/c.txt would *not* be ignored\n" + - " backups/** # ignore all contents of backups folder in chezmoi directory\n" + - " # but not backups folder itself\n" + - "\n" + - " {{- if ne .email \"[email protected]\" }}\n" + - " # Ignore .company-directory unless configured with a company email\n" + - " .company-directory # note that the pattern is not dot_company-directory\n" + - " {{- end }}\n" + - "\n" + - " {{- if ne .email \"[email protected] }}\n" + - " .personal-file\n" + - " {{- end }}\n" + - "\n" + - "### `.chezmoiremove`\n" + - "\n" + - "If a file called `.chezmoiremove` exists in the source state then it is\n" + - "interpreted as a list of targets to remove. `.chezmoiremove` is interpreted as a\n" + - "template.\n" + - "\n" + - "### `.chezmoitemplates`\n" + - "\n" + - "If a directory called `.chezmoitemplates` exists, then all files in this\n" + - "directory are parsed as templates are available as templates with a name equal\n" + - "to the relative path of the file.\n" + - "\n" + - "#### `.chezmoitemplates` examples\n" + - "\n" + - "Given:\n" + - "\n" + - " .chezmoitemplates/foo\n" + - " {{ if true }}bar{{ end }}\n" + - "\n" + - " dot_config.tmpl\n" + - " {{ template \"foo\" }}\n" + - "\n" + - "The target state of `.config` will be `bar`.\n" + - "\n" + - "### `.chezmoiversion`\n" + - "\n" + - "If a file called `.chezmoiversion` exists, then its contents are interpreted as\n" + - "a semantic version defining the minimum version of chezmoi required to interpret\n" + - "the source state correctly. chezmoi will refuse to interpret the source state if\n" + - "the current version is too old.\n" + - "\n" + - "#### `.chezmoiversion` examples\n" + - "\n" + - " 1.5.0\n" + - "\n" + - "## Commands\n" + - "\n" + - "### `add` *targets*\n" + - "\n" + - "Add *targets* to the source state. If any target is already in the source state,\n" + - "then its source state is replaced with its current state in the destination\n" + - "directory. The `add` command accepts additional flags:\n" + - "\n" + - "#### `--autotemplate`\n" + - "\n" + - "Automatically generate a template by replacing strings with variable names from\n" + - "the `data` section of the config file. Longer substitutions occur before shorter\n" + - "ones. This implies the `--template` option.\n" + - "\n" + - "#### `-e`, `--empty`\n" + - "\n" + - "Set the `empty` attribute on added files.\n" + - "\n" + - "#### `-f`, `--force`\n" + - "\n" + - "Add *targets*, even if doing so would cause a source template to be overwritten.\n" + - "\n" + - "#### `--follow`\n" + - "\n" + - "If the last part of a target is a symlink, add the target of the symlink instead\n" + - "of the symlink itself.\n" + - "\n" + - "#### `-x`, `--exact`\n" + - "\n" + - "Set the `exact` attribute on added directories.\n" + - "\n" + - "#### `-i`, `--include` *types*\n" + - "\n" + - "Only add entries of type *types*.\n" + - "\n" + - "#### `-p`, `--prompt`\n" + - "\n" + - "Interactively prompt before adding each file.\n" + - "\n" + - "#### `-r`, `--recursive`\n" + - "\n" + - "Recursively add all files, directories, and symlinks.\n" + - "\n" + - "#### `-T`, `--template`\n" + - "\n" + - "Set the `template` attribute on added files and symlinks.\n" + - "\n" + - "#### `add` examples\n" + - "\n" + - " chezmoi add ~/.bashrc\n" + - " chezmoi add ~/.gitconfig --template\n" + - " chezmoi add ~/.vim --recursive\n" + - " chezmoi add ~/.oh-my-zsh --exact --recursive\n" + - "\n" + - "### `apply` [*targets*]\n" + - "\n" + - "Ensure that *targets* are in the target state, updating them if necessary. If no\n" + - "targets are specified, the state of all targets are ensured. If a target has\n" + - "been modified since chezmoi last wrote it then the user will be prompted if they\n" + - "want to overwrite the file.\n" + - "\n" + - "#### `-i`, `--include` *types*\n" + - "\n" + - "Only add entries of type *types*.\n" + - "\n" + - "#### `--source-path`\n" + - "\n" + - "Specify targets by source path, rather than target path. This is useful for\n" + - "applying changes after editing.\n" + - "\n" + - "#### `apply` examples\n" + - "\n" + - " chezmoi apply\n" + - " chezmoi apply --dry-run --verbose\n" + - " chezmoi apply ~/.bashrc\n" + - "\n" + - "In `~/.vimrc`:\n" + - "\n" + - " autocmd BufWritePost ~/.local/share/chezmoi/* ! chezmoi apply --source-path %\n" + - "\n" + - "### `archive`\n" + - "\n" + - "Generate a tar archive of the target state. This can be piped into `tar` to\n" + - "inspect the target state.\n" + - "\n" + - "#### `--format` *format*\n" + - "\n" + - "Write the archive in *format*. *format* can be either `tar` (the default) or `zip`.\n" + - "\n" + - "#### `-i`, `--include` *types*\n" + - "\n" + - "Only include entries of type *types*.\n" + - "\n" + - "#### `-z`, `--gzip`\n" + - "\n" + - "Compress the output with gzip.\n" + - "\n" + - "#### `archive` examples\n" + - "\n" + - " chezmoi archive | tar tvf -\n" + - " chezmoi archive --output=dotfiles.tar\n" + - " chezmoi archive --format=zip --output=dotfiles.zip\n" + - "\n" + - "### `cat` *targets*\n" + - "\n" + - "Write the target state of *targets* to stdout. *targets* must be files or\n" + - "symlinks. For files, the target file contents are written. For symlinks, the\n" + - "target target is written.\n" + - "\n" + - "#### `cat` examples\n" + - "\n" + - " chezmoi cat ~/.bashrc\n" + - "\n" + - "### `cd`\n" + - "\n" + - "Launch a shell in the source directory. chezmoi will launch the command set by\n" + - "the `cd.command` configuration variable with any extra arguments specified by\n" + - "`cd.args`. If this is not set, chezmoi will attempt to detect your shell and\n" + - "will finally fall back to an OS-specific default.\n" + - "\n" + - "#### `cd` examples\n" + - "\n" + - " chezmoi cd\n" + - "\n" + - "### `chattr` *attributes* *targets*\n" + - "\n" + - "Change the attributes of *targets*. *attributes* specifies which attributes to\n" + - "modify. Add attributes by specifying them or their abbreviations directly,\n" + - "optionally prefixed with a plus sign (`+`). Remove attributes by prefixing them\n" + - "or their attributes with the string `no` or a minus sign (`-`). The available\n" + - "attributes and their abbreviations are:\n" + - "\n" + - "| Attribute | Abbreviation |\n" + - "| ------------ | ------------ |\n" + - "| `empty` | `e` |\n" + - "| `encrypted` | *none* |\n" + - "| `exact` | *none* |\n" + - "| `executable` | `x` |\n" + - "| `private` | `p` |\n" + - "| `template` | `t` |\n" + - "\n" + - "Multiple attributes modifications may be specified by separating them with a\n" + - "comma (`,`).\n" + - "\n" + - "#### `chattr` examples\n" + - "\n" + - " chezmoi chattr template ~/.bashrc\n" + - " chezmoi chattr noempty ~/.profile\n" + - " chezmoi chattr private,template ~/.netrc\n" + - "\n" + - "### `completion` *shell*\n" + - "\n" + - "Generate shell completion code for the specified shell (`bash`, `fish`,\n" + - "`powershell`, or `zsh`).\n" + - "\n" + - "#### `completion` examples\n" + - "\n" + - " chezmoi completion bash\n" + - " chezmoi completion fish --output=~/.config/fish/completions/chezmoi.fish\n" + - "\n" + - "### `data`\n" + - "\n" + - "Write the computed template data to stdout.\n" + - "\n" + - "#### `data` examples\n" + - "\n" + - " chezmoi data\n" + - " chezmoi data --format=yaml\n" + - "\n" + - "### `diff` [*targets*]\n" + - "\n" + - "Print the difference between the target state and the destination state for\n" + - "*targets*. If no targets are specified, print the differences for all targets.\n" + - "\n" + - "If a `diff.pager` command is set in the configuration file then the output will\n" + - "be piped into it.\n" + - "\n" + - "#### `diff` examples\n" + - "\n" + - " chezmoi diff\n" + - " chezmoi diff ~/.bashrc\n" + - "\n" + - "### `docs` [*regexp*]\n" + - "\n" + - "Print the documentation page matching the regular expression *regexp*. Matching\n" + - "is case insensitive. If no pattern is given, print `REFERENCE.md`.\n" + - "\n" + - "#### `docs` examples\n" + - "\n" + - " chezmoi docs\n" + - " chezmoi docs faq\n" + - " chezmoi docs howto\n" + - "\n" + - "### `doctor`\n" + - "\n" + - "Check for potential problems.\n" + - "\n" + - "#### `doctor` examples\n" + - "\n" + - " chezmoi doctor\n" + - "\n" + - "### `dump` [*targets*]\n" + - "\n" + - "Dump the target state. If no targets are specified, then the entire target\n" + - "state.\n" + - "\n" + - "#### `-i`, `--include` *types*\n" + - "\n" + - "Only include entries of type *types*.\n" + - "\n" + - "#### `dump` examples\n" + - "\n" + - " chezmoi dump ~/.bashrc\n" + - " chezmoi dump --format=yaml\n" + - "\n" + - "### `edit` [*targets*]\n" + - "\n" + - "Edit the source state of *targets*, which must be files or symlinks. If no\n" + - "targets are given the the source directory itself is opened with `$EDITOR`. The\n" + - "`edit` command accepts additional arguments:\n" + - "\n" + - "#### `-a`, `--apply`\n" + - "\n" + - "Apply target immediately after editing. Ignored if there are no targets.\n" + - "\n" + - "#### `edit` examples\n" + - "\n" + - " chezmoi edit ~/.bashrc\n" + - " chezmoi edit ~/.bashrc --apply\n" + - " chezmoi edit\n" + - "\n" + - "### `edit-config`\n" + - "\n" + - "Edit the configuration file.\n" + - "\n" + - "#### `edit-config` examples\n" + - "\n" + - " chezmoi edit-config\n" + - "\n" + - "### `execute-template` [*templates*]\n" + - "\n" + - "Execute *templates*. This is useful for testing templates or for calling chezmoi\n" + - "from other scripts. *templates* are interpreted as literal templates, with no\n" + - "whitespace added to the output between arguments. If no templates are specified,\n" + - "the template is read from stdin.\n" + - "\n" + - "#### `--init`, `-i`\n" + - "\n" + - "Include simulated functions only available during `chezmoi init`.\n" + - "\n" + - "#### `--promptBool` *pairs*\n" + - "\n" + - "Simulate the `promptBool` function with a function that returns values from\n" + - "*pairs*. *pairs* is a comma-separated list of *prompt*`=`*value* pairs. If\n" + - "`promptBool` is called with a *prompt* that does not match any of *pairs*, then\n" + - "it returns false.\n" + - "\n" + - "#### `--promptInt`, `-p` *pairs*\n" + - "\n" + - "Simulate the `promptInt` function with a function that returns values from\n" + - "*pairs*. *pairs* is a comma-separated list of *prompt*`=`*value* pairs. If\n" + - "`promptInt` is called with a *prompt* that does not match any of *pairs*, then\n" + - "it returns zero.\n" + - "\n" + - "#### `--promptString`, `-p` *pairs*\n" + - "\n" + - "Simulate the `promptString` function with a function that returns values from\n" + - "*pairs*. *pairs* is a comma-separated list of *prompt*`=`*value* pairs. If\n" + - "`promptString` is called with a *prompt* that does not match any of *pairs*,\n" + - "then it returns *prompt* unchanged.\n" + - "\n" + - "#### `execute-template` examples\n" + - "\n" + - " chezmoi execute-template '{{ .chezmoi.sourceDir }}'\n" + - " chezmoi execute-template '{{ .chezmoi.os }}' / '{{ .chezmoi.arch }}'\n" + - " echo '{{ .chezmoi | toJson }}' | chezmoi execute-template\n" + - " chezmoi execute-template --init --promptString [email protected] < ~/.local/share/chezmoi/.chezmoi.toml.tmpl\n" + - "\n" + - "### `forget` *targets*\n" + - "\n" + - "Remove *targets* from the source state, i.e. stop managing them.\n" + - "\n" + - "#### `forget` examples\n" + - "\n" + - " chezmoi forget ~/.bashrc\n" + - "\n" + - "### `git` [*arguments*]\n" + - "\n" + - "Run `git` *arguments* in the source directory. Note that flags in *arguments*\n" + - "must occur after `--` to prevent chezmoi from interpreting them.\n" + - "\n" + - "#### `git` examples\n" + - "\n" + - " chezmoi git add .\n" + - " chezmoi git add dot_gitconfig\n" + - " chezmoi git -- commit -m \"Add .gitconfig\"\n" + - "\n" + - "### `help` *command*\n" + - "\n" + - "Print the help associated with *command*.\n" + - "\n" + - "### `init` [*repo*]\n" + - "\n" + - "Setup the source directory and update the destination directory to match the\n" + - "target state. *repo* is expanded to a full git repo URL using the following\n" + - "rules:\n" + - "\n" + - "| Pattern | Repo |\n" + - "| ------------------ | -------------------------------------- |\n" + - "| `user` | `https://github.com/user/dotfiles.git` |\n" + - "| `user/repo` | `https://github.com/user/repo.git` |\n" + - "| `site/user/repo` | `https://site/user/repo.git` |\n" + - "| `~sr.ht/user` | `https://git.sr.ht/~user/dotfiles` |\n" + - "| `~sr.ht/user/repo` | `https://git.sr.ht/~user/repo` |\n" + - "\n" + - "First, if the source directory is not already contain a repository, then if\n" + - "*repo* is given it is checked out into the source directory, otherwise a new\n" + - "repository is initialized in the source directory.\n" + - "\n" + - "Second, if a file called `.chezmoi.<format>.tmpl` exists, where `<format>` is\n" + - "one of the supported file formats (e.g. `json`, `toml`, or `yaml`) then a new\n" + - "configuration file is created using that file as a template.\n" + - "\n" + - "Then, if the `--apply` flag is passed, `chezmoi apply` is run.\n" + - "\n" + - "Then, if the `--purge` flag is passed, chezmoi will remove the source directory\n" + - "and its config directory.\n" + - "\n" + - "Finally, if the `--purge-binary` is passed, chezmoi will attempt to remove its\n" + - "own binary.\n" + - "\n" + - "#### `--apply`\n" + - "\n" + - "Run `chezmoi apply` after checking out the repo and creating the config file.\n" + - "\n" + - "#### `--depth` *depth*\n" + - "\n" + - "Clone the repo with depth *depth*.\n" + - "\n" + - "#### `--one-shot`\n" + - "\n" + - "`--one-shot` is the equivalent of `--apply`, `--depth=1`, `--purge`,\n" + - "`--purge-binary`. It attempts to install your dotfiles with chezmoi and then\n" + - "remove all traces of chezmoi from the system. This is useful for setting up\n" + - "temporary environments (e.g. Docker containers).\n" + - "\n" + - "#### `--purge`\n" + - "\n" + - "Remove the source and config directories after applying.\n" + - "\n" + - "#### `--purge-binary`\n" + - "\n" + - "Attempt to remove the chezmoi binary after applying.\n" + - "\n" + - "#### `--skip-encrypted`\n" + - "\n" + - "Skip encrypted files. This is useful for setting up machines with an inital set\n" + - "of dotfiles before private decryption keys are available.\n" + - "\n" + - "#### `init` examples\n" + - "\n" + - " chezmoi init user\n" + - " chezmoi init user --apply\n" + - " chezmoi init user --apply --purge\n" + - " chezmoi init user/dots\n" + - " chezmoi init gitlab.com/user\n" + - "\n" + - "### `import` *filename*\n" + - "\n" + - "Import the source state from an archive file in to a directory in the source\n" + - "state. This is primarily used to make subdirectories of your home directory\n" + - "exactly match the contents of a downloaded archive. You will generally always\n" + - "want to set the `--destination`, `--exact`, and `--remove-destination` flags.\n" + - "\n" + - "The only supported archive format is `.tar.gz`.\n" + - "\n" + - "#### `--destination` *directory*\n" + - "\n" + - "Set the destination (in the source state) where the archive will be imported.\n" + - "\n" + - "#### `-x`, `--exact`\n" + - "\n" + - "Set the `exact` attribute on all imported directories.\n" + - "\n" + - "#### `-r`, `--remove-destination`\n" + - "\n" + - "Remove destination (in the source state) before importing.\n" + - "\n" + - "#### `--strip-components` *n*\n" + - "\n" + - "Strip *n* leading components from paths.\n" + - "\n" + - "#### `import` examples\n" + - "\n" + - " curl -s -L -o oh-my-zsh-master.tar.gz https://github.com/robbyrussell/oh-my-zsh/archive/master.tar.gz\n" + - " chezmoi import --strip-components 1 --destination ~/.oh-my-zsh oh-my-zsh-master.tar.gz\n" + - "\n" + - "### `manage` *targets*\n" + - "\n" + - "`manage` is an alias for `add` for symmetry with `unmanage`.\n" + - "\n" + - "### `managed`\n" + - "\n" + - "List all managed entries in the destination directory in alphabetical order.\n" + - "\n" + - "#### `-i`, `--include` *types*\n" + - "\n" + - "Only include entries of type *types*.\n" + - "\n" + - "#### `managed` examples\n" + - "\n" + - " chezmoi managed\n" + - " chezmoi managed --include=files\n" + - " chezmoi managed --include=files,symlinks\n" + - " chezmoi managed -i d\n" + - " chezmoi managed -i d,f\n" + - "\n" + - "### `merge` *targets*\n" + - "\n" + - "Perform a three-way merge between the destination state, the target state, and\n" + - "the source state. The merge tool is defined by the `merge.command` configuration\n" + - "variable, and defaults to `vimdiff`. If multiple targets are specified the merge\n" + - "tool is invoked for each target. If the target state cannot be computed (for\n" + - "example if source is a template containing errors or an encrypted file that\n" + - "cannot be decrypted) a two-way merge is performed instead.\n" + - "\n" + - "#### `merge` examples\n" + - "\n" + - " chezmoi merge ~/.bashrc\n" + - "\n" + - "### `purge`\n" + - "\n" + - "Remove chezmoi's configuration, state, and source directory, but leave the\n" + - "target state intact.\n" + - "\n" + - "#### `-f`, `--force`\n" + - "\n" + - "Remove without prompting.\n" + - "\n" + - "#### `purge` examples\n" + - "\n" + - " chezmoi purge\n" + - " chezmoi purge --force\n" + - "\n" + - "### `remove` *targets*\n" + - "\n" + - "Remove *targets* from both the source state and the destination directory.\n" + - "\n" + - "#### `-f`, `--force`\n" + - "\n" + - "Remove without prompting.\n" + - "\n" + - "### `rm` *targets*\n" + - "\n" + - "`rm` is an alias for `remove`.\n" + - "\n" + - "### `secret`\n" + - "\n" + - "Run a secret manager's CLI, passing any extra arguments to the secret manager's\n" + - "CLI. This is primarily for verifying chezmoi's integration with your secret\n" + - "manager. Normally you would use template functions to retrieve secrets. Note\n" + - "that if you want to pass flags to the secret manager's CLI you will need to\n" + - "separate them with `--` to prevent chezmoi from interpreting them.\n" + - "\n" + - "To get a full list of available commands run:\n" + - "\n" + - " chezmoi secret help\n" + - "\n" + - "#### `secret` examples\n" + - "\n" + - " chezmoi secret keyring set --service=service --user=user --value=password\n" + - " chezmoi secret keyring get --service=service --user=user\n" + - "\n" + - "### `source-path` [*targets*]\n" + - "\n" + - "Print the path to each target's source state. If no targets are specified then\n" + - "print the source directory.\n" + - "\n" + - "#### `source-path` examples\n" + - "\n" + - " chezmoi source-path\n" + - " chezmoi source-path ~/.bashrc\n" + - "\n" + - "### `state`\n" + - "\n" + - "Manipulate the persistent state.\n" + - "\n" + - "#### `state` examples\n" + - "\n" + - " chezmoi state dump\n" + - " chemzoi state reset\n" + - "\n" + - "### `status`\n" + - "\n" + - "Print the status of the files and scripts managed by chezmoi in a format similar\n" + - "to [`git status`](https://git-scm.com/docs/git-status).\n" + - "\n" + - "The first column of output indicates the difference between the last state\n" + - "written by chezmoi and the actual state. The second column indicates the\n" + - "difference between the actual state and the target state.\n" + - "\n" + - "#### `-i`, `--include` *types*\n" + - "\n" + - "Only include entries of type *types*.\n" + - "\n" + - "#### `status` examples\n" + - "\n" + - " chezmoi status\n" + - "\n" + - "### `unmanage` *targets*\n" + - "\n" + - "`unmanage` is an alias for `forget` for symmetry with `manage`.\n" + - "\n" + - "### `unmanaged`\n" + - "\n" + - "List all unmanaged files in the destination directory.\n" + - "\n" + - "#### `unmanaged` examples\n" + - "\n" + - " chezmoi unmanaged\n" + - "\n" + - "### `update`\n" + - "\n" + - "Pull changes from the source VCS and apply any changes.\n" + - "\n" + - "#### `-i`, `--include` *types*\n" + - "\n" + - "Only update entries of type *types*.\n" + - "\n" + - "#### `update` examples\n" + - "\n" + - " chezmoi update\n" + - "\n" + - "### `upgrade`\n" + - "\n" + - "Upgrade chezmoi by downloading and installing the latest released version. This\n" + - "will call the GitHub API to determine if there is a new version of chezmoi\n" + - "available, and if so, download and attempt to install it in the same way as\n" + - "chezmoi was previously installed.\n" + - "\n" + - "If chezmoi was installed with a package manager (`dpkg` or `rpm`) then `upgrade`\n" + - "will download a new package and install it, using `sudo` if it is installed.\n" + - "Otherwise, chezmoi will download the latest executable and replace the existing\n" + - "executable with the new version.\n" + - "\n" + - "If the `CHEZMOI_GITHUB_API_TOKEN` environment variable is set, then its value\n" + - "will be used to authenticate requests to the GitHub API, otherwise\n" + - "unauthenticated requests are used which are subject to stricter [rate\n" + - "limiting](https://developer.github.com/v3/#rate-limiting). Unauthenticated\n" + - "requests should be sufficient for most cases.\n" + - "\n" + - "#### `upgrade` examples\n" + - "\n" + - " chezmoi upgrade\n" + - "\n" + - "### `verify` [*targets*]\n" + - "\n" + - "Verify that all *targets* match their target state. chezmoi exits with code 0\n" + - "(success) if all targets match their target state, or 1 (failure) otherwise. If\n" + - "no targets are specified then all targets are checked.\n" + - "\n" + - "#### `-i`, `--include` *types*\n" + - "\n" + - "Only include entries of type *types*.\n" + - "\n" + - "#### `verify` examples\n" + - "\n" + - " chezmoi verify\n" + - " chezmoi verify ~/.bashrc\n" + - "\n" + - "## Editor configuration\n" + - "\n" + - "The `edit` and `edit-config` commands use the editor specified by the `VISUAL`\n" + - "environment variable, the `EDITOR` environment variable, or `vi`, whichever is\n" + - "specified first.\n" + - "\n" + - "## Umask configuration\n" + - "\n" + - "By default, chezmoi uses your current umask as set by your operating system and\n" + - "shell. chezmoi only stores crude permissions in its source state, namely in the\n" + - "`executable` and `private` attributes, corresponding to the umasks of `0o111`\n" + - "and `0o077` respectively.\n" + - "\n" + - "For machine-specific control of umask, set the `umask` configuration variable in\n" + - "chezmoi's configuration file, for example:\n" + - "\n" + - " umask = 0o22\n" + - "\n" + - "## Template execution\n" + - "\n" + - "chezmoi executes templates using\n" + - "[`text/template`](https://pkg.go.dev/text/template). The result is treated\n" + - "differently depending on whether the target is a file or a symlink.\n" + - "\n" + - "If target is a file, then:\n" + - "\n" + - "* If the result is an empty string, then the file is removed.\n" + - "* Otherwise, the target file contents are result.\n" + - "\n" + - "If the target is a symlink, then:\n" + - "\n" + - "* Leading and trailing whitespace are stripped from the result.\n" + - "* If the result is an empty string, then the symlink is removed.\n" + - "* Otherwise, the target symlink target is the result.\n" + - "\n" + - "chezmoi executes templates using `text/template`'s `missingkey=error` option,\n" + - "which means that misspelled or missing keys will raise an error. This can be\n" + - "overridden by setting a list of options in the configuration file, for example:\n" + - "\n" + - " [template]\n" + - " options = [\"missingkey=zero\"]\n" + - "\n" + - "For a full list of options, see\n" + - "[`Template.Option`](https://pkg.go.dev/text/template?tab=doc#Template.Option).\n" + - "\n" + - "## Template variables\n" + - "\n" + - "chezmoi provides the following automatically-populated variables:\n" + - "\n" + - "| Variable | Value |\n" + - "| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------- |\n" + - "| `.chezmoi.arch` | Architecture, e.g. `amd64`, `arm`, etc. as returned by [runtime.GOARCH](https://pkg.go.dev/runtime?tab=doc#pkg-constants). |\n" + - "| `.chezmoi.fqdnHostname` | The fully-qualified domain name hostname of the machine chezmoi is running on. |\n" + - "| `.chezmoi.group` | The group of the user running chezmoi. |\n" + - "| `.chezmoi.homeDir` | The home directory of the user running chezmoi. |\n" + - "| `.chezmoi.hostname` | The hostname of the machine chezmoi is running on, up to the first `.`. |\n" + - "| `.chezmoi.kernel` | Contains information from `/proc/sys/kernel`. Linux only, useful for detecting specific kernels (i.e. Microsoft's WSL kernel). |\n" + - "| `.chezmoi.os` | Operating system, e.g. `darwin`, `linux`, etc. as returned by [runtime.GOOS](https://pkg.go.dev/runtime?tab=doc#pkg-constants). |\n" + - "| `.chezmoi.osRelease` | The information from `/etc/os-release`, Linux only, run `chezmoi data` to see its output. |\n" + - "| `.chezmoi.sourceDir` | The source directory. |\n" + - "| `.chezmoi.username` | The username of the user running chezmoi. |\n" + - "| `.chezmoi.version` | The version of chezmoi. |\n" + - "\n" + - "Additional variables can be defined in the config file in the `data` section.\n" + - "Variable names must consist of a letter and be followed by zero or more letters\n" + - "and/or digits.\n" + - "\n" + - "## Template functions\n" + - "\n" + - "All standard [`text/template`](https://pkg.go.dev/text/template) and [text\n" + - "template functions from `sprig`](http://masterminds.github.io/sprig/) are\n" + - "included. chezmoi provides some additional functions.\n" + - "\n" + - "### `bitwarden` [*args*]\n" + - "\n" + - "`bitwarden` returns structured data retrieved from\n" + - "[Bitwarden](https://bitwarden.com) using the [Bitwarden\n" + - "CLI](https://github.com/bitwarden/cli) (`bw`). *args* are passed to `bw get`\n" + - "unchanged and the output from `bw get` is parsed as JSON. The output from `bw\n" + - "get` is cached so calling `bitwarden` multiple times with the same arguments\n" + - "will only invoke `bw` once.\n" + - "\n" + - "#### `bitwarden` examples\n" + - "\n" + - " username = {{ (bitwarden \"item\" \"<itemid>\").login.username }}\n" + - " password = {{ (bitwarden \"item\" \"<itemid>\").login.password }}\n" + - "\n" + - "### `bitwardenAttachment` *filename* *itemid*\n" + - "\n" + - "`bitwardenAttachment` returns a document from\n" + - "[Bitwarden](https://bitwarden.com/) using the [Bitwarden\n" + - "CLI](https://bitwarden.com/help/article/cli/) (`bw`). *filename* and *itemid* is\n" + - "passed to `bw get attachment <filename> --itemid <itemid>` and the output from\n" + - "`bw` is returned. The output from `bw` is cached so calling\n" + - "`bitwardenAttachment` multiple times with the same *filename* and *itemid* will\n" + - "only invoke `bw` once.\n" + - "\n" + - "#### `bitwardenAttachment` examples\n" + - "\n" + - " {{- (bitwardenAttachment \"<filename>\" \"<itemid>\") -}}\n" + - "\n" + - "### `bitwardenFields` [*args*]\n" + - "\n" + - "`bitwardenFields` returns structured data retrieved from\n" + - "[Bitwarden](https://bitwarden.com) using the [Bitwarden\n" + - "CLI](https://github.com/bitwarden/cli) (`bw`). *args* are passed to `bw get`\n" + - "unchanged, the output from `bw get` is parsed as JSON, and elements of `fields`\n" + - "are returned as a map indexed by each field's `name`. For example, given the\n" + - "output from `bw get`:\n" + - "\n" + - "```json\n" + - "{\n" + - " \"object\": \"item\",\n" + - " \"id\": \"bf22e4b4-ae4a-4d1c-8c98-ac620004b628\",\n" + - " \"organizationId\": null,\n" + - " \"folderId\": null,\n" + - " \"type\": 1,\n" + - " \"name\": \"example.com\",\n" + - " \"notes\": null,\n" + - " \"favorite\": false,\n" + - " \"fields\": [\n" + - " {\n" + - " \"name\": \"text\",\n" + - " \"value\": \"text-value\",\n" + - " \"type\": 0\n" + - " },\n" + - " {\n" + - " \"name\": \"hidden\",\n" + - " \"value\": \"hidden-value\",\n" + - " \"type\": 1\n" + - " }\n" + - " ],\n" + - " \"login\": {\n" + - " \"username\": \"username-value\",\n" + - " \"password\": \"password-value\",\n" + - " \"totp\": null,\n" + - " \"passwordRevisionDate\": null\n" + - " },\n" + - " \"collectionIds\": [],\n" + - " \"revisionDate\": \"2020-10-28T00:21:02.690Z\"\n" + - "}\n" + - "```\n" + - "\n" + - "the return value will be the map\n" + - "\n" + - "```json\n" + - "{\n" + - " \"hidden\": {\n" + - " \"name\": \"hidden\",\n" + - " \"type\": 1,\n" + - " \"value\": \"hidden-value\"\n" + - " },\n" + - " \"token\": {\n" + - " \"name\": \"token\",\n" + - " \"type\": 0,\n" + - " \"value\": \"token-value\"\n" + - " }\n" + - "}\n" + - "```\n" + - "\n" + - "The output from `bw get` is cached so calling `bitwarden` multiple times with\n" + - "the same arguments will only invoke `bw get` once.\n" + - "\n" + - "#### `bitwardenFields` examples\n" + - "\n" + - " {{ (bitwardenFields \"item\" \"<itemid>\").token.value }}\n" + - "\n" + - "### `gitHubKeys` *user*\n" + - "\n" + - "`gitHubKeys` returns *user*'s public SSH keys from GitHub using the GitHub API.\n" + - "If any of the environment variables `CHEZMOI_GITHUB_ACCESS_TOKEN`,\n" + - "`GITHUB_ACCESS_TOKEN`, or `GITHUB_TOKEN` are found, then the first one found\n" + - "will be used to authenticate the API request, otherwise an anonymous API request\n" + - "will be used, which may be subject to lower rate limits.\n" + - "\n" + - "#### `gitHubKeys` examples\n" + - "\n" + - " {{ range (gitHubKeys \"user\") }}\n" + - " {{- .Key }}\n" + - " {{- end }}\n" + - "\n" + - "### `gopass` *gopass-name*\n" + - "\n" + - "`gopass` returns passwords stored in [gopass](https://www.gopass.pw/) using the\n" + - "gopass CLI (`gopass`). *gopass-name* is passed to `gopass show <gopass-name>`\n" + - "and first line of the output of `gopass` is returned with the trailing newline\n" + - "stripped. The output from `gopass` is cached so calling `gopass` multiple times\n" + - "with the same *gopass-name* will only invoke `gopass` once.\n" + - "\n" + - "#### `gopass` examples\n" + - "\n" + - " {{ gopass \"<pass-name>\" }}\n" + - "\n" + - "### `include` *filename*\n" + - "\n" + - "`include` returns the literal contents of the file named `*filename*`, relative\n" + - "to the source directory.\n" + - "\n" + - "### `ioreg`\n" + - "\n" + - "On macOS, `ioreg` returns the structured output of the `ioreg -a -l` command,\n" + - "which includes detailed information about the I/O Kit registry.\n" + - "\n" + - "On non-macOS operating systems, `ioreg` returns `nil`.\n" + - "\n" + - "The output from `ioreg` is cached so multiple calls to the `ioreg` function will\n" + - "only execute the `ioreg -a -l` command once.\n" + - "\n" + - "#### `ioreg` examples\n" + - "\n" + - " {{ if (eq .chezmoi.os \"darwin\") }}\n" + - " {{ $serialNumber := index ioreg \"IORegistryEntryChildren\" 0 \"IOPlatformSerialNumber\" }}\n" + - " {{ end }}\n" + - "\n" + - "### `joinPath` *elements*\n" + - "\n" + - "`joinPath` joins any number of path elements into a single path, separating them\n" + - "with the OS-specific path separator. Empty elements are ignored. The result is\n" + - "cleaned. If the argument list is empty or all its elements are empty, `joinPath`\n" + - "returns an empty string. On Windows, the result will only be a UNC path if the\n" + - "first non-empty element is a UNC path.\n" + - "\n" + - "#### `joinPath` examples\n" + - "\n" + - " {{ joinPath .chezmoi.homeDir \".zshrc\" }}\n" + - "\n" + - "### `keepassxc` *entry*\n" + - "\n" + - "`keepassxc` returns structured data retrieved from a\n" + - "[KeePassXC](https://keepassxc.org/) database using the KeePassXC CLI\n" + - "(`keepassxc-cli`). The database is configured by setting `keepassxc.database` in\n" + - "the configuration file. *database* and *entry* are passed to `keepassxc-cli\n" + - "show`. You will be prompted for the database password the first time\n" + - "`keepassxc-cli` is run, and the password is cached, in plain text, in memory\n" + - "until chezmoi terminates. The output from `keepassxc-cli` is parsed into\n" + - "key-value pairs and cached so calling `keepassxc` multiple times with the same\n" + - "*entry* will only invoke `keepassxc-cli` once.\n" + - "\n" + - "#### `keepassxc` examples\n" + - "\n" + - " username = {{ (keepassxc \"example.com\").UserName }}\n" + - " password = {{ (keepassxc \"example.com\").Password }}\n" + - "\n" + - "### `keepassxcAttribute` *entry* *attribute*\n" + - "\n" + - "`keepassxcAttribute` returns the attribute *attribute* of *entry* using\n" + - "`keepassxc-cli`, with any leading or trailing whitespace removed. It behaves\n" + - "identically to the `keepassxc` function in terms of configuration, password\n" + - "prompting, password storage, and result caching.\n" + - "\n" + - "#### `keepassxcAttribute` examples\n" + - "\n" + - " {{ keepassxcAttribute \"SSH Key\" \"private-key\" }}\n" + - "\n" + - "### `keyring` *service* *user*\n" + - "\n" + - "`keyring` retrieves the value associated with *service* and *user* from the\n" + - "user's keyring.\n" + - "\n" + - "| OS | Keyring |\n" + - "| ------- | --------------------------- |\n" + - "| macOS | Keychain |\n" + - "| Linux | GNOME Keyring |\n" + - "| Windows | Windows Credentials Manager |\n" + - "\n" + - "#### `keyring` examples\n" + - "\n" + - " [github]\n" + - " user = \"{{ .github.user }}\"\n" + - " token = \"{{ keyring \"github\" .github.user }}\"\n" + - "\n" + - "### `lastpass` *id*\n" + - "\n" + - "`lastpass` returns structured data from [LastPass](https://lastpass.com) using\n" + - "the [LastPass CLI](https://lastpass.github.io/lastpass-cli/lpass.1.html)\n" + - "(`lpass`). *id* is passed to `lpass show --json <id>` and the output from\n" + - "`lpass` is parsed as JSON. In addition, the `note` field, if present, is further\n" + - "parsed as colon-separated key-value pairs. The structured data is an array so\n" + - "typically the `index` function is used to extract the first item. The output\n" + - "from `lastpass` is cached so calling `lastpass` multiple times with the same\n" + - "*id* will only invoke `lpass` once.\n" + - "\n" + - "#### `lastpass` examples\n" + - "\n" + - " githubPassword = \"{{ (index (lastpass \"GitHub\") 0).password }}\"\n" + - " {{ (index (lastpass \"SSH\") 0).note.privateKey }}\n" + - "\n" + - "### `lastpassRaw` *id*\n" + - "\n" + - "`lastpassRaw` returns structured data from [LastPass](https://lastpass.com)\n" + - "using the [LastPass CLI](https://lastpass.github.io/lastpass-cli/lpass.1.html)\n" + - "(`lpass`). It behaves identically to the `lastpass` function, except that no\n" + - "further parsing is done on the `note` field.\n" + - "\n" + - "#### `lastpassRaw` examples\n" + - "\n" + - " {{ (index (lastpassRaw \"SSH Private Key\") 0).note }}\n" + - "\n" + - "### `lookPath` *file*\n" + - "\n" + - "`lookPath` searches for an executable named *file* in the directories named by\n" + - "the `PATH` environment variable. If file contains a slash, it is tried directly\n" + - "and the `PATH` is not consulted. The result may be an absolute path or a path\n" + - "relative to the current directory. If *file* is not found, `lookPath` returns an\n" + - "empty string.\n" + - "\n" + - "`lookPath` is not hermetic: its return value depends on the state of the\n" + - "environment and the filesystem at the moment the template is executed. Exercise\n" + - "caution when using it in your templates.\n" + - "\n" + - "#### `lookPath` examples\n" + - "\n" + - " {{ if lookPath \"diff-so-fancy\" }}\n" + - " # diff-so-fancy is in $PATH\n" + - " {{ end }}\n" + - "\n" + - "### `onepassword` *uuid* [*vault-uuid*]\n" + - "\n" + - "`onepassword` returns structured data from [1Password](https://1password.com/)\n" + - "using the [1Password\n" + - "CLI](https://support.1password.com/command-line-getting-started/) (`op`). *uuid*\n" + - "is passed to `op get item <uuid>` and the output from `op` is parsed as JSON.\n" + - "The output from `op` is cached so calling `onepassword` multiple times with the\n" + - "same *uuid* will only invoke `op` once. If the optional *vault-uuid* is supplied,\n" + - "it will be passed along to the `op get` call, which can significantly improve\n" + - "performance.\n" + - "\n" + - "#### `onepassword` examples\n" + - "\n" + - " {{ (onepassword \"<uuid>\").details.password }}\n" + - " {{ (onepassword \"<uuid>\" \"<vault-uuid>\").details.password }}\n" + - "\n" + - "### `onepasswordDocument` *uuid* [*vault-uuid*]\n" + - "\n" + - "`onepassword` returns a document from [1Password](https://1password.com/)\n" + - "using the [1Password\n" + - "CLI](https://support.1password.com/command-line-getting-started/) (`op`). *uuid*\n" + - "is passed to `op get document <uuid>` and the output from `op` is returned.\n" + - "The output from `op` is cached so calling `onepasswordDocument` multiple times with the\n" + - "same *uuid* will only invoke `op` once. If the optional *vault-uuid* is supplied,\n" + - "it will be passed along to the `op get` call, which can significantly improve\n" + - "performance.\n" + - "\n" + - "#### `onepasswordDocument` examples\n" + - "\n" + - " {{- onepasswordDocument \"<uuid>\" -}}\n" + - " {{- onepasswordDocument \"<uuid>\" \"<vault-uuid>\" -}}\n" + - "\n" + - "### `onepasswordDetailsFields` *uuid* [*vault-uuid*]\n" + - "\n" + - "`onepasswordDetailsFields` returns structured data from\n" + - "[1Password](https://1password.com/) using the [1Password\n" + - "CLI](https://support.1password.com/command-line-getting-started/) (`op`). *uuid*\n" + - "is passed to `op get item <uuid>`, the output from `op` is parsed as JSON, and\n" + - "elements of `details.fields` are returned as a map indexed by each field's\n" + - "`designation`. For example, give the output from `op`:\n" + - "\n" + - "```json\n" + - "{\n" + - " \"uuid\": \"<uuid>\",\n" + - " \"details\": {\n" + - " \"fields\": [\n" + - " {\n" + - " \"designation\": \"username\",\n" + - " \"name\": \"username\",\n" + - " \"type\": \"T\",\n" + - " \"value\": \"exampleuser\"\n" + - " },\n" + - " {\n" + - " \"designation\": \"password\",\n" + - " \"name\": \"password\",\n" + - " \"type\": \"P\",\n" + - " \"value\": \"examplepassword\"\n" + - " }\n" + - " ],\n" + - " }\n" + - "}\n" + - "```\n" + - "\n" + - "the return value will be the map:\n" + - "\n" + - "```json\n" + - "{\n" + - " \"username\": {\n" + - " \"designation\": \"username\",\n" + - " \"name\": \"username\",\n" + - " \"type\": \"T\",\n" + - " \"value\": \"exampleuser\"\n" + - " },\n" + - " \"password\": {\n" + - " \"designation\": \"password\",\n" + - " \"name\": \"password\",\n" + - " \"type\": \"P\",\n" + - " \"value\": \"examplepassword\"\n" + - " }\n" + - "}\n" + - "```\n" + - "\n" + - "The output from `op` is cached so calling `onepassword` multiple times with the\n" + - "same *uuid* will only invoke `op` once. If the optional *vault-uuid* is supplied,\n" + - "it will be passed along to the `op get` call, which can significantly improve\n" + - "performance.\n" + - "\n" + - "#### `onepasswordDetailsFields` examples\n" + - "\n" + - " {{ (onepasswordDetailsFields \"<uuid>\").password.value }}\n" + - "\n" + - "### `pass` *pass-name*\n" + - "\n" + - "`pass` returns passwords stored in [pass](https://www.passwordstore.org/) using\n" + - "the pass CLI (`pass`). *pass-name* is passed to `pass show <pass-name>` and\n" + - "first line of the output of `pass` is returned with the trailing newline\n" + - "stripped. The output from `pass` is cached so calling `pass` multiple times with\n" + - "the same *pass-name* will only invoke `pass` once.\n" + - "\n" + - "#### `pass` examples\n" + - "\n" + - " {{ pass \"<pass-name>\" }}\n" + - "\n" + - "### `promptBool` *prompt*\n" + - "\n" + - "`promptBool` prompts the user with *prompt* and returns the user's response with\n" + - "interpreted as a boolean. It is only available when generating the initial\n" + - "config file. The user's response is interpreted as follows (case insensitive):\n" + - "\n" + - "| Response | Result |\n" + - "| ----------------------- | ------- |\n" + - "| 1, on, t, true, y, yes | `true` |\n" + - "| 0, off, f, false, n, no | `false` |\n" + - "\n" + - "### `promptInt` *prompt*\n" + - "\n" + - "`promptInt` prompts the user with *prompt* and returns the user's response with\n" + - "interpreted as an integer. It is only available when generating the initial\n" + - "config file.\n" + - "\n" + - "### `promptString` *prompt*\n" + - "\n" + - "`promptString` prompts the user with *prompt* and returns the user's response\n" + - "with all leading and trailing spaces stripped. It is only available when\n" + - "generating the initial config file.\n" + - "\n" + - "#### `promptString` examples\n" + - "\n" + - " {{ $email := promptString \"email\" -}}\n" + - " [data]\n" + - " email = \"{{ $email }}\"\n" + - "\n" + - "### `secret` [*args*]\n" + - "\n" + - "`secret` returns the output of the generic secret command defined by the\n" + - "`secret.command` configuration variable with *args* with leading and trailing\n" + - "whitespace removed. The output is cached so multiple calls to `secret` with the\n" + - "same *args* will only invoke the generic secret command once.\n" + - "\n" + - "### `secretJSON` [*args*]\n" + - "\n" + - "`secretJSON` returns structured data from the generic secret command defined by\n" + - "the `secret.command` configuration variable with *args*. The output is parsed as\n" + - "JSON. The output is cached so multiple calls to `secret` with the same *args*\n" + - "will only invoke the generic secret command once.\n" + - "\n" + - "### `stat` *name*\n" + - "\n" + - "`stat` runs `stat(2)` on *name*. If *name* exists it returns structured data. If\n" + - "*name* does not exist then it returns a false value. If `stat(2)` returns any\n" + - "other error then it raises an error. The structured value returned if *name*\n" + - "exists contains the fields `name`, `size`, `mode`, `perm`, `modTime`, and\n" + - "`isDir`.\n" + - "\n" + - "`stat` is not hermetic: its return value depends on the state of the filesystem\n" + - "at the moment the template is executed. Exercise caution when using it in your\n" + - "templates.\n" + - "\n" + - "#### `stat` examples\n" + - "\n" + - " {{ if stat (joinPath .chezmoi.homeDir \".pyenv\") }}\n" + - " # ~/.pyenv exists\n" + - " {{ end }}\n" + - "\n" + - "### `vault` *key*\n" + - "\n" + - "`vault` returns structured data from [Vault](https://www.vaultproject.io/) using\n" + - "the [Vault CLI](https://www.vaultproject.io/docs/commands/) (`vault`). *key* is\n" + - "passed to `vault kv get -format=json <key>` and the output from `vault` is\n" + - "parsed as JSON. The output from `vault` is cached so calling `vault` multiple\n" + - "times with the same *key* will only invoke `vault` once.\n" + - "\n" + - "#### `vault` examples\n" + - "\n" + - " {{ (vault \"<key>\").data.data.password }}\n" + - "\n") -} diff --git a/chezmoi2/cmd/templatefuncs.go b/chezmoi2/cmd/templatefuncs.go deleted file mode 100644 index 074ac7d27f5..00000000000 --- a/chezmoi2/cmd/templatefuncs.go +++ /dev/null @@ -1,93 +0,0 @@ -package cmd - -import ( - "errors" - "fmt" - "os" - "os/exec" - "path/filepath" - "runtime" - - "howett.net/plist" - - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" -) - -type ioregData struct { - value map[string]interface{} -} - -func (c *Config) includeTemplateFunc(filename string) string { - contents, err := c.fs.ReadFile(string(c.sourceDirAbsPath.Join(chezmoi.RelPath(filename)))) - if err != nil { - returnTemplateError(err) - return "" - } - return string(contents) -} - -func (c *Config) ioregTemplateFunc() map[string]interface{} { - if runtime.GOOS != "darwin" { - return nil - } - - if c.ioregData.value != nil { - return c.ioregData.value - } - - cmd := exec.Command("ioreg", "-a", "-l") - output, err := c.baseSystem.IdempotentCmdOutput(cmd) - if err != nil { - returnTemplateError(fmt.Errorf("ioreg: %w", err)) - return nil - } - - var value map[string]interface{} - if _, err := plist.Unmarshal(output, &value); err != nil { - returnTemplateError(fmt.Errorf("ioreg: %w", err)) - return nil - } - c.ioregData.value = value - return value -} - -func (c *Config) joinPathTemplateFunc(elem ...string) string { - return filepath.Join(elem...) -} - -func (c *Config) lookPathTemplateFunc(file string) string { - path, err := exec.LookPath(file) - switch { - case err == nil: - return path - case errors.Is(err, exec.ErrNotFound): - return "" - default: - returnTemplateError(err) - return "" - } -} - -func (c *Config) statTemplateFunc(name string) interface{} { - info, err := c.fs.Stat(name) - switch { - case err == nil: - return map[string]interface{}{ - "name": info.Name(), - "size": info.Size(), - "mode": int(info.Mode()), - "perm": int(info.Mode() & os.ModePerm), - "modTime": info.ModTime().Unix(), - "isDir": info.IsDir(), - } - case os.IsNotExist(err): - return nil - default: - returnTemplateError(err) - return nil - } -} - -func returnTemplateError(err error) { - panic(err) -} diff --git a/chezmoi2/cmd/templates.gen.go b/chezmoi2/cmd/templates.gen.go deleted file mode 100644 index f331042e250..00000000000 --- a/chezmoi2/cmd/templates.gen.go +++ /dev/null @@ -1,31 +0,0 @@ -// Code generated by github.com/twpayne/chezmoi/internal/cmd/generate-assets. DO NOT EDIT. - -package cmd - -func init() { - assets["assets/templates/COMMIT_MESSAGE.tmpl"] = []byte("" + - "{{- /* FIXME generate commit summary */ -}}\n" + - "\n" + - "{{- range .Ordinary -}}\n" + - "{{ if and (eq .X 'A') (eq .Y '.') -}}Add {{ .Path }}\n" + - "{{ else if and (eq .X 'D') (eq .Y '.') -}}Remove {{ .Path }}\n" + - "{{ else if and (eq .X 'M') (eq .Y '.') -}}Update {{ .Path }}\n" + - "{{ else }}{{with (printf \"unsupported XY: %q\" (printf \"%c%c\" .X .Y)) }}{{ fail . }}{{ end }}\n" + - "{{ end }}\n" + - "{{- end -}}\n" + - "\n" + - "{{- range .RenamedOrCopied -}}\n" + - "{{ if and (eq .X 'R') (eq .Y '.') }}Rename {{ .OrigPath }} to {{ .Path }}\n" + - "{{ else }}{{with (printf \"unsupported XY: %q\" (printf \"%c%c\" .X .Y)) }}{{ fail . }}{{ end }}\n" + - "{{ end }}\n" + - "{{- end -}}\n" + - "\n" + - "{{- range .Unmerged -}}\n" + - "{{ fail \"unmerged files\" }}\n" + - "{{- end -}}\n" + - "\n" + - "{{- range .Untracked -}}\n" + - "{{ fail \"untracked files\" }}\n" + - "{{- end -}}\n" + - "\n") -} diff --git a/chezmoi2/cmd/util_windows.go b/chezmoi2/cmd/util_windows.go deleted file mode 100644 index dd5b6adceb0..00000000000 --- a/chezmoi2/cmd/util_windows.go +++ /dev/null @@ -1,22 +0,0 @@ -package cmd - -import ( - "io" - "os" - - "golang.org/x/sys/windows" -) - -// enableVirtualTerminalProcessing enables virtual terminal processing. See -// https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences. -func enableVirtualTerminalProcessing(w io.Writer) error { - f, ok := w.(*os.File) - if !ok { - return nil - } - var dwMode uint32 - if err := windows.GetConsoleMode(windows.Handle(f.Fd()), &dwMode); err != nil { - return nil // Ignore error in the case that fd is not a terminal. - } - return windows.SetConsoleMode(windows.Handle(f.Fd()), dwMode|windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING) -} diff --git a/chezmoi2/completions/chezmoi2-completion.bash b/chezmoi2/completions/chezmoi2-completion.bash deleted file mode 100644 index e8d67daf8b6..00000000000 --- a/chezmoi2/completions/chezmoi2-completion.bash +++ /dev/null @@ -1,3205 +0,0 @@ -# bash completion for chezmoi2 -*- shell-script -*- - -__chezmoi2_debug() -{ - if [[ -n ${BASH_COMP_DEBUG_FILE} ]]; then - echo "$*" >> "${BASH_COMP_DEBUG_FILE}" - fi -} - -# Homebrew on Macs have version 1.3 of bash-completion which doesn't include -# _init_completion. This is a very minimal version of that function. -__chezmoi2_init_completion() -{ - COMPREPLY=() - _get_comp_words_by_ref "$@" cur prev words cword -} - -__chezmoi2_index_of_word() -{ - local w word=$1 - shift - index=0 - for w in "$@"; do - [[ $w = "$word" ]] && return - index=$((index+1)) - done - index=-1 -} - -__chezmoi2_contains_word() -{ - local w word=$1; shift - for w in "$@"; do - [[ $w = "$word" ]] && return - done - return 1 -} - -__chezmoi2_handle_go_custom_completion() -{ - __chezmoi2_debug "${FUNCNAME[0]}: cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}" - - local shellCompDirectiveError=1 - local shellCompDirectiveNoSpace=2 - local shellCompDirectiveNoFileComp=4 - local shellCompDirectiveFilterFileExt=8 - local shellCompDirectiveFilterDirs=16 - - local out requestComp lastParam lastChar comp directive args - - # Prepare the command to request completions for the program. - # Calling ${words[0]} instead of directly chezmoi2 allows to handle aliases - args=("${words[@]:1}") - requestComp="${words[0]} __completeNoDesc ${args[*]}" - - lastParam=${words[$((${#words[@]}-1))]} - lastChar=${lastParam:$((${#lastParam}-1)):1} - __chezmoi2_debug "${FUNCNAME[0]}: lastParam ${lastParam}, lastChar ${lastChar}" - - if [ -z "${cur}" ] && [ "${lastChar}" != "=" ]; then - # If the last parameter is complete (there is a space following it) - # We add an extra empty parameter so we can indicate this to the go method. - __chezmoi2_debug "${FUNCNAME[0]}: Adding extra empty parameter" - requestComp="${requestComp} \"\"" - fi - - __chezmoi2_debug "${FUNCNAME[0]}: calling ${requestComp}" - # Use eval to handle any environment variables and such - out=$(eval "${requestComp}" 2>/dev/null) - - # Extract the directive integer at the very end of the output following a colon (:) - directive=${out##*:} - # Remove the directive - out=${out%:*} - if [ "${directive}" = "${out}" ]; then - # There is not directive specified - directive=0 - fi - __chezmoi2_debug "${FUNCNAME[0]}: the completion directive is: ${directive}" - __chezmoi2_debug "${FUNCNAME[0]}: the completions are: ${out[*]}" - - if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then - # Error code. No completion. - __chezmoi2_debug "${FUNCNAME[0]}: received error from custom completion go code" - return - else - if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then - if [[ $(type -t compopt) = "builtin" ]]; then - __chezmoi2_debug "${FUNCNAME[0]}: activating no space" - compopt -o nospace - fi - fi - if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then - if [[ $(type -t compopt) = "builtin" ]]; then - __chezmoi2_debug "${FUNCNAME[0]}: activating no file completion" - compopt +o default - fi - fi - fi - - if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then - # File extension filtering - local fullFilter filter filteringCmd - # Do not use quotes around the $out variable or else newline - # characters will be kept. - for filter in ${out[*]}; do - fullFilter+="$filter|" - done - - filteringCmd="_filedir $fullFilter" - __chezmoi2_debug "File filtering command: $filteringCmd" - $filteringCmd - elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then - # File completion for directories only - local subDir - # Use printf to strip any trailing newline - subdir=$(printf "%s" "${out[0]}") - if [ -n "$subdir" ]; then - __chezmoi2_debug "Listing directories in $subdir" - __chezmoi2_handle_subdirs_in_dir_flag "$subdir" - else - __chezmoi2_debug "Listing directories in ." - _filedir -d - fi - else - while IFS='' read -r comp; do - COMPREPLY+=("$comp") - done < <(compgen -W "${out[*]}" -- "$cur") - fi -} - -__chezmoi2_handle_reply() -{ - __chezmoi2_debug "${FUNCNAME[0]}" - local comp - case $cur in - -*) - if [[ $(type -t compopt) = "builtin" ]]; then - compopt -o nospace - fi - local allflags - if [ ${#must_have_one_flag[@]} -ne 0 ]; then - allflags=("${must_have_one_flag[@]}") - else - allflags=("${flags[*]} ${two_word_flags[*]}") - fi - while IFS='' read -r comp; do - COMPREPLY+=("$comp") - done < <(compgen -W "${allflags[*]}" -- "$cur") - if [[ $(type -t compopt) = "builtin" ]]; then - [[ "${COMPREPLY[0]}" == *= ]] || compopt +o nospace - fi - - # complete after --flag=abc - if [[ $cur == *=* ]]; then - if [[ $(type -t compopt) = "builtin" ]]; then - compopt +o nospace - fi - - local index flag - flag="${cur%=*}" - __chezmoi2_index_of_word "${flag}" "${flags_with_completion[@]}" - COMPREPLY=() - if [[ ${index} -ge 0 ]]; then - PREFIX="" - cur="${cur#*=}" - ${flags_completion[${index}]} - if [ -n "${ZSH_VERSION}" ]; then - # zsh completion needs --flag= prefix - eval "COMPREPLY=( \"\${COMPREPLY[@]/#/${flag}=}\" )" - fi - fi - fi - return 0; - ;; - esac - - # check if we are handling a flag with special work handling - local index - __chezmoi2_index_of_word "${prev}" "${flags_with_completion[@]}" - if [[ ${index} -ge 0 ]]; then - ${flags_completion[${index}]} - return - fi - - # we are parsing a flag and don't have a special handler, no completion - if [[ ${cur} != "${words[cword]}" ]]; then - return - fi - - local completions - completions=("${commands[@]}") - if [[ ${#must_have_one_noun[@]} -ne 0 ]]; then - completions+=("${must_have_one_noun[@]}") - elif [[ -n "${has_completion_function}" ]]; then - # if a go completion function is provided, defer to that function - __chezmoi2_handle_go_custom_completion - fi - if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then - completions+=("${must_have_one_flag[@]}") - fi - while IFS='' read -r comp; do - COMPREPLY+=("$comp") - done < <(compgen -W "${completions[*]}" -- "$cur") - - if [[ ${#COMPREPLY[@]} -eq 0 && ${#noun_aliases[@]} -gt 0 && ${#must_have_one_noun[@]} -ne 0 ]]; then - while IFS='' read -r comp; do - COMPREPLY+=("$comp") - done < <(compgen -W "${noun_aliases[*]}" -- "$cur") - fi - - if [[ ${#COMPREPLY[@]} -eq 0 ]]; then - if declare -F __chezmoi2_custom_func >/dev/null; then - # try command name qualified custom func - __chezmoi2_custom_func - else - # otherwise fall back to unqualified for compatibility - declare -F __custom_func >/dev/null && __custom_func - fi - fi - - # available in bash-completion >= 2, not always present on macOS - if declare -F __ltrim_colon_completions >/dev/null; then - __ltrim_colon_completions "$cur" - fi - - # If there is only 1 completion and it is a flag with an = it will be completed - # but we don't want a space after the = - if [[ "${#COMPREPLY[@]}" -eq "1" ]] && [[ $(type -t compopt) = "builtin" ]] && [[ "${COMPREPLY[0]}" == --*= ]]; then - compopt -o nospace - fi -} - -# The arguments should be in the form "ext1|ext2|extn" -__chezmoi2_handle_filename_extension_flag() -{ - local ext="$1" - _filedir "@(${ext})" -} - -__chezmoi2_handle_subdirs_in_dir_flag() -{ - local dir="$1" - pushd "${dir}" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return -} - -__chezmoi2_handle_flag() -{ - __chezmoi2_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" - - # if a command required a flag, and we found it, unset must_have_one_flag() - local flagname=${words[c]} - local flagvalue - # if the word contained an = - if [[ ${words[c]} == *"="* ]]; then - flagvalue=${flagname#*=} # take in as flagvalue after the = - flagname=${flagname%=*} # strip everything after the = - flagname="${flagname}=" # but put the = back - fi - __chezmoi2_debug "${FUNCNAME[0]}: looking for ${flagname}" - if __chezmoi2_contains_word "${flagname}" "${must_have_one_flag[@]}"; then - must_have_one_flag=() - fi - - # if you set a flag which only applies to this command, don't show subcommands - if __chezmoi2_contains_word "${flagname}" "${local_nonpersistent_flags[@]}"; then - commands=() - fi - - # keep flag value with flagname as flaghash - # flaghash variable is an associative array which is only supported in bash > 3. - if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then - if [ -n "${flagvalue}" ] ; then - flaghash[${flagname}]=${flagvalue} - elif [ -n "${words[ $((c+1)) ]}" ] ; then - flaghash[${flagname}]=${words[ $((c+1)) ]} - else - flaghash[${flagname}]="true" # pad "true" for bool flag - fi - fi - - # skip the argument to a two word flag - if [[ ${words[c]} != *"="* ]] && __chezmoi2_contains_word "${words[c]}" "${two_word_flags[@]}"; then - __chezmoi2_debug "${FUNCNAME[0]}: found a flag ${words[c]}, skip the next argument" - c=$((c+1)) - # if we are looking for a flags value, don't show commands - if [[ $c -eq $cword ]]; then - commands=() - fi - fi - - c=$((c+1)) - -} - -__chezmoi2_handle_noun() -{ - __chezmoi2_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" - - if __chezmoi2_contains_word "${words[c]}" "${must_have_one_noun[@]}"; then - must_have_one_noun=() - elif __chezmoi2_contains_word "${words[c]}" "${noun_aliases[@]}"; then - must_have_one_noun=() - fi - - nouns+=("${words[c]}") - c=$((c+1)) -} - -__chezmoi2_handle_command() -{ - __chezmoi2_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" - - local next_command - if [[ -n ${last_command} ]]; then - next_command="_${last_command}_${words[c]//:/__}" - else - if [[ $c -eq 0 ]]; then - next_command="_chezmoi2_root_command" - else - next_command="_${words[c]//:/__}" - fi - fi - c=$((c+1)) - __chezmoi2_debug "${FUNCNAME[0]}: looking for ${next_command}" - declare -F "$next_command" >/dev/null && $next_command -} - -__chezmoi2_handle_word() -{ - if [[ $c -ge $cword ]]; then - __chezmoi2_handle_reply - return - fi - __chezmoi2_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" - if [[ "${words[c]}" == -* ]]; then - __chezmoi2_handle_flag - elif __chezmoi2_contains_word "${words[c]}" "${commands[@]}"; then - __chezmoi2_handle_command - elif [[ $c -eq 0 ]]; then - __chezmoi2_handle_command - elif __chezmoi2_contains_word "${words[c]}" "${command_aliases[@]}"; then - # aliashash variable is an associative array which is only supported in bash > 3. - if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then - words[c]=${aliashash[${words[c]}]} - __chezmoi2_handle_command - else - __chezmoi2_handle_noun - fi - else - __chezmoi2_handle_noun - fi - __chezmoi2_handle_word -} - -_chezmoi2_add() -{ - last_command="chezmoi2_add" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--autotemplate") - flags+=("-a") - local_nonpersistent_flags+=("--autotemplate") - local_nonpersistent_flags+=("-a") - flags+=("--create") - local_nonpersistent_flags+=("--create") - flags+=("--empty") - flags+=("-e") - local_nonpersistent_flags+=("--empty") - local_nonpersistent_flags+=("-e") - flags+=("--encrypt") - local_nonpersistent_flags+=("--encrypt") - flags+=("--exact") - flags+=("-x") - local_nonpersistent_flags+=("--exact") - local_nonpersistent_flags+=("-x") - flags+=("--follow") - flags+=("-f") - local_nonpersistent_flags+=("--follow") - local_nonpersistent_flags+=("-f") - flags+=("--recursive") - flags+=("-r") - local_nonpersistent_flags+=("--recursive") - local_nonpersistent_flags+=("-r") - flags+=("--template") - flags+=("-T") - local_nonpersistent_flags+=("--template") - local_nonpersistent_flags+=("-T") - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_apply() -{ - last_command="chezmoi2_apply" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--ignore-encrypted") - local_nonpersistent_flags+=("--ignore-encrypted") - flags+=("--include=") - two_word_flags+=("--include") - two_word_flags+=("-i") - local_nonpersistent_flags+=("--include") - local_nonpersistent_flags+=("--include=") - local_nonpersistent_flags+=("-i") - flags+=("--recursive") - flags+=("-r") - local_nonpersistent_flags+=("--recursive") - local_nonpersistent_flags+=("-r") - flags+=("--source-path") - local_nonpersistent_flags+=("--source-path") - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_archive() -{ - last_command="chezmoi2_archive" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--format=") - two_word_flags+=("--format") - local_nonpersistent_flags+=("--format") - local_nonpersistent_flags+=("--format=") - flags+=("--gzip") - flags+=("-z") - local_nonpersistent_flags+=("--gzip") - local_nonpersistent_flags+=("-z") - flags+=("--include=") - two_word_flags+=("--include") - two_word_flags+=("-i") - local_nonpersistent_flags+=("--include") - local_nonpersistent_flags+=("--include=") - local_nonpersistent_flags+=("-i") - flags+=("--recursive") - flags+=("-r") - local_nonpersistent_flags+=("--recursive") - local_nonpersistent_flags+=("-r") - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_cat() -{ - last_command="chezmoi2_cat" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_cd() -{ - last_command="chezmoi2_cd" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_chattr() -{ - last_command="chezmoi2_chattr" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - must_have_one_noun+=("+a") - must_have_one_noun+=("+after") - must_have_one_noun+=("+b") - must_have_one_noun+=("+before") - must_have_one_noun+=("+e") - must_have_one_noun+=("+empty") - must_have_one_noun+=("+encrypted") - must_have_one_noun+=("+exact") - must_have_one_noun+=("+executable") - must_have_one_noun+=("+o") - must_have_one_noun+=("+once") - must_have_one_noun+=("+p") - must_have_one_noun+=("+private") - must_have_one_noun+=("+t") - must_have_one_noun+=("+template") - must_have_one_noun+=("+x") - must_have_one_noun+=("-a") - must_have_one_noun+=("-after") - must_have_one_noun+=("-b") - must_have_one_noun+=("-before") - must_have_one_noun+=("-e") - must_have_one_noun+=("-empty") - must_have_one_noun+=("-encrypted") - must_have_one_noun+=("-exact") - must_have_one_noun+=("-executable") - must_have_one_noun+=("-o") - must_have_one_noun+=("-once") - must_have_one_noun+=("-p") - must_have_one_noun+=("-private") - must_have_one_noun+=("-t") - must_have_one_noun+=("-template") - must_have_one_noun+=("-x") - must_have_one_noun+=("a") - must_have_one_noun+=("after") - must_have_one_noun+=("b") - must_have_one_noun+=("before") - must_have_one_noun+=("e") - must_have_one_noun+=("empty") - must_have_one_noun+=("encrypted") - must_have_one_noun+=("exact") - must_have_one_noun+=("executable") - must_have_one_noun+=("noa") - must_have_one_noun+=("noafter") - must_have_one_noun+=("nob") - must_have_one_noun+=("nobefore") - must_have_one_noun+=("noe") - must_have_one_noun+=("noempty") - must_have_one_noun+=("noencrypted") - must_have_one_noun+=("noexact") - must_have_one_noun+=("noexecutable") - must_have_one_noun+=("noo") - must_have_one_noun+=("noonce") - must_have_one_noun+=("nop") - must_have_one_noun+=("noprivate") - must_have_one_noun+=("not") - must_have_one_noun+=("notemplate") - must_have_one_noun+=("nox") - must_have_one_noun+=("o") - must_have_one_noun+=("once") - must_have_one_noun+=("p") - must_have_one_noun+=("private") - must_have_one_noun+=("t") - must_have_one_noun+=("template") - must_have_one_noun+=("x") - noun_aliases=() -} - -_chezmoi2_completion() -{ - last_command="chezmoi2_completion" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--help") - flags+=("-h") - local_nonpersistent_flags+=("--help") - local_nonpersistent_flags+=("-h") - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - must_have_one_noun+=("bash") - must_have_one_noun+=("fish") - must_have_one_noun+=("powershell") - must_have_one_noun+=("zsh") - noun_aliases=() -} - -_chezmoi2_data() -{ - last_command="chezmoi2_data" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--format=") - two_word_flags+=("--format") - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_diff() -{ - last_command="chezmoi2_diff" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--include=") - two_word_flags+=("--include") - two_word_flags+=("-i") - local_nonpersistent_flags+=("--include") - local_nonpersistent_flags+=("--include=") - local_nonpersistent_flags+=("-i") - flags+=("--recursive") - flags+=("-r") - local_nonpersistent_flags+=("--recursive") - local_nonpersistent_flags+=("-r") - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_docs() -{ - last_command="chezmoi2_docs" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_doctor() -{ - last_command="chezmoi2_doctor" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_dump() -{ - last_command="chezmoi2_dump" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--format=") - two_word_flags+=("--format") - two_word_flags+=("-f") - local_nonpersistent_flags+=("--format") - local_nonpersistent_flags+=("--format=") - local_nonpersistent_flags+=("-f") - flags+=("--include=") - two_word_flags+=("--include") - two_word_flags+=("-i") - local_nonpersistent_flags+=("--include") - local_nonpersistent_flags+=("--include=") - local_nonpersistent_flags+=("-i") - flags+=("--recursive") - flags+=("-r") - local_nonpersistent_flags+=("--recursive") - local_nonpersistent_flags+=("-r") - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_edit() -{ - last_command="chezmoi2_edit" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--apply") - flags+=("-a") - local_nonpersistent_flags+=("--apply") - local_nonpersistent_flags+=("-a") - flags+=("--include=") - two_word_flags+=("--include") - two_word_flags+=("-i") - local_nonpersistent_flags+=("--include") - local_nonpersistent_flags+=("--include=") - local_nonpersistent_flags+=("-i") - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_edit-config() -{ - last_command="chezmoi2_edit-config" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_execute-template() -{ - last_command="chezmoi2_execute-template" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--init") - flags+=("-i") - local_nonpersistent_flags+=("--init") - local_nonpersistent_flags+=("-i") - flags+=("--promptBool=") - two_word_flags+=("--promptBool") - local_nonpersistent_flags+=("--promptBool") - local_nonpersistent_flags+=("--promptBool=") - flags+=("--promptInt=") - two_word_flags+=("--promptInt") - local_nonpersistent_flags+=("--promptInt") - local_nonpersistent_flags+=("--promptInt=") - flags+=("--promptString=") - two_word_flags+=("--promptString") - two_word_flags+=("-p") - local_nonpersistent_flags+=("--promptString") - local_nonpersistent_flags+=("--promptString=") - local_nonpersistent_flags+=("-p") - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_forget() -{ - last_command="chezmoi2_forget" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_git() -{ - last_command="chezmoi2_git" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_help() -{ - last_command="chezmoi2_help" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_import() -{ - last_command="chezmoi2_import" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--exact") - flags+=("-x") - local_nonpersistent_flags+=("--exact") - local_nonpersistent_flags+=("-x") - flags+=("--include=") - two_word_flags+=("--include") - two_word_flags+=("-i") - local_nonpersistent_flags+=("--include") - local_nonpersistent_flags+=("--include=") - local_nonpersistent_flags+=("-i") - flags+=("--remove-destination") - flags+=("-r") - local_nonpersistent_flags+=("--remove-destination") - local_nonpersistent_flags+=("-r") - flags+=("--strip-components=") - two_word_flags+=("--strip-components") - local_nonpersistent_flags+=("--strip-components") - local_nonpersistent_flags+=("--strip-components=") - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_init() -{ - last_command="chezmoi2_init" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--apply") - flags+=("-a") - local_nonpersistent_flags+=("--apply") - local_nonpersistent_flags+=("-a") - flags+=("--depth=") - two_word_flags+=("--depth") - two_word_flags+=("-d") - local_nonpersistent_flags+=("--depth") - local_nonpersistent_flags+=("--depth=") - local_nonpersistent_flags+=("-d") - flags+=("--one-shot") - local_nonpersistent_flags+=("--one-shot") - flags+=("--purge") - flags+=("-p") - local_nonpersistent_flags+=("--purge") - local_nonpersistent_flags+=("-p") - flags+=("--purge-binary") - flags+=("-P") - local_nonpersistent_flags+=("--purge-binary") - local_nonpersistent_flags+=("-P") - flags+=("--skip-encrypted") - local_nonpersistent_flags+=("--skip-encrypted") - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_managed() -{ - last_command="chezmoi2_managed" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--include=") - two_word_flags+=("--include") - two_word_flags+=("-i") - local_nonpersistent_flags+=("--include") - local_nonpersistent_flags+=("--include=") - local_nonpersistent_flags+=("-i") - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_merge() -{ - last_command="chezmoi2_merge" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_purge() -{ - last_command="chezmoi2_purge" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--binary") - flags+=("-P") - local_nonpersistent_flags+=("--binary") - local_nonpersistent_flags+=("-P") - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_remove() -{ - last_command="chezmoi2_remove" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_secret_keyring_get() -{ - last_command="chezmoi2_secret_keyring_get" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--service=") - two_word_flags+=("--service") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--user=") - two_word_flags+=("--user") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_secret_keyring_set() -{ - last_command="chezmoi2_secret_keyring_set" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--service=") - two_word_flags+=("--service") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--user=") - two_word_flags+=("--user") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_secret_keyring() -{ - last_command="chezmoi2_secret_keyring" - - command_aliases=() - - commands=() - commands+=("get") - commands+=("set") - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--service=") - two_word_flags+=("--service") - flags+=("--user=") - two_word_flags+=("--user") - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_flag+=("--service=") - must_have_one_flag+=("--user=") - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_secret() -{ - last_command="chezmoi2_secret" - - command_aliases=() - - commands=() - commands+=("keyring") - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_source-path() -{ - last_command="chezmoi2_source-path" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_state_dump() -{ - last_command="chezmoi2_state_dump" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--format=") - two_word_flags+=("--format") - two_word_flags+=("-f") - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_state_reset() -{ - last_command="chezmoi2_state_reset" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_state() -{ - last_command="chezmoi2_state" - - command_aliases=() - - commands=() - commands+=("dump") - commands+=("reset") - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_status() -{ - last_command="chezmoi2_status" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--include=") - two_word_flags+=("--include") - two_word_flags+=("-i") - local_nonpersistent_flags+=("--include") - local_nonpersistent_flags+=("--include=") - local_nonpersistent_flags+=("-i") - flags+=("--recursive") - flags+=("-r") - local_nonpersistent_flags+=("--recursive") - local_nonpersistent_flags+=("-r") - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_unmanaged() -{ - last_command="chezmoi2_unmanaged" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_update() -{ - last_command="chezmoi2_update" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--apply") - flags+=("-a") - local_nonpersistent_flags+=("--apply") - local_nonpersistent_flags+=("-a") - flags+=("--include=") - two_word_flags+=("--include") - two_word_flags+=("-i") - local_nonpersistent_flags+=("--include") - local_nonpersistent_flags+=("--include=") - local_nonpersistent_flags+=("-i") - flags+=("--recursive") - flags+=("-r") - local_nonpersistent_flags+=("--recursive") - local_nonpersistent_flags+=("-r") - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_verify() -{ - last_command="chezmoi2_verify" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--include=") - two_word_flags+=("--include") - two_word_flags+=("-i") - local_nonpersistent_flags+=("--include") - local_nonpersistent_flags+=("--include=") - local_nonpersistent_flags+=("-i") - flags+=("--recursive") - flags+=("-r") - local_nonpersistent_flags+=("--recursive") - local_nonpersistent_flags+=("-r") - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi2_root_command() -{ - last_command="chezmoi2" - - command_aliases=() - - commands=() - commands+=("add") - if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then - command_aliases+=("manage") - aliashash["manage"]="add" - fi - commands+=("apply") - commands+=("archive") - commands+=("cat") - commands+=("cd") - commands+=("chattr") - commands+=("completion") - commands+=("data") - commands+=("diff") - commands+=("docs") - commands+=("doctor") - commands+=("dump") - commands+=("edit") - commands+=("edit-config") - commands+=("execute-template") - commands+=("forget") - if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then - command_aliases+=("unmanage") - aliashash["unmanage"]="forget" - fi - commands+=("git") - commands+=("help") - commands+=("import") - commands+=("init") - commands+=("managed") - commands+=("merge") - commands+=("purge") - commands+=("remove") - if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then - command_aliases+=("rm") - aliashash["rm"]="remove" - fi - commands+=("secret") - commands+=("source-path") - commands+=("state") - commands+=("status") - commands+=("unmanaged") - commands+=("update") - commands+=("verify") - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--cpu-profile=") - two_word_flags+=("--cpu-profile") - flags_with_completion+=("--cpu-profile") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--force") - flags+=("--keep-going") - flags+=("-k") - flags+=("--no-pager") - flags+=("--no-tty") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--use-builtin-git=") - two_word_flags+=("--use-builtin-git") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -__start_chezmoi2() -{ - local cur prev words cword - declare -A flaghash 2>/dev/null || : - declare -A aliashash 2>/dev/null || : - if declare -F _init_completion >/dev/null 2>&1; then - _init_completion -s || return - else - __chezmoi2_init_completion -n "=" || return - fi - - local c=0 - local flags=() - local two_word_flags=() - local local_nonpersistent_flags=() - local flags_with_completion=() - local flags_completion=() - local commands=("chezmoi2") - local must_have_one_flag=() - local must_have_one_noun=() - local has_completion_function - local last_command - local nouns=() - - __chezmoi2_handle_word -} - -if [[ $(type -t compopt) = "builtin" ]]; then - complete -o default -F __start_chezmoi2 chezmoi2 -else - complete -o default -o nospace -F __start_chezmoi2 chezmoi2 -fi - -# ex: ts=4 sw=4 et filetype=sh diff --git a/chezmoi2/completions/chezmoi2.fish b/chezmoi2/completions/chezmoi2.fish deleted file mode 100644 index 358a4a03d63..00000000000 --- a/chezmoi2/completions/chezmoi2.fish +++ /dev/null @@ -1,164 +0,0 @@ -# fish completion for chezmoi2 -*- shell-script -*- - -function __chezmoi2_debug - set file "$BASH_COMP_DEBUG_FILE" - if test -n "$file" - echo "$argv" >> $file - end -end - -function __chezmoi2_perform_completion - __chezmoi2_debug "Starting __chezmoi2_perform_completion with: $argv" - - set args (string split -- " " "$argv") - set lastArg "$args[-1]" - - __chezmoi2_debug "args: $args" - __chezmoi2_debug "last arg: $lastArg" - - set emptyArg "" - if test -z "$lastArg" - __chezmoi2_debug "Setting emptyArg" - set emptyArg \"\" - end - __chezmoi2_debug "emptyArg: $emptyArg" - - if not type -q "$args[1]" - # This can happen when "complete --do-complete chezmoi2" is called when running this script. - __chezmoi2_debug "Cannot find $args[1]. No completions." - return - end - - set requestComp "$args[1] __complete $args[2..-1] $emptyArg" - __chezmoi2_debug "Calling $requestComp" - - set results (eval $requestComp 2> /dev/null) - set comps $results[1..-2] - set directiveLine $results[-1] - - # For Fish, when completing a flag with an = (e.g., <program> -n=<TAB>) - # completions must be prefixed with the flag - set flagPrefix (string match -r -- '-.*=' "$lastArg") - - __chezmoi2_debug "Comps: $comps" - __chezmoi2_debug "DirectiveLine: $directiveLine" - __chezmoi2_debug "flagPrefix: $flagPrefix" - - for comp in $comps - printf "%s%s\n" "$flagPrefix" "$comp" - end - - printf "%s\n" "$directiveLine" -end - -# This function does three things: -# 1- Obtain the completions and store them in the global __chezmoi2_comp_results -# 2- Set the __chezmoi2_comp_do_file_comp flag if file completion should be performed -# and unset it otherwise -# 3- Return true if the completion results are not empty -function __chezmoi2_prepare_completions - # Start fresh - set --erase __chezmoi2_comp_do_file_comp - set --erase __chezmoi2_comp_results - - # Check if the command-line is already provided. This is useful for testing. - if not set --query __chezmoi2_comp_commandLine - # Use the -c flag to allow for completion in the middle of the line - set __chezmoi2_comp_commandLine (commandline -c) - end - __chezmoi2_debug "commandLine is: $__chezmoi2_comp_commandLine" - - set results (__chezmoi2_perform_completion "$__chezmoi2_comp_commandLine") - set --erase __chezmoi2_comp_commandLine - __chezmoi2_debug "Completion results: $results" - - if test -z "$results" - __chezmoi2_debug "No completion, probably due to a failure" - # Might as well do file completion, in case it helps - set --global __chezmoi2_comp_do_file_comp 1 - return 1 - end - - set directive (string sub --start 2 $results[-1]) - set --global __chezmoi2_comp_results $results[1..-2] - - __chezmoi2_debug "Completions are: $__chezmoi2_comp_results" - __chezmoi2_debug "Directive is: $directive" - - set shellCompDirectiveError 1 - set shellCompDirectiveNoSpace 2 - set shellCompDirectiveNoFileComp 4 - set shellCompDirectiveFilterFileExt 8 - set shellCompDirectiveFilterDirs 16 - - if test -z "$directive" - set directive 0 - end - - set compErr (math (math --scale 0 $directive / $shellCompDirectiveError) % 2) - if test $compErr -eq 1 - __chezmoi2_debug "Received error directive: aborting." - # Might as well do file completion, in case it helps - set --global __chezmoi2_comp_do_file_comp 1 - return 1 - end - - set filefilter (math (math --scale 0 $directive / $shellCompDirectiveFilterFileExt) % 2) - set dirfilter (math (math --scale 0 $directive / $shellCompDirectiveFilterDirs) % 2) - if test $filefilter -eq 1; or test $dirfilter -eq 1 - __chezmoi2_debug "File extension filtering or directory filtering not supported" - # Do full file completion instead - set --global __chezmoi2_comp_do_file_comp 1 - return 1 - end - - set nospace (math (math --scale 0 $directive / $shellCompDirectiveNoSpace) % 2) - set nofiles (math (math --scale 0 $directive / $shellCompDirectiveNoFileComp) % 2) - - __chezmoi2_debug "nospace: $nospace, nofiles: $nofiles" - - # Important not to quote the variable for count to work - set numComps (count $__chezmoi2_comp_results) - __chezmoi2_debug "numComps: $numComps" - - if test $numComps -eq 1; and test $nospace -ne 0 - # To support the "nospace" directive we trick the shell - # by outputting an extra, longer completion. - __chezmoi2_debug "Adding second completion to perform nospace directive" - set --append __chezmoi2_comp_results $__chezmoi2_comp_results[1]. - end - - if test $numComps -eq 0; and test $nofiles -eq 0 - __chezmoi2_debug "Requesting file completion" - set --global __chezmoi2_comp_do_file_comp 1 - end - - # If we don't want file completion, we must return true even if there - # are no completions found. This is because fish will perform the last - # completion command, even if its condition is false, if no other - # completion command was triggered - return (not set --query __chezmoi2_comp_do_file_comp) -end - -# Since Fish completions are only loaded once the user triggers them, we trigger them ourselves -# so we can properly delete any completions provided by another script. -# The space after the the program name is essential to trigger completion for the program -# and not completion of the program name itself. -complete --do-complete "chezmoi2 " > /dev/null 2>&1 -# Using '> /dev/null 2>&1' since '&>' is not supported in older versions of fish. - -# Remove any pre-existing completions for the program since we will be handling all of them. -complete -c chezmoi2 -e - -# The order in which the below two lines are defined is very important so that __chezmoi2_prepare_completions -# is called first. It is __chezmoi2_prepare_completions that sets up the __chezmoi2_comp_do_file_comp variable. -# -# This completion will be run second as complete commands are added FILO. -# It triggers file completion choices when __chezmoi2_comp_do_file_comp is set. -complete -c chezmoi2 -n 'set --query __chezmoi2_comp_do_file_comp' - -# This completion will be run first as complete commands are added FILO. -# The call to __chezmoi2_prepare_completions will setup both __chezmoi2_comp_results and __chezmoi2_comp_do_file_comp. -# It provides the program's completion choices. -complete -c chezmoi2 -n '__chezmoi2_prepare_completions' -f -a '$__chezmoi2_comp_results' - diff --git a/chezmoi2/completions/chezmoi2.ps1 b/chezmoi2/completions/chezmoi2.ps1 deleted file mode 100644 index 6baa2f6d56c..00000000000 --- a/chezmoi2/completions/chezmoi2.ps1 +++ /dev/null @@ -1,225 +0,0 @@ -# powershell completion for chezmoi2 -*- shell-script -*- - -function __chezmoi2_debug { - if ($env:BASH_COMP_DEBUG_FILE) { - "$args" | Out-File -Append -FilePath "$env:BASH_COMP_DEBUG_FILE" - } -} - -filter __chezmoi2_escapeStringWithSpecialChars { - $_ -replace '\s|#|@|\$|;|,|''|\{|\}|\(|\)|"|`|\||<|>|&','`$&' -} - -Register-ArgumentCompleter -CommandName 'chezmoi2' -ScriptBlock { - param( - $WordToComplete, - $CommandAst, - $CursorPosition - ) - - # Get the current command line and convert into a string - $Command = $CommandAst.CommandElements - $Command = "$Command" - - __chezmoi2_debug "" - __chezmoi2_debug "========= starting completion logic ==========" - __chezmoi2_debug "WordToComplete: $WordToComplete Command: $Command CursorPosition: $CursorPosition" - - # The user could have moved the cursor backwards on the command-line. - # We need to trigger completion from the $CursorPosition location, so we need - # to truncate the command-line ($Command) up to the $CursorPosition location. - # Make sure the $Command is longer then the $CursorPosition before we truncate. - # This happens because the $Command does not include the last space. - if ($Command.Length -gt $CursorPosition) { - $Command=$Command.Substring(0,$CursorPosition) - } - __chezmoi2_debug "Truncated command: $Command" - - $ShellCompDirectiveError=1 - $ShellCompDirectiveNoSpace=2 - $ShellCompDirectiveNoFileComp=4 - $ShellCompDirectiveFilterFileExt=8 - $ShellCompDirectiveFilterDirs=16 - - # Prepare the command to request completions for the program. - # Split the command at the first space to separate the program and arguments. - $Program,$Arguments = $Command.Split(" ",2) - $RequestComp="$Program __completeNoDesc $Arguments" - __chezmoi2_debug "RequestComp: $RequestComp" - - # we cannot use $WordToComplete because it - # has the wrong values if the cursor was moved - # so use the last argument - if ($WordToComplete -ne "" ) { - $WordToComplete = $Arguments.Split(" ")[-1] - } - __chezmoi2_debug "New WordToComplete: $WordToComplete" - - - # Check for flag with equal sign - $IsEqualFlag = ($WordToComplete -Like "--*=*" ) - if ( $IsEqualFlag ) { - __chezmoi2_debug "Completing equal sign flag" - # Remove the flag part - $Flag,$WordToComplete = $WordToComplete.Split("=",2) - } - - if ( $WordToComplete -eq "" -And ( -Not $IsEqualFlag )) { - # If the last parameter is complete (there is a space following it) - # We add an extra empty parameter so we can indicate this to the go method. - __chezmoi2_debug "Adding extra empty parameter" - # We need to use `"`" to pass an empty argument a "" or '' does not work!!! - $RequestComp="$RequestComp" + ' `"`"' - } - - __chezmoi2_debug "Calling $RequestComp" - #call the command store the output in $out and redirect stderr and stdout to null - # $Out is an array contains each line per element - Invoke-Expression -OutVariable out "$RequestComp" 2>&1 | Out-Null - - - # get directive from last line - [int]$Directive = $Out[-1].TrimStart(':') - if ($Directive -eq "") { - # There is no directive specified - $Directive = 0 - } - __chezmoi2_debug "The completion directive is: $Directive" - - # remove directive (last element) from out - $Out = $Out | Where-Object { $_ -ne $Out[-1] } - __chezmoi2_debug "The completions are: $Out" - - if (($Directive -band $ShellCompDirectiveError) -ne 0 ) { - # Error code. No completion. - __chezmoi2_debug "Received error from custom completion go code" - return - } - - $Longest = 0 - $Values = $Out | ForEach-Object { - #Split the output in name and description - $Name, $Description = $_.Split("`t",2) - __chezmoi2_debug "Name: $Name Description: $Description" - - # Look for the longest completion so that we can format things nicely - if ($Longest -lt $Name.Length) { - $Longest = $Name.Length - } - - # Set the description to a one space string if there is none set. - # This is needed because the CompletionResult does not accept an empty string as argument - if (-Not $Description) { - $Description = " " - } - @{Name="$Name";Description="$Description"} - } - - - $Space = " " - if (($Directive -band $ShellCompDirectiveNoSpace) -ne 0 ) { - # remove the space here - __chezmoi2_debug "ShellCompDirectiveNoSpace is called" - $Space = "" - } - - if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) { - __chezmoi2_debug "ShellCompDirectiveNoFileComp is called" - - if ($Values.Length -eq 0) { - # Just print an empty string here so the - # shell does not start to complete paths. - # We cannot use CompletionResult here because - # it does not accept an empty string as argument. - "" - return - } - } - - if ((($Directive -band $ShellCompDirectiveFilterFileExt) -ne 0 ) -or - (($Directive -band $ShellCompDirectiveFilterDirs) -ne 0 )) { - __chezmoi2_debug "ShellCompDirectiveFilterFileExt ShellCompDirectiveFilterDirs are not supported" - - # return here to prevent the completion of the extensions - return - } - - $Values = $Values | Where-Object { - # filter the result - $_.Name -like "$WordToComplete*" - - # Join the flag back if we have a equal sign flag - if ( $IsEqualFlag ) { - __chezmoi2_debug "Join the equal sign flag back to the completion value" - $_.Name = $Flag + "=" + $_.Name - } - } - - # Get the current mode - $Mode = (Get-PSReadLineKeyHandler | Where-Object {$_.Key -eq "Tab" }).Function - __chezmoi2_debug "Mode: $Mode" - - $Values | ForEach-Object { - - # store temporay because switch will overwrite $_ - $comp = $_ - - # PowerShell supports three different completion modes - # - TabCompleteNext (default windows style - on each key press the next option is displayed) - # - Complete (works like bash) - # - MenuComplete (works like zsh) - # You set the mode with Set-PSReadLineKeyHandler -Key Tab -Function <mode> - - # CompletionResult Arguments: - # 1) CompletionText text to be used as the auto completion result - # 2) ListItemText text to be displayed in the suggestion list - # 3) ResultType type of completion result - # 4) ToolTip text for the tooltip with details about the object - - switch ($Mode) { - - # bash like - "Complete" { - - if ($Values.Length -eq 1) { - __chezmoi2_debug "Only one completion left" - - # insert space after value - [System.Management.Automation.CompletionResult]::new($($comp.Name | __chezmoi2_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)") - - } else { - # Add the proper number of spaces to align the descriptions - while($comp.Name.Length -lt $Longest) { - $comp.Name = $comp.Name + " " - } - - # Check for empty description and only add parentheses if needed - if ($($comp.Description) -eq " " ) { - $Description = "" - } else { - $Description = " ($($comp.Description))" - } - - [System.Management.Automation.CompletionResult]::new("$($comp.Name)$Description", "$($comp.Name)$Description", 'ParameterValue', "$($comp.Description)") - } - } - - # zsh like - "MenuComplete" { - # insert space after value - # MenuComplete will automatically show the ToolTip of - # the highlighted value at the bottom of the suggestions. - [System.Management.Automation.CompletionResult]::new($($comp.Name | __chezmoi2_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)") - } - - # TabCompleteNext and in case we get something unknown - Default { - # Like MenuComplete but we don't want to add a space here because - # the user need to press space anyway to get the completion. - # Description will not be shown because thats not possible with TabCompleteNext - [System.Management.Automation.CompletionResult]::new($($comp.Name | __chezmoi2_escapeStringWithSpecialChars), "$($comp.Name)", 'ParameterValue', "$($comp.Description)") - } - } - - } -} diff --git a/chezmoi2/completions/chezmoi2.zsh b/chezmoi2/completions/chezmoi2.zsh deleted file mode 100644 index a7ce25d09dd..00000000000 --- a/chezmoi2/completions/chezmoi2.zsh +++ /dev/null @@ -1,159 +0,0 @@ -#compdef _chezmoi2 chezmoi2 - -# zsh completion for chezmoi2 -*- shell-script -*- - -__chezmoi2_debug() -{ - local file="$BASH_COMP_DEBUG_FILE" - if [[ -n ${file} ]]; then - echo "$*" >> "${file}" - fi -} - -_chezmoi2() -{ - local shellCompDirectiveError=1 - local shellCompDirectiveNoSpace=2 - local shellCompDirectiveNoFileComp=4 - local shellCompDirectiveFilterFileExt=8 - local shellCompDirectiveFilterDirs=16 - - local lastParam lastChar flagPrefix requestComp out directive compCount comp lastComp - local -a completions - - __chezmoi2_debug "\n========= starting completion logic ==========" - __chezmoi2_debug "CURRENT: ${CURRENT}, words[*]: ${words[*]}" - - # The user could have moved the cursor backwards on the command-line. - # We need to trigger completion from the $CURRENT location, so we need - # to truncate the command-line ($words) up to the $CURRENT location. - # (We cannot use $CURSOR as its value does not work when a command is an alias.) - words=("${=words[1,CURRENT]}") - __chezmoi2_debug "Truncated words[*]: ${words[*]}," - - lastParam=${words[-1]} - lastChar=${lastParam[-1]} - __chezmoi2_debug "lastParam: ${lastParam}, lastChar: ${lastChar}" - - # For zsh, when completing a flag with an = (e.g., chezmoi2 -n=<TAB>) - # completions must be prefixed with the flag - setopt local_options BASH_REMATCH - if [[ "${lastParam}" =~ '-.*=' ]]; then - # We are dealing with a flag with an = - flagPrefix="-P ${BASH_REMATCH}" - fi - - # Prepare the command to obtain completions - requestComp="${words[1]} __complete ${words[2,-1]}" - if [ "${lastChar}" = "" ]; then - # If the last parameter is complete (there is a space following it) - # We add an extra empty parameter so we can indicate this to the go completion code. - __chezmoi2_debug "Adding extra empty parameter" - requestComp="${requestComp} \"\"" - fi - - __chezmoi2_debug "About to call: eval ${requestComp}" - - # Use eval to handle any environment variables and such - out=$(eval ${requestComp} 2>/dev/null) - __chezmoi2_debug "completion output: ${out}" - - # Extract the directive integer following a : from the last line - local lastLine - while IFS='\n' read -r line; do - lastLine=${line} - done < <(printf "%s\n" "${out[@]}") - __chezmoi2_debug "last line: ${lastLine}" - - if [ "${lastLine[1]}" = : ]; then - directive=${lastLine[2,-1]} - # Remove the directive including the : and the newline - local suffix - (( suffix=${#lastLine}+2)) - out=${out[1,-$suffix]} - else - # There is no directive specified. Leave $out as is. - __chezmoi2_debug "No directive found. Setting do default" - directive=0 - fi - - __chezmoi2_debug "directive: ${directive}" - __chezmoi2_debug "completions: ${out}" - __chezmoi2_debug "flagPrefix: ${flagPrefix}" - - if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then - __chezmoi2_debug "Completion received error. Ignoring completions." - return - fi - - compCount=0 - while IFS='\n' read -r comp; do - if [ -n "$comp" ]; then - # If requested, completions are returned with a description. - # The description is preceded by a TAB character. - # For zsh's _describe, we need to use a : instead of a TAB. - # We first need to escape any : as part of the completion itself. - comp=${comp//:/\\:} - - local tab=$(printf '\t') - comp=${comp//$tab/:} - - ((compCount++)) - __chezmoi2_debug "Adding completion: ${comp}" - completions+=${comp} - lastComp=$comp - fi - done < <(printf "%s\n" "${out[@]}") - - if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then - # File extension filtering - local filteringCmd - filteringCmd='_files' - for filter in ${completions[@]}; do - if [ ${filter[1]} != '*' ]; then - # zsh requires a glob pattern to do file filtering - filter="\*.$filter" - fi - filteringCmd+=" -g $filter" - done - filteringCmd+=" ${flagPrefix}" - - __chezmoi2_debug "File filtering command: $filteringCmd" - _arguments '*:filename:'"$filteringCmd" - elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then - # File completion for directories only - local subDir - subdir="${completions[1]}" - if [ -n "$subdir" ]; then - __chezmoi2_debug "Listing directories in $subdir" - pushd "${subdir}" >/dev/null 2>&1 - else - __chezmoi2_debug "Listing directories in ." - fi - - _arguments '*:dirname:_files -/'" ${flagPrefix}" - if [ -n "$subdir" ]; then - popd >/dev/null 2>&1 - fi - elif [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ] && [ ${compCount} -eq 1 ]; then - __chezmoi2_debug "Activating nospace." - # We can use compadd here as there is no description when - # there is only one completion. - compadd -S '' "${lastComp}" - elif [ ${compCount} -eq 0 ]; then - if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then - __chezmoi2_debug "deactivating file completion" - else - # Perform file completion - __chezmoi2_debug "activating file completion" - _arguments '*:filename:_files'" ${flagPrefix}" - fi - else - _describe "completions" completions $(echo $flagPrefix) - fi -} - -# don't run the completion function when being source-ed or eval-ed -if [ "$funcstack[1]" = "_chezmoi2" ]; then - _chezmoi2 -fi diff --git a/chezmoi2/docs/CHANGES.md b/chezmoi2/docs/CHANGES.md deleted file mode 100644 index 90c496c9b08..00000000000 --- a/chezmoi2/docs/CHANGES.md +++ /dev/null @@ -1,49 +0,0 @@ -## Changes in v2, already done - -General: -- `--recursive` is default for some commands, notably `chezmoi add` -- only diff format is git -- remove hg support -- remove source command (use git instead) -- `--include` option to many commands -- errors output to stderr, not stdout -- `--force` now global -- `--output` now global -- diff includes scripts -- archive includes scripts -- `encrypt` -> `encrypted` in chattr -- `--format` now global, don't use toml for dump -- `y`, `yes`, `on`, `n`, `no`, `off` recognized as bools -- order for `merge` is now dest, target, source -- No more `--prompt` to `chezmoi edit` -- `--keep-going` global -- `chezmoi init` guesses your repo URL if you use github.com and dotfiles -- `edit.command` and `edit.args` settable in config file, overrides `$EDITOR` / `$VISUAL` -- state data has changed, `run_once_` scripts will be run again -- `init` gets `--depth` and `--purge` -- `run_once_` scripts with same content but different names will only be run once -- global `--use-builtin-git` -- added `.chezmoi.version` template var -- added `gitHubKeys` template func uses `CHEZMOI_GITHUB_ACCESS_TOKEN`, `GITHUB_ACCESS_TOKEN`, and `GITHUB_TOKEN` first non-empty -- template data on a best-effort basis, errors ignored -- `chezmoi status` -- `chezmoi apply` no longer overwrites by default -- `chezmoi init --one-shot` -- new type `--create` -- `chezmoi archive --format=zip` -- `before_` and `after_` script attributes change script order, scripts now run during -- new `fqdnHostname` template var (UNIX only for now) -- age encryption support - -{{ range (gitHubKeys "twpayne") -}} -{{ .Key }} -{{ end -}} - -Config file: -- rename `sourceVCS` to `git` -- use `gpg.recipient` instead of `gpgRecipient` -- rename `genericSecret` to `secret` -- rename `homedir` to `homeDir` -- add `encryption` (currently `age` or `gpg`) -- apply `--ignore-encrypted` -- apply `--source-paths` diff --git a/chezmoi2/docs/REFERENCE.md b/chezmoi2/docs/REFERENCE.md deleted file mode 100644 index 78a55437ca4..00000000000 --- a/chezmoi2/docs/REFERENCE.md +++ /dev/null @@ -1,1586 +0,0 @@ -# chezmoi Reference Manual - -Manage your dotfiles securely across multiple machines. - -<!--- toc ---> -* [Concepts](#concepts) -* [Global command line flags](#global-command-line-flags) - * [`--color` *value*](#--color-value) - * [`-c`, `--config` *filename*](#-c---config-filename) - * [`--cpu-profile` *filename*](#--cpu-profile-filename) - * [`--debug`](#--debug) - * [`-D`, `--destination` *directory*](#-d---destination-directory) - * [`-n`, `--dry-run`](#-n---dry-run) - * [`--force`](#--force) - * [`-h`, `--help`](#-h---help) - * [`-k`, `--keep-going`](#-k---keep-going) - * [`--no-pager`](#--no-pager) - * [`--no-tty`](#--no-tty) - * [`-o`, `--output` *filename*](#-o---output-filename) - * [`-r`. `--remove`](#-r---remove) - * [`-S`, `--source` *directory*](#-s---source-directory) - * [`--use-builtin-git` *value*](#--use-builtin-git-value) - * [`-v`, `--verbose`](#-v---verbose) - * [`--version`](#--version) -* [Common command line flags](#common-command-line-flags) - * [`--format` *format*](#--format-format) - * [`--include` *types*](#--include-types) - * [`-r`, `--recursive`](#-r---recursive) -* [Configuration file](#configuration-file) - * [Variables](#variables) - * [Examples](#examples) -* [Source state attributes](#source-state-attributes) -* [Target types](#target-types) - * [Files](#files) - * [Directories](#directories) - * [Symbolic links](#symbolic-links) - * [Scripts](#scripts) -* [Special files and directories](#special-files-and-directories) - * [`.chezmoi.<format>.tmpl`](#chezmoiformattmpl) - * [`.chezmoiignore`](#chezmoiignore) - * [`.chezmoiremove`](#chezmoiremove) - * [`.chezmoitemplates`](#chezmoitemplates) - * [`.chezmoiversion`](#chezmoiversion) -* [Commands](#commands) - * [`add` *targets*](#add-targets) - * [`apply` [*targets*]](#apply-targets) - * [`archive`](#archive) - * [`cat` *targets*](#cat-targets) - * [`cd`](#cd) - * [`chattr` *attributes* *targets*](#chattr-attributes-targets) - * [`completion` *shell*](#completion-shell) - * [`data`](#data) - * [`diff` [*targets*]](#diff-targets) - * [`docs` [*regexp*]](#docs-regexp) - * [`doctor`](#doctor) - * [`dump` [*targets*]](#dump-targets) - * [`edit` [*targets*]](#edit-targets) - * [`edit-config`](#edit-config) - * [`execute-template` [*templates*]](#execute-template-templates) - * [`forget` *targets*](#forget-targets) - * [`git` [*arguments*]](#git-arguments) - * [`help` *command*](#help-command) - * [`init` [*repo*]](#init-repo) - * [`import` *filename*](#import-filename) - * [`manage` *targets*](#manage-targets) - * [`managed`](#managed) - * [`merge` *targets*](#merge-targets) - * [`purge`](#purge) - * [`remove` *targets*](#remove-targets) - * [`rm` *targets*](#rm-targets) - * [`secret`](#secret) - * [`source-path` [*targets*]](#source-path-targets) - * [`state`](#state) - * [`status`](#status) - * [`unmanage` *targets*](#unmanage-targets) - * [`unmanaged`](#unmanaged) - * [`update`](#update) - * [`upgrade`](#upgrade) - * [`verify` [*targets*]](#verify-targets) -* [Editor configuration](#editor-configuration) -* [Umask configuration](#umask-configuration) -* [Template execution](#template-execution) -* [Template variables](#template-variables) -* [Template functions](#template-functions) - * [`bitwarden` [*args*]](#bitwarden-args) - * [`bitwardenAttachment` *filename* *itemid*](#bitwardenattachment-filename-itemid) - * [`bitwardenFields` [*args*]](#bitwardenfields-args) - * [`gitHubKeys` *user*](#githubkeys-user) - * [`gopass` *gopass-name*](#gopass-gopass-name) - * [`include` *filename*](#include-filename) - * [`ioreg`](#ioreg) - * [`joinPath` *elements*](#joinpath-elements) - * [`keepassxc` *entry*](#keepassxc-entry) - * [`keepassxcAttribute` *entry* *attribute*](#keepassxcattribute-entry-attribute) - * [`keyring` *service* *user*](#keyring-service-user) - * [`lastpass` *id*](#lastpass-id) - * [`lastpassRaw` *id*](#lastpassraw-id) - * [`lookPath` *file*](#lookpath-file) - * [`onepassword` *uuid* [*vault-uuid*]](#onepassword-uuid-vault-uuid) - * [`onepasswordDocument` *uuid* [*vault-uuid*]](#onepassworddocument-uuid-vault-uuid) - * [`onepasswordDetailsFields` *uuid* [*vault-uuid*]](#onepassworddetailsfields-uuid-vault-uuid) - * [`pass` *pass-name*](#pass-pass-name) - * [`promptBool` *prompt*](#promptbool-prompt) - * [`promptInt` *prompt*](#promptint-prompt) - * [`promptString` *prompt*](#promptstring-prompt) - * [`secret` [*args*]](#secret-args) - * [`secretJSON` [*args*]](#secretjson-args) - * [`stat` *name*](#stat-name) - * [`vault` *key*](#vault-key) - -## Concepts - -chezmoi evaluates the source state for the current machine and then updates the -destination directory, where: - -* The *source state* declares the desired state of your home directory, - including templates and machine-specific configuration. - -* The *source directory* is where chezmoi stores the source state, by default - `~/.local/share/chezmoi`. - -* The *target state* is the source state computed for the current machine. - -* The *destination directory* is the directory that chezmoi manages, by default - `~`, your home directory. - -* A *target* is a file, directory, or symlink in the destination directory. - -* The *destination state* is the current state of all the targets in the - destination directory. - -* The *config file* contains machine-specific configuration, by default it is - `~/.config/chezmoi/chezmoi.toml`. - -## Global command line flags - -Command line flags override any values set in the configuration file. - -### `--color` *value* - -Colorize diffs, *value* can be `on`, `off`, `auto`, or any boolean-like value -recognized by `parseBool`. The default is `auto` which will colorize diffs only -if the the environment variable `NO_COLOR` is not set and stdout is a terminal. - -### `-c`, `--config` *filename* - -Read the configuration from *filename*. - -### `--cpu-profile` *filename* - -Write a [CPU profile](https://blog.golang.org/pprof) to *filename*. - -### `--debug` - -Log information helpful for debugging. - -### `-D`, `--destination` *directory* - -Use *directory* as the destination directory. - -### `-n`, `--dry-run` - -Set dry run mode. In dry run mode, the destination directory is never modified. -This is most useful in combination with the `-v` (verbose) flag to print changes -that would be made without making them. - -### `--force` - -Make changes without prompting. - -### `-h`, `--help` - -Print help. - -### `-k`, `--keep-going` - -Keep going as far as possible after a encountering an error. - -### `--no-pager` - -Do not use the pager. - -### `--no-tty` - -Do not attempt to get a TTY to read input and passwords. Instead, read them from -stdin. - -### `-o`, `--output` *filename* - -Write the output to *filename* instead of stdout. - -### `-r`. `--remove` - -Also remove targets according to `.chezmoiremove`. - -### `-S`, `--source` *directory* - -Use *directory* as the source directory. - -### `--use-builtin-git` *value* - -Use chezmoi's builtin git instead of `git.command` for the `init` and `update` -commands. *value* can be `on`, `off`, `auto`, or any boolean-like value -recognized by `parseBool`. The default is `auto` which will only use the builtin -git if `git.command` cannot be found in `$PATH`. - -### `-v`, `--verbose` - -Set verbose mode. In verbose mode, chezmoi prints the changes that it is making -as approximate shell commands, and any differences in files between the target -state and the destination set are printed as unified diffs. - -### `--version` - -Print the version of chezmoi, the commit at which it was built, and the build -timestamp. - -## Common command line flags - -The following flags apply to multiple commands where they are relevant. - -### `--format` *format* - -Set the output format. *format* can be `json` or `yaml`. - -### `--include` *types* - -Only operate on target state entries of type *types*. *types* is a -comma-separated list of target states (`all`, `dirs`, `files`, `remove`, -`scripts`, `symlinks`) and can be excluded by preceeding them with a `!`. For -example, `--include=all,!scripts` will cause the command to apply to all target -state entries except scripts. - -### `-r`, `--recursive` - -Recurse into subdirectories, `true` by default. - -## Configuration file - -chezmoi searches for its configuration file according to the [XDG Base Directory -Specification](https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html) -and supports all formats supported by -[`github.com/spf13/viper`](https://github.com/spf13/viper), namely -[JSON](https://www.json.org/json-en.html), -[TOML](https://github.com/toml-lang/toml), [YAML](https://yaml.org/), macOS -property file format, and [HCL](https://github.com/hashicorp/hcl). The basename -of the config file is `chezmoi`, and the first config file found is used. - -### Variables - -The following configuration variables are available: - -| Section | Variable | Type | Default value | Description | -| ------------- | ----------------- | -------- | ------------------------- | ------------------------------------------------------ | -| Top level | `color` | string | `auto` | Colorize output | -| | `data` | any | *none* | Template data | -| | `destDir` | string | `~` | Destination directory | -| | `encryption` | string | *none* | Encryption tool, either `age` or `gpg` | -| | `format` | string | `json` | Format for data output, either `json` or `yaml` | -| | `remove` | bool | `false` | Remove targets | -| | `sourceDir` | string | `~/.local/share/chezmoi` | Source directory | -| | `umask` | int | *from system* | Umask | -| | `useBuiltinGit` | string | `auto` | Use builtin git if `git` command is not found in $PATH | -| `age` | `args` | []string | *none* | Extra args to age CLI command | -| | `command` | string | `age` | age CLI command | -| | `identity` | string | *none* | age identity file | -| | `identities` | []string | *none* | age identity files | -| | `recipient` | string | *none* | age recipient | -| | `recipients` | []string | *none* | age recipients | -| | `recipientsFile` | []string | *none* | age recipients file | -| | `recipientsFiles` | []string | *none* | age receipients files | -| | `suffix` | string | `.age` | Suffix appended to age-encrypted files | -| `bitwarden` | `command` | string | `bw` | Bitwarden CLI command | -| `cd` | `args` | []string | *none* | Extra args to shell in `cd` command | -| | `command` | string | *none* | Shell to run in `cd` command | -| `diff` | `pager` | string | `$PAGER` / `less` | Pager | -| `edit` | `args` | []string | *none* | Extra args to edit command | -| | `command` | string | `$EDITOR` / `$VISUAL` | Edit command | -| `secret` | `command` | string | *none* | Generic secret command | -| `git` | `autoAdd ` | bool | `false` | Add changes to the source state after any change | -| | `autoCommit` | bool | `false` | Commit changes to the source state after any change | -| | `autoPush` | bool | `false` | Push changes to the source state after any change | -| | `command` | string | `git` | Source version control system | -| `gopass` | `command` | string | `gopass` | gopass CLI command | -| `gpg` | `args` | []string | *none* | Extra args to GPG CLI command | -| | `command` | string | `gpg` | GPG CLI command | -| | `recipient` | string | *none* | GPG recipient | -| | `suffix` | string | `.asc` | Suffix appended to GPG-encrypted files | -| | `symmetric` | bool | `false` | Use symmetric GPG encryption | -| `keepassxc` | `args` | []string | *none* | Extra args to KeePassXC CLI command | -| | `command` | string | `keepassxc-cli` | KeePassXC CLI command | -| | `database` | string | *none* | KeePassXC database | -| `lastpass` | `command` | string | `lpass` | Lastpass CLI command | -| `merge` | `args` | []string | *none* | Extra args to 3-way merge command | -| | `command` | string | `vimdiff` | 3-way merge command | -| `onepassword` | `cache` | bool | `true` | Enable optional caching provided by `op` | -| | `command` | string | `op` | 1Password CLI command | -| `pass` | `command` | string | `pass` | Pass CLI command | -| `template` | `options` | []string | `["missingkey=error"]` | Template options | -| `vault` | `command` | string | `vault` | Vault CLI command | - -### Examples - -#### JSON - -```json -{ - "sourceDir": "/home/user/.dotfiles", - "git": { - "autoPush": true - } -} -``` - -#### TOML - -```toml -sourceDir = "/home/user/.dotfiles" -[git] - autoPush = true -``` - -#### YAML - -```yaml -sourceDir: /home/user/.dotfiles -git: - autoPush: true -``` - -## Source state attributes - -chezmoi stores the source state of files, symbolic links, and directories in -regular files and directories in the source directory (`~/.local/share/chezmoi` -by default). This location can be overridden with the `-S` flag or by giving a -value for `sourceDir` in `~/.config/chezmoi/chezmoi.toml`. Some state is -encoded in the source names. chezmoi ignores all files and directories in the -source directory that begin with a `.`. The following prefixes and suffixes are -special, and are collectively referred to as "attributes": - -| Prefix | Effect | -| ------------ | ------------------------------------------------------------------------------ | -| `after_` | Run script after updating the destination. | -| `before_` | Run script before updating the desintation. | -| `create_` | Ensure that the file exists, and create it with contents if it does not. | -| `dot_` | Rename to use a leading dot, e.g. `dot_foo` becomes `.foo`. | -| `empty_` | Ensure the file exists, even if is empty. By default, empty files are removed. | -| `encrypted_` | Encrypt the file in the source state. | -| `exact_` | Remove anything not managed by chezmoi. | -| `executable_`| Add executable permissions to the target file. | -| `modify_` | Treat the contents as a script that modifies an existing file. | -| `once_` | Run script once. | -| `private_` | Remove all group and world permissions from the target file or directory. | -| `run_` | Treat the contents as a script to run. | -| `symlink_` | Create a symlink instead of a regular file. | - -| Suffix | Effect | -| ------- | ---------------------------------------------------- | -| `.tmpl` | Treat the contents of the source file as a template. | - -The order of prefixes is important, the order is `run_`, `create_`, `modify_`, -`before_`, `after_`, `exact_`, `private_`, `empty_`, `executable_`, `symlink_`, -`once_`, `dot_`. - -Different target types allow different prefixes and suffixes: - -| Target type | Allowed prefixes | Allowed suffixes | -| ------------- | --------------------------------------------------------------------- | ---------------- | -| Directory | `exact_`, `private_`, `dot_` | *none* | -| Regular file | `encrypted_`, `private_`, `executable_`, `dot_` | `.tmpl` | -| Create file | `create_`, `encrypted_`, `private_`, `executable_`, `dot_` | `.tmpl` | -| Modify file | `modify_`, `encrypted_`, `private_`, `executable_`, `dot_` | `.tmpl` | -| Script | `run_`, `once_`, `before_` or `after_` | `.tmpl` | -| Symbolic link | `symlink_`, `dot_`, | `.tmpl` | - -## Target types - -chezmoi will create, update, and delete files, directories, and symbolic links -in the destination directory, and run scripts. chezmoi deterministically -performs actions in ASCII order of their target name. For example, given a file -`dot_a`, a script `run_z`, and a directory `exact_dot_c`, chezmoi will first -create `.a`, create `.c`, and then execute `run_z`. - -### Files - -Files are represented by regular files in the source state. The `encrypted_` -attribute determines whether the file in the source state is encrypted. The -`executable_` attribute will set the executable bits when the file is written to -the target state, and the `private_` attribute will clear all group and world -permissions. Files with the `.tmpl` suffix will be interpreted as templates. - -#### Create file - -Files with the `create_` prefix will be created in the target state with the -contents of the file in the source state if they do not already exist. If the -file in the destination state already exists then its contents will be left -unchanged. - -#### Modify file - -Files with the `modify_` prefix are treated as scripts that modify an existing -file. The contents of the existing file (which maybe empty if the existing file -does not exist or is empty) are passed to the script's standard input, and the -new contents are read from the scripts standard output. - -### Directories - -Directories are represented by regular directories in the source state. The -`exact_` attribute causes chezmoi to remove any entries in the target state that -are not explicitly specified in the source state, and the `private_` attribute -causes chezmoi to clear all group and world permssions. - -### Symbolic links - -Symbolic links are represented by regular files in the source state with the -prefix `symlink_`. The contents of the file will have a trailing newline -stripped, and the result be interpreted as the target of the symbolic link. -Symbolic links with the `.tmpl` suffix in the source state are interpreted as -templates. - -### Scripts - -Scripts are represented as regular files in the source state with prefix `run_`. -The file's contents (after being interpreted as a template if it has a `.tmpl` -suffix) are executed. Scripts are executed on every `chezmoi apply`, unless they -have the `once_` attribute, in which case they are only executed when they are -first found or when their contents have changed. - -Scripts with the `before_` attribute are executed before any files, directories, -or symlinks are updated. Scripts with the `after_` attribute are executed after -all files, directories, and symlinks have been updated. Scripts without an -`before_` or `after_` attribute are executed in ASCII order of their target -names with respect to files, directories, and symlinks. - -## Special files and directories - -All files and directories in the source state whose name begins with `.` are -ignored by default, unless they are one of the special files listed here. - -### `.chezmoi.<format>.tmpl` - -If a file called `.chezmoi.<format>.tmpl` exists then `chezmoi init` will use it -to create an initial config file. *format* must be one of the the supported -config file formats. - -#### `.chezmoi.<format>.tmpl` examples - - {{ $email := promptString "email" -}} - data: - email: "{{ $email }}" - -### `.chezmoiignore` - -If a file called `.chezmoiignore` exists in the source state then it is -interpreted as a set of patterns to ignore. Patterns are matched using -[`doublestar.PathMatch`](https://pkg.go.dev/github.com/bmatcuk/doublestar?tab=doc#PathMatch) -and match against the target path, not the source path. - -Patterns can be excluded by prefixing them with a `!` character. All excludes -take priority over all includes. - -Comments are introduced with the `#` character and run until the end of the -line. - -`.chezmoiignore` is interpreted as a template. This allows different files to be -ignored on different machines. - -`.chezmoiignore` files in subdirectories apply only to that subdirectory. - -#### `.chezmoiignore` examples - - README.md - - *.txt # ignore *.txt in the target directory - */*.txt # ignore *.txt in subdirectories of the target directory - backups/** # ignore backups folder in chezmoi directory and all its contents - # but not in subdirectories of subdirectories; - # so a/b/c.txt would *not* be ignored - backups/** # ignore all contents of backups folder in chezmoi directory - # but not backups folder itself - - {{- if ne .email "[email protected]" }} - # Ignore .company-directory unless configured with a company email - .company-directory # note that the pattern is not dot_company-directory - {{- end }} - - {{- if ne .email "[email protected] }} - .personal-file - {{- end }} - -### `.chezmoiremove` - -If a file called `.chezmoiremove` exists in the source state then it is -interpreted as a list of targets to remove. `.chezmoiremove` is interpreted as a -template. - -### `.chezmoitemplates` - -If a directory called `.chezmoitemplates` exists, then all files in this -directory are parsed as templates are available as templates with a name equal -to the relative path of the file. - -#### `.chezmoitemplates` examples - -Given: - - .chezmoitemplates/foo - {{ if true }}bar{{ end }} - - dot_config.tmpl - {{ template "foo" }} - -The target state of `.config` will be `bar`. - -### `.chezmoiversion` - -If a file called `.chezmoiversion` exists, then its contents are interpreted as -a semantic version defining the minimum version of chezmoi required to interpret -the source state correctly. chezmoi will refuse to interpret the source state if -the current version is too old. - -#### `.chezmoiversion` examples - - 1.5.0 - -## Commands - -### `add` *targets* - -Add *targets* to the source state. If any target is already in the source state, -then its source state is replaced with its current state in the destination -directory. The `add` command accepts additional flags: - -#### `--autotemplate` - -Automatically generate a template by replacing strings with variable names from -the `data` section of the config file. Longer substitutions occur before shorter -ones. This implies the `--template` option. - -#### `-e`, `--empty` - -Set the `empty` attribute on added files. - -#### `-f`, `--force` - -Add *targets*, even if doing so would cause a source template to be overwritten. - -#### `--follow` - -If the last part of a target is a symlink, add the target of the symlink instead -of the symlink itself. - -#### `-x`, `--exact` - -Set the `exact` attribute on added directories. - -#### `-i`, `--include` *types* - -Only add entries of type *types*. - -#### `-p`, `--prompt` - -Interactively prompt before adding each file. - -#### `-r`, `--recursive` - -Recursively add all files, directories, and symlinks. - -#### `-T`, `--template` - -Set the `template` attribute on added files and symlinks. - -#### `add` examples - - chezmoi add ~/.bashrc - chezmoi add ~/.gitconfig --template - chezmoi add ~/.vim --recursive - chezmoi add ~/.oh-my-zsh --exact --recursive - -### `apply` [*targets*] - -Ensure that *targets* are in the target state, updating them if necessary. If no -targets are specified, the state of all targets are ensured. If a target has -been modified since chezmoi last wrote it then the user will be prompted if they -want to overwrite the file. - -#### `-i`, `--include` *types* - -Only add entries of type *types*. - -#### `--source-path` - -Specify targets by source path, rather than target path. This is useful for -applying changes after editing. - -#### `apply` examples - - chezmoi apply - chezmoi apply --dry-run --verbose - chezmoi apply ~/.bashrc - -In `~/.vimrc`: - - autocmd BufWritePost ~/.local/share/chezmoi/* ! chezmoi apply --source-path % - -### `archive` - -Generate a tar archive of the target state. This can be piped into `tar` to -inspect the target state. - -#### `--format` *format* - -Write the archive in *format*. *format* can be either `tar` (the default) or `zip`. - -#### `-i`, `--include` *types* - -Only include entries of type *types*. - -#### `-z`, `--gzip` - -Compress the output with gzip. - -#### `archive` examples - - chezmoi archive | tar tvf - - chezmoi archive --output=dotfiles.tar - chezmoi archive --format=zip --output=dotfiles.zip - -### `cat` *targets* - -Write the target state of *targets* to stdout. *targets* must be files or -symlinks. For files, the target file contents are written. For symlinks, the -target target is written. - -#### `cat` examples - - chezmoi cat ~/.bashrc - -### `cd` - -Launch a shell in the source directory. chezmoi will launch the command set by -the `cd.command` configuration variable with any extra arguments specified by -`cd.args`. If this is not set, chezmoi will attempt to detect your shell and -will finally fall back to an OS-specific default. - -#### `cd` examples - - chezmoi cd - -### `chattr` *attributes* *targets* - -Change the attributes of *targets*. *attributes* specifies which attributes to -modify. Add attributes by specifying them or their abbreviations directly, -optionally prefixed with a plus sign (`+`). Remove attributes by prefixing them -or their attributes with the string `no` or a minus sign (`-`). The available -attributes and their abbreviations are: - -| Attribute | Abbreviation | -| ------------ | ------------ | -| `empty` | `e` | -| `encrypted` | *none* | -| `exact` | *none* | -| `executable` | `x` | -| `private` | `p` | -| `template` | `t` | - -Multiple attributes modifications may be specified by separating them with a -comma (`,`). - -#### `chattr` examples - - chezmoi chattr template ~/.bashrc - chezmoi chattr noempty ~/.profile - chezmoi chattr private,template ~/.netrc - -### `completion` *shell* - -Generate shell completion code for the specified shell (`bash`, `fish`, -`powershell`, or `zsh`). - -#### `completion` examples - - chezmoi completion bash - chezmoi completion fish --output=~/.config/fish/completions/chezmoi.fish - -### `data` - -Write the computed template data to stdout. - -#### `data` examples - - chezmoi data - chezmoi data --format=yaml - -### `diff` [*targets*] - -Print the difference between the target state and the destination state for -*targets*. If no targets are specified, print the differences for all targets. - -If a `diff.pager` command is set in the configuration file then the output will -be piped into it. - -#### `diff` examples - - chezmoi diff - chezmoi diff ~/.bashrc - -### `docs` [*regexp*] - -Print the documentation page matching the regular expression *regexp*. Matching -is case insensitive. If no pattern is given, print `REFERENCE.md`. - -#### `docs` examples - - chezmoi docs - chezmoi docs faq - chezmoi docs howto - -### `doctor` - -Check for potential problems. - -#### `doctor` examples - - chezmoi doctor - -### `dump` [*targets*] - -Dump the target state. If no targets are specified, then the entire target -state. - -#### `-i`, `--include` *types* - -Only include entries of type *types*. - -#### `dump` examples - - chezmoi dump ~/.bashrc - chezmoi dump --format=yaml - -### `edit` [*targets*] - -Edit the source state of *targets*, which must be files or symlinks. If no -targets are given the the source directory itself is opened with `$EDITOR`. The -`edit` command accepts additional arguments: - -#### `-a`, `--apply` - -Apply target immediately after editing. Ignored if there are no targets. - -#### `edit` examples - - chezmoi edit ~/.bashrc - chezmoi edit ~/.bashrc --apply - chezmoi edit - -### `edit-config` - -Edit the configuration file. - -#### `edit-config` examples - - chezmoi edit-config - -### `execute-template` [*templates*] - -Execute *templates*. This is useful for testing templates or for calling chezmoi -from other scripts. *templates* are interpreted as literal templates, with no -whitespace added to the output between arguments. If no templates are specified, -the template is read from stdin. - -#### `--init`, `-i` - -Include simulated functions only available during `chezmoi init`. - -#### `--promptBool` *pairs* - -Simulate the `promptBool` function with a function that returns values from -*pairs*. *pairs* is a comma-separated list of *prompt*`=`*value* pairs. If -`promptBool` is called with a *prompt* that does not match any of *pairs*, then -it returns false. - -#### `--promptInt`, `-p` *pairs* - -Simulate the `promptInt` function with a function that returns values from -*pairs*. *pairs* is a comma-separated list of *prompt*`=`*value* pairs. If -`promptInt` is called with a *prompt* that does not match any of *pairs*, then -it returns zero. - -#### `--promptString`, `-p` *pairs* - -Simulate the `promptString` function with a function that returns values from -*pairs*. *pairs* is a comma-separated list of *prompt*`=`*value* pairs. If -`promptString` is called with a *prompt* that does not match any of *pairs*, -then it returns *prompt* unchanged. - -#### `execute-template` examples - - chezmoi execute-template '{{ .chezmoi.sourceDir }}' - chezmoi execute-template '{{ .chezmoi.os }}' / '{{ .chezmoi.arch }}' - echo '{{ .chezmoi | toJson }}' | chezmoi execute-template - chezmoi execute-template --init --promptString [email protected] < ~/.local/share/chezmoi/.chezmoi.toml.tmpl - -### `forget` *targets* - -Remove *targets* from the source state, i.e. stop managing them. - -#### `forget` examples - - chezmoi forget ~/.bashrc - -### `git` [*arguments*] - -Run `git` *arguments* in the source directory. Note that flags in *arguments* -must occur after `--` to prevent chezmoi from interpreting them. - -#### `git` examples - - chezmoi git add . - chezmoi git add dot_gitconfig - chezmoi git -- commit -m "Add .gitconfig" - -### `help` *command* - -Print the help associated with *command*. - -### `init` [*repo*] - -Setup the source directory and update the destination directory to match the -target state. *repo* is expanded to a full git repo URL using the following -rules: - -| Pattern | Repo | -| ------------------ | -------------------------------------- | -| `user` | `https://github.com/user/dotfiles.git` | -| `user/repo` | `https://github.com/user/repo.git` | -| `site/user/repo` | `https://site/user/repo.git` | -| `~sr.ht/user` | `https://git.sr.ht/~user/dotfiles` | -| `~sr.ht/user/repo` | `https://git.sr.ht/~user/repo` | - -First, if the source directory is not already contain a repository, then if -*repo* is given it is checked out into the source directory, otherwise a new -repository is initialized in the source directory. - -Second, if a file called `.chezmoi.<format>.tmpl` exists, where `<format>` is -one of the supported file formats (e.g. `json`, `toml`, or `yaml`) then a new -configuration file is created using that file as a template. - -Then, if the `--apply` flag is passed, `chezmoi apply` is run. - -Then, if the `--purge` flag is passed, chezmoi will remove the source directory -and its config directory. - -Finally, if the `--purge-binary` is passed, chezmoi will attempt to remove its -own binary. - -#### `--apply` - -Run `chezmoi apply` after checking out the repo and creating the config file. - -#### `--depth` *depth* - -Clone the repo with depth *depth*. - -#### `--one-shot` - -`--one-shot` is the equivalent of `--apply`, `--depth=1`, `--purge`, -`--purge-binary`. It attempts to install your dotfiles with chezmoi and then -remove all traces of chezmoi from the system. This is useful for setting up -temporary environments (e.g. Docker containers). - -#### `--purge` - -Remove the source and config directories after applying. - -#### `--purge-binary` - -Attempt to remove the chezmoi binary after applying. - -#### `--skip-encrypted` - -Skip encrypted files. This is useful for setting up machines with an inital set -of dotfiles before private decryption keys are available. - -#### `init` examples - - chezmoi init user - chezmoi init user --apply - chezmoi init user --apply --purge - chezmoi init user/dots - chezmoi init gitlab.com/user - -### `import` *filename* - -Import the source state from an archive file in to a directory in the source -state. This is primarily used to make subdirectories of your home directory -exactly match the contents of a downloaded archive. You will generally always -want to set the `--destination`, `--exact`, and `--remove-destination` flags. - -The only supported archive format is `.tar.gz`. - -#### `--destination` *directory* - -Set the destination (in the source state) where the archive will be imported. - -#### `-x`, `--exact` - -Set the `exact` attribute on all imported directories. - -#### `-r`, `--remove-destination` - -Remove destination (in the source state) before importing. - -#### `--strip-components` *n* - -Strip *n* leading components from paths. - -#### `import` examples - - curl -s -L -o oh-my-zsh-master.tar.gz https://github.com/robbyrussell/oh-my-zsh/archive/master.tar.gz - chezmoi import --strip-components 1 --destination ~/.oh-my-zsh oh-my-zsh-master.tar.gz - -### `manage` *targets* - -`manage` is an alias for `add` for symmetry with `unmanage`. - -### `managed` - -List all managed entries in the destination directory in alphabetical order. - -#### `-i`, `--include` *types* - -Only include entries of type *types*. - -#### `managed` examples - - chezmoi managed - chezmoi managed --include=files - chezmoi managed --include=files,symlinks - chezmoi managed -i d - chezmoi managed -i d,f - -### `merge` *targets* - -Perform a three-way merge between the destination state, the target state, and -the source state. The merge tool is defined by the `merge.command` configuration -variable, and defaults to `vimdiff`. If multiple targets are specified the merge -tool is invoked for each target. If the target state cannot be computed (for -example if source is a template containing errors or an encrypted file that -cannot be decrypted) a two-way merge is performed instead. - -#### `merge` examples - - chezmoi merge ~/.bashrc - -### `purge` - -Remove chezmoi's configuration, state, and source directory, but leave the -target state intact. - -#### `-f`, `--force` - -Remove without prompting. - -#### `purge` examples - - chezmoi purge - chezmoi purge --force - -### `remove` *targets* - -Remove *targets* from both the source state and the destination directory. - -#### `-f`, `--force` - -Remove without prompting. - -### `rm` *targets* - -`rm` is an alias for `remove`. - -### `secret` - -Run a secret manager's CLI, passing any extra arguments to the secret manager's -CLI. This is primarily for verifying chezmoi's integration with your secret -manager. Normally you would use template functions to retrieve secrets. Note -that if you want to pass flags to the secret manager's CLI you will need to -separate them with `--` to prevent chezmoi from interpreting them. - -To get a full list of available commands run: - - chezmoi secret help - -#### `secret` examples - - chezmoi secret keyring set --service=service --user=user --value=password - chezmoi secret keyring get --service=service --user=user - -### `source-path` [*targets*] - -Print the path to each target's source state. If no targets are specified then -print the source directory. - -#### `source-path` examples - - chezmoi source-path - chezmoi source-path ~/.bashrc - -### `state` - -Manipulate the persistent state. - -#### `state` examples - - chezmoi state dump - chemzoi state reset - -### `status` - -Print the status of the files and scripts managed by chezmoi in a format similar -to [`git status`](https://git-scm.com/docs/git-status). - -The first column of output indicates the difference between the last state -written by chezmoi and the actual state. The second column indicates the -difference between the actual state and the target state. - -#### `-i`, `--include` *types* - -Only include entries of type *types*. - -#### `status` examples - - chezmoi status - -### `unmanage` *targets* - -`unmanage` is an alias for `forget` for symmetry with `manage`. - -### `unmanaged` - -List all unmanaged files in the destination directory. - -#### `unmanaged` examples - - chezmoi unmanaged - -### `update` - -Pull changes from the source VCS and apply any changes. - -#### `-i`, `--include` *types* - -Only update entries of type *types*. - -#### `update` examples - - chezmoi update - -### `upgrade` - -Upgrade chezmoi by downloading and installing the latest released version. This -will call the GitHub API to determine if there is a new version of chezmoi -available, and if so, download and attempt to install it in the same way as -chezmoi was previously installed. - -If chezmoi was installed with a package manager (`dpkg` or `rpm`) then `upgrade` -will download a new package and install it, using `sudo` if it is installed. -Otherwise, chezmoi will download the latest executable and replace the existing -executable with the new version. - -If the `CHEZMOI_GITHUB_API_TOKEN` environment variable is set, then its value -will be used to authenticate requests to the GitHub API, otherwise -unauthenticated requests are used which are subject to stricter [rate -limiting](https://developer.github.com/v3/#rate-limiting). Unauthenticated -requests should be sufficient for most cases. - -#### `upgrade` examples - - chezmoi upgrade - -### `verify` [*targets*] - -Verify that all *targets* match their target state. chezmoi exits with code 0 -(success) if all targets match their target state, or 1 (failure) otherwise. If -no targets are specified then all targets are checked. - -#### `-i`, `--include` *types* - -Only include entries of type *types*. - -#### `verify` examples - - chezmoi verify - chezmoi verify ~/.bashrc - -## Editor configuration - -The `edit` and `edit-config` commands use the editor specified by the `VISUAL` -environment variable, the `EDITOR` environment variable, or `vi`, whichever is -specified first. - -## Umask configuration - -By default, chezmoi uses your current umask as set by your operating system and -shell. chezmoi only stores crude permissions in its source state, namely in the -`executable` and `private` attributes, corresponding to the umasks of `0o111` -and `0o077` respectively. - -For machine-specific control of umask, set the `umask` configuration variable in -chezmoi's configuration file, for example: - - umask = 0o22 - -## Template execution - -chezmoi executes templates using -[`text/template`](https://pkg.go.dev/text/template). The result is treated -differently depending on whether the target is a file or a symlink. - -If target is a file, then: - -* If the result is an empty string, then the file is removed. -* Otherwise, the target file contents are result. - -If the target is a symlink, then: - -* Leading and trailing whitespace are stripped from the result. -* If the result is an empty string, then the symlink is removed. -* Otherwise, the target symlink target is the result. - -chezmoi executes templates using `text/template`'s `missingkey=error` option, -which means that misspelled or missing keys will raise an error. This can be -overridden by setting a list of options in the configuration file, for example: - - [template] - options = ["missingkey=zero"] - -For a full list of options, see -[`Template.Option`](https://pkg.go.dev/text/template?tab=doc#Template.Option). - -## Template variables - -chezmoi provides the following automatically-populated variables: - -| Variable | Value | -| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------- | -| `.chezmoi.arch` | Architecture, e.g. `amd64`, `arm`, etc. as returned by [runtime.GOARCH](https://pkg.go.dev/runtime?tab=doc#pkg-constants). | -| `.chezmoi.fqdnHostname` | The fully-qualified domain name hostname of the machine chezmoi is running on. | -| `.chezmoi.group` | The group of the user running chezmoi. | -| `.chezmoi.homeDir` | The home directory of the user running chezmoi. | -| `.chezmoi.hostname` | The hostname of the machine chezmoi is running on, up to the first `.`. | -| `.chezmoi.kernel` | Contains information from `/proc/sys/kernel`. Linux only, useful for detecting specific kernels (i.e. Microsoft's WSL kernel). | -| `.chezmoi.os` | Operating system, e.g. `darwin`, `linux`, etc. as returned by [runtime.GOOS](https://pkg.go.dev/runtime?tab=doc#pkg-constants). | -| `.chezmoi.osRelease` | The information from `/etc/os-release`, Linux only, run `chezmoi data` to see its output. | -| `.chezmoi.sourceDir` | The source directory. | -| `.chezmoi.username` | The username of the user running chezmoi. | -| `.chezmoi.version` | The version of chezmoi. | - -Additional variables can be defined in the config file in the `data` section. -Variable names must consist of a letter and be followed by zero or more letters -and/or digits. - -## Template functions - -All standard [`text/template`](https://pkg.go.dev/text/template) and [text -template functions from `sprig`](http://masterminds.github.io/sprig/) are -included. chezmoi provides some additional functions. - -### `bitwarden` [*args*] - -`bitwarden` returns structured data retrieved from -[Bitwarden](https://bitwarden.com) using the [Bitwarden -CLI](https://github.com/bitwarden/cli) (`bw`). *args* are passed to `bw get` -unchanged and the output from `bw get` is parsed as JSON. The output from `bw -get` is cached so calling `bitwarden` multiple times with the same arguments -will only invoke `bw` once. - -#### `bitwarden` examples - - username = {{ (bitwarden "item" "<itemid>").login.username }} - password = {{ (bitwarden "item" "<itemid>").login.password }} - -### `bitwardenAttachment` *filename* *itemid* - -`bitwardenAttachment` returns a document from -[Bitwarden](https://bitwarden.com/) using the [Bitwarden -CLI](https://bitwarden.com/help/article/cli/) (`bw`). *filename* and *itemid* is -passed to `bw get attachment <filename> --itemid <itemid>` and the output from -`bw` is returned. The output from `bw` is cached so calling -`bitwardenAttachment` multiple times with the same *filename* and *itemid* will -only invoke `bw` once. - -#### `bitwardenAttachment` examples - - {{- (bitwardenAttachment "<filename>" "<itemid>") -}} - -### `bitwardenFields` [*args*] - -`bitwardenFields` returns structured data retrieved from -[Bitwarden](https://bitwarden.com) using the [Bitwarden -CLI](https://github.com/bitwarden/cli) (`bw`). *args* are passed to `bw get` -unchanged, the output from `bw get` is parsed as JSON, and elements of `fields` -are returned as a map indexed by each field's `name`. For example, given the -output from `bw get`: - -```json -{ - "object": "item", - "id": "bf22e4b4-ae4a-4d1c-8c98-ac620004b628", - "organizationId": null, - "folderId": null, - "type": 1, - "name": "example.com", - "notes": null, - "favorite": false, - "fields": [ - { - "name": "text", - "value": "text-value", - "type": 0 - }, - { - "name": "hidden", - "value": "hidden-value", - "type": 1 - } - ], - "login": { - "username": "username-value", - "password": "password-value", - "totp": null, - "passwordRevisionDate": null - }, - "collectionIds": [], - "revisionDate": "2020-10-28T00:21:02.690Z" -} -``` - -the return value will be the map - -```json -{ - "hidden": { - "name": "hidden", - "type": 1, - "value": "hidden-value" - }, - "token": { - "name": "token", - "type": 0, - "value": "token-value" - } -} -``` - -The output from `bw get` is cached so calling `bitwarden` multiple times with -the same arguments will only invoke `bw get` once. - -#### `bitwardenFields` examples - - {{ (bitwardenFields "item" "<itemid>").token.value }} - -### `gitHubKeys` *user* - -`gitHubKeys` returns *user*'s public SSH keys from GitHub using the GitHub API. -If any of the environment variables `CHEZMOI_GITHUB_ACCESS_TOKEN`, -`GITHUB_ACCESS_TOKEN`, or `GITHUB_TOKEN` are found, then the first one found -will be used to authenticate the API request, otherwise an anonymous API request -will be used, which may be subject to lower rate limits. - -#### `gitHubKeys` examples - - {{ range (gitHubKeys "user") }} - {{- .Key }} - {{- end }} - -### `gopass` *gopass-name* - -`gopass` returns passwords stored in [gopass](https://www.gopass.pw/) using the -gopass CLI (`gopass`). *gopass-name* is passed to `gopass show <gopass-name>` -and first line of the output of `gopass` is returned with the trailing newline -stripped. The output from `gopass` is cached so calling `gopass` multiple times -with the same *gopass-name* will only invoke `gopass` once. - -#### `gopass` examples - - {{ gopass "<pass-name>" }} - -### `include` *filename* - -`include` returns the literal contents of the file named `*filename*`, relative -to the source directory. - -### `ioreg` - -On macOS, `ioreg` returns the structured output of the `ioreg -a -l` command, -which includes detailed information about the I/O Kit registry. - -On non-macOS operating systems, `ioreg` returns `nil`. - -The output from `ioreg` is cached so multiple calls to the `ioreg` function will -only execute the `ioreg -a -l` command once. - -#### `ioreg` examples - - {{ if (eq .chezmoi.os "darwin") }} - {{ $serialNumber := index ioreg "IORegistryEntryChildren" 0 "IOPlatformSerialNumber" }} - {{ end }} - -### `joinPath` *elements* - -`joinPath` joins any number of path elements into a single path, separating them -with the OS-specific path separator. Empty elements are ignored. The result is -cleaned. If the argument list is empty or all its elements are empty, `joinPath` -returns an empty string. On Windows, the result will only be a UNC path if the -first non-empty element is a UNC path. - -#### `joinPath` examples - - {{ joinPath .chezmoi.homeDir ".zshrc" }} - -### `keepassxc` *entry* - -`keepassxc` returns structured data retrieved from a -[KeePassXC](https://keepassxc.org/) database using the KeePassXC CLI -(`keepassxc-cli`). The database is configured by setting `keepassxc.database` in -the configuration file. *database* and *entry* are passed to `keepassxc-cli -show`. You will be prompted for the database password the first time -`keepassxc-cli` is run, and the password is cached, in plain text, in memory -until chezmoi terminates. The output from `keepassxc-cli` is parsed into -key-value pairs and cached so calling `keepassxc` multiple times with the same -*entry* will only invoke `keepassxc-cli` once. - -#### `keepassxc` examples - - username = {{ (keepassxc "example.com").UserName }} - password = {{ (keepassxc "example.com").Password }} - -### `keepassxcAttribute` *entry* *attribute* - -`keepassxcAttribute` returns the attribute *attribute* of *entry* using -`keepassxc-cli`, with any leading or trailing whitespace removed. It behaves -identically to the `keepassxc` function in terms of configuration, password -prompting, password storage, and result caching. - -#### `keepassxcAttribute` examples - - {{ keepassxcAttribute "SSH Key" "private-key" }} - -### `keyring` *service* *user* - -`keyring` retrieves the value associated with *service* and *user* from the -user's keyring. - -| OS | Keyring | -| ------- | --------------------------- | -| macOS | Keychain | -| Linux | GNOME Keyring | -| Windows | Windows Credentials Manager | - -#### `keyring` examples - - [github] - user = "{{ .github.user }}" - token = "{{ keyring "github" .github.user }}" - -### `lastpass` *id* - -`lastpass` returns structured data from [LastPass](https://lastpass.com) using -the [LastPass CLI](https://lastpass.github.io/lastpass-cli/lpass.1.html) -(`lpass`). *id* is passed to `lpass show --json <id>` and the output from -`lpass` is parsed as JSON. In addition, the `note` field, if present, is further -parsed as colon-separated key-value pairs. The structured data is an array so -typically the `index` function is used to extract the first item. The output -from `lastpass` is cached so calling `lastpass` multiple times with the same -*id* will only invoke `lpass` once. - -#### `lastpass` examples - - githubPassword = "{{ (index (lastpass "GitHub") 0).password }}" - {{ (index (lastpass "SSH") 0).note.privateKey }} - -### `lastpassRaw` *id* - -`lastpassRaw` returns structured data from [LastPass](https://lastpass.com) -using the [LastPass CLI](https://lastpass.github.io/lastpass-cli/lpass.1.html) -(`lpass`). It behaves identically to the `lastpass` function, except that no -further parsing is done on the `note` field. - -#### `lastpassRaw` examples - - {{ (index (lastpassRaw "SSH Private Key") 0).note }} - -### `lookPath` *file* - -`lookPath` searches for an executable named *file* in the directories named by -the `PATH` environment variable. If file contains a slash, it is tried directly -and the `PATH` is not consulted. The result may be an absolute path or a path -relative to the current directory. If *file* is not found, `lookPath` returns an -empty string. - -`lookPath` is not hermetic: its return value depends on the state of the -environment and the filesystem at the moment the template is executed. Exercise -caution when using it in your templates. - -#### `lookPath` examples - - {{ if lookPath "diff-so-fancy" }} - # diff-so-fancy is in $PATH - {{ end }} - -### `onepassword` *uuid* [*vault-uuid*] - -`onepassword` returns structured data from [1Password](https://1password.com/) -using the [1Password -CLI](https://support.1password.com/command-line-getting-started/) (`op`). *uuid* -is passed to `op get item <uuid>` and the output from `op` is parsed as JSON. -The output from `op` is cached so calling `onepassword` multiple times with the -same *uuid* will only invoke `op` once. If the optional *vault-uuid* is supplied, -it will be passed along to the `op get` call, which can significantly improve -performance. - -#### `onepassword` examples - - {{ (onepassword "<uuid>").details.password }} - {{ (onepassword "<uuid>" "<vault-uuid>").details.password }} - -### `onepasswordDocument` *uuid* [*vault-uuid*] - -`onepassword` returns a document from [1Password](https://1password.com/) -using the [1Password -CLI](https://support.1password.com/command-line-getting-started/) (`op`). *uuid* -is passed to `op get document <uuid>` and the output from `op` is returned. -The output from `op` is cached so calling `onepasswordDocument` multiple times with the -same *uuid* will only invoke `op` once. If the optional *vault-uuid* is supplied, -it will be passed along to the `op get` call, which can significantly improve -performance. - -#### `onepasswordDocument` examples - - {{- onepasswordDocument "<uuid>" -}} - {{- onepasswordDocument "<uuid>" "<vault-uuid>" -}} - -### `onepasswordDetailsFields` *uuid* [*vault-uuid*] - -`onepasswordDetailsFields` returns structured data from -[1Password](https://1password.com/) using the [1Password -CLI](https://support.1password.com/command-line-getting-started/) (`op`). *uuid* -is passed to `op get item <uuid>`, the output from `op` is parsed as JSON, and -elements of `details.fields` are returned as a map indexed by each field's -`designation`. For example, give the output from `op`: - -```json -{ - "uuid": "<uuid>", - "details": { - "fields": [ - { - "designation": "username", - "name": "username", - "type": "T", - "value": "exampleuser" - }, - { - "designation": "password", - "name": "password", - "type": "P", - "value": "examplepassword" - } - ], - } -} -``` - -the return value will be the map: - -```json -{ - "username": { - "designation": "username", - "name": "username", - "type": "T", - "value": "exampleuser" - }, - "password": { - "designation": "password", - "name": "password", - "type": "P", - "value": "examplepassword" - } -} -``` - -The output from `op` is cached so calling `onepassword` multiple times with the -same *uuid* will only invoke `op` once. If the optional *vault-uuid* is supplied, -it will be passed along to the `op get` call, which can significantly improve -performance. - -#### `onepasswordDetailsFields` examples - - {{ (onepasswordDetailsFields "<uuid>").password.value }} - -### `pass` *pass-name* - -`pass` returns passwords stored in [pass](https://www.passwordstore.org/) using -the pass CLI (`pass`). *pass-name* is passed to `pass show <pass-name>` and -first line of the output of `pass` is returned with the trailing newline -stripped. The output from `pass` is cached so calling `pass` multiple times with -the same *pass-name* will only invoke `pass` once. - -#### `pass` examples - - {{ pass "<pass-name>" }} - -### `promptBool` *prompt* - -`promptBool` prompts the user with *prompt* and returns the user's response with -interpreted as a boolean. It is only available when generating the initial -config file. The user's response is interpreted as follows (case insensitive): - -| Response | Result | -| ----------------------- | ------- | -| 1, on, t, true, y, yes | `true` | -| 0, off, f, false, n, no | `false` | - -### `promptInt` *prompt* - -`promptInt` prompts the user with *prompt* and returns the user's response with -interpreted as an integer. It is only available when generating the initial -config file. - -### `promptString` *prompt* - -`promptString` prompts the user with *prompt* and returns the user's response -with all leading and trailing spaces stripped. It is only available when -generating the initial config file. - -#### `promptString` examples - - {{ $email := promptString "email" -}} - [data] - email = "{{ $email }}" - -### `secret` [*args*] - -`secret` returns the output of the generic secret command defined by the -`secret.command` configuration variable with *args* with leading and trailing -whitespace removed. The output is cached so multiple calls to `secret` with the -same *args* will only invoke the generic secret command once. - -### `secretJSON` [*args*] - -`secretJSON` returns structured data from the generic secret command defined by -the `secret.command` configuration variable with *args*. The output is parsed as -JSON. The output is cached so multiple calls to `secret` with the same *args* -will only invoke the generic secret command once. - -### `stat` *name* - -`stat` runs `stat(2)` on *name*. If *name* exists it returns structured data. If -*name* does not exist then it returns a false value. If `stat(2)` returns any -other error then it raises an error. The structured value returned if *name* -exists contains the fields `name`, `size`, `mode`, `perm`, `modTime`, and -`isDir`. - -`stat` is not hermetic: its return value depends on the state of the filesystem -at the moment the template is executed. Exercise caution when using it in your -templates. - -#### `stat` examples - - {{ if stat (joinPath .chezmoi.homeDir ".pyenv") }} - # ~/.pyenv exists - {{ end }} - -### `vault` *key* - -`vault` returns structured data from [Vault](https://www.vaultproject.io/) using -the [Vault CLI](https://www.vaultproject.io/docs/commands/) (`vault`). *key* is -passed to `vault kv get -format=json <key>` and the output from `vault` is -parsed as JSON. The output from `vault` is cached so calling `vault` multiple -times with the same *key* will only invoke `vault` once. - -#### `vault` examples - - {{ (vault "<key>").data.data.password }} diff --git a/chezmoi2/internal/chezmoi/autotemplate.go b/chezmoi2/internal/chezmoi/autotemplate.go deleted file mode 100644 index 4f0e70d32d1..00000000000 --- a/chezmoi2/internal/chezmoi/autotemplate.go +++ /dev/null @@ -1,100 +0,0 @@ -package chezmoi - -import ( - "sort" - "strings" -) - -// A templateVariable is a template variable. It is used instead of a -// map[string]string so that we can control order. -type templateVariable struct { - name string - value string -} - -// byValueLength implements sort.Interface for a slice of templateVariables, -// sorting by value length. -type byValueLength []templateVariable - -func (b byValueLength) Len() int { return len(b) } -func (b byValueLength) Less(i, j int) bool { - switch { - case len(b[i].value) < len(b[j].value): // First sort by value length. - return true - case len(b[i].value) == len(b[j].value): - return b[i].name > b[j].name // Second sort by value name. - default: - return false - } -} -func (b byValueLength) Swap(i, j int) { b[i], b[j] = b[j], b[i] } - -func autoTemplate(contents []byte, data map[string]interface{}) []byte { - // This naive approach will generate incorrect templates if the variable - // names match variable values. The algorithm here is probably O(N^2), we - // can do better. - variables := extractVariables(data) - sort.Sort(sort.Reverse(byValueLength(variables))) - contentsStr := string(contents) - for _, variable := range variables { - if variable.value == "" { - continue - } - index := strings.Index(contentsStr, variable.value) - for index != -1 && index != len(contentsStr) { - if !inWord(contentsStr, index) && !inWord(contentsStr, index+len(variable.value)) { - // Replace variable.value which is on word boundaries at both - // ends. - replacement := "{{ ." + variable.name + " }}" - contentsStr = contentsStr[:index] + replacement + contentsStr[index+len(variable.value):] - index += len(replacement) - } else { - // Otherwise, keep looking. Consume at least one byte so we make - // progress. - index++ - } - // Look for the next occurrence of variable.value. - j := strings.Index(contentsStr[index:], variable.value) - if j == -1 { - // No more occurrences found, so terminate the loop. - break - } else { - // Advance to the next occurrence. - index += j - } - } - } - return []byte(contentsStr) -} - -// extractVariables extracts all template variables from data. -func extractVariables(data map[string]interface{}) []templateVariable { - return extractVariablesHelper(nil /* variables */, nil /* parent */, data) -} - -// extractVariablesHelper appends all template variables in data to variables -// and returns variables. data is assumed to be rooted at parent. -func extractVariablesHelper(variables []templateVariable, parent []string, data map[string]interface{}) []templateVariable { - for name, value := range data { - switch value := value.(type) { - case string: - variables = append(variables, templateVariable{ - name: strings.Join(append(parent, name), "."), - value: value, - }) - case map[string]interface{}: - variables = extractVariablesHelper(variables, append(parent, name), value) - } - } - return variables -} - -// inWord returns true if splitting s at position i would split a word. -func inWord(s string, i int) bool { - return i > 0 && i < len(s) && isWord(s[i-1]) && isWord(s[i]) -} - -// isWord returns true if b is a word byte. -func isWord(b byte) bool { - return '0' <= b && b <= '9' || 'A' <= b && b <= 'Z' || 'a' <= b && b <= 'z' -} diff --git a/chezmoi2/internal/chezmoi/autotemplate_test.go b/chezmoi2/internal/chezmoi/autotemplate_test.go deleted file mode 100644 index ca84a9ac1c1..00000000000 --- a/chezmoi2/internal/chezmoi/autotemplate_test.go +++ /dev/null @@ -1,170 +0,0 @@ -package chezmoi - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestAutoTemplate(t *testing.T) { - for _, tc := range []struct { - name string - contentsStr string - data map[string]interface{} - expected string - }{ - { - name: "simple", - contentsStr: "email = [email protected]\n", - data: map[string]interface{}{ - "email": "[email protected]", - }, - expected: "email = {{ .email }}\n", - }, - { - name: "longest_first", - contentsStr: "name = John Smith\nfirstName = John\n", - data: map[string]interface{}{ - "name": "John Smith", - "firstName": "John", - }, - expected: "" + - "name = {{ .name }}\n" + - "firstName = {{ .firstName }}\n", - }, - { - name: "alphabetical_first", - contentsStr: "name = John Smith\n", - data: map[string]interface{}{ - "alpha": "John Smith", - "beta": "John Smith", - "gamma": "John Smith", - }, - expected: "name = {{ .alpha }}\n", - }, - { - name: "nested_values", - contentsStr: "email = [email protected]\n", - data: map[string]interface{}{ - "personal": map[string]interface{}{ - "email": "[email protected]", - }, - }, - expected: "email = {{ .personal.email }}\n", - }, - { - name: "only_replace_words", - contentsStr: "darwinian evolution", - data: map[string]interface{}{ - "os": "darwin", - }, - expected: "darwinian evolution", // not "{{ .os }}ian evolution" - }, - { - name: "longest_match_first", - contentsStr: "/home/user", - data: map[string]interface{}{ - "homeDir": "/home/user", - }, - expected: "{{ .homeDir }}", - }, - { - name: "longest_match_first_prefix", - contentsStr: "HOME=/home/user", - data: map[string]interface{}{ - "homeDir": "/home/user", - }, - expected: "HOME={{ .homeDir }}", - }, - { - name: "longest_match_first_suffix", - contentsStr: "/home/user/something", - data: map[string]interface{}{ - "homeDir": "/home/user", - }, - expected: "{{ .homeDir }}/something", - }, - { - name: "longest_match_first_prefix_and_suffix", - contentsStr: "HOME=/home/user/something", - data: map[string]interface{}{ - "homeDir": "/home/user", - }, - expected: "HOME={{ .homeDir }}/something", - }, - { - name: "words_only", - contentsStr: "aaa aa a aa aaa aa a aa aaa", - data: map[string]interface{}{ - "alpha": "a", - }, - expected: "aaa aa {{ .alpha }} aa aaa aa {{ .alpha }} aa aaa", - }, - { - name: "words_only_2", - contentsStr: "aaa aa a aa aaa aa a aa aaa", - data: map[string]interface{}{ - "alpha": "aa", - }, - expected: "aaa {{ .alpha }} a {{ .alpha }} aaa {{ .alpha }} a {{ .alpha }} aaa", - }, - { - name: "words_only_3", - contentsStr: "aaa aa a aa aaa aa a aa aaa", - data: map[string]interface{}{ - "alpha": "aaa", - }, - expected: "{{ .alpha }} aa a aa {{ .alpha }} aa a aa {{ .alpha }}", - }, - { - name: "skip_empty", - contentsStr: "a", - data: map[string]interface{}{ - "empty": "", - }, - expected: "a", - }, - } { - t.Run(tc.name, func(t *testing.T) { - assert.Equal(t, tc.expected, string(autoTemplate([]byte(tc.contentsStr), tc.data))) - }) - } -} - -func TestInWord(t *testing.T) { - for _, tc := range []struct { - s string - i int - expected bool - }{ - {s: "", i: 0, expected: false}, - {s: "a", i: 0, expected: false}, - {s: "a", i: 1, expected: false}, - {s: "ab", i: 0, expected: false}, - {s: "ab", i: 1, expected: true}, - {s: "ab", i: 2, expected: false}, - {s: "abc", i: 0, expected: false}, - {s: "abc", i: 1, expected: true}, - {s: "abc", i: 2, expected: true}, - {s: "abc", i: 3, expected: false}, - {s: " abc ", i: 0, expected: false}, - {s: " abc ", i: 1, expected: false}, - {s: " abc ", i: 2, expected: true}, - {s: " abc ", i: 3, expected: true}, - {s: " abc ", i: 4, expected: false}, - {s: " abc ", i: 5, expected: false}, - {s: "/home/user", i: 0, expected: false}, - {s: "/home/user", i: 1, expected: false}, - {s: "/home/user", i: 2, expected: true}, - {s: "/home/user", i: 3, expected: true}, - {s: "/home/user", i: 4, expected: true}, - {s: "/home/user", i: 5, expected: false}, - {s: "/home/user", i: 6, expected: false}, - {s: "/home/user", i: 7, expected: true}, - {s: "/home/user", i: 8, expected: true}, - {s: "/home/user", i: 9, expected: true}, - {s: "/home/user", i: 10, expected: false}, - } { - assert.Equal(t, tc.expected, inWord(tc.s, tc.i)) - } -} diff --git a/chezmoi2/internal/chezmoi/boltpersistentstate.go b/chezmoi2/internal/chezmoi/boltpersistentstate.go deleted file mode 100644 index 70bf2c5f190..00000000000 --- a/chezmoi2/internal/chezmoi/boltpersistentstate.go +++ /dev/null @@ -1,145 +0,0 @@ -package chezmoi - -import ( - "os" - "time" - - "go.etcd.io/bbolt" -) - -// A BoltPersistentStateMode is a mode for opening a PersistentState. -type BoltPersistentStateMode int - -// PersistentStateModes. -const ( - BoltPersistentStateReadOnly BoltPersistentStateMode = iota - BoltPersistentStateReadWrite -) - -// A BoltPersistentState is a state persisted with bolt. -type BoltPersistentState struct { - db *bbolt.DB -} - -// NewBoltPersistentState returns a new BoltPersistentState. -func NewBoltPersistentState(system System, path AbsPath, mode BoltPersistentStateMode) (*BoltPersistentState, error) { - if _, err := system.Stat(path); os.IsNotExist(err) { - if mode == BoltPersistentStateReadOnly { - return &BoltPersistentState{}, nil - } - if err := MkdirAll(system, path.Dir(), 0o777); err != nil { - return nil, err - } - } - options := bbolt.Options{ - OpenFile: func(name string, flag int, perm os.FileMode) (*os.File, error) { - rawPath, err := system.RawPath(AbsPath(name)) - if err != nil { - return nil, err - } - return os.OpenFile(string(rawPath), flag, perm) - }, - ReadOnly: mode == BoltPersistentStateReadOnly, - Timeout: time.Second, - } - db, err := bbolt.Open(string(path), 0o600, &options) - if err != nil { - return nil, err - } - return &BoltPersistentState{ - db: db, - }, nil -} - -// Close closes b. -func (b *BoltPersistentState) Close() error { - if b.db == nil { - return nil - } - return b.db.Close() -} - -// CopyTo copies b to p. -func (b *BoltPersistentState) CopyTo(p PersistentState) error { - if b.db == nil { - return nil - } - - return b.db.View(func(tx *bbolt.Tx) error { - return tx.ForEach(func(bucket []byte, b *bbolt.Bucket) error { - return b.ForEach(func(key, value []byte) error { - return p.Set(copyByteSlice(bucket), copyByteSlice(key), copyByteSlice(value)) - }) - }) - }) -} - -// Delete deletes the value associate with key in bucket. If bucket or key does -// not exist then Delete does nothing. -func (b *BoltPersistentState) Delete(bucket, key []byte) error { - return b.db.Update(func(tx *bbolt.Tx) error { - b := tx.Bucket(bucket) - if b == nil { - return nil - } - return b.Delete(key) - }) -} - -// ForEach calls fn for each key, value pair in bucket. -func (b *BoltPersistentState) ForEach(bucket []byte, fn func(k, v []byte) error) error { - if b.db == nil { - return nil - } - - return b.db.View(func(tx *bbolt.Tx) error { - b := tx.Bucket(bucket) - if b == nil { - return nil - } - return b.ForEach(func(k, v []byte) error { - return fn(copyByteSlice(k), copyByteSlice(v)) - }) - }) -} - -// Get returns the value associated with key in bucket. -func (b *BoltPersistentState) Get(bucket, key []byte) ([]byte, error) { - if b.db == nil { - return nil, nil - } - - var value []byte - if err := b.db.View(func(tx *bbolt.Tx) error { - b := tx.Bucket(bucket) - if b == nil { - return nil - } - value = copyByteSlice(b.Get(key)) - return nil - }); err != nil { - return nil, err - } - return value, nil -} - -// Set sets the value associated with key in bucket. bucket will be created if -// it does not already exist. -func (b *BoltPersistentState) Set(bucket, key, value []byte) error { - return b.db.Update(func(tx *bbolt.Tx) error { - b, err := tx.CreateBucketIfNotExists(bucket) - if err != nil { - return err - } - return b.Put(key, value) - }) -} - -func copyByteSlice(value []byte) []byte { - if value == nil { - return nil - } - result := make([]byte, len(value)) - copy(result, value) - return result -} diff --git a/chezmoi2/internal/chezmoi/boltpersistentstate_test.go b/chezmoi2/internal/chezmoi/boltpersistentstate_test.go deleted file mode 100644 index bf877ad30a1..00000000000 --- a/chezmoi2/internal/chezmoi/boltpersistentstate_test.go +++ /dev/null @@ -1,144 +0,0 @@ -package chezmoi - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/twpayne/go-vfs" - "github.com/twpayne/go-vfs/vfst" - - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoitest" -) - -var _ PersistentState = &BoltPersistentState{} - -func TestBoltPersistentState(t *testing.T) { - chezmoitest.WithTestFS(t, nil, func(fs vfs.FS) { - var ( - s = NewRealSystem(fs) - path = AbsPath("/home/user/.config/chezmoi/chezmoistate.boltdb") - bucket = []byte("bucket") - key = []byte("key") - value = []byte("value") - ) - - b1, err := NewBoltPersistentState(s, path, BoltPersistentStateReadWrite) - require.NoError(t, err) - vfst.RunTests(t, fs, "", - vfst.TestPath(string(path), - vfst.TestModeIsRegular, - ), - ) - - actualValue, err := b1.Get(bucket, key) - require.NoError(t, err) - assert.Equal(t, []byte(nil), actualValue) - - assert.NoError(t, b1.Set(bucket, key, value)) - actualValue, err = b1.Get(bucket, key) - require.NoError(t, err) - assert.Equal(t, value, actualValue) - - visited := false - require.NoError(t, b1.ForEach(bucket, func(k, v []byte) error { - visited = true - assert.Equal(t, key, k) - assert.Equal(t, value, v) - return nil - })) - require.True(t, visited) - - require.NoError(t, b1.Close()) - - b2, err := NewBoltPersistentState(s, path, BoltPersistentStateReadWrite) - require.NoError(t, err) - - require.NoError(t, b2.Delete(bucket, key)) - - actualValue, err = b2.Get(bucket, key) - require.NoError(t, err) - assert.Equal(t, []byte(nil), actualValue) - }) -} - -func TestBoltPersistentStateMock(t *testing.T) { - chezmoitest.WithTestFS(t, nil, func(fs vfs.FS) { - var ( - s = NewRealSystem(fs) - path = AbsPath("/home/user/.config/chezmoi/chezmoistate.boltdb") - bucket = []byte("bucket") - key = []byte("key") - value1 = []byte("value1") - value2 = []byte("value2") - ) - - b, err := NewBoltPersistentState(s, path, BoltPersistentStateReadWrite) - require.NoError(t, err) - require.NoError(t, b.Set(bucket, key, value1)) - - m := NewMockPersistentState() - require.NoError(t, b.CopyTo(m), err) - - actualValue, err := m.Get(bucket, key) - require.NoError(t, err) - assert.Equal(t, value1, actualValue) - - require.NoError(t, m.Set(bucket, key, value2)) - actualValue, err = m.Get(bucket, key) - require.NoError(t, err) - assert.Equal(t, value2, actualValue) - actualValue, err = b.Get(bucket, key) - require.NoError(t, err) - assert.Equal(t, value1, actualValue) - - require.NoError(t, m.Delete(bucket, key)) - actualValue, err = m.Get(bucket, key) - require.NoError(t, err) - assert.Nil(t, actualValue) - actualValue, err = b.Get(bucket, key) - require.NoError(t, err) - assert.Equal(t, value1, actualValue) - - require.NoError(t, b.Close()) - }) -} - -func TestBoltPersistentStateReadOnly(t *testing.T) { - chezmoitest.WithTestFS(t, nil, func(fs vfs.FS) { - var ( - s = NewRealSystem(fs) - path = AbsPath("/home/user/.config/chezmoi/chezmoistate.boltdb") - bucket = []byte("bucket") - key = []byte("key") - value = []byte("value") - ) - - b1, err := NewBoltPersistentState(s, path, BoltPersistentStateReadWrite) - require.NoError(t, err) - require.NoError(t, b1.Set(bucket, key, value)) - require.NoError(t, b1.Close()) - - b2, err := NewBoltPersistentState(s, path, BoltPersistentStateReadOnly) - require.NoError(t, err) - defer b2.Close() - - b3, err := NewBoltPersistentState(s, path, BoltPersistentStateReadOnly) - require.NoError(t, err) - defer b3.Close() - - actualValueB, err := b2.Get(bucket, key) - require.NoError(t, err) - assert.Equal(t, value, actualValueB) - - actualValueC, err := b3.Get(bucket, key) - require.NoError(t, err) - assert.Equal(t, value, actualValueC) - - assert.Error(t, b2.Set(bucket, key, value)) - assert.Error(t, b3.Set(bucket, key, value)) - - require.NoError(t, b2.Close()) - require.NoError(t, b3.Close()) - }) -} diff --git a/chezmoi2/internal/chezmoi/chezmoi.go b/chezmoi2/internal/chezmoi/chezmoi.go deleted file mode 100644 index d39469c87f0..00000000000 --- a/chezmoi2/internal/chezmoi/chezmoi.go +++ /dev/null @@ -1,163 +0,0 @@ -package chezmoi - -import ( - "bytes" - "crypto/sha256" - "fmt" - "os" - "path/filepath" - "strings" -) - -var ( - // DefaultTemplateOptions are the default template options. - DefaultTemplateOptions = []string{"missingkey=error"} - - // Skip indicates that entry should be skipped. - Skip = filepath.SkipDir - - // Umask is the process's umask. - Umask = os.FileMode(0) -) - -// Suffixes and prefixes. -const ( - ignorePrefix = "." - afterPrefix = "after_" - beforePrefix = "before_" - createPrefix = "create_" - dotPrefix = "dot_" - emptyPrefix = "empty_" - encryptedPrefix = "encrypted_" - exactPrefix = "exact_" - executablePrefix = "executable_" - modifyPrefix = "modify_" - oncePrefix = "once_" - privatePrefix = "private_" - runPrefix = "run_" - symlinkPrefix = "symlink_" - TemplateSuffix = ".tmpl" -) - -// Special file names. -const ( - Prefix = ".chezmoi" - - dataName = Prefix + "data" - ignoreName = Prefix + "ignore" - removeName = Prefix + "remove" - templatesDirName = Prefix + "templates" - versionName = Prefix + "version" -) - -var knownPrefixedFiles = map[string]bool{ - Prefix + ".json" + TemplateSuffix: true, - Prefix + ".toml" + TemplateSuffix: true, - Prefix + ".yaml" + TemplateSuffix: true, - dataName: true, - ignoreName: true, - removeName: true, - versionName: true, -} - -var modeTypeNames = map[os.FileMode]string{ - 0: "file", - os.ModeDir: "dir", - os.ModeSymlink: "symlink", - os.ModeNamedPipe: "named pipe", - os.ModeSocket: "socket", - os.ModeDevice: "device", - os.ModeCharDevice: "char device", -} - -type errDuplicateTarget struct { - targetRelPath RelPath - sourceRelPaths SourceRelPaths -} - -func (e *errDuplicateTarget) Error() string { - sourceRelPathStrs := make([]string, 0, len(e.sourceRelPaths)) - for _, sourceRelPath := range e.sourceRelPaths { - sourceRelPathStrs = append(sourceRelPathStrs, sourceRelPath.String()) - } - return fmt.Sprintf("%s: duplicate source state entries (%s)", e.targetRelPath, strings.Join(sourceRelPathStrs, ", ")) -} - -type errNotInAbsDir struct { - pathAbsPath AbsPath - dirAbsPath AbsPath -} - -func (e *errNotInAbsDir) Error() string { - return fmt.Sprintf("%s: not in %s", e.pathAbsPath, e.dirAbsPath) -} - -type errNotInRelDir struct { - pathRelPath RelPath - dirRelPath RelPath -} - -func (e *errNotInRelDir) Error() string { - return fmt.Sprintf("%s: not in %s", e.pathRelPath, e.dirRelPath) -} - -type errUnsupportedFileType struct { - absPath AbsPath - mode os.FileMode -} - -func (e *errUnsupportedFileType) Error() string { - return fmt.Sprintf("%s: unsupported file type %s", e.absPath, modeTypeName(e.mode)) -} - -// SHA256Sum returns the SHA256 sum of data. -func SHA256Sum(data []byte) []byte { - sha256SumArr := sha256.Sum256(data) - return sha256SumArr[:] -} - -// SuspiciousSourceDirEntry returns true if base is a suspicous dir entry. -func SuspiciousSourceDirEntry(base string, info os.FileInfo) bool { - //nolint:exhaustive - switch info.Mode() & os.ModeType { - case 0: - return strings.HasPrefix(base, Prefix) && !knownPrefixedFiles[base] - case os.ModeDir: - return strings.HasPrefix(base, Prefix) && base != templatesDirName - case os.ModeSymlink: - return strings.HasPrefix(base, Prefix) - default: - return true - } -} - -// isEmpty returns true if data is empty after trimming whitespace from both -// ends. -func isEmpty(data []byte) bool { - return len(bytes.TrimSpace(data)) == 0 -} - -func modeTypeName(mode os.FileMode) string { - if name, ok := modeTypeNames[mode&os.ModeType]; ok { - return name - } - return fmt.Sprintf("0o%o: unknown type", mode&os.ModeType) -} - -// mustTrimPrefix is like strings.TrimPrefix but panics if s is not prefixed by -// prefix. -func mustTrimPrefix(s, prefix string) string { - if !strings.HasPrefix(s, prefix) { - panic(fmt.Sprintf("%s: not prefixed by %s", s, prefix)) - } - return s[len(prefix):] -} - -// mustTrimSuffix is like strings.TrimSuffix but panics if s is not suffixed by -// suffix. -func mustTrimSuffix(s, suffix string) string { - if !strings.HasSuffix(s, suffix) { - panic(fmt.Sprintf("%s: not suffixed by %s", s, suffix)) - } - return s[:len(s)-len(suffix)] -} diff --git a/chezmoi2/internal/chezmoi/chezmoi_test.go b/chezmoi2/internal/chezmoi/chezmoi_test.go deleted file mode 100644 index 858c016d295..00000000000 --- a/chezmoi2/internal/chezmoi/chezmoi_test.go +++ /dev/null @@ -1,17 +0,0 @@ -package chezmoi - -import ( - "os" - - "github.com/rs/zerolog" - "github.com/rs/zerolog/log" - "github.com/rs/zerolog/pkgerrors" -) - -func init() { - log.Logger = log.Output(zerolog.ConsoleWriter{ - Out: os.Stderr, - NoColor: true, - }) - zerolog.ErrorStackMarshaler = pkgerrors.MarshalStack -} diff --git a/chezmoi2/internal/chezmoi/chezmoi_unix.go b/chezmoi2/internal/chezmoi/chezmoi_unix.go deleted file mode 100644 index 406dd4d7f48..00000000000 --- a/chezmoi2/internal/chezmoi/chezmoi_unix.go +++ /dev/null @@ -1,74 +0,0 @@ -// +build !windows - -package chezmoi - -import ( - "bufio" - "bytes" - "net" - "os" - "regexp" - "strings" - "syscall" - - vfs "github.com/twpayne/go-vfs" -) - -var whitespaceRx = regexp.MustCompile(`\s+`) - -func init() { - Umask = os.FileMode(syscall.Umask(0)) - syscall.Umask(int(Umask)) -} - -// FQDNHostname returns the FQDN hostname. -func FQDNHostname(fs vfs.FS) (string, error) { - if fqdnHostname, err := etcHostsFQDNHostname(fs); err == nil && fqdnHostname != "" { - return fqdnHostname, nil - } - return lookupAddrFQDNHostname() -} - -// etcHostsFQDNHostname returns the FQDN hostname from parsing /etc/hosts. -func etcHostsFQDNHostname(fs vfs.FS) (string, error) { - etcHostsContents, err := fs.ReadFile("/etc/hosts") - if err != nil { - return "", err - } - s := bufio.NewScanner(bytes.NewReader(etcHostsContents)) - for s.Scan() { - text := s.Text() - text = strings.TrimSpace(text) - if index := strings.IndexByte(text, '#'); index != -1 { - text = text[:index] - } - fields := whitespaceRx.Split(text, -1) - if len(fields) >= 2 && fields[0] == "127.0.1.1" { - return fields[1], nil - } - } - return "", s.Err() -} - -// isExecutable returns if info is executable. -func isExecutable(info os.FileInfo) bool { - return info.Mode().Perm()&0o111 != 0 -} - -// isPrivate returns if info is private. -func isPrivate(info os.FileInfo) bool { - return info.Mode().Perm()&0o77 == 0 -} - -// lookupAddrFQDNHostname returns the FQDN hostname by doing a reverse lookup of -// 127.0.1.1. -func lookupAddrFQDNHostname() (string, error) { - names, err := net.LookupAddr("127.0.1.1") - if err != nil { - return "", err - } - if len(names) == 0 { - return "", nil - } - return strings.TrimSuffix(names[0], "."), nil -} diff --git a/chezmoi2/internal/chezmoi/chezmoi_windows.go b/chezmoi2/internal/chezmoi/chezmoi_windows.go deleted file mode 100644 index dd027fbe4f5..00000000000 --- a/chezmoi2/internal/chezmoi/chezmoi_windows.go +++ /dev/null @@ -1,39 +0,0 @@ -package chezmoi - -import ( - "errors" - "os" - "unicode/utf16" - - vfs "github.com/twpayne/go-vfs" - "golang.org/x/sys/windows" -) - -// FQDNHostname returns the machine's fully-qualified DNS domain name. -func FQDNHostname(fs vfs.FS) (string, error) { - n := uint32(windows.MAX_COMPUTERNAME_LENGTH + 1) - buf := make([]uint16, n) - err := windows.GetComputerNameEx(windows.ComputerNameDnsFullyQualified, &buf[0], &n) - if errors.Is(err, windows.ERROR_MORE_DATA) { - buf = make([]uint16, n) - err = windows.GetComputerNameEx(windows.ComputerNameDnsFullyQualified, &buf[0], &n) - } - if err != nil { - return "", err - } - return string(utf16.Decode(buf[0:n])), nil -} - -// isExecutable returns false on Windows. -func isExecutable(info os.FileInfo) bool { - return false -} - -// isPrivate returns false on Windows. -func isPrivate(info os.FileInfo) bool { - return false -} - -func isSlash(c uint8) bool { - return c == '\\' || c == '/' -} diff --git a/chezmoi2/internal/chezmoi/doublestaros.go b/chezmoi2/internal/chezmoi/doublestaros.go deleted file mode 100644 index a9554c836cd..00000000000 --- a/chezmoi2/internal/chezmoi/doublestaros.go +++ /dev/null @@ -1,21 +0,0 @@ -package chezmoi - -import ( - "os" - - "github.com/bmatcuk/doublestar/v3" - vfs "github.com/twpayne/go-vfs" -) - -// A doubleStarOS embeds a vfs.FS into a value that implements doublestar.OS. -type doubleStarOS struct { - vfs.FS -} - -func (os doubleStarOS) Lstat(name string) (os.FileInfo, error) { - return os.FS.Lstat(name) -} - -func (os doubleStarOS) Open(name string) (doublestar.File, error) { - return os.FS.Open(name) -} diff --git a/chezmoi2/internal/chezmoi/includeset.go b/chezmoi2/internal/chezmoi/includeset.go deleted file mode 100644 index a54423ac706..00000000000 --- a/chezmoi2/internal/chezmoi/includeset.go +++ /dev/null @@ -1,160 +0,0 @@ -package chezmoi - -// FIXME Add IncludeEncrypted - -import ( - "fmt" - "os" - "strings" -) - -// An IncludeSet controls what types of entries to include. It parses and prints -// as a comma-separated list of strings, but is internally represented as a -// bitmask. *IncludeSet implements the github.com/spf13/pflag.Value interface. -type IncludeSet struct { - bits IncludeBits -} - -// An IncludeBits is a bitmask of entries to include. -type IncludeBits int - -// Include bits. -const ( - IncludeDirs IncludeBits = 1 << iota - IncludeFiles - IncludeRemove - IncludeScripts - IncludeSymlinks - - // IncludeAll is all include bits. - IncludeAll IncludeBits = IncludeDirs | IncludeFiles | IncludeRemove | IncludeScripts | IncludeSymlinks - - // includeNone is no include bits. - includeNone IncludeBits = 0 -) - -// includeBits is a map from human-readable strings to IncludeBits. -var includeBits = map[string]IncludeBits{ - "all": IncludeAll, - "dirs": IncludeDirs, - "files": IncludeFiles, - "remove": IncludeRemove, - "scripts": IncludeScripts, - "symlinks": IncludeSymlinks, -} - -// NewIncludeSet returns a new IncludeSet. -func NewIncludeSet(bits IncludeBits) *IncludeSet { - return &IncludeSet{ - bits: bits, - } -} - -// IncludeActualStateEntry returns true if actualStateEntry should be included. -func (s *IncludeSet) IncludeActualStateEntry(actualStateEntry ActualStateEntry) bool { - switch actualStateEntry.(type) { - case *ActualStateAbsent: - return s.bits&IncludeRemove != 0 - case *ActualStateDir: - return s.bits&IncludeDirs != 0 - case *ActualStateFile: - return s.bits&IncludeFiles != 0 - case *ActualStateSymlink: - return s.bits&IncludeSymlinks != 0 - default: - return false - } -} - -// IncludeFileInfo returns true if info should be included. -func (s *IncludeSet) IncludeFileInfo(info os.FileInfo) bool { - switch { - case info.IsDir(): - return s.bits&IncludeDirs != 0 - case info.Mode().IsRegular(): - return s.bits&IncludeFiles != 0 - case info.Mode()&os.ModeType == os.ModeSymlink: - return s.bits&IncludeSymlinks != 0 - default: - return false - } -} - -// IncludeTargetStateEntry returns true if targetStateEntry should be included. -func (s *IncludeSet) IncludeTargetStateEntry(targetStateEntry TargetStateEntry) bool { - switch targetStateEntry.(type) { - case *TargetStateDir: - return s.bits&IncludeDirs != 0 - case *TargetStateFile: - return s.bits&IncludeFiles != 0 - case *TargetStateRemove: - return s.bits&IncludeRemove != 0 - case *TargetStateScript: - return s.bits&IncludeScripts != 0 - case *TargetStateSymlink: - return s.bits&IncludeSymlinks != 0 - case *targetStateRenameDir: - return s.bits&IncludeDirs != 0 - default: - return false - } -} - -// Set implements github.com/spf13/pflag.Value.Set. -func (s *IncludeSet) Set(str string) error { - if str == "none" { - s.bits = includeNone - return nil - } - - var bits IncludeBits - for _, element := range strings.Split(str, ",") { - if element == "" { - continue - } - exclude := false - if strings.HasPrefix(element, "!") { - exclude = true - element = element[1:] - } - bit, ok := includeBits[element] - if !ok { - return fmt.Errorf("%s: unknown include element", element) - } - if exclude { - bits &^= bit - } else { - bits |= bit - } - } - s.bits = bits - return nil -} - -func (s *IncludeSet) String() string { - //nolint:exhaustive - switch s.bits { - case IncludeAll: - return "all" - case includeNone: - return "none" - } - var elements []string - for i, element := range []string{ - "dirs", - "files", - "remove", - "scripts", - "symlinks", - } { - if s.bits&(1<<i) != 0 { - elements = append(elements, element) - } - } - return strings.Join(elements, ",") -} - -// Type implements github.com/spf13/pflag.Value.Type. -func (s *IncludeSet) Type() string { - return "include set" -} diff --git a/chezmoi2/internal/chezmoi/maybeshellquote.go b/chezmoi2/internal/chezmoi/maybeshellquote.go deleted file mode 100644 index e09220c9270..00000000000 --- a/chezmoi2/internal/chezmoi/maybeshellquote.go +++ /dev/null @@ -1,63 +0,0 @@ -package chezmoi - -import ( - "regexp" - "strings" -) - -// nonShellLiteralRx is a regular expression that matches anything that is not a -// shell literal. -var nonShellLiteralRx = regexp.MustCompile(`[^+\-./0-9=A-Z_a-z]`) - -// maybeShellQuote returns s quoted as a shell argument, if necessary. -func maybeShellQuote(s string) string { - const ( - backslash = '\\' - singleQuote = '\'' - ) - - switch { - case s == "": - return "''" - case nonShellLiteralRx.MatchString(s): - result := make([]byte, 0, 2+len(s)) - inSingleQuotes := false - for _, b := range []byte(s) { - switch b { - case backslash: - if !inSingleQuotes { - result = append(result, singleQuote) - inSingleQuotes = true - } - result = append(result, backslash, backslash) - case singleQuote: - if inSingleQuotes { - result = append(result, singleQuote) - inSingleQuotes = false - } - result = append(result, '\\', singleQuote) - default: - if !inSingleQuotes { - result = append(result, singleQuote) - inSingleQuotes = true - } - result = append(result, b) - } - } - if inSingleQuotes { - result = append(result, singleQuote) - } - return string(result) - default: - return s - } -} - -// ShellQuoteArgs returs args shell quoted and joined into a single string. -func ShellQuoteArgs(args []string) string { - shellQuotedArgs := make([]string, 0, len(args)) - for _, arg := range args { - shellQuotedArgs = append(shellQuotedArgs, maybeShellQuote(arg)) - } - return strings.Join(shellQuotedArgs, " ") -} diff --git a/chezmoi2/internal/chezmoi/maybeshellquote_test.go b/chezmoi2/internal/chezmoi/maybeshellquote_test.go deleted file mode 100644 index 37b174fb200..00000000000 --- a/chezmoi2/internal/chezmoi/maybeshellquote_test.go +++ /dev/null @@ -1,48 +0,0 @@ -package chezmoi - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestMaybeShellQuote(t *testing.T) { - for s, expected := range map[string]string{ - ``: `''`, - `'`: `\'`, - `''`: `\'\'`, - `'a'`: `\''a'\'`, - `\`: `'\\'`, - `\a`: `'\\a'`, - `$a`: `'$a'`, - `a`: `a`, - `a/b`: `a/b`, - `a b`: `'a b'`, - `--arg`: `--arg`, - `--arg=value`: `--arg=value`, - } { - assert.Equal(t, expected, maybeShellQuote(s), "quoting %q", s) - } -} - -func TestShellQuoteArgs(t *testing.T) { - for _, tc := range []struct { - args []string - expected string - }{ - { - args: []string{}, - expected: "", - }, - { - args: []string{"foo"}, - expected: "foo", - }, - { - args: []string{"foo", "bar baz"}, - expected: "foo 'bar baz'", - }, - } { - assert.Equal(t, tc.expected, ShellQuoteArgs(tc.args)) - } -} diff --git a/chezmoi2/internal/chezmoi/patternset.go b/chezmoi2/internal/chezmoi/patternset.go deleted file mode 100644 index 280a09d318b..00000000000 --- a/chezmoi2/internal/chezmoi/patternset.go +++ /dev/null @@ -1,108 +0,0 @@ -package chezmoi - -import ( - "path/filepath" - "sort" - - "github.com/bmatcuk/doublestar/v3" - vfs "github.com/twpayne/go-vfs" -) - -// A stringSet is a set of strings. -type stringSet map[string]struct{} - -// An patternSet is a set of patterns. -type patternSet struct { - includePatterns stringSet - excludePatterns stringSet -} - -// newPatternSet returns a new patternSet. -func newPatternSet() *patternSet { - return &patternSet{ - includePatterns: newStringSet(), - excludePatterns: newStringSet(), - } -} - -// add adds a pattern to ps. -func (ps *patternSet) add(pattern string, include bool) error { - if _, err := doublestar.Match(pattern, ""); err != nil { - return err - } - if include { - ps.includePatterns.add(pattern) - } else { - ps.excludePatterns.add(pattern) - } - return nil -} - -// glob returns all matches in fs. -func (ps *patternSet) glob(fs vfs.FS, prefix string) ([]string, error) { - // FIXME use AbsPath and RelPath - vos := doubleStarOS{FS: fs} - allMatches := newStringSet() - for includePattern := range ps.includePatterns { - matches, err := doublestar.GlobOS(vos, prefix+includePattern) - if err != nil { - return nil, err - } - allMatches.add(matches...) - } - for match := range allMatches { - for excludePattern := range ps.excludePatterns { - exclude, err := doublestar.PathMatchOS(vos, prefix+excludePattern, match) - if err != nil { - return nil, err - } - if exclude { - delete(allMatches, match) - } - } - } - matchesSlice := allMatches.elements() - for i, match := range matchesSlice { - matchesSlice[i] = mustTrimPrefix(filepath.ToSlash(match), prefix) - } - sort.Strings(matchesSlice) - return matchesSlice, nil -} - -// match returns if name matches any pattern in ps. -func (ps *patternSet) match(name string) bool { - for pattern := range ps.excludePatterns { - if ok, _ := doublestar.Match(pattern, name); ok { - return false - } - } - for pattern := range ps.includePatterns { - if ok, _ := doublestar.Match(pattern, name); ok { - return true - } - } - return false -} - -// newStringSet returns a new StringSet containing elements. -func newStringSet(elements ...string) stringSet { - s := make(stringSet) - s.add(elements...) - return s -} - -// add adds elements to s. -func (s stringSet) add(elements ...string) { - for _, element := range elements { - s[element] = struct{}{} - } -} - -// elements returns all the elements of s. -func (s stringSet) elements() []string { - elements := make([]string, 0, len(s)) - for element := range s { - elements = append(elements, element) - } - return elements -} diff --git a/chezmoi2/internal/chezmoi/patternset_test.go b/chezmoi2/internal/chezmoi/patternset_test.go deleted file mode 100644 index 778de13a8fe..00000000000 --- a/chezmoi2/internal/chezmoi/patternset_test.go +++ /dev/null @@ -1,148 +0,0 @@ -package chezmoi - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - vfs "github.com/twpayne/go-vfs" - - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoitest" -) - -func TestPatternSet(t *testing.T) { - for _, tc := range []struct { - name string - ps *patternSet - expectMatches map[string]bool - }{ - { - name: "empty", - ps: newPatternSet(), - expectMatches: map[string]bool{ - "foo": false, - }, - }, - { - name: "exact", - ps: mustNewPatternSet(t, map[string]bool{ - "foo": true, - }), - expectMatches: map[string]bool{ - "foo": true, - "bar": false, - }, - }, - { - name: "wildcard", - ps: mustNewPatternSet(t, map[string]bool{ - "b*": true, - }), - expectMatches: map[string]bool{ - "foo": false, - "bar": true, - "baz": true, - }, - }, - { - name: "exclude", - ps: mustNewPatternSet(t, map[string]bool{ - "b*": true, - "baz": false, - }), - expectMatches: map[string]bool{ - "foo": false, - "bar": true, - "baz": false, - }, - }, - { - name: "doublestar", - ps: mustNewPatternSet(t, map[string]bool{ - "**/foo": true, - }), - expectMatches: map[string]bool{ - "foo": true, - "bar/foo": true, - "baz/bar/foo": true, - }, - }, - } { - t.Run(tc.name, func(t *testing.T) { - for s, expectMatch := range tc.expectMatches { - assert.Equal(t, expectMatch, tc.ps.match(s)) - } - }) - } -} - -func TestPatternSetGlob(t *testing.T) { - for _, tc := range []struct { - name string - ps *patternSet - root interface{} - expectedMatches []string - }{ - { - name: "empty", - ps: newPatternSet(), - root: nil, - expectedMatches: []string{}, - }, - { - name: "simple", - ps: mustNewPatternSet(t, map[string]bool{ - "f*": true, - }), - root: map[string]interface{}{ - "foo": "", - }, - expectedMatches: []string{ - "foo", - }, - }, - { - name: "include_exclude", - ps: mustNewPatternSet(t, map[string]bool{ - "b*": true, - "*z": false, - }), - root: map[string]interface{}{ - "bar": "", - "baz": "", - }, - expectedMatches: []string{ - "bar", - }, - }, - { - name: "doublestar", - ps: mustNewPatternSet(t, map[string]bool{ - "**/f*": true, - }), - root: map[string]interface{}{ - "dir1/dir2/foo": "", - }, - expectedMatches: []string{ - "dir1/dir2/foo", - }, - }, - } { - t.Run(tc.name, func(t *testing.T) { - chezmoitest.WithTestFS(t, tc.root, func(fs vfs.FS) { - actualMatches, err := tc.ps.glob(fs, "/") - require.NoError(t, err) - assert.Equal(t, tc.expectedMatches, actualMatches) - }) - }) - } -} - -func mustNewPatternSet(t *testing.T, patterns map[string]bool) *patternSet { - t.Helper() - ps := newPatternSet() - for pattern, exclude := range patterns { - require.NoError(t, ps.add(pattern, exclude)) - } - return ps -} diff --git a/chezmoi2/main.go b/chezmoi2/main.go deleted file mode 100644 index bad585fa657..00000000000 --- a/chezmoi2/main.go +++ /dev/null @@ -1,34 +0,0 @@ -//go:generate go run ../internal/cmd/generate-assets -o cmd/docs.gen.go -tags=!noembeddocs -trimprefix=../ ../docs/CHANGES.md ../docs/COMPARISON.md ../docs/CONTRIBUTING.md ../docs/FAQ.md ../docs/HOWTO.md ../docs/INSTALL.md ../docs/MEDIA.md ../docs/QUICKSTART.md -//go:generate go run ../internal/cmd/generate-assets -o cmd/reference.gen.go -tags=!noembeddocs docs/REFERENCE.md -//go:generate go run ../internal/cmd/generate-assets -o cmd/templates.gen.go -trimprefix=../ ../assets/templates/COMMIT_MESSAGE.tmpl -//go:generate go run ../internal/cmd/generate-helps -o cmd/helps.gen.go -i docs/REFERENCE.md -//go:generate go run . completion bash -o completions/chezmoi2-completion.bash -//go:generate go run . completion fish -o completions/chezmoi2.fish -//go:generate go run . completion powershell -o completions/chezmoi2.ps1 -//go:generate go run . completion zsh -o completions/chezmoi2.zsh - -package main - -import ( - "os" - - "github.com/twpayne/chezmoi/chezmoi2/cmd" -) - -var ( - version string - commit string - date string - builtBy string -) - -func main() { - if exitCode := cmd.Main(cmd.VersionInfo{ - Version: version, - Commit: commit, - Date: date, - BuiltBy: builtBy, - }, os.Args[1:]); exitCode != 0 { - os.Exit(exitCode) - } -} diff --git a/chezmoi2/main_test.go b/chezmoi2/main_test.go deleted file mode 100644 index 041cf9e313f..00000000000 --- a/chezmoi2/main_test.go +++ /dev/null @@ -1,469 +0,0 @@ -package main - -import ( - "fmt" - "io/ioutil" - "os" - "path" - "path/filepath" - "runtime" - "strconv" - "strings" - "testing" - "time" - - "github.com/rogpeppe/go-internal/testscript" - "github.com/twpayne/go-vfs" - "github.com/twpayne/go-vfs/vfst" - - "github.com/twpayne/chezmoi/chezmoi2/cmd" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoitest" -) - -//nolint:interfacer -func TestMain(m *testing.M) { - os.Exit(testscript.RunMain(m, map[string]func() int{ - "chezmoi": func() int { - return cmd.Main(cmd.VersionInfo{ - Version: "v2.0.0+test", - Commit: "HEAD", - Date: time.Now().UTC().Format(time.RFC3339), - BuiltBy: "testscript", - }, os.Args[1:]) - }, - })) -} - -func TestScript(t *testing.T) { - testscript.Run(t, testscript.Params{ - Dir: filepath.Join("testdata", "scripts"), - Cmds: map[string]func(*testscript.TestScript, bool, []string){ - "appendline": cmdAppendLine, - "chhome": cmdChHome, - "cmpmod": cmdCmpMod, - "edit": cmdEdit, - "mkfile": cmdMkFile, - "mkageconfig": cmdMkAGEConfig, - "mkgitconfig": cmdMkGitConfig, - "mkgpgconfig": cmdMkGPGConfig, - "mkhomedir": cmdMkHomeDir, - "mksourcedir": cmdMkSourceDir, - "rmfinalnewline": cmdRmFinalNewline, - }, - Condition: func(cond string) (bool, error) { - switch cond { - case "darwin": - return runtime.GOOS == "darwin", nil - case "freebsd": - return runtime.GOOS == "freebsd", nil - case "githubactionsonwindows": - return chezmoitest.GitHubActionsOnWindows(), nil - case "windows": - return runtime.GOOS == "windows", nil - default: - return false, fmt.Errorf("%s: unknown condition", cond) - } - }, - Setup: setup, - UpdateScripts: os.Getenv("CHEZMOIUPDATESCRIPTS") != "", - }) -} - -// cmdAppendLine appends lines to a file. -func cmdAppendLine(ts *testscript.TestScript, neg bool, args []string) { - if neg { - ts.Fatalf("unsupported: ! appendline") - } - if len(args) != 2 { - ts.Fatalf("usage: appendline file line") - } - filename := ts.MkAbs(args[0]) - data, err := ioutil.ReadFile(filename) - ts.Check(err) - data = append(data, append([]byte(args[1]), '\n')...) - ts.Check(ioutil.WriteFile(filename, data, 0o666)) -} - -// cmdChHome changes the home directory to its argument, creating the directory -// if it does not already exist. It updates the HOME environment variable, and, -// if running on Windows, USERPROFILE too. -func cmdChHome(ts *testscript.TestScript, neg bool, args []string) { - if neg { - ts.Fatalf("unsupported: ! chhome") - } - if len(args) != 1 { - ts.Fatalf("usage: chhome dir") - } - var ( - homeDir = ts.MkAbs(args[0]) - chezmoiConfigDir = path.Join(homeDir, ".config", "chezmoi") - chezmoiSourceDir = path.Join(homeDir, ".local", "share", "chezmoi") - ) - ts.Check(os.MkdirAll(homeDir, 0o777)) - ts.Setenv("HOME", homeDir) - ts.Setenv("CHEZMOICONFIGDIR", chezmoiConfigDir) - ts.Setenv("CHEZMOISOURCEDIR", chezmoiSourceDir) - if runtime.GOOS == "windows" { - ts.Setenv("USERPROFILE", homeDir) - } -} - -// cmdCmpMod compares modes. -func cmdCmpMod(ts *testscript.TestScript, neg bool, args []string) { - if len(args) != 2 { - ts.Fatalf("usage: cmpmod mode path") - } - mode64, err := strconv.ParseUint(args[0], 8, 32) - if err != nil || os.FileMode(mode64).Perm() != os.FileMode(mode64) { - ts.Fatalf("invalid mode: %s", args[0]) - } - if runtime.GOOS == "windows" { - return - } - info, err := os.Stat(args[1]) - if err != nil { - ts.Fatalf("%s: %v", args[1], err) - } - equal := info.Mode().Perm() == os.FileMode(mode64)&^chezmoitest.Umask - if neg && equal { - ts.Fatalf("%s unexpectedly has mode %03o", args[1], info.Mode().Perm()) - } - if !neg && !equal { - ts.Fatalf("%s has mode %03o, expected %03o", args[1], info.Mode().Perm(), os.FileMode(mode64)&^chezmoitest.Umask) - } -} - -// cmdEdit edits all of its arguments by appending "# edited\n" to them. -func cmdEdit(ts *testscript.TestScript, neg bool, args []string) { - if neg { - ts.Fatalf("unsupported: ! edit") - } - for _, arg := range args { - filename := ts.MkAbs(arg) - data, err := ioutil.ReadFile(filename) - if err != nil { - ts.Fatalf("edit: %v", err) - } - data = append(data, []byte("# edited\n")...) - if err := ioutil.WriteFile(filename, data, 0o666); err != nil { - ts.Fatalf("edit: %v", err) - } - } -} - -// cmdMkFile creates empty files. -func cmdMkFile(ts *testscript.TestScript, neg bool, args []string) { - if neg { - ts.Fatalf("unsupported: ! mkfile") - } - perm := os.FileMode(0o666) - if len(args) >= 1 && strings.HasPrefix(args[0], "-perm=") { - permStr := strings.TrimPrefix(args[0], "-perm=") - permUint32, err := strconv.ParseUint(permStr, 8, 32) - if err != nil { - ts.Fatalf("%s: bad permissions", permStr) - } - perm = os.FileMode(permUint32) - args = args[1:] - } - for _, arg := range args { - filename := ts.MkAbs(arg) - _, err := os.Lstat(filename) - switch { - case err == nil: - ts.Fatalf("%s: already exists", arg) - case !os.IsNotExist(err): - ts.Fatalf("%s: %v", arg, err) - } - if err := ioutil.WriteFile(filename, nil, perm); err != nil { - ts.Fatalf("%s: %v", arg, err) - } - } -} - -// cmdMkAGEConfig creates a AGE key and a chezmoi configuration file. -func cmdMkAGEConfig(ts *testscript.TestScript, neg bool, args []string) { - if neg { - ts.Fatalf("unupported: ! mkageconfig") - } - if len(args) > 0 { - ts.Fatalf("usage: mkageconfig") - } - homeDir := ts.Getenv("HOME") - ts.Check(os.MkdirAll(homeDir, 0o777)) - privateKeyFile := filepath.Join(homeDir, "key.txt") - publicKey, _, err := chezmoitest.AGEGenerateKey(ts.MkAbs(privateKeyFile)) - ts.Check(err) - configFile := filepath.Join(homeDir, ".config", "chezmoi", "chezmoi.toml") - ts.Check(os.MkdirAll(filepath.Dir(configFile), 0o777)) - ts.Check(ioutil.WriteFile(configFile, []byte(fmt.Sprintf(chezmoitest.JoinLines( - `encryption = "age"`, - `[age]`, - ` identity = %q`, - ` recipient = %q`, - ), privateKeyFile, publicKey)), 0o666)) -} - -// cmdMkGitConfig makes a .gitconfig file in the home directory. -func cmdMkGitConfig(ts *testscript.TestScript, neg bool, args []string) { - if neg { - ts.Fatalf("unsupported: ! mkgitconfig") - } - if len(args) > 1 { - ts.Fatalf(("usage: mkgitconfig [path]")) - } - path := filepath.Join(ts.Getenv("HOME"), ".gitconfig") - if len(args) > 0 { - path = ts.MkAbs(args[0]) - } - ts.Check(os.MkdirAll(filepath.Dir(path), 0o777)) - ts.Check(ioutil.WriteFile(path, []byte(chezmoitest.JoinLines( - `[core]`, - ` autocrlf = false`, - `[user]`, - ` name = User`, - ` email = [email protected]`, - )), 0o666)) -} - -// cmdMkGPGConfig creates a GPG key and a chezmoi configuration file. -func cmdMkGPGConfig(ts *testscript.TestScript, neg bool, args []string) { - if neg { - ts.Fatalf("unupported: ! mkgpgconfig") - } - if len(args) > 0 { - ts.Fatalf("usage: mkgpgconfig") - } - - // Create a new directory for GPG. We can't use a subdirectory of the - // testscript's working directory because on darwin the absolute path can - // exceed GPG's limit of sockaddr_un.sun_path (107 characters, see man - // unix(7)). The limit exists because GPG creates a UNIX domain socket in - // its home directory and UNIX domain socket paths are limited to - // sockaddr_un.sun_path characters. - gpgHomeDir, err := ioutil.TempDir("", "chezmoi-test-gpg-homedir") - ts.Check(err) - ts.Defer(func() { - os.RemoveAll(gpgHomeDir) - }) - if runtime.GOOS != "windows" { - ts.Check(os.Chmod(gpgHomeDir, 0o700)) - } - - command, err := chezmoitest.GPGCommand() - ts.Check(err) - - key, passphrase, err := chezmoitest.GPGGenerateKey(command, gpgHomeDir) - ts.Check(err) - - configFile := filepath.Join(ts.Getenv("HOME"), ".config", "chezmoi", "chezmoi.toml") - ts.Check(os.MkdirAll(filepath.Dir(configFile), 0o777)) - ts.Check(ioutil.WriteFile(configFile, []byte(fmt.Sprintf(chezmoitest.JoinLines( - `encryption = "gpg"`, - `[gpg]`, - ` args = [`, - ` "--homedir", %q,`, - ` "--no-tty",`, - ` "--passphrase", %q,`, - ` "--pinentry-mode", "loopback",`, - ` ]`, - ` recipient = %q`, - ), gpgHomeDir, passphrase, key)), 0o666)) -} - -// cmdMkHomeDir makes and populates a home directory. -func cmdMkHomeDir(ts *testscript.TestScript, neg bool, args []string) { - if neg { - ts.Fatalf("unsupported: ! mkhomedir") - } - if len(args) > 1 { - ts.Fatalf(("usage: mkhomedir [path]")) - } - path := ts.Getenv("HOME") - if len(args) > 0 { - path = ts.MkAbs(args[0]) - } - workDir := ts.Getenv("WORK") - relPath, err := filepath.Rel(workDir, path) - ts.Check(err) - if err := vfst.NewBuilder().Build(vfs.NewPathFS(vfs.OSFS, workDir), map[string]interface{}{ - relPath: map[string]interface{}{ - ".create": "# contents of .create\n", - ".dir": map[string]interface{}{ - "file": "# contents of .dir/file\n", - "subdir": map[string]interface{}{ - "file": "# contents of .dir/subdir/file\n", - }, - }, - ".empty": "", - ".executable": &vfst.File{ - Perm: 0o777, - Contents: []byte("# contents of .executable\n"), - }, - ".file": "# contents of .file\n", - ".private": &vfst.File{ - Perm: 0o600, - Contents: []byte("# contents of .private\n"), - }, - ".symlink": &vfst.Symlink{Target: ".dir/subdir/file"}, - ".template": "key = value\n", - }, - }); err != nil { - ts.Fatalf("mkhomedir: %v", err) - } -} - -// cmdMkSourceDir makes and populates a source directory. -func cmdMkSourceDir(ts *testscript.TestScript, neg bool, args []string) { - if neg { - ts.Fatalf("unsupported: ! mksourcedir") - } - if len(args) > 1 { - ts.Fatalf("usage: mksourcedir [path]") - } - sourceDir := ts.Getenv("CHEZMOISOURCEDIR") - if len(args) > 0 { - sourceDir = ts.MkAbs(args[0]) - } - workDir := ts.Getenv("WORK") - relPath, err := filepath.Rel(workDir, sourceDir) - ts.Check(err) - err = vfst.NewBuilder().Build(vfs.NewPathFS(vfs.OSFS, workDir), map[string]interface{}{ - relPath: map[string]interface{}{ - "create_dot_create": "# contents of .create\n", - "dot_dir": map[string]interface{}{ - "file": "# contents of .dir/file\n", - "subdir": map[string]interface{}{ - "file": "# contents of .dir/subdir/file\n", - }, - }, - "dot_remove": "", - "empty_dot_empty": "", - "executable_dot_executable": "# contents of .executable\n", - "dot_file": "# contents of .file\n", - "private_dot_private": "# contents of .private\n", - "symlink_dot_symlink": ".dir/subdir/file\n", - "dot_template.tmpl": chezmoitest.JoinLines( - `key = {{ "value" }}`, - ), - }, - }) - if err != nil { - ts.Fatalf("mksourcedir: %v", err) - } -} - -// cmdRmFinalNewline removes final newlines. -func cmdRmFinalNewline(ts *testscript.TestScript, neg bool, args []string) { - if neg { - ts.Fatalf("unsupported: ! rmfinalnewline") - } - if len(args) < 1 { - ts.Fatalf("usage: rmfinalnewline paths...") - } - for _, arg := range args { - filename := ts.MkAbs(arg) - data, err := ioutil.ReadFile(filename) - if err != nil { - ts.Fatalf("%s: %v", filename, err) - } - if len(data) == 0 || data[len(data)-1] != '\n' { - continue - } - if err := ioutil.WriteFile(filename, data[:len(data)-1], 0o666); err != nil { - ts.Fatalf("%s: %v", filename, err) - } - } -} - -func prependDirToPath(dir, path string) string { - return strings.Join(append([]string{dir}, filepath.SplitList(path)...), string(os.PathListSeparator)) -} - -func setup(env *testscript.Env) error { - var ( - binDir = filepath.Join(env.WorkDir, "bin") - homeDir = filepath.Join(env.WorkDir, "home", "user") - ) - - absHomeDir, err := filepath.Abs(homeDir) - if err != nil { - return err - } - absSlashHomeDir := filepath.ToSlash(absHomeDir) - - var ( - chezmoiConfigDir = path.Join(absSlashHomeDir, ".config", "chezmoi") - chezmoiSourceDir = path.Join(absSlashHomeDir, ".local", "share", "chezmoi") - ) - - env.Setenv("HOME", homeDir) - env.Setenv("PATH", prependDirToPath(binDir, env.Getenv("PATH"))) - env.Setenv("CHEZMOICONFIGDIR", chezmoiConfigDir) - env.Setenv("CHEZMOISOURCEDIR", chezmoiSourceDir) - switch runtime.GOOS { - case "windows": - env.Setenv("EDITOR", filepath.Join(binDir, "editor.cmd")) - env.Setenv("USERPROFILE", homeDir) - // There is not currently a convenient way to override the shell on - // Windows. - default: - env.Setenv("EDITOR", filepath.Join(binDir, "editor")) - env.Setenv("SHELL", filepath.Join(binDir, "shell")) - } - - root := make(map[string]interface{}) - switch runtime.GOOS { - case "windows": - root["/bin"] = map[string]interface{}{ - // editor.cmd is a non-interactive script that appends "# edited\n" - // to the end of each file and creates an empty .edited file in each - // directory. - "editor.cmd": &vfst.File{ - Contents: []byte(chezmoitest.JoinLines( - `@echo off`, - `:loop`, - `IF EXIST %~s1\NUL (`, - ` copy /y NUL "%~1\.edited" >NUL`, - `) ELSE (`, - ` echo # edited >> "%~1"`, - `)`, - `shift`, - `IF NOT "%~1"=="" goto loop`, - )), - }, - } - default: - root["/bin"] = map[string]interface{}{ - // editor is a non-interactive script that appends "# edited\n" to - // the end of each file and creates an empty .edited file in each - // directory. - "editor": &vfst.File{ - Perm: 0o755, - Contents: []byte(chezmoitest.JoinLines( - `#!/bin/sh`, - ``, - `for name in $*; do`, - ` if [ -d $name ]; then`, - ` touch $name/.edited`, - ` else`, - ` echo "# edited" >> $name`, - ` fi`, - `done`, - )), - }, - // shell is a non-interactive script that appends the directory in - // which it was launched to $WORK/shell.log. - "shell": &vfst.File{ - Perm: 0o755, - Contents: []byte(chezmoitest.JoinLines( - `#!/bin/sh`, - ``, - `echo $PWD >> '`+filepath.Join(env.WorkDir, "shell.log")+`'`, - )), - }, - } - } - - return vfst.NewBuilder().Build(vfs.NewPathFS(vfs.OSFS, env.WorkDir), root) -} diff --git a/chezmoi2/testdata/scripts/add.txt b/chezmoi2/testdata/scripts/add.txt deleted file mode 100644 index 12e7df3f1c2..00000000000 --- a/chezmoi2/testdata/scripts/add.txt +++ /dev/null @@ -1,46 +0,0 @@ -mkhomedir -mksourcedir golden - -# test chezmoi add --create -chezmoi add --create $HOME${/}.create -cmp $CHEZMOISOURCEDIR/create_dot_create golden/create_dot_create - -# test adding a file in a directory -chezmoi add $HOME${/}.dir/file -cmp $CHEZMOISOURCEDIR/dot_dir/file golden/dot_dir/file - -# test adding a subdirectory -chezmoi add $HOME${/}.dir/subdir -cmp $CHEZMOISOURCEDIR/dot_dir/subdir/file golden/dot_dir/subdir/file - -# test adding an empty file without --empty -chezmoi add $HOME${/}.empty -! exists $CHEZMOISOURCEDIR/dot_empty - -# test adding an empty file with --empty -chezmoi add --empty $HOME${/}.empty -cmp $CHEZMOISOURCEDIR/empty_dot_empty golden/empty_dot_empty - -# test adding an executable file -chezmoi add $HOME${/}.executable -[!windows] cmp $CHEZMOISOURCEDIR/executable_dot_executable golden/executable_dot_executable -[windows] cmp $CHEZMOISOURCEDIR/dot_executable golden/executable_dot_executable - -# test adding a private file -chezmoi add $HOME${/}.private -[!windows] cmp $CHEZMOISOURCEDIR/private_dot_private $HOME/.private -[windows] cmp $CHEZMOISOURCEDIR/dot_private $HOME/.private - -# test adding a symlink -chezmoi add $HOME${/}.symlink -cmp $CHEZMOISOURCEDIR/symlink_dot_symlink golden/symlink_dot_symlink - -# test adding a symlink with a separator -symlink $HOME${/}.symlink2 -> .dir${/}subdir${/}file -chezmoi add $HOME${/}.symlink2 -cmp $CHEZMOISOURCEDIR/symlink_dot_symlink2 golden/symlink_dot_symlink - -# test adding a symlink with --follow -symlink $HOME${/}.symlink3 -> .file -chezmoi add --follow $HOME${/}.symlink3 -cmp $CHEZMOISOURCEDIR/dot_symlink3 golden/dot_file diff --git a/chezmoi2/testdata/scripts/addautotemplate.txt b/chezmoi2/testdata/scripts/addautotemplate.txt deleted file mode 100644 index 90085da336f..00000000000 --- a/chezmoi2/testdata/scripts/addautotemplate.txt +++ /dev/null @@ -1,18 +0,0 @@ -# test adding a file with --autotemplate -chezmoi add --autotemplate $HOME${/}.template -cmp $CHEZMOISOURCEDIR/dot_template.tmpl golden/dot_template.tmpl - -# test adding a symlink with --autotemplate -symlink $HOME/.symlink -> .target-value -chezmoi add --autotemplate $HOME${/}.symlink -cmp $CHEZMOISOURCEDIR/symlink_dot_symlink.tmpl golden/symlink_dot_symlink.tmpl - --- golden/dot_template.tmpl -- -key = {{ .variable }} --- golden/symlink_dot_symlink.tmpl -- -.target-{{ .variable }} --- home/user/.config/chezmoi/chezmoi.toml -- -[data] - variable = "value" --- home/user/.template -- -key = value diff --git a/chezmoi2/testdata/scripts/apply.txt b/chezmoi2/testdata/scripts/apply.txt deleted file mode 100644 index 490176b67f7..00000000000 --- a/chezmoi2/testdata/scripts/apply.txt +++ /dev/null @@ -1,71 +0,0 @@ -mkhomedir golden -mksourcedir - -# test that chezmoi apply --dry-run does not create any files -chezmoi apply --dry-run --force -! exists $HOME/.create -! exists $HOME/.dir -! exists $HOME/.dir/file -! exists $HOME/.dir/subdir -! exists $HOME/.dir/subdir/file -! exists $HOME/.empty -! exists $HOME/.executable -! exists $HOME/.file -! exists $HOME/.private -! exists $HOME/.remove -! exists $HOME/.template - -# test that chezmoi apply file creates a single file only -chezmoi apply --force $HOME${/}.file -! exists $HOME/.create -! exists $HOME/.dir -! exists $HOME/.dir/file -! exists $HOME/.dir/subdir -! exists $HOME/.dir/subdir/file -! exists $HOME/.empty -! exists $HOME/.executable -exists $HOME/.file -! exists $HOME/.private -! exists $HOME/.remove -! exists $HOME/.template - -# test that chezmoi apply dir --recursive=false creates only the directory -chezmoi apply --force --recursive=false $HOME${/}.dir -exists $HOME/.dir -! exists $HOME/.dir/file -! exists $HOME/.dir/subdir -! exists $HOME/.dir/subdir/file - -# test that chezmoi apply dir creates all files in the directory -chezmoi apply --force $HOME${/}.dir -exists $HOME/.dir -exists $HOME/.dir/file -exists $HOME/.dir/subdir -exists $HOME/.dir/subdir/file - -# test that chezmoi apply creates all files -chezmoi apply --force -exists $HOME/.create -exists $HOME/.dir -exists $HOME/.dir/file -exists $HOME/.dir/subdir -exists $HOME/.dir/subdir/file -exists $HOME/.empty -exists $HOME/.executable -exists $HOME/.file -exists $HOME/.private -! exists $HOME/.remove -exists $HOME/.template - -# test apply after edit -edit $CHEZMOISOURCEDIR/dot_file -chezmoi apply --force -cmp $HOME/.file $CHEZMOISOURCEDIR/dot_file - -# test that chezmoi apply --source-path applies a file based on its source path -edit $CHEZMOISOURCEDIR/dot_file -chezmoi apply --force --source-path $CHEZMOISOURCEDIR/dot_file -grep -count=2 '# edited' $HOME/.file - -# test that chezmoi apply --source-path fails when called with a targetDirAbsPath -! chezmoi apply --force --source-path $HOME${/}.file diff --git a/chezmoi2/testdata/scripts/applychmod.txt b/chezmoi2/testdata/scripts/applychmod.txt deleted file mode 100644 index f6f82a30612..00000000000 --- a/chezmoi2/testdata/scripts/applychmod.txt +++ /dev/null @@ -1,20 +0,0 @@ -[windows] stop - -mkhomedir golden -mkhomedir -mksourcedir - -# test change file mode -chmod 777 $HOME${/}.file -chezmoi apply --force -cmpmod 666 $HOME/.file - -# test change executable file mode -chmod 666 $HOME/.executable -chezmoi apply --force -cmpmod 777 $HOME/.executable - -# test change directory mode -chmod 700 $HOME/.dir -chezmoi apply --force -cmpmod 777 $HOME/.dir diff --git a/chezmoi2/testdata/scripts/applyexact.txt b/chezmoi2/testdata/scripts/applyexact.txt deleted file mode 100644 index ea1c71ee574..00000000000 --- a/chezmoi2/testdata/scripts/applyexact.txt +++ /dev/null @@ -1,20 +0,0 @@ -# test that chezmoi apply --dry-run does not remove entries from exact directories -chezmoi apply --dry-run --force -exists $HOME/.dir/file1 -exists $HOME/.dir/file2 -exists $HOME/.dir/subdir/file - -# test that chezmoi apply removes entries from exact directories -chezmoi apply --force -exists $HOME/.dir/file1 -! exists $HOME/.dir/file2 -! exists $HOME/.dir/subdir/file - --- home/user/.dir/file1 -- -# contents of .dir/file1 --- home/user/.dir/file2 -- -# contents of .dir/file2 --- home/user/.dir/subdir/file -- -# contents of .dir/subdir/file --- home/user/.local/share/chezmoi/exact_dot_dir/file1 -- -# contents of .dir/file1 diff --git a/chezmoi2/testdata/scripts/applyremove.txt b/chezmoi2/testdata/scripts/applyremove.txt deleted file mode 100644 index 9af27848d48..00000000000 --- a/chezmoi2/testdata/scripts/applyremove.txt +++ /dev/null @@ -1,27 +0,0 @@ -# test that chezmoi apply --dry-run --remove does not remove entries -chezmoi apply --dry-run --force --remove -exists $HOME/.dir/file -exists $HOME/.file1 -exists $HOME/.file2 - -# test that chezmoi apply --remove file removes only file -chezmoi apply --force --remove $HOME${/}.file1 -exists $HOME/.dir/file -! exists $HOME/.file1 -exists $HOME/.file2 - -# test that chezmoi apply --remove removes all entries -chezmoi apply --force --remove -! exists $HOME/.dir/file -! exists $HOME/.file1 -! exists $HOME/.file2 - --- home/user/.dir/file -- -# contents of .dir/file --- home/user/.file1 -- -# contents of .file1 --- home/user/.file2 -- -# contents of .file2 --- home/user/.local/share/chezmoi/.chezmoiremove -- -.dir -.file* diff --git a/chezmoi2/testdata/scripts/applytype.txt b/chezmoi2/testdata/scripts/applytype.txt deleted file mode 100644 index f9ac8fa5027..00000000000 --- a/chezmoi2/testdata/scripts/applytype.txt +++ /dev/null @@ -1,22 +0,0 @@ -mkhomedir golden -mkhomedir -mksourcedir - -# test replace directory with file -rm $HOME/.file -mkdir $HOME/.file -chezmoi apply --force -cmp $HOME/.file golden/.file - -# test replace file with directory -rm $HOME/.dir -mkfile $HOME/.dir -chezmoi apply --force -cmp $HOME/.dir/file golden/.dir/file -cmp $HOME/.dir/subdir/file golden/.dir/subdir/file - -# test replace file with symlink -rm $HOME/.symlink -mkfile $HOME/.symlink -chezmoi apply --force -cmp $HOME/.symlink golden/.symlink diff --git a/chezmoi2/testdata/scripts/autocommit.txt b/chezmoi2/testdata/scripts/autocommit.txt deleted file mode 100644 index 7fa2535377b..00000000000 --- a/chezmoi2/testdata/scripts/autocommit.txt +++ /dev/null @@ -1,26 +0,0 @@ -[!exec:git] skip 'git not found in $PATH' - -mkgitconfig -mkhomedir golden -mkhomedir - -chezmoi init - -# test that chezmoi add creates and pushes a commit -chezmoi add $HOME${/}.file -exec git --git-dir=$CHEZMOISOURCEDIR/.git show HEAD -stdout 'Add dot_file' - -# test that chezmoi edit creates and pushes a commit -chezmoi edit $HOME${/}.file -exec git --git-dir=$CHEZMOISOURCEDIR/.git show HEAD -stdout 'Update dot_file' - -# test that chezmoi forget creates and pushes a commit -chezmoi forget --force $HOME${/}.file -exec git --git-dir=$CHEZMOISOURCEDIR/.git show HEAD -stdout 'Remove dot_file' - --- home/user/.config/chezmoi/chezmoi.toml -- -[git] - autoCommit = true diff --git a/chezmoi2/testdata/scripts/autopush.txt b/chezmoi2/testdata/scripts/autopush.txt deleted file mode 100644 index 59ba04bf2fa..00000000000 --- a/chezmoi2/testdata/scripts/autopush.txt +++ /dev/null @@ -1,28 +0,0 @@ -[!exec:git] skip 'git not found in $PATH' - -mkgitconfig -mkhomedir golden -mkhomedir - -# create a repo -exec git init --bare $WORK/dotfiles.git -chezmoi init file://$WORK/dotfiles.git - -# test that chezmoi add creates and pushes a commit -chezmoi add $HOME${/}.file -exec git --git-dir=$WORK/dotfiles.git show HEAD -stdout 'Add dot_file' - -# test that chezmoi edit creates and pushes a commit -chezmoi edit $HOME${/}.file -exec git --git-dir=$WORK/dotfiles.git show HEAD -stdout 'Update dot_file' - -# test that chezmoi forget creates and pushes a commit -chezmoi forget --force $HOME${/}.file -exec git --git-dir=$WORK/dotfiles.git show HEAD -stdout 'Remove dot_file' - --- home/user/.config/chezmoi/chezmoi.toml -- -[git] - autoPush = true diff --git a/chezmoi2/testdata/scripts/bitwarden.txt b/chezmoi2/testdata/scripts/bitwarden.txt deleted file mode 100644 index f37759a5e0b..00000000000 --- a/chezmoi2/testdata/scripts/bitwarden.txt +++ /dev/null @@ -1,103 +0,0 @@ -[!windows] chmod 755 bin/bw -[windows] unix2dos bin/bw.cmd - -# test bitwarden template function -chezmoi execute-template '{{ (bitwarden "item" "example.com").login.password }}' -stdout password-value - -# test bitwardenFields template function -chezmoi execute-template '{{ (bitwardenFields "item" "example.com").Hidden.value }}' -stdout hidden-value - -# test bitwardenAttachment template function -chezmoi execute-template '{{ (bitwardenAttachment "filename" "item-id") }}' -stdout hidden-file-value - --- bin/bw -- -#!/bin/sh - -case "$*" in -"get item example.com") - cat <<EOF -{ - "object": "item", - "id": "bf22e4b4-ae4a-4d1c-8c98-ac620004b628", - "organizationId": null, - "folderId": null, - "type": 1, - "name": "example.com", - "notes": null, - "favorite": false, - "fields": [ - { - "name": "Text", - "value": "text-value", - "type": 0 - }, - { - "name": "Hidden", - "value": "hidden-value", - "type": 1 - } - ], - "login": { - "username": "username-value", - "password": "password-value", - "totp": null, - "passwordRevisionDate": null - }, - "collectionIds": [], - "revisionDate": "2020-10-28T00:21:02.690Z" -} -EOF - ;; -"get attachment filename --itemid item-id --raw") - cat <<EOF -hidden-file-value -EOF - ;; -*) - echo "Invalid command: $*" - echo "See --help for a list of available commands." - exit 1 -esac --- bin/bw.cmd -- -@echo off -IF "%*" == "get item example.com" ( - echo.{ - echo. "object": "item", - echo. "id": "bf22e4b4-ae4a-4d1c-8c98-ac620004b628", - echo. "organizationId": null, - echo. "folderId": null, - echo. "type": 1, - echo. "name": "example.com", - echo. "notes": null, - echo. "favorite": false, - echo. "fields": [ - echo. { - echo. "name": "Text", - echo. "value": "text-value", - echo. "type": 0 - echo. }, - echo. { - echo. "name": "Hidden", - echo. "value": "hidden-value", - echo. "type": 1 - echo. } - echo. ], - echo. "login": { - echo. "username": "username-value", - echo. "password": "password-value", - echo. "totp": null, - echo. "passwordRevisionDate": null - echo. }, - echo. "collectionIds": [], - echo. "revisionDate": "2020-10-28T00:21:02.690Z" - echo.} -) ELSE IF "%*" == "get attachment filename --itemid item-id --raw" ( - echo. hidden-file-value -) ELSE ( - echo Invalid command: $* - echo "See --help for a list of available commands." - exit /b 1 -) diff --git a/chezmoi2/testdata/scripts/cat.txt b/chezmoi2/testdata/scripts/cat.txt deleted file mode 100644 index 4ee1c25c8b1..00000000000 --- a/chezmoi2/testdata/scripts/cat.txt +++ /dev/null @@ -1,32 +0,0 @@ -mkhomedir golden -mksourcedir - -# test that chezmoi cat prints an empty file -chezmoi cat $HOME${/}.empty -cmp stdout golden/.empty - -# test that chezmoi cat prints a file -chezmoi cat $HOME${/}.file -cmp stdout golden/.file - -# test that chezmoi cat prints a symlink -chezmoi cat $HOME${/}.symlink -stdout '\.dir/subdir/file' - -# test that chezmoi cat prints a template -chezmoi cat $HOME${/}.template -cmp stdout golden/.template - -# test that chezmoi cat does not print directories -! chezmoi cat $HOME${/}.dir -stderr 'not a file or symlink' - -# test that chezmoi cat does not print files outside the destination directory -! chezmoi cat ${/}etc${/}passwd -stderr 'not in' - -# test that chezmoi cat uses relative paths -mkdir $HOME/.dir -cd $HOME/.dir -chezmoi cat file -cmp stdout $WORK/golden/.dir/file diff --git a/chezmoi2/testdata/scripts/cd_unix.txt b/chezmoi2/testdata/scripts/cd_unix.txt deleted file mode 100644 index 4affc462f7b..00000000000 --- a/chezmoi2/testdata/scripts/cd_unix.txt +++ /dev/null @@ -1,22 +0,0 @@ -[windows] skip 'UNIX only' - -# test chezmoi cd creates source directory if needed -chezmoi cd -exists $CHEZMOISOURCEDIR -grep -count=1 ${CHEZMOISOURCEDIR@R} shell.log - -# test chezmoi cd changes into an existing directory -chezmoi cd -grep -count=2 ${CHEZMOISOURCEDIR@R} shell.log - -[!exec:bash] stop 'bash not found in $PATH' - -# test chezmoi cd with command with args -chhome home2/user -chezmoi cd -stdout version - --- home2/user/.config/chezmoi/chezmoi.toml -- -[cd] - command = "bash" - args = ["--version"] diff --git a/chezmoi2/testdata/scripts/cd_windows.txt b/chezmoi2/testdata/scripts/cd_windows.txt deleted file mode 100644 index 305db5c528d..00000000000 --- a/chezmoi2/testdata/scripts/cd_windows.txt +++ /dev/null @@ -1,11 +0,0 @@ -[!windows] skip 'Windows only' - -# test chezmoi cd with command with args (Windows variant) -chezmoi cd -! stdout PowerShell -stdout evidence - --- home/user/.config/chezmoi/chezmoi.toml -- -[cd] - command = "powershell" - args = ["-nologo", "-command", "Write-Host 'evidence'"] diff --git a/chezmoi2/testdata/scripts/chattr.txt b/chezmoi2/testdata/scripts/chattr.txt deleted file mode 100644 index d207275da46..00000000000 --- a/chezmoi2/testdata/scripts/chattr.txt +++ /dev/null @@ -1,68 +0,0 @@ -mksourcedir - -exists $CHEZMOISOURCEDIR/dot_file -chezmoi chattr empty $HOME${/}.file -! exists $CHEZMOISOURCEDIR/dot_file -exists $CHEZMOISOURCEDIR/empty_dot_file - -chezmoi chattr +p $HOME${/}.file -! exists $CHEZMOISOURCEDIR/empty_dot_file -exists $CHEZMOISOURCEDIR/private_empty_dot_file - -chezmoi chattr t,-e $HOME${/}.file -! exists $CHEZMOISOURCEDIR/private_empty_dot_file -exists $CHEZMOISOURCEDIR/private_dot_file.tmpl - -exists $CHEZMOISOURCEDIR/executable_dot_executable -chezmoi chattr nox $HOME${/}.executable -! exists $CHEZMOISOURCEDIR/executable_dot_executable -exists $CHEZMOISOURCEDIR/dot_executable - -chezmoi chattr x $HOME${/}.executable -! exists $CHEZMOISOURCEDIR/dot_executable -exists $CHEZMOISOURCEDIR/executable_dot_executable - -chezmoi chattr +private $HOME${/}.create -! exists $CHEZMOISOURCEDIR/create_dot_create -exists $CHEZMOISOURCEDIR/create_private_dot_create - -chezmoi chattr noprivate $HOME${/}.create -! exists $CHEZMOISOURCEDIR/create_private_dot_create -exists $CHEZMOISOURCEDIR/create_dot_create - -exists $CHEZMOISOURCEDIR/dot_dir -chezmoi chattr exact $HOME/.dir -! exists $CHEZMOISOURCEDIR/dot_dir -exists $CHEZMOISOURCEDIR/exact_dot_dir - -exists $CHEZMOISOURCEDIR/symlink_dot_symlink -chezmoi chattr +t $HOME${/}.symlink -! exists $CHEZMOISOURCEDIR/symlink_dot_symlink -exists $CHEZMOISOURCEDIR/symlink_dot_symlink.tmpl - -chezmoi chattr -- -t $HOME${/}.symlink -! exists $CHEZMOISOURCEDIR/symlink_dot_symlink.tmpl -exists $CHEZMOISOURCEDIR/symlink_dot_symlink - -chezmoi chattr -- before $HOME/script -! exists $CHEZMOISOURCEDIR/run_script -exists $CHEZMOISOURCEDIR/run_before_script - -chezmoi chattr -- once $HOME/script -! exists $CHEZMOISOURCEDIR/run_before_script -exists $CHEZMOISOURCEDIR/run_once_before_script - -chezmoi chattr -- after $HOME/script -! exists $CHEZMOISOURCEDIR/run_once_before_script -exists $CHEZMOISOURCEDIR/run_once_after_script - -chezmoi chattr -- -o $HOME/script -! exists $CHEZMOISOURCEDIR/run_once_after_script -exists $CHEZMOISOURCEDIR/run_after_script - -chezmoi chattr -- -a $HOME/script -! exists $CHEZMOISOURCEDIR/run_after_script -exists $CHEZMOISOURCEDIR/run_script - --- home/user/.local/share/chezmoi/run_script -- -#!/bin/sh diff --git a/chezmoi2/testdata/scripts/completion.txt b/chezmoi2/testdata/scripts/completion.txt deleted file mode 100644 index f5a8ee6bc43..00000000000 --- a/chezmoi2/testdata/scripts/completion.txt +++ /dev/null @@ -1,11 +0,0 @@ -chezmoi completion bash -stdout '# bash completion for chezmoi2' - -chezmoi completion fish -stdout '# fish completion for chezmoi2' - -chezmoi completion powershell -stdout 'Register-ArgumentCompleter' - -chezmoi completion zsh -stdout '#compdef _chezmoi2 chezmoi2' diff --git a/chezmoi2/testdata/scripts/data.txt b/chezmoi2/testdata/scripts/data.txt deleted file mode 100644 index b66f24d8b39..00000000000 --- a/chezmoi2/testdata/scripts/data.txt +++ /dev/null @@ -1,18 +0,0 @@ -# test that chezmoi data includes data set in config file -chezmoi data -stdout '"chezmoi":' -stdout '"uniquekey": "uniqueValue"' # viper downcases uniqueKey - -# test that chezmoi data --format=json includes data set in config file -chezmoi data --format=json -stdout '"chezmoi":' -stdout '"uniquekey": "uniqueValue"' - -# test that chezmoi data --format=yaml includes data set in config file -chezmoi data --format=yaml -stdout 'chezmoi:' -stdout 'uniquekey: uniqueValue' - --- home/user/.config/chezmoi/chezmoi.toml -- -[data] - uniqueKey = "uniqueValue" diff --git a/chezmoi2/testdata/scripts/diff.txt b/chezmoi2/testdata/scripts/diff.txt deleted file mode 100644 index 8eb172a2127..00000000000 --- a/chezmoi2/testdata/scripts/diff.txt +++ /dev/null @@ -1,122 +0,0 @@ -mkhomedir golden -mkhomedir -mksourcedir - -# test that chezmoi diff generates no output when the source and destination states are equal -chezmoi diff -! stdout . - -# test that chezmoi diff generates a diff when a file is added to the source state -cp golden/dot_newfile $CHEZMOISOURCEDIR/dot_newfile -chezmoi diff -[!windows] cmp stdout golden/add-newfile-diff-unix -[windows] cmp stdout golden/add-newfile-diff-windows -rm $CHEZMOISOURCEDIR/dot_newfile - -# test that chezmoi diff generates a diff when a file is edited -edit $HOME/.file -chezmoi diff -[!windows] cmp stdout golden/modify-file-diff-unix -[windows] cmp stdout golden/modify-file-diff-windows -chezmoi apply --force $HOME${/}.file - -# test that chezmoi diff generates a diff when a file is removed from the destination directory -rm $HOME/.file -chezmoi diff -[!windows] cmp stdout golden/restore-file-diff-unix -[windows] cmp stdout golden/restore-file-diff-windows -chezmoi apply --force $HOME${/}.file - -# test that chezmoi diff generates a diff when a directory is removed from the destination directory -rm $HOME/.dir -chezmoi diff --recursive=false $HOME${/}.dir -[!windows] cmp stdout golden/restore-dir-diff-unix -[windows] cmp stdout golden/restore-dir-diff-windows -chezmoi apply --force $HOME${/}.dir - -[windows] stop 'remaining tests use file modes' - -# test that chezmoi diff generates a diff when a file's permissions are changed -chmod 777 $HOME/.file -chezmoi diff -cmp stdout golden/chmod-file-diff -chezmoi apply --force $HOME${/}.file - -# test that chezmoi diff generates a diff when a dir's permissions are changed -chmod 700 $HOME/.dir -chezmoi diff -cmp stdout golden/chmod-dir-diff -chezmoi apply --force --recursive=false $HOME${/}.dir - --- golden/add-newfile-diff-unix -- -diff --git a/.newfile b/.newfile -new file mode 100644 -index 0000000000000000000000000000000000000000..06e05235fdd12fd5c367b6d629fef94536c85525 ---- /dev/null -+++ b/.newfile -@@ -0,0 +1 @@ -+# contents of .newfile --- golden/add-newfile-diff-windows -- -diff --git a/.newfile b/.newfile -new file mode 100666 -index 0000000000000000000000000000000000000000..06e05235fdd12fd5c367b6d629fef94536c85525 ---- /dev/null -+++ b/.newfile -@@ -0,0 +1 @@ -+# contents of .newfile --- golden/modify-file-diff-unix -- -diff --git a/.file b/.file -index 5d2730a8850a2db479af83de87cc8345437aef06..8a52cb9ce9551221716a53786ad74104c5902362 100644 ---- a/.file -+++ b/.file -@@ -1,2 +1 @@ - # contents of .file --# edited --- golden/modify-file-diff-windows -- -diff --git a/.file b/.file -index 5d2730a8850a2db479af83de87cc8345437aef06..8a52cb9ce9551221716a53786ad74104c5902362 100666 ---- a/.file -+++ b/.file -@@ -1,2 +1 @@ - # contents of .file --# edited --- golden/restore-file-diff-unix -- -diff --git a/.file b/.file -new file mode 100644 -index 0000000000000000000000000000000000000000..8a52cb9ce9551221716a53786ad74104c5902362 ---- /dev/null -+++ b/.file -@@ -0,0 +1 @@ -+# contents of .file --- golden/restore-file-diff-windows -- -diff --git a/.file b/.file -new file mode 100666 -index 0000000000000000000000000000000000000000..8a52cb9ce9551221716a53786ad74104c5902362 ---- /dev/null -+++ b/.file -@@ -0,0 +1 @@ -+# contents of .file --- golden/restore-dir-diff-unix -- -diff --git a/.dir b/.dir -new file mode 40755 -index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 ---- /dev/null -+++ b/.dir --- golden/restore-dir-diff-windows -- -diff --git a/.dir b/.dir -new file mode 40777 -index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 ---- /dev/null -+++ b/.dir --- golden/dot_newfile -- -# contents of .newfile --- golden/chmod-file-diff -- -diff --git a/.file b/.file -old mode 100777 -new mode 100644 --- golden/chmod-dir-diff -- -diff --git a/.dir b/.dir -old mode 40700 -new mode 40755 --- golden/dot_newfile -- -# contents of .newfile diff --git a/chezmoi2/testdata/scripts/docs.txt b/chezmoi2/testdata/scripts/docs.txt deleted file mode 100644 index 024792159fe..00000000000 --- a/chezmoi2/testdata/scripts/docs.txt +++ /dev/null @@ -1,14 +0,0 @@ -chezmoi docs -stdout 'chezmoi Reference Manual' - -chezmoi docs faq -stdout 'chezmoi Frequently Asked Questions' - -chezmoi docs quickstart -stdout 'chezmoi Quick Start Guide' - -! chezmoi docs a -stderr 'ambiguous pattern' - -! chezmoi docs z -stderr 'no matching files' diff --git a/chezmoi2/testdata/scripts/edit.txt b/chezmoi2/testdata/scripts/edit.txt deleted file mode 100644 index 66ec652e726..00000000000 --- a/chezmoi2/testdata/scripts/edit.txt +++ /dev/null @@ -1,31 +0,0 @@ -mkhomedir -mksourcedir - -chezmoi edit $HOME${/}.file -grep -count=1 '# edited' $CHEZMOISOURCEDIR/dot_file -! grep '# edited' $HOME/.file - -chezmoi edit --apply --force $HOME${/}.file -grep -count=2 '# edited' $CHEZMOISOURCEDIR/dot_file -grep -count=2 '# edited' $HOME/.file - -chezmoi edit $HOME${/}.symlink -grep -count=1 '# edited' $CHEZMOISOURCEDIR/symlink_dot_symlink - -chezmoi edit -v $HOME${/}script -grep -count=1 '# edited' $CHEZMOISOURCEDIR/run_script - -chezmoi edit $HOME${/}.file $HOME${/}.symlink -grep -count=3 '# edited' $CHEZMOISOURCEDIR/dot_file -grep -count=2 '# edited' $CHEZMOISOURCEDIR/symlink_dot_symlink - -chezmoi edit -exists $CHEZMOISOURCEDIR/.edited - -[windows] stop 'remaining tests use file modes' - -chezmoi edit $HOME${/}.dir -exists $CHEZMOISOURCEDIR/dot_dir/.edited - --- home/user/.local/share/chezmoi/run_script -- -#!/bin/sh diff --git a/chezmoi2/testdata/scripts/editconfig.txt b/chezmoi2/testdata/scripts/editconfig.txt deleted file mode 100644 index f038a976c74..00000000000 --- a/chezmoi2/testdata/scripts/editconfig.txt +++ /dev/null @@ -1,25 +0,0 @@ -# test that edit-config creates a config file if needed -chezmoi edit-config -grep -count=1 '# edited' $CHEZMOICONFIGDIR/chezmoi.toml - -# test that edit-config edits an existing config file -chezmoi edit-config -grep -count=2 '# edited' $CHEZMOICONFIGDIR/chezmoi.toml - -# test that edit-config edits an existing YAML config file -chhome home2/user -chezmoi edit-config -grep -count=1 '# edited' $CHEZMOICONFIGDIR/chezmoi.yaml - -# test that edit-config reports a warning if the config is no longer valid -chhome home3/user -! stderr warning -chezmoi edit-config -stderr warning -grep -count=1 '# edited' $CHEZMOICONFIGDIR/chezmoi.json - --- home2/user/.config/chezmoi/chezmoi.yaml -- -data: - email: "[email protected]" --- home3/user/.config/chezmoi/chezmoi.json -- -{"data":{"email":"[email protected]"}} diff --git a/chezmoi2/testdata/scripts/errors.txt b/chezmoi2/testdata/scripts/errors.txt deleted file mode 100644 index 94da73c42d3..00000000000 --- a/chezmoi2/testdata/scripts/errors.txt +++ /dev/null @@ -1,39 +0,0 @@ -mksourcedir - -# test duplicate source state entry detection -cp $CHEZMOISOURCEDIR/dot_file $CHEZMOISOURCEDIR/empty_dot_file -! chezmoi verify -stderr 'duplicate source state entries' - -# test invalid config -chhome home2/user -! chezmoi verify -stderr 'invalid config' - -# test source directory is not a directory -chhome home3/user -! chezmoi verify -stderr 'not a directory' - -# test that chezmoi checks .chezmoiversion -chhome home4/user -! chezmoi verify -stderr 'source state requires version' - -# test duplicate script detection -chhome home5/user -! chezmoi verify -stderr 'duplicate source state entries' - -# FIXME add more tests - --- home2/user/.config/chezmoi/chezmoi.json -- -{ --- home3/user/.local/share/chezmoi -- -# contents of .local/share/chezmoi --- home4/user/.local/share/chezmoi/.chezmoiversion -- -3.0.0 --- home5/user/.local/share/chezmoi/run_install_packages -- -# contents of install_packages --- home5/user/.local/share/chezmoi/run_once_install_packages -- -# contents of install_packages diff --git a/chezmoi2/testdata/scripts/executetemplate.txt b/chezmoi2/testdata/scripts/executetemplate.txt deleted file mode 100644 index c7eab180f94..00000000000 --- a/chezmoi2/testdata/scripts/executetemplate.txt +++ /dev/null @@ -1,80 +0,0 @@ -# test reading args -chezmoi execute-template '{{ "arg-template" }}' -stdout arg-template - -# test reading from stdin -stdin golden/stdin.tmpl -chezmoi execute-template -stdout stdin-template - -# test partial templates work -chezmoi execute-template '{{ template "partial" }}' -stdout 'hello world' - -# FIXME merge the following tests into a single test - -chezmoi execute-template '{{ .last.config }}' -stdout 'chezmoi\.toml' - -# test that template data are read from .chezmoidata.json -chezmoi execute-template '{{ .last.json }}' -stdout '\.chezmoidata\.json' - -# test that template data are read from .chezmoidata.toml -chezmoi execute-template '{{ .last.toml }}' -stdout '\.chezmoidata\.toml' - -# test that template data are read from .chezmoidata.yaml -chezmoi execute-template '{{ .last.yaml }}' -stdout '\.chezmoidata\.yaml' - -# test that the last .chezmoidata.<format> file read wins -chezmoi execute-template '{{ .last.format }}' -stdout '\.chezmoidata\.yaml' - -# test that the config file wins over .chezmoidata.<format> -chezmoi execute-template '{{ .last.global }}' -stdout chezmoi.toml - -# test --init --promptBool -chezmoi execute-template --init --promptBool value=yes '{{ promptBool "value" }}' -stdout true -! chezmoi execute-template --promptBool value=error -stderr 'invalid syntax' - -# test --init --promptInt -chezmoi execute-template --init --promptInt value=1 '{{ promptInt "value" }}' -stdout 1 -! chezmoi execute-template --promptInt value=error -stderr 'invalid syntax' - -# test --init --promptString -chezmoi execute-template --init --promptString [email protected] '{{ promptString "email" }}' -stdout '[email protected]' - --- golden/stdin.tmpl -- -{{ "stdin-template" }} --- home/user/.config/chezmoi/chezmoi.toml -- -[data.last] - config = "chezmoi.toml" - global = "chezmoi.toml" --- home/user/.local/share/chezmoi/.chezmoidata.json -- -{ - "last": { - "format": ".chezmoidata.json", - "global": ".chezmoidata.json", - "json": ".chezmoidata.json" - } -} --- home/user/.local/share/chezmoi/.chezmoidata.toml -- -[last] - format = ".chezmoidata.toml" - global = ".chezmoidata.toml" - toml = ".chezmoidata.toml" --- home/user/.local/share/chezmoi/.chezmoidata.yaml -- -last: - format: ".chezmoidata.yaml" - global: ".chezmoidata.yaml" - yaml: ".chezmoidata.yaml" --- home/user/.local/share/chezmoi/.chezmoitemplates/partial -- -{{ cat "hello" "world" }} diff --git a/chezmoi2/testdata/scripts/forget.txt b/chezmoi2/testdata/scripts/forget.txt deleted file mode 100644 index 1e368f9d92d..00000000000 --- a/chezmoi2/testdata/scripts/forget.txt +++ /dev/null @@ -1,11 +0,0 @@ -mksourcedir - -# test that chezmoi forget file forgets a file -exists $CHEZMOISOURCEDIR/dot_file -chezmoi forget --force $HOME${/}.file -! exists $CHEZMOISOURCEDIR/dot_file - -# test that chezmoi forget dir forgets a dir -exists $CHEZMOISOURCEDIR/dot_dir -chezmoi forget --force $HOME${/}.dir -! exists $CHEZMOISOURCEDIR/dot_dir diff --git a/chezmoi2/testdata/scripts/git.txt b/chezmoi2/testdata/scripts/git.txt deleted file mode 100644 index 47bc8604597..00000000000 --- a/chezmoi2/testdata/scripts/git.txt +++ /dev/null @@ -1,18 +0,0 @@ -[!windows] chmod 755 bin/git -[windows] unix2dos bin/git.cmd - -chezmoi git hello -exists $CHEZMOISOURCEDIR -stdout hello - --- bin/git -- -#!/bin/sh - -echo $* --- bin/git.cmd -- -@echo off -setlocal -set out=%* -set out=%out:\=% -echo %out% -endlocal diff --git a/chezmoi2/testdata/scripts/gopass.txt b/chezmoi2/testdata/scripts/gopass.txt deleted file mode 100644 index 35057f0874e..00000000000 --- a/chezmoi2/testdata/scripts/gopass.txt +++ /dev/null @@ -1,32 +0,0 @@ -[!windows] chmod 755 bin/gopass -[windows] unix2dos bin/gopass.cmd - -# test gopass template function -chezmoi execute-template '{{ gopass "misc/example.com" }}' -stdout examplepassword - --- bin/gopass -- -#!/bin/sh - -case "$*" in -"--version") - echo "gopass 1.10.1 go1.15 linux amd64" - ;; -"show --password misc/example.com") - echo "examplepassword" - ;; -*) - echo "gopass: invalid command: $*" - exit 1 -esac --- bin/gopass.cmd -- -@echo off -IF "%*" == "--version" ( - echo "gopass 1.10.1 go1.15 windows amd64" -) ELSE IF "%*" == "show --password misc/example.com" ( - echo | set /p=examplepassword - exit /b 0 -) ELSE ( - echo gopass: invalid command: %* - exit /b 1 -) diff --git a/chezmoi2/testdata/scripts/help.txt b/chezmoi2/testdata/scripts/help.txt deleted file mode 100644 index 249c15596b6..00000000000 --- a/chezmoi2/testdata/scripts/help.txt +++ /dev/null @@ -1,5 +0,0 @@ -chezmoi help -stdout 'Manage your dotfiles across multiple diverse machines, securely' - -chezmoi help add -stdout 'Add \*targets\* to the source state\.' diff --git a/chezmoi2/testdata/scripts/init.txt b/chezmoi2/testdata/scripts/init.txt deleted file mode 100644 index 760413ee286..00000000000 --- a/chezmoi2/testdata/scripts/init.txt +++ /dev/null @@ -1,58 +0,0 @@ -[!exec:git] stop - -mkgitconfig -mkhomedir golden -mkhomedir - -# test that chezmoi init creates a git repo -chezmoi init -exists $CHEZMOISOURCEDIR/.git - -# create a commit -cp golden/.file $CHEZMOISOURCEDIR/dot_file -chezmoi git add dot_file -chezmoi git commit -- --message 'Add dot_file' - -# test that chezmoi init fetches git repo but does not apply -chhome home2/user -mkgitconfig -chezmoi init file://$WORK/home/user/.local/share/chezmoi -exists $CHEZMOISOURCEDIR/.git -! exists $HOME/.file - -# test that chezmoi init --apply fetches a git repo and runs chezmoi apply -chhome home3/user -mkgitconfig -chezmoi init --apply --force file://$WORK/home/user/.local/share/chezmoi -exists $CHEZMOISOURCEDIR/.git -cmp $HOME/.file golden/.file - -# test that chezmoi init --apply --depth 1 --force --purge clones, applies, and purges -chhome home4/user -mkgitconfig -exists $CHEZMOICONFIGDIR -! exists $CHEZMOISOURCEDIR -chezmoi init --apply --depth 1 --force --purge file://$WORK/home/user/.local/share/chezmoi -cmp $HOME/.file golden/.file -! exists $CHEZMOICONFIGDIR -! exists $CHEZMOISOURCEDIR - -# test that chezmoi init does not clone the repo if it is already checked out but does create the config file -chhome home5/user -mkgitconfig -chezmoi init --source=$HOME/dotfiles file://$WORK/nonexistentrepo -exists $CHEZMOICONFIGDIR/chezmoi.toml - -# test chezmoi init --one-shot -chhome home6/user -mkgitconfig -chezmoi init --one-shot file://$WORK/home/user/.local/share/chezmoi -cmp $HOME/.file golden/.file -! exists $CHEZMOICONFIGDIR -! exists $CHEZMOISOURCEDIR - --- home4/user/.config/chezmoi/chezmoi.toml -- --- home5/user/dotfiles/.git/.keep -- --- home5/user/dotfiles/.chezmoi.toml.tmpl -- -[data] - email = "[email protected]" diff --git a/chezmoi2/testdata/scripts/keepassxc.txt b/chezmoi2/testdata/scripts/keepassxc.txt deleted file mode 100644 index c0ed68ee74d..00000000000 --- a/chezmoi2/testdata/scripts/keepassxc.txt +++ /dev/null @@ -1,58 +0,0 @@ -[!windows] chmod 755 bin/keepass-test -[windows] unix2dos bin/keepass-test.cmd - -# test keepassxcAttribute template function -stdin $HOME/input -chezmoi execute-template --no-tty '{{ keepassxcAttribute "example.com" "host-name" }}' -stdout example.com - -# test keepassxc template function and that password is only requested once -stdin $HOME/input -chezmoi execute-template --no-tty '{{ (keepassxc "example.com").UserName }}/{{ (keepassxc "example.com").Password }}' -stdout examplelogin/examplepassword - --- bin/keepass-test -- -#!/bin/sh - -case "$*" in -"--version") - echo "2.5.4" - ;; -"show --show-protected secrets.kdbx example.com") - cat <<EOF -Title: example.com -UserName: examplelogin -Password: examplepassword -URL: -Notes: -EOF - ;; -"show --attributes host-name --quiet --show-protected secrets.kdbx example.com") - echo "example.com" - ;; -*) - echo "keepass-test: invalid command: $*" - exit 1 -esac --- bin/keepass-test.cmd -- -@echo off -IF "%*" == "--version" ( - echo 2.5.4 -) ELSE IF "%*" == "show --show-protected secrets.kdbx example.com" ( - echo.Title: example.com - echo.UserName: examplelogin - echo.Password: examplepassword - echo.URL: - echo.Notes: -) ELSE IF "%*" == "show --attributes host-name --quiet --show-protected secrets.kdbx example.com" ( - echo.example.com -) ELSE ( - echo keepass-test: invalid command: %* - exit /b 1 -) --- home/user/input -- -fakepassword --- home/user/.config/chezmoi/chezmoi.toml -- -[keepassxc] - command = "keepass-test" - database = "secrets.kdbx" diff --git a/chezmoi2/testdata/scripts/lastpass.txt b/chezmoi2/testdata/scripts/lastpass.txt deleted file mode 100644 index 7956903116e..00000000000 --- a/chezmoi2/testdata/scripts/lastpass.txt +++ /dev/null @@ -1,84 +0,0 @@ -[!windows] chmod 755 bin/lpass -[windows] unix2dos bin/lpass.cmd - -# test lastpass template function -chezmoi execute-template '{{ (index (lastpass "example.com") 0).password }}' -stdout examplepassword - -# test lastpass version check -chmod 755 $WORK/bin2/lpass -env PATH=$WORK${/}bin2${:}$PATH -! chezmoi execute-template '{{ (index (lastpass "example.com") 0).password }}' -stderr 'need version 1\.3\.0 or later' - --- bin/lpass -- -#!/bin/sh - -case "$*" in -"--version") - echo "LastPass CLI v1.3.3.GIT" - ;; -"show --json example.com") - cat <<EOF -[ - { - "id": "0", - "name": "example.com", - "fullname": "Examples/example.com", - "username": "examplelogin", - "password": "examplepassword", - "last_modified_gmt": "0", - "last_touch": "0", - "group": "Examples", - "url": "", - "note": "" - } -] -EOF - ;; -*) - echo "lpass: invalid command: $*" - exit 1 -esac --- bin/lpass.cmd -- -@echo off -IF "%*" == "--version" ( - echo LastPass CLI v1.3.3.GIT -) ELSE IF "%*" == "show --json example.com" ( - echo.[ - echo. { - echo. "id": "0", - echo. "name": "example.com", - echo. "fullname": "Examples/example.com", - echo. "username": "examplelogin", - echo. "password": "examplepassword", - echo. "last_modified_gmt": "0", - echo. "last_touch": "0", - echo. "group": "Examples", - echo. "url": "", - echo. "note": "" - echo. } - echo.] -) ELSE ( - echo lpass: invalid command: %* - exit /b 1 -) --- bin2/lpass -- -#!/bin/sh - -case "$*" in -"--version") - echo "LastPass CLI v1.2.0.GIT" - ;; -*) - echo "lpass: invalid command: $*" - exit 1 -esac --- bin2/lpass.cmd -- -@echo off -IF "%*" == "--version" ( - echo LastPass CLI v1.2.0.GIT -) ELSE ( - echo lpass: invalid command: %* - exit /b 1 -) diff --git a/chezmoi2/testdata/scripts/managed.txt b/chezmoi2/testdata/scripts/managed.txt deleted file mode 100644 index 17ae592bf92..00000000000 --- a/chezmoi2/testdata/scripts/managed.txt +++ /dev/null @@ -1,61 +0,0 @@ -mksourcedir - -chezmoi managed -cmpenv stdout golden/managed - -chezmoi managed --include=all -cmpenv stdout golden/managed-all - -chezmoi managed --include=remove -cmpenv stdout golden/managed-remove - -chezmoi managed --include=dirs -cmpenv stdout golden/managed-dirs - -chezmoi managed --include=files -cmpenv stdout golden/managed-files - -chezmoi managed --include=symlinks -cmpenv stdout golden/managed-symlinks - --- golden/managed -- -.create -.dir -.dir/file -.dir/subdir -.dir/subdir/file -.empty -.executable -.file -.private -.symlink -.template --- golden/managed-all -- -.create -.dir -.dir/file -.dir/subdir -.dir/subdir/file -.empty -.executable -.file -.private -.remove -.symlink -.template --- golden/managed-dirs -- -.dir -.dir/subdir --- golden/managed-files -- -.create -.dir/file -.dir/subdir/file -.empty -.executable -.file -.private -.template --- golden/managed-remove -- -.remove --- golden/managed-symlinks -- -.symlink diff --git a/chezmoi2/testdata/scripts/onepassword.txt b/chezmoi2/testdata/scripts/onepassword.txt deleted file mode 100644 index bd99e09816a..00000000000 --- a/chezmoi2/testdata/scripts/onepassword.txt +++ /dev/null @@ -1,35 +0,0 @@ -[!windows] chmod 755 bin/op -[windows] unix2dos bin/op.cmd - -# test onepassword template function -chezmoi execute-template '{{ (onepassword "ExampleLogin").uuid }}' -stdout '^wxcplh5udshnonkzg2n4qx262y$' - -# test onepasswordDetailsFields template function -chezmoi execute-template '{{ (onepasswordDetailsFields "ExampleLogin").password.value }}' -stdout '^L8rm1JXJIE1b8YUDWq7h$' - --- bin/op -- -#!/bin/sh - -case "$*" in -"--version") - echo 1.3.0 - ;; -"get item ExampleLogin") - echo '{"uuid":"wxcplh5udshnonkzg2n4qx262y","templateUuid":"001","trashed":"N","createdAt":"2020-07-28T13:44:57Z","updatedAt":"2020-07-28T14:27:46Z","changerUuid":"VBDXOA4MPVHONK5IIJVKUQGLXM","itemVersion":2,"vaultUuid":"tscpxgi6s7c662jtqn3vmw4n5a","details":{"fields":[{"designation":"username","name":"username","type":"T","value":"exampleuser"},{"designation":"password","name":"password","type":"P","value":"L8rm1JXJIE1b8YUDWq7h"}],"notesPlain":"","passwordHistory":[],"sections":[]},"overview":{"URLs":[{"l":"website","u":"https://www.example.com/"}],"ainfo":"exampleuser","pbe":119.083926,"pgrng":true,"ps":100,"tags":[],"title":"ExampleLogin","url":"https://www.example.com/"}}' - ;; -*) - echo [ERROR] 2020/01/01 00:00:00 unknown command \"$*\" for \"op\" - exit 1 -esac --- bin/op.cmd -- -@echo off -IF "%*" == "--version" ( - echo 1.3.0 -) ELSE IF "%*" == "get item ExampleLogin" ( - echo.{"uuid":"wxcplh5udshnonkzg2n4qx262y","templateUuid":"001","trashed":"N","createdAt":"2020-07-28T13:44:57Z","updatedAt":"2020-07-28T14:27:46Z","changerUuid":"VBDXOA4MPVHONK5IIJVKUQGLXM","itemVersion":2,"vaultUuid":"tscpxgi6s7c662jtqn3vmw4n5a","details":{"fields":[{"designation":"username","name":"username","type":"T","value":"exampleuser"},{"designation":"password","name":"password","type":"P","value":"L8rm1JXJIE1b8YUDWq7h"}],"notesPlain":"","passwordHistory":[],"sections":[]},"overview":{"URLs":[{"l":"website","u":"https://www.example.com/"}],"ainfo":"exampleuser","pbe":119.083926,"pgrng":true,"ps":100,"tags":[],"title":"ExampleLogin","url":"https://www.example.com/"}} -) ELSE ( - echo.[ERROR] 2020/01/01 00:00:00 unknown command "%*" for "op" - exit /b 1 -) diff --git a/chezmoi2/testdata/scripts/pass.txt b/chezmoi2/testdata/scripts/pass.txt deleted file mode 100644 index 2db7e67b258..00000000000 --- a/chezmoi2/testdata/scripts/pass.txt +++ /dev/null @@ -1,27 +0,0 @@ -[!windows] chmod 755 bin/pass -[windows] unix2dos bin/pass.cmd - -# test pass template function -chezmoi execute-template '{{ pass "misc/example.com" }}' -stdout examplepassword - --- bin/pass -- -#!/bin/sh - -case "$*" in -"show misc/example.com") - echo "examplepassword" - ;; -*) - echo "pass: invalid command: $*" - exit 1 -esac --- bin/pass.cmd -- -@echo off -IF "%*" == "show misc/example.com" ( - echo | set /p=examplepassword - exit /b 0 -) ELSE ( - echo pass: invalid command: %* - exit /b 1 -) diff --git a/chezmoi2/testdata/scripts/purge.txt b/chezmoi2/testdata/scripts/purge.txt deleted file mode 100644 index cef13857537..00000000000 --- a/chezmoi2/testdata/scripts/purge.txt +++ /dev/null @@ -1,14 +0,0 @@ -mksourcedir - -# test chezmoi purge purges source dir -exists $CHEZMOISOURCEDIR -chezmoi purge --force -! exists $CHEZMOISOURCEDIR - -# test chezmoi purge purges config dir -chhome home2/user -exists $CHEZMOICONFIGDIR -chezmoi purge --force -! exists $CHEZMOICONFIGDIR - --- home2/user/.config/chezmoi/chezmoi.toml -- diff --git a/chezmoi2/testdata/scripts/remove.txt b/chezmoi2/testdata/scripts/remove.txt deleted file mode 100644 index 61d79803d10..00000000000 --- a/chezmoi2/testdata/scripts/remove.txt +++ /dev/null @@ -1,18 +0,0 @@ -mkhomedir -mksourcedir - -# test that chezmoi remove file removes a file -exists $HOME/.file -chezmoi remove --force $HOME${/}.file -! exists $HOME/.file - -# test that chezmoi remove dir removes a directory -exists $HOME/.dir -chezmoi remove --force $HOME${/}.dir -! exists $HOME/.dir - -# test that if any chezmoi remove stops on any error -exists $HOME/.executable -! chezmoi remove --force $HOME${/}.newfile $HOME${/}.executable -stderr 'not in source state' -exists $HOME/.executable diff --git a/chezmoi2/testdata/scripts/script_unix.txt b/chezmoi2/testdata/scripts/script_unix.txt deleted file mode 100644 index 61df8268b7d..00000000000 --- a/chezmoi2/testdata/scripts/script_unix.txt +++ /dev/null @@ -1,51 +0,0 @@ -[windows] skip 'UNIX only' - -# test that chezmoi status prints that it will run the script -chezmoi status -cmp stdout golden/status - -# test that chezmoi apply runs the script -chezmoi apply --force -stdout ${HOME@R} - -# test that chezmoi status prints that it will run the script again -chezmoi status -cmp stdout golden/status - -# test that chezmoi apply runs the script even if it has run before -chezmoi apply --force -stdout ${HOME@R} - -# test that chezmoi dump includes the script -chezmoi dump -cmp stdout golden/dump.json - -# test that chezmoi managed includes the script -chezmoi managed --include=scripts -cmpenv stdout golden/managed - -[!exec:tar] stop 'tar not found in $PATH' - -# test that chezmoi archive includes the script in the archive -chezmoi archive --format=tar --gzip --output=archive.tar.gz -exec tar -tzf archive.tar.gz -cmp stdout golden/archive - --- golden/archive -- -script --- golden/dump.json -- -{ - "script": { - "type": "script", - "name": "script", - "contents": "#!/bin/sh\n\necho $PWD\n" - } -} --- golden/managed -- -script --- golden/status -- - R script --- home/user/.local/share/chezmoi/run_script -- -#!/bin/sh - -echo $PWD diff --git a/chezmoi2/testdata/scripts/script_windows.txt b/chezmoi2/testdata/scripts/script_windows.txt deleted file mode 100644 index 9d030c16fc8..00000000000 --- a/chezmoi2/testdata/scripts/script_windows.txt +++ /dev/null @@ -1,32 +0,0 @@ -[!windows] skip 'Windows only' - -chezmoi apply --force -stdout evidence - -chezmoi dump -cmp stdout golden/dump.json - -chezmoi managed --include=scripts -cmpenv stdout golden/managed - -[!exec:tar] 'tar not found in $PATH' - -chezmoi archive --gzip --output=archive.tar.gz -exec tar -tzf archive.tar.gz -[windows] unix2dos golden/archive -cmp stdout golden/archive - --- golden/archive -- -script.cmd --- golden/dump.json -- -{ - "script.cmd": { - "type": "script", - "name": "script.cmd", - "contents": "echo evidence\n" - } -} --- golden/managed -- -script.cmd --- home/user/.local/share/chezmoi/run_script.cmd -- -echo evidence diff --git a/chezmoi2/testdata/scripts/sourcedir.txt b/chezmoi2/testdata/scripts/sourcedir.txt deleted file mode 100644 index 11424e8cfbe..00000000000 --- a/chezmoi2/testdata/scripts/sourcedir.txt +++ /dev/null @@ -1,5 +0,0 @@ -chezmoi execute-template '{{ .chezmoi.sourceDir }}' -stdout '/tmp/user' - --- home/user/.config/chezmoi/chezmoi.toml -- -sourceDir = "/tmp/user" diff --git a/chezmoi2/testdata/scripts/sourcepath.txt b/chezmoi2/testdata/scripts/sourcepath.txt deleted file mode 100644 index c12938ff146..00000000000 --- a/chezmoi2/testdata/scripts/sourcepath.txt +++ /dev/null @@ -1,18 +0,0 @@ -mksourcedir - -chezmoi source-path -cmpenv stdout golden/source-path - -chezmoi source-path $HOME${/}.file -cmpenv stdout golden/source-path-file - -! chezmoi source-path $HOME${/}.newfile -stderr 'not in source state' - -! chezmoi source-path $WORK${/}etc${/}passwd -stderr 'not in' - --- golden/source-path -- -$CHEZMOISOURCEDIR --- golden/source-path-file -- -$CHEZMOISOURCEDIR/dot_file diff --git a/chezmoi2/testdata/scripts/templatefuncs.txt b/chezmoi2/testdata/scripts/templatefuncs.txt deleted file mode 100644 index 7a0553baf07..00000000000 --- a/chezmoi2/testdata/scripts/templatefuncs.txt +++ /dev/null @@ -1,11 +0,0 @@ -[darwin] chezmoi execute-template '{{ index ioreg "IOKitBuildVersion" }}' -[darwin] stdout 'Darwin Kernel Version' - -chezmoi execute-template '{{ joinPath "a" "b" }}' -stdout a${/}b - -chezmoi execute-template '{{ lookPath "go" }}' -stdout go${exe} - -chezmoi execute-template '{{ (stat ".").isDir }}' -stdout true diff --git a/chezmoi2/testdata/scripts/unmanaged.txt b/chezmoi2/testdata/scripts/unmanaged.txt deleted file mode 100644 index dde48b07f1f..00000000000 --- a/chezmoi2/testdata/scripts/unmanaged.txt +++ /dev/null @@ -1,23 +0,0 @@ -mkhomedir -mksourcedir - -chezmoi unmanaged -cmp stdout golden/unmanaged - -rm $CHEZMOISOURCEDIR/dot_dir -chezmoi unmanaged -cmp stdout golden/unmanaged-dir - -rm $CHEZMOISOURCEDIR/dot_file -chezmoi unmanaged -cmp stdout golden/unmanaged-dir-file - --- golden/unmanaged -- -.local --- golden/unmanaged-dir -- -.dir -.local --- golden/unmanaged-dir-file -- -.dir -.file -.local diff --git a/chezmoi2/testdata/scripts/update.txt b/chezmoi2/testdata/scripts/update.txt deleted file mode 100644 index 7d59b887e9b..00000000000 --- a/chezmoi2/testdata/scripts/update.txt +++ /dev/null @@ -1,46 +0,0 @@ -[!exec:git] skip 'git not found in $PATH' - -mkgitconfig -mkhomedir golden -mkhomedir - -exec git init --bare $WORK/dotfiles.git - -chezmoi init file://$WORK/dotfiles.git - -# create a commit -chezmoi add $HOME${/}.file -chezmoi git add dot_file -chezmoi git commit -- --message 'Add dot_file' -chezmoi git push - -chhome home2/user -mkgitconfig -chezmoi init --apply --force file://$WORK/dotfiles.git -cmp $HOME/.file golden/.file - -# create and push a new commit -chhome home/user -edit $CHEZMOISOURCEDIR/dot_file -chezmoi git -- add dot_file -chezmoi git -- commit -m 'Update dot_file' -chezmoi git -- push - -# test chezmoi update -chhome home2/user -chezmoi update -grep -count=1 '# edited' $HOME/.file - -# create and push a new commit -chhome home/user -edit $CHEZMOISOURCEDIR/dot_file -chezmoi git -- add dot_file -chezmoi git -- commit -m 'Update dot_file' -chezmoi git -- push - -# test chezmoi update --apply=false -chhome home2/user -chezmoi update --apply=false -grep -count=1 '# edited' $HOME/.file -chezmoi apply --force -grep -count=2 '# edited' $HOME/.file diff --git a/chezmoi2/testdata/scripts/verify.txt b/chezmoi2/testdata/scripts/verify.txt deleted file mode 100644 index baac57fcbde..00000000000 --- a/chezmoi2/testdata/scripts/verify.txt +++ /dev/null @@ -1,48 +0,0 @@ -mkhomedir golden -mkhomedir -mksourcedir - -# test that chezmoi verify succeeds -chezmoi verify - -# test that chezmoi verify fails when a file is added to the source state -cp golden/dot_newfile $CHEZMOISOURCEDIR/dot_newfile -! chezmoi verify -chezmoi forget --force $HOME${/}.newfile -chezmoi verify - -# test that chezmoi verify fails when a file is edited -edit $HOME/.file -! chezmoi verify -chezmoi apply --force $HOME${/}.file -chezmoi verify - -# test that chezmoi verify fails when a file is removed from the destination directory -rm $HOME/.file -! chezmoi verify -chezmoi apply --force $HOME${/}.file -chezmoi verify - -# test that chezmoi verify fails when a directory is removed from the destination directory -rm $HOME/.dir -! chezmoi verify -mkdir $HOME/.dir -chezmoi apply --force $HOME${/}.dir -chezmoi verify - -[windows] stop 'remaining tests use file modes' - -# test that chezmoi verify fails when a file's permissions are changed -chmod 777 $HOME/.file -! chezmoi verify -chezmoi apply --force $HOME${/}.file -chezmoi verify - -# test that chezmoi verify fails when a dir's permissions are changed -chmod 700 $HOME/.dir -! chezmoi verify -chezmoi apply --force $HOME${/}.dir -chezmoi verify - --- golden/dot_newfile -- -# contents of .newfile diff --git a/chezmoi2/testdata/scripts/version.txt b/chezmoi2/testdata/scripts/version.txt deleted file mode 100644 index 9e997f59dcb..00000000000 --- a/chezmoi2/testdata/scripts/version.txt +++ /dev/null @@ -1,2 +0,0 @@ -chezmoi --version -stdout 'chezmoi2 version v2\.0\.0' diff --git a/cmd/add.go b/cmd/add.go deleted file mode 100644 index e380b1299c7..00000000000 --- a/cmd/add.go +++ /dev/null @@ -1,152 +0,0 @@ -package cmd - -import ( - "fmt" - "os" - "path/filepath" - "strings" - - "github.com/spf13/cobra" - vfs "github.com/twpayne/go-vfs" - - "github.com/twpayne/chezmoi/internal/chezmoi" -) - -var addCmd = &cobra.Command{ - Use: "add targets...", - Aliases: []string{"manage"}, - Args: cobra.MinimumNArgs(1), - Short: "Add an existing file, directory, or symlink to the source state", - Long: mustGetLongHelp("add"), - Example: getExample("add"), - PreRunE: config.ensureNoError, - RunE: config.runAddCmd, - PostRunE: config.autoCommitAndAutoPush, -} - -type addCmdConfig struct { - force bool - prompt bool - options chezmoi.AddOptions -} - -func init() { - rootCmd.AddCommand(addCmd) - - persistentFlags := addCmd.PersistentFlags() - persistentFlags.BoolVarP(&config.add.options.Empty, "empty", "e", false, "add empty files") - persistentFlags.BoolVar(&config.add.options.Encrypt, "encrypt", false, "encrypt files") - persistentFlags.BoolVarP(&config.add.force, "force", "f", false, "overwrite source state, even if template would be lost") - persistentFlags.BoolVarP(&config.add.options.Exact, "exact", "x", false, "add directories exactly") - persistentFlags.BoolVarP(&config.add.prompt, "prompt", "p", false, "prompt before adding") - persistentFlags.BoolVarP(&config.add.options.Recursive, "recursive", "r", false, "recurse in to subdirectories") - persistentFlags.BoolVarP(&config.add.options.Template, "template", "T", false, "add files as templates") - persistentFlags.BoolVarP(&config.add.options.AutoTemplate, "autotemplate", "a", false, "auto generate the template when adding files as templates") - - markRemainingZshCompPositionalArgumentsAsFiles(addCmd, 1) -} - -func (c *Config) runAddCmd(cmd *cobra.Command, args []string) (err error) { - // Make --autotemplate imply --template. - if c.add.options.AutoTemplate { - c.add.options.Template = true - } - - ts, err := c.getTargetState(nil) - if err != nil { - return err - } - if err := c.ensureSourceDirectory(); err != nil { - return err - } - destDirPrefix := filepath.FromSlash(ts.DestDir + "/") - var quit int // quit is an int with a unique address - defer func() { - if r := recover(); r != nil { - if p, ok := r.(*int); ok && p == &quit { - err = nil - } else { - panic(r) - } - } - }() - for _, arg := range args { - path, err := filepath.Abs(arg) - if err != nil { - return err - } - if c.add.options.Recursive { - if err := vfs.Walk(c.fs, path, func(path string, info os.FileInfo, err error) error { - if err != nil { - return err - } - if ts.TargetIgnore.Match(strings.TrimPrefix(path, destDirPrefix)) { - cmd.Printf("warning: %s: skipping file ignored by .chezmoiignore\n", path) - return nil - } - if !c.add.force { - entry, err := ts.Get(c.fs, path) - if err != nil && !os.IsNotExist(err) { - return err - } - if file, ok := entry.(*chezmoi.File); ok && file.Template { - cmd.Printf("warning: %s: skipping file generated by template, use --force to force\n", path) - return nil - } - } - if c.add.prompt { - choice, err := c.prompt(fmt.Sprintf("Add %s", path), "ynqa") - if err != nil { - return err - } - switch choice { - case 'y': - case 'n': - return nil - case 'q': - panic(&quit) // abort vfs.Walk by panicking - case 'a': - c.add.prompt = false - } - } - return ts.Add(c.fs, c.add.options, path, info, c.Follow, c.mutator) - }); err != nil { - return err - } - } else { - if ts.TargetIgnore.Match(strings.TrimPrefix(path, destDirPrefix)) { - cmd.Printf("warning: %s: skipping file ignored by .chezmoiignore\n", path) - continue - } - if !c.add.force { - entry, err := ts.Get(c.fs, path) - if err != nil && !os.IsNotExist(err) { - return err - } - if file, ok := entry.(*chezmoi.File); ok && file.Template { - cmd.Printf("warning: %s: skipping file generated by template, use --force to force\n", path) - continue - } - } - if c.add.prompt { - choice, err := c.prompt(fmt.Sprintf("Add %s", path), "ynqa") - if err != nil { - return err - } - switch choice { - case 'y': - case 'n': - continue - case 'q': - return nil - case 'a': - c.add.prompt = false - } - } - if err := ts.Add(c.fs, c.add.options, path, nil, c.Follow, c.mutator); err != nil { - return err - } - } - } - return nil -} diff --git a/cmd/add_test.go b/cmd/add_test.go deleted file mode 100644 index b9141d1944c..00000000000 --- a/cmd/add_test.go +++ /dev/null @@ -1,591 +0,0 @@ -package cmd - -import ( - "path/filepath" - "testing" - - "github.com/spf13/cobra" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/twpayne/go-vfs/vfst" - - "github.com/twpayne/chezmoi/internal/chezmoi" -) - -func TestAddAfterModification(t *testing.T) { - fs, cleanup, err := vfst.NewTestFS(map[string]interface{}{ - "/home/user": &vfst.Dir{Perm: 0o755}, - "/home/user/.local/share/chezmoi": &vfst.Dir{Perm: 0o700}, - "/home/user/.bashrc": "# contents of .bashrc\n", - }) - require.NoError(t, err) - defer cleanup() - c := newTestConfig(fs) - args := []string{"/home/user/.bashrc"} - assert.NoError(t, c.runAddCmd(nil, args)) - vfst.RunTests(t, fs, "", - vfst.TestPath("/home/user/.local/share/chezmoi/dot_bashrc", - vfst.TestModeIsRegular, - vfst.TestContentsString("# contents of .bashrc\n"), - ), - ) - assert.NoError(t, fs.WriteFile("/home/user/.bashrc", []byte("# new contents of .bashrc\n"), 0o644)) - assert.NoError(t, c.runAddCmd(nil, args)) - vfst.RunTests(t, fs, "", - vfst.TestPath("/home/user/.local/share/chezmoi/dot_bashrc", - vfst.TestModeIsRegular, - vfst.TestContentsString("# new contents of .bashrc\n"), - ), - ) -} - -func TestAddCommand(t *testing.T) { - for _, tc := range []struct { - name string - args []string - add addCmdConfig - follow bool - root interface{} - tests interface{} - }{ - { - name: "add_dir", - args: []string{"/home/user/.config/htop"}, - root: map[string]interface{}{ - "/home/user/.config/htop": &vfst.Dir{Perm: 0o755}, - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi", - vfst.TestIsDir, - vfst.TestModePerm(0o700), - ), - vfst.TestPath("/home/user/.local/share/chezmoi/dot_config", - vfst.TestIsDir, - vfst.TestModePerm(0o755), - ), - vfst.TestPath("/home/user/.local/share/chezmoi/dot_config/htop", - vfst.TestIsDir, - vfst.TestModePerm(0o755), - ), - vfst.TestPath("/home/user/.local/share/chezmoi/dot_config/htop/.keep", - vfst.TestModeIsRegular, - vfst.TestModePerm(0o644), - vfst.TestContents(nil), - ), - }, - }, - { - name: "add_non_empty_dir", - args: []string{"/home/user/.config/htop"}, - root: map[string]interface{}{ - "/home/user/.config/htop": map[string]interface{}{ - "foo": "bar", - }, - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi", - vfst.TestIsDir, - vfst.TestModePerm(0o700), - ), - vfst.TestPath("/home/user/.local/share/chezmoi/dot_config", - vfst.TestIsDir, - vfst.TestModePerm(0o755), - ), - vfst.TestPath("/home/user/.local/share/chezmoi/dot_config/htop", - vfst.TestIsDir, - vfst.TestModePerm(0o755), - ), - vfst.TestPath("/home/user/.local/share/chezmoi/dot_config/htop/.keep", - vfst.TestModeIsRegular, - vfst.TestModePerm(0o644), - vfst.TestContents(nil), - ), - vfst.TestPath("/home/user/.local/share/chezmoi/dot_config/htop/foo", - vfst.TestDoesNotExist, - ), - }, - }, - { - name: "add_first_file", - args: []string{"/home/user/.bashrc"}, - root: map[string]interface{}{ - "/home/user/.bashrc": "foo", - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi", - vfst.TestIsDir, - vfst.TestModePerm(0o700), - ), - vfst.TestPath("/home/user/.local/share/chezmoi/dot_bashrc", - vfst.TestModeIsRegular, - vfst.TestContentsString("foo"), - ), - }, - }, - { - name: "add_autotemplate", - args: []string{"/home/user/.gitconfig"}, - add: addCmdConfig{ - options: chezmoi.AddOptions{ - AutoTemplate: true, - }, - }, - root: map[string]interface{}{ - "/home/user": &vfst.Dir{Perm: 0o755}, - "/home/user/.local/share/chezmoi": &vfst.Dir{Perm: 0o700}, - "/home/user/.gitconfig": "[user]\n\tname = John Smith\n\temail = [email protected]\n", - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/dot_gitconfig.tmpl", - vfst.TestModeIsRegular, - vfst.TestContentsString("[user]\n\tname = {{ .name }}\n\temail = {{ .email }}\n"), - ), - }, - }, - { - name: "add_autotemplate_escape", - args: []string{"/home/user/.vimrc"}, - add: addCmdConfig{ - options: chezmoi.AddOptions{ - AutoTemplate: true, - }, - }, - root: map[string]interface{}{ - "/home/user": map[string]interface{}{ - ".local/share/chezmoi": &vfst.Dir{Perm: 0o700}, - ".vimrc": "vim: set foldmethod=marker foldmarker={{,}}", - }, - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/dot_vimrc.tmpl", - vfst.TestModeIsRegular, - vfst.TestContentsString(`vim: set foldmethod=marker foldmarker={{ "{{" }},{{ "}}" }}`), - ), - }, - }, - { - // Test for PR #393 - // Ensure that auto template generating is disabled by default - name: "add_autotemplate_off_by_default", - args: []string{"/home/user/.gitconfig"}, - add: addCmdConfig{ - options: chezmoi.AddOptions{ - Template: true, - }, - }, - root: map[string]interface{}{ - "/home/user": &vfst.Dir{Perm: 0o755}, - "/home/user/.local/share/chezmoi": &vfst.Dir{Perm: 0o700}, - "/home/user/.gitconfig": "[user]\n\tname = John Smith\n\temail = [email protected]\n", - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/dot_gitconfig.tmpl", - vfst.TestModeIsRegular, - vfst.TestContentsString("[user]\n\tname = John Smith\n\temail = [email protected]\n"), - ), - }, - }, - { - name: "add_recursive", - args: []string{"/home/user/.config"}, - add: addCmdConfig{ - options: chezmoi.AddOptions{ - Recursive: true, - }, - }, - root: map[string]interface{}{ - "/home/user": &vfst.Dir{Perm: 0o755}, - "/home/user/.local/share/chezmoi": &vfst.Dir{Perm: 0o700}, - "/home/user/.config/micro/settings.json": "{}", - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/dot_config/micro/settings.json", - vfst.TestModeIsRegular, - vfst.TestContentsString("{}"), - ), - }, - }, - { - name: "add_nested_directory", - args: []string{"/home/user/.config/micro/settings.json"}, - root: map[string]interface{}{ - "/home/user": &vfst.Dir{Perm: 0o755}, - "/home/user/.local/share/chezmoi": &vfst.Dir{Perm: 0o700}, - "/home/user/.config/micro/settings.json": "{}", - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/dot_config/micro/settings.json", - vfst.TestModeIsRegular, - vfst.TestContentsString("{}"), - ), - }, - }, - { - name: "add_exact_dir", - args: []string{"/home/user/dir"}, - add: addCmdConfig{ - options: chezmoi.AddOptions{ - Exact: true, - }, - }, - root: map[string]interface{}{ - "/home/user": &vfst.Dir{Perm: 0o755}, - "/home/user/.local/share/chezmoi": &vfst.Dir{Perm: 0o700}, - "/home/user/dir": &vfst.Dir{Perm: 0o755}, - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/exact_dir", - vfst.TestIsDir, - ), - }, - }, - { - name: "add_exact_dir_recursive", - args: []string{"/home/user/dir"}, - add: addCmdConfig{ - options: chezmoi.AddOptions{ - Exact: true, - Recursive: true, - }, - }, - root: map[string]interface{}{ - "/home/user": &vfst.Dir{Perm: 0o755}, - "/home/user/.local/share/chezmoi": &vfst.Dir{Perm: 0o700}, - "/home/user/dir": map[string]interface{}{ - "foo": "bar", - }, - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/exact_dir", - vfst.TestIsDir, - ), - vfst.TestPath("/home/user/.local/share/chezmoi/exact_dir/foo", - vfst.TestModeIsRegular, - vfst.TestContentsString("bar"), - ), - }, - }, - { - name: "add_empty_file", - args: []string{"/home/user/empty"}, - add: addCmdConfig{ - options: chezmoi.AddOptions{ - Empty: true, - }, - }, - root: map[string]interface{}{ - "/home/user": &vfst.Dir{Perm: 0o755}, - "/home/user/.local/share/chezmoi": &vfst.Dir{Perm: 0o700}, - "/home/user/empty": "", - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/empty_empty", - vfst.TestModeIsRegular, - vfst.TestContents(nil), - ), - }, - }, - { - name: "add_empty_file_in_subdir", - args: []string{"/home/user/subdir/empty"}, - root: map[string]interface{}{ - "/home/user": &vfst.Dir{Perm: 0o755}, - "/home/user/.local/share/chezmoi": &vfst.Dir{Perm: 0o700}, - "/home/user/subdir/empty": "", - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/subdir", - vfst.TestIsDir, - ), - }, - }, - { - name: "add_symlink", - args: []string{"/home/user/foo"}, - root: map[string]interface{}{ - "/home/user": &vfst.Dir{Perm: 0o755}, - "/home/user/.local/share/chezmoi": &vfst.Dir{Perm: 0o700}, - "/home/user/foo": &vfst.Symlink{Target: "bar"}, - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/symlink_foo", - vfst.TestModeIsRegular, - vfst.TestContentsString("bar"), - ), - }, - }, - { - name: "add_followed_symlink", - args: []string{"/home/user/foo"}, - follow: true, - root: map[string]interface{}{ - "/home/user": &vfst.Dir{Perm: 0o755}, - "/home/user/.local/share/chezmoi": &vfst.Dir{Perm: 0o700}, - "/home/user/foo": &vfst.Symlink{Target: "bar"}, - "/home/user/bar": "bux", - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/foo", - vfst.TestModeIsRegular, - vfst.TestContentsString("bux"), - ), - }, - }, - { - name: "add_symlink_follow", - args: []string{"/home/user/foo"}, - follow: true, - root: map[string]interface{}{ - "/home/user": &vfst.Dir{Perm: 0o755}, - "/home/user/.local/share/chezmoi": &vfst.Dir{Perm: 0o700}, - "/home/user/.dotfiles/foo": "bar", - "/home/user/foo": &vfst.Symlink{Target: ".dotfiles/foo"}, - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/foo", - vfst.TestModeIsRegular, - vfst.TestContentsString("bar"), - ), - }, - }, - { - name: "add_symlink_no_follow", - args: []string{"/home/user/foo"}, - root: map[string]interface{}{ - "/home/user": &vfst.Dir{Perm: 0o755}, - "/home/user/.local/share/chezmoi": &vfst.Dir{Perm: 0o700}, - "/home/user/.dotfiles/foo": "bar", - "/home/user/foo": &vfst.Symlink{Target: ".dotfiles/foo"}, - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/symlink_foo", - vfst.TestModeIsRegular, - vfst.TestContentsString(filepath.FromSlash(".dotfiles/foo")), - ), - }, - }, - { - name: "add_symlink_follow_double", - args: []string{"/home/user/foo"}, - follow: true, - root: map[string]interface{}{ - "/home/user": &vfst.Dir{Perm: 0o755}, - "/home/user/.local/share/chezmoi": &vfst.Dir{Perm: 0o700}, - "/home/user/.dotfiles/baz": "qux", - "/home/user/foo": &vfst.Symlink{Target: "bar"}, - "/home/user/bar": &vfst.Symlink{Target: ".dotfiles/baz"}, - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/foo", - vfst.TestModeIsRegular, - vfst.TestContentsString("qux"), - ), - }, - }, - { - name: "add_symlink_in_dir_recursive", - args: []string{"/home/user/foo"}, - add: addCmdConfig{ - options: chezmoi.AddOptions{ - Recursive: true, - }, - }, - root: map[string]interface{}{ - "/home/user": &vfst.Dir{Perm: 0o755}, - "/home/user/.local/share/chezmoi": &vfst.Dir{Perm: 0o700}, - "/home/user/foo/bar": &vfst.Symlink{Target: "baz"}, - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/foo", - vfst.TestIsDir, - ), - vfst.TestPath("/home/user/.local/share/chezmoi/foo/symlink_bar", - vfst.TestModeIsRegular, - vfst.TestContentsString("baz"), - ), - }, - }, - { - name: "add_symlink_with_parent_dir", - args: []string{"/home/user/foo/bar/baz"}, - root: map[string]interface{}{ - "/home/user": &vfst.Dir{Perm: 0o755}, - "/home/user/.local/share/chezmoi": &vfst.Dir{Perm: 0o700}, - "/home/user/foo/bar/baz": &vfst.Symlink{Target: "qux"}, - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/foo", - vfst.TestIsDir, - ), - vfst.TestPath("/home/user/.local/share/chezmoi/foo/bar", - vfst.TestIsDir, - ), - vfst.TestPath("/home/user/.local/share/chezmoi/foo/bar/symlink_baz", - vfst.TestModeIsRegular, - vfst.TestContentsString("qux"), - ), - }, - }, - { - name: "dont_add_ignored_file", - args: []string{"/home/user/foo"}, - root: map[string]interface{}{ - "/home/user": &vfst.Dir{Perm: 0o755}, - "/home/user/.local/share/chezmoi": &vfst.Dir{ - Perm: 0o700, - Entries: map[string]interface{}{ - ".chezmoiignore": "foo\n", - }, - }, - "/home/user/foo": "bar", - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/foo", - vfst.TestDoesNotExist, - ), - }, - }, - { - name: "dont_add_ignored_file_recursive", - args: []string{"/home/user/foo"}, - add: addCmdConfig{ - options: chezmoi.AddOptions{ - Recursive: true, - }, - }, - root: map[string]interface{}{ - "/home/user": &vfst.Dir{Perm: 0o755}, - "/home/user/.local/share/chezmoi": &vfst.Dir{ - Perm: 0o700, - Entries: map[string]interface{}{ - "exact_foo/.chezmoiignore": "bar/qux\n", - }, - }, - "/home/user/foo/bar": map[string]interface{}{ - "baz": "baz", - "qux": "quz", - }, - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/exact_foo/bar/baz", - vfst.TestModeIsRegular, - vfst.TestContentsString("baz"), - ), - vfst.TestPath("/home/user/.local/share/chezmoi/exact_foo/bar/qux", - vfst.TestDoesNotExist, - ), - }, - }, - { - name: "remove_existing_source_without_empty", - args: []string{"/home/user/foo"}, - add: addCmdConfig{ - options: chezmoi.AddOptions{ - Empty: false, - }, - }, - root: map[string]interface{}{ - "/home/user/foo": "", - "/home/user/.local/share/chezmoi/foo": "bar", - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/foo", - vfst.TestDoesNotExist, - ), - }, - }, - { - name: "replace_existing_source_with_empty", - args: []string{"/home/user/foo"}, - add: addCmdConfig{ - options: chezmoi.AddOptions{ - Empty: true, - }, - }, - root: map[string]interface{}{ - "/home/user/foo": "", - "/home/user/.local/share/chezmoi/foo": "bar", - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/empty_foo", - vfst.TestModeIsRegular, - vfst.TestContentsString(""), - ), - }, - }, - { - name: "dest_dir_is_symlink", - args: []string{"/home/user/foo"}, - root: []interface{}{ - map[string]interface{}{ - "/local/home/user/.local/share/chezmoi": &vfst.Dir{Perm: 0o700}, - "/local/home/user/foo": "bar", - }, - map[string]interface{}{ - "/home/user": &vfst.Symlink{Target: "../local/home/user"}, - }, - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi", - vfst.TestIsDir, - ), - vfst.TestPath("/home/user/.local/share/chezmoi/foo", - vfst.TestModeIsRegular, - vfst.TestContentsString("bar"), - ), - vfst.TestPath("/local/home/user/.local/share/chezmoi", - vfst.TestIsDir, - ), - vfst.TestPath("/local/home/user/.local/share/chezmoi/foo", - vfst.TestModeIsRegular, - vfst.TestContentsString("bar"), - ), - }, - }, - } { - t.Run(tc.name, func(t *testing.T) { - fs, cleanup, err := vfst.NewTestFS(tc.root) - require.NoError(t, err) - defer cleanup() - c := newTestConfig( - fs, - withFollow(tc.follow), - withData(map[string]interface{}{ - "name": "John Smith", - "email": "[email protected]", - }), - withAddCmdConfig(tc.add), - ) - assert.NoError(t, c.runAddCmd(&cobra.Command{}, tc.args)) - vfst.RunTests(t, fs, "", tc.tests) - }) - } -} - -func TestIssue192(t *testing.T) { - root := []interface{}{ - map[string]interface{}{ - "/local/home/user": &vfst.Dir{ - Perm: 0o750, - Entries: map[string]interface{}{ - ".local/share/chezmoi": &vfst.Dir{Perm: 0o700}, - "snoop/.list": "# contents of .list\n", - }, - }, - }, - map[string]interface{}{ - "/home/user": &vfst.Symlink{Target: "/local/home/user/"}, - }, - } - fs, cleanup, err := vfst.NewTestFS(root) - require.NoError(t, err) - defer cleanup() - c := newTestConfig(fs) - assert.NoError(t, c.runAddCmd(nil, []string{"/home/user/snoop/.list"})) - vfst.RunTests(t, fs, "", - vfst.TestPath("/local/home/user/.local/share/chezmoi/snoop/dot_list", - vfst.TestModeIsRegular, - vfst.TestContentsString("# contents of .list\n"), - ), - ) -} diff --git a/chezmoi2/cmd/addcmd.go b/cmd/addcmd.go similarity index 92% rename from chezmoi2/cmd/addcmd.go rename to cmd/addcmd.go index 41d52399490..5767980ef4d 100644 --- a/chezmoi2/cmd/addcmd.go +++ b/cmd/addcmd.go @@ -3,7 +3,7 @@ package cmd import ( "github.com/spf13/cobra" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoi" ) type addCmdConfig struct { @@ -13,7 +13,7 @@ type addCmdConfig struct { encrypt bool exact bool follow bool - include *chezmoi.IncludeSet + include *chezmoi.EntryTypeSet recursive bool template bool } @@ -39,7 +39,7 @@ func (c *Config) newAddCmd() *cobra.Command { flags.BoolVar(&c.add.create, "create", c.add.create, "add files that should exist, irrespective of their contents") flags.BoolVarP(&c.add.empty, "empty", "e", c.add.empty, "add empty files") flags.BoolVar(&c.add.encrypt, "encrypt", c.add.encrypt, "encrypt files") - flags.BoolVarP(&c.add.exact, "exact", "x", c.add.exact, "add directories exactly") + flags.BoolVar(&c.add.exact, "exact", c.add.exact, "add directories exactly") flags.BoolVarP(&c.add.follow, "follow", "f", c.add.follow, "add symlink targets instead of symlinks") flags.BoolVarP(&c.add.recursive, "recursive", "r", c.add.recursive, "recursive") flags.BoolVarP(&c.add.template, "template", "T", c.add.template, "add files as templates") diff --git a/chezmoi2/cmd/addcmd_test.go b/cmd/addcmd_test.go similarity index 98% rename from chezmoi2/cmd/addcmd_test.go rename to cmd/addcmd_test.go index 33925312d99..94eed3c0798 100644 --- a/chezmoi2/cmd/addcmd_test.go +++ b/cmd/addcmd_test.go @@ -4,10 +4,10 @@ import ( "testing" "github.com/stretchr/testify/require" - "github.com/twpayne/go-vfs" - "github.com/twpayne/go-vfs/vfst" + "github.com/twpayne/go-vfs/v2" + "github.com/twpayne/go-vfs/v2/vfst" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoitest" + "github.com/twpayne/chezmoi/internal/chezmoitest" ) func TestAddCmd(t *testing.T) { diff --git a/cmd/apply.go b/cmd/apply.go deleted file mode 100644 index 89203be9547..00000000000 --- a/cmd/apply.go +++ /dev/null @@ -1,30 +0,0 @@ -package cmd - -import ( - "github.com/spf13/cobra" -) - -var applyCmd = &cobra.Command{ - Use: "apply [targets...]", - Short: "Update the destination directory to match the target state", - Long: mustGetLongHelp("apply"), - Example: getExample("apply"), - PreRunE: config.ensureNoError, - RunE: config.runApplyCmd, -} - -func init() { - rootCmd.AddCommand(applyCmd) - - markRemainingZshCompPositionalArgumentsAsFiles(applyCmd, 1) -} - -func (c *Config) runApplyCmd(cmd *cobra.Command, args []string) error { - persistentState, err := c.getPersistentState(nil) - if err != nil { - return err - } - defer persistentState.Close() - - return c.applyArgs(args, persistentState) -} diff --git a/cmd/apply_posix_test.go b/cmd/apply_posix_test.go deleted file mode 100644 index ff588f88652..00000000000 --- a/cmd/apply_posix_test.go +++ /dev/null @@ -1,84 +0,0 @@ -// +build !windows - -package cmd - -import ( - "path/filepath" - "strings" - - "github.com/twpayne/go-vfs/vfst" -) - -func getApplyScriptTestCases(tempDir string) []scriptTestCase { - return []scriptTestCase{ - { - name: "simple", - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi/run_true": "#!/bin/sh\necho foo >>" + filepath.Join(tempDir, "evidence") + "\n", - }, - tests: []vfst.Test{ - vfst.TestPath(filepath.Join(tempDir, "evidence"), - vfst.TestModeIsRegular, - vfst.TestContentsString("foo\nfoo\nfoo\n"), - ), - }, - }, - { - name: "simple_once", - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi/run_once_true": "#!/bin/sh\necho foo >>" + filepath.Join(tempDir, "evidence") + "\n", - }, - tests: []vfst.Test{ - vfst.TestPath(filepath.Join(tempDir, "evidence"), - vfst.TestModeIsRegular, - vfst.TestContentsString("foo\n"), - ), - }, - }, - { - name: "template", - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi/run_true.tmpl": "#!/bin/sh\necho {{ .Foo }} >>" + filepath.Join(tempDir, "evidence") + "\n", - }, - data: map[string]interface{}{ - "Foo": "foo", - }, - tests: []vfst.Test{ - vfst.TestPath(filepath.Join(tempDir, "evidence"), - vfst.TestModeIsRegular, - vfst.TestContentsString("foo\nfoo\nfoo\n"), - ), - }, - }, - { - name: "issue_353", - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi": map[string]interface{}{ - "run_050_giraffe": "#!/usr/bin/env bash\necho giraffe >>" + filepath.Join(tempDir, "evidence") + "\n", - "run_150_elephant": "#!/usr/bin/env bash\necho elephant >>" + filepath.Join(tempDir, "evidence") + "\n", - "run_once_100_miauw.sh": "#!/usr/bin/env bash\necho miauw >>" + filepath.Join(tempDir, "evidence") + "\n", - }, - }, - tests: []vfst.Test{ - vfst.TestPath(filepath.Join(tempDir, "evidence"), - vfst.TestModeIsRegular, - vfst.TestContentsString(strings.Join([]string{ - "giraffe\n", - "miauw\n", - "elephant\n", - "giraffe\n", - "elephant\n", - "giraffe\n", - "elephant\n", - }, "")), - ), - }, - }, - } -} - -func getRunOnceFiles() map[string]interface{} { - return map[string]interface{}{ - "/home/user/.local/share/chezmoi/run_once_foo.tmpl": "#!/bin/sh\necho bar >> {{ .TempFile }}\n", - } -} diff --git a/cmd/apply_test.go b/cmd/apply_test.go deleted file mode 100644 index 029fe914dfb..00000000000 --- a/cmd/apply_test.go +++ /dev/null @@ -1,487 +0,0 @@ -package cmd - -import ( - "io/ioutil" - "os" - "path/filepath" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - vfs "github.com/twpayne/go-vfs" - "github.com/twpayne/go-vfs/vfst" -) - -type scriptTestCase struct { - name string - root interface{} - data map[string]interface{} - tests []vfst.Test -} - -func TestApplyCommand(t *testing.T) { - for _, tc := range []struct { - name string - root map[string]interface{} - }{ - { - name: "create", - root: make(map[string]interface{}), - }, - { - name: "change_dir_permissions", - root: map[string]interface{}{ - "/home/user/dir": &vfst.Dir{Perm: 0o700}, - }, - }, - { - name: "replace_file_with_dir", - root: map[string]interface{}{ - "/home/user/dir": "file", - }, - }, - { - name: "replace_symlink_with_dir", - root: map[string]interface{}{ - "/home/user/dir": &vfst.Symlink{Target: "target"}, - }, - }, - { - name: "change_file_permissions", - root: map[string]interface{}{ - "/home/user/dir/file": &vfst.File{ - Perm: 0o755, - Contents: []byte("contents"), - }, - }, - }, - { - name: "replace_dir_with_file", - root: map[string]interface{}{ - "/home/user/dir/file": &vfst.Dir{Perm: 0o755}, - }, - }, - { - name: "replace_symlink_with_file", - root: map[string]interface{}{ - "/home/user/dir/file": &vfst.Symlink{Target: "target"}, - }, - }, - { - name: "replace_dir_with_symlink", - root: map[string]interface{}{ - "/home/user/symlink": &vfst.Dir{Perm: 0o755}, - }, - }, - { - name: "replace_file_with_symlink", - root: map[string]interface{}{ - "/home/user/symlink": "contents", - }, - }, - { - name: "change_symlink_target", - root: map[string]interface{}{ - "/home/user/symlink": &vfst.Symlink{Target: "file"}, - }, - }, - { - name: "strip_symlink_newline", - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi": map[string]interface{}{ - "symlink_symlink.tmpl": "{{ if true }}tar{{ end }}get\n", - }, - }, - }, - { - name: "templates_dir", - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi": map[string]interface{}{ - "dir/file.tmpl": `{{ template "foo" }}`, - ".chezmoitemplates/foo": "{{ if true }}contents{{ end }}", - }, - }, - }, - { - name: "define_template", - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi": map[string]interface{}{ - "dir/file.tmpl": `{{ define "foo" }}cont{{end}}{{ template "foo" }}ents`, - }, - }, - }, - { - name: "partial_template", - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi": map[string]interface{}{ - "dir/file.tmpl": `{{ template "foo" }}ents`, - ".chezmoitemplates/foo": "{{ if true }}cont{{ end }}", - }, - }, - }, - { - name: "partial_template_in_subdir", - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi": map[string]interface{}{ - "dir/file.tmpl": `{{ template "foo" }}{{ template "bar/foo" }}`, - ".chezmoitemplates/foo": "{{ if true }}cont{{ end }}", - ".chezmoitemplates/bar/foo": "{{ if true }}ents{{ end }}", - }, - }, - }, - { - name: "multiple_templates", - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi": map[string]interface{}{ - "dir/file.tmpl": `{{ template "foo" }}`, - "dir/other.tmpl": `{{ if true }}other stuff{{ end }}`, - ".chezmoitemplates/foo": "{{ if true }}contents{{ end }}", - }, - }, - }, - { - name: "multiple_associated", - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi": map[string]interface{}{ - "dir/file.tmpl": `{{ template "foo" }}{{ template "bar" }}`, - ".chezmoitemplates/foo": "{{ if true }}cont{{ end }}", - ".chezmoitemplates/bar": "{{ if true }}ents{{ end }}", - }, - }, - }, - } { - t.Run(tc.name, func(t *testing.T) { - tc.root["/home/user/.local/share/chezmoi/dir/file"] = "contents" - tc.root["/home/user/.local/share/chezmoi/dir/other"] = "other stuff" - tc.root["/home/user/.local/share/chezmoi/symlink_symlink"] = "target" - fs, cleanup, err := vfst.NewTestFS(tc.root) - require.NoError(t, err) - defer cleanup() - c := newTestConfig(fs) - assert.NoError(t, c.runApplyCmd(nil, nil)) - vfst.RunTests(t, fs, "", - vfst.TestPath("/home/user/dir", - vfst.TestIsDir, - vfst.TestModePerm(0o755), - ), - vfst.TestPath("/home/user/dir/file", - vfst.TestModeIsRegular, - vfst.TestModePerm(0o644), - vfst.TestContentsString("contents"), - ), - vfst.TestPath("/home/user/dir/other", - vfst.TestModeIsRegular, - vfst.TestModePerm(0o644), - vfst.TestContentsString("other stuff"), - ), - vfst.TestPath("/home/user/symlink", - vfst.TestModeType(os.ModeSymlink), - vfst.TestSymlinkTarget("target"), - ), - ) - }) - } -} - -func TestApplyFollow(t *testing.T) { - for _, tc := range []struct { - name string - follow bool - root interface{} - tests []vfst.Test - }{ - { - name: "follow", - follow: true, - root: map[string]interface{}{ - "/home/user": map[string]interface{}{ - "bar": "baz", - "foo": &vfst.Symlink{Target: "bar"}, - }, - "/home/user/.local/share/chezmoi": map[string]interface{}{ - "foo": "qux", - }, - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/bar", - vfst.TestModeIsRegular, - vfst.TestContentsString("qux"), - ), - vfst.TestPath("/home/user/foo", - vfst.TestModeType(os.ModeSymlink), - vfst.TestSymlinkTarget("bar"), - ), - }, - }, - { - name: "nofollow", - follow: false, - root: map[string]interface{}{ - "/home/user": map[string]interface{}{ - "bar": "baz", - "foo": &vfst.Symlink{Target: "bar"}, - }, - "/home/user/.local/share/chezmoi": map[string]interface{}{ - "foo": "qux", - }, - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/bar", - vfst.TestContentsString("baz"), - ), - vfst.TestPath("/home/user/foo", - vfst.TestModeIsRegular, - vfst.TestContentsString("qux"), - ), - }, - }, - } { - t.Run(tc.name, func(t *testing.T) { - fs, cleanup, err := vfst.NewTestFS(tc.root) - require.NoError(t, err) - defer cleanup() - c := newTestConfig( - fs, - withFollow(tc.follow), - ) - assert.NoError(t, c.runApplyCmd(nil, nil)) - vfst.RunTests(t, fs, "", tc.tests) - }) - } -} - -func TestApplyRemove(t *testing.T) { - for _, tc := range []struct { - name string - noRemove bool - root interface{} - data map[string]interface{} - tests []vfst.Test - }{ - { - name: "simple", - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi/.chezmoiremove": "foo", - "/home/user/foo": "# contents of foo\n", - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/foo", - vfst.TestDoesNotExist, - ), - }, - }, - { - name: "no_remove", - noRemove: true, - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi/.chezmoiremove": "foo", - "/home/user/foo": "# contents of foo\n", - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/foo", - vfst.TestModeIsRegular, - vfst.TestContentsString("# contents of foo\n"), - ), - }, - }, - { - name: "pattern", - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi/.chezmoiremove": "f*", - "/home/user/foo": "# contents of foo\n", - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/foo", - vfst.TestDoesNotExist, - ), - }, - }, - { - name: "template", - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi/.chezmoiremove": "{{ .bar }}", - "/home/user/foo": "# contents of foo\n", - }, - data: map[string]interface{}{ - "bar": "foo", - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/foo", - vfst.TestDoesNotExist, - ), - }, - }, - { - name: "dont_remove_negative_pattern", - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi/.chezmoiremove": "f*\n!foo\n", - "/home/user/foo": "# contents of foo\n", - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/foo", - vfst.TestModeIsRegular, - vfst.TestContentsString("# contents of foo\n"), - ), - }, - }, - { - name: "dont_remove_ignored", - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi/.chezmoiignore": "foo", - "/home/user/.local/share/chezmoi/.chezmoiremove": "f*", - "/home/user/foo": "# contents of foo\n", - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/foo", - vfst.TestModeIsRegular, - vfst.TestContentsString("# contents of foo\n"), - ), - }, - }, - { - name: "remove_subdirectory_first", - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi/.chezmoiremove": "foo\nfoo/bar\n", - "/home/user/foo/bar": "# contents of bar\n", - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/foo", - vfst.TestDoesNotExist, - ), - }, - }, - } { - t.Run(tc.name, func(t *testing.T) { - fs, cleanup, err := vfst.NewTestFS(tc.root) - require.NoError(t, err) - defer cleanup() - c := newTestConfig( - fs, - withData(tc.data), - withRemove(!tc.noRemove), - ) - assert.NoError(t, c.runApplyCmd(nil, nil)) - vfst.RunTests(t, fs, "", tc.tests) - }) - } -} - -func TestApplyScript(t *testing.T) { - tempDir, err := ioutil.TempDir("", "chezmoi") - require.NoError(t, err) - defer func() { - require.NoError(t, os.RemoveAll(tempDir)) - }() - for _, tc := range getApplyScriptTestCases(tempDir) { - t.Run(tc.name, func(t *testing.T) { - fs := vfs.NewPathFS(vfs.OSFS, tempDir) - require.NoError(t, vfst.NewBuilder().Build(fs, tc.root)) - defer func() { - require.NoError(t, os.RemoveAll(tempDir)) - require.NoError(t, os.Mkdir(tempDir, 0o700)) - }() - apply := func() { - c := newTestConfig( - fs, - withDestDir("/"), - withData(tc.data), - ) - require.NoError(t, c.runApplyCmd(nil, nil)) - } - // Run apply three times. As chezmoi should be idempotent, the - // result should be the same each time. - for i := 0; i < 3; i++ { - apply() - } - vfst.RunTests(t, vfs.OSFS, "", tc.tests) - }) - } -} - -func TestApplyRunOnce(t *testing.T) { - tempDir, err := ioutil.TempDir("", "chezmoi") - require.NoError(t, err) - defer func() { - require.NoError(t, os.RemoveAll(tempDir)) - }() - tempFile := filepath.Join(tempDir, "foo") - - fs, cleanup, err := vfst.NewTestFS( - []interface{}{ - getRunOnceFiles(), - }, - ) - require.NoError(t, err) - defer cleanup() - - c := newTestConfig( - fs, - withDestDir("/"), - withData(map[string]interface{}{ - "TempFile": tempFile, - }), - ) - - require.NoError(t, c.runApplyCmd(nil, nil)) - vfst.RunTests(t, fs, "", - vfst.TestPath("/home/user/.config/chezmoi/chezmoistate.boltdb", - vfst.TestModeIsRegular, - ), - ) - - actualData, err := ioutil.ReadFile(tempFile) - require.NoError(t, err) - assert.Equal(t, []byte("bar\n"), actualData) - - require.NoError(t, c.runApplyCmd(nil, nil)) - actualData, err = ioutil.ReadFile(tempFile) - require.NoError(t, err) - assert.Equal(t, []byte("bar\n"), actualData) -} - -func TestApplyRemoveEmptySymlink(t *testing.T) { - for _, tc := range []struct { - name string - root interface{} - tests []vfst.Test - }{ - { - name: "empty_symlink_remove_existing_symlink", - root: map[string]interface{}{ - "/home/user/foo": &vfst.Symlink{Target: "bar"}, - "/home/user/.local/share/chezmoi/symlink_foo": "", - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/foo", vfst.TestDoesNotExist), - }, - }, - { - name: "empty_symlink_remove_existing_dir", - root: map[string]interface{}{ - "/home/user/foo/bar": "baz", - "/home/user/.local/share/chezmoi/symlink_foo": "", - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/foo", vfst.TestDoesNotExist), - }, - }, - { - name: "empty_symlink_no_target", - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi/symlink_foo": "", - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/foo", vfst.TestDoesNotExist), - }, - }, - } { - t.Run(tc.name, func(t *testing.T) { - fs, cleanup, err := vfst.NewTestFS(tc.root) - require.NoError(t, err) - defer cleanup() - c := newTestConfig(fs) - assert.NoError(t, c.runApplyCmd(nil, nil)) - vfst.RunTests(t, fs, "", tc.tests) - }) - } -} diff --git a/cmd/apply_windows_test.go b/cmd/apply_windows_test.go deleted file mode 100644 index 61e310ee297..00000000000 --- a/cmd/apply_windows_test.go +++ /dev/null @@ -1,90 +0,0 @@ -// +build windows - -package cmd - -import ( - "path/filepath" - "strings" - - "github.com/twpayne/go-vfs/vfst" -) - -func getApplyScriptTestCases(tempDir string) []scriptTestCase { - return []scriptTestCase{ - { - name: "simple", - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi/run_true.bat": "@echo foo>>" + filepath.Join(tempDir, "evidence") + "\n", - }, - tests: []vfst.Test{ - vfst.TestPath(filepath.Join(tempDir, "evidence"), - vfst.TestModeIsRegular, - vfst.TestContentsString("foo\r\nfoo\r\nfoo\r\n"), - ), - }, - }, - { - name: "simple_once", - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi/run_once_true.bat": "@echo foo>>" + filepath.Join(tempDir, "evidence") + "\n", - }, - tests: []vfst.Test{ - vfst.TestPath(filepath.Join(tempDir, "evidence"), - vfst.TestModeIsRegular, - vfst.TestContentsString("foo\r\n"), - ), - }, - }, - { - name: "template", - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi/run_true.bat.tmpl": "@echo {{ .Foo }}>>" + filepath.Join(tempDir, "evidence") + "\n", - }, - data: map[string]interface{}{ - "Foo": "foo", - }, - tests: []vfst.Test{ - vfst.TestPath(filepath.Join(tempDir, "evidence"), - vfst.TestModeIsRegular, - vfst.TestContentsString("foo\r\nfoo\r\nfoo\r\n"), - ), - }, - }, - { - name: "issue_353", - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi": map[string]interface{}{ - "run_050_giraffe.bat": "@echo giraffe>>" + filepath.Join(tempDir, "evidence") + "\n", - "run_150_elephant.bat": "@echo elephant>>" + filepath.Join(tempDir, "evidence") + "\n", - "run_once_100_miauw.bat": "@echo miauw>>" + filepath.Join(tempDir, "evidence") + "\n", - }, - }, - tests: []vfst.Test{ - vfst.TestPath(filepath.Join(tempDir, "evidence"), - vfst.TestModeIsRegular, - vfst.TestContentsString(strings.Join([]string{ - "giraffe\r\n", - "miauw\r\n", - "elephant\r\n", - "giraffe\r\n", - "elephant\r\n", - "giraffe\r\n", - "elephant\r\n", - }, "")), - ), - }, - }, - } -} - -func getRunOnceFiles() map[string]interface{} { - return map[string]interface{}{ - // Windows batch script does not include any way to print a string to - // the console with only a linefeed (0x0A) and no carriage return - // (0x0D), but it can be done with PowerShell. The default action for - // PowerShell script files on Windows is to open them in the default - // text editor rather than to execute them (for security reasons). The - // easiest solution is to make a batch file that calls PowerShell. - "/home/user/.local/share/chezmoi/run_once_foo.bat.tmpl": "@powershell.exe -NoProfile -NonInteractive -c \"Write-Host -NoNewLine ('bar{0}' -f (0x0A -as [char]))\">> {{ .TempFile }}\n", - } -} diff --git a/chezmoi2/cmd/applycmd.go b/cmd/applycmd.go similarity index 59% rename from chezmoi2/cmd/applycmd.go rename to cmd/applycmd.go index e60f1230eba..16dc831b741 100644 --- a/chezmoi2/cmd/applycmd.go +++ b/cmd/applycmd.go @@ -3,14 +3,12 @@ package cmd import ( "github.com/spf13/cobra" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoi" ) type applyCmdConfig struct { - include *chezmoi.IncludeSet - recursive bool - skipEncrypted bool - sourcePath bool + include *chezmoi.EntryTypeSet + recursive bool } func (c *Config) newApplyCmd() *cobra.Command { @@ -27,21 +25,17 @@ func (c *Config) newApplyCmd() *cobra.Command { } flags := applyCmd.Flags() - flags.BoolVar(&c.apply.skipEncrypted, "ignore-encrypted", c.apply.skipEncrypted, "ignore encrypted files") flags.VarP(c.apply.include, "include", "i", "include entry types") flags.BoolVarP(&c.apply.recursive, "recursive", "r", c.apply.recursive, "recursive") - flags.BoolVar(&c.apply.sourcePath, "source-path", c.apply.sourcePath, "specify targets by source path") return applyCmd } func (c *Config) runApplyCmd(cmd *cobra.Command, args []string) error { return c.applyArgs(c.destSystem, c.destDirAbsPath, args, applyArgsOptions{ - include: c.apply.include, - recursive: c.apply.recursive, - skipEncrypted: c.apply.skipEncrypted, - sourcePath: c.apply.sourcePath, - umask: c.Umask, - preApplyFunc: c.defaultPreApplyFunc, + include: c.apply.include, + recursive: c.apply.recursive, + umask: c.Umask, + preApplyFunc: c.defaultPreApplyFunc, }) } diff --git a/chezmoi2/cmd/applycmd_test.go b/cmd/applycmd_test.go similarity index 97% rename from chezmoi2/cmd/applycmd_test.go rename to cmd/applycmd_test.go index 20eb32656fc..4fe0991009d 100644 --- a/chezmoi2/cmd/applycmd_test.go +++ b/cmd/applycmd_test.go @@ -6,10 +6,10 @@ import ( "testing" "github.com/stretchr/testify/require" - "github.com/twpayne/go-vfs" - "github.com/twpayne/go-vfs/vfst" + "github.com/twpayne/go-vfs/v2" + "github.com/twpayne/go-vfs/v2/vfst" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoitest" + "github.com/twpayne/chezmoi/internal/chezmoitest" ) func TestApplyCmd(t *testing.T) { diff --git a/cmd/archive.go b/cmd/archive.go deleted file mode 100644 index 04795e4154b..00000000000 --- a/cmd/archive.go +++ /dev/null @@ -1,53 +0,0 @@ -package cmd - -import ( - "archive/tar" - "os" - "strings" - - "github.com/spf13/cobra" -) - -type archiveCmdConfig struct { - output string -} - -var archiveCmd = &cobra.Command{ - Use: "archive", - Args: cobra.NoArgs, - Short: "Write a tar archive of the target state to stdout", - Long: mustGetLongHelp("archive"), - Example: getExample("archive"), - PreRunE: config.ensureNoError, - RunE: config.runArchiveCmd, -} - -func init() { - rootCmd.AddCommand(archiveCmd) - - persistentFlags := archiveCmd.PersistentFlags() - persistentFlags.StringVarP(&config.archive.output, "output", "o", "", "output filename") - panicOnError(archiveCmd.MarkPersistentFlagFilename("output")) -} - -func (c *Config) runArchiveCmd(cmd *cobra.Command, args []string) error { - ts, err := c.getTargetState(nil) - if err != nil { - return err - } - - output := &strings.Builder{} - w := tar.NewWriter(output) - if err := ts.Archive(w, os.FileMode(c.Umask)); err != nil { - return err - } - if err := w.Close(); err != nil { - return err - } - - if c.archive.output == "" { - _, err := c.Stdout.Write([]byte(output.String())) - return err - } - return c.fs.WriteFile(c.archive.output, []byte(output.String()), 0o666) -} diff --git a/cmd/archive_test.go b/cmd/archive_test.go deleted file mode 100644 index 25a1e87817d..00000000000 --- a/cmd/archive_test.go +++ /dev/null @@ -1,49 +0,0 @@ -package cmd - -import ( - "archive/tar" - "bytes" - "io" - "io/ioutil" - "path/filepath" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/twpayne/go-vfs/vfst" -) - -func TestArchiveCmd(t *testing.T) { - fs, cleanup, err := vfst.NewTestFS(map[string]interface{}{ - "/home/user/.local/share/chezmoi/dir/file": "contents", - "/home/user/.local/share/chezmoi/symlink_symlink": "target", - }) - require.NoError(t, err) - defer cleanup() - stdout := &bytes.Buffer{} - c := newTestConfig( - fs, - withStdout(stdout), - ) - assert.NoError(t, c.runArchiveCmd(nil, nil)) - r := tar.NewReader(stdout) - - h, err := r.Next() - assert.NoError(t, err) - assert.Equal(t, "dir/", h.Name) - - h, err = r.Next() - assert.NoError(t, err) - assert.Equal(t, filepath.Join("dir", "file"), h.Name) - data, err := ioutil.ReadAll(r) - assert.NoError(t, err) - assert.Equal(t, []byte("contents"), data) - - h, err = r.Next() - assert.NoError(t, err) - assert.Equal(t, "symlink", h.Name) - assert.Equal(t, "target", h.Linkname) - - _, err = r.Next() - assert.Equal(t, err, io.EOF) -} diff --git a/chezmoi2/cmd/archivecmd.go b/cmd/archivecmd.go similarity index 96% rename from chezmoi2/cmd/archivecmd.go rename to cmd/archivecmd.go index 897f72786b4..05905b92b6a 100644 --- a/chezmoi2/cmd/archivecmd.go +++ b/cmd/archivecmd.go @@ -11,13 +11,13 @@ import ( "github.com/spf13/cobra" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoi" ) type archiveCmdConfig struct { format string gzip bool - include *chezmoi.IncludeSet + include *chezmoi.EntryTypeSet recursive bool } diff --git a/chezmoi2/cmd/bitwardentemplatefuncs.go b/cmd/bitwardentemplatefuncs.go similarity index 97% rename from chezmoi2/cmd/bitwardentemplatefuncs.go rename to cmd/bitwardentemplatefuncs.go index 4285fbb3373..b01003b2ba3 100644 --- a/chezmoi2/cmd/bitwardentemplatefuncs.go +++ b/cmd/bitwardentemplatefuncs.go @@ -6,7 +6,7 @@ import ( "os/exec" "strings" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoi" ) type bitwardenConfig struct { diff --git a/cmd/cat.go b/cmd/cat.go deleted file mode 100644 index e41af4eaec2..00000000000 --- a/cmd/cat.go +++ /dev/null @@ -1,57 +0,0 @@ -package cmd - -import ( - "fmt" - - "github.com/spf13/cobra" - - "github.com/twpayne/chezmoi/internal/chezmoi" -) - -var catCmd = &cobra.Command{ - Use: "cat targets...", - Args: cobra.MinimumNArgs(1), - Short: "Print the target contents of a file or symlink", - Long: mustGetLongHelp("cat"), - Example: getExample("cat"), - PreRunE: config.ensureNoError, - RunE: config.runCatCmd, -} - -func init() { - rootCmd.AddCommand(catCmd) - - markRemainingZshCompPositionalArgumentsAsFiles(catCmd, 1) -} - -func (c *Config) runCatCmd(cmd *cobra.Command, args []string) error { - ts, err := c.getTargetState(nil) - if err != nil { - return err - } - entries, err := c.getEntries(ts, args) - if err != nil { - return err - } - for i, entry := range entries { - switch entry := entry.(type) { - case *chezmoi.File: - contents, err := entry.Contents() - if err != nil { - return err - } - if _, err := c.Stdout.Write(contents); err != nil { - return err - } - case *chezmoi.Symlink: - linkname, err := entry.Linkname() - if err != nil { - return err - } - fmt.Println(linkname) - default: - return fmt.Errorf("%s: not a file or symlink", args[i]) - } - } - return nil -} diff --git a/chezmoi2/cmd/catcmd.go b/cmd/catcmd.go similarity index 96% rename from chezmoi2/cmd/catcmd.go rename to cmd/catcmd.go index df06b2fdec9..0e6c07aa4ba 100644 --- a/chezmoi2/cmd/catcmd.go +++ b/cmd/catcmd.go @@ -6,7 +6,7 @@ import ( "github.com/spf13/cobra" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoi" ) func (c *Config) newCatCmd() *cobra.Command { diff --git a/cmd/cd.go b/cmd/cd.go deleted file mode 100644 index b57eb555c46..00000000000 --- a/cmd/cd.go +++ /dev/null @@ -1,37 +0,0 @@ -package cmd - -import ( - "github.com/spf13/cobra" - "github.com/twpayne/go-shell" -) - -var cdCmd = &cobra.Command{ - Use: "cd", - Args: cobra.NoArgs, - Short: "Launch a shell in the source directory", - Long: mustGetLongHelp("cd"), - Example: getExample("cd"), - PreRunE: config.ensureNoError, - RunE: config.runCDCmd, -} - -type cdCmdConfig struct { - Command string - Args []string -} - -func init() { - rootCmd.AddCommand(cdCmd) -} - -func (c *Config) runCDCmd(cmd *cobra.Command, args []string) error { - if err := c.ensureSourceDirectory(); err != nil { - return err - } - - shellCommand := c.CD.Command - if shellCommand == "" { - shellCommand, _ = shell.CurrentUserShell() - } - return c.run(c.SourceDir, shellCommand, c.CD.Args...) -} diff --git a/chezmoi2/cmd/cdcmd.go b/cmd/cdcmd.go similarity index 100% rename from chezmoi2/cmd/cdcmd.go rename to cmd/cdcmd.go diff --git a/cmd/chattr.go b/cmd/chattr.go deleted file mode 100644 index 8daff6abb73..00000000000 --- a/cmd/chattr.go +++ /dev/null @@ -1,215 +0,0 @@ -package cmd - -import ( - "fmt" - "os" - "path/filepath" - "sort" - "strings" - - "github.com/spf13/cobra" - - "github.com/twpayne/chezmoi/internal/chezmoi" -) - -var chattrCmd = &cobra.Command{ - Use: "chattr attributes targets...", - Args: cobra.MinimumNArgs(2), - Short: "Change the attributes of a target in the source state", - Long: mustGetLongHelp("chattr"), - Example: getExample("chattr"), - PreRunE: config.ensureNoError, - RunE: config.runChattrCmd, - PostRunE: config.autoCommitAndAutoPush, -} - -type boolModifier int - -type attributeModifiers struct { - empty boolModifier - encrypted boolModifier - exact boolModifier - executable boolModifier - private boolModifier - template boolModifier -} - -func init() { - rootCmd.AddCommand(chattrCmd) - - attributes := []string{ - "empty", "e", - "encrypted", - "exact", - "executable", "x", - "private", "p", - "template", "t", - } - words := make([]string, 0, 4*len(attributes)) - for _, attribute := range attributes { - words = append(words, attribute, "-"+attribute, "+"+attribute, "no"+attribute) - } - panicOnError(chattrCmd.MarkZshCompPositionalArgumentWords(1, words...)) - markRemainingZshCompPositionalArgumentsAsFiles(chattrCmd, 2) -} - -func (c *Config) runChattrCmd(cmd *cobra.Command, args []string) error { - ams, err := parseAttributeModifiers(args[0]) - if err != nil { - return err - } - - ts, err := c.getTargetState(nil) - if err != nil { - return err - } - - entries, err := c.getEntries(ts, args[1:]) - if err != nil { - return err - } - - updates := make(map[string]func() error) - for _, entry := range entries { - dir, oldBase := filepath.Split(entry.SourceName()) - oldpath := filepath.Join(ts.SourceDir, dir, oldBase) - switch entry := entry.(type) { - case *chezmoi.Dir: - da := chezmoi.ParseDirAttributes(oldBase) - da.Exact = ams.exact.modify(entry.Exact) - perm := os.FileMode(0o777) - if private := ams.private.modify(entry.Private()); private { - perm &= 0o700 - } - da.Perm = perm - newBase := da.SourceName() - if newBase != oldBase { - newpath := filepath.Join(ts.SourceDir, dir, newBase) - updates[oldpath] = func() error { - return c.mutator.Rename(oldpath, newpath) - } - } - case *chezmoi.File: - fa := chezmoi.ParseFileAttributes(oldBase) - mode := os.FileMode(0o666) - if executable := ams.executable.modify(entry.Executable()); executable { - mode |= 0o111 - } - if private := ams.private.modify(entry.Private()); private { - mode &= 0o700 - } - fa.Mode = mode - fa.Encrypted = ams.encrypted.modify(entry.Encrypted) - fa.Empty = ams.empty.modify(entry.Empty) - fa.Template = ams.template.modify(entry.Template) - newpath := filepath.Join(ts.SourceDir, dir, fa.SourceName()) - if fa.Encrypted != entry.Encrypted { - oldContents, err := c.fs.ReadFile(filepath.Join(c.SourceDir, entry.SourceName())) - if err != nil { - return err - } - var newContents []byte - if fa.Encrypted { - newContents, err = ts.GPG.Encrypt(entry.TargetName(), oldContents) - } else { - newContents, err = ts.GPG.Decrypt(entry.TargetName(), oldContents) - } - if err != nil { - return err - } - updates[oldpath] = func() error { - // FIXME replace file and contents atomically, see - // https://github.com/google/renameio/issues/16. - if err := c.mutator.WriteFile(newpath, newContents, 0o644, oldContents); err != nil { - return err - } - return c.mutator.RemoveAll(oldpath) - } - } else if newpath != oldpath { - updates[oldpath] = func() error { - return c.mutator.Rename(oldpath, newpath) - } - } - case *chezmoi.Symlink: - fa := chezmoi.ParseFileAttributes(oldBase) - fa.Template = ams.template.modify(entry.Template) - newBase := fa.SourceName() - if newBase != oldBase { - newpath := filepath.Join(ts.SourceDir, dir, newBase) - updates[oldpath] = func() error { - return c.mutator.Rename(oldpath, newpath) - } - } - } - } - - // Sort oldpaths in reverse so we update files before their parent - // directories. - oldpaths := make([]string, 0, len(updates)) - for oldpath := range updates { - oldpaths = append(oldpaths, oldpath) - } - sort.Sort(sort.Reverse(sort.StringSlice(oldpaths))) - - // Apply all updates. - for _, oldpath := range oldpaths { - if err := updates[oldpath](); err != nil { - return err - } - } - return nil -} - -func parseAttributeModifiers(s string) (*attributeModifiers, error) { - ams := &attributeModifiers{} - for _, attributeModifier := range strings.Split(s, ",") { - attributeModifier = strings.TrimSpace(attributeModifier) - if attributeModifier == "" { - continue - } - var modifier boolModifier - var attribute string - switch { - case attributeModifier[0] == '-': - modifier = boolModifier(-1) - attribute = attributeModifier[1:] - case attributeModifier[0] == '+': - modifier = boolModifier(1) - attribute = attributeModifier[1:] - case strings.HasPrefix(attributeModifier, "no"): - modifier = boolModifier(-1) - attribute = attributeModifier[2:] - default: - modifier = boolModifier(1) - attribute = attributeModifier - } - switch attribute { - case "empty", "e": - ams.empty = modifier - case "encrypted": - ams.encrypted = modifier - case "exact": - ams.exact = modifier - case "executable", "x": - ams.executable = modifier - case "private", "p": - ams.private = modifier - case "template", "t": - ams.template = modifier - default: - return nil, fmt.Errorf("%s: unknown attribute", attribute) - } - } - return ams, nil -} - -func (bm boolModifier) modify(x bool) bool { - switch { - case bm < 0: - return false - case bm > 0: - return true - default: - return x - } -} diff --git a/cmd/chattr_test.go b/cmd/chattr_test.go deleted file mode 100644 index f98c2a970f5..00000000000 --- a/cmd/chattr_test.go +++ /dev/null @@ -1,353 +0,0 @@ -package cmd - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/twpayne/go-vfs/vfst" -) - -func TestChattrCommand(t *testing.T) { - for _, tc := range []struct { - name string - args []string - root interface{} - tests interface{} - }{ - { - name: "dir_add_exact", - args: []string{"+exact", "/home/user/dir"}, - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi": map[string]interface{}{ - "dir": &vfst.Dir{Perm: 0o755}, - }, - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/dir", - vfst.TestDoesNotExist, - ), - vfst.TestPath("/home/user/.local/share/chezmoi/exact_dir", - vfst.TestIsDir, - ), - }, - }, - { - name: "dir_remove_exact", - args: []string{"-exact", "/home/user/dir"}, - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi": map[string]interface{}{ - "exact_dir": &vfst.Dir{Perm: 0o755}, - }, - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/exact_dir", - vfst.TestDoesNotExist, - ), - vfst.TestPath("/home/user/.local/share/chezmoi/dir", - vfst.TestIsDir, - ), - }, - }, - { - name: "dir_add_private", - args: []string{"+private", "/home/user/dir"}, - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi": map[string]interface{}{ - "dir": &vfst.Dir{Perm: 0o755}, - }, - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/dir", - vfst.TestDoesNotExist, - ), - vfst.TestPath("/home/user/.local/share/chezmoi/private_dir", - vfst.TestIsDir, - ), - }, - }, - { - name: "dir_remove_private", - args: []string{"-private", "/home/user/dir"}, - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi": map[string]interface{}{ - "private_dir": &vfst.Dir{Perm: 0o755}, - }, - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/private_dir", - vfst.TestDoesNotExist, - ), - vfst.TestPath("/home/user/.local/share/chezmoi/dir", - vfst.TestIsDir, - ), - }, - }, - { - name: "file_add_empty", - args: []string{"+empty", "/home/user/foo"}, - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi": map[string]interface{}{ - "foo": "# contents of ~/foo\n", - }, - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/foo", - vfst.TestDoesNotExist, - ), - vfst.TestPath("/home/user/.local/share/chezmoi/empty_foo", - vfst.TestModeIsRegular, - vfst.TestContentsString("# contents of ~/foo\n"), - ), - }, - }, - { - name: "file_remove_empty", - args: []string{"-empty", "/home/user/foo"}, - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi": map[string]interface{}{ - "empty_foo": "# contents of ~/foo\n", - }, - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/foo", - vfst.TestModeIsRegular, - vfst.TestContentsString("# contents of ~/foo\n"), - ), - vfst.TestPath("/home/user/.local/share/chezmoi/empty_foo", - vfst.TestDoesNotExist, - ), - }, - }, - { - name: "file_add_executable", - args: []string{"+executable", "/home/user/foo"}, - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi": map[string]interface{}{ - "foo": "# contents of ~/foo\n", - }, - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/foo", - vfst.TestDoesNotExist, - ), - vfst.TestPath("/home/user/.local/share/chezmoi/executable_foo", - vfst.TestModeIsRegular, - vfst.TestContentsString("# contents of ~/foo\n"), - ), - }, - }, - { - name: "file_remove_executable", - args: []string{"-executable", "/home/user/foo"}, - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi": map[string]interface{}{ - "executable_foo": "# contents of ~/foo\n", - }, - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/foo", - vfst.TestModeIsRegular, - vfst.TestContentsString("# contents of ~/foo\n"), - ), - vfst.TestPath("/home/user/.local/share/chezmoi/executable_foo", - vfst.TestDoesNotExist, - ), - }, - }, - { - name: "file_add_private", - args: []string{"+private", "/home/user/foo"}, - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi": map[string]interface{}{ - "foo": "# contents of ~/foo\n", - }, - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/foo", - vfst.TestDoesNotExist, - ), - vfst.TestPath("/home/user/.local/share/chezmoi/private_foo", - vfst.TestModeIsRegular, - vfst.TestContentsString("# contents of ~/foo\n"), - ), - }, - }, - { - name: "file_remove_private", - args: []string{"-private", "/home/user/foo"}, - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi": map[string]interface{}{ - "private_foo": "# contents of ~/foo\n", - }, - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/foo", - vfst.TestModeIsRegular, - vfst.TestContentsString("# contents of ~/foo\n"), - ), - vfst.TestPath("/home/user/.local/share/chezmoi/private_foo", - vfst.TestDoesNotExist, - ), - }, - }, - { - name: "file_add_template", - args: []string{"+template", "/home/user/foo"}, - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi": map[string]interface{}{ - "foo": "# contents of ~/foo\n", - }, - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/foo", - vfst.TestDoesNotExist, - ), - vfst.TestPath("/home/user/.local/share/chezmoi/foo.tmpl", - vfst.TestModeIsRegular, - vfst.TestContentsString("# contents of ~/foo\n"), - ), - }, - }, - { - name: "file_remove_template", - args: []string{"-template", "/home/user/foo"}, - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi": map[string]interface{}{ - "foo.tmpl": "# contents of ~/foo\n", - }, - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/foo", - vfst.TestModeIsRegular, - vfst.TestContentsString("# contents of ~/foo\n"), - ), - vfst.TestPath("/home/user/.local/share/chezmoi/foo.tmpl", - vfst.TestDoesNotExist, - ), - }, - }, - { - name: "file_add_template_in_private_dir", - args: []string{"+template", "/home/user/.ssh/authorized_keys"}, - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi": map[string]interface{}{ - "private_dot_ssh": map[string]interface{}{ - "authorized_keys": "# contents of ~/.ssh/authorized_keys\n", - }, - }, - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/private_dot_ssh/authorized_keys", - vfst.TestDoesNotExist, - ), - vfst.TestPath("/home/user/.local/share/chezmoi/private_dot_ssh/authorized_keys.tmpl", - vfst.TestModeIsRegular, - vfst.TestContentsString("# contents of ~/.ssh/authorized_keys\n"), - ), - }, - }, - { - name: "symlink_add_template", - args: []string{"+template", "/home/user/foo"}, - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi": map[string]interface{}{ - "symlink_foo": "# contents of ~/foo\n", - }, - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/symlink_foo", - vfst.TestDoesNotExist, - ), - vfst.TestPath("/home/user/.local/share/chezmoi/symlink_foo.tmpl", - vfst.TestModeIsRegular, - vfst.TestContentsString("# contents of ~/foo\n"), - ), - }, - }, - { - name: "symlink_remove_template", - args: []string{"-template", "/home/user/foo"}, - root: map[string]interface{}{ - "/home/user/.local/share/chezmoi": map[string]interface{}{ - "symlink_foo.tmpl": "# contents of ~/foo\n", - }, - }, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.local/share/chezmoi/symlink_foo", - vfst.TestModeIsRegular, - vfst.TestContentsString("# contents of ~/foo\n"), - ), - vfst.TestPath("/home/user/.local/share/chezmoi/symlink_foo.tmpl", - vfst.TestDoesNotExist, - ), - }, - }, - } { - t.Run(tc.name, func(t *testing.T) { - fs, cleanup, err := vfst.NewTestFS(tc.root) - require.NoError(t, err) - defer cleanup() - c := newTestConfig(fs) - assert.NoError(t, c.runChattrCmd(nil, tc.args)) - vfst.RunTests(t, fs, "", tc.tests) - }) - } -} - -func TestParseAttributeModifiers(t *testing.T) { - for _, tc := range []struct { - s string - want *attributeModifiers - wantErr bool - }{ - {s: "empty", want: &attributeModifiers{empty: 1}}, - {s: "+empty", want: &attributeModifiers{empty: 1}}, - {s: "-empty", want: &attributeModifiers{empty: -1}}, - {s: "noempty", want: &attributeModifiers{empty: -1}}, - {s: "e", want: &attributeModifiers{empty: 1}}, - {s: "+e", want: &attributeModifiers{empty: 1}}, - {s: "-e", want: &attributeModifiers{empty: -1}}, - {s: "noe", want: &attributeModifiers{empty: -1}}, - {s: "executable", want: &attributeModifiers{executable: 1}}, - {s: "+executable", want: &attributeModifiers{executable: 1}}, - {s: "-executable", want: &attributeModifiers{executable: -1}}, - {s: "noexecutable", want: &attributeModifiers{executable: -1}}, - {s: "x", want: &attributeModifiers{executable: 1}}, - {s: "+x", want: &attributeModifiers{executable: 1}}, - {s: "-x", want: &attributeModifiers{executable: -1}}, - {s: "nox", want: &attributeModifiers{executable: -1}}, - {s: "private", want: &attributeModifiers{private: 1}}, - {s: "+private", want: &attributeModifiers{private: 1}}, - {s: "-private", want: &attributeModifiers{private: -1}}, - {s: "noprivate", want: &attributeModifiers{private: -1}}, - {s: "p", want: &attributeModifiers{private: 1}}, - {s: "+p", want: &attributeModifiers{private: 1}}, - {s: "-p", want: &attributeModifiers{private: -1}}, - {s: "nop", want: &attributeModifiers{private: -1}}, - {s: "template", want: &attributeModifiers{template: 1}}, - {s: "+template", want: &attributeModifiers{template: 1}}, - {s: "-template", want: &attributeModifiers{template: -1}}, - {s: "notemplate", want: &attributeModifiers{template: -1}}, - {s: "t", want: &attributeModifiers{template: 1}}, - {s: "+t", want: &attributeModifiers{template: 1}}, - {s: "-t", want: &attributeModifiers{template: -1}}, - {s: "not", want: &attributeModifiers{template: -1}}, - {s: "empty,executable,private,template", want: &attributeModifiers{empty: 1, executable: 1, private: 1, template: 1}}, - {s: "+empty,+executable,+private,+template", want: &attributeModifiers{empty: 1, executable: 1, private: 1, template: 1}}, - {s: "-empty,-executable,-private,-template", want: &attributeModifiers{empty: -1, executable: -1, private: -1, template: -1}}, - {s: "foo", wantErr: true}, - {s: "empty,foo", wantErr: true}, - {s: "empty,foo", wantErr: true}, - {s: " empty , -private, notemplate ", want: &attributeModifiers{empty: 1, private: -1, template: -1}}, - {s: "empty,,-private", want: &attributeModifiers{empty: 1, private: -1}}, - } { - got, gotErr := parseAttributeModifiers(tc.s) - if tc.wantErr { - assert.Error(t, gotErr) - } else { - assert.NoError(t, gotErr) - assert.Equal(t, tc.want, got) - } - } -} diff --git a/chezmoi2/cmd/chattrcmd.go b/cmd/chattrcmd.go similarity index 99% rename from chezmoi2/cmd/chattrcmd.go rename to cmd/chattrcmd.go index 7433eb83f5a..9e5f24da33c 100644 --- a/chezmoi2/cmd/chattrcmd.go +++ b/cmd/chattrcmd.go @@ -7,7 +7,7 @@ import ( "github.com/spf13/cobra" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoi" ) type boolModifier int diff --git a/chezmoi2/cmd/chattrcmd_test.go b/cmd/chattrcmd_test.go similarity index 100% rename from chezmoi2/cmd/chattrcmd_test.go rename to cmd/chattrcmd_test.go diff --git a/internal/cmd/generate-helps/main.go b/cmd/cmd.go similarity index 52% rename from internal/cmd/generate-helps/main.go rename to cmd/cmd.go index 07a50cf86f4..cdd0423a65a 100644 --- a/internal/cmd/generate-helps/main.go +++ b/cmd/cmd.go @@ -1,22 +1,45 @@ -package main +// Package cmd contains chezmoi's commands. +package cmd import ( "bufio" - "flag" + "bytes" + "errors" "fmt" - "go/format" "io" "os" "regexp" + "strconv" "strings" - "text/template" "github.com/charmbracelet/glamour" + "github.com/spf13/cobra" + + "github.com/twpayne/chezmoi/docs" +) + +// Command annotations. +const ( + doesNotRequireValidConfig = "chezmoi_does_not_require_valid_config" + modifiesConfigFile = "chezmoi_modifies_config_file" + modifiesDestinationDirectory = "chezmoi_modifies_destination_directory" + modifiesSourceDirectory = "chezmoi_modifies_source_directory" + persistentStateMode = "chezmoi_persistent_state_mode" + requiresConfigDirectory = "chezmoi_requires_config_directory" + requiresSourceDirectory = "chezmoi_requires_source_directory" + runsCommands = "chezmoi_runs_commands" +) + +// Persistent state modes. +const ( + persistentStateModeEmpty = "empty" + persistentStateModeReadOnly = "read-only" + persistentStateModeReadMockWrite = "read-mock-write" + persistentStateModeReadWrite = "read-write" ) var ( - inputFile = flag.String("i", "", "input file") - outputFile = flag.String("o", "", "output file") + noArgs = []string(nil) commandsRegexp = regexp.MustCompile(`^## Commands`) commandRegexp = regexp.MustCompile("^### `(\\S+)`") @@ -24,53 +47,70 @@ var ( endOfCommandsRegexp = regexp.MustCompile(`^## `) trailingSpaceRegexp = regexp.MustCompile(` +\n`) - funcs = template.FuncMap{ - "printMultiLineString": printMultiLineString, - } + helps map[string]*help +) - outputTemplate = template.Must(template.New("output").Funcs(funcs).Parse(`// Code generated by github.com/twpayne/chezmoi/internal/cmd/generate-helps. DO NOT EDIT. +// An ErrExitCode indicates the the main program should exit with the given +// code. +type ErrExitCode int -package cmd +func (e ErrExitCode) Error() string { return "" } + +// A VersionInfo contains a version. +type VersionInfo struct { + Version string + Commit string + Date string + BuiltBy string +} type help struct { long string example string } -var helps = map[string]help{ -{{- range $command, $help := .Helps }} - "{{ $command }}": { - long: {{ printMultiLineString $help.Long "\t\t\t" }}, -{{- if $help.Example }} - example: {{ printMultiLineString $help.Example "\t\t\t" }}, -{{- end }} - }, -{{- end }} +func init() { + reference, err := docs.FS.ReadFile("REFERENCE.md") + if err != nil { + panic(err) + } + helps, err = extractHelps(bytes.NewReader(reference)) + if err != nil { + panic(err) + } } -`)) -) -type help struct { - Long string - Example string +// Main runs chezmoi and returns an exit code. +func Main(versionInfo VersionInfo, args []string) int { + if err := runMain(versionInfo, args); err != nil { + if s := err.Error(); s != "" { + fmt.Fprintf(os.Stderr, "chezmoi: %s\n", s) + } + errExitCode := ErrExitCode(1) + _ = errors.As(err, &errExitCode) + return int(errExitCode) + } + return 0 } -func printMultiLineString(s, indent string) string { - if len(s) == 0 { - return `""` +func boolAnnotation(cmd *cobra.Command, key string) bool { + value, ok := cmd.Annotations[key] + if !ok { + return false } - b := &strings.Builder{} - b.WriteString("\"\" +\n" + indent) - for i, line := range strings.SplitAfter(s, "\n") { - if line == "" { - continue - } - if i != 0 { - b.WriteString(" +\n" + indent) - } - fmt.Fprintf(b, "%q", line) + boolValue, err := strconv.ParseBool(value) + if err != nil { + panic(err) + } + return boolValue +} + +func example(command string) string { + help, ok := helps[command] + if !ok { + return "" } - return b.String() + return help.example } func extractHelps(r io.Reader) (map[string]*help, error) { @@ -118,9 +158,9 @@ func extractHelps(r io.Reader) (map[string]*help, error) { s = strings.Trim(s, "\n") switch state { case "in-command": - h.Long = "Description:\n" + s + h.long = "Description:\n" + s case "in-example": - h.Example = s + h.example = s default: panic(fmt.Sprintf("%s: invalid state", state)) } @@ -179,64 +219,28 @@ FOR: return helps, nil } -func run() error { - flag.Parse() - - var r io.Reader - if *inputFile == "" { - r = os.Stdin - } else { - fr, err := os.Open(*inputFile) - if err != nil { - return err +func markPersistentFlagsRequired(cmd *cobra.Command, flags ...string) { + for _, flag := range flags { + if err := cmd.MarkPersistentFlagRequired(flag); err != nil { + panic(err) } - defer fr.Close() - r = fr - } - - helps, err := extractHelps(r) - if err != nil { - return err - } - - data := struct { - Helps map[string]*help - InputFile string - OutputFile string - }{ - Helps: helps, - InputFile: *inputFile, - OutputFile: *outputFile, - } - sb := &strings.Builder{} - if err := outputTemplate.ExecuteTemplate(sb, "output", data); err != nil { - return err } +} - var w io.Writer - if *outputFile == "" { - w = os.Stdout - } else { - fw, err := os.Create(*outputFile) - if err != nil { - return err - } - defer fw.Close() - w = fw +func mustLongHelp(command string) string { + help, ok := helps[command] + if !ok { + panic(fmt.Sprintf("missing long help for command %s", command)) } + return help.long +} - output, err := format.Source([]byte(sb.String())) +func runMain(versionInfo VersionInfo, args []string) error { + config, err := newConfig( + withVersionInfo(versionInfo), + ) if err != nil { return err } - - _, err = w.Write(output) - return err -} - -func main() { - if err := run(); err != nil { - fmt.Println(err) - os.Exit(1) - } + return config.execute(args) } diff --git a/cmd/cmd_test.go b/cmd/cmd_test.go index 7cf9d93b8db..1ca63da03a5 100644 --- a/cmd/cmd_test.go +++ b/cmd/cmd_test.go @@ -1,112 +1,23 @@ package cmd import ( - "os" - "runtime" "testing" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/twpayne/go-vfs/vfst" -) - -// TestExercise exercises a few commands. -func TestExercise(t *testing.T) { - fs, cleanup, err := vfst.NewTestFS(map[string]interface{}{ - "/home/user/.bashrc": "# contents of .bashrc\n", - }) - require.NoError(t, err) - defer cleanup() - - c := newTestConfig( - fs, - withRemoveCmdConfig(removeCmdConfig{ - force: true, - }), - ) - mustWriteFile := func(name, contents string, mode os.FileMode) { - require.NoError(t, fs.WriteFile(name, []byte(contents), mode)) - } - - // chezmoi add ~/.bashrc - t.Run("chezmoi_add_bashrc", func(t *testing.T) { - assert.NoError(t, c.runAddCmd(nil, []string{"/home/user/.bashrc"})) - vfst.RunTests(t, fs, "", - vfst.TestPath("/home/user/.local/share/chezmoi", - vfst.TestIsDir, - vfst.TestModePerm(0o700), - ), - vfst.TestPath("/home/user/.local/share/chezmoi/dot_bashrc", - vfst.TestModeIsRegular, - vfst.TestModePerm(0o644), - vfst.TestContentsString("# contents of .bashrc\n"), - ), - ) - }) - - // chezmoi forget ~/.bashrc - t.Run("chezmoi_forget_bashrc", func(t *testing.T) { - assert.NoError(t, c.runForgetCmd(nil, []string{"/home/user/.bashrc"})) - vfst.RunTests(t, fs, "", - vfst.TestPath("/home/user/.local/share/chezmoi/dot_bashrc", - vfst.TestDoesNotExist, - ), - ) - }) - - // chezmoi add ~/.netrc - t.Run("chezmoi_add_netrc", func(t *testing.T) { - mustWriteFile("/home/user/.netrc", "# contents of .netrc\n", 0o600) - assert.NoError(t, c.runAddCmd(nil, []string{"/home/user/.netrc"})) - path := "/home/user/.local/share/chezmoi/private_dot_netrc" - // Private files are not supported on Windows. - if runtime.GOOS == "windows" { - path = "/home/user/.local/share/chezmoi/dot_netrc" - } - vfst.RunTests(t, fs, "", - vfst.TestPath(path, - vfst.TestModeIsRegular, - vfst.TestModePerm(0o644), - vfst.TestContentsString("# contents of .netrc\n"), - ), - ) - }) - - // chezmoi chattr -- -private,+empty ~/.netrc - t.Run("chezmoi_chattr_netrc", func(t *testing.T) { - assert.NoError(t, c.runChattrCmd(nil, []string{"-private,+empty", "/home/user/.netrc"})) - vfst.RunTests(t, fs, "", - vfst.TestPath("/home/user/.local/share/chezmoi/empty_dot_netrc", - vfst.TestModeIsRegular, - vfst.TestModePerm(0o644), - vfst.TestContentsString("# contents of .netrc\n"), - ), - ) - }) + "github.com/twpayne/chezmoi/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoitest" +) - // chezmoi apply ~/.netrc - t.Run("chezmoi_apply_netrc", func(t *testing.T) { - assert.NoError(t, c.runApplyCmd(nil, []string{"/home/user/.netrc"})) - vfst.RunTests(t, fs, "", - vfst.TestPath("/home/user/.netrc", - vfst.TestModeIsRegular, - vfst.TestModePerm(0o644), - vfst.TestContentsString("# contents of .netrc\n"), - ), - ) - }) +func init() { + // github.com/twpayne/chezmoi/internal/chezmoi reads the umask + // before github.com/twpayne/chezmoi/internal/chezmoitest sets it, + // so update it. + chezmoi.Umask = chezmoitest.Umask +} - // chezmoi remove ~/.netrc - t.Run("chezmoi_remove_netrc", func(t *testing.T) { - assert.NoError(t, c.runRemoveCmd(nil, []string{"/home/user/.netrc"})) - vfst.RunTests(t, fs, "", - vfst.TestPath("/home/user/.netrc", - vfst.TestDoesNotExist, - ), - vfst.TestPath("/home/user/.local/share/chezmoi/empty_dot_netrc", - vfst.TestDoesNotExist, - ), - ) +func TestMustGetLongHelpPanics(t *testing.T) { + assert.Panics(t, func() { + mustLongHelp("non-existent-command") }) } diff --git a/cmd/completion.go b/cmd/completion.go deleted file mode 100644 index 25bc466d525..00000000000 --- a/cmd/completion.go +++ /dev/null @@ -1,60 +0,0 @@ -package cmd - -import ( - "errors" - "strings" - - "github.com/spf13/cobra" -) - -type completionCmdConfig struct { - output string -} - -var completionCmd = &cobra.Command{ - Use: "completion shell", - Args: cobra.ExactArgs(1), - Short: "Generate shell completion code for the specified shell (bash, fish, or zsh)", - Long: mustGetLongHelp("completion"), - Example: getExample("completion"), - ValidArgs: []string{"bash", "fish", "powershell", "zsh"}, - RunE: config.runCompletion, -} - -func init() { - rootCmd.AddCommand(completionCmd) - - persistentFlags := completionCmd.PersistentFlags() - persistentFlags.StringVarP(&config.completion.output, "output", "o", "", "output filename") - panicOnError(completionCmd.MarkPersistentFlagFilename("output")) -} - -func (c *Config) runCompletion(cmd *cobra.Command, args []string) error { - output := &strings.Builder{} - switch args[0] { - case "bash": - if err := rootCmd.GenBashCompletion(output); err != nil { - return err - } - case "fish": - if err := rootCmd.GenFishCompletion(output, true); err != nil { - return err - } - case "powershell": - if err := rootCmd.GenPowerShellCompletion(output); err != nil { - return err - } - case "zsh": - if err := rootCmd.GenZshCompletion(output); err != nil { - return err - } - default: - return errors.New("unsupported shell") - } - - if c.completion.output == "" { - _, err := c.Stdout.Write([]byte(output.String())) - return err - } - return c.fs.WriteFile(c.completion.output, []byte(output.String()), 0o666) -} diff --git a/chezmoi2/cmd/completioncmd.go b/cmd/completioncmd.go similarity index 100% rename from chezmoi2/cmd/completioncmd.go rename to cmd/completioncmd.go diff --git a/cmd/config.go b/cmd/config.go index 39b7eed470e..7bfc07e2b1b 100644 --- a/cmd/config.go +++ b/cmd/config.go @@ -1,7 +1,7 @@ package cmd import ( - "bufio" + "bytes" "encoding/json" "errors" "fmt" @@ -9,9 +9,10 @@ import ( "os" "os/exec" "os/user" - "path/filepath" "regexp" "runtime" + "runtime/pprof" + "sort" "strings" "text/template" "time" @@ -19,316 +20,485 @@ import ( "github.com/Masterminds/sprig/v3" "github.com/coreos/go-semver/semver" - "github.com/pelletier/go-toml" + "github.com/go-git/go-git/v5/plumbing/format/diff" + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" "github.com/spf13/cobra" "github.com/spf13/viper" - vfs "github.com/twpayne/go-vfs" - xdg "github.com/twpayne/go-xdg/v3" - bolt "go.etcd.io/bbolt" - yaml "gopkg.in/yaml.v2" + "github.com/twpayne/go-shell" + "github.com/twpayne/go-vfs/v2" + vfsafero "github.com/twpayne/go-vfsafero/v2" + "github.com/twpayne/go-xdg/v3" + "golang.org/x/term" + "github.com/twpayne/chezmoi/assets/templates" "github.com/twpayne/chezmoi/internal/chezmoi" "github.com/twpayne/chezmoi/internal/git" ) -const commitMessageTemplateAsset = "assets/templates/COMMIT_MESSAGE.tmpl" +var defaultFormat = "json" -var whitespaceRegexp = regexp.MustCompile(`\s+`) - -type sourceVCSConfig struct { - Command string - AutoCommit bool - AutoPush bool - Init interface{} - NotGit bool - Pull interface{} +type purgeOptions struct { + binary bool } type templateConfig struct { - Options []string + Options []string `mapstructure:"options"` } // A Config represents a configuration. type Config struct { - configFile string - err error - fs vfs.FS - mutator chezmoi.Mutator - SourceDir string - DestDir string - Umask permValue - DryRun bool - Follow bool - Remove bool - Verbose bool - Color string - Debug bool - GPG chezmoi.GPG - GPGRecipient string - SourceVCS sourceVCSConfig - Template templateConfig - Merge mergeConfig - Bitwarden bitwardenCmdConfig - CD cdCmdConfig - Diff diffCmdConfig - GenericSecret genericSecretCmdConfig - Gopass gopassCmdConfig - KeePassXC keePassXCCmdConfig - Lastpass lastpassCmdConfig - Onepassword onepasswordCmdConfig - Vault vaultCmdConfig - Pass passCmdConfig - Data map[string]interface{} - colored bool - maxDiffDataSize int - templateFuncs template.FuncMap - add addCmdConfig - archive archiveCmdConfig - completion completionCmdConfig - data dataCmdConfig - dump dumpCmdConfig - edit editCmdConfig - executeTemplate executeTemplateCmdConfig - _import importCmdConfig - init initCmdConfig - keyring keyringCmdConfig - managed managedCmdConfig - purge purgeCmdConfig - remove removeCmdConfig - update updateCmdConfig - upgrade upgradeCmdConfig - Stdin io.Reader - Stdout io.Writer - Stderr io.Writer - bds *xdg.BaseDirectorySpecification - scriptStateBucket []byte - - //nolint:structcheck,unused + version *semver.Version + versionInfo VersionInfo + versionStr string + + bds *xdg.BaseDirectorySpecification + + fs vfs.FS + configFile string + baseSystem chezmoi.System + sourceSystem chezmoi.System + destSystem chezmoi.System + persistentState chezmoi.PersistentState + color bool + + // Global configuration, settable in the config file. + SourceDir string `mapstructure:"sourceDir"` + DestDir string `mapstructure:"destDir"` + Umask os.FileMode `mapstructure:"umask"` + Remove bool `mapstructure:"remove"` + Color string `mapstructure:"color"` + Data map[string]interface{} `mapstructure:"data"` + Template templateConfig `mapstructure:"template"` + UseBuiltinGit string `mapstructure:"useBuiltinGit"` + + // Global configuration, not settable in the config file. + cpuProfile string + debug bool + dryRun bool + exclude *chezmoi.EntryTypeSet + force bool + homeDir string + keepGoing bool + noPager bool + noTTY bool + outputStr string + sourcePath bool + verbose 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. + CD cdCmdConfig `mapstructure:"cd"` + Diff diffCmdConfig `mapstructure:"diff"` + Edit editCmdConfig `mapstructure:"edit"` + Git gitCmdConfig `mapstructure:"git"` + Merge mergeCmdConfig `mapstructure:"merge"` + + // Command configurations, not settable in the config file. + add addCmdConfig + apply applyCmdConfig + archive archiveCmdConfig + data dataCmdConfig + dump dumpCmdConfig + executeTemplate executeTemplateCmdConfig + _import importCmdConfig + init initCmdConfig + managed managedCmdConfig + purge purgeCmdConfig + secretKeyring secretKeyringCmdConfig + state stateCmdConfig + status statusCmdConfig + update updateCmdConfig + verify verifyCmdConfig + + // Computed configuration. + configFileAbsPath chezmoi.AbsPath + homeDirAbsPath chezmoi.AbsPath + sourceDirAbsPath chezmoi.AbsPath + destDirAbsPath chezmoi.AbsPath + encryption chezmoi.Encryption + + stdin io.Reader + stdout io.Writer + stderr io.Writer + ioregData ioregData } -// A configOption sets an option on a Config. -type configOption func(*Config) +// A configOption sets and option on a Config. +type configOption func(*Config) error -var ( - formatMap = map[string]func(io.Writer, interface{}) error{ - "json": func(w io.Writer, value interface{}) error { - e := json.NewEncoder(w) - e.SetIndent("", " ") - return e.Encode(value) - }, - "toml": func(w io.Writer, value interface{}) error { - return toml.NewEncoder(w).Encode(value) - }, - "yaml": func(w io.Writer, value interface{}) error { - return yaml.NewEncoder(w).Encode(value) - }, - } - - wellKnownAbbreviations = map[string]struct{}{ - "ANSI": {}, - "CPE": {}, - "ID": {}, - "URL": {}, - } +type configState struct { + ConfigTemplateContentsSHA256 chezmoi.HexBytes `json:"configTemplateContentsSHA256" yaml:"configTemplateContentsSHA256"` +} - identifierRegexp = regexp.MustCompile(`\A[\pL_][\pL\p{Nd}_]*\z`) +var ( + persistentStateFilename = chezmoi.RelPath("chezmoistate.boltdb") + configStateKey = []byte("configState") - assets = make(map[string][]byte) + identifierRx = regexp.MustCompile(`\A[\pL_][\pL\p{Nd}_]*\z`) + whitespaceRx = regexp.MustCompile(`\s+`) ) // newConfig creates a new Config with the given options. -func newConfig(options ...configOption) *Config { +func newConfig(options ...configOption) (*Config, error) { + homeDir, err := os.UserHomeDir() + if err != nil { + return nil, err + } + normalizedHomeDir, err := chezmoi.NormalizePath(homeDir) + if err != nil { + return nil, err + } + + bds, err := xdg.NewBaseDirectorySpecification() + if err != nil { + return nil, err + } + c := &Config{ - Umask: permValue(chezmoi.GetUmask()), - Color: "auto", - SourceVCS: sourceVCSConfig{ + bds: bds, + fs: vfs.OSFS, + homeDir: homeDir, + DestDir: homeDir, + Umask: chezmoi.Umask, + Color: "auto", + Diff: diffCmdConfig{ + Pager: firstNonEmptyString(os.Getenv("PAGER"), "less"), + include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll &^ chezmoi.EntryTypeScripts), + }, + Edit: editCmdConfig{ + include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypeDirs | chezmoi.EntryTypeFiles | chezmoi.EntryTypeSymlinks | chezmoi.EntryTypeEncrypted), + }, + Git: gitCmdConfig{ Command: "git", }, + Merge: mergeCmdConfig{ + Command: "vimdiff", + }, Template: templateConfig{ Options: chezmoi.DefaultTemplateOptions, }, - Diff: diffCmdConfig{ - Format: "chezmoi", + templateFuncs: sprig.TxtFuncMap(), + exclude: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesNone), + Bitwarden: bitwardenConfig{ + Command: "bw", }, - Merge: mergeConfig{ - Command: "vimdiff", + Gopass: gopassConfig{ + Command: "gopass", + }, + Keepassxc: keepassxcConfig{ + Command: "keepassxc-cli", + }, + Lastpass: lastpassConfig{ + Command: "lpass", + }, + Onepassword: onepasswordConfig{ + Command: "op", + }, + Pass: passConfig{ + Command: "pass", }, - GPG: chezmoi.GPG{ + Vault: vaultConfig{ + Command: "vault", + }, + AGE: chezmoi.AGEEncryption{ + Command: "age", + Suffix: ".age", + }, + GPG: chezmoi.GPGEncryption{ Command: "gpg", + Suffix: ".asc", + }, + add: addCmdConfig{ + include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll), + recursive: true, + }, + apply: applyCmdConfig{ + include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll), + recursive: true, + }, + archive: archiveCmdConfig{ + include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll), + recursive: true, + }, + data: dataCmdConfig{ + format: defaultFormat, + }, + dump: dumpCmdConfig{ + format: defaultFormat, + include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll), + recursive: true, }, - maxDiffDataSize: 1 * 1024 * 1024, // 1MB - templateFuncs: sprig.TxtFuncMap(), - scriptStateBucket: []byte("script"), - Stdin: os.Stdin, - Stdout: os.Stdout, - Stderr: os.Stderr, + _import: importCmdConfig{ + include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll), + }, + managed: managedCmdConfig{ + include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypeDirs | chezmoi.EntryTypeFiles | chezmoi.EntryTypeSymlinks | chezmoi.EntryTypeEncrypted), + }, + state: stateCmdConfig{ + dump: stateDumpCmdConfig{ + format: defaultFormat, + }, + }, + status: statusCmdConfig{ + include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll), + recursive: true, + }, + update: updateCmdConfig{ + apply: true, + include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll), + recursive: true, + }, + verify: verifyCmdConfig{ + include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll &^ chezmoi.EntryTypeScripts), + recursive: true, + }, + + stdin: os.Stdin, + stdout: os.Stdout, + stderr: os.Stderr, + + homeDirAbsPath: normalizedHomeDir, + } + + for key, value := range map[string]interface{}{ + "bitwarden": c.bitwardenTemplateFunc, + "bitwardenAttachment": c.bitwardenAttachmentTemplateFunc, + "bitwardenFields": c.bitwardenFieldsTemplateFunc, + "gitHubKeys": c.gitHubKeysTemplateFunc, + "gopass": c.gopassTemplateFunc, + "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, + "onepassword": c.onepasswordTemplateFunc, + "onepasswordDetailsFields": c.onepasswordDetailsFieldsTemplateFunc, + "onepasswordDocument": c.onepasswordDocumentTemplateFunc, + "pass": c.passTemplateFunc, + "secret": c.secretTemplateFunc, + "secretJSON": c.secretJSONTemplateFunc, + "stat": c.statTemplateFunc, + "vault": c.vaultTemplateFunc, + } { + c.addTemplateFunc(key, value) } + for _, option := range options { - option(c) + if err := option(c); err != nil { + return nil, err + } } - return c + + c.configFile = string(defaultConfigFile(c.fs, c.bds)) + c.SourceDir = string(defaultSourceDir(c.fs, c.bds)) + + c.homeDirAbsPath, err = chezmoi.NormalizePath(c.homeDir) + if err != nil { + return nil, err + } + c._import.destination = string(c.homeDirAbsPath) + + return c, nil } func (c *Config) addTemplateFunc(key string, value interface{}) { - if c.templateFuncs == nil { - c.templateFuncs = make(template.FuncMap) - } if _, ok := c.templateFuncs[key]; ok { - panic(fmt.Sprintf("Config.addTemplateFunc: %s already defined", key)) + panic(fmt.Sprintf("%s: already defined", key)) } c.templateFuncs[key] = value } -func (c *Config) applyArgs(args []string, persistentState chezmoi.PersistentState) error { - fs := vfs.NewReadOnlyFS(c.fs) - ts, err := c.getTargetState(nil) - if err != nil { - return err - } - applyOptions := &chezmoi.ApplyOptions{ - DestDir: ts.DestDir, - DryRun: c.DryRun, - Ignore: ts.TargetIgnore.Match, - PersistentState: persistentState, - Remove: c.Remove, - ScriptStateBucket: c.scriptStateBucket, - Stdout: c.Stdout, - Umask: ts.Umask, - Verbose: c.Verbose, - } - if len(args) == 0 { - return ts.Apply(fs, c.mutator, c.Follow, applyOptions) - } - entries, err := c.getEntries(ts, args) - if err != nil { - return err - } - for _, entry := range entries { - if err := entry.Apply(fs, c.mutator, c.Follow, applyOptions); err != nil { - return err - } - } - return nil +type applyArgsOptions struct { + include *chezmoi.EntryTypeSet + recursive bool + umask os.FileMode + preApplyFunc chezmoi.PreApplyFunc } -func (c *Config) autoCommit(vcs VCS) error { - addArgs := vcs.AddArgs(".") - if addArgs == nil { - return fmt.Errorf("%s: autocommit not supported", c.SourceVCS.Command) - } - if err := c.run(c.SourceDir, c.SourceVCS.Command, addArgs...); err != nil { - return err - } - output, err := c.output(c.SourceDir, c.SourceVCS.Command, vcs.StatusArgs()...) +func (c *Config) applyArgs(targetSystem chezmoi.System, targetDirAbsPath chezmoi.AbsPath, args []string, options applyArgsOptions) error { + sourceState, err := c.sourceState() if err != nil { return err } - status, err := vcs.ParseStatusOutput(output) + + var currentConfigTemplateContentsSHA256 []byte + configTemplateRelPath, _, configTemplateContents, err := c.findConfigTemplate() if err != nil { return err } - if gitStatus, ok := status.(*git.Status); ok && gitStatus.Empty() { - return nil - } - commitMessageText, err := getAsset(commitMessageTemplateAsset) - if err != nil { - return err + if configTemplateRelPath != "" { + currentConfigTemplateContentsSHA256 = chezmoi.SHA256Sum(configTemplateContents) } - commitMessageTmpl, err := template.New("commit_message").Funcs(c.templateFuncs).Parse(string(commitMessageText)) - if err != nil { + 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) } - sb := &strings.Builder{} - if err := commitMessageTmpl.Execute(sb, status); err != nil { - return err + configTemplateContentsUnchanged := (currentConfigTemplateContentsSHA256 == nil && previousConfigTemplateContentsSHA256 == nil) || + bytes.Equal(currentConfigTemplateContentsSHA256, previousConfigTemplateContentsSHA256) + if !configTemplateContentsUnchanged { + if c.force { + if configTemplateRelPath == "" { + 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") + } } - commitArgs := vcs.CommitArgs(sb.String()) - return c.run(c.SourceDir, c.SourceVCS.Command, commitArgs...) -} -func (c *Config) autoCommitAndAutoPush(cmd *cobra.Command, args []string) error { - vcs, err := c.getVCS() - if err != nil { - return err + applyOptions := chezmoi.ApplyOptions{ + Include: options.include.Sub(c.exclude), + PreApplyFunc: options.preApplyFunc, + Umask: options.umask, } - if c.DryRun { - return nil - } - if c.SourceVCS.AutoCommit || c.SourceVCS.AutoPush { - if err := c.autoCommit(vcs); err != nil { + + 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 } - } - if c.SourceVCS.AutoPush { - if err := c.autoPush(vcs); err != nil { + default: + targetRelPaths, err = c.targetRelPaths(sourceState, args, targetRelPathsOptions{ + mustBeInSourceState: true, + recursive: options.recursive, + }) + if err != nil { return err } } - return nil -} -func (c *Config) autoPush(vcs VCS) error { - pushArgs := vcs.PushArgs() - if pushArgs == nil { - return fmt.Errorf("%s: autopush not supported", c.SourceVCS.Command) + 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", err) + keptGoingAfterErr = true + case err != nil: + return err + } } - return c.run(c.SourceDir, c.SourceVCS.Command, pushArgs...) -} - -// ensureNoError ensures that no error was encountered when loading c. -func (c *Config) ensureNoError(cmd *cobra.Command, args []string) error { - if c.err != nil { - return errors.New("config contains errors, aborting") + if keptGoingAfterErr { + return ErrExitCode(1) } + return nil } -func (c *Config) ensureSourceDirectory() error { - info, err := c.fs.Stat(c.SourceDir) - switch { - case err == nil && info.IsDir(): - private, err := chezmoi.IsPrivate(c.fs, c.SourceDir, true) +func (c *Config) cmdOutput(dirAbsPath chezmoi.AbsPath, name string, args []string) ([]byte, error) { + cmd := exec.Command(name, args...) + if dirAbsPath != "" { + dirRawAbsPath, err := c.baseSystem.RawPath(dirAbsPath) if err != nil { - return err - } - if !private { - if err := c.mutator.Chmod(c.SourceDir, 0o700&^os.FileMode(c.Umask)); err != nil { - return err - } - } - return nil - case os.IsNotExist(err): - if err := vfs.MkdirAll(c.mutator, filepath.Dir(c.SourceDir), 0o777&^os.FileMode(c.Umask)); err != nil { - return err + return nil, err } - return c.mutator.Mkdir(c.SourceDir, 0o700&^os.FileMode(c.Umask)) - case err == nil: - return fmt.Errorf("%s: not a directory", c.SourceDir) - default: - return err + cmd.Dir = string(dirRawAbsPath) } + return c.baseSystem.IdempotentCmdOutput(cmd) } -func (c *Config) getData() (map[string]interface{}, error) { - defaultData, err := c.getDefaultData() - if err != nil { - return nil, err +func (c *Config) defaultPreApplyFunc(targetRelPath chezmoi.RelPath, targetEntryState, lastWrittenEntryState, actualEntryState *chezmoi.EntryState) error { + switch { + case targetEntryState.Type == chezmoi.EntryStateTypeScript: + return nil + case c.force: + return nil + case lastWrittenEntryState == nil: + return nil + case lastWrittenEntryState.Equivalent(actualEntryState): + return nil } - data := map[string]interface{}{ - "chezmoi": defaultData, + + // LATER add merge option + var choices []string + actualContents := actualEntryState.Contents() + targetContents := targetEntryState.Contents() + if actualContents != nil || targetContents != nil { + choices = append(choices, "diff") } - for key, value := range c.Data { - data[key] = value + choices = append(choices, "overwrite", "all-overwite", "skip", "quit") + for { + switch choice, err := c.promptChoice(fmt.Sprintf("%s has changed since chezmoi last wrote it", targetRelPath), 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 ErrExitCode(1) + default: + return nil + } } - return data, nil } -func (c *Config) getDefaultData() (map[string]interface{}, error) { +func (c *Config) defaultTemplateData() map[string]interface{} { data := map[string]interface{}{ "arch": runtime.GOARCH, + "homeDir": c.homeDir, "os": runtime.GOOS, - "sourceDir": c.SourceDir, + "sourceDir": c.sourceDirAbsPath, + "version": map[string]interface{}{ + "builtBy": c.versionInfo.BuiltBy, + "commit": c.versionInfo.Commit, + "date": c.versionInfo.Date, + "version": c.versionInfo.Version, + }, } // Determine the user's username and group, if possible. @@ -348,330 +518,964 @@ func (c *Config) getDefaultData() (map[string]interface{}, error) { // 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. - - // First, attempt to determine the current user using user.Current, falling - // back to the $USER environment variable if set, and otherwise leaving - // username unset. - currentUser, err := user.Current() - if err == nil { + if currentUser, err := user.Current(); err == nil { data["username"] = currentUser.Username - } else if user, ok := os.LookupEnv("USER"); ok { - data["username"] = user + if runtime.GOOS != "windows" { + if group, err := user.LookupGroupId(currentUser.Gid); err == nil { + data["group"] = group.Name + } else { + log.Debug(). + Str("gid", currentUser.Gid). + Err(err). + Msg("user.LookupGroupId") + } + } + } else { + log.Debug(). + Err(err). + Msg("user.Current") + user, ok := os.LookupEnv("USER") + if ok { + data["username"] = user + } else { + log.Debug(). + Str("key", "USER"). + Bool("ok", ok). + Msg("os.LookupEnv") + } } - // If the current user could be determined, then attempt to lookup the group - // id. There is no fallback. - if currentUser != nil { - if group, err := user.LookupGroupId(currentUser.Gid); err == nil { - data["group"] = group.Name + if fqdnHostname, err := chezmoi.FQDNHostname(c.fs); err == nil && fqdnHostname != "" { + data["fqdnHostname"] = fqdnHostname + } else { + log.Debug(). + Err(err). + Msg("chezmoi.EtcHostsFQDNHostname") + } + + if hostname, err := os.Hostname(); err == nil { + data["hostname"] = strings.SplitN(hostname, ".", 2)[0] + } else { + log.Debug(). + Err(err). + Msg("os.Hostname") + } + + if kernelInfo, err := chezmoi.KernelInfo(c.fs); err == nil { + data["kernel"] = kernelInfo + } else { + log.Debug(). + Err(err). + Msg("chezmoi.KernelInfo") + } + + if osRelease, err := chezmoi.OSRelease(c.fs); err == nil { + data["osRelease"] = upperSnakeCaseToCamelCaseMap(osRelease) + } else { + log.Debug(). + Err(err). + Msg("chezmoi.OSRelease") + } + + return map[string]interface{}{ + "chezmoi": data, + } +} + +func (c *Config) destAbsPathInfos(sourceState *chezmoi.SourceState, args []string, recursive, follow bool) (map[chezmoi.AbsPath]os.FileInfo, error) { + destAbsPathInfos := make(map[chezmoi.AbsPath]os.FileInfo) + for _, arg := range args { + 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 recursive { + if err := chezmoi.Walk(c.destSystem, destAbsPath, func(destAbsPath chezmoi.AbsPath, info os.FileInfo, err error) error { + if err != nil { + return err + } + if follow && info.Mode()&os.ModeType == os.ModeSymlink { + info, err = c.destSystem.Stat(destAbsPath) + if err != nil { + return err + } + } + return sourceState.AddDestAbsPathInfos(destAbsPathInfos, c.destSystem, destAbsPath, info) + }); err != nil { + return nil, err + } + } else { + var info os.FileInfo + if follow { + info, err = c.destSystem.Stat(destAbsPath) + } else { + info, err = c.destSystem.Lstat(destAbsPath) + } + if err != nil { + return nil, err + } + if err := sourceState.AddDestAbsPathInfos(destAbsPathInfos, c.destSystem, destAbsPath, info); err != nil { + return nil, err + } } } + return destAbsPathInfos, nil +} - homedir, err := os.UserHomeDir() +func (c *Config) diffFile(path chezmoi.RelPath, fromData []byte, fromMode os.FileMode, toData []byte, toMode os.FileMode) error { + var sb strings.Builder + unifiedEncoder := diff.NewUnifiedEncoder(&sb, diff.DefaultContextLines) + if c.color { + unifiedEncoder.SetColor(diff.NewColorConfig()) + } + diffPatch, err := chezmoi.DiffPatch(path, fromData, fromMode, toData, toMode) if err != nil { - return nil, err + return err } - data["homedir"] = homedir + if err := unifiedEncoder.Encode(diffPatch); err != nil { + return err + } + return c.diffPager(sb.String()) +} - hostname, err := os.Hostname() +func (c *Config) diffPager(output string) error { + if c.noPager || c.Diff.Pager == "" { + return c.writeOutputString(output) + } + + // If the pager command contains any spaces, assume that it is a full + // shell command to be executed via the user's shell. Otherwise, execute + // it directly. + var pagerCmd *exec.Cmd + if strings.IndexFunc(c.Diff.Pager, unicode.IsSpace) != -1 { + shell, _ := shell.CurrentUserShell() + pagerCmd = exec.Command(shell, "-c", c.Diff.Pager) + } else { + //nolint:gosec + pagerCmd = exec.Command(c.Diff.Pager) + } + pagerCmd.Stdin = bytes.NewBufferString(output) + pagerCmd.Stdout = c.stdout + pagerCmd.Stderr = c.stderr + return pagerCmd.Run() +} + +func (c *Config) doPurge(purgeOptions *purgeOptions) error { + if c.persistentState != nil { + if err := c.persistentState.Close(); err != nil { + return err + } + } + + absSlashPersistentStateFile := c.persistentStateFile() + absPaths := chezmoi.AbsPaths{ + c.configFileAbsPath.Dir(), + c.configFileAbsPath, + absSlashPersistentStateFile, + c.sourceDirAbsPath, + } + if purgeOptions != nil && purgeOptions.binary { + executable, err := os.Executable() + if err == nil { + absPaths = append(absPaths, chezmoi.AbsPath(executable)) + } + } + + // Remove all paths that exist. + for _, absPath := range absPaths { + switch _, err := c.destSystem.Stat(absPath); { + case os.IsNotExist(err): + continue + case err != nil: + return err + } + + if !c.force { + switch choice, err := c.promptChoice(fmt.Sprintf("Remove %s", absPath), yesNoAllQuit); { + case err != nil: + return err + case choice == "yes": + case choice == "no": + continue + case choice == "all": + c.force = true + case choice == "quit": + return nil + } + } + + switch err := c.destSystem.RemoveAll(absPath); { + case os.IsPermission(err): + continue + case err != nil: + return err + } + } + + return nil +} + +// editor returns the path to the user's editor and any extra arguments. +func (c *Config) editor() (string, []string) { + // If the user has set and edit command then use it. + if c.Edit.Command != "" { + return c.Edit.Command, c.Edit.Args + } + + // Prefer $VISUAL over $EDITOR and fallback to vi. + editor := firstNonEmptyString( + os.Getenv("VISUAL"), + os.Getenv("EDITOR"), + "vi", + ) + + // If editor is found, return it. + if path, err := exec.LookPath(editor); err == nil { + return path, nil + } + + // Otherwise, if editor contains spaces, then assume that the first word is + // the editor and the rest are arguments. + components := whitespaceRx.Split(editor, -1) + if len(components) > 1 { + if path, err := exec.LookPath(components[0]); err == nil { + return path, components[1:] + } + } + + // Fallback to editor only. + return editor, nil +} + +func (c *Config) errorf(format string, args ...interface{}) { + fmt.Fprintf(c.stderr, "chezmoi: "+format, args...) +} + +func (c *Config) execute(args []string) error { + rootCmd, err := c.newRootCmd() if err != nil { - return nil, err + return err } - data["fullHostname"] = hostname - data["hostname"] = strings.SplitN(hostname, ".", 2)[0] + rootCmd.SetArgs(args) + return rootCmd.Execute() +} - osRelease, err := getOSRelease(c.fs) - if err == nil { - if osRelease != nil { - data["osRelease"] = upperSnakeCaseToCamelCaseMap(osRelease) +func (c *Config) findConfigTemplate() (chezmoi.RelPath, string, []byte, error) { + for _, ext := range viper.SupportedExts { + filename := chezmoi.RelPath(chezmoi.Prefix + "." + ext + chezmoi.TemplateSuffix) + contents, err := c.baseSystem.ReadFile(c.sourceDirAbsPath.Join(filename)) + switch { + case os.IsNotExist(err): + continue + case err != nil: + return "", "", nil, err } - } else if !os.IsNotExist(err) { - return nil, err + return chezmoi.RelPath("chezmoi." + ext), ext, contents, nil } + return "", "", nil, nil +} - kernelInfo, err := getKernelInfo(c.fs) - if err == nil && kernelInfo != nil { - data["kernel"] = kernelInfo - } else if err != nil { +func (c *Config) gitAutoAdd() (*git.Status, error) { + if err := c.run(c.sourceDirAbsPath, c.Git.Command, []string{"add", "."}); err != nil { return nil, err } - - return data, nil + output, err := c.cmdOutput(c.sourceDirAbsPath, c.Git.Command, []string{"status", "--porcelain=v2"}) + if err != nil { + return nil, err + } + return git.ParseStatusPorcelainV2(output) } -func (c *Config) getEditor() (string, []string) { - editor := os.Getenv("VISUAL") - if editor == "" { - editor = os.Getenv("EDITOR") +func (c *Config) gitAutoCommit(status *git.Status) error { + if status.Empty() { + return nil + } + commitMessageTemplate, err := templates.FS.ReadFile("COMMIT_MESSAGE.tmpl") + if err != nil { + return err + } + commitMessageTmpl, err := template.New("commit_message").Funcs(c.templateFuncs).Parse(string(commitMessageTemplate)) + if err != nil { + return err } - if editor == "" { - editor = "vi" + commitMessage := strings.Builder{} + if err := commitMessageTmpl.Execute(&commitMessage, status); err != nil { + return err } - components := whitespaceRegexp.Split(editor, -1) - return components[0], components[1:] + return c.run(c.sourceDirAbsPath, c.Git.Command, []string{"commit", "--message", commitMessage.String()}) } -func (c *Config) getEntries(ts *chezmoi.TargetState, args []string) ([]chezmoi.Entry, error) { - entries := []chezmoi.Entry{} - for _, arg := range args { - targetPath, err := filepath.Abs(arg) +func (c *Config) gitAutoPush(status *git.Status) error { + if status.Empty() { + return nil + } + return c.run(c.sourceDirAbsPath, c.Git.Command, []string{"push"}) +} + +func (c *Config) makeRunEWithSourceState(runE func(*cobra.Command, []string, *chezmoi.SourceState) error) func(*cobra.Command, []string) error { + return func(cmd *cobra.Command, args []string) error { + sourceState, err := c.sourceState() if err != nil { + return err + } + return runE(cmd, args, sourceState) + } +} + +func (c *Config) marshal(formatStr string, data interface{}) error { + var format chezmoi.Format + switch formatStr { + case "json": + format = chezmoi.JSONFormat + case "yaml": + format = chezmoi.YAMLFormat + default: + return fmt.Errorf("%s: unknown format", formatStr) + } + marshaledData, err := format.Marshal(data) + if err != nil { + return err + } + return c.writeOutput(marshaledData) +} + +func (c *Config) newRootCmd() (*cobra.Command, error) { + rootCmd := &cobra.Command{ + Use: "chezmoi", + Short: "Manage your dotfiles across multiple diverse machines, securely", + Version: c.versionStr, + PersistentPreRunE: c.persistentPreRunRootE, + PersistentPostRunE: c.persistentPostRunRootE, + SilenceErrors: true, + SilenceUsage: true, + } + + persistentFlags := rootCmd.PersistentFlags() + + persistentFlags.StringVar(&c.Color, "color", c.Color, "colorize diffs") + persistentFlags.StringVarP(&c.DestDir, "destination", "D", c.DestDir, "destination directory") + persistentFlags.BoolVar(&c.Remove, "remove", c.Remove, "remove targets") + persistentFlags.StringVarP(&c.SourceDir, "source", "S", c.SourceDir, "source directory") + persistentFlags.StringVar(&c.UseBuiltinGit, "use-builtin-git", c.UseBuiltinGit, "use builtin git") + for _, key := range []string{ + "color", + "destination", + "remove", + "source", + } { + if err := viper.BindPFlag(key, persistentFlags.Lookup(key)); err != nil { return nil, err } - entry, err := ts.Get(c.fs, targetPath) + } + + persistentFlags.StringVarP(&c.configFile, "config", "c", c.configFile, "config file") + persistentFlags.StringVar(&c.cpuProfile, "cpu-profile", c.cpuProfile, "write CPU profile to file") + persistentFlags.BoolVarP(&c.dryRun, "dry-run", "n", c.dryRun, "dry run") + persistentFlags.VarP(c.exclude, "exclude", "x", "exclude entry types") + persistentFlags.BoolVar(&c.force, "force", c.force, "force") + persistentFlags.BoolVarP(&c.keepGoing, "keep-going", "k", c.keepGoing, "keep going as far as possible after an error") + persistentFlags.BoolVar(&c.noPager, "no-pager", c.noPager, "do not use the pager") + persistentFlags.BoolVar(&c.noTTY, "no-tty", c.noTTY, "don't attempt to get a TTY for reading passwords") + persistentFlags.BoolVar(&c.sourcePath, "source-path", c.sourcePath, "specify targets by source path") + persistentFlags.BoolVarP(&c.verbose, "verbose", "v", c.verbose, "verbose") + persistentFlags.StringVarP(&c.outputStr, "output", "o", c.outputStr, "output file") + persistentFlags.BoolVar(&c.debug, "debug", c.debug, "write debug logs") + + for _, err := range []error{ + rootCmd.MarkPersistentFlagFilename("config"), + rootCmd.MarkPersistentFlagFilename("cpu-profile"), + rootCmd.MarkPersistentFlagDirname("destination"), + rootCmd.MarkPersistentFlagFilename("output"), + rootCmd.MarkPersistentFlagDirname("source"), + } { if err != nil { return nil, err } - if entry == nil { - return nil, fmt.Errorf("%s: not in source state", arg) - } - entries = append(entries, entry) } - return entries, nil -} -func (c *Config) getPersistentState(options *bolt.Options) (chezmoi.PersistentState, error) { - persistentStateFile := c.getPersistentStateFile() - if options == nil { - options = &bolt.Options{} + rootCmd.SetHelpCommand(c.newHelpCmd()) + for _, newCmdFunc := range []func() *cobra.Command{ + c.newAddCmd, + c.newApplyCmd, + c.newArchiveCmd, + c.newCatCmd, + c.newCDCmd, + c.newChattrCmd, + c.newCompletionCmd, + c.newDataCmd, + c.newDiffCmd, + c.newDocsCmd, + c.newDoctorCmd, + c.newDumpCmd, + c.newEditCmd, + c.newEditConfigCmd, + c.newExecuteTemplateCmd, + c.newForgetCmd, + c.newGitCmd, + c.newImportCmd, + c.newInitCmd, + c.newManagedCmd, + c.newMergeCmd, + c.newPurgeCmd, + c.newRemoveCmd, + c.newSecretCmd, + c.newSourcePathCmd, + c.newStateCmd, + c.newStatusCmd, + c.newUnmanagedCmd, + c.newUpdateCmd, + c.newVerifyCmd, + } { + rootCmd.AddCommand(newCmdFunc()) } - if options.Timeout == 0 { - options.Timeout = 2 * time.Second + + return rootCmd, nil +} + +func (c *Config) persistentPostRunRootE(cmd *cobra.Command, args []string) error { + defer pprof.StopCPUProfile() + + if c.persistentState != nil { + if err := c.persistentState.Close(); err != nil { + return err + } } - if c.DryRun { - options.ReadOnly = true + + if boolAnnotation(cmd, modifiesConfigFile) { + // Warn the user of any errors reading the config file. + v := viper.New() + v.SetFs(vfsafero.NewAferoFS(c.fs)) + v.SetConfigFile(string(c.configFileAbsPath)) + err := v.ReadInConfig() + if err == nil { + err = v.Unmarshal(&Config{}) + } + if err != nil { + cmd.Printf("warning: %s: %v\n", c.configFileAbsPath, err) + } } - state, err := chezmoi.NewBoltPersistentState(c.fs, persistentStateFile, options) - if errors.Is(err, bolt.ErrTimeout) { - return nil, fmt.Errorf("failed to lock database: %w", err) + + if boolAnnotation(cmd, modifiesSourceDirectory) { + var status *git.Status + if c.Git.AutoAdd || c.Git.AutoCommit || c.Git.AutoPush { + var err error + status, err = c.gitAutoAdd() + if err != nil { + return err + } + } + if c.Git.AutoCommit || c.Git.AutoPush { + if err := c.gitAutoCommit(status); err != nil { + return err + } + } + if c.Git.AutoPush { + if err := c.gitAutoPush(status); err != nil { + return err + } + } } - return state, err + + return nil } -func (c *Config) getPersistentStateFile() string { - if c.configFile != "" { - return filepath.Join(filepath.Dir(c.configFile), "chezmoistate.boltdb") +func (c *Config) persistentPreRunRootE(cmd *cobra.Command, args []string) error { + if c.cpuProfile != "" { + f, err := os.Create(c.cpuProfile) + if err != nil { + return err + } + if err := pprof.StartCPUProfile(f); err != nil { + return err + } } - for _, configDir := range c.bds.ConfigDirs { - persistentStateFile := filepath.Join(configDir, "chezmoi", "chezmoistate.boltdb") - if _, err := os.Stat(persistentStateFile); err == nil { - return persistentStateFile + + var err error + c.configFileAbsPath, err = chezmoi.NewAbsPathFromExtPath(c.configFile, c.homeDirAbsPath) + if err != nil { + return err + } + + if err := c.readConfig(); err != nil { + if !boolAnnotation(cmd, doesNotRequireValidConfig) { + return fmt.Errorf("invalid config: %s: %w", c.configFile, err) } + cmd.Printf("warning: %s: %v\n", c.configFile, err) } - return filepath.Join(filepath.Dir(getDefaultConfigFile(c.bds)), "chezmoistate.boltdb") -} -func (c *Config) getTargetState(populateOptions *chezmoi.PopulateOptions) (*chezmoi.TargetState, error) { - fs := vfs.NewReadOnlyFS(c.fs) + if c.Color == "" || strings.ToLower(c.Color) == "auto" { + if _, ok := os.LookupEnv("NO_COLOR"); ok { + c.color = false + } else if stdout, ok := c.stdout.(*os.File); ok { + c.color = term.IsTerminal(int(stdout.Fd())) + } else { + c.color = false + } + } else if color, err := parseBool(c.Color); err == nil { + c.color = color + } else if !boolAnnotation(cmd, doesNotRequireValidConfig) { + return fmt.Errorf("%s: invalid color value", c.Color) + } - data, err := c.getData() - if err != nil { - return nil, err + if c.color { + if err := enableVirtualTerminalProcessing(c.stdout); err != nil { + return err + } } - destDir := c.DestDir - if destDir != "" { - destDir, err = filepath.Abs(c.DestDir) + if c.sourceDirAbsPath, err = chezmoi.NewAbsPathFromExtPath(c.SourceDir, c.homeDirAbsPath); err != nil { + return err + } + if c.destDirAbsPath, err = chezmoi.NewAbsPathFromExtPath(c.DestDir, c.homeDirAbsPath); err != nil { + return err + } + + log.Logger = log.Output(zerolog.NewConsoleWriter( + func(w *zerolog.ConsoleWriter) { + w.Out = c.stderr + w.NoColor = !c.color + w.TimeFormat = time.RFC3339 + }, + )) + if !c.debug { + zerolog.SetGlobalLevel(zerolog.InfoLevel) + } + + c.baseSystem = chezmoi.NewRealSystem(c.fs) + if c.debug { + c.baseSystem = chezmoi.NewDebugSystem(c.baseSystem) + } + + switch { + case cmd.Annotations[persistentStateMode] == persistentStateModeEmpty: + c.persistentState = chezmoi.NewMockPersistentState() + case cmd.Annotations[persistentStateMode] == persistentStateModeReadOnly: + persistentStateFile := c.persistentStateFile() + c.persistentState, err = chezmoi.NewBoltPersistentState(c.baseSystem, persistentStateFile, chezmoi.BoltPersistentStateReadOnly) if err != nil { - return nil, err + return err + } + case cmd.Annotations[persistentStateMode] == persistentStateModeReadMockWrite: + fallthrough + case cmd.Annotations[persistentStateMode] == persistentStateModeReadWrite && c.dryRun: + persistentStateFile := c.persistentStateFile() + persistentState, err := chezmoi.NewBoltPersistentState(c.baseSystem, persistentStateFile, chezmoi.BoltPersistentStateReadOnly) + if err != nil { + return err + } + dryRunPeristentState := chezmoi.NewMockPersistentState() + if err := persistentState.CopyTo(dryRunPeristentState); err != nil { + return err } + if err := persistentState.Close(); err != nil { + return err + } + c.persistentState = dryRunPeristentState + case cmd.Annotations[persistentStateMode] == persistentStateModeReadWrite: + persistentStateFile := c.persistentStateFile() + c.persistentState, err = chezmoi.NewBoltPersistentState(c.baseSystem, persistentStateFile, chezmoi.BoltPersistentStateReadWrite) + if err != nil { + return err + } + default: + c.persistentState = nil + } + if c.debug && c.persistentState != nil { + c.persistentState = chezmoi.NewDebugPersistentState(c.persistentState) } - // For backwards compatibility, prioritize gpgRecipient over gpg.recipient. - if c.GPGRecipient != "" { - c.GPG.Recipient = c.GPGRecipient + c.sourceSystem = c.baseSystem + c.destSystem = c.baseSystem + if !boolAnnotation(cmd, modifiesDestinationDirectory) { + c.destSystem = chezmoi.NewReadOnlySystem(c.destSystem) + } + if !boolAnnotation(cmd, modifiesSourceDirectory) { + c.sourceSystem = chezmoi.NewReadOnlySystem(c.sourceSystem) + } + if c.dryRun { + c.sourceSystem = chezmoi.NewDryRunSystem(c.sourceSystem) + c.destSystem = chezmoi.NewDryRunSystem(c.destSystem) + } + if c.verbose { + c.sourceSystem = chezmoi.NewGitDiffSystem(c.sourceSystem, c.stdout, c.sourceDirAbsPath, c.color) + c.destSystem = chezmoi.NewGitDiffSystem(c.destSystem, c.stdout, c.destDirAbsPath, c.color) } - ts := chezmoi.NewTargetState( - chezmoi.WithDestDir(destDir), - chezmoi.WithGPG(&c.GPG), - chezmoi.WithSourceDir(c.SourceDir), - chezmoi.WithTemplateData(data), - chezmoi.WithTemplateFuncs(c.templateFuncs), - chezmoi.WithTemplateOptions(c.Template.Options), - chezmoi.WithUmask(os.FileMode(c.Umask)), - ) - if err := ts.Populate(fs, populateOptions); err != nil { - return nil, err + switch c.Encryption { + case "age": + c.encryption = &c.AGE + case "gpg": + c.encryption = &c.GPG + case "": + c.encryption = chezmoi.NoEncryption{} + default: + return fmt.Errorf("%s: unknown encryption", c.Encryption) } - if Version != nil && !isDevVersion(Version) && ts.MinVersion != nil && Version.LessThan(*ts.MinVersion) { - return nil, fmt.Errorf("chezmoi version %s too old, source state requires at least %s", Version, ts.MinVersion) + if c.debug { + c.encryption = chezmoi.NewDebugEncryption(c.encryption) + } + + if boolAnnotation(cmd, requiresConfigDirectory) { + if err := chezmoi.MkdirAll(c.baseSystem, c.configFileAbsPath.Dir(), 0o777); err != nil { + return err + } + } + + if boolAnnotation(cmd, requiresSourceDirectory) { + if err := chezmoi.MkdirAll(c.baseSystem, c.sourceDirAbsPath, 0o777); err != nil { + return err + } } - return ts, nil -} -func (c *Config) getVCS() (VCS, error) { - vcs, ok := vcses[filepath.Base(c.SourceVCS.Command)] - if !ok { - return nil, fmt.Errorf("%s: unsupported source VCS command", c.SourceVCS.Command) + if boolAnnotation(cmd, runsCommands) { + if runtime.GOOS == "linux" && c.bds.RuntimeDir != "" { + // Snap sets the $XDG_RUNTIME_DIR environment variable to + // /run/user/$uid/snap.$snap_name, but does not create this + // directory. Consequently, any spawned processes that need + // $XDG_DATA_DIR will fail. As a work-around, create the directory + // if it does not exist. See + // https://forum.snapcraft.io/t/wayland-dconf-and-xdg-runtime-dir/186/13. + if err := chezmoi.MkdirAll(c.baseSystem, chezmoi.AbsPath(c.bds.RuntimeDir), 0o700); err != nil { + return err + } + } } - return vcs, nil + + return nil } -func (c *Config) output(dir, name string, argv ...string) ([]byte, error) { - cmd := exec.Command(name, argv...) - if dir != "" { - var err error - cmd.Dir, err = c.fs.RawPath(dir) - if err != nil { - return nil, err +func (c *Config) persistentStateFile() chezmoi.AbsPath { + if c.configFile != "" { + return chezmoi.AbsPath(c.configFile).Dir().Join(persistentStateFilename) + } + for _, configDir := range c.bds.ConfigDirs { + configDirAbsPath := chezmoi.AbsPath(configDir) + persistentStateFile := configDirAbsPath.Join(chezmoi.RelPath("chezmoi"), persistentStateFilename) + if _, err := os.Stat(string(persistentStateFile)); err == nil { + return persistentStateFile } } - return c.mutator.IdempotentCmdOutput(cmd) + return defaultConfigFile(c.fs, c.bds).Dir().Join(persistentStateFilename) } -//nolint:unparam -func (c *Config) prompt(s, choices string) (byte, error) { - r := bufio.NewReader(c.Stdin) +func (c *Config) promptChoice(prompt string, choices []string) (string, error) { + promptWithChoices := fmt.Sprintf("%s [%s]? ", prompt, strings.Join(choices, ",")) + abbreviations := uniqueAbbreviations(choices) for { - _, err := fmt.Printf("%s [%s]? ", s, strings.Join(strings.Split(choices, ""), ",")) + line, err := c.readLine(promptWithChoices) if err != nil { - return 0, err + return "", err } - line, err := r.ReadString('\n') - if err != nil { - return 0, err - } - line = strings.TrimSpace(line) - if len(line) == 1 && strings.IndexByte(choices, line[0]) != -1 { - return line[0], nil + if value, ok := abbreviations[strings.TrimSpace(line)]; ok { + return value, nil } } } -// run runs name argv... in dir. -func (c *Config) run(dir, name string, argv ...string) error { - cmd := exec.Command(name, argv...) - if dir != "" { +func (c *Config) readConfig() error { + v := viper.New() + v.SetConfigFile(string(c.configFileAbsPath)) + v.SetFs(vfsafero.NewAferoFS(c.fs)) + switch err := v.ReadInConfig(); { + case os.IsNotExist(err): + return nil + case err != nil: + return err + } + if err := v.Unmarshal(c); err != nil { + return err + } + return c.validateData() +} + +func (c *Config) readLine(prompt string) (string, error) { + var line string + if err := c.withTerminal(prompt, func(t terminal) error { + var err error + line, err = t.ReadLine() + return err + }); err != nil { + return "", err + } + return line, nil +} + +func (c *Config) readPassword(prompt string) (string, error) { + var password string + if err := c.withTerminal("", func(t terminal) error { var err error - cmd.Dir, err = c.fs.RawPath(dir) + password, err = t.ReadPassword(prompt) + return err + }); err != nil { + return "", err + } + return password, nil +} + +func (c *Config) run(dir chezmoi.AbsPath, name string, args []string) error { + cmd := exec.Command(name, args...) + if dir != "" { + dirRawAbsPath, err := c.baseSystem.RawPath(dir) if err != nil { return err } + cmd.Dir = string(dirRawAbsPath) } - cmd.Stdin = c.Stdin - cmd.Stdout = c.Stdout - cmd.Stderr = c.Stdout - return c.mutator.RunCmd(cmd) + cmd.Stdin = c.stdin + cmd.Stdout = c.stdout + cmd.Stderr = c.stderr + return c.baseSystem.RunCmd(cmd) } -func (c *Config) runEditor(argv ...string) error { - editorName, editorArgs := c.getEditor() - return c.run("", editorName, append(editorArgs, argv...)...) +func (c *Config) runEditor(args []string) error { + editor, editorArgs := c.editor() + return c.run("", editor, append(editorArgs, args...)) } -func (c *Config) validateData() error { - return validateKeys(config.Data, identifierRegexp) +func (c *Config) sourceAbsPaths(sourceState *chezmoi.SourceState, args []string) (chezmoi.AbsPaths, error) { + targetRelPaths, err := c.targetRelPaths(sourceState, args, targetRelPathsOptions{ + mustBeInSourceState: true, + }) + if err != nil { + return nil, err + } + sourceAbsPaths := make(chezmoi.AbsPaths, 0, len(targetRelPaths)) + for _, targetRelPath := range targetRelPaths { + sourceAbsPath := c.sourceDirAbsPath.Join(sourceState.MustEntry(targetRelPath).SourceRelPath().RelPath()) + sourceAbsPaths = append(sourceAbsPaths, sourceAbsPath) + } + return sourceAbsPaths, nil } -func getAsset(name string) ([]byte, error) { - asset, ok := assets[name] - if !ok { - return nil, fmt.Errorf("%s: not found", name) +func (c *Config) sourceState() (*chezmoi.SourceState, error) { + s := chezmoi.NewSourceState( + chezmoi.WithDefaultTemplateDataFunc(c.defaultTemplateData), + chezmoi.WithDestDir(c.destDirAbsPath), + chezmoi.WithEncryption(c.encryption), + chezmoi.WithPriorityTemplateData(c.Data), + chezmoi.WithSourceDir(c.sourceDirAbsPath), + chezmoi.WithSystem(c.sourceSystem), + chezmoi.WithTemplateFuncs(c.templateFuncs), + chezmoi.WithTemplateOptions(c.Template.Options), + ) + + if err := s.Read(); err != nil { + return nil, err + } + + if minVersion := s.MinVersion(); c.version != nil && !isDevVersion(c.version) && c.version.LessThan(minVersion) { + return nil, fmt.Errorf("source state requires version %s or later, chezmoi is version %s", minVersion, c.version) } - return asset, nil + + return s, nil +} + +type targetRelPathsOptions struct { + mustBeInSourceState bool + recursive bool } -func getDefaultConfigFile(bds *xdg.BaseDirectorySpecification) string { - // Search XDG Base Directory Specification config directories first. - for _, configDir := range bds.ConfigDirs { - for _, extension := range viper.SupportedExts { - configFilePath := filepath.Join(configDir, "chezmoi", "chezmoi."+extension) - if _, err := os.Stat(configFilePath); err == nil { - return configFilePath +func (c *Config) targetRelPaths(sourceState *chezmoi.SourceState, args []string, options targetRelPathsOptions) (chezmoi.RelPaths, error) { + targetRelPaths := make(chezmoi.RelPaths, 0, len(args)) + for _, arg := range args { + argAbsPath, err := chezmoi.NewAbsPathFromExtPath(arg, c.homeDirAbsPath) + if err != nil { + return nil, err + } + targetRelPath, err := argAbsPath.TrimDirPrefix(c.destDirAbsPath) + if err != nil { + return nil, err + } + if err != nil { + return nil, err + } + if options.mustBeInSourceState { + if _, ok := sourceState.Entry(targetRelPath); !ok { + return nil, fmt.Errorf("%s: not in source state", arg) } } + targetRelPaths = append(targetRelPaths, targetRelPath) + if options.recursive { + parentRelPath := targetRelPath + // FIXME we should not call s.TargetRelPaths() here - risk of accidentally quadratic + for _, targetRelPath := range sourceState.TargetRelPaths() { + if _, err := targetRelPath.TrimDirPrefix(parentRelPath); err == nil { + targetRelPaths = append(targetRelPaths, targetRelPath) + } + } + } + } + + if len(targetRelPaths) == 0 { + return nil, nil } - // Fallback to XDG Base Directory Specification default. - return filepath.Join(bds.ConfigHome, "chezmoi", "chezmoi.toml") + + // Sort and de-duplicate targetRelPaths in place. + sort.Sort(targetRelPaths) + n := 1 + for i := 1; i < len(targetRelPaths); i++ { + if targetRelPaths[i] != targetRelPaths[i-1] { + targetRelPaths[n] = targetRelPaths[i] + n++ + } + } + return targetRelPaths[:n], nil } -func getDefaultSourceDir(bds *xdg.BaseDirectorySpecification) string { - // Check for XDG Base Directory Specification data directories first. - for _, dataDir := range bds.DataDirs { - sourceDir := filepath.Join(dataDir, "chezmoi") - if _, err := os.Stat(sourceDir); err == nil { - return sourceDir +func (c *Config) targetRelPathsBySourcePath(sourceState *chezmoi.SourceState, args []string) (chezmoi.RelPaths, error) { + targetRelPaths := make(chezmoi.RelPaths, 0, len(args)) + targetRelPathsBySourceRelPath := make(map[chezmoi.RelPath]chezmoi.RelPath) + for targetRelPath, sourceStateEntry := range sourceState.Entries() { + sourceRelPath := sourceStateEntry.SourceRelPath().RelPath() + targetRelPathsBySourceRelPath[sourceRelPath] = targetRelPath + } + for _, arg := range args { + argAbsPath, err := chezmoi.NewAbsPathFromExtPath(arg, c.homeDirAbsPath) + if err != nil { + return nil, err } + sourceRelPath, err := argAbsPath.TrimDirPrefix(c.sourceDirAbsPath) + if err != nil { + return nil, err + } + targetRelPath, ok := targetRelPathsBySourceRelPath[sourceRelPath] + if !ok { + return nil, fmt.Errorf("%s: not in source state", arg) + } + targetRelPaths = append(targetRelPaths, targetRelPath) } - // Fallback to XDG Base Directory Specification default. - return filepath.Join(bds.DataHome, "chezmoi") + return targetRelPaths, nil } -// isDevVersion returns true if version is a development version (i.e. that the -// major, minor, and patch version numbers are all zero). -func isDevVersion(v *semver.Version) bool { - return v.Major == 0 && v.Minor == 0 && v.Patch == 0 +func (c *Config) useBuiltinGit() (bool, error) { + if c.UseBuiltinGit == "" || strings.ToLower(c.UseBuiltinGit) == "auto" { + if _, err := exec.LookPath(c.Git.Command); err == nil { + return false, nil + } + return true, nil + } + return parseBool(c.UseBuiltinGit) } -// isWellKnownAbbreviation returns true if word is a well known abbreviation. -func isWellKnownAbbreviation(word string) bool { - _, ok := wellKnownAbbreviations[word] - return ok +func (c *Config) validateData() error { + return validateKeys(c.Data, identifierRx) } -func panicOnError(err error) { +func (c *Config) withTerminal(prompt string, f func(terminal) error) error { + if c.noTTY { + return f(newNullTerminal(c.stdin)) + } + + if stdinFile, ok := c.stdin.(*os.File); ok && term.IsTerminal(int(stdinFile.Fd())) { + fd := int(stdinFile.Fd()) + width, height, err := term.GetSize(fd) + if err != nil { + return err + } + oldState, err := term.MakeRaw(fd) + if err != nil { + return err + } + defer func() { + _ = term.Restore(fd, oldState) + }() + t := term.NewTerminal(struct { + io.Reader + io.Writer + }{ + Reader: c.stdin, + Writer: c.stdout, + }, prompt) + if err := t.SetSize(width, height); err != nil { + return err + } + return f(t) + } + + if runtime.GOOS == "windows" { + return f(newDumbTerminal(c.stdin, c.stdout, prompt)) + } + + devTTY, err := os.OpenFile("/dev/tty", os.O_RDWR, 0) + if err != nil { + return err + } + defer devTTY.Close() + fd := int(devTTY.Fd()) + width, height, err := term.GetSize(fd) if err != nil { - panic(err) + return err + } + oldState, err := term.MakeRaw(fd) + if err != nil { + return err } + defer func() { + _ = term.Restore(fd, oldState) + }() + t := term.NewTerminal(devTTY, prompt) + if err := t.SetSize(width, height); err != nil { + return err + } + return f(t) } -// titilize returns s, titilized. -func titilize(s string) string { - if s == "" { - return s +func (c *Config) writeOutput(data []byte) error { + if c.outputStr == "" || c.outputStr == "-" { + _, err := c.stdout.Write(data) + return err } - runes := []rune(s) - return string(append([]rune{unicode.ToTitle(runes[0])}, runes[1:]...)) + return c.baseSystem.WriteFile(chezmoi.AbsPath(c.outputStr), data, 0o666) } -// upperSnakeCaseToCamelCase converts a string in UPPER_SNAKE_CASE to -// camelCase. -func upperSnakeCaseToCamelCase(s string) string { - words := strings.Split(s, "_") - for i, word := range words { - if i == 0 { - words[i] = strings.ToLower(word) - } else if !isWellKnownAbbreviation(word) { - words[i] = titilize(strings.ToLower(word)) - } - } - return strings.Join(words, "") +func (c *Config) writeOutputString(data string) error { + return c.writeOutput([]byte(data)) } -// upperSnakeCaseToCamelCaseKeys returns m with all keys converted from -// UPPER_SNAKE_CASE to camelCase. -func upperSnakeCaseToCamelCaseMap(m map[string]string) map[string]string { - result := make(map[string]string) - for k, v := range m { - result[upperSnakeCaseToCamelCase(k)] = v - } - return result +// isDevVersion returns true if version is a development version (i.e. that the +// major, minor, and patch version numbers are all zero). +func isDevVersion(v *semver.Version) bool { + return v.Major == 0 && v.Minor == 0 && v.Patch == 0 } -// validateKeys ensures that all keys in data match re. -func validateKeys(data interface{}, re *regexp.Regexp) error { - switch data := data.(type) { - case map[string]interface{}: - for key, value := range data { - if !re.MatchString(key) { - return fmt.Errorf("invalid key: %q", key) - } - if err := validateKeys(value, re); err != nil { +// withVersionInfo sets the version information. +func withVersionInfo(versionInfo VersionInfo) configOption { + return func(c *Config) error { + var version *semver.Version + var versionElems []string + if versionInfo.Version != "" { + var err error + version, err = semver.NewVersion(strings.TrimPrefix(versionInfo.Version, "v")) + if err != nil { return err } + versionElems = append(versionElems, "v"+version.String()) + } else { + versionElems = append(versionElems, "dev") } - case []interface{}: - for _, value := range data { - if err := validateKeys(value, re); err != nil { - return err - } + if versionInfo.Commit != "" { + versionElems = append(versionElems, "commit "+versionInfo.Commit) + } + if versionInfo.Date != "" { + versionElems = append(versionElems, "built at "+versionInfo.Date) } + if versionInfo.BuiltBy != "" { + versionElems = append(versionElems, "built by "+versionInfo.BuiltBy) + } + c.version = version + c.versionInfo = versionInfo + c.versionStr = strings.Join(versionElems, ", ") + return nil } - return nil } diff --git a/cmd/config_test.go b/cmd/config_test.go index ea3a8ecd126..9a023a17839 100644 --- a/cmd/config_test.go +++ b/cmd/config_test.go @@ -1,75 +1,107 @@ package cmd import ( - "bytes" "io" + "os" "path/filepath" + "runtime" "testing" - "text/template" - "github.com/Masterminds/sprig/v3" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - vfs "github.com/twpayne/go-vfs" + vfs "github.com/twpayne/go-vfs/v2" xdg "github.com/twpayne/go-xdg/v3" "github.com/twpayne/chezmoi/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoitest" ) -func TestAutoCommitCommitMessage(t *testing.T) { - commitMessageText, err := getAsset(commitMessageTemplateAsset) - require.NoError(t, err) - commitMessageTmpl, err := template.New("commit_message").Funcs(sprig.TxtFuncMap()).Parse(string(commitMessageText)) - require.NoError(t, err) +func TestAddTemplateFuncPanic(t *testing.T) { + chezmoitest.WithTestFS(t, nil, func(fs vfs.FS) { + c := newTestConfig(t, fs) + assert.NotPanics(t, func() { + c.addTemplateFunc("func", nil) + }) + assert.Panics(t, func() { + c.addTemplateFunc("func", nil) + }) + }) +} + +func TestParseConfig(t *testing.T) { for _, tc := range []struct { - name string - statusStr string - wantErr bool - expectedMessage string + name string + filename string + contents string + expectedColor bool }{ { - name: "add", - statusStr: "1 A. N... 000000 100644 100644 0000000000000000000000000000000000000000 cea5c3500651a923bacd80f960dd20f04f71d509 main.go\n", - expectedMessage: "Add main.go\n", + name: "json_bool", + filename: "chezmoi.json", + contents: chezmoitest.JoinLines( + `{`, + ` "color":true`, + `}`, + ), + expectedColor: true, + }, + { + name: "json_string", + filename: "chezmoi.json", + contents: chezmoitest.JoinLines( + `{`, + ` "color":"on"`, + `}`, + ), + expectedColor: true, }, { - name: "remove", - statusStr: "1 D. N... 100644 000000 000000 cea5c3500651a923bacd80f960dd20f04f71d509 0000000000000000000000000000000000000000 main.go\n", - expectedMessage: "Remove main.go\n", + name: "toml_bool", + filename: "chezmoi.toml", + contents: chezmoitest.JoinLines( + `color = true`, + ), + expectedColor: true, }, { - name: "update", - statusStr: "1 M. N... 100644 100644 100644 353dbbb3c29a80fb44d4e26dac111739d25294db 353dbbb3c29a80fb44d4e26dac111739d25294db main.go\n", - expectedMessage: "Update main.go\n", + name: "toml_string", + filename: "chezmoi.toml", + contents: chezmoitest.JoinLines( + `color = "y"`, + ), + expectedColor: true, }, { - name: "rename", - statusStr: "2 R. N... 100644 100644 100644 9d06c86ecba40e1c695e69b55a40843df6a79cef 9d06c86ecba40e1c695e69b55a40843df6a79cef R100 chezmoi_rename.go\tchezmoi.go\n", - expectedMessage: "Rename chezmoi.go to chezmoi_rename.go\n", + name: "yaml_bool", + filename: "chezmoi.yaml", + contents: chezmoitest.JoinLines( + `color: true`, + ), + expectedColor: true, }, { - name: "unsupported_xy", - statusStr: "1 MM N... 100644 100644 100644 353dbbb3c29a80fb44d4e26dac111739d25294db 353dbbb3c29a80fb44d4e26dac111739d25294db main.go\n", - wantErr: true, + name: "yaml_string", + filename: "chezmoi.yaml", + contents: chezmoitest.JoinLines( + `color: "yes"`, + ), + expectedColor: true, }, } { t.Run(tc.name, func(t *testing.T) { - status, err := gitVCS{}.ParseStatusOutput([]byte(tc.statusStr)) - require.NoError(t, err) - b := &bytes.Buffer{} - err = commitMessageTmpl.Execute(b, status) - if tc.wantErr { - require.Error(t, err) - } else { - require.NoError(t, err) - assert.Equal(t, tc.expectedMessage, b.String()) - } + chezmoitest.WithTestFS(t, map[string]interface{}{ + "/home/user/.config/chezmoi/" + tc.filename: tc.contents, + }, func(fs vfs.FS) { + c := newTestConfig(t, fs) + require.NoError(t, c.execute([]string{"init"})) + assert.Equal(t, tc.expectedColor, c.color) + }) }) } } func TestUpperSnakeCaseToCamelCase(t *testing.T) { - for s, want := range map[string]string{ + for s, expected := range map[string]string{ "BUG_REPORT_URL": "bugReportURL", "ID": "id", "ID_LIKE": "idLike", @@ -77,18 +109,18 @@ func TestUpperSnakeCaseToCamelCase(t *testing.T) { "VERSION_CODENAME": "versionCodename", "VERSION_ID": "versionID", } { - assert.Equal(t, want, upperSnakeCaseToCamelCase(s)) + assert.Equal(t, expected, upperSnakeCaseToCamelCase(s)) } } func TestValidateKeys(t *testing.T) { for _, tc := range []struct { - data interface{} - wantErr bool + data interface{} + expectedErr bool }{ { - data: nil, - wantErr: false, + data: nil, + expectedErr: false, }, { data: map[string]interface{}{ @@ -98,13 +130,13 @@ func TestValidateKeys(t *testing.T) { "ThisVariableIsExported": nil, "αβ": "", }, - wantErr: false, + expectedErr: false, }, { data: map[string]interface{}{ "foo-foo": "bar", }, - wantErr: true, + expectedErr: true, }, { data: map[string]interface{}{ @@ -112,7 +144,7 @@ func TestValidateKeys(t *testing.T) { "bar-bar": "baz", }, }, - wantErr: true, + expectedErr: true, }, { data: map[string]interface{}{ @@ -122,111 +154,104 @@ func TestValidateKeys(t *testing.T) { }, }, }, - wantErr: true, + expectedErr: true, }, } { - if tc.wantErr { - assert.Error(t, validateKeys(tc.data, identifierRegexp)) + if tc.expectedErr { + assert.Error(t, validateKeys(tc.data, identifierRx)) } else { - assert.NoError(t, validateKeys(tc.data, identifierRegexp)) + assert.NoError(t, validateKeys(tc.data, identifierRx)) } } } -func newTestConfig(fs vfs.FS, options ...configOption) *Config { - return newConfig(append( - []configOption{ +func newTestConfig(t *testing.T, fs vfs.FS, options ...configOption) *Config { + t.Helper() + system := chezmoi.NewRealSystem(fs) + c, err := newConfig( + append([]configOption{ + withBaseSystem(system), + withDestSystem(system), + withSourceSystem(system), withTestFS(fs), withTestUser("user"), - }, - options..., - )...) -} - -func withAddCmdConfig(add addCmdConfig) configOption { - return func(c *Config) { - c.add = add - } -} - -func withData(data map[string]interface{}) configOption { - return func(c *Config) { - c.Data = data - } -} - -func withDestDir(destDir string) configOption { - return func(c *Config) { - c.DestDir = destDir - } -} - -func withDumpCmdConfig(dumpCmdConfig dumpCmdConfig) configOption { - return func(c *Config) { - c.dump = dumpCmdConfig - } -} - -func withFollow(follow bool) configOption { - return func(c *Config) { - c.Follow = follow - } -} - -func withGenericSecretCmdConfig(genericSecretCmdConfig genericSecretCmdConfig) configOption { - return func(c *Config) { - c.GenericSecret = genericSecretCmdConfig - } + withUmask(chezmoitest.Umask), + }, options...)..., + ) + require.NoError(t, err) + return c } -func withMutator(mutator chezmoi.Mutator) configOption { - return func(c *Config) { - c.mutator = mutator +func withBaseSystem(baseSystem chezmoi.System) configOption { + return func(c *Config) error { + c.baseSystem = baseSystem + return nil } } -func withRemove(remove bool) configOption { - return func(c *Config) { - c.Remove = remove +func withDestSystem(destSystem chezmoi.System) configOption { + return func(c *Config) error { + c.destSystem = destSystem + return nil } } -func withRemoveCmdConfig(remove removeCmdConfig) configOption { - return func(c *Config) { - c.remove = remove +func withSourceSystem(sourceSystem chezmoi.System) configOption { + return func(c *Config) error { + c.sourceSystem = sourceSystem + return nil } } func withStdin(stdin io.Reader) configOption { - return func(c *Config) { - c.Stdin = stdin + return func(c *Config) error { + c.stdin = stdin + return nil } } func withStdout(stdout io.Writer) configOption { - return func(c *Config) { - c.Stdout = stdout + return func(c *Config) error { + c.stdout = stdout + return nil } } func withTestFS(fs vfs.FS) configOption { - return func(c *Config) { + return func(c *Config) error { c.fs = fs - c.mutator = chezmoi.NewFSMutator(fs) + return nil } } func withTestUser(username string) configOption { - return func(c *Config) { - homeDir := filepath.Join("/", "home", username) - c.SourceDir = filepath.Join(homeDir, ".local", "share", "chezmoi") - c.DestDir = homeDir + return func(c *Config) error { + switch runtime.GOOS { + case "windows": + c.homeDir = `c:\home\user` + default: + c.homeDir = "/home/user" + } + c.SourceDir = filepath.Join(c.homeDir, ".local", "share", "chezmoi") + c.DestDir = c.homeDir c.Umask = 0o22 + configHome := filepath.Join(c.homeDir, ".config") + dataHome := filepath.Join(c.homeDir, ".local", "share") c.bds = &xdg.BaseDirectorySpecification{ - ConfigHome: filepath.Join(homeDir, ".config"), - DataHome: filepath.Join(homeDir, ".local"), - CacheHome: filepath.Join(homeDir, ".cache"), - RuntimeDir: filepath.Join(homeDir, ".run"), + ConfigHome: configHome, + ConfigDirs: []string{configHome}, + DataHome: dataHome, + DataDirs: []string{dataHome}, + CacheHome: filepath.Join(c.homeDir, ".cache"), + RuntimeDir: filepath.Join(c.homeDir, ".run"), } + return nil + } +} + +func withUmask(umask os.FileMode) configOption { + return func(c *Config) error { + c.Umask = umask + return nil } } diff --git a/cmd/data.go b/cmd/data.go deleted file mode 100644 index 3da8b2426ad..00000000000 --- a/cmd/data.go +++ /dev/null @@ -1,41 +0,0 @@ -package cmd - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" -) - -type dataCmdConfig struct { - format string -} - -var dataCmd = &cobra.Command{ - Use: "data", - Args: cobra.NoArgs, - Short: "Print the template data", - Long: mustGetLongHelp("data"), - Example: getExample("data"), - PreRunE: config.ensureNoError, - RunE: config.runDataCmd, -} - -func init() { - rootCmd.AddCommand(dataCmd) - - persistentFlags := dataCmd.PersistentFlags() - persistentFlags.StringVarP(&config.data.format, "format", "f", "json", "format (JSON, TOML, or YAML)") -} - -func (c *Config) runDataCmd(cmd *cobra.Command, args []string) error { - format, ok := formatMap[strings.ToLower(c.data.format)] - if !ok { - return fmt.Errorf("%s: unknown format", c.data.format) - } - data, err := c.getData() - if err != nil { - return err - } - return format(c.Stdout, data) -} diff --git a/cmd/data_linux.go b/cmd/data_linux.go deleted file mode 100644 index 14eb0835d52..00000000000 --- a/cmd/data_linux.go +++ /dev/null @@ -1,101 +0,0 @@ -package cmd - -import ( - "bufio" - "bytes" - "fmt" - "io" - "os" - "path/filepath" - "strconv" - "strings" - "unicode" - - "github.com/twpayne/go-vfs" -) - -func getKernelInfo(fs vfs.FS) (map[string]string, error) { - const procSysKernel = "/proc/sys/kernel" - - info, err := fs.Stat(procSysKernel) - switch { - case os.IsNotExist(err): - return nil, nil - case os.IsPermission(err): - return nil, nil - case !info.Mode().IsDir(): - return nil, nil - } - - kernelInfo := make(map[string]string) - for _, filename := range []string{ - "osrelease", - "ostype", - "version", - } { - data, err := fs.ReadFile(filepath.Join(procSysKernel, filename)) - switch { - case os.IsNotExist(err): - continue - case os.IsPermission(err): - continue - case err != nil: - return nil, err - } - kernelInfo[filename] = string(bytes.TrimSpace(data)) - } - return kernelInfo, nil -} - -// getOSRelease returns the operating system identification data as defined by -// https://www.freedesktop.org/software/systemd/man/os-release.html. -func getOSRelease(fs vfs.FS) (map[string]string, error) { - for _, filename := range []string{"/usr/lib/os-release", "/etc/os-release"} { - f, err := fs.Open(filename) - if os.IsNotExist(err) { - continue - } else if err != nil { - return nil, err - } - defer f.Close() - m, err := parseOSRelease(f) - if err != nil { - return nil, err - } - return m, nil - } - return nil, os.ErrNotExist -} - -// maybeUnquote removes quotation marks around s. -func maybeUnquote(s string) string { - // Try to unquote. - if s, err := strconv.Unquote(s); err == nil { - return s - } - // Otherwise return s, unchanged. - return s -} - -// parseOSRelease parses operating system identification data from r as defined -// by https://www.freedesktop.org/software/systemd/man/os-release.html. -func parseOSRelease(r io.Reader) (map[string]string, error) { - result := make(map[string]string) - s := bufio.NewScanner(r) - for s.Scan() { - // trim all leading whitespace, but not necessarily trailing whitespace - token := strings.TrimLeftFunc(s.Text(), unicode.IsSpace) - // if the line is empty or starts with #, skip - if len(token) == 0 || token[0] == '#' { - continue - } - fields := strings.SplitN(token, "=", 2) - if len(fields) != 2 { - return nil, fmt.Errorf("cannot parse %q", token) - } - key := fields[0] - value := maybeUnquote(fields[1]) - result[key] = value - } - return result, s.Err() -} diff --git a/cmd/data_linux_test.go b/cmd/data_linux_test.go deleted file mode 100644 index d4b37541e95..00000000000 --- a/cmd/data_linux_test.go +++ /dev/null @@ -1,200 +0,0 @@ -package cmd - -import ( - "bytes" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/twpayne/go-vfs/vfst" -) - -func TestGetKernelInfo(t *testing.T) { - for _, tc := range []struct { - name string - root interface{} - expectedKernelInfo map[string]string - }{ - { - name: "windows_services_for_linux", - root: map[string]interface{}{ - "/proc/sys/kernel": map[string]interface{}{ - "osrelease": "4.19.81-microsoft-standard\n", - "ostype": "Linux\n", - "version": "#1 SMP Debian 5.2.9-2 (2019-08-21)\n", - }, - }, - expectedKernelInfo: map[string]string{ - "osrelease": "4.19.81-microsoft-standard", - "ostype": "Linux", - "version": "#1 SMP Debian 5.2.9-2 (2019-08-21)", - }, - }, - { - name: "debian_version_only", - root: map[string]interface{}{ - "/proc/sys/kernel": map[string]interface{}{ - "version": "#1 SMP Debian 5.2.9-2 (2019-08-21)\n", - }, - }, - expectedKernelInfo: map[string]string{ - "version": "#1 SMP Debian 5.2.9-2 (2019-08-21)", - }, - }, - { - name: "proc_sys_kernel_missing", - root: map[string]interface{}{ - "/proc/sys": &vfst.Dir{Perm: 0o755}, - }, - expectedKernelInfo: nil, - }, - } { - t.Run(tc.name, func(t *testing.T) { - fs, cleanup, err := vfst.NewTestFS(tc.root) - require.NoError(t, err) - defer cleanup() - kernelInfo, err := getKernelInfo(fs) - assert.NoError(t, err) - assert.Equal(t, tc.expectedKernelInfo, kernelInfo) - }) - } -} - -func TestGetOSRelease(t *testing.T) { - for _, tc := range []struct { - name string - root map[string]interface{} - want map[string]string - }{ - { - name: "fedora", - root: map[string]interface{}{ - "/etc/os-release": `NAME=Fedora -VERSION="17 (Beefy Miracle)" -ID=fedora -VERSION_ID=17 -PRETTY_NAME="Fedora 17 (Beefy Miracle)" -ANSI_COLOR="0;34" -CPE_NAME="cpe:/o:fedoraproject:fedora:17" -HOME_URL="https://fedoraproject.org/" -BUG_REPORT_URL="https://bugzilla.redhat.com/"`, - }, - want: map[string]string{ - "NAME": "Fedora", - "VERSION": "17 (Beefy Miracle)", - "ID": "fedora", - "VERSION_ID": "17", - "PRETTY_NAME": "Fedora 17 (Beefy Miracle)", - "ANSI_COLOR": "0;34", - "CPE_NAME": "cpe:/o:fedoraproject:fedora:17", - "HOME_URL": "https://fedoraproject.org/", - "BUG_REPORT_URL": "https://bugzilla.redhat.com/", - }, - }, - { - name: "ubuntu", - root: map[string]interface{}{ - "/usr/lib/os-release": `NAME="Ubuntu" -VERSION="18.04.1 LTS (Bionic Beaver)" -ID=ubuntu -ID_LIKE=debian -PRETTY_NAME="Ubuntu 18.04.1 LTS" -VERSION_ID="18.04" -HOME_URL="https://www.ubuntu.com/" -SUPPORT_URL="https://help.ubuntu.com/" -BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/" -PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy" -VERSION_CODENAME=bionic -UBUNTU_CODENAME=bionic`, - }, - want: map[string]string{ - "NAME": "Ubuntu", - "VERSION": "18.04.1 LTS (Bionic Beaver)", - "ID": "ubuntu", - "ID_LIKE": "debian", - "PRETTY_NAME": "Ubuntu 18.04.1 LTS", - "VERSION_ID": "18.04", - "HOME_URL": "https://www.ubuntu.com/", - "SUPPORT_URL": "https://help.ubuntu.com/", - "BUG_REPORT_URL": "https://bugs.launchpad.net/ubuntu/", - "PRIVACY_POLICY_URL": "https://www.ubuntu.com/legal/terms-and-policies/privacy-policy", - "VERSION_CODENAME": "bionic", - "UBUNTU_CODENAME": "bionic", - }, - }, - } { - t.Run(tc.name, func(t *testing.T) { - fs, cleanup, err := vfst.NewTestFS(tc.root) - require.NoError(t, err) - defer cleanup() - got, gotErr := getOSRelease(fs) - assert.NoError(t, gotErr) - assert.Equal(t, tc.want, got) - }) - } -} - -func TestParseOSRelease(t *testing.T) { - for _, tc := range []struct { - s string - want map[string]string - }{ - { - s: `NAME=Fedora -VERSION="17 (Beefy Miracle)" -ID=fedora -VERSION_ID=17 -PRETTY_NAME="Fedora 17 (Beefy Miracle)" -ANSI_COLOR="0;34" -CPE_NAME="cpe:/o:fedoraproject:fedora:17" -HOME_URL="https://fedoraproject.org/" -BUG_REPORT_URL="https://bugzilla.redhat.com/"`, - want: map[string]string{ - "NAME": "Fedora", - "VERSION": "17 (Beefy Miracle)", - "ID": "fedora", - "VERSION_ID": "17", - "PRETTY_NAME": "Fedora 17 (Beefy Miracle)", - "ANSI_COLOR": "0;34", - "CPE_NAME": "cpe:/o:fedoraproject:fedora:17", - "HOME_URL": "https://fedoraproject.org/", - "BUG_REPORT_URL": "https://bugzilla.redhat.com/", - }, - }, - { - s: `NAME="Ubuntu" -VERSION="18.04.1 LTS (Bionic Beaver)" -ID=ubuntu -ID_LIKE=debian -PRETTY_NAME="Ubuntu 18.04.1 LTS" -VERSION_ID="18.04" -HOME_URL="https://www.ubuntu.com/" -SUPPORT_URL="https://help.ubuntu.com/" -BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/" -PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy" -# comment - - # comment -VERSION_CODENAME=bionic -UBUNTU_CODENAME=bionic`, - want: map[string]string{ - "NAME": "Ubuntu", - "VERSION": "18.04.1 LTS (Bionic Beaver)", - "ID": "ubuntu", - "ID_LIKE": "debian", - "PRETTY_NAME": "Ubuntu 18.04.1 LTS", - "VERSION_ID": "18.04", - "HOME_URL": "https://www.ubuntu.com/", - "SUPPORT_URL": "https://help.ubuntu.com/", - "BUG_REPORT_URL": "https://bugs.launchpad.net/ubuntu/", - "PRIVACY_POLICY_URL": "https://www.ubuntu.com/legal/terms-and-policies/privacy-policy", - "VERSION_CODENAME": "bionic", - "UBUNTU_CODENAME": "bionic", - }, - }, - } { - got, gotErr := parseOSRelease(bytes.NewBufferString(tc.s)) - assert.NoError(t, gotErr) - assert.Equal(t, tc.want, got) - } -} diff --git a/cmd/data_notlinux.go b/cmd/data_notlinux.go deleted file mode 100644 index 6dc54b5e39a..00000000000 --- a/cmd/data_notlinux.go +++ /dev/null @@ -1,13 +0,0 @@ -// +build !linux - -package cmd - -import "github.com/twpayne/go-vfs" - -func getKernelInfo(fs vfs.FS) (map[string]string, error) { - return nil, nil -} - -func getOSRelease(fs vfs.FS) (map[string]string, error) { - return nil, nil -} diff --git a/chezmoi2/cmd/datacmd.go b/cmd/datacmd.go similarity index 92% rename from chezmoi2/cmd/datacmd.go rename to cmd/datacmd.go index b1284ea2a6a..579224eadc1 100644 --- a/chezmoi2/cmd/datacmd.go +++ b/cmd/datacmd.go @@ -3,7 +3,7 @@ package cmd import ( "github.com/spf13/cobra" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoi" ) type dataCmdConfig struct { diff --git a/chezmoi2/cmd/datacmd_test.go b/cmd/datacmd_test.go similarity index 91% rename from chezmoi2/cmd/datacmd_test.go rename to cmd/datacmd_test.go index fffb8c22712..3b20d04fcc7 100644 --- a/chezmoi2/cmd/datacmd_test.go +++ b/cmd/datacmd_test.go @@ -6,10 +6,10 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/twpayne/go-vfs" + "github.com/twpayne/go-vfs/v2" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoitest" + "github.com/twpayne/chezmoi/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoitest" ) func TestDataCmd(t *testing.T) { diff --git a/cmd/diff.go b/cmd/diff.go deleted file mode 100644 index 2d17e47c476..00000000000 --- a/cmd/diff.go +++ /dev/null @@ -1,125 +0,0 @@ -package cmd - -import ( - "fmt" - "io" - "os/exec" - "path/filepath" - "strings" - "unicode" - - "github.com/go-git/go-git/v5/plumbing/format/diff" - "github.com/spf13/cobra" - "github.com/twpayne/go-shell" - "github.com/twpayne/go-vfs" - bolt "go.etcd.io/bbolt" - - "github.com/twpayne/chezmoi/internal/chezmoi" -) - -type diffCmdConfig struct { - Format string - NoPager bool - Pager string -} - -var diffCmd = &cobra.Command{ - Use: "diff [targets...]", - Short: "Print the diff between the target state and the destination state", - Long: mustGetLongHelp("diff"), - Example: getExample("diff"), - PreRunE: config.ensureNoError, - RunE: config.runDiffCmd, -} - -func init() { - rootCmd.AddCommand(diffCmd) - - persistentFlags := diffCmd.PersistentFlags() - persistentFlags.StringVarP(&config.Diff.Format, "format", "f", config.Diff.Format, "format, \"chezmoi\" or \"git\"") - persistentFlags.BoolVar(&config.Diff.NoPager, "no-pager", false, "disable pager") - - markRemainingZshCompPositionalArgumentsAsFiles(diffCmd, 1) -} - -func (c *Config) runDiffCmd(cmd *cobra.Command, args []string) error { - c.DryRun = true // Prevent scripts from running. - - switch c.Diff.Format { - case "chezmoi": - c.mutator = chezmoi.NullMutator{} - case "git": - c.mutator = chezmoi.NewFSMutator(vfs.NewReadOnlyFS(c.fs)) - default: - return fmt.Errorf("unknown diff format: %q", c.Diff.Format) - } - if c.Debug { - c.mutator = chezmoi.NewDebugMutator(c.mutator) - } - - persistentState, err := c.getPersistentState(&bolt.Options{ - ReadOnly: true, - }) - if err != nil { - return err - } - defer persistentState.Close() - - if c.Diff.NoPager || c.Diff.Pager == "" { - switch c.Diff.Format { - case "chezmoi": - c.mutator = chezmoi.NewVerboseMutator(c.Stdout, c.mutator, c.colored, c.maxDiffDataSize) - case "git": - unifiedEncoder := diff.NewUnifiedEncoder(c.Stdout, diff.DefaultContextLines) - if c.colored { - unifiedEncoder.SetColor(diff.NewColorConfig()) - } - c.mutator = chezmoi.NewGitDiffMutator(unifiedEncoder, c.mutator, c.DestDir+string(filepath.Separator)) - } - return c.applyArgs(args, persistentState) - } - - var pagerCmd *exec.Cmd - var pagerStdinPipe io.WriteCloser - - // If the pager command contains any spaces, assume that it is a full - // shell command to be executed via the user's shell. Otherwise, execute - // it directly. - if strings.IndexFunc(c.Diff.Pager, unicode.IsSpace) != -1 { - shell, _ := shell.CurrentUserShell() - pagerCmd = exec.Command(shell, "-c", c.Diff.Pager) - } else { - //nolint:gosec - pagerCmd = exec.Command(c.Diff.Pager) - } - pagerStdinPipe, err = pagerCmd.StdinPipe() - if err != nil { - return err - } - pagerCmd.Stdout = c.Stdout - pagerCmd.Stderr = c.Stderr - if err := pagerCmd.Start(); err != nil { - return err - } - - switch c.Diff.Format { - case "chezmoi": - c.mutator = chezmoi.NewVerboseMutator(pagerStdinPipe, c.mutator, c.colored, c.maxDiffDataSize) - case "git": - unifiedEncoder := diff.NewUnifiedEncoder(pagerStdinPipe, diff.DefaultContextLines) - if c.colored { - unifiedEncoder.SetColor(diff.NewColorConfig()) - } - c.mutator = chezmoi.NewGitDiffMutator(unifiedEncoder, c.mutator, c.DestDir+string(filepath.Separator)) - } - - if err := c.applyArgs(args, persistentState); err != nil { - return err - } - - if err := pagerStdinPipe.Close(); err != nil { - return err - } - - return pagerCmd.Wait() -} diff --git a/cmd/diff_posix_test.go b/cmd/diff_posix_test.go deleted file mode 100644 index 15311d12f70..00000000000 --- a/cmd/diff_posix_test.go +++ /dev/null @@ -1,37 +0,0 @@ -// +build !windows - -package cmd - -import ( - "io/ioutil" - "os" - "path/filepath" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - vfs "github.com/twpayne/go-vfs" - "github.com/twpayne/go-vfs/vfst" -) - -func TestDiffDoesNotRunScript(t *testing.T) { - tempDir, err := ioutil.TempDir("", "chezmoi") - require.NoError(t, err) - defer func() { - require.NoError(t, os.RemoveAll(tempDir)) - }() - fs := vfs.NewPathFS(vfs.OSFS, tempDir) - require.NoError(t, vfst.NewBuilder().Build( - fs, - map[string]interface{}{ - "/home/user/.local/share/chezmoi/run_true": "#!/bin/sh\necho foo >>" + filepath.Join(tempDir, "evidence") + "\n", - }, - )) - c := newTestConfig(fs) - assert.NoError(t, c.runDiffCmd(nil, nil)) - vfst.RunTests(t, vfs.OSFS, "", - vfst.TestPath(filepath.Join(tempDir, "evidence"), - vfst.TestDoesNotExist, - ), - ) -} diff --git a/cmd/diff_test.go b/cmd/diff_test.go deleted file mode 100644 index c66fa88e25a..00000000000 --- a/cmd/diff_test.go +++ /dev/null @@ -1,31 +0,0 @@ -package cmd - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/twpayne/go-vfs/vfst" -) - -func TestIssue740(t *testing.T) { - fs, cleanup, err := vfst.NewTestFS(map[string]interface{}{ - "/home/user": map[string]interface{}{ - "dir": map[string]interface{}{ - "foo": "foo", - }, - ".local/share/chezmoi": map[string]interface{}{ - "exact_dir": map[string]interface{}{ - "foo": "foo", - "bar": "bar", - }, - }, - }, - }) - require.NoError(t, err) - defer cleanup() - - c := newTestConfig(fs) - c.Diff.Format = "git" - assert.NoError(t, c.runDiffCmd(nil, nil)) -} diff --git a/chezmoi2/cmd/diffcmd.go b/cmd/diffcmd.go similarity index 93% rename from chezmoi2/cmd/diffcmd.go rename to cmd/diffcmd.go index 682492389b2..1c219b224b4 100644 --- a/chezmoi2/cmd/diffcmd.go +++ b/cmd/diffcmd.go @@ -5,11 +5,11 @@ import ( "github.com/spf13/cobra" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoi" ) type diffCmdConfig struct { - include *chezmoi.IncludeSet + include *chezmoi.EntryTypeSet recursive bool Pager string `mapstructure:"pager"` } diff --git a/cmd/docs.gen.go b/cmd/docs.gen.go deleted file mode 100644 index 2bdb97e31fe..00000000000 --- a/cmd/docs.gen.go +++ /dev/null @@ -1,3794 +0,0 @@ -// Code generated by github.com/twpayne/chezmoi/internal/cmd/generate-assets. DO NOT EDIT. -// +build !noembeddocs - -package cmd - -func init() { - assets["docs/CHANGES.md"] = []byte("" + - "# chezmoi Changes\n" + - "\n" + - "<!--- toc --->\n" + - "* [Upcoming](#upcoming)\n" + - " * [Default diff format changing from `chezmoi` to `git`.](#default-diff-format-changing-from-chezmoi-to-git)\n" + - " * [`gpgRecipient` config variable changing to `gpg.recipient`](#gpgrecipient-config-variable-changing-to-gpgrecipient)\n" + - "\n" + - "## Upcoming\n" + - "\n" + - "### Default diff format changing from `chezmoi` to `git`.\n" + - "\n" + - "Currently chezmoi outputs diffs in its own format, containing a mix of unified\n" + - "diffs and shell commands. This will be replaced with a [git format\n" + - "diff](https://git-scm.com/docs/diff-format) in version 2.0.0.\n" + - "\n" + - "### `gpgRecipient` config variable changing to `gpg.recipient`\n" + - "\n" + - "The `gpgRecipient` config variable is changing to `gpg.recipient`. To update,\n" + - "change your config from:\n" + - "\n" + - " gpgRecipient = \"...\"\n" + - "\n" + - "to:\n" + - "\n" + - " [gpg]\n" + - " recipient = \"...\"\n" + - "\n" + - "Support for the `gpgRecipient` config variable will be removed in version 2.0.0.\n" + - "\n") - assets["docs/COMPARISON.md"] = []byte("" + - "# chezmoi Comparison guide\n" + - "\n" + - "<!--- toc --->\n" + - "* [Comparison table](#comparison-table)\n" + - "* [I already have a system to manage my dotfiles, why should I use chezmoi?](#i-already-have-a-system-to-manage-my-dotfiles-why-should-i-use-chezmoi)\n" + - " * [...if coping with differences between machines requires special care](#if-coping-with-differences-between-machines-requires-special-care)\n" + - " * [...if you need to think for a moment before giving anyone access to your dotfiles](#if-you-need-to-think-for-a-moment-before-giving-anyone-access-to-your-dotfiles)\n" + - " * [...if your needs are outgrowing your current tool](#if-your-needs-are-outgrowing-your-current-tool)\n" + - " * [...if setting up your dotfiles requires more than two short commands](#if-setting-up-your-dotfiles-requires-more-than-two-short-commands)\n" + - "\n" + - "## Comparison table\n" + - "\n" + - "[chezmoi]: https://chezmoi.io/\n" + - "[dotbot]: https://github.com/anishathalye/dotbot\n" + - "[rcm]: https://github.com/thoughtbot/rcm\n" + - "[homesick]: https://github.com/technicalpickles/homesick\n" + - "[yadm]: https://yadm.io/\n" + - "[bare git]: https://www.atlassian.com/git/tutorials/dotfiles \"bare git\"\n" + - "\n" + - "| | [chezmoi] | [dotbot] | [rcm] | [homesick] | [yadm] | [bare git] |\n" + - "| -------------------------------------- | ------------- | ----------------- | ----------------- | ----------------- | ------------- | ---------- |\n" + - "| Implementation language | Go | Python | Perl | Ruby | Bash | C |\n" + - "| Distribution | Single binary | Python package | Multiple files | Ruby gem | Single script | n/a |\n" + - "| Install method | Multiple | git submodule | Multiple | Ruby gem | Multiple | n/a |\n" + - "| Non-root install on bare system | Yes | Difficult | Difficult | Difficult | Yes | Yes |\n" + - "| Windows support | Yes | No | No | No | No | Yes |\n" + - "| Bootstrap requirements | git | Python, git | Perl, git | Ruby, git | git | git |\n" + - "| Source repos | Single | Single | Multiple | Single | Single | Single |\n" + - "| Method | File | Symlink | File | Symlink | File | File |\n" + - "| Config file | Optional | Required | Optional | None | None | No |\n" + - "| Private files | Yes | No | No | No | No | No |\n" + - "| Show differences without applying | Yes | No | No | No | Yes | Yes |\n" + - "| Whole file encryption | Yes | No | No | No | Yes | No |\n" + - "| Password manager integration | Yes | No | No | No | No | No |\n" + - "| Machine-to-machine file differences | Templates | Alternative files | Alternative files | Alternative files | Templates | Manual |\n" + - "| Custom variables in templates | Yes | n/a | n/a | n/a | No | No |\n" + - "| Executable files | Yes | Yes | Yes | Yes | No | Yes |\n" + - "| File creation with initial contents | Yes | No | No | No | No | No |\n" + - "| File removal | Yes | Manual | No | No | No | No |\n" + - "| Directory creation | Yes | Yes | Yes | No | No | Yes |\n" + - "| Run scripts | Yes | Yes | Yes | No | No | No |\n" + - "| Run once scripts | Yes | No | No | No | Manual | No |\n" + - "| Machine-to-machine symlink differences | Yes | No | No | No | Yes | No |\n" + - "| Shell completion | Yes | No | No | No | Yes | Yes |\n" + - "| Archive import | Yes | No | No | No | No | No |\n" + - "| Archive export | Yes | No | No | No | No | Yes |\n" + - "\n" + - "## I already have a system to manage my dotfiles, why should I use chezmoi?\n" + - "\n" + - "If you're using any of the following methods:\n" + - "\n" + - "* A custom shell script.\n" + - "* An existing dotfile manager like\n" + - " [homeshick](https://github.com/andsens/homeshick),\n" + - " [homesick](https://github.com/technicalpickles/homesick),\n" + - " [rcm](https://github.com/thoughtbot/rcm), [GNU\n" + - " Stow](https://www.gnu.org/software/stow/), or [yadm](https://yadm.io/).\n" + - "* A [bare git repo](https://www.atlassian.com/git/tutorials/dotfiles).\n" + - "\n" + - "Then you've probably run into at least one of the following problems.\n" + - "\n" + - "### ...if coping with differences between machines requires special care\n" + - "\n" + - "If you want to synchronize your dotfiles across multiple operating systems or\n" + - "distributions, then you may need to manually perform extra steps to cope with\n" + - "differences from machine to machine. You might need to run different commands on\n" + - "different machines, maintain separate per-machine files or branches (with the\n" + - "associated hassle of merging, rebasing, or copying each change), or hope that\n" + - "your custom logic handles the differences correctly.\n" + - "\n" + - "chezmoi uses a single source of truth (a single branch) and a single command\n" + - "that works on every machine. Individual files can be templates to handle machine\n" + - "to machine differences, if needed.\n" + - "\n" + - "### ...if you need to think for a moment before giving anyone access to your dotfiles\n" + - "\n" + - "If your system stores secrets in plain text, then you must be very careful about\n" + - "where you clone your dotfiles. If you clone them on your work machine then\n" + - "anyone with access to your work machine (e.g. your IT department) will have\n" + - "access to your home secrets. If you clone it on your home machine then you risk\n" + - "leaking work secrets.\n" + - "\n" + - "With chezmoi you can store secrets in your password manager or encrypt them, and\n" + - "even store passwords in different ways on different machines. You can clone your\n" + - "dotfiles repository anywhere, and even make your dotfiles repo public, without\n" + - "leaving personal secrets on your work machine or work secrets on your personal\n" + - "machine.\n" + - "\n" + - "### ...if your needs are outgrowing your current tool\n" + - "\n" + - "If your system was written by you for your personal use, then it probably has\n" + - "the minimum functionality that you needed when you wrote it. If you need more\n" + - "functionality then you have to implement it yourself.\n" + - "\n" + - "chezmoi includes a huge range of battle-tested functionality out-of-the-box,\n" + - "including dry-run and diff modes, script execution, conflict resolution, Windows\n" + - "support, and much, much more. chezmoi is [used by thousands of\n" + - "people](https://github.com/twpayne/chezmoi/stargazers), so it is likely that\n" + - "when you hit the limits of your existing dotfile management system, chezmoi\n" + - "already has a tried-and-tested solution ready for you to use.\n" + - "\n" + - "### ...if setting up your dotfiles requires more than two short commands\n" + - "\n" + - "If your system is written in a scripting language like Python, Perl, or Ruby,\n" + - "then you also need to install a compatible version of that language's runtime\n" + - "before you can use your system.\n" + - "\n" + - "chezmoi is distributed as a single stand-alone statically-linked binary with no\n" + - "dependencies that you can simply copy onto your machine and run. chezmoi\n" + - "provides one-line installs, pre-built binaries, packages for Linux and BSD\n" + - "distributions, Homebrew formulae, Scoop and Chocolatey support on Windows, and a\n" + - "initial config file generation mechanism to make installing your dotfiles on a\n" + - "new machine as painless as possible.\n" + - "\n" + - "\n") - assets["docs/CONTRIBUTING.md"] = []byte("" + - "# chezmoi Contributing Guide\n" + - "\n" + - "<!--- toc --->\n" + - "* [Getting started](#getting-started)\n" + - "* [Developing locally](#developing-locally)\n" + - "* [Generated code](#generated-code)\n" + - "* [Contributing changes](#contributing-changes)\n" + - "* [Managing releases](#managing-releases)\n" + - "* [Packaging](#packaging)\n" + - "* [Updating the website](#updating-the-website)\n" + - "\n" + - "## Getting started\n" + - "\n" + - "chezmoi is written in [Go](https://golang.org) and development happens on\n" + - "[GitHub](https://github.com). The rest of this document assumes that you've\n" + - "checked out chezmoi locally.\n" + - "\n" + - "## Developing locally\n" + - "\n" + - "chezmoi requires Go 1.14 or later and Go modules enabled. Enable Go modules by\n" + - "setting the environment variable `GO111MODULE=on`.\n" + - "\n" + - "chezmoi is a standard Go project, using standard Go tooling, with a few extra\n" + - "tools. Ensure that these extra tools are installed with:\n" + - "\n" + - " make ensure-tools\n" + - "\n" + - "Build chezmoi:\n" + - "\n" + - " go build .\n" + - "\n" + - "Run all tests:\n" + - "\n" + - " go test ./...\n" + - "\n" + - "Run chezmoi:\n" + - "\n" + - " go run .\n" + - "\n" + - "## Generated code\n" + - "\n" + - "chezmoi generates help text, shell completions, embedded files, and the website\n" + - "from a single source of truth. You must run\n" + - "\n" + - " go generate\n" + - "\n" + - "if you change includes any of the following:\n" + - "\n" + - "* Modify any documentation in the `docs/` directory.\n" + - "* Modify any files in the `assets/templates/` directory.\n" + - "* Add or modify a command.\n" + - "* Add or modify a command's flags.\n" + - "\n" + - "chezmoi's continuous integration verifies that all generated files are up to\n" + - "date. Changes to generated files should be included in the commit that modifies\n" + - "the source of truth.\n" + - "\n" + - "## Contributing changes\n" + - "\n" + - "Bug reports, bug fixes, and documentation improvements are always welcome.\n" + - "Please [open an issue](https://github.com/twpayne/chezmoi/issues/new/choose) or\n" + - "[create a pull\n" + - "request](https://help.github.com/en/articles/creating-a-pull-request) with your\n" + - "report, fix, or improvement.\n" + - "\n" + - "If you want to make a more significant change, please first [open an\n" + - "issue](https://github.com/twpayne/chezmoi/issues/new/choose) to discuss the\n" + - "change that you want to make. Dave Cheney gives a [good\n" + - "rationale](https://dave.cheney.net/2019/02/18/talk-then-code) as to why this is\n" + - "important.\n" + - "\n" + - "All changes are made via pull requests. In your pull request, please make sure\n" + - "that:\n" + - "\n" + - "* All existing tests pass.\n" + - "\n" + - "* There are appropriate additional tests that demonstrate that your PR works as\n" + - " intended.\n" + - "\n" + - "* The documentation is updated, if necessary. For new features you should add an\n" + - " entry in `docs/HOWTO.md` and a complete description in `docs/REFERENCE.md`.\n" + - "\n" + - "* All generated files are up to date. You can ensure this by running `go\n" + - " generate` and including any modified files in your commit.\n" + - "\n" + - "* The code is correctly formatted, according to\n" + - " [`gofumports`](https://mvdan.cc/gofumpt/gofumports). You can ensure this by\n" + - " running `make format`.\n" + - "\n" + - "* The code passes [`golangci-lint`](https://github.com/golangci/golangci-lint).\n" + - " You can ensure this by running `make lint`.\n" + - "\n" + - "* The commit messages match chezmoi's convention, specifically that they begin\n" + - " with a capitalized verb in the imperative and give a short description of what\n" + - " the commit does. Detailed information or justification can be optionally\n" + - " included in the body of the commit message.\n" + - "\n" + - "* Commits are logically separate, with no merge or \"fixup\" commits.\n" + - "\n" + - "* The branch applies cleanly to `master`.\n" + - "\n" + - "## Managing releases\n" + - "\n" + - "Releases are managed with [`goreleaser`](https://goreleaser.com/).\n" + - "\n" + - "To build a test release, without publishing, (Linux only) run:\n" + - "\n" + - " make test-release\n" + - "\n" + - "Publish a new release by creating and pushing a tag, e.g.:\n" + - "\n" + - " git tag v1.2.3\n" + - " git push --tags\n" + - "\n" + - "This triggers a [GitHub Action](https://github.com/twpayne/chezmoi/actions) that\n" + - "builds and publishes archives, packages, and snaps, and creates a new [GitHub\n" + - "Release](https://github.com/twpayne/chezmoi/releases).\n" + - "\n" + - "Publishing [Snaps](https://snapcraft.io/) requires a `SNAPCRAFT_LOGIN`\n" + - "[repository\n" + - "secret](https://github.com/twpayne/chezmoi/settings/secrets/actions). Snapcraft\n" + - "logins periodically expire. Create a new snapcraft login by running:\n" + - "\n" + - " snapcraft export-login --snaps=chezmoi --channels=stable --acls=package_upload -\n" + - "\n" + - "[brew](https://brew.sh/) formula must be updated manually with the command:\n" + - "\n" + - " brew bump-formula-pr --tag=v1.2.3 chezmoi\n" + - "\n" + - "## Packaging\n" + - "\n" + - "If you're packaging chezmoi for an operating system or distribution:\n" + - "\n" + - "* chezmoi has no build or install dependencies other than the standard Go\n" + - " toolchain.\n" + - "\n" + - "* Please set the version number, git commit, and build time in the binary. This\n" + - " greatly assists debugging when end users report problems or ask for help. You\n" + - " can do this by passing the following flags to the Go linker:\n" + - "\n" + - " ```\n" + - " -X main.version=$VERSION\n" + - " -X main.commit=$COMMIT\n" + - " -X main.date=$DATE\n" + - " -X main.builtBy=$BUILT_BY\n" + - " ```\n" + - "\n" + - " `$VERSION` should be the chezmoi version, e.g. `1.7.3`. Any `v` prefix is\n" + - " optional and will be stripped, so you can pass the git tag in directly.\n" + - "\n" + - " `$COMMIT` should be the full git commit hash at which chezmoi is built, e.g.\n" + - " `4d678ce6850c9d81c7ab2fe0d8f20c1547688b91`.\n" + - "\n" + - " `$DATE` should be the date of the build in RFC3339 format, e.g.\n" + - " `2019-11-23T18:29:25Z`.\n" + - "\n" + - " `$BUILT_BY` should be a string indicating what mechanism was used to build the\n" + - " binary, e.g. `goreleaser`.\n" + - "\n" + - "* Please enable cgo, if possible. chezmoi can be built and run without cgo, but\n" + - " the `.chezmoi.username` and `.chezmoi.group` template variables may not be set\n" + - " correctly on some systems.\n" + - "\n" + - "* chezmoi includes a `docs` command which prints its documentation. By default,\n" + - " the docs are embedded in the binary. You can disable this behavior, and have\n" + - " chezmoi read its docs from the filesystem by building with the `noembeddocs`\n" + - " build tag and setting the directory where chezmoi can find them with the `-X\n" + - " github.com/twpayne/chezmoi/cmd.DocDir=$DOCDIR` linker flag. For example:\n" + - "\n" + - " ```\n" + - " go build -tags noembeddocs -ldflags \"-X github.com/twpayne/chezmoi/cmd.DocsDir=/usr/share/doc/chezmoi\" .\n" + - " ```\n" + - "\n" + - " To remove the `docs` command completely, use the `nodocs` build tag.\n" + - "\n" + - "* chezmoi includes an `upgrade` command which attempts to self-upgrade. You can\n" + - " remove this command completely by building chezmoi with the `noupgrade` build\n" + - " tag.\n" + - "\n" + - "* chezmoi includes shell completions in the `completions` directory. Please\n" + - " include these in the package and install them in the shell-appropriate\n" + - " directory, if possible.\n" + - "\n" + - "* If the instructions for installing chezmoi in chezmoi's [install\n" + - " guide](https://github.com/twpayne/chezmoi/blob/master/docs/INSTALL.md) are\n" + - " absent or incorrect, please open an issue or submit a PR to correct them.\n" + - "\n" + - "## Updating the website\n" + - "\n" + - "[The website](https://chezmoi.io) is generated with [Hugo](https://gohugo.io/)\n" + - "and served with [GitHub pages](https://pages.github.com/) from the [`gh-pages`\n" + - "branch](https://github.com/twpayne/chezmoi/tree/gh-pages) to GitHub.\n" + - "\n" + - "Before building the website, you must download the [Hugo Book\n" + - "Theme](https://github.com/alex-shpak/hugo-book) by running:\n" + - "\n" + - " git submodule update --init\n" + - "\n" + - "Test the website locally by running:\n" + - "\n" + - " ( cd chezmoi.io && hugo serve )\n" + - "\n" + - "and visit http://localhost:1313/.\n" + - "\n" + - "To build the website in a temporary directory, run:\n" + - "\n" + - " ( cd chezmoi.io && make )\n" + - "\n" + - "From here you can run\n" + - "\n" + - " git show\n" + - "\n" + - "to show changes and\n" + - "\n" + - " git push\n" + - "\n" + - "to push them. You can only push changes if you have write permissions to the\n" + - "chezmoi GitHub repo.\n" + - "\n") - assets["docs/FAQ.md"] = []byte("" + - "# chezmoi Frequently Asked Questions\n" + - "\n" + - "<!--- toc --->\n" + - "* [How can I quickly check for problems with chezmoi on my machine?](#how-can-i-quickly-check-for-problems-with-chezmoi-on-my-machine)\n" + - "* [What are the consequences of \"bare\" modifications to the target files? If my `.zshrc` is managed by chezmoi and I edit `~/.zshrc` without using `chezmoi edit`, what happens?](#what-are-the-consequences-of-bare-modifications-to-the-target-files-if-my-zshrc-is-managed-by-chezmoi-and-i-edit-zshrc-without-using-chezmoi-edit-what-happens)\n" + - "* [How can I tell what dotfiles in my home directory aren't managed by chezmoi? Is there an easy way to have chezmoi manage a subset of them?](#how-can-i-tell-what-dotfiles-in-my-home-directory-arent-managed-by-chezmoi-is-there-an-easy-way-to-have-chezmoi-manage-a-subset-of-them)\n" + - "* [How can I tell what dotfiles in my home directory are currently managed by chezmoi?](#how-can-i-tell-what-dotfiles-in-my-home-directory-are-currently-managed-by-chezmoi)\n" + - "* [If there's a mechanism in place for the above, is there also a way to tell chezmoi to ignore specific files or groups of files (e.g. by directory name or by glob)?](#if-theres-a-mechanism-in-place-for-the-above-is-there-also-a-way-to-tell-chezmoi-to-ignore-specific-files-or-groups-of-files-eg-by-directory-name-or-by-glob)\n" + - "* [If the target already exists, but is \"behind\" the source, can chezmoi be configured to preserve the target version before replacing it with one derived from the source?](#if-the-target-already-exists-but-is-behind-the-source-can-chezmoi-be-configured-to-preserve-the-target-version-before-replacing-it-with-one-derived-from-the-source)\n" + - "* [Once I've made a change to the source directory, how do I commit it?](#once-ive-made-a-change-to-the-source-directory-how-do-i-commit-it)\n" + - "* [How do I only run a script when a file has changed?](#how-do-i-only-run-a-script-when-a-file-has-changed)\n" + - "* [I've made changes to both the destination state and the source state that I want to keep. How can I keep them both?](#ive-made-changes-to-both-the-destination-state-and-the-source-state-that-i-want-to-keep-how-can-i-keep-them-both)\n" + - "* [Why does chezmoi convert all my template variables to lowercase?](#why-does-chezmoi-convert-all-my-template-variables-to-lowercase)\n" + - "* [chezmoi makes `~/.ssh/config` group writeable. How do I stop this?](#chezmoi-makes-sshconfig-group-writeable-how-do-i-stop-this)\n" + - "* [Why doesn't chezmoi use symlinks like GNU Stow?](#why-doesnt-chezmoi-use-symlinks-like-gnu-stow)\n" + - "* [Do I have to use `chezmoi edit` to edit my dotfiles?](#do-i-have-to-use-chezmoi-edit-to-edit-my-dotfiles)\n" + - "* [Can I change how chezmoi's source state is represented on disk?](#can-i-change-how-chezmois-source-state-is-represented-on-disk)\n" + - "* [gpg encryption fails. What could be wrong?](#gpg-encryption-fails-what-could-be-wrong)\n" + - "* [chezmoi reports \"user: lookup userid NNNNN: input/output error\"](#chezmoi-reports-user-lookup-userid-nnnnn-inputoutput-error)\n" + - "* [I'm getting errors trying to build chezmoi from source](#im-getting-errors-trying-to-build-chezmoi-from-source)\n" + - "* [What inspired chezmoi?](#what-inspired-chezmoi)\n" + - "* [Why not use Ansible/Chef/Puppet/Salt, or similar to manage my dotfiles instead?](#why-not-use-ansiblechefpuppetsalt-or-similar-to-manage-my-dotfiles-instead)\n" + - "* [Can I use chezmoi to manage files outside my home directory?](#can-i-use-chezmoi-to-manage-files-outside-my-home-directory)\n" + - "* [Where does the name \"chezmoi\" come from?](#where-does-the-name-chezmoi-come-from)\n" + - "* [What other questions have been asked about chezmoi?](#what-other-questions-have-been-asked-about-chezmoi)\n" + - "* [Where do I ask a question that isn't answered here?](#where-do-i-ask-a-question-that-isnt-answered-here)\n" + - "* [I like chezmoi. How do I say thanks?](#i-like-chezmoi-how-do-i-say-thanks)\n" + - "\n" + - "## How can I quickly check for problems with chezmoi on my machine?\n" + - "\n" + - "Run:\n" + - "\n" + - " chezmoi doctor\n" + - "\n" + - "Anything `ok` is fine, anything `warning` is only a problem if you want to use\n" + - "the related feature, and anything `error` indicates a definite problem.\n" + - "\n" + - "## What are the consequences of \"bare\" modifications to the target files? If my `.zshrc` is managed by chezmoi and I edit `~/.zshrc` without using `chezmoi edit`, what happens?\n" + - "\n" + - "chezmoi will overwrite the file the next time you run `chezmoi apply`. Until you\n" + - "run `chezmoi apply` your modified `~/.zshrc` will remain in place.\n" + - "\n" + - "## How can I tell what dotfiles in my home directory aren't managed by chezmoi? Is there an easy way to have chezmoi manage a subset of them?\n" + - "\n" + - "`chezmoi unmanaged` will list everything not managed by chezmoi. You can add\n" + - "entire directories with `chezmoi add -r`.\n" + - "\n" + - "## How can I tell what dotfiles in my home directory are currently managed by chezmoi?\n" + - "\n" + - "`chezmoi managed` will list everything managed by chezmoi.\n" + - "\n" + - "## If there's a mechanism in place for the above, is there also a way to tell chezmoi to ignore specific files or groups of files (e.g. by directory name or by glob)?\n" + - "\n" + - "By default, chezmoi ignores everything that you haven't explicitly `chezmoi\n" + - "add`'ed. If you have files in your source directory that you don't want added to\n" + - "your destination directory when you run `chezmoi apply` add their names to a\n" + - "file called `.chezmoiignore` in the source state.\n" + - "\n" + - "Patterns are supported, and you can change what's ignored from machine to\n" + - "machine. The full usage and syntax is described in the [reference\n" + - "manual](https://github.com/twpayne/chezmoi/blob/master/docs/REFERENCE.md#chezmoiignore).\n" + - "\n" + - "## If the target already exists, but is \"behind\" the source, can chezmoi be configured to preserve the target version before replacing it with one derived from the source?\n" + - "\n" + - "Yes. Run `chezmoi add` will update the source state with the target. To see\n" + - "diffs of what would change, without actually changing anything, use `chezmoi\n" + - "diff`.\n" + - "\n" + - "## Once I've made a change to the source directory, how do I commit it?\n" + - "\n" + - "You have several options:\n" + - "\n" + - "* `chezmoi cd` opens a shell in the source directory, where you can run your\n" + - " usual version control commands, like `git add` and `git commit`.\n" + - "* `chezmoi git` and `chezmoi hg` run `git` and `hg` respectively in the source\n" + - " directory and pass extra arguments to the command. If you're passing any\n" + - " flags, you'll need to use `--` to prevent chezmoi from consuming them, for\n" + - " example `chezmoi git -- commit -m \"Update dotfiles\"`.\n" + - "* `chezmoi source` runs your configured version control system in your source\n" + - " directory. It works in the same way as the `chezmoi git` and `chezmoi hg`\n" + - " commands, but uses `sourceVCS.command`.\n" + - "\n" + - "## How do I only run a script when a file has changed?\n" + - "\n" + - "A common example of this is that you're using [Homebrew](https://brew.sh/) and\n" + - "have `.Brewfile` listing all the packages that you want installed and only want\n" + - "to run `brew bundle --global` when the contents of `.Brewfile` have changed.\n" + - "\n" + - "chezmoi has two types of scripts: scripts that run every time, and scripts that\n" + - "only run when their contents change. chezmoi does not have a mechanism to run a\n" + - "script when an arbitrary file has changed, but there are some ways to achieve\n" + - "the desired behavior:\n" + - "\n" + - "1. Have the script create `.Brewfile` instead of chezmoi, e.g. in your\n" + - " `run_once_install-packages`:\n" + - "\n" + - " ```sh\n" + - " #!/bin/sh\n" + - "\n" + - " cat > $HOME/.Brewfile <<EOF\n" + - " brew \"imagemagick\"\n" + - " brew \"openssl\"\n" + - " EOF\n" + - "\n" + - " brew bundle --global\n" + - " ```\n" + - "\n" + - "2. Don't use `.Brewfile`, and instead install the packages explicitly in\n" + - " `run_once_install-packages`:\n" + - "\n" + - " ```sh\n" + - " #!/bin/sh\n" + - "\n" + - " brew install imagemagick || true\n" + - " brew install openssl || true\n" + - " ```\n" + - "\n" + - " The `|| true` is necessary because `brew install` exits with failure if the\n" + - " package is already installed.\n" + - "\n" + - "3. Use a script that runs every time (not just once) and rely on `brew bundle\n" + - " --global` being idempotent.\n" + - "\n" + - "4. Use a script that runs every time, records a checksum of `.Brewfile` in\n" + - " another file, and only runs `brew bundle --global` if the checksum has\n" + - " changed, and updates the recorded checksum after.\n" + - "\n" + - "## I've made changes to both the destination state and the source state that I want to keep. How can I keep them both?\n" + - "\n" + - "`chezmoi merge` will open a merge tool to resolve differences between the source\n" + - "state, target state, and destination state. Copy the changes you want to keep in\n" + - "to the source state.\n" + - "\n" + - "## Why does chezmoi convert all my template variables to lowercase?\n" + - "\n" + - "This is due to a feature in\n" + - "[`github.com/spf13/viper`](https://github.com/spf13/viper), the library that\n" + - "chezmoi uses to read its configuration file. For more information see [this\n" + - "GitHub issue](https://github.com/twpayne/chezmoi/issues/463).\n" + - "\n" + - "## chezmoi makes `~/.ssh/config` group writeable. How do I stop this?\n" + - "\n" + - "By default, chezmoi uses your system's umask when creating files. On most\n" + - "systems the default umask is `022` but some systems use `002`, which means\n" + - "that files and directories are group writeable by default.\n" + - "\n" + - "You can override this for chezmoi by setting the `umask` configuration variable\n" + - "in your configuration file, for example:\n" + - "\n" + - " umask = 0o022\n" + - "\n" + - "Note that this will apply to all files and directories that chezmoi manages and\n" + - "will ensure that none of them are group writeable. It is not currently possible\n" + - "to control group write permissions for individual files or directories. Please\n" + - "[open an issue on\n" + - "GitHub](https://github.com/twpayne/chezmoi/issues/new?assignees=&labels=enhancement&template=02_feature_request.md&title=)\n" + - "if you need this.\n" + - "\n" + - "## Why doesn't chezmoi use symlinks like GNU Stow?\n" + - "\n" + - "Symlinks are first class citizens in chezmoi: chezmoi supports creating them,\n" + - "updating them, removing them, and even more advanced features not found\n" + - "elsewhere like having the same symlink point to different targets on different\n" + - "machines by using templates.\n" + - "\n" + - "With chezmoi, you only use symlinks where you really need a symlink, in contrast\n" + - "to some other dotfile managers (e.g. GNU Stow) which require the use of symlinks\n" + - "as a layer of indirection between a dotfile's location (which can be anywhere in\n" + - "your home directory) and a dotfile's content (which needs to be in a centralized\n" + - "directory that you manage with version control). chezmoi solves this problem in\n" + - "a different way.\n" + - "\n" + - "Instead of using a symlink to redirect from the dotfile's location to the\n" + - "centralized directory, chezmoi generates the dotfile in its final location from\n" + - "the contents of the centralized directory. Not only is no symlink is needed,\n" + - "this has the advantages that chezmoi is better able to cope with differences\n" + - "from machine to machine (as a dotfile's contents can be unique to that machine)\n" + - "and the dotfiles that chezmoi creates are just regular files. There's nothing\n" + - "special about dotfiles managed by chezmoi, whereas dotfiles managed with GNU\n" + - "Stow are special because they're actually symlinks to somewhere else.\n" + - "\n" + - "The only advantage to using GNU Stow-style symlinks is that changes that you\n" + - "make to the dotfile's contents in the centralized directory are immediately\n" + - "visible, whereas chezmoi currently requires you to run `chezmoi apply` or\n" + - "`chezmoi edit --apply`. chezmoi will likely get an alternative solution to this\n" + - "too, see [#752](https://github.com/twpayne/chezmoi/issues/752).\n" + - "\n" + - "You can configure chezmoi to work like GNU Stow and have it create a set of\n" + - "symlinks back to a central directory, but this currently requires a bit of\n" + - "manual work (as described in\n" + - "[#167](https://github.com/twpayne/chezmoi/issues/167)). chezmoi might get some\n" + - "automation to help (see [#886](https://github.com/twpayne/chezmoi/issues/886)\n" + - "for example) but it does need some convincing use cases that demonstrate that a\n" + - "symlink from a dotfile's location to its contents in a central directory is\n" + - "better than just having the correct dotfile contents.\n" + - "\n" + - "## Do I have to use `chezmoi edit` to edit my dotfiles?\n" + - "\n" + - "No. `chezmoi edit` is a convenience command that has a couple of useful\n" + - "features, but you don't have to use it. You can also run `chezmoi cd` and then\n" + - "just edit the files in the source state directly. After saving an edited file\n" + - "you can run `chezmoi diff` to check what effect the changes would have, and run\n" + - "`chezmoi apply` if you're happy with them.\n" + - "\n" + - "`chezmoi edit` provides the following useful features:\n" + - "* It opens the correct file in the source state for you, so you don't have to\n" + - " know anything about source state attributes.\n" + - "* If the dotfille is encrypted in the source state, then `chezmoi edit` will\n" + - " decrypt it to a private directory, open that file in your `$EDITOR`, and then\n" + - " re-encrypt the file when you quit your editor. That makes encryption more\n" + - " transparent to the user. With the `--diff` and `--apply` options you can see what\n" + - " would change and apply those changes without having to run `chezmoi diff` or\n" + - " `chezmoi apply`. Note also that the arguments to `chezmoi edit` are the files in\n" + - " their target location.\n" + - "\n" + - "## Can I change how chezmoi's source state is represented on disk?\n" + - "\n" + - "There are a number of criticisms of how chezmoi's source state is represented on\n" + - "disk:\n" + - "\n" + - "1. The source file naming system cannot handle all possible filenames.\n" + - "2. Not all possible file permissions can be represented.\n" + - "3. The long source file names are verbose.\n" + - "4. Everything is in a single directory, which can end up containing many entries.\n" + - "\n" + - "chezmoi's source state representation is a deliberate, practical compromise.\n" + - "\n" + - "Certain target filenames, for example `~/dot_example`, are incompatible with\n" + - "chezmoi's\n" + - "[attributes](https://github.com/twpayne/chezmoi/blob/master/docs/REFERENCE.md#source-state-attributes)\n" + - "used in the source state. In practice, dotfile filenames are unlikely to\n" + - "conflict with chezmoi's attributes. If this does cause a genuine problem for\n" + - "you, please [open an issue on\n" + - "GitHub](https://github.com/twpayne/chezmoi/issues/new/choose).\n" + - "\n" + - "The `dot_` attribute makes it transparent which dotfiles are managed by chezmoi\n" + - "and which files are ignored by chezmoi. chezmoi ignores all files and\n" + - "directories that start with `.` so no special whitelists are needed for version\n" + - "control systems and their control files (e.g. `.git` and `.gitignore`).\n" + - "\n" + - "chezmoi needs per-file metadata to know how to interpret the source file's\n" + - "contents, for example to know when the source file is a template or if the\n" + - "file's contents are encrypted. By storing this metadata in the filename, the\n" + - "metadata is unambiguously associated with a single file and adding, updating, or\n" + - "removing a single file touches only a single file in the source state. Changes\n" + - "to the metadata (e.g. `chezmoi chattr +template *target*`) are simple file\n" + - "renames and isolated to the affected file.\n" + - "\n" + - "If chezmoi were to, say, use a common configuration file listing which files\n" + - "were templates and/or encrypted, then changes to any file would require updates\n" + - "to the common configuration file. Automating updates to configuration files\n" + - "requires a round trip (read config file, update config, write config) and it is\n" + - "not always possible preserve comments and formatting.\n" + - "\n" + - "chezmoi's attributes of `executable_` and `private_` only allow a the file\n" + - "permissions `0o644`, `0o755`, `0o600`, and `0o700` to be represented.\n" + - "Directories can only have permissions `0o755` or `0o700`. In practice, these\n" + - "cover all permissions typically used for dotfiles. If this does cause a genuine\n" + - "problem for you, please [open an issue on\n" + - "GitHub](https://github.com/twpayne/chezmoi/issues/new/choose).\n" + - "\n" + - "File permissions and modes like `executable_`, `private_`, and `symlink_` could\n" + - "also be stored in the filesystem, rather than in the filename. However, this\n" + - "requires the permissions to be preserved and handled by the underlying version\n" + - "control system and filesystem. chezmoi provides first-class support for Windows,\n" + - "where the `executable_` and `private_` attributes have no direct equivalents and\n" + - "symbolic links are not always permitted. Some version control systems do not\n" + - "preserve file permissions or handle symbolic links. By using regular files and\n" + - "directories, chezmoi avoids variations in the operating system, version control\n" + - "system, and filesystem making it both more robust and more portable.\n" + - "\n" + - "chezmoi uses a 1:1 mapping between entries in the source state and entries in\n" + - "the target state. This mapping is bi-directional and unambiguous.\n" + - "\n" + - "However, this also means that dotfiles that in the same directory in the target\n" + - "state must be in the same directory in the source state. In particular, every\n" + - "entry managed by chezmoi in the root of your home directory has a corresponding\n" + - "entry in the root of your source directory, which can mean that you end up with\n" + - "a lot of entries in the root of your source directory.\n" + - "\n" + - "If chezmoi were to permit, say, multiple separate source directories (so you\n" + - "could, say, put `dot_bashrc` in a `bash/` subdirectory, and `dot_vimrc` in a\n" + - "`vim/` subdirectory, but have `chezmoi apply` map these to `~/.bashrc` and\n" + - "`~/.vimrc` in the root of your home directory) then the mapping between source\n" + - "and target states is no longer bidirectional nor unambiguous, which\n" + - "significantly increases complexity and requires more user interaction. For\n" + - "example, if both `bash/dot_bashrc` and `vim/dot_bashrc` exist, what should be\n" + - "the contents of `~/.bashrc`? If you run `chezmoi add ~/.zshrc`, should\n" + - "`dot_zshrc` be stored in the source `bash/` directory, the source `vim/`\n" + - "directory, or somewhere else? How does the user communicate their preferences?\n" + - "\n" + - "chezmoi has many users and any changes to the source state representation must\n" + - "be backwards-compatible.\n" + - "\n" + - "In summary, chezmoi's source state representation is a compromise with both\n" + - "advantages and disadvantages. Changes to the representation will be considered,\n" + - "but must meet the following criteria, in order of importance:\n" + - "\n" + - "1. Be fully backwards-compatible for existing users.\n" + - "2. Fix a genuine problem encountered in practice.\n" + - "3. Be independent of the underlying operating system, version control system, and\n" + - " filesystem.\n" + - "4. Not add significant extra complexity to the user interface or underlying\n" + - " implementation.\n" + - "\n" + - "## gpg encryption fails. What could be wrong?\n" + - "\n" + - "The `gpg.recipient` key should be ultimately trusted, otherwise encryption will\n" + - "fail because gpg will prompt for input, which chezmoi does not handle. You can\n" + - "check the trust level by running:\n" + - "\n" + - " gpg --export-ownertrust\n" + - "\n" + - "The trust level for the recipient's key should be `6`. If it is not, you can\n" + - "change the trust level by running:\n" + - "\n" + - " gpg --edit-key $recipient\n" + - "\n" + - "Enter `trust` at the prompt and chose `5 = I trust ultimately`.\n" + - "\n" + - "## chezmoi reports \"user: lookup userid NNNNN: input/output error\"\n" + - "\n" + - "This is likely because the chezmoi binary you are using was statically compiled\n" + - "with [musl](https://musl.libc.org/) and the machine you are running on uses\n" + - "LDAP or NIS.\n" + - "\n" + - "The immediate fix is to use a package built for your distriubtion (e.g a `.deb`\n" + - "or `.rpm`) which is linked against glibc and includes LDAP/NIS support instead\n" + - "of the statically-compiled binary.\n" + - "\n" + - "If the problem still persists, then please [open an issue on\n" + - "GitHub](https://github.com/twpayne/chezmoi/issues/new/choose).\n" + - "\n" + - "## I'm getting errors trying to build chezmoi from source\n" + - "\n" + - "chezmoi requires Go version 1.14 or later and Go modules enabled. You can check\n" + - "the version of Go with:\n" + - "\n" + - " go version\n" + - "\n" + - "Enable Go modules by setting `GO111MODULE=on` when running `go get`:\n" + - "\n" + - " GO111MODULE=on go get -u github.com/twpayne/chezmoi\n" + - "\n" + - "For more details on building chezmoi, see the [Contributing\n" + - "Guide](CONTRIBUTING.md).\n" + - "\n" + - "## What inspired chezmoi?\n" + - "\n" + - "chezmoi was inspired by [Puppet](https://puppet.com/), but created because\n" + - "Puppet is a slow overkill for managing your personal configuration files. The\n" + - "focus of chezmoi will always be personal home directory management. If your\n" + - "needs grow beyond that, switch to a whole system configuration management tool.\n" + - "\n" + - "## Why not use Ansible/Chef/Puppet/Salt, or similar to manage my dotfiles instead?\n" + - "\n" + - "Whole system management tools are more than capable of managing your dotfiles,\n" + - "but are large systems that entail several disadvantages. Compared to whole\n" + - "system management tools, chezmoi offers:\n" + - "\n" + - "* Small, focused feature set designed for dotfiles. There's simply less to learn\n" + - " with chezmoi compared to whole system management tools.\n" + - "* Easy installation and execution on every platform, without root access.\n" + - " Installing chezmoi requires only copying a single binary file with no external\n" + - " dependencies. Executing chezmoi just involves running the binary. In contrast,\n" + - " installing and running a whole system management tools typically requires\n" + - " installing a scripting language runtime, several packages, and running a\n" + - " system service, all typically requiring root access.\n" + - "\n" + - "chezmoi's focus and simple installation means that it runs almost everywhere:\n" + - "from tiny ARM-based Linux systems to Windows desktops, from inside lightweight\n" + - "containers to FreeBSD-based virtual machines in the cloud.\n" + - "\n" + - "## Can I use chezmoi to manage files outside my home directory?\n" + - "\n" + - "In practice, yes, you can, but this is strongly discouraged beyond using your\n" + - "system's package manager to install the packages you need.\n" + - "\n" + - "chezmoi is designed to operate on your home directory, and is explicitly not a\n" + - "full system configuration management tool. That said, there are some ways to\n" + - "have chezmoi manage a few files outside your home directory.\n" + - "\n" + - "chezmoi's scripts can execute arbitrary commands, so you can use a `run_` script\n" + - "that is run every time you run `chezmoi apply`, to, for example:\n" + - "\n" + - "* Make the target file outside your home directory a symlink to a file managed\n" + - " by chezmoi in your home directory.\n" + - "* Copy a file managed by chezmoi inside your home directory to the target file.\n" + - "* Execute a template with `chezmoi execute-template --output=filename template`\n" + - " where `filename` is outside the target directory.\n" + - "\n" + - "chezmoi executes all scripts as the user executing chezmoi, so you may need to\n" + - "add extra privilege elevation commands like `sudo` or `PowerShell start -verb\n" + - "runas -wait` to your script.\n" + - "\n" + - "chezmoi, by default, operates on your home directory but this can be overridden\n" + - "with the `--destination` command line flag or by specifying `destDir` in your\n" + - "config file, and could even be the root directory (`/` or `C:\\`). This allows\n" + - "you, in theory, to use chezmoi to manage any file in your filesystem, but this\n" + - "usage is extremely strongly discouraged.\n" + - "\n" + - "If your needs extend beyond modifying a handful of files outside your target\n" + - "system, then existing configuration management tools like\n" + - "[Puppet](https://puppet.com/), [Chef](https://chef.io/),\n" + - "[Ansible](https://www.ansible.com/), and [Salt](https://www.saltstack.com/) are\n" + - "much better suited - and of course can be called from a chezmoi `run_` script.\n" + - "Put your Puppet Manifests, Chef Recipes, Ansible Modules, and Salt Modules in a\n" + - "directory ignored by `.chezmoiignore` so they do not pollute your home\n" + - "directory.\n" + - "\n" + - "## Where does the name \"chezmoi\" come from?\n" + - "\n" + - "\"chezmoi\" splits to \"chez moi\" and pronounced /ʃeɪ mwa/ (shay-moi) meaning \"at\n" + - "my house\" in French. It's seven letters long, which is an appropriate length for\n" + - "a command that is only run occasionally.\n" + - "\n" + - "## What other questions have been asked about chezmoi?\n" + - "\n" + - "See the [issues on\n" + - "GitHub](https://github.com/twpayne/chezmoi/issues?utf8=%E2%9C%93&q=is%3Aissue+sort%3Aupdated-desc+label%3Asupport).\n" + - "\n" + - "## Where do I ask a question that isn't answered here?\n" + - "\n" + - "Please [open an issue on GitHub](https://github.com/twpayne/chezmoi/issues/new/choose).\n" + - "\n" + - "## I like chezmoi. How do I say thanks?\n" + - "\n" + - "Thank you! chezmoi was written to scratch a personal itch, and I'm very happy\n" + - "that it's useful to you. Please give [chezmoi a star on\n" + - "GitHub](https://github.com/twpayne/chezmoi/stargazers), and if you're happy to\n" + - "share your public dotfile repo then [tag it with\n" + - "`chezmoi`](https://github.com/topics/chezmoi?o=desc&s=updated). [Contributions\n" + - "are very\n" + - "welcome](https://github.com/twpayne/chezmoi/blob/master/docs/CONTRIBUTING.md)\n" + - "and every [bug report, support request, and feature\n" + - "request](https://github.com/twpayne/chezmoi/issues/new/choose) helps make\n" + - "chezmoi better. Thank you :)\n" + - "\n") - assets["docs/HOWTO.md"] = []byte("" + - "# chezmoi How-To Guide\n" + - "\n" + - "<!--- toc --->\n" + - "* [Use a hosted repo to manage your dotfiles across multiple machines](#use-a-hosted-repo-to-manage-your-dotfiles-across-multiple-machines)\n" + - "* [Pull the latest changes from your repo and apply them](#pull-the-latest-changes-from-your-repo-and-apply-them)\n" + - "* [Pull the latest changes from your repo and see what would change, without actually applying the changes](#pull-the-latest-changes-from-your-repo-and-see-what-would-change-without-actually-applying-the-changes)\n" + - "* [Automatically commit and push changes to your repo](#automatically-commit-and-push-changes-to-your-repo)\n" + - "* [Use templates to manage files that vary from machine to machine](#use-templates-to-manage-files-that-vary-from-machine-to-machine)\n" + - "* [Use completely separate config files on different machines](#use-completely-separate-config-files-on-different-machines)\n" + - " * [Without using symlinks](#without-using-symlinks)\n" + - "* [Create a config file on a new machine automatically](#create-a-config-file-on-a-new-machine-automatically)\n" + - "* [Have chezmoi create a directory, but ignore its contents](#have-chezmoi-create-a-directory-but-ignore-its-contents)\n" + - "* [Ensure that a target is removed](#ensure-that-a-target-is-removed)\n" + - "* [Include a subdirectory from another repository, like Oh My Zsh](#include-a-subdirectory-from-another-repository-like-oh-my-zsh)\n" + - "* [Handle configuration files which are externally modified](#handle-configuration-files-which-are-externally-modified)\n" + - "* [Handle different file locations on different systems with the same contents](#handle-different-file-locations-on-different-systems-with-the-same-contents)\n" + - "* [Keep data private](#keep-data-private)\n" + - " * [Use Bitwarden to keep your secrets](#use-bitwarden-to-keep-your-secrets)\n" + - " * [Use gopass to keep your secrets](#use-gopass-to-keep-your-secrets)\n" + - " * [Use gpg to keep your secrets](#use-gpg-to-keep-your-secrets)\n" + - " * [Use KeePassXC to keep your secrets](#use-keepassxc-to-keep-your-secrets)\n" + - " * [Use a keyring to keep your secrets](#use-a-keyring-to-keep-your-secrets)\n" + - " * [Use LastPass to keep your secrets](#use-lastpass-to-keep-your-secrets)\n" + - " * [Use 1Password to keep your secrets](#use-1password-to-keep-your-secrets)\n" + - " * [Use pass to keep your secrets](#use-pass-to-keep-your-secrets)\n" + - " * [Use Vault to keep your secrets](#use-vault-to-keep-your-secrets)\n" + - " * [Use a generic tool to keep your secrets](#use-a-generic-tool-to-keep-your-secrets)\n" + - " * [Use templates variables to keep your secrets](#use-templates-variables-to-keep-your-secrets)\n" + - "* [Use scripts to perform actions](#use-scripts-to-perform-actions)\n" + - " * [Understand how scripts work](#understand-how-scripts-work)\n" + - " * [Install packages with scripts](#install-packages-with-scripts)\n" + - "* [Use chezmoi with GitHub Codespaces, Visual Studio Codespaces, Visual Studio Code Remote - Containers](#use-chezmoi-with-github-codespaces-visual-studio-codespaces-visual-studio-code-remote---containers)\n" + - "* [Detect Windows Subsystem for Linux (WSL)](#detect-windows-subsystem-for-linux-wsl)\n" + - "* [Run a PowerShell script as admin on Windows](#run-a-powershell-script-as-admin-on-windows)\n" + - "* [Import archives](#import-archives)\n" + - "* [Export archives](#export-archives)\n" + - "* [Use a non-git version control system](#use-a-non-git-version-control-system)\n" + - "* [Customize the `diff` command](#customize-the-diff-command)\n" + - "* [Use a merge tool other than vimdiff](#use-a-merge-tool-other-than-vimdiff)\n" + - "* [Migrate from a dotfile manager that uses symlinks](#migrate-from-a-dotfile-manager-that-uses-symlinks)\n" + - "\n" + - "## Use a hosted repo to manage your dotfiles across multiple machines\n" + - "\n" + - "chezmoi relies on your version control system and hosted repo to share changes\n" + - "across multiple machines. You should create a repo on the source code repository\n" + - "of your choice (e.g. [Bitbucket](https://bitbucket.org),\n" + - "[GitHub](https://github.com/), or [GitLab](https://gitlab.com), many people call\n" + - "their repo `dotfiles`) and push the repo in the source directory here. For\n" + - "example:\n" + - "\n" + - " chezmoi cd\n" + - " git remote add origin https://github.com/username/dotfiles.git\n" + - " git push -u origin master\n" + - " exit\n" + - "\n" + - "On another machine you can checkout this repo:\n" + - "\n" + - " chezmoi init https://github.com/username/dotfiles.git\n" + - "\n" + - "You can then see what would be changed:\n" + - "\n" + - " chezmoi diff\n" + - "\n" + - "If you're happy with the changes then apply them:\n" + - "\n" + - " chezmoi apply\n" + - "\n" + - "The above commands can be combined into a single init, checkout, and apply:\n" + - "\n" + - " chezmoi init --apply --verbose https://github.com/username/dotfiles.git\n" + - "\n" + - "## Pull the latest changes from your repo and apply them\n" + - "\n" + - "You can pull the changes from your repo and apply them in a single command:\n" + - "\n" + - " chezmoi update\n" + - "\n" + - "This runs `git pull --rebase` in your source directory and then `chezmoi apply`.\n" + - "\n" + - "## Pull the latest changes from your repo and see what would change, without actually applying the changes\n" + - "\n" + - "Run:\n" + - "\n" + - " chezmoi source pull -- --rebase && chezmoi diff\n" + - "\n" + - "This runs `git pull --rebase` in your source directory and `chezmoi\n" + - "diff` then shows the difference between the target state computed from your\n" + - "source directory and the actual state.\n" + - "\n" + - "If you're happy with the changes, then you can run\n" + - "\n" + - " chezmoi apply\n" + - "\n" + - "to apply them.\n" + - "\n" + - "## Automatically commit and push changes to your repo\n" + - "\n" + - "chezmoi can automatically commit and push changes to your source directory to\n" + - "your repo. This feature is disabled by default. To enable it, add the following\n" + - "to your config file:\n" + - "\n" + - " [sourceVCS]\n" + - " autoCommit = true\n" + - " autoPush = true\n" + - "\n" + - "Whenever a change is made to your source directory, chezmoi will commit the\n" + - "changes with an automatically-generated commit message (if `autoCommit` is true)\n" + - "and push them to your repo (if `autoPush` is true). `autoPush` implies\n" + - "`autoCommit`, i.e. if `autoPush` is true then chezmoi will auto-commit your\n" + - "changes. If you only set `autoCommit` to true then changes will be committed but\n" + - "not pushed.\n" + - "\n" + - "Be careful when using `autoPush`. If your dotfiles repo is public and you\n" + - "accidentally add a secret in plain text, that secret will be pushed to your\n" + - "public repo.\n" + - "\n" + - "## Use templates to manage files that vary from machine to machine\n" + - "\n" + - "The primary goal of chezmoi is to manage configuration files across multiple\n" + - "machines, for example your personal macOS laptop, your work Ubuntu desktop, and\n" + - "your work Linux laptop. You will want to keep much configuration the same across\n" + - "these, but also need machine-specific configurations for email addresses,\n" + - "credentials, etc. chezmoi achieves this functionality by using\n" + - "[`text/template`](https://pkg.go.dev/text/template) for the source state where\n" + - "needed.\n" + - "\n" + - "For example, your home `~/.gitconfig` on your personal machine might look like:\n" + - "\n" + - " [user]\n" + - " email = \"[email protected]\"\n" + - "\n" + - "Whereas at work it might be:\n" + - "\n" + - " [user]\n" + - " email = \"[email protected]\"\n" + - "\n" + - "To handle this, on each machine create a configuration file called\n" + - "`~/.config/chezmoi/chezmoi.toml` defining variables that might vary from machine\n" + - "to machine. For example, for your home machine:\n" + - "\n" + - " [data]\n" + - " email = \"[email protected]\"\n" + - "\n" + - "Note that all variable names will be converted to lowercase. This is due to a\n" + - "feature of a library used by chezmoi.\n" + - "\n" + - "If you intend to store private data (e.g. access tokens) in\n" + - "`~/.config/chezmoi/chezmoi.toml`, make sure it has permissions `0600`.\n" + - "\n" + - "If you prefer, you can use any format supported by\n" + - "[Viper](https://github.com/spf13/viper) for your configuration file. This\n" + - "includes JSON, YAML, and TOML. Variable names must start with a letter and be\n" + - "followed by zero or more letters or digits.\n" + - "\n" + - "Then, add `~/.gitconfig` to chezmoi using the `--autotemplate` flag to turn it\n" + - "into a template and automatically detect variables from the `data` section\n" + - "of your `~/.config/chezmoi/chezmoi.toml` file:\n" + - "\n" + - " chezmoi add --autotemplate ~/.gitconfig\n" + - "\n" + - "You can then open the template (which will be saved in the file\n" + - "`~/.local/share/chezmoi/dot_gitconfig.tmpl`):\n" + - "\n" + - " chezmoi edit ~/.gitconfig\n" + - "\n" + - "The file should look something like:\n" + - "\n" + - " [user]\n" + - " email = \"{{ .email }}\"\n" + - "\n" + - "To disable automatic variable detection, use the `--template` or `-T` option to\n" + - "`chezmoi add` instead of `--autotemplate`.\n" + - "\n" + - "Templates are often used to capture machine-specific differences. For example,\n" + - "in your `~/.local/share/chezmoi/dot_bashrc.tmpl` you might have:\n" + - "\n" + - " # common config\n" + - " export EDITOR=vi\n" + - "\n" + - " # machine-specific configuration\n" + - " {{- if eq .chezmoi.hostname \"work-laptop\" }}\n" + - " # this will only be included in ~/.bashrc on work-laptop\n" + - " {{- end }}\n" + - "\n" + - "For a full list of variables, run:\n" + - "\n" + - " chezmoi data\n" + - "\n" + - "For more advanced usage, you can use the full power of the\n" + - "[`text/template`](https://pkg.go.dev/text/template) language. chezmoi includes\n" + - "all of the text functions from [sprig](http://masterminds.github.io/sprig/) and\n" + - "its own [functions for interacting with password\n" + - "managers](https://github.com/twpayne/chezmoi/blob/master/docs/REFERENCE.md#template-functions).\n" + - "\n" + - "Templates can be executed directly from the command line, without the need to\n" + - "create a file on disk, with the `execute-template` command, for example:\n" + - "\n" + - " chezmoi execute-template '{{ .chezmoi.os }}/{{ .chezmoi.arch }}'\n" + - "\n" + - "This is useful when developing or debugging templates.\n" + - "\n" + - "Some password managers allow you to store complete files. The files can be\n" + - "retrieved with chezmoi's template functions. For example, if you have a file\n" + - "stored in 1Password with the UUID `uuid` then you can retrieve it with the\n" + - "template:\n" + - "\n" + - " {{- onepasswordDocument \"uuid\" -}}\n" + - "\n" + - "The `-`s inside the brackets remove any whitespace before or after the template\n" + - "expression, which is useful if your editor has added any newlines.\n" + - "\n" + - "If, after executing the template, the file contents are empty, the target file\n" + - "will be removed. This can be used to ensure that files are only present on\n" + - "certain machines. If you want an empty file to be created anyway, you will need\n" + - "to give it an `empty_` prefix.\n" + - "\n" + - "For coarser-grained control of files and entire directories managed on different\n" + - "machines, or to exclude certain files completely, you can create\n" + - "`.chezmoiignore` files in the source directory. These specify a list of patterns\n" + - "that chezmoi should ignore, and are interpreted as templates. An example\n" + - "`.chezmoiignore` file might look like:\n" + - "\n" + - " README.md\n" + - " {{- if ne .chezmoi.hostname \"work-laptop\" }}\n" + - " .work # only manage .work on work-laptop\n" + - " {{- end }}\n" + - "\n" + - "The use of `ne` (not equal) is deliberate. What we want to achieve is \"only\n" + - "install `.work` if hostname is `work-laptop`\" but chezmoi installs everything by\n" + - "default, so we have to turn the logic around and instead write \"ignore `.work`\n" + - "unless the hostname is `work-laptop`\".\n" + - "\n" + - "Patterns can be excluded by prefixing them with a `!`, for example:\n" + - "\n" + - " f*\n" + - " !foo\n" + - "\n" + - "will ignore all files beginning with an `f` except `foo`.\n" + - "\n" + - "## Use completely separate config files on different machines\n" + - "\n" + - "chezmoi's template functionality allows you to change a file's contents based on\n" + - "any variable. For example, if you want `~/.bashrc` to be different on Linux and\n" + - "macOS you would create a file in the source state called `dot_bashrc.tmpl`\n" + - "containing:\n" + - "\n" + - "```\n" + - "{{ if eq .chezmoi.os \"darwin\" -}}\n" + - "# macOS .bashrc contents\n" + - "{{ else if eq .chezmoi.os \"linux\" -}}\n" + - "# Linux .bashrc contents\n" + - "{{ end -}}\n" + - "```\n" + - "\n" + - "However, if the differences between the two versions are so large that you'd\n" + - "prefer to use completely separate files in the source state, you can achieve\n" + - "this using a symbolic link template. Create the following files:\n" + - "\n" + - "`symlink_dot_bashrc.tmpl`:\n" + - "\n" + - "```\n" + - ".bashrc_{{ .chezmoi.os }}\n" + - "```\n" + - "\n" + - "`dot_bashrc_darwin`:\n" + - "\n" + - "```\n" + - "# macOS .bashrc contents\n" + - "```\n" + - "\n" + - "`dot_bashrc_linux`:\n" + - "\n" + - "```\n" + - "# Linux .bashrc contents\n" + - "```\n" + - "\n" + - "`.chezmoiignore`\n" + - "\n" + - "```\n" + - "{{ if ne .chezmoi.os \"darwin\" }}\n" + - ".bashrc_darwin\n" + - "{{ end }}\n" + - "{{ if ne .chezmoi.os \"linux\" }}\n" + - ".bashrc_linux\n" + - "{{ end }}\n" + - "```\n" + - "\n" + - "This will make `~/.bashrc` a symlink to `.bashrc_darwin` on `darwin` and to\n" + - "`.bashrc_linux` on `linux`. The `.chezmoiignore` configuration ensures that only\n" + - "the OS-specific `.bashrc_os` file will be installed on each OS.\n" + - "\n" + - "### Without using symlinks\n" + - "\n" + - "The same thing can be achieved using the include function.\n" + - "\n" + - "`dot_bashrc.tmpl`\n" + - "\n" + - "\t{{ if eq .chezmoi.os \"darwin\" }}\n" + - "\t{{ include \".bashrc_darwin\" }}\n" + - "\t{{ end }}\n" + - "\t{{ if eq .chezmoi.os \"linux\" }}\n" + - "\t{{ include \".bashrc_linux\" }}\n" + - "\t{{ end }}\n" + - "\n" + - "\n" + - "## Create a config file on a new machine automatically\n" + - "\n" + - "`chezmoi init` can also create a config file automatically, if one does not\n" + - "already exist. If your repo contains a file called `.chezmoi.<format>.tmpl`\n" + - "where *format* is one of the supported config file formats (e.g. `json`, `toml`,\n" + - "or `yaml`) then `chezmoi init` will execute that template to generate your\n" + - "initial config file.\n" + - "\n" + - "Specifically, if you have `.chezmoi.toml.tmpl` that looks like this:\n" + - "\n" + - " {{- $email := promptString \"email\" -}}\n" + - " [data]\n" + - " email = \"{{ $email }}\"\n" + - "\n" + - "Then `chezmoi init` will create an initial `chezmoi.toml` using this template.\n" + - "`promptString` is a special function that prompts the user (you) for a value.\n" + - "\n" + - "To test this template, use `chezmoi execute-template` with the `--init` and\n" + - "`--promptString` flags, for example:\n" + - "\n" + - " chezmoi execute-template --init --promptString [email protected] < ~/.local/share/chezmoi/.chezmoi.toml.tmpl\n" + - "\n" + - "## Have chezmoi create a directory, but ignore its contents\n" + - "\n" + - "If you want chezmoi to create a directory, but ignore its contents, say `~/src`,\n" + - "first run:\n" + - "\n" + - " mkdir -p $(chezmoi source-path)/src\n" + - "\n" + - "This creates the directory in the source state, which means that chezmoi will\n" + - "create it (if it does not already exist) when you run `chezmoi apply`.\n" + - "\n" + - "However, as this is an empty directory it will be ignored by git. So, create a\n" + - "file in the directory in the source state that will be seen by git (so git does\n" + - "not ignore the directory) but ignored by chezmoi (so chezmoi does not include it\n" + - "in the target state):\n" + - "\n" + - " touch $(chezmoi source-path)/src/.keep\n" + - "\n" + - "chezmoi automatically creates `.keep` files when you add an empty directory with\n" + - "`chezmoi add`.\n" + - "\n" + - "## Ensure that a target is removed\n" + - "\n" + - "Create a file called `.chezmoiremove` in the source directory containing a list\n" + - "of patterns of files to remove. When you run\n" + - "\n" + - " chezmoi apply --remove\n" + - "\n" + - "chezmoi will remove anything in the target directory that matches the pattern.\n" + - "As this command is potentially dangerous, you should run chezmoi in verbose,\n" + - "dry-run mode beforehand to see what would be removed:\n" + - "\n" + - " chezmoi apply --remove --dry-run --verbose\n" + - "\n" + - "`.chezmoiremove` is interpreted as a template, so you can remove different files\n" + - "on different machines. Negative matches (patterns prefixed with a `!`) or\n" + - "targets listed in `.chezmoiignore` will never be removed.\n" + - "\n" + - "## Include a subdirectory from another repository, like Oh My Zsh\n" + - "\n" + - "To include a subdirectory from another repository, e.g. [Oh My\n" + - "Zsh](https://github.com/robbyrussell/oh-my-zsh), you cannot use git submodules\n" + - "because chezmoi uses its own format for the source state and Oh My Zsh is not\n" + - "distributed in this format. Instead, you can use the `import` command to import\n" + - "a snapshot from a tarball:\n" + - "\n" + - " curl -s -L -o oh-my-zsh-master.tar.gz https://github.com/robbyrussell/oh-my-zsh/archive/master.tar.gz\n" + - " chezmoi import --strip-components 1 --destination ${HOME}/.oh-my-zsh oh-my-zsh-master.tar.gz\n" + - "\n" + - "Add `oh-my-zsh-master.tar.gz` to `.chezmoiignore` if you run these commands in\n" + - "your source directory so that chezmoi doesn't try to copy the tarball anywhere.\n" + - "\n" + - "Disable Oh My Zsh auto-updates by setting `DISABLE_AUTO_UPDATE=\"true\"` in\n" + - "`~/.zshrc`. Auto updates will cause the `~/.oh-my-zsh` directory to drift out of\n" + - "sync with chezmoi's source state. To update Oh My Zsh, re-run the `curl` and\n" + - "`chezmoi import` commands above.\n" + - "\n" + - "## Handle configuration files which are externally modified\n" + - "\n" + - "Some programs modify their configuration files. When you next run `chezmoi\n" + - "apply`, any modifications made by the program will be lost.\n" + - "\n" + - "You can track changes to these files by replacing with a symlink back to a file\n" + - "in your source directory, which is under version control. Here is a worked\n" + - "example for VSCode's `settings.json` on Linux:\n" + - "\n" + - "Copy the configuration file to your source directory:\n" + - "\n" + - " cp ~/.config/Code/User/settings.json $(chezmoi source-path)\n" + - "\n" + - "Tell chezmoi to ignore this file:\n" + - "\n" + - " echo settings.json >> $(chezmoi source-path)/.chezmoiignore\n" + - "\n" + - "Tell chezmoi that `~/.config/Code/User/settings.json` should be a symlink to the\n" + - "file in your source directory:\n" + - "\n" + - " mkdir -p $(chezmoi source-path)/private_dot_config/private_Code/User\n" + - " echo -n \"{{ .chezmoi.sourceDir }}/settings.json\" > $(chezmoi source-path)/private_dot_config/private_Code/User/symlink_settings.json.tmpl\n" + - "\n" + - "The prefix `private_` is used because the `~/.config` and `~/.config/Code`\n" + - "directories are private by default.\n" + - "\n" + - "Apply the changes:\n" + - "\n" + - " chezmoi apply -v\n" + - "\n" + - "Now, when the program modifies its configuration file it will modify the file in\n" + - "the source state instead.\n" + - "\n" + - "## Handle different file locations on different systems with the same contents\n" + - "\n" + - "If you want to have the same file contents in different locations on different\n" + - "systems, but maintain only a single file in your source state, you can use\n" + - "a shared template.\n" + - "\n" + - "Create the common file in the `.chezmoitemplates` directory in the source state. For\n" + - "example, create `.chezmoitemplates/file.conf`. The contents of this file are\n" + - "available in templates with the `template *name*` function where *name* is the\n" + - "name of the file.\n" + - "\n" + - "Then create files for each system, for example `Library/Application\n" + - "Support/App/file.conf.tmpl` for macOS and `dot_config/app/file.conf.tmpl` for\n" + - "Linux. Both template files should contain `{{- template \"file.conf\" -}}`.\n" + - "\n" + - "Finally, tell chezmoi to ignore files where they are not needed by adding lines\n" + - "to your `.chezmoiignore` file, for example:\n" + - "\n" + - "```\n" + - "{{ if ne .chezmoi.os \"darwin\" }}\n" + - "Library/Application Support/App/file.conf\n" + - "{{ end }}\n" + - "{{ if ne .chezmoi.os \"linux\" }}\n" + - ".config/app/file.conf\n" + - "{{ end }}\n" + - "```\n" + - "\n" + - "## Keep data private\n" + - "\n" + - "chezmoi automatically detects when files and directories are private when adding\n" + - "them by inspecting their permissions. Private files and directories are stored\n" + - "in `~/.local/share/chezmoi` as regular, public files with permissions `0644` and\n" + - "the name prefix `private_`. For example:\n" + - "\n" + - " chezmoi add ~/.netrc\n" + - "\n" + - "will create `~/.local/share/chezmoi/private_dot_netrc` (assuming `~/.netrc` is\n" + - "not world- or group- readable, as it should be). This file is still private\n" + - "because `~/.local/share/chezmoi` is not group- or world- readable or executable.\n" + - "chezmoi checks that the permissions of `~/.local/share/chezmoi` are `0700` on\n" + - "every run and will print a warning if they are not.\n" + - "\n" + - "It is common that you need to store access tokens in config files, e.g. a\n" + - "[GitHub access\n" + - "token](https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/).\n" + - "There are several ways to keep these tokens secure, and to prevent them leaving\n" + - "your machine.\n" + - "\n" + - "### Use Bitwarden to keep your secrets\n" + - "\n" + - "chezmoi includes support for [Bitwarden](https://bitwarden.com/) using the\n" + - "[Bitwarden CLI](https://github.com/bitwarden/cli) to expose data as a template\n" + - "function.\n" + - "\n" + - "Log in to Bitwarden using:\n" + - "\n" + - " bw login <bitwarden-email>\n" + - "\n" + - "Unlock your Bitwarden vault:\n" + - "\n" + - " bw unlock\n" + - "\n" + - "Set the `BW_SESSION` environment variable, as instructed.\n" + - "\n" + - "The structured data from `bw get` is available as the `bitwarden` template\n" + - "function in your config files, for example:\n" + - "\n" + - " username = {{ (bitwarden \"item\" \"example.com\").login.username }}\n" + - " password = {{ (bitwarden \"item\" \"example.com\").login.password }}\n" + - "\n" + - "Custom fields can be accessed with the `bitwardenFields` template function. For\n" + - "example, if you have a custom field named `token` you can retrieve its value\n" + - "with:\n" + - "\n" + - " {{ (bitwardenFields \"item\" \"example.com\").token.value }}\n" + - "\n" + - "### Use gopass to keep your secrets\n" + - "\n" + - "chezmoi includes support for [gopass](https://www.gopass.pw/) using the gopass CLI.\n" + - "\n" + - "The first line of the output of `gopass show <pass-name>` is available as the\n" + - "`gopass` template function, for example:\n" + - "\n" + - " {{ gopass \"<pass-name>\" }}\n" + - "\n" + - "### Use gpg to keep your secrets\n" + - "\n" + - "chezmoi supports encrypting files with [gpg](https://www.gnupg.org/). Encrypted\n" + - "files are stored in the source state and automatically be decrypted when\n" + - "generating the target state or printing a file's contents with `chezmoi cat`.\n" + - "`chezmoi edit` will transparently decrypt the file before editing and re-encrypt\n" + - "it afterwards.\n" + - "\n" + - "#### Asymmetric (private/public-key) encryption\n" + - "\n" + - "Specify the encryption key to use in your configuration file (`chezmoi.toml`)\n" + - "with the `gpg.recipient` key:\n" + - "\n" + - " [gpg]\n" + - " recipient = \"...\"\n" + - "\n" + - "Add files to be encrypted with the `--encrypt` flag, for example:\n" + - "\n" + - " chezmoi add --encrypt ~/.ssh/id_rsa\n" + - "\n" + - "chezmoi will encrypt the file with:\n" + - "\n" + - " gpg --armor --recipient ${gpg.recipient} --encrypt\n" + - "\n" + - "and store the encrypted file in the source state. The file will automatically be\n" + - "decrypted when generating the target state.\n" + - "\n" + - "#### Symmetric encryption\n" + - "\n" + - "Specify symmetric encryption in your configuration file:\n" + - "\n" + - " [gpg]\n" + - " symmetric = true\n" + - "\n" + - "Add files to be encrypted with the `--encrypt` flag, for example:\n" + - "\n" + - " chezmoi add --encrypt ~/.ssh/id_rsa\n" + - "\n" + - "chezmoi will encrypt the file with:\n" + - "\n" + - " gpg --armor --symmetric\n" + - "\n" + - "### Use KeePassXC to keep your secrets\n" + - "\n" + - "chezmoi includes support for [KeePassXC](https://keepassxc.org) using the\n" + - "KeePassXC CLI (`keepassxc-cli`) to expose data as a template function.\n" + - "\n" + - "Provide the path to your KeePassXC database in your configuration file:\n" + - "\n" + - " [keepassxc]\n" + - " database = \"/home/user/Passwords.kdbx\"\n" + - "\n" + - "The structured data from `keepassxc-cli show $database` is available as the\n" + - "`keepassxc` template function in your config files, for example:\n" + - "\n" + - " username = {{ (keepassxc \"example.com\").UserName }}\n" + - " password = {{ (keepassxc \"example.com\").Password }}\n" + - "\n" + - "Additional attributes are available through the `keepassxcAttribute` function.\n" + - "For example, if you have an entry called `SSH Key` with an additional attribute\n" + - "called `private-key`, its value is available as:\n" + - "\n" + - " {{ keepassxcAttribute \"SSH Key\" \"private-key\" }}\n" + - "\n" + - "### Use a keyring to keep your secrets\n" + - "\n" + - "chezmoi includes support for Keychain (on macOS), GNOME Keyring (on Linux), and\n" + - "Windows Credentials Manager (on Windows) via the\n" + - "[`zalando/go-keyring`](https://github.com/zalando/go-keyring) library.\n" + - "\n" + - "Set values with:\n" + - "\n" + - " $ chezmoi keyring set --service=<service> --user=<user>\n" + - " Value: xxxxxxxx\n" + - "\n" + - "The value can then be used in templates using the `keyring` function which takes\n" + - "the service and user as arguments.\n" + - "\n" + - "For example, save a GitHub access token in keyring with:\n" + - "\n" + - " $ chezmoi keyring set --service=github --user=<github-username>\n" + - " Value: xxxxxxxx\n" + - "\n" + - "and then include it in your `~/.gitconfig` file with:\n" + - "\n" + - " [github]\n" + - " user = \"{{ .github.user }}\"\n" + - " token = \"{{ keyring \"github\" .github.user }}\"\n" + - "\n" + - "You can query the keyring from the command line:\n" + - "\n" + - " chezmoi keyring get --service=github --user=<github-username>\n" + - "\n" + - "### Use LastPass to keep your secrets\n" + - "\n" + - "chezmoi includes support for [LastPass](https://lastpass.com) using the\n" + - "[LastPass CLI](https://lastpass.github.io/lastpass-cli/lpass.1.html) to expose\n" + - "data as a template function.\n" + - "\n" + - "Log in to LastPass using:\n" + - "\n" + - " lpass login <lastpass-username>\n" + - "\n" + - "Check that `lpass` is working correctly by showing password data:\n" + - "\n" + - " lpass show --json <lastpass-entry-id>\n" + - "\n" + - "where `<lastpass-entry-id>` is a [LastPass Entry\n" + - "Specification](https://lastpass.github.io/lastpass-cli/lpass.1.html#_entry_specification).\n" + - "\n" + - "The structured data from `lpass show --json id` is available as the `lastpass`\n" + - "template function. The value will be an array of objects. You can use the\n" + - "`index` function and `.Field` syntax of the `text/template` language to extract\n" + - "the field you want. For example, to extract the `password` field from first the\n" + - "\"GitHub\" entry, use:\n" + - "\n" + - " githubPassword = \"{{ (index (lastpass \"GitHub\") 0).password }}\"\n" + - "\n" + - "chezmoi automatically parses the `note` value of the Lastpass entry as\n" + - "colon-separated key-value pairs, so, for example, you can extract a private SSH\n" + - "key like this:\n" + - "\n" + - " {{ (index (lastpass \"SSH\") 0).note.privateKey }}\n" + - "\n" + - "Keys in the `note` section written as `CamelCase Words` are converted to\n" + - "`camelCaseWords`.\n" + - "\n" + - "If the `note` value does not contain colon-separated key-value pairs, then you\n" + - "can use `lastpassRaw` to get its raw value, for example:\n" + - "\n" + - " {{ (index (lastpassRaw \"SSH Private Key\") 0).note }}\n" + - "\n" + - "### Use 1Password to keep your secrets\n" + - "\n" + - "chezmoi includes support for [1Password](https://1password.com/) using the\n" + - "[1Password CLI](https://support.1password.com/command-line-getting-started/) to\n" + - "expose data as a template function.\n" + - "\n" + - "Log in and get a session using:\n" + - "\n" + - " eval $(op signin <subdomain>.1password.com <email>)\n" + - "\n" + - "The output of `op get item <uuid>` is available as the `onepassword` template\n" + - "function. chezmoi parses the JSON output and returns it as structured data. For\n" + - "example, if the output of `op get item \"<uuid>\"` is:\n" + - "\n" + - " {\n" + - " \"uuid\": \"<uuid>\",\n" + - " \"details\": {\n" + - " \"password\": \"xxx\"\n" + - " }\n" + - " }\n" + - "\n" + - "Then you can access `details.password` with the syntax:\n" + - "\n" + - " {{ (onepassword \"<uuid>\").details.password }}\n" + - "\n" + - "Login details fields can be retrieved with the `onepasswordDetailsFields`\n" + - "function, for example:\n" + - "\n" + - " {{- (onepasswordDetailsFields \"uuid\").password.value }}\n" + - "\n" + - "Documents can be retrieved with:\n" + - "\n" + - " {{- onepasswordDocument \"uuid\" -}}\n" + - "\n" + - "Note the extra `-` after the opening `{{` and before the closing `}}`. This\n" + - "instructs the template language to remove and whitespace before and after the\n" + - "substitution. This removes any trailing newline added by your editor when saving\n" + - "the template.\n" + - "\n" + - "### Use pass to keep your secrets\n" + - "\n" + - "chezmoi includes support for [pass](https://www.passwordstore.org/) using the\n" + - "pass CLI.\n" + - "\n" + - "The first line of the output of `pass show <pass-name>` is available as the\n" + - "`pass` template function, for example:\n" + - "\n" + - " {{ pass \"<pass-name>\" }}\n" + - "\n" + - "### Use Vault to keep your secrets\n" + - "\n" + - "chezmoi includes support for [Vault](https://www.vaultproject.io/) using the\n" + - "[Vault CLI](https://www.vaultproject.io/docs/commands/) to expose data as a\n" + - "template function.\n" + - "\n" + - "The vault CLI needs to be correctly configured on your machine, e.g. the\n" + - "`VAULT_ADDR` and `VAULT_TOKEN` environment variables must be set correctly.\n" + - "Verify that this is the case by running:\n" + - "\n" + - " vault kv get -format=json <key>\n" + - "\n" + - "The structured data from `vault kv get -format=json` is available as the `vault`\n" + - "template function. You can use the `.Field` syntax of the `text/template`\n" + - "language to extract the data you want. For example:\n" + - "\n" + - " {{ (vault \"<key>\").data.data.password }}\n" + - "\n" + - "### Use a generic tool to keep your secrets\n" + - "\n" + - "You can use any command line tool that outputs secrets either as a string or in\n" + - "JSON format. Choose the binary by setting `genericSecret.command` in your\n" + - "configuration file. You can then invoke this command with the `secret` and\n" + - "`secretJSON` template functions which return the raw output and JSON-decoded\n" + - "output respectively. All of the above secret managers can be supported in this\n" + - "way:\n" + - "\n" + - "| Secret Manager | `genericSecret.command` | Template skeleton |\n" + - "| --------------- | ----------------------- | ------------------------------------------------- |\n" + - "| 1Password | `op` | `{{ secretJSON \"get\" \"item\" <id> }}` |\n" + - "| Bitwarden | `bw` | `{{ secretJSON \"get\" <id> }}` |\n" + - "| Hashicorp Vault | `vault` | `{{ secretJSON \"kv\" \"get\" \"-format=json\" <id> }}` |\n" + - "| LastPass | `lpass` | `{{ secretJSON \"show\" \"--json\" <id> }}` |\n" + - "| KeePassXC | `keepassxc-cli` | Not possible (interactive command only) |\n" + - "| pass | `pass` | `{{ secret \"show\" <id> }}` |\n" + - "\n" + - "### Use templates variables to keep your secrets\n" + - "\n" + - "Typically, `~/.config/chezmoi/chezmoi.toml` is not checked in to version control\n" + - "and has permissions 0600. You can store tokens as template values in the `data`\n" + - "section. For example, if your `~/.config/chezmoi/chezmoi.toml` contains:\n" + - "\n" + - " [data]\n" + - " [data.github]\n" + - " user = \"<github-username>\"\n" + - " token = \"<github-token>\"\n" + - "\n" + - "Your `~/.local/share/chezmoi/private_dot_gitconfig.tmpl` can then contain:\n" + - "\n" + - " {{- if (index . \"github\") }}\n" + - " [github]\n" + - " user = \"{{ .github.user }}\"\n" + - " token = \"{{ .github.token }}\"\n" + - " {{- end }}\n" + - "\n" + - "Any config files containing tokens in plain text should be private (permissions\n" + - "`0600`).\n" + - "\n" + - "## Use scripts to perform actions\n" + - "\n" + - "### Understand how scripts work\n" + - "\n" + - "chezmoi supports scripts, which are executed when you run `chezmoi apply`. The\n" + - "scripts can either run every time you run `chezmoi apply`, or only when their\n" + - "contents have changed.\n" + - "\n" + - "In verbose mode, the script's contents will be printed before executing it. In\n" + - "dry-run mode, the script is not executed.\n" + - "\n" + - "Scripts are any file in the source directory with the prefix `run_`, and are\n" + - "executed in alphabetical order. Scripts that should only be run when their\n" + - "contents change have the prefix `run_once_`.\n" + - "\n" + - "Scripts break chezmoi's declarative approach, and as such should be used\n" + - "sparingly. Any script should be idempotent, even `run_once_` scripts.\n" + - "\n" + - "Scripts must be created manually in the source directory, typically by running\n" + - "`chezmoi cd` and then creating a file with a `run_` prefix. Scripts are executed\n" + - "directly using `exec` and must include a shebang line or be executable binaries.\n" + - "There is no need to set the executable bit on the script.\n" + - "\n" + - "Scripts with the suffix `.tmpl` are treated as templates, with the usual\n" + - "template variables available. If, after executing the template, the result is\n" + - "only whitespace or an empty string, then the script is not executed. This is\n" + - "useful for disabling scripts.\n" + - "\n" + - "### Install packages with scripts\n" + - "\n" + - "Change to the source directory and create a file called\n" + - "`run_once_install-packages.sh`:\n" + - "\n" + - " chezmoi cd\n" + - " $EDITOR run_once_install-packages.sh\n" + - "\n" + - "In this file create your package installation script, e.g.\n" + - "\n" + - " #!/bin/sh\n" + - " sudo apt install ripgrep\n" + - "\n" + - "The next time you run `chezmoi apply` or `chezmoi update` this script will be\n" + - "run. As it has the `run_once_` prefix, it will not be run again unless its\n" + - "contents change, for example if you add more packages to be installed.\n" + - "\n" + - "This script can also be a template. For example, if you create\n" + - "`run_once_install-packages.sh.tmpl` with the contents:\n" + - "\n" + - " {{ if eq .chezmoi.os \"linux\" -}}\n" + - " #!/bin/sh\n" + - " sudo apt install ripgrep\n" + - " {{ else if eq .chezmoi.os \"darwin\" -}}\n" + - " #!/bin/sh\n" + - " brew install ripgrep\n" + - " {{ end -}}\n" + - "\n" + - "This will install `ripgrep` on both Debian/Ubuntu Linux systems and macOS.\n" + - "\n" + - "## Use chezmoi with GitHub Codespaces, Visual Studio Codespaces, Visual Studio Code Remote - Containers\n" + - "\n" + - "The following assumes you are using chezmoi 1.8.4 or later. It does not work\n" + - "with earlier versions of chezmoi.\n" + - "\n" + - "You can use chezmoi to manage your dotfiles in [GitHub\n" + - "Codespaces](https://docs.github.com/en/github/developing-online-with-codespaces/personalizing-codespaces-for-your-account),\n" + - "[Visual Studio\n" + - "Codespaces](https://docs.microsoft.com/en/visualstudio/codespaces/reference/personalizing),\n" + - "and [Visual Studio Code Remote -\n" + - "Containers](https://code.visualstudio.com/docs/remote/containers#_personalizing-with-dotfile-repositories).\n" + - "\n" + - "For a quick start, you can clone the [`chezmoi/dotfiles`\n" + - "repository](https://github.com/chezmoi/dotfiles) which supports Codespaces out\n" + - "of the box.\n" + - "\n" + - "The workflow is different to using chezmoi on a new machine, notably:\n" + - "* These systems will automatically clone your `dotfiles` repo to `~/dotfiles`,\n" + - " so there is no need to clone your repo yourself.\n" + - "* The installation script must be non-interactive.\n" + - "* When running in a Codespace, the environment variable `CODESPACES` will be set\n" + - " to `true`. You can read its value with the [`env` template\n" + - " function](http://masterminds.github.io/sprig/os.html).\n" + - "\n" + - "First, if you are using a chezmoi configuration file template, ensure that it is\n" + - "non-interactive when running in codespaces, for example, `.chezmoi.toml.tmpl`\n" + - "might contain:\n" + - "\n" + - "```\n" + - "{{- $codespaces:= env \"CODESPACES\" | not | not -}}\n" + - "sourceDir = \"{{ .chezmoi.sourceDir }}\"\n" + - "\n" + - "[data]\n" + - " name = \"Your name\"\n" + - " codespaces = {{ $codespaces }}\n" + - "{{- if $codespaces }}{{/* Codespaces dotfiles setup is non-interactive, so set an email address */}}\n" + - " email = \"[email protected]\"\n" + - "{{- else }}{{/* Interactive setup, so prompt for an email address */}}\n" + - " email = \"{{ promptString \"email\" }}\"\n" + - "{{- end }}\n" + - "```\n" + - "\n" + - "This sets the `codespaces` template variable, so you don't have to repeat `(env\n" + - "\"CODESPACES\")` in your templates. It also sets the `sourceDir` configuration to\n" + - "the `--source` argument passed in `chezmoi init`.\n" + - "\n" + - "Second, create an `install.sh` script that installs chezmoi and your dotfiles:\n" + - "\n" + - "```sh\n" + - "#!/bin/sh\n" + - "\n" + - "set -e # -e: exit on error\n" + - "\n" + - "if [ ! \"$(command -v chezmoi)\" ]; then\n" + - " bin_dir=\"$HOME/.local/bin\"\n" + - " chezmoi=\"$bin_dir/chezmoi\"\n" + - " if [ \"$(command -v curl)\" ]; then\n" + - " sh -c \"$(curl -fsSL https://git.io/chezmoi)\" -- -b \"$bin_dir\"\n" + - " elif [ \"$(command -v wget)\" ]; then\n" + - " sh -c \"$(wget -qO- https://git.io/chezmoi)\" -- -b \"$bin_dir\"\n" + - " else\n" + - " echo \"To install chezmoi, you must have curl or wget installed.\" >&2\n" + - " exit 1\n" + - " fi\n" + - "else\n" + - " chezmoi=chezmoi\n" + - "fi\n" + - "\n" + - "# POSIX way to get script's dir: https://stackoverflow.com/a/29834779/12156188\n" + - "script_dir=\"$(cd -P -- \"$(dirname -- \"$(command -v -- \"$0\")\")\" && pwd -P)\"\n" + - "# exec: replace current process with chezmoi init\n" + - "exec \"$chezmoi\" init --apply \"--source=$script_dir\"\n" + - "```\n" + - "\n" + - "Ensure that this file is executable (`chmod a+x install.sh`), and add\n" + - "`install.sh` to your `.chezmoiignore` file.\n" + - "\n" + - "It installs the latest version of chezmoi in `~/.local/bin` if needed, and then\n" + - "`chezmoi init ...` invokes chezmoi to create its configuration file and\n" + - "initialize your dotfiles. `--apply` tells chezmoi to apply the changes\n" + - "immediately, and `--source=...` tells chezmoi where to find the cloned\n" + - "`dotfiles` repo, which in this case is the same folder in which the script is\n" + - "running from.\n" + - "\n" + - "If you do not use a chezmoi configuration file template you can use `chezmoi\n" + - "apply --source=$HOME/dotfiles` instead of `chezmoi init ...` in `install.sh`.\n" + - "\n" + - "Finally, modify any of your templates to use the `codespaces` variable if\n" + - "needed. For example, to install `vim-gtk` on Linux but not in Codespaces, your\n" + - "`run_once_install-packages.sh.tmpl` might contain:\n" + - "\n" + - "```\n" + - "{{- if (and (eq .chezmoi.os \"linux\")) (not .codespaces))) -}}\n" + - "#!/bin/sh\n" + - "sudo apt install -y vim-gtk\n" + - "{{- end -}}\n" + - "```\n" + - "\n" + - "## Detect Windows Subsystem for Linux (WSL)\n" + - "\n" + - "WSL can be detected by looking for the string `Microsoft` in\n" + - "`/proc/kernel/osrelease`, which is available in the template variable\n" + - "`.chezmoi.kernel.osrelease`, for example:\n" + - "\n" + - "WSL 1:\n" + - "```\n" + - "{{ if (contains \"Microsoft\" .chezmoi.kernel.osrelease) }}\n" + - "# WSL-specific code\n" + - "{{ end }}\n" + - "```\n" + - "\n" + - "WSL 2:\n" + - "```\n" + - "{{ if (contains \"microsoft\" .chezmoi.kernel.osrelease) }}\n" + - "# WSL-specific code\n" + - "{{ end }}\n" + - "```\n" + - "\n" + - "WSL 2 since version 4.19.112:\n" + - "```\n" + - "{{ if (contains \"microsoft-WSL2\" .chezmoi.kernel.osrelease) }}\n" + - "# WSL-specific code\n" + - "{{ end }}\n" + - "```\n" + - "\n" + - "## Run a PowerShell script as admin on Windows\n" + - "\n" + - "Put the following at the top of your script:\n" + - "\n" + - "```powershell\n" + - "# Self-elevate the script if required\n" + - "if (-Not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')) {\n" + - " if ([int](Get-CimInstance -Class Win32_OperatingSystem | Select-Object -ExpandProperty BuildNumber) -ge 6000) {\n" + - " $CommandLine = \"-NoExit -File `\"\" + $MyInvocation.MyCommand.Path + \"`\" \" + $MyInvocation.UnboundArguments\n" + - " Start-Process -FilePath PowerShell.exe -Verb Runas -ArgumentList $CommandLine\n" + - " Exit\n" + - " }\n" + - "}\n" + - "```\n" + - "\n" + - "## Import archives\n" + - "\n" + - "It is occasionally useful to import entire archives of configuration into your\n" + - "source state. The `import` command does this. For example, to import the latest\n" + - "version\n" + - "[`github.com/robbyrussell/oh-my-zsh`](https://github.com/robbyrussell/oh-my-zsh)\n" + - "to `~/.oh-my-zsh` run:\n" + - "\n" + - " curl -s -L -o oh-my-zsh-master.tar.gz https://github.com/robbyrussell/oh-my-zsh/archive/master.tar.gz\n" + - " chezmoi import --strip-components 1 --destination ~/.oh-my-zsh oh-my-zsh-master.tar.gz\n" + - "\n" + - "Note that this only updates the source state. You will need to run\n" + - "\n" + - " chezmoi apply\n" + - "\n" + - "to update your destination directory.\n" + - "\n" + - "## Export archives\n" + - "\n" + - "chezmoi can create an archive containing the target state. This can be useful\n" + - "for generating target state on a different machine or for simply inspecting the\n" + - "target state. A particularly useful command is:\n" + - "\n" + - " chezmoi archive | tar tvf -\n" + - "\n" + - "which lists all the targets in the target state.\n" + - "\n" + - "## Use a non-git version control system\n" + - "\n" + - "By default, chezmoi uses git, but you can use any version control system of your\n" + - "choice. In your config file, specify the command to use. For example, to use\n" + - "Mercurial specify:\n" + - "\n" + - " [sourceVCS]\n" + - " command = \"hg\"\n" + - "\n" + - "The source VCS command is used in the chezmoi commands `init`, `source`, and\n" + - "`update`, and support for VCSes other than git is limited but easy to add. If\n" + - "you'd like to see your VCS better supported, please [open an issue on\n" + - "GitHub](https://github.com/twpayne/chezmoi/issues/new/choose).\n" + - "\n" + - "## Customize the `diff` command\n" + - "\n" + - "By default, chezmoi uses a built-in diff. You can change the format, and/or pipe\n" + - "the output into a pager of your choice. For example, to use\n" + - "[`diff-so-fancy`](https://github.com/so-fancy/diff-so-fancy) specify:\n" + - "\n" + - " [diff]\n" + - " format = \"git\"\n" + - " pager = \"diff-so-fancy\"\n" + - "\n" + - "The format can also be set with the `--format` option to the `diff` command, and\n" + - "the pager can be disabled using `--no-pager`.\n" + - "\n" + - "## Use a merge tool other than vimdiff\n" + - "\n" + - "By default, chezmoi uses vimdiff, but you can use any merge tool of your choice.\n" + - "In your config file, specify the command and args to use. For example, to use\n" + - "neovim's diff mode specify:\n" + - "\n" + - " [merge]\n" + - " command = \"nvim\"\n" + - " args = \"-d\"\n" + - "\n" + - "## Migrate from a dotfile manager that uses symlinks\n" + - "\n" + - "Many dotfile managers replace dotfiles with symbolic links to files in a common\n" + - "directory. If you `chezmoi add` such a symlink, chezmoi will add the symlink,\n" + - "not the file. To assist with migrating from symlink-based systems, use the\n" + - "`--follow` option to `chezmoi add`, for example:\n" + - "\n" + - " chezmoi add --follow ~/.bashrc\n" + - "\n" + - "This will tell `chezmoi add` that the target state of `~/.bashrc` is the target\n" + - "of the `~/.bashrc` symlink, rather than the symlink itself. When you run\n" + - "`chezmoi apply`, chezmoi will replace the `~/.bashrc` symlink with the file\n" + - "contents.\n" + - "\n") - assets["docs/INSTALL.md"] = []byte("" + - "# chezmoi Install Guide\n" + - "\n" + - "<!--- toc --->\n" + - "* [One-line binary install](#one-line-binary-install)\n" + - "* [One-line package install](#one-line-package-install)\n" + - "* [Pre-built Linux packages](#pre-built-linux-packages)\n" + - "* [Pre-built binaries](#pre-built-binaries)\n" + - "* [All pre-built Linux packages and binaries](#all-pre-built-linux-packages-and-binaries)\n" + - "* [From source](#from-source)\n" + - "* [Upgrading](#upgrading)\n" + - "\n" + - "## One-line binary install\n" + - "\n" + - "Install the correct binary for your operating system and architecture in `./bin`\n" + - "with a single command.\n" + - "\n" + - " curl -sfL https://git.io/chezmoi | sh\n" + - "\n" + - "Or on systems with Powershell, you can use this command:\n" + - "\n" + - " # To install in ./bin\n" + - " (iwr https://git.io/chezmoi.ps1).Content | powershell -c -\n" + - "\n" + - " # To install in another location\n" + - " '$params = \"-BinDir ~/other\"', (iwr https://git.io/chezmoi.ps1).Content | powershell -c -\n" + - "\n" + - " # For information about other options, try this:\n" + - " '$params = \"-?\"', (iwr https://git.io/chezmoi.ps1).Content | powershell -c -\n" + - "\n" + - "## One-line package install\n" + - "\n" + - "Install chezmoi with a single command.\n" + - "\n" + - "| OS | Method | Command |\n" + - "| ------------ | ---------- | ------------------------------------------------------------------------------------------- |\n" + - "| Linux | snap | `snap install chezmoi --classic` |\n" + - "| Linux | Linuxbrew | `brew install chezmoi` |\n" + - "| Alpine Linux | apk | `apk add chezmoi` |\n" + - "| Arch Linux | pacman | `pacman -S chezmoi` |\n" + - "| Guix Linux | guix | `guix install chezmoi` |\n" + - "| NixOS Linux | nix-env | `nix-env -i chezmoi` |\n" + - "| Void Linux | xbps | `xbps-install -S chezmoi` |\n" + - "| macOS | Homebrew | `brew install chezmoi` |\n" + - "| macOS | MacPorts | `sudo port install chezmoi` |\n" + - "| Windows | Scoop | `scoop bucket add twpayne https://github.com/twpayne/scoop-bucket && scoop install chezmoi` |\n" + - "| Windows | Chocolatey | `choco install chezmoi` |\n" + - "\n" + - "## Pre-built Linux packages\n" + - "\n" + - "Download a package for your operating system and architecture and install it\n" + - "with your package manager.\n" + - "\n" + - "| Distribution | Architectures | Package |\n" + - "| ------------ | --------------------------------------------------------- | ----------------------------------------------------------- |\n" + - "| Alpine | `386`, `amd64`, `arm64`, `arm`, `ppc64`, `ppc64le` | [`apk`](https://github.com/twpayne/chezmoi/releases/latest) |\n" + - "| Debian | `amd64`, `arm64`, `armel`, `i386`, `ppc64`, `ppc64le` | [`deb`](https://github.com/twpayne/chezmoi/releases/latest) |\n" + - "| RedHat | `aarch64`, `armhfp`, `i686`, `ppc64`, `ppc64le`, `x86_64` | [`rpm`](https://github.com/twpayne/chezmoi/releases/latest) |\n" + - "| OpenSUSE | `aarch64`, `armhfp`, `i686`, `ppc64`, `ppc64le`, `x86_64` | [`rpm`](https://github.com/twpayne/chezmoi/releases/latest) |\n" + - "| Ubuntu | `amd64`, `arm64`, `armel`, `i386`, `ppc64`, `ppc64le` | [`deb`](https://github.com/twpayne/chezmoi/releases/latest) |\n" + - "\n" + - "## Pre-built binaries\n" + - "\n" + - "Download an archive for your operating system containing a pre-built binary,\n" + - "documentation, and shell completions.\n" + - "\n" + - "| OS | Architectures | Archive |\n" + - "| ---------- | --------------------------------------------------- | -------------------------------------------------------------- |\n" + - "| FreeBSD | `amd64`, `arm`, `arm64`, `i386` | [`tar.gz`](https://github.com/twpayne/chezmoi/releases/latest) |\n" + - "| Linux | `amd64`, `arm`, `arm64`, `i386`, `ppc64`, `ppc64le` | [`tar.gz`](https://github.com/twpayne/chezmoi/releases/latest) |\n" + - "| macOS | `amd64` | [`tar.gz`](https://github.com/twpayne/chezmoi/releases/latest) |\n" + - "| OpenBSD | `amd64`, `arm`, `arm64`, `i386` | [`tar.gz`](https://github.com/twpayne/chezmoi/releases/latest) |\n" + - "| Windows | `amd64`, `i386` | [`zip`](https://github.com/twpayne/chezmoi/releases/latest) |\n" + - "\n" + - "## All pre-built Linux packages and binaries\n" + - "\n" + - "All pre-built binaries and packages can be found on the [chezmoi GitHub releases\n" + - "page](https://github.com/twpayne/chezmoi/releases/latest).\n" + - "\n" + - "## From source\n" + - "\n" + - "Download, build, and install chezmoi for your system:\n" + - "\n" + - " cd $(mktemp -d)\n" + - " git clone --depth=1 https://github.com/twpayne/chezmoi.git\n" + - " cd chezmoi\n" + - " go install\n" + - "\n" + - "Building chezmoi requires Go 1.14 or later.\n" + - "\n" + - "## Upgrading\n" + - "\n" + - "If you have installed a pre-built binary of chezmoi, you can upgrade it to the\n" + - "latest release with:\n" + - "\n" + - " chezmoi upgrade\n" + - "\n" + - "This will re-use whichever mechanism you used to install chezmoi to install the\n" + - "latest release.\n" + - "\n") - assets["docs/MEDIA.md"] = []byte("" + - "# chezmoi in the media\n" + - "\n" + - "<!--- toc --->\n" + - "\n" + - "Recommended article: [Fedora Magazine: Take back your dotfiles with Chezmoi](https://fedoramagazine.org/take-back-your-dotfiles-with-chezmoi/)\n" + - "\n" + - "Recommended video: [Conf42: chezmoi: Manage your dotfiles across multiple machines, securely](https://www.youtube.com/watch?v=JrCMCdvoMAw)\n" + - "\n" + - "Recommended podcast: [FLOSS weekly episode 556: chezmoi](https://twit.tv/shows/floss-weekly/episodes/556)\n" + - "\n" + - "| Date | Version | Format | Link |\n" + - "| ---------- | ------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n" + - "| 2021-02-06 | 1.8.10 | Video | [chezmoi: manage your dotfiles across multiple, diverse machines, securely](https://fosdem.org/2021/schedule/event/chezmoi/) |\n" + - "| 2021-01-12 | 1.8.10 | Text | [Automating the Setup of a New Mac With All Your Apps, Preferences, and Development Tools](https://www.moncefbelyamani.com/automating-the-setup-of-a-new-mac-with-all-your-apps-preferences-and-development-tools/) |\n" + - "| 2020-11-06 | 1.8.8 | Text | [Chezmoi – Securely Manage dotfiles across multiple machines](https://computingforgeeks.com/chezmoi-manage-dotfiles-across-multiple-machines/) |\n" + - "| 2020-11-05 | 1.8.8 | Text | [Using chezmoi to manage dotfiles](https://pashinskikh.de/posts/chezmoi/) |\n" + - "| 2020-10-05 | 1.8.6 | Text | [Dotfiles with /Chezmoi/](https://blog.lazkani.io/posts/backup/dotfiles-with-chezmoi/) |\n" + - "| 2020-08-13 | 1.8.3 | Text | [Using BitWarden and Chezmoi to manage SSH keys](https://www.jx0.uk/chezmoi/bitwarden/unix/ssh/2020/08/13/bitwarden-chezmoi-ssh-key.html) |\n" + - "| 2020-08-09 | 1.8.3 | Text | [Automating and testing dotfiles](https://seds.nl/posts/automating-and-testing-dotfiles/) |\n" + - "| 2020-08-03 | 1.8.3 | Text | [Automating a Linux in Windows Dev Setup](https://matt.aimonetti.net/posts/2020-08-automating-a-linux-in-windows-dev-setup/) |\n" + - "| 2020-07-06 | 1.8.3 | Video | [Conf42: chezmoi: Manage your dotfiles across multiple machines, securely](https://www.youtube.com/watch?v=JrCMCdvoMAw) |\n" + - "| 2020-07-03 | 1.8.3 | Text | [Feeling at home in a LXD container](https://ubuntu.com/blog/feeling-at-home-in-a-lxd-container) |\n" + - "| 2020-06-15 | 1.8.2 | Text | [Dotfiles management using chezmoi - How I Use Linux Desktop at Work Part5](https://blog.benoitj.ca/2020-06-15-how-i-use-linux-desktop-at-work-part5-dotfiles/) |\n" + - "| 2020-04-27 | 1.8.0 | Text | [Managing my dotfiles with chezmoi](http://blog.emilieschario.com/post/managing-my-dotfiles-with-chezmoi/) |\n" + - "| 2020-04-20 | 1.8.0 | Text (FR) | [Gestion des dotfiles et des secrets avec chezmoi](https://blog.arkey.fr/2020/04/01/manage_dotfiles_with_chezmoi.fr/) |\n" + - "| 2020-04-19 | 1.7.19 | Text (FR) | [Git & dotfiles : versionner ses fichiers de configuration](https://www.armandphilippot.com/dotfiles-git-fichiers-configuration/) |\n" + - "| 2020-04-16 | 1.7.19 | Text (FR) | [Chezmoi, visite guidée](https://blog.wescale.fr/2020/04/16/chezmoi-visite-guidee/) |\n" + - "| 2020-04-03 | 1.7.17 | Text | [Fedora Magazine: Take back your dotfiles with Chezmoi](https://fedoramagazine.org/take-back-your-dotfiles-with-chezmoi/) |\n" + - "| 2020-04-01 | 1.7.17 | Text | [Managing dotfiles and secret with chezmoi](https://blog.arkey.fr/2020/04/01/manage_dotfiles_with_chezmoi/) |\n" + - "| 2020-03-12 | 1.7.16 | Video | [Managing Dotfiles with ChezMoi](https://www.youtube.com/watch?v=HXx6ugA98Qo) |\n" + - "| 2019-11-20 | 1.7.2 | Audio/video | [FLOSS weekly episode 556: chezmoi](https://twit.tv/shows/floss-weekly/episodes/556) |\n" + - "| 2019-01-10 | 0.0.11 | Text | [Linux Fu: The kitchen sync](https://hackaday.com/2019/01/10/linux-fu-the-kitchen-sync/) |\n" + - "\n" + - "To add your article to this page please either [open an\n" + - "issue](https://github.com/twpayne/chezmoi/issues/new/choose) or submit a pull\n" + - "request that modifies this file\n" + - "([`docs/MEDIA.md`](https://github.com/twpayne/chezmoi/blob/master/docs/MEDIA.md)).\n" + - "\n") - assets["docs/QUICKSTART.md"] = []byte("" + - "# chezmoi Quick Start Guide\n" + - "\n" + - "<!--- toc --->\n" + - "* [Concepts](#concepts)\n" + - "* [Start using chezmoi on your current machine](#start-using-chezmoi-on-your-current-machine)\n" + - "* [Using chezmoi across multiple machines](#using-chezmoi-across-multiple-machines)\n" + - "* [Next steps](#next-steps)\n" + - "\n" + - "## Concepts\n" + - "\n" + - "chezmoi stores the desired state of your dotfiles in the directory\n" + - "`~/.local/share/chezmoi`. When you run `chezmoi apply`, chezmoi calculates the\n" + - "desired contents and permissions for each dotfile and then makes any changes\n" + - "necessary so that your dotfiles match that state.\n" + - "\n" + - "## Start using chezmoi on your current machine\n" + - "\n" + - "Initialize chezmoi:\n" + - "\n" + - " chezmoi init\n" + - "\n" + - "This will create a new git repository in `~/.local/share/chezmoi` with\n" + - "permissions `0700` where chezmoi will store the source state. chezmoi only\n" + - "modifies files in the working copy. It is your responsibility to commit changes.\n" + - "\n" + - "Manage an existing file with chezmoi:\n" + - "\n" + - " chezmoi add ~/.bashrc\n" + - "\n" + - "This will copy `~/.bashrc` to `~/.local/share/chezmoi/dot_bashrc`. If you want\n" + - "to add a whole folder to chezmoi, you have to add the `-r` argument after `add`.\n" + - "\n" + - "Edit the source state:\n" + - "\n" + - " chezmoi edit ~/.bashrc\n" + - "\n" + - "This will open `~/.local/share/chezmoi/dot_bashrc` in your `$EDITOR`. Make some\n" + - "changes and save them.\n" + - "\n" + - "See what changes chezmoi would make:\n" + - "\n" + - " chezmoi diff\n" + - "\n" + - "Apply the changes:\n" + - "\n" + - " chezmoi -v apply\n" + - "\n" + - "All chezmoi commands accept the `-v` (verbose) flag to print out exactly what\n" + - "changes they will make to the file system, and the `-n` (dry run) flag to not\n" + - "make any actual changes. The combination `-n` `-v` is very useful if you want to\n" + - "see exactly what changes would be made.\n" + - "\n" + - "Finally, open a shell in the source directory, commit your changes, and return\n" + - "to where you were:\n" + - "\n" + - " chezmoi cd\n" + - " git add dot_bashrc\n" + - " git commit -m \"Add .bashrc\"\n" + - " exit\n" + - "\n" + - "## Using chezmoi across multiple machines\n" + - "\n" + - "Clone the git repo in `~/.local/share/chezmoi` to a hosted Git service, e.g.\n" + - "[GitHub](https://github.com), [GitLab](https://gitlab.com), or\n" + - "[BitBucket](https://bitbucket.org). Many people call their dotfiles repo\n" + - "`dotfiles`. You can then setup chezmoi on a second machine:\n" + - "\n" + - " chezmoi init https://github.com/username/dotfiles.git\n" + - "\n" + - "This will check out the repo and any submodules and optionally create a chezmoi\n" + - "config file for you. It won't make any changes to your home directory until you\n" + - "run:\n" + - "\n" + - " chezmoi apply\n" + - "\n" + - "On any machine, you can pull and apply the latest changes from your repo with:\n" + - "\n" + - " chezmoi update\n" + - "\n" + - "## Next steps\n" + - "\n" + - "For a full list of commands run:\n" + - "\n" + - " chezmoi help\n" + - "\n" + - "chezmoi has much more functionality. Read the [how-to\n" + - "guide](https://github.com/twpayne/chezmoi/blob/master/docs/HOWTO.md) to explore.\n" + - "\n") - assets["docs/REFERENCE.md"] = []byte("" + - "# chezmoi Reference Manual\n" + - "\n" + - "Manage your dotfiles securely across multiple machines.\n" + - "\n" + - "<!--- toc --->\n" + - "* [Concepts](#concepts)\n" + - "* [Global command line flags](#global-command-line-flags)\n" + - " * [`--color` *value*](#--color-value)\n" + - " * [`-c`, `--config` *filename*](#-c---config-filename)\n" + - " * [`--debug`](#--debug)\n" + - " * [`-D`, `--destination` *directory*](#-d---destination-directory)\n" + - " * [`--follow`](#--follow)\n" + - " * [`-n`, `--dry-run`](#-n---dry-run)\n" + - " * [`-h`, `--help`](#-h---help)\n" + - " * [`-r`. `--remove`](#-r---remove)\n" + - " * [`-S`, `--source` *directory*](#-s---source-directory)\n" + - " * [`-v`, `--verbose`](#-v---verbose)\n" + - " * [`--version`](#--version)\n" + - "* [Configuration file](#configuration-file)\n" + - " * [Variables](#variables)\n" + - " * [Examples](#examples)\n" + - "* [Source state attributes](#source-state-attributes)\n" + - "* [Special files and directories](#special-files-and-directories)\n" + - " * [`.chezmoi.<format>.tmpl`](#chezmoiformattmpl)\n" + - " * [`.chezmoiignore`](#chezmoiignore)\n" + - " * [`.chezmoiremove`](#chezmoiremove)\n" + - " * [`.chezmoitemplates`](#chezmoitemplates)\n" + - " * [`.chezmoiversion`](#chezmoiversion)\n" + - "* [Commands](#commands)\n" + - " * [`add` *targets*](#add-targets)\n" + - " * [`apply` [*targets*]](#apply-targets)\n" + - " * [`archive`](#archive)\n" + - " * [`cat` *targets*](#cat-targets)\n" + - " * [`cd`](#cd)\n" + - " * [`chattr` *attributes* *targets*](#chattr-attributes-targets)\n" + - " * [`completion` *shell*](#completion-shell)\n" + - " * [`data`](#data)\n" + - " * [`diff` [*targets*]](#diff-targets)\n" + - " * [`docs` [*regexp*]](#docs-regexp)\n" + - " * [`doctor`](#doctor)\n" + - " * [`dump` [*targets*]](#dump-targets)\n" + - " * [`edit` [*targets*]](#edit-targets)\n" + - " * [`edit-config`](#edit-config)\n" + - " * [`execute-template` [*templates*]](#execute-template-templates)\n" + - " * [`forget` *targets*](#forget-targets)\n" + - " * [`git` [*arguments*]](#git-arguments)\n" + - " * [`help` *command*](#help-command)\n" + - " * [`hg` [*arguments*]](#hg-arguments)\n" + - " * [`init` [*repo*]](#init-repo)\n" + - " * [`import` *filename*](#import-filename)\n" + - " * [`manage` *targets*](#manage-targets)\n" + - " * [`managed`](#managed)\n" + - " * [`merge` *targets*](#merge-targets)\n" + - " * [`purge`](#purge)\n" + - " * [`remove` *targets*](#remove-targets)\n" + - " * [`rm` *targets*](#rm-targets)\n" + - " * [`secret`](#secret)\n" + - " * [`source` [*args*]](#source-args)\n" + - " * [`source-path` [*targets*]](#source-path-targets)\n" + - " * [`unmanage` *targets*](#unmanage-targets)\n" + - " * [`unmanaged`](#unmanaged)\n" + - " * [`update`](#update)\n" + - " * [`upgrade`](#upgrade)\n" + - " * [`verify` [*targets*]](#verify-targets)\n" + - "* [Editor configuration](#editor-configuration)\n" + - "* [Umask configuration](#umask-configuration)\n" + - "* [Template execution](#template-execution)\n" + - "* [Template variables](#template-variables)\n" + - "* [Template functions](#template-functions)\n" + - " * [`bitwarden` [*args*]](#bitwarden-args)\n" + - " * [`bitwardenAttachment` *filename* *itemid*](#bitwardenattachment-filename-itemid)\n" + - " * [`bitwardenFields` [*args*]](#bitwardenfields-args)\n" + - " * [`gopass` *gopass-name*](#gopass-gopass-name)\n" + - " * [`include` *filename*](#include-filename)\n" + - " * [`ioreg`](#ioreg)\n" + - " * [`joinPath` *elements*](#joinpath-elements)\n" + - " * [`keepassxc` *entry*](#keepassxc-entry)\n" + - " * [`keepassxcAttribute` *entry* *attribute*](#keepassxcattribute-entry-attribute)\n" + - " * [`keyring` *service* *user*](#keyring-service-user)\n" + - " * [`lastpass` *id*](#lastpass-id)\n" + - " * [`lastpassRaw` *id*](#lastpassraw-id)\n" + - " * [`lookPath` *file*](#lookpath-file)\n" + - " * [`onepassword` *uuid* [*vault-uuid*]](#onepassword-uuid-vault-uuid)\n" + - " * [`onepasswordDocument` *uuid* [*vault-uuid*]](#onepassworddocument-uuid-vault-uuid)\n" + - " * [`onepasswordDetailsFields` *uuid* [*vault-uuid*]](#onepassworddetailsfields-uuid-vault-uuid)\n" + - " * [`pass` *pass-name*](#pass-pass-name)\n" + - " * [`promptBool` *prompt*](#promptbool-prompt)\n" + - " * [`promptInt` *prompt*](#promptint-prompt)\n" + - " * [`promptString` *prompt*](#promptstring-prompt)\n" + - " * [`secret` [*args*]](#secret-args)\n" + - " * [`secretJSON` [*args*]](#secretjson-args)\n" + - " * [`stat` *name*](#stat-name)\n" + - " * [`vault` *key*](#vault-key)\n" + - "\n" + - "## Concepts\n" + - "\n" + - "chezmoi evaluates the source state for the current machine and then updates the\n" + - "destination directory, where:\n" + - "\n" + - "* The *source state* declares the desired state of your home directory,\n" + - " including templates and machine-specific configuration.\n" + - "\n" + - "* The *source directory* is where chezmoi stores the source state, by default\n" + - " `~/.local/share/chezmoi`.\n" + - "\n" + - "* The *target state* is the source state computed for the current machine.\n" + - "\n" + - "* The *destination directory* is the directory that chezmoi manages, by default\n" + - " `~`, your home directory.\n" + - "\n" + - "* A *target* is a file, directory, or symlink in the destination directory.\n" + - "\n" + - "* The *destination state* is the current state of all the targets in the\n" + - " destination directory.\n" + - "\n" + - "* The *config file* contains machine-specific configuration, by default it is\n" + - " `~/.config/chezmoi/chezmoi.toml`.\n" + - "\n" + - "## Global command line flags\n" + - "\n" + - "Command line flags override any values set in the configuration file.\n" + - "\n" + - "### `--color` *value*\n" + - "\n" + - "Colorize diffs, *value* can be `on`, `off`, `auto`, or any boolean-like value\n" + - "recognized by\n" + - "[`strconv.ParseBool`](https://pkg.go.dev/strconv?tab=doc#ParseBool). The default\n" + - "value is `auto` which will colorize diffs only if the the environment variable\n" + - "`NO_COLOR` is not set and stdout is a terminal.\n" + - "\n" + - "### `-c`, `--config` *filename*\n" + - "\n" + - "Read the configuration from *filename*.\n" + - "\n" + - "### `--debug`\n" + - "\n" + - "Log information helpful for debugging.\n" + - "\n" + - "### `-D`, `--destination` *directory*\n" + - "\n" + - "Use *directory* as the destination directory.\n" + - "\n" + - "### `--follow`\n" + - "\n" + - "If the last part of a target is a symlink, deal with what the symlink\n" + - "references, rather than the symlink itself.\n" + - "\n" + - "### `-n`, `--dry-run`\n" + - "\n" + - "Set dry run mode. In dry run mode, the destination directory is never modified.\n" + - "This is most useful in combination with the `-v` (verbose) flag to print changes\n" + - "that would be made without making them.\n" + - "\n" + - "### `-h`, `--help`\n" + - "\n" + - "Print help.\n" + - "\n" + - "### `-r`. `--remove`\n" + - "\n" + - "Also remove targets according to `.chezmoiremove`.\n" + - "\n" + - "### `-S`, `--source` *directory*\n" + - "\n" + - "Use *directory* as the source directory.\n" + - "\n" + - "### `-v`, `--verbose`\n" + - "\n" + - "Set verbose mode. In verbose mode, chezmoi prints the changes that it is making\n" + - "as approximate shell commands, and any differences in files between the target\n" + - "state and the destination set are printed as unified diffs.\n" + - "\n" + - "### `--version`\n" + - "\n" + - "Print the version of chezmoi, the commit at which it was built, and the build\n" + - "timestamp.\n" + - "\n" + - "## Configuration file\n" + - "\n" + - "chezmoi searches for its configuration file according to the [XDG Base Directory\n" + - "Specification](https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html)\n" + - "and supports all formats supported by\n" + - "[`github.com/spf13/viper`](https://github.com/spf13/viper), namely\n" + - "[JSON](https://www.json.org/json-en.html),\n" + - "[TOML](https://github.com/toml-lang/toml), [YAML](https://yaml.org/), macOS\n" + - "property file format, and [HCL](https://github.com/hashicorp/hcl). The basename\n" + - "of the config file is `chezmoi`, and the first config file found is used.\n" + - "\n" + - "### Variables\n" + - "\n" + - "The following configuration variables are available:\n" + - "\n" + - "| Section | Variable | Type | Default value | Description |\n" + - "| --------------- | ------------ | -------- | ------------------------- | --------------------------------------------------- |\n" + - "| Top level | `color` | string | `auto` | Colorize diffs |\n" + - "| | `data` | any | *none* | Template data |\n" + - "| | `destDir` | string | `~` | Destination directory |\n" + - "| | `dryRun` | bool | `false` | Dry run mode |\n" + - "| | `follow` | bool | `false` | Follow symlinks |\n" + - "| | `remove` | bool | `false` | Remove targets |\n" + - "| | `sourceDir` | string | `~/.local/share/chezmoi` | Source directory |\n" + - "| | `umask` | int | *from system* | Umask |\n" + - "| | `verbose` | bool | `false` | Verbose mode |\n" + - "| `bitwarden` | `command` | string | `bw` | Bitwarden CLI command |\n" + - "| `cd` | `args` | []string | *none* | Extra args to shell in `cd` command |\n" + - "| | `command` | string | *none* | Shell to run in `cd` command |\n" + - "| `diff` | `format` | string | `chezmoi` | Diff format, either `chezmoi` or `git` |\n" + - "| | `pager` | string | *none* | Pager |\n" + - "| `genericSecret` | `command` | string | *none* | Generic secret command |\n" + - "| `gopass` | `command` | string | `gopass` | gopass CLI command |\n" + - "| `gpg` | `command` | string | `gpg` | GPG CLI command |\n" + - "| | `recipient` | string | *none* | GPG recipient |\n" + - "| | `symmetric` | bool | `false` | Use symmetric GPG encryption |\n" + - "| `keepassxc` | `args` | []string | *none* | Extra args to KeePassXC CLI command |\n" + - "| | `command` | string | `keepassxc-cli` | KeePassXC CLI command |\n" + - "| | `database` | string | *none* | KeePassXC database |\n" + - "| `lastpass` | `command` | string | `lpass` | Lastpass CLI command |\n" + - "| `merge` | `args` | []string | *none* | Extra args to 3-way merge command |\n" + - "| | `command` | string | `vimdiff` | 3-way merge command |\n" + - "| `onepassword` | `cache` | bool | `true` | Enable optional caching provided by `op` |\n" + - "| | `command` | string | `op` | 1Password CLI command |\n" + - "| `pass` | `command` | string | `pass` | Pass CLI command |\n" + - "| `sourceVCS` | `autoCommit` | bool | `false` | Commit changes to the source state after any change |\n" + - "| | `autoPush` | bool | `false` | Push changes to the source state after any change |\n" + - "| | `command` | string | `git` | Source version control system |\n" + - "| `template` | `options` | []string | `[\"missingkey=error\"]` | Template options |\n" + - "| `vault` | `command` | string | `vault` | Vault CLI command |\n" + - "\n" + - "### Examples\n" + - "\n" + - "#### JSON\n" + - "\n" + - "```json\n" + - "{\n" + - " \"sourceDir\": \"/home/user/.dotfiles\",\n" + - " \"diff\": {\n" + - " \"format\": \"git\"\n" + - " }\n" + - "}\n" + - "```\n" + - "\n" + - "#### TOML\n" + - "\n" + - "```toml\n" + - "sourceDir = \"/home/user/.dotfiles\"\n" + - "[diff]\n" + - " format = \"git\"\n" + - "```\n" + - "\n" + - "#### YAML\n" + - "\n" + - "```yaml\n" + - "sourceDir: /home/user/.dotfiles\n" + - "diff:\n" + - " format: git\n" + - "```\n" + - "\n" + - "## Source state attributes\n" + - "\n" + - "chezmoi stores the source state of files, symbolic links, and directories in\n" + - "regular files and directories in the source directory (`~/.local/share/chezmoi`\n" + - "by default). This location can be overridden with the `-S` flag or by giving a\n" + - "value for `sourceDir` in `~/.config/chezmoi/chezmoi.toml`. Some state is\n" + - "encoded in the source names. chezmoi ignores all files and directories in the\n" + - "source directory that begin with a `.`. The following prefixes and suffixes are\n" + - "special, and are collectively referred to as \"attributes\":\n" + - "\n" + - "| Prefix | Effect |\n" + - "| ------------ | ------------------------------------------------------------------------------ |\n" + - "| `encrypted_` | Encrypt the file in the source state. |\n" + - "| `once_` | Only run script once. |\n" + - "| `private_` | Remove all group and world permissions from the target file or directory. |\n" + - "| `empty_` | Ensure the file exists, even if is empty. By default, empty files are removed. |\n" + - "| `exact_` | Remove anything not managed by chezmoi. |\n" + - "| `executable_`| Add executable permissions to the target file. |\n" + - "| `run_` | Treat the contents as a script to run. |\n" + - "| `symlink_` | Create a symlink instead of a regular file. |\n" + - "| `dot_` | Rename to use a leading dot, e.g. `dot_foo` becomes `.foo`. |\n" + - "\n" + - "| Suffix | Effect |\n" + - "| ------- | ---------------------------------------------------- |\n" + - "| `.tmpl` | Treat the contents of the source file as a template. |\n" + - "\n" + - "Order of prefixes is important, the order is `run_`, `exact_`, `private_`,\n" + - "`empty_`, `executable_`, `symlink_`, `once_`, `dot_`.\n" + - "\n" + - "Different target types allow different prefixes and suffixes:\n" + - "\n" + - "| Target type | Allowed prefixes | Allowed suffixes |\n" + - "| ------------- | --------------------------------------------------------- | ---------------- |\n" + - "| Directory | `exact_`, `private_`, `dot_` | *none* |\n" + - "| Regular file | `encrypted_`, `private_`, `empty_`, `executable_`, `dot_` | `.tmpl` |\n" + - "| Script | `run_`, `once_` | `.tmpl` |\n" + - "| Symbolic link | `symlink_`, `dot_`, | `.tmpl` |\n" + - "\n" + - "## Special files and directories\n" + - "\n" + - "All files and directories in the source state whose name begins with `.` are\n" + - "ignored by default, unless they are one of the special files listed here.\n" + - "\n" + - "### `.chezmoi.<format>.tmpl`\n" + - "\n" + - "If a file called `.chezmoi.<format>.tmpl` exists then `chezmoi init` will use it\n" + - "to create an initial config file. *format* must be one of the the supported\n" + - "config file formats.\n" + - "\n" + - "#### `.chezmoi.<format>.tmpl` examples\n" + - "\n" + - " {{ $email := promptString \"email\" -}}\n" + - " data:\n" + - " email: \"{{ $email }}\"\n" + - "\n" + - "### `.chezmoiignore`\n" + - "\n" + - "If a file called `.chezmoiignore` exists in the source state then it is\n" + - "interpreted as a set of patterns to ignore. Patterns are matched using\n" + - "[`doublestar.PathMatch`](https://pkg.go.dev/github.com/bmatcuk/doublestar?tab=doc#PathMatch)\n" + - "and match against the target path, not the source path.\n" + - "\n" + - "Patterns can be excluded by prefixing them with a `!` character. All excludes\n" + - "take priority over all includes.\n" + - "\n" + - "Comments are introduced with the `#` character and run until the end of the\n" + - "line.\n" + - "\n" + - "`.chezmoiignore` is interpreted as a template. This allows different files to be\n" + - "ignored on different machines.\n" + - "\n" + - "`.chezmoiignore` files in subdirectories apply only to that subdirectory.\n" + - "\n" + - "#### `.chezmoiignore` examples\n" + - "\n" + - " README.md\n" + - "\n" + - " *.txt # ignore *.txt in the target directory\n" + - " */*.txt # ignore *.txt in subdirectories of the target directory\n" + - " # but not in subdirectories of subdirectories;\n" + - " # so a/b/c.txt would *not* be ignored\n" + - " backups/** # ignore all contents of backups folder in chezmoi directory\n" + - " # but not backups folder itself\n" + - "\n" + - " {{- if ne .email \"[email protected]\" }}\n" + - " # Ignore .company-directory unless configured with a company email\n" + - " .company-directory # note that the pattern is not dot_company-directory\n" + - " {{- end }}\n" + - "\n" + - " {{- if ne .email \"[email protected] }}\n" + - " .personal-file\n" + - " {{- end }}\n" + - "\n" + - "### `.chezmoiremove`\n" + - "\n" + - "If a file called `.chezmoiremove` exists in the source state then it is\n" + - "interpreted as a list of targets to remove. `.chezmoiremove` is interpreted as a\n" + - "template.\n" + - "\n" + - "### `.chezmoitemplates`\n" + - "\n" + - "If a directory called `.chezmoitemplates` exists, then all files in this\n" + - "directory are parsed as templates are available as templates with a name equal\n" + - "to the relative path of the file.\n" + - "\n" + - "#### `.chezmoitemplates` examples\n" + - "\n" + - "Given:\n" + - "\n" + - " .chezmoitemplates/foo\n" + - " {{ if true }}bar{{ end }}\n" + - "\n" + - " dot_config.tmpl\n" + - " {{ template \"foo\" }}\n" + - "\n" + - "The target state of `.config` will be `bar`.\n" + - "\n" + - "### `.chezmoiversion`\n" + - "\n" + - "If a file called `.chezmoiversion` exists, then its contents are interpreted as\n" + - "a semantic version defining the minimum version of chezmoi required to interpret\n" + - "the source state correctly. chezmoi will refuse to interpret the source state if\n" + - "the current version is too old.\n" + - "\n" + - "#### `.chezmoiversion` examples\n" + - "\n" + - " 1.5.0\n" + - "\n" + - "## Commands\n" + - "\n" + - "### `add` *targets*\n" + - "\n" + - "Add *targets* to the source state. If any target is already in the source state,\n" + - "then its source state is replaced with its current state in the destination\n" + - "directory. The `add` command accepts additional flags:\n" + - "\n" + - "#### `--autotemplate`\n" + - "\n" + - "Automatically generate a template by replacing strings with variable names from\n" + - "the `data` section of the config file. Longer substitutions occur before shorter\n" + - "ones. This implies the `--template` option.\n" + - "\n" + - "#### `-e`, `--empty`\n" + - "\n" + - "Set the `empty` attribute on added files.\n" + - "\n" + - "#### `-f`, `--force`\n" + - "\n" + - "Add *targets*, even if doing so would cause a source template to be overwritten.\n" + - "\n" + - "#### `-x`, `--exact`\n" + - "\n" + - "Set the `exact` attribute on added directories.\n" + - "\n" + - "#### `-p`, `--prompt`\n" + - "\n" + - "Interactively prompt before adding each file.\n" + - "\n" + - "#### `-r`, `--recursive`\n" + - "\n" + - "Recursively add all files, directories, and symlinks.\n" + - "\n" + - "#### `-T`, `--template`\n" + - "\n" + - "Set the `template` attribute on added files and symlinks.\n" + - "\n" + - "#### `add` examples\n" + - "\n" + - " chezmoi add ~/.bashrc\n" + - " chezmoi add ~/.gitconfig --template\n" + - " chezmoi add ~/.vim --recursive\n" + - " chezmoi add ~/.oh-my-zsh --exact --recursive\n" + - "\n" + - "### `apply` [*targets*]\n" + - "\n" + - "Ensure that *targets* are in the target state, updating them if necessary. If no\n" + - "targets are specified, the state of all targets are ensured.\n" + - "\n" + - "#### `apply` examples\n" + - "\n" + - " chezmoi apply\n" + - " chezmoi apply --dry-run --verbose\n" + - " chezmoi apply ~/.bashrc\n" + - "\n" + - "### `archive`\n" + - "\n" + - "Generate a tar archive of the target state. This can be piped into `tar` to\n" + - "inspect the target state.\n" + - "\n" + - "#### `--output`, `-o` *filename*\n" + - "\n" + - "Write the output to *filename* instead of stdout.\n" + - "\n" + - "#### `archive` examples\n" + - "\n" + - " chezmoi archive | tar tvf -\n" + - " chezmoi archive --output=dotfiles.tar\n" + - "\n" + - "### `cat` *targets*\n" + - "\n" + - "Write the target state of *targets* to stdout. *targets* must be files or\n" + - "symlinks. For files, the target file contents are written. For symlinks, the\n" + - "target target is written.\n" + - "\n" + - "#### `cat` examples\n" + - "\n" + - " chezmoi cat ~/.bashrc\n" + - "\n" + - "### `cd`\n" + - "\n" + - "Launch a shell in the source directory. chezmoi will launch the command set by\n" + - "the `cd.command` configuration variable with any extra arguments specified by\n" + - "`cd.args`. If this is not set, chezmoi will attempt to detect your shell and\n" + - "will finally fall back to an OS-specific default.\n" + - "\n" + - "#### `cd` examples\n" + - "\n" + - " chezmoi cd\n" + - "\n" + - "### `chattr` *attributes* *targets*\n" + - "\n" + - "Change the attributes of *targets*. *attributes* specifies which attributes to\n" + - "modify. Add attributes by specifying them or their abbreviations directly,\n" + - "optionally prefixed with a plus sign (`+`). Remove attributes by prefixing them\n" + - "or their attributes with the string `no` or a minus sign (`-`). The available\n" + - "attributes and their abbreviations are:\n" + - "\n" + - "| Attribute | Abbreviation |\n" + - "| ------------ | ------------ |\n" + - "| `empty` | `e` |\n" + - "| `encrypted` | *none* |\n" + - "| `exact` | *none* |\n" + - "| `executable` | `x` |\n" + - "| `private` | `p` |\n" + - "| `template` | `t` |\n" + - "\n" + - "Multiple attributes modifications may be specified by separating them with a\n" + - "comma (`,`).\n" + - "\n" + - "#### `chattr` examples\n" + - "\n" + - " chezmoi chattr template ~/.bashrc\n" + - " chezmoi chattr noempty ~/.profile\n" + - " chezmoi chattr private,template ~/.netrc\n" + - "\n" + - "### `completion` *shell*\n" + - "\n" + - "Generate shell completion code for the specified shell (`bash`, `fish`,\n" + - "`powershell`, or `zsh`).\n" + - "\n" + - "#### `--output`, `-o` *filename*\n" + - "\n" + - "Write the shell completion code to *filename* instead of stdout.\n" + - "\n" + - "#### `completion` examples\n" + - "\n" + - " chezmoi completion bash\n" + - " chezmoi completion fish --output ~/.config/fish/completions/chezmoi.fish\n" + - "\n" + - "### `data`\n" + - "\n" + - "Write the computed template data in JSON format to stdout. The `data` command\n" + - "accepts additional flags:\n" + - "\n" + - "#### `-f`, `--format` *format*\n" + - "\n" + - "Print the computed template data in the given format. The accepted formats are\n" + - "`json` (JSON), `toml` (TOML), and `yaml` (YAML).\n" + - "\n" + - "#### `data` examples\n" + - "\n" + - " chezmoi data\n" + - " chezmoi data --format=yaml\n" + - "\n" + - "### `diff` [*targets*]\n" + - "\n" + - "Print the difference between the target state and the destination state for\n" + - "*targets*. If no targets are specified, print the differences for all targets.\n" + - "\n" + - "If a `diff.pager` command is set in the configuration file then the output will\n" + - "be piped into it.\n" + - "\n" + - "#### `-f`, `--format` *format*\n" + - "\n" + - "Print the diff in *format*. The format can be set with the `diff.format`\n" + - "variable in the configuration file. Valid formats are:\n" + - "\n" + - "##### `chezmoi`\n" + - "\n" + - "A mix of unified diffs and pseudo shell commands, including scripts, equivalent\n" + - "to `chezmoi apply --dry-run --verbose`.\n" + - "\n" + - "##### `git`\n" + - "\n" + - "A [git format diff](https://git-scm.com/docs/diff-format), excluding scripts. In\n" + - "version 2.0.0 of chezmoi, `git` format diffs will become the default and include\n" + - "scripts and the `chezmoi` format will be removed.\n" + - "\n" + - "#### `--no-pager`\n" + - "\n" + - "Do not use the pager.\n" + - "\n" + - "#### `diff` examples\n" + - "\n" + - " chezmoi diff\n" + - " chezmoi diff ~/.bashrc\n" + - " chezmoi diff --format=git\n" + - "\n" + - "### `docs` [*regexp*]\n" + - "\n" + - "Print the documentation page matching the regular expression *regexp*. Matching\n" + - "is case insensitive. If no pattern is given, print `REFERENCE.md`.\n" + - "\n" + - "#### `docs` examples\n" + - "\n" + - " chezmoi docs\n" + - " chezmoi docs faq\n" + - " chezmoi docs howto\n" + - "\n" + - "### `doctor`\n" + - "\n" + - "Check for potential problems.\n" + - "\n" + - "#### `doctor` examples\n" + - "\n" + - " chezmoi doctor\n" + - "\n" + - "### `dump` [*targets*]\n" + - "\n" + - "Dump the target state in JSON format. If no targets are specified, then the\n" + - "entire target state. The `dump` command accepts additional arguments:\n" + - "\n" + - "#### `-f`, `--format` *format*\n" + - "\n" + - "Print the target state in the given format. The accepted formats are `json`\n" + - "(JSON) and `yaml` (YAML).\n" + - "\n" + - "#### `dump` examples\n" + - "\n" + - " chezmoi dump ~/.bashrc\n" + - " chezmoi dump --format=yaml\n" + - "\n" + - "### `edit` [*targets*]\n" + - "\n" + - "Edit the source state of *targets*, which must be files or symlinks. If no\n" + - "targets are given the the source directory itself is opened with `$EDITOR`. The\n" + - "`edit` command accepts additional arguments:\n" + - "\n" + - "#### `-a`, `--apply`\n" + - "\n" + - "Apply target immediately after editing. Ignored if there are no targets.\n" + - "\n" + - "#### `-d`, `--diff`\n" + - "\n" + - "Print the difference between the target state and the actual state after\n" + - "editing.. Ignored if there are no targets.\n" + - "\n" + - "#### `-p`, `--prompt`\n" + - "\n" + - "Prompt before applying each target.. Ignored if there are no targets.\n" + - "\n" + - "#### `edit` examples\n" + - "\n" + - " chezmoi edit ~/.bashrc\n" + - " chezmoi edit ~/.bashrc --apply --prompt\n" + - " chezmoi edit\n" + - "\n" + - "### `edit-config`\n" + - "\n" + - "Edit the configuration file.\n" + - "\n" + - "#### `edit-config` examples\n" + - "\n" + - " chezmoi edit-config\n" + - "\n" + - "### `execute-template` [*templates*]\n" + - "\n" + - "Execute *templates*. This is useful for testing templates or for calling chezmoi\n" + - "from other scripts. *templates* are interpreted as literal templates, with no\n" + - "whitespace added to the output between arguments. If no templates are specified,\n" + - "the template is read from stdin.\n" + - "\n" + - "#### `--init`, `-i`\n" + - "\n" + - "Include simulated functions only available during `chezmoi init`.\n" + - "\n" + - "#### `--output`, `-o` *filename*\n" + - "\n" + - "Write the output to *filename* instead of stdout.\n" + - "\n" + - "#### `--promptBool` *pairs*\n" + - "\n" + - "Simulate the `promptBool` function with a function that returns values from\n" + - "*pairs*. *pairs* is a comma-separated list of *prompt*`=`*value* pairs. If\n" + - "`promptBool` is called with a *prompt* that does not match any of *pairs*, then\n" + - "it returns false.\n" + - "\n" + - "#### `--promptInt`, `-p` *pairs*\n" + - "\n" + - "Simulate the `promptInt` function with a function that returns values from\n" + - "*pairs*. *pairs* is a comma-separated list of *prompt*`=`*value* pairs. If\n" + - "`promptInt` is called with a *prompt* that does not match any of *pairs*, then\n" + - "it returns zero.\n" + - "\n" + - "#### `--promptString`, `-p` *pairs*\n" + - "\n" + - "Simulate the `promptString` function with a function that returns values from\n" + - "*pairs*. *pairs* is a comma-separated list of *prompt*`=`*value* pairs. If\n" + - "`promptString` is called with a *prompt* that does not match any of *pairs*,\n" + - "then it returns *prompt* unchanged.\n" + - "\n" + - "#### `execute-template` examples\n" + - "\n" + - " chezmoi execute-template '{{ .chezmoi.sourceDir }}'\n" + - " chezmoi execute-template '{{ .chezmoi.os }}' / '{{ .chezmoi.arch }}'\n" + - " echo '{{ .chezmoi | toJson }}' | chezmoi execute-template\n" + - " chezmoi execute-template --init --promptString [email protected] < ~/.local/share/chezmoi/.chezmoi.toml.tmpl\n" + - "\n" + - "### `forget` *targets*\n" + - "\n" + - "Remove *targets* from the source state, i.e. stop managing them.\n" + - "\n" + - "#### `forget` examples\n" + - "\n" + - " chezmoi forget ~/.bashrc\n" + - "\n" + - "### `git` [*arguments*]\n" + - "\n" + - "Run `git` *arguments* in the source directory. Note that flags in *arguments*\n" + - "must occur after `--` to prevent chezmoi from interpreting them.\n" + - "\n" + - "#### `git` examples\n" + - "\n" + - " chezmoi git add .\n" + - " chezmoi git add dot_gitconfig\n" + - " chezmoi git -- commit -m \"Add .gitconfig\"\n" + - "\n" + - "### `help` *command*\n" + - "\n" + - "Print the help associated with *command*.\n" + - "\n" + - "### `hg` [*arguments*]\n" + - "\n" + - "Run `hg` *arguments* in the source directory. Note that flags in *arguments*\n" + - "must occur after `--` to prevent chezmoi from interpreting them.\n" + - "\n" + - "#### `hg` examples\n" + - "\n" + - " chezmoi hg -- pull --rebase --update\n" + - "\n" + - "### `init` [*repo*]\n" + - "\n" + - "Setup the source directory and update the destination directory to match the\n" + - "target state.\n" + - "\n" + - "First, if the source directory is not already contain a repository, then if\n" + - "*repo* is given it is checked out into the source directory, otherwise a new\n" + - "repository is initialized in the source directory.\n" + - "\n" + - "Second, if a file called `.chezmoi.format.tmpl` exists, where `format` is one of\n" + - "the supported file formats (e.g. `json`, `toml`, or `yaml`) then a new\n" + - "configuration file is created using that file as a template.\n" + - "\n" + - "Finally, if the `--apply` flag is passed, `chezmoi apply` is run.\n" + - "\n" + - "#### `--apply`\n" + - "\n" + - "Run `chezmoi apply` after checking out the repo and creating the config file.\n" + - "This is `false` by default.\n" + - "\n" + - "#### `init` examples\n" + - "\n" + - " chezmoi init https://github.com/user/dotfiles.git\n" + - " chezmoi init https://github.com/user/dotfiles.git --apply\n" + - "\n" + - "### `import` *filename*\n" + - "\n" + - "Import the source state from an archive file in to a directory in the source\n" + - "state. This is primarily used to make subdirectories of your home directory\n" + - "exactly match the contents of a downloaded archive. You will generally always\n" + - "want to set the `--destination`, `--exact`, and `--remove-destination` flags.\n" + - "\n" + - "The only supported archive format is `.tar.gz`.\n" + - "\n" + - "#### `--destination` *directory*\n" + - "\n" + - "Set the destination (in the source state) where the archive will be imported.\n" + - "\n" + - "#### `-x`, `--exact`\n" + - "\n" + - "Set the `exact` attribute on all imported directories.\n" + - "\n" + - "#### `-r`, `--remove-destination`\n" + - "\n" + - "Remove destination (in the source state) before importing.\n" + - "\n" + - "#### `--strip-components` *n*\n" + - "\n" + - "Strip *n* leading components from paths.\n" + - "\n" + - "#### `import` examples\n" + - "\n" + - " curl -s -L -o oh-my-zsh-master.tar.gz https://github.com/robbyrussell/oh-my-zsh/archive/master.tar.gz\n" + - " chezmoi import --strip-components 1 --destination ~/.oh-my-zsh oh-my-zsh-master.tar.gz\n" + - "\n" + - "### `manage` *targets*\n" + - "\n" + - "`manage` is an alias for `add` for symmetry with `unmanage`.\n" + - "\n" + - "### `managed`\n" + - "\n" + - "List all managed entries in the destination directory in alphabetical order.\n" + - "\n" + - "#### `-i`, `--include` *types*\n" + - "\n" + - "Only list entries of type *types*. *types* is a comma-separated list of types of\n" + - "entry to include. Valid types are `dirs`, `files`, and `symlinks` which can be\n" + - "abbreviated to `d`, `f`, and `s` respectively. By default, `manage` will list\n" + - "entries of all types.\n" + - "\n" + - "#### `managed` examples\n" + - "\n" + - " chezmoi managed\n" + - " chezmoi managed --include=files\n" + - " chezmoi managed --include=files,symlinks\n" + - " chezmoi managed -i d\n" + - " chezmoi managed -i d,f\n" + - "\n" + - "### `merge` *targets*\n" + - "\n" + - "Perform a three-way merge between the destination state, the source state, and\n" + - "the target state. The merge tool is defined by the `merge.command` configuration\n" + - "variable, and defaults to `vimdiff`. If multiple targets are specified the merge\n" + - "tool is invoked for each target. If the target state cannot be computed (for\n" + - "example if source is a template containing errors or an encrypted file that\n" + - "cannot be decrypted) a two-way merge is performed instead.\n" + - "\n" + - "#### `merge` examples\n" + - "\n" + - " chezmoi merge ~/.bashrc\n" + - "\n" + - "### `purge`\n" + - "\n" + - "Remove chezmoi's configuration, state, and source directory, but leave the\n" + - "target state intact.\n" + - "\n" + - "#### `-f`, `--force`\n" + - "\n" + - "Remove without prompting.\n" + - "\n" + - "#### `purge` examples\n" + - "\n" + - " chezmoi purge\n" + - " chezmoi purge --force\n" + - "\n" + - "### `remove` *targets*\n" + - "\n" + - "Remove *targets* from both the source state and the destination directory.\n" + - "\n" + - "#### `-f`, `--force`\n" + - "\n" + - "Remove without prompting.\n" + - "\n" + - "### `rm` *targets*\n" + - "\n" + - "`rm` is an alias for `remove`.\n" + - "\n" + - "### `secret`\n" + - "\n" + - "Run a secret manager's CLI, passing any extra arguments to the secret manager's\n" + - "CLI. This is primarily for verifying chezmoi's integration with your secret\n" + - "manager. Normally you would use template functions to retrieve secrets. Note\n" + - "that if you want to pass flags to the secret manager's CLI you will need to\n" + - "separate them with `--` to prevent chezmoi from interpreting them.\n" + - "\n" + - "To get a full list of available commands run:\n" + - "\n" + - " chezmoi secret help\n" + - "\n" + - "#### `secret` examples\n" + - "\n" + - " chezmoi secret bitwarden list items\n" + - " chezmoi secret keyring set --service service --user user\n" + - " chezmoi secret keyring get --service service --user user\n" + - " chezmoi secret lastpass ls\n" + - " chezmoi secret lastpass -- show --format=json id\n" + - " chezmoi secret onepassword list items\n" + - " chezmoi secret onepassword get item id\n" + - " chezmoi secret pass show id\n" + - " chezmoi secret vault -- kv get -format=json id\n" + - "\n" + - "### `source` [*args*]\n" + - "\n" + - "Execute the source version control system in the source directory with *args*.\n" + - "Note that any flags for the source version control system must be separated with\n" + - "a `--` to stop chezmoi from reading them.\n" + - "\n" + - "#### `source` examples\n" + - "\n" + - " chezmoi source init\n" + - " chezmoi source add .\n" + - " chezmoi source commit -- -m \"Initial commit\"\n" + - "\n" + - "### `source-path` [*targets*]\n" + - "\n" + - "Print the path to each target's source state. If no targets are specified then\n" + - "print the source directory.\n" + - "\n" + - "#### `source-path` examples\n" + - "\n" + - " chezmoi source-path\n" + - " chezmoi source-path ~/.bashrc\n" + - "\n" + - "### `unmanage` *targets*\n" + - "\n" + - "`unmanage` is an alias for `forget` for symmetry with `manage`.\n" + - "\n" + - "### `unmanaged`\n" + - "\n" + - "List all unmanaged files in the destination directory.\n" + - "\n" + - "#### `unmanaged` examples\n" + - "\n" + - " chezmoi unmanaged\n" + - "\n" + - "### `update`\n" + - "\n" + - "Pull changes from the source VCS and apply any changes.\n" + - "\n" + - "#### `update` examples\n" + - "\n" + - " chezmoi update\n" + - "\n" + - "### `upgrade`\n" + - "\n" + - "Upgrade chezmoi by downloading and installing the latest released version. This\n" + - "will call the GitHub API to determine if there is a new version of chezmoi\n" + - "available, and if so, download and attempt to install it in the same way as\n" + - "chezmoi was previously installed.\n" + - "\n" + - "If chezmoi was installed with a package manager (`dpkg` or `rpm`) then `upgrade`\n" + - "will download a new package and install it, using `sudo` if it is installed.\n" + - "Otherwise, chezmoi will download the latest executable and replace the existing\n" + - "executable with the new version.\n" + - "\n" + - "If the `CHEZMOI_GITHUB_API_TOKEN` environment variable is set, then its value\n" + - "will be used to authenticate requests to the GitHub API, otherwise\n" + - "unauthenticated requests are used which are subject to stricter [rate\n" + - "limiting](https://developer.github.com/v3/#rate-limiting). Unauthenticated\n" + - "requests should be sufficient for most cases.\n" + - "\n" + - "#### `upgrade` examples\n" + - "\n" + - " chezmoi upgrade\n" + - "\n" + - "### `verify` [*targets*]\n" + - "\n" + - "Verify that all *targets* match their target state. chezmoi exits with code 0\n" + - "(success) if all targets match their target state, or 1 (failure) otherwise. If\n" + - "no targets are specified then all targets are checked.\n" + - "\n" + - "#### `verify` examples\n" + - "\n" + - " chezmoi verify\n" + - " chezmoi verify ~/.bashrc\n" + - "\n" + - "## Editor configuration\n" + - "\n" + - "The `edit` and `edit-config` commands use the editor specified by the `VISUAL`\n" + - "environment variable, the `EDITOR` environment variable, or `vi`, whichever is\n" + - "specified first.\n" + - "\n" + - "## Umask configuration\n" + - "\n" + - "By default, chezmoi uses your current umask as set by your operating system and\n" + - "shell. chezmoi only stores crude permissions in its source state, namely in the\n" + - "`executable` and `private` attributes, corresponding to the umasks of `0o111`\n" + - "and `0o077` respectively.\n" + - "\n" + - "For machine-specific control of umask, set the `umask` configuration variable in\n" + - "chezmoi's configuration file, for example:\n" + - "\n" + - " umask = 0o22\n" + - "\n" + - "## Template execution\n" + - "\n" + - "chezmoi executes templates using\n" + - "[`text/template`](https://pkg.go.dev/text/template). The result is treated\n" + - "differently depending on whether the target is a file or a symlink.\n" + - "\n" + - "If target is a file, then:\n" + - "\n" + - "* If the result is an empty string, then the file is removed.\n" + - "* Otherwise, the target file contents are result.\n" + - "\n" + - "If the target is a symlink, then:\n" + - "\n" + - "* Leading and trailing whitespace are stripped from the result.\n" + - "* If the result is an empty string, then the symlink is removed.\n" + - "* Otherwise, the target symlink target is the result.\n" + - "\n" + - "chezmoi executes templates using `text/template`'s `missingkey=error` option,\n" + - "which means that misspelled or missing keys will raise an error. This can be\n" + - "overridden by setting a list of options in the configuration file, for example:\n" + - "\n" + - " [template]\n" + - " options = [\"missingkey=zero\"]\n" + - "\n" + - "For a full list of options, see\n" + - "[`Template.Option`](https://pkg.go.dev/text/template?tab=doc#Template.Option).\n" + - "\n" + - "## Template variables\n" + - "\n" + - "chezmoi provides the following automatically populated variables:\n" + - "\n" + - "| Variable | Value |\n" + - "| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------- |\n" + - "| `.chezmoi.arch` | Architecture, e.g. `amd64`, `arm`, etc. as returned by [runtime.GOARCH](https://pkg.go.dev/runtime?tab=doc#pkg-constants). |\n" + - "| `.chezmoi.fullHostname` | The full hostname of the machine chezmoi is running on. |\n" + - "| `.chezmoi.group` | The group of the user running chezmoi. |\n" + - "| `.chezmoi.homedir` | The home directory of the user running chezmoi. |\n" + - "| `.chezmoi.hostname` | The hostname of the machine chezmoi is running on, up to the first `.`. |\n" + - "| `.chezmoi.kernel` | Contains information from `/proc/sys/kernel`. Linux only, useful for detecting specific kernels (i.e. Microsoft's WSL kernel). |\n" + - "| `.chezmoi.os` | Operating system, e.g. `darwin`, `linux`, etc. as returned by [runtime.GOOS](https://pkg.go.dev/runtime?tab=doc#pkg-constants). |\n" + - "| `.chezmoi.osRelease` | The information from `/etc/os-release`, Linux only, run `chezmoi data` to see its output. |\n" + - "| `.chezmoi.sourceDir` | The source directory. |\n" + - "| `.chezmoi.username` | The username of the user running chezmoi. |\n" + - "\n" + - "Additional variables can be defined in the config file in the `data` section.\n" + - "Variable names must consist of a letter and be followed by zero or more letters\n" + - "and/or digits.\n" + - "\n" + - "## Template functions\n" + - "\n" + - "All standard [`text/template`](https://pkg.go.dev/text/template) and [text\n" + - "template functions from `sprig`](http://masterminds.github.io/sprig/) are\n" + - "included. chezmoi provides some additional functions.\n" + - "\n" + - "### `bitwarden` [*args*]\n" + - "\n" + - "`bitwarden` returns structured data retrieved from\n" + - "[Bitwarden](https://bitwarden.com) using the [Bitwarden\n" + - "CLI](https://github.com/bitwarden/cli) (`bw`). *args* are passed to `bw get`\n" + - "unchanged and the output from `bw get` is parsed as JSON. The output from `bw\n" + - "get` is cached so calling `bitwarden` multiple times with the same arguments\n" + - "will only invoke `bw` once.\n" + - "\n" + - "#### `bitwarden` examples\n" + - "\n" + - " username = {{ (bitwarden \"item\" \"<itemid>\").login.username }}\n" + - " password = {{ (bitwarden \"item\" \"<itemid>\").login.password }}\n" + - "\n" + - "### `bitwardenAttachment` *filename* *itemid*\n" + - "\n" + - "`bitwardenAttachment` returns a document from\n" + - "[Bitwarden](https://bitwarden.com/) using the [Bitwarden\n" + - "CLI](https://bitwarden.com/help/article/cli/) (`bw`). *filename* and *itemid* is\n" + - "passed to `bw get attachment <filename> --itemid <itemid>` and the output from\n" + - "`bw` is returned. The output from `bw` is cached so calling\n" + - "`bitwardenAttachment` multiple times with the same *filename* and *itemid* will\n" + - "only invoke `bw` once.\n" + - "\n" + - "#### `bitwardenAttachment` examples\n" + - "\n" + - " {{- (bitwardenAttachment \"<filename>\" \"<itemid>\") -}}\n" + - "\n" + - "### `bitwardenFields` [*args*]\n" + - "\n" + - "`bitwardenFields` returns structured data retrieved from\n" + - "[Bitwarden](https://bitwarden.com) using the [Bitwarden\n" + - "CLI](https://github.com/bitwarden/cli) (`bw`). *args* are passed to `bw get`\n" + - "unchanged, the output from `bw get` is parsed as JSON, and elements of `fields`\n" + - "are returned as a map indexed by each field's `name`. For example, given the\n" + - "output from `bw get`:\n" + - "\n" + - "```json\n" + - "{\n" + - " \"object\": \"item\",\n" + - " \"id\": \"bf22e4b4-ae4a-4d1c-8c98-ac620004b628\",\n" + - " \"organizationId\": null,\n" + - " \"folderId\": null,\n" + - " \"type\": 1,\n" + - " \"name\": \"example.com\",\n" + - " \"notes\": null,\n" + - " \"favorite\": false,\n" + - " \"fields\": [\n" + - " {\n" + - " \"name\": \"text\",\n" + - " \"value\": \"text-value\",\n" + - " \"type\": 0\n" + - " },\n" + - " {\n" + - " \"name\": \"hidden\",\n" + - " \"value\": \"hidden-value\",\n" + - " \"type\": 1\n" + - " }\n" + - " ],\n" + - " \"login\": {\n" + - " \"username\": \"username-value\",\n" + - " \"password\": \"password-value\",\n" + - " \"totp\": null,\n" + - " \"passwordRevisionDate\": null\n" + - " },\n" + - " \"collectionIds\": [],\n" + - " \"revisionDate\": \"2020-10-28T00:21:02.690Z\"\n" + - "}\n" + - "```\n" + - "\n" + - "the return value will be the map\n" + - "\n" + - "```json\n" + - "{\n" + - " \"hidden\": {\n" + - " \"name\": \"hidden\",\n" + - " \"type\": 1,\n" + - " \"value\": \"hidden-value\"\n" + - " },\n" + - " \"token\": {\n" + - " \"name\": \"token\",\n" + - " \"type\": 0,\n" + - " \"value\": \"token-value\"\n" + - " }\n" + - "}\n" + - "```\n" + - "\n" + - "The output from `bw get` is cached so calling `bitwarden` multiple times with\n" + - "the same arguments will only invoke `bw get` once.\n" + - "\n" + - "#### `bitwardenFields` examples\n" + - "\n" + - " {{ (bitwardenFields \"item\" \"<itemid>\").token.value }}\n" + - "\n" + - "### `gopass` *gopass-name*\n" + - "\n" + - "`gopass` returns passwords stored in [gopass](https://www.gopass.pw/) using the\n" + - "gopass CLI (`gopass`). *gopass-name* is passed to `gopass show <gopass-name>`\n" + - "and first line of the output of `gopass` is returned with the trailing newline\n" + - "stripped. The output from `gopass` is cached so calling `gopass` multiple times\n" + - "with the same *gopass-name* will only invoke `gopass` once.\n" + - "\n" + - "#### `gopass` examples\n" + - "\n" + - " {{ gopass \"<pass-name>\" }}\n" + - "\n" + - "### `include` *filename*\n" + - "\n" + - "`include` returns the literal contents of the file named `*filename*`, relative\n" + - "to the source directory.\n" + - "\n" + - "### `ioreg`\n" + - "\n" + - "On macOS, `ioreg` returns the structured output of the `ioreg -a -l` command,\n" + - "which includes detailed information about the I/O Kit registry.\n" + - "\n" + - "On non-macOS operating systems, `ioreg` returns `nil`.\n" + - "\n" + - "The output from `ioreg` is cached so multiple calls to the `ioreg` function will\n" + - "only execute the `ioreg -a -l` command once.\n" + - "\n" + - "#### `ioreg` examples\n" + - "\n" + - " {{ if (eq .chezmoi.os \"darwin\") }}\n" + - " {{ $serialNumber := index ioreg \"IORegistryEntryChildren\" 0 \"IOPlatformSerialNumber\" }}\n" + - " {{ end }}\n" + - "\n" + - "### `joinPath` *elements*\n" + - "\n" + - "`joinPath` joins any number of path elements into a single path, separating them\n" + - "with the OS-specific path separator. Empty elements are ignored. The result is\n" + - "cleaned. If the argument list is empty or all its elements are empty, `joinPath`\n" + - "returns an empty string. On Windows, the result will only be a UNC path if the\n" + - "first non-empty element is a UNC path.\n" + - "\n" + - "#### `joinPath` examples\n" + - "\n" + - " {{ joinPath .chezmoi.homedir \".zshrc\" }}\n" + - "\n" + - "### `keepassxc` *entry*\n" + - "\n" + - "`keepassxc` returns structured data retrieved from a\n" + - "[KeePassXC](https://keepassxc.org/) database using the KeePassXC CLI\n" + - "(`keepassxc-cli`). The database is configured by setting `keepassxc.database` in\n" + - "the configuration file. *database* and *entry* are passed to `keepassxc-cli\n" + - "show`. You will be prompted for the database password the first time\n" + - "`keepassxc-cli` is run, and the password is cached, in plain text, in memory\n" + - "until chezmoi terminates. The output from `keepassxc-cli` is parsed into\n" + - "key-value pairs and cached so calling `keepassxc` multiple times with the same\n" + - "*entry* will only invoke `keepassxc-cli` once.\n" + - "\n" + - "#### `keepassxc` examples\n" + - "\n" + - " username = {{ (keepassxc \"example.com\").UserName }}\n" + - " password = {{ (keepassxc \"example.com\").Password }}\n" + - "\n" + - "### `keepassxcAttribute` *entry* *attribute*\n" + - "\n" + - "`keepassxcAttribute` returns the attribute *attribute* of *entry* using\n" + - "`keepassxc-cli`, with any leading or trailing whitespace removed. It behaves\n" + - "identically to the `keepassxc` function in terms of configuration, password\n" + - "prompting, password storage, and result caching.\n" + - "\n" + - "#### `keepassxcAttribute` examples\n" + - "\n" + - " {{ keepassxcAttribute \"SSH Key\" \"private-key\" }}\n" + - "\n" + - "### `keyring` *service* *user*\n" + - "\n" + - "`keyring` retrieves the value associated with *service* and *user* from the\n" + - "user's keyring.\n" + - "\n" + - "| OS | Keyring |\n" + - "| ------- | --------------------------- |\n" + - "| macOS | Keychain |\n" + - "| Linux | GNOME Keyring |\n" + - "| Windows | Windows Credentials Manager |\n" + - "\n" + - "#### `keyring` examples\n" + - "\n" + - " [github]\n" + - " user = \"{{ .github.user }}\"\n" + - " token = \"{{ keyring \"github\" .github.user }}\"\n" + - "\n" + - "### `lastpass` *id*\n" + - "\n" + - "`lastpass` returns structured data from [LastPass](https://lastpass.com) using\n" + - "the [LastPass CLI](https://lastpass.github.io/lastpass-cli/lpass.1.html)\n" + - "(`lpass`). *id* is passed to `lpass show --json <id>` and the output from\n" + - "`lpass` is parsed as JSON. In addition, the `note` field, if present, is further\n" + - "parsed as colon-separated key-value pairs. The structured data is an array so\n" + - "typically the `index` function is used to extract the first item. The output\n" + - "from `lastpass` is cached so calling `lastpass` multiple times with the same\n" + - "*id* will only invoke `lpass` once.\n" + - "\n" + - "#### `lastpass` examples\n" + - "\n" + - " githubPassword = \"{{ (index (lastpass \"GitHub\") 0).password }}\"\n" + - " {{ (index (lastpass \"SSH\") 0).note.privateKey }}\n" + - "\n" + - "### `lastpassRaw` *id*\n" + - "\n" + - "`lastpassRaw` returns structured data from [LastPass](https://lastpass.com)\n" + - "using the [LastPass CLI](https://lastpass.github.io/lastpass-cli/lpass.1.html)\n" + - "(`lpass`). It behaves identically to the `lastpass` function, except that no\n" + - "further parsing is done on the `note` field.\n" + - "\n" + - "#### `lastpassRaw` examples\n" + - "\n" + - " {{ (index (lastpassRaw \"SSH Private Key\") 0).note }}\n" + - "\n" + - "### `lookPath` *file*\n" + - "\n" + - "`lookPath` searches for an executable named *file* in the directories named by\n" + - "the `PATH` environment variable. If file contains a slash, it is tried directly\n" + - "and the `PATH` is not consulted. The result may be an absolute path or a path\n" + - "relative to the current directory. If *file* is not found, `lookPath` returns an\n" + - "empty string.\n" + - "\n" + - "`lookPath` is not hermetic: its return value depends on the state of the\n" + - "environment and the filesystem at the moment the template is executed. Exercise\n" + - "caution when using it in your templates.\n" + - "\n" + - "#### `lookPath` examples\n" + - "\n" + - " {{ if lookPath \"diff-so-fancy\" }}\n" + - " # diff-so-fancy is in $PATH\n" + - " {{ end }}\n" + - "\n" + - "### `onepassword` *uuid* [*vault-uuid*]\n" + - "\n" + - "`onepassword` returns structured data from [1Password](https://1password.com/)\n" + - "using the [1Password\n" + - "CLI](https://support.1password.com/command-line-getting-started/) (`op`). *uuid*\n" + - "is passed to `op get item <uuid>` and the output from `op` is parsed as JSON.\n" + - "The output from `op` is cached so calling `onepassword` multiple times with the\n" + - "same *uuid* will only invoke `op` once. If the optional *vault-uuid* is supplied,\n" + - "it will be passed along to the `op get` call, which can significantly improve\n" + - "performance.\n" + - "\n" + - "#### `onepassword` examples\n" + - "\n" + - " {{ (onepassword \"<uuid>\").details.password }}\n" + - " {{ (onepassword \"<uuid>\" \"<vault-uuid>\").details.password }}\n" + - "\n" + - "### `onepasswordDocument` *uuid* [*vault-uuid*]\n" + - "\n" + - "`onepassword` returns a document from [1Password](https://1password.com/)\n" + - "using the [1Password\n" + - "CLI](https://support.1password.com/command-line-getting-started/) (`op`). *uuid*\n" + - "is passed to `op get document <uuid>` and the output from `op` is returned.\n" + - "The output from `op` is cached so calling `onepasswordDocument` multiple times with the\n" + - "same *uuid* will only invoke `op` once. If the optional *vault-uuid* is supplied,\n" + - "it will be passed along to the `op get` call, which can significantly improve\n" + - "performance.\n" + - "\n" + - "#### `onepasswordDocument` examples\n" + - "\n" + - " {{- onepasswordDocument \"<uuid>\" -}}\n" + - " {{- onepasswordDocument \"<uuid>\" \"<vault-uuid>\" -}}\n" + - "\n" + - "### `onepasswordDetailsFields` *uuid* [*vault-uuid*]\n" + - "\n" + - "`onepasswordDetailsFields` returns structured data from\n" + - "[1Password](https://1password.com/) using the [1Password\n" + - "CLI](https://support.1password.com/command-line-getting-started/) (`op`). *uuid*\n" + - "is passed to `op get item <uuid>`, the output from `op` is parsed as JSON, and\n" + - "elements of `details.fields` are returned as a map indexed by each field's\n" + - "`designation`. For example, give the output from `op`:\n" + - "\n" + - "```json\n" + - "{\n" + - " \"uuid\": \"<uuid>\",\n" + - " \"details\": {\n" + - " \"fields\": [\n" + - " {\n" + - " \"designation\": \"username\",\n" + - " \"name\": \"username\",\n" + - " \"type\": \"T\",\n" + - " \"value\": \"exampleuser\"\n" + - " },\n" + - " {\n" + - " \"designation\": \"password\",\n" + - " \"name\": \"password\",\n" + - " \"type\": \"P\",\n" + - " \"value\": \"examplepassword\"\n" + - " }\n" + - " ],\n" + - " }\n" + - "}\n" + - "```\n" + - "\n" + - "the return value will be the map:\n" + - "\n" + - "```json\n" + - "{\n" + - " \"username\": {\n" + - " \"designation\": \"username\",\n" + - " \"name\": \"username\",\n" + - " \"type\": \"T\",\n" + - " \"value\": \"exampleuser\"\n" + - " },\n" + - " \"password\": {\n" + - " \"designation\": \"password\",\n" + - " \"name\": \"password\",\n" + - " \"type\": \"P\",\n" + - " \"value\": \"examplepassword\"\n" + - " }\n" + - "}\n" + - "```\n" + - "\n" + - "The output from `op` is cached so calling `onepassword` multiple times with the\n" + - "same *uuid* will only invoke `op` once. If the optional *vault-uuid* is supplied,\n" + - "it will be passed along to the `op get` call, which can significantly improve\n" + - "performance.\n" + - "\n" + - "#### `onepasswordDetailsFields` examples\n" + - "\n" + - " {{ (onepasswordDetailsFields \"<uuid>\").password.value }}\n" + - "\n" + - "### `pass` *pass-name*\n" + - "\n" + - "`pass` returns passwords stored in [pass](https://www.passwordstore.org/) using\n" + - "the pass CLI (`pass`). *pass-name* is passed to `pass show <pass-name>` and\n" + - "first line of the output of `pass` is returned with the trailing newline\n" + - "stripped. The output from `pass` is cached so calling `pass` multiple times with\n" + - "the same *pass-name* will only invoke `pass` once.\n" + - "\n" + - "#### `pass` examples\n" + - "\n" + - " {{ pass \"<pass-name>\" }}\n" + - "\n" + - "### `promptBool` *prompt*\n" + - "\n" + - "`promptBool` prompts the user with *prompt* and returns the user's response with\n" + - "interpreted as a boolean. It is only available when generating the initial\n" + - "config file.\n" + - "\n" + - "### `promptInt` *prompt*\n" + - "\n" + - "`promptInt` prompts the user with *prompt* and returns the user's response with\n" + - "interpreted as an integer. It is only available when generating the initial\n" + - "config file.\n" + - "\n" + - "### `promptString` *prompt*\n" + - "\n" + - "`promptString` prompts the user with *prompt* and returns the user's response\n" + - "with all leading and trailing spaces stripped. It is only available when\n" + - "generating the initial config file.\n" + - "\n" + - "#### `promptString` examples\n" + - "\n" + - " {{ $email := promptString \"email\" -}}\n" + - " [data]\n" + - " email = \"{{ $email }}\"\n" + - "\n" + - "### `secret` [*args*]\n" + - "\n" + - "`secret` returns the output of the generic secret command defined by the\n" + - "`genericSecret.command` configuration variable with *args* with leading and\n" + - "trailing whitespace removed. The output is cached so multiple calls to `secret`\n" + - "with the same *args* will only invoke the generic secret command once.\n" + - "\n" + - "### `secretJSON` [*args*]\n" + - "\n" + - "`secretJSON` returns structured data from the generic secret command defined by\n" + - "the `genericSecret.command` configuration variable with *args*. The output is\n" + - "parsed as JSON. The output is cached so multiple calls to `secret` with the same\n" + - "*args* will only invoke the generic secret command once.\n" + - "\n" + - "### `stat` *name*\n" + - "\n" + - "`stat` runs `stat(2)` on *name*. If *name* exists it returns structured data. If\n" + - "*name* does not exist then it returns a false value. If `stat(2)` returns any\n" + - "other error then it raises an error. The structured value returned if *name*\n" + - "exists contains the fields `name`, `size`, `mode`, `perm`, `modTime`, and\n" + - "`isDir`.\n" + - "\n" + - "`stat` is not hermetic: its return value depends on the state of the filesystem\n" + - "at the moment the template is executed. Exercise caution when using it in your\n" + - "templates.\n" + - "\n" + - "#### `stat` examples\n" + - "\n" + - " {{ if stat (joinPath .chezmoi.homedir \".pyenv\") }}\n" + - " # ~/.pyenv exists\n" + - " {{ end }}\n" + - "\n" + - "### `vault` *key*\n" + - "\n" + - "`vault` returns structured data from [Vault](https://www.vaultproject.io/) using\n" + - "the [Vault CLI](https://www.vaultproject.io/docs/commands/) (`vault`). *key* is\n" + - "passed to `vault kv get -format=json <key>` and the output from `vault` is\n" + - "parsed as JSON. The output from `vault` is cached so calling `vault` multiple\n" + - "times with the same *key* will only invoke `vault` once.\n" + - "\n" + - "#### `vault` examples\n" + - "\n" + - " {{ (vault \"<key>\").data.data.password }}\n" + - "\n") - assets["docs/TEMPLATING.md"] = []byte("" + - "# chezmoi Templating Guide\n" + - "\n" + - "<!--- toc --->\n" + - "* [Introduction](#introduction)\n" + - "* [Creating a template file](#creating-a-template-file)\n" + - "* [Debugging templates](#debugging-templates)\n" + - "* [Simple logic](#simple-logic)\n" + - "* [More complicated logic](#more-complicated-logic)\n" + - "* [Helper functions](#helper-functions)\n" + - "* [Template variables](#template-variables)\n" + - "* [Using .chezmoitemplates for creating similar files](#using-chezmoitemplates-for-creating-similar-files)\n" + - "\n" + - "## Introduction\n" + - "\n" + - "Templates are used to change the contents of a file depending on the\n" + - "environment. For example, you can use the hostname of the machine to create\n" + - "different configurations on different machines.\n" + - "\n" + - "chezmoi uses the [`text/template`](https://pkg.go.dev/text/template) syntax from\n" + - "Go extended with [text template functions from\n" + - "`sprig`](http://masterminds.github.io/sprig/).\n" + - "\n" + - "When reading files from the source state, chezmoi interprets them as a template\n" + - "if either of the following is true:\n" + - "\n" + - "* The file name has a `.tmpl` suffix.\n" + - "* The file is in the `.chezmoitemplates` directory, or a subdirectory of\n" + - " `.chezmoitemplates`.\n" + - "\n" + - "## Template data\n" + - "\n" + - "chezmoi provides a variety of template variables. For a full list, run\n" + - "\n" + - " chezmoi data\n" + - "\n" + - "These come from a variety of sources:\n" + - "\n" + - "* Variables populated by chezmoi are in `.chezmoi`, for example `.chezmoi.os`.\n" + - "* Variables created by you in the `data` section of the configuration file.\n" + - "\n" + - "Furthermore, chezmoi provides a variety of functions to retrieve data at runtime\n" + - "from password managers, environment variables, and the filesystem.\n" + - "\n" + - "## Creating a template file\n" + - "\n" + - "There are several ways to create a template:\n" + - "\n" + - "* When adding a file for the first time, pass the `--template` argument, for example:\n" + - "\n" + - " chezmoi add --template ~/.zshrc\n" + - "\n" + - "* When adding a file for the first time, you can pass the `--autotemplate`\n" + - " argument, which tells chezmoi to make the file as a template and automatically\n" + - " replace variables that chezmoi knows about, for example:\n" + - "\n" + - " chezmoi add --autotemplate ~/.zshrc\n" + - "\n" + - "* If a file is already managed by chezmoi, but is not a template, you can make\n" + - " it a template by running, for example:\n" + - "\n" + - " chezmoi chattr +template ~/.zshrc\n" + - "\n" + - "* You can create a template manually in the source directory by giving it a\n" + - " `.tmpl` extension, for example:\n" + - "\n" + - " chezmoi cd\n" + - " $EDITOR dot_zshrc.tmpl\n" + - "\n" + - "* Templates in `.chezmoitemplates` must be created manually, for example:\n" + - "\n" + - " chezmoi cd\n" + - "\t mkdir -p .chezmoitemplates\n" + - "\t cd .chezmoitemplates\n" + - "\t $EDITOR mytemplate\n" + - "\n" + - "## Editing a template file\n" + - "\n" + - "The easiest way to edit a template is to use `chezmoi edit`, for example:\n" + - "\n" + - "\tchezmoi edit ~/.zshrc\n" + - "\n" + - "This will open the source file for `~/.zshrc` in `$EDITOR`. When you quit the\n" + - "editor, chezmoi will check the template syntax.\n" + - "\n" + - "If you want the changes you make to be immediately applied after you quit the\n" + - "editor, use the `--apply` option, for example:\n" + - "\n" + - "\tchezmoi edit --apply ~/.zshrc\n" + - "\n" + - "## Testing templates\n" + - "\n" + - "Templates can be tested with the `chezmoi execute-template` command which treats\n" + - "each of its arguments as a template and executes it. This can be useful for\n" + - "testing small fragments of templates, for example:\n" + - "\n" + - " chezmoi execute-template '{{ .chezmoi.hostname }}'\n" + - "\n" + - "If there are no arguments, `chezmoi execute-template` will read the template\n" + - "from the standard input. This can be useful for testing whole files, for example:\n" + - "\n" + - "\tchezmoi cd\n" + - "\tchezmoi execute-template < dot_zshrc.tmpl\n" + - "\n" + - "## Template syntax\n" + - "\n" + - "Template actions are written inside double curly brackets, `{{` and `}}`.\n" + - "Actions can be variables, pipelines, or control statements. Text outside actions\n" + - "is copied literally.\n" + - "\n" + - "Variables are written literally, for example:\n" + - "\n" + - " {{ .chezmoi.hostname }}\n" + - "\n" + - "Conditional expressions can be written using `if`, `else if`, `else`, and `end`,\n" + - "for example:\n" + - "\n" + - "\t{{ if (eq .chezmoi.os \"darwin\") }}\n" + - "\t# darwin\n" + - "\t{{ else if (eq .chezmoi.os \"linux\" ) }}\n" + - "\t# linux\n" + - "\t{{ else }}\n" + - "\t# other operating system\n" + - "\t{{ end }}\n" + - "\n" + - "For a full description of the template syntax, see the [`text/template`\n" + - "documentation](https://pkg.go.dev/text/template).\n" + - "\n" + - "### Removing whitespace\n" + - "\n" + - "For formatting reasons you might want to leave some whitespace after or before\n" + - "the template code. This whitespace will remain in the final file, which you\n" + - "might not want.\n" + - "\n" + - "A solution for this is to place a minus sign and a space next to the brackets.\n" + - "So `{{- ` for the left brackets and ` -}}` for the right brackets. Here's an\n" + - "example:\n" + - "\n" + - "\tHOSTNAME= {{- .chezmoi.hostname }}\n" + - "\n" + - "This will result in\n" + - "\n" + - "\tHOSTNAME=myhostname\n" + - "\n" + - "Notice that this will remove any number of tabs, spaces and even newlines and\n" + - "carriage returns.\n" + - "\n" + - "## Debugging templates\n" + - "\n" + - "If there is a mistake in one of your templates and you want to debug it, chezmoi\n" + - "can help you. You can use this subcommand to test and play with the examples in\n" + - "these docs as well.\n" + - "\n" + - "There is a very handy subcommand called `execute-template`. chezmoi will\n" + - "interpret any data coming from stdin or at the end of the command. It will then\n" + - "interpret all templates and output the result to stdout. For example with the\n" + - "command:\n" + - "\n" + - "\tchezmoi execute-template '{{ .chezmoi.os }}/{{ .chezmoi.arch }}'\n" + - "\n" + - "chezmoi will output the current OS and architecture to stdout.\n" + - "\n" + - "You can also feed the contents of a file to this command by typing:\n" + - "\n" + - "\tcat foo.txt | chezmoi execute-template\n" + - "\n" + - "## Simple logic\n" + - "\n" + - "A very useful feature of chezmoi templates is the ability to perform logical\n" + - "operations.\n" + - "\n" + - "\t# common config\n" + - "\texport EDITOR=vi\n" + - "\n" + - "\t# machine-specific configuration\n" + - "\t{{- if eq .chezmoi.hostname \"work-laptop\" }}\n" + - "\t# this will only be included in ~/.bashrc on work-laptop\n" + - "\t{{- end }}\n" + - "\n" + - "In this example chezmoi will look at the hostname of the machine and if that is\n" + - "equal to \"work-laptop\", the text between the `if` and the `end` will be included\n" + - "in the result.\n" + - "\n" + - "### Boolean functions\n" + - "\n" + - "| Function | Return value |\n" + - "| -------- | --------------------------------------------------------- |\n" + - "| `eq` | Returns true if the first argument is equal to any of the other arguments. |\n" + - "| `not` | Returns the boolean negation of its single argument. |\n" + - "| `and` | Returns the boolean AND of its arguments by returning the first empty argument or the last argument, that is, `and x y` behaves as `if x then y else x`. All the arguments are evaluated. |\n" + - "| `or` | Returns the boolean OR of its arguments by returning the first non-empty argument or the last argument, that is, `or x y` behaves as `if x then x else y` All the arguments are evaluated. |\n" + - "\n" + - "### Integer functions\n" + - "\n" + - "| Function | Return value |\n" + - "| -------- | ------------------------------------------- |\n" + - "| `len` | Returns the integer length of its argument. |\n" + - "| `eq` | Returns the boolean truth of arg1 == arg2. |\n" + - "| `ne` | Returns the boolean truth of arg1 != arg2. |\n" + - "| `lt` | Returns the boolean truth of arg1 < arg2. |\n" + - "| `le` | Returns the boolean truth of arg1 <= arg2. |\n" + - "| `gt` | Returns the boolean truth of arg1 > arg2. |\n" + - "| `ge` | Returns the boolean truth of arg1 >= arg2. |\n" + - "\n" + - "## More complicated logic\n" + - "\n" + - "Up until now, we have only seen if statements that can handle at most two\n" + - "variables. In this part we will see how to create more complicated expressions.\n" + - "\n" + - "You can also create more complicated expressions. The `eq` command can accept\n" + - "multiple arguments. It will check if the first argument is equal to any of the\n" + - "other arguments.\n" + - "\n" + - "\t{{ if eq \"foo\" \"foo\" \"bar\" }}one{{end}}\n" + - "\t{{ if eq \"foo\" \"bar\" \"foo\" }}hello{{end}}\n" + - "\t{{ if eq \"foo\" \"bar\" \"bar\" }}hello{{end}}\n" + - "\n" + - "The first two examples will output `hello` and the last example will output\n" + - "nothing.\n" + - "\n" + - "The operators `or` and `and` can also accept multiple arguments.\n" + - "\n" + - "### Chaining operators\n" + - "\n" + - "You can perform multiple checks in one if statement.\n" + - "\n" + - "\t{{ if (and (eq .chezmoi.os \"linux\") (ne .email \"[email protected]\")) }}\n" + - "\t...\n" + - "\t{{ end }}\n" + - "\n" + - "This will check if the operating system is Linux and the configured email is not\n" + - "the home email. The brackets are needed here, because otherwise all the\n" + - "arguments will be give to the `and` command.\n" + - "\n" + - "This way you can chain as many operators together as you like.\n" + - "\n" + - "## Helper functions\n" + - "\n" + - "chezmoi has added multiple helper functions to the\n" + - "[`text/template`](https://pkg.go.dev/text/template) syntax.\n" + - "\n" + - "chezmoi includes [`sprig`](http://masterminds.github.io/sprig/), an extension to\n" + - "the `text/template` format that contains many helper functions. Take a look at\n" + - "their documentation for a list.\n" + - "\n" + - "chezmoi adds a few functions of its own as well. Take a look at the\n" + - "[`reference`](REFERENCE.md#template-functions) for complete list.\n" + - "\n" + - "## Template variables\n" + - "\n" + - "chezmoi defines a few useful templates variables that depend on the system you\n" + - "are currently on. A list of the variables defined by chezmoi can be found\n" + - "[here](REFERENCE.md#template-variables).\n" + - "\n" + - "There are, however more variables than that. To view the variables available on\n" + - "your system, execute:\n" + - "\n" + - "\tchezmoi data\n" + - "\n" + - "This outputs the variables in JSON format by default. To access the variable\n" + - "`chezmoi.kernel.osrelease` in a template, use\n" + - "\n" + - "\t{{ .chezmoi.kernel.osrelease }}\n" + - "\n" + - "This way you can also access the variables you defined yourself.\n" + - "\n" + - "## Using .chezmoitemplates for creating similar files\n" + - "\n" + - "When you have multiple similar files, but they aren't quite the same, you can\n" + - "create a template file in the directory `.chezmoitemplates`. This template can\n" + - "be inserted in other template files, for example:\n" + - "\n" + - "Create `.local/share/chezmoi/.chezmoitemplates/alacritty`:\n" + - "\n" + - "\tsome: config\n" + - "\tfontsize: {{ . }}\n" + - "\tsomemore: config\n" + - "\n" + - "Notice the file name doesn't have to end in `.tmpl`, as all files in the\n" + - "directory `.chemzoitemplates` are interpreted as templates.\n" + - "\n" + - "Create other files using the template `.local/share/chezmoi/small-font.yml.tmpl`\n" + - "\n" + - " {{- template \"alacritty\" 12 -}}\n" + - "\n" + - "`.local/share/chezmoi/big-font.yml.tmpl`\n" + - "\n" + - " {{- template \"alacritty\" 18 -}}\n" + - "\n" + - "Here we're calling the shared `alacritty` template with the font size as the\n" + - "`.` value passed in. You can test this with `chezmoi cat`:\n" + - "\n" + - " $ chezmoi cat ~/small-font.yml\n" + - " some: config\n" + - " fontsize: 12\n" + - " somemore: config\n" + - " $ chezmoi cat ~/big-font.yml\n" + - " some: config\n" + - " fontsize: 18\n" + - " somemore: config\n" + - "\n" + - "### Passing multiple arguments\n" + - "\n" + - "In the example above only one arguments is passed to the template. To pass more\n" + - "arguments to the template, you can do it in two ways.\n" + - "\n" + - "#### Via the config file\n" + - "\n" + - "This method is useful if you want to use the same template arguments multiple\n" + - "times, because you don't specify the arguments every time. Instead you specify\n" + - "them in the file `.config/chezmoi/.chezmoi.toml`:\n" + - "\n" + - "```toml\n" + - "[data.alacritty.big]\n" + - " fontsize = 18\n" + - " font = \"DejaVu Serif\"\n" + - "[data.alacritty.small]\n" + - " fontsize = 12\n" + - " font = \"DejaVu Sans Mono\"\n" + - "```\n" + - "\n" + - "Use the variables in `.local/share/chezmoi/.chezmoitemplates/alacritty`:\n" + - "\n" + - " some: config\n" + - " fontsize: {{ .fontsize }}\n" + - " font: {{ .font }}\n" + - " somemore: config\n" + - "\n" + - "And connect them with `.local/share/chezmoi/small-font.yml.tmpl`:\n" + - "\n" + - " {{- template \"alacritty\" .alacritty.small -}}\n" + - "\n" + - "At the moment, this means that you'll have to duplicate the alacritty data in\n" + - "the config file on every machine, but a feature will be added to avoid this.\n" + - "\n" + - "#### By passing a dictionary\n" + - "\n" + - "Using the same alacritty configuration as above, you can pass the arguments to\n" + - "it with a dictionary, for example `.local/share/chezmoi/small-font.yml.tmpl`:\n" + - "\n" + - " {{- template \"alacritty\" dict \"fontsize\" 12 \"font\" \"DejaVu Sans Mono\" -}}\n" + - "\n") -} diff --git a/cmd/docs.go b/cmd/docs.go deleted file mode 100644 index 2ec11476b91..00000000000 --- a/cmd/docs.go +++ /dev/null @@ -1,85 +0,0 @@ -// +build !nodocs - -package cmd - -import ( - "fmt" - "os" - "regexp" - "strings" - - "github.com/charmbracelet/glamour" - "github.com/spf13/cobra" - "golang.org/x/term" -) - -var docsCmd = &cobra.Command{ - Use: "docs [regexp]", - Args: cobra.MaximumNArgs(1), - Short: "Print documentation", - Long: mustGetLongHelp("docs"), - Example: getExample("docs"), - RunE: config.runDocsCmd, -} - -func init() { - rootCmd.AddCommand(docsCmd) -} - -func (c *Config) runDocsCmd(cmd *cobra.Command, args []string) error { - filename := "REFERENCE.md" - if len(args) > 0 { - pattern := args[0] - re, err := regexp.Compile(strings.ToLower(pattern)) - if err != nil { - return err - } - docsFilenames, err := getDocsFilenames() - if err != nil { - return err - } - var filenames []string - for _, fn := range docsFilenames { - if re.FindStringIndex(strings.ToLower(fn)) != nil { - filenames = append(filenames, fn) - } - } - switch { - case len(filenames) == 0: - return fmt.Errorf("%s: no matching files", pattern) - case len(filenames) == 1: - filename = filenames[0] - default: - return fmt.Errorf("%s: ambiguous pattern, matches %s", pattern, strings.Join(filenames, ", ")) - } - } - - data, err := getDoc(filename) - if err != nil { - return err - } - - width := 80 - if stdout, ok := c.Stdout.(*os.File); ok && term.IsTerminal(int(stdout.Fd())) { - width, _, err = term.GetSize(int(stdout.Fd())) - if err != nil { - return err - } - } - - tr, err := glamour.NewTermRenderer( - glamour.WithStyles(glamour.ASCIIStyleConfig), - glamour.WithWordWrap(width), - ) - if err != nil { - return err - } - - out, err := tr.RenderBytes(data) - if err != nil { - return err - } - - _, err = c.Stdout.Write(out) - return err -} diff --git a/cmd/docs_embeddocs.go b/cmd/docs_embeddocs.go deleted file mode 100644 index 803d70f6eca..00000000000 --- a/cmd/docs_embeddocs.go +++ /dev/null @@ -1,27 +0,0 @@ -// +build !nodocs -// +build !noembeddocs - -package cmd - -import ( - "strings" -) - -// DocsDir is unused when chezmoi is built with embedded docs. -var DocsDir = "" - -var docsPrefix = "docs/" - -func getDocsFilenames() ([]string, error) { - var docsFilenames []string - for name := range assets { - if strings.HasPrefix(name, docsPrefix) { - docsFilenames = append(docsFilenames, strings.TrimPrefix(name, docsPrefix)) - } - } - return docsFilenames, nil -} - -func getDoc(filename string) ([]byte, error) { - return getAsset(docsPrefix + filename) -} diff --git a/cmd/docs_noembeddocs.go b/cmd/docs_noembeddocs.go index 8d753e711bc..baec9532570 100644 --- a/cmd/docs_noembeddocs.go +++ b/cmd/docs_noembeddocs.go @@ -4,7 +4,6 @@ package cmd import ( - "io/ioutil" "os" "path/filepath" ) @@ -13,7 +12,11 @@ import ( // embedded docs. It should be an absolute path. var DocsDir = "docs" -func getDocsFilenames() ([]string, error) { +func doc(filename string) ([]byte, error) { + return os.ReadFile(filepath.Join(DocsDir, filename)) +} + +func docsFilenames() ([]string, error) { f, err := os.Open(DocsDir) if err != nil { return nil, err @@ -21,7 +24,3 @@ func getDocsFilenames() ([]string, error) { defer f.Close() return f.Readdirnames(-1) } - -func getDoc(filename string) ([]byte, error) { - return ioutil.ReadFile(filepath.Join(DocsDir, filename)) -} diff --git a/chezmoi2/cmd/docscmd.go b/cmd/docscmd.go similarity index 75% rename from chezmoi2/cmd/docscmd.go rename to cmd/docscmd.go index 214e6dc9e71..eb8c9090399 100644 --- a/chezmoi2/cmd/docscmd.go +++ b/cmd/docscmd.go @@ -4,6 +4,7 @@ package cmd import ( "fmt" + "io" "os" "regexp" "strings" @@ -11,6 +12,8 @@ import ( "github.com/charmbracelet/glamour" "github.com/spf13/cobra" "golang.org/x/term" + + "github.com/twpayne/chezmoi/docs" ) func (c *Config) newDocsCmd() *cobra.Command { @@ -37,14 +40,21 @@ func (c *Config) runDocsCmd(cmd *cobra.Command, args []string) error { if err != nil { return err } - allDocsFilenames, err := docsFilenames() + dirEntries, err := docs.FS.ReadDir(".") if err != nil { return err } var filenames []string - for _, fn := range allDocsFilenames { - if re.FindStringIndex(strings.ToLower(fn)) != nil { - filenames = append(filenames, fn) + for _, dirEntry := range dirEntries { + fileInfo, err := dirEntry.Info() + if err != nil { + return err + } + if fileInfo.Mode()&^os.ModePerm != 0 { + continue + } + if filename := dirEntry.Name(); re.FindStringIndex(strings.ToLower(filename)) != nil { + filenames = append(filenames, filename) } } switch { @@ -57,7 +67,12 @@ func (c *Config) runDocsCmd(cmd *cobra.Command, args []string) error { } } - documentData, err := doc(filename) + file, err := docs.FS.Open(filename) + if err != nil { + return err + } + defer file.Close() + documentData, err := io.ReadAll(file) if err != nil { return err } diff --git a/cmd/doctor.go b/cmd/doctor.go deleted file mode 100644 index 612a4e9a5f7..00000000000 --- a/cmd/doctor.go +++ /dev/null @@ -1,454 +0,0 @@ -package cmd - -import ( - "fmt" - "os" - "os/exec" - "path/filepath" - "regexp" - "runtime" - "strings" - - "github.com/coreos/go-semver/semver" - "github.com/spf13/cobra" - shell "github.com/twpayne/go-shell" -) - -var doctorCmd = &cobra.Command{ - Args: cobra.NoArgs, - Use: "doctor", - Short: "Check your system for potential problems", - Example: getExample("doctor"), - Long: mustGetLongHelp("doctor"), - RunE: config.runDoctorCmd, -} - -const ( - okPrefix = "ok" - warningPrefix = "warning" - errorPrefix = "ERROR" -) - -type doctorCheck interface { - Check() (bool, error) - Enabled() bool - MustSucceed() bool - Result() string - Skip() bool -} - -type doctorCheckResult struct { - ok bool - prefix string - result string -} - -type doctorBinaryCheck struct { - name string - binaryName string - path string - minVersion *semver.Version - mustSucceed bool - versionArgs []string - versionRegexp *regexp.Regexp - version *semver.Version -} - -type doctorDirectoryCheck struct { - name string - path string - err error - dontWantPerm os.FileMode - info os.FileInfo -} - -type doctorFileCheck struct { - name string - path string - canSkip bool - mustSucceed bool - info os.FileInfo -} - -type doctorRuntimeCheck struct{} - -type doctorSuspiciousFilesCheck struct { - path string - filenames map[string]bool - found []string -} - -type doctorVersionCheck struct{} - -var gpgBinaryCheck = &doctorBinaryCheck{ - name: "GnuPG", - binaryName: "gpg", - versionArgs: []string{"--version"}, - versionRegexp: regexp.MustCompile(`^gpg \(.*?\) (\d+\.\d+\.\d+)`), -} - -func init() { - rootCmd.AddCommand(doctorCmd) -} - -func (c *Config) runDoctorCmd(cmd *cobra.Command, args []string) error { - shell, _ := shell.CurrentUserShell() - - var vcsCommandCheck doctorCheck - if vcs, err := c.getVCS(); err == nil { - vcsCommandCheck = &doctorBinaryCheck{ - name: "source VCS command", - binaryName: c.SourceVCS.Command, - versionArgs: vcs.VersionArgs(), - versionRegexp: vcs.VersionRegexp(), - } - } else { - vcsCommandCheck = &doctorBinaryCheck{ - name: "source VCS command", - binaryName: c.SourceVCS.Command, - } - } - - editorName, _ := c.getEditor() - editorCheck := &doctorBinaryCheck{ - name: "editor", - binaryName: editorName, - mustSucceed: true, - } - - allOK := true - for _, dc := range []doctorCheck{ - &doctorVersionCheck{}, - &doctorRuntimeCheck{}, - &doctorDirectoryCheck{ - name: "source directory", - path: c.SourceDir, - dontWantPerm: 0o77, - }, - &doctorSuspiciousFilesCheck{ - path: c.SourceDir, - filenames: map[string]bool{ - ".chezmoignore": true, - }, - }, - &doctorDirectoryCheck{ - name: "destination directory", - path: c.DestDir, - }, - &doctorFileCheck{ - name: "configuration file", - path: c.configFile, - }, - &doctorBinaryCheck{ - name: "shell", - binaryName: shell, - mustSucceed: true, - }, - &doctorFileCheck{ - name: "KeePassXC database", - path: c.KeePassXC.Database, - canSkip: true, - }, - editorCheck, - &doctorBinaryCheck{ - name: "merge command", - binaryName: c.Merge.Command, - }, - vcsCommandCheck, - gpgBinaryCheck, - &doctorBinaryCheck{ - name: "1Password CLI", - binaryName: c.Onepassword.Command, - versionArgs: []string{"--version"}, - versionRegexp: regexp.MustCompile(`^(\d+\.\d+\.\d+)`), - }, - &doctorBinaryCheck{ - name: "Bitwarden CLI", - binaryName: c.Bitwarden.Command, - versionArgs: []string{"--version"}, - versionRegexp: regexp.MustCompile(`^(\d+\.\d+\.\d+)`), - }, - &doctorBinaryCheck{ - name: "gopass CLI", - binaryName: c.Gopass.Command, - versionArgs: gopassVersionArgs, - versionRegexp: gopassVersionRegexp, - minVersion: &gopassMinVersion, - }, - &doctorBinaryCheck{ - name: "KeePassXC CLI", - binaryName: c.KeePassXC.Command, - versionArgs: []string{"--version"}, - versionRegexp: regexp.MustCompile(`^(\d+\.\d+\.\d+)`), - }, - &doctorBinaryCheck{ - name: "LastPass CLI", - binaryName: c.Lastpass.Command, - versionArgs: lastpassVersionArgs, - versionRegexp: lastpassVersionRegexp, - minVersion: &lastpassMinVersion, - }, - &doctorBinaryCheck{ - name: "pass CLI", - binaryName: c.Pass.Command, - versionArgs: []string{"version"}, - versionRegexp: regexp.MustCompile(`(?m)=\s*v(\d+\.\d+\.\d+)`), - }, - &doctorBinaryCheck{ - name: "Vault CLI", - binaryName: c.Vault.Command, - versionArgs: []string{"version"}, - versionRegexp: regexp.MustCompile(`^Vault\s+v(\d+\.\d+\.\d+)`), - }, - &doctorBinaryCheck{ - name: "generic secret CLI", - binaryName: c.GenericSecret.Command, - }, - } { - if dc.Skip() { - continue - } - dcr := runDoctorCheck(dc) - if !dcr.ok { - allOK = false - } - if dcr.result != "" { - fmt.Printf("%7s: %s\n", dcr.prefix, dcr.result) - } - } - if !allOK { - return errExitFailure - } - return nil -} - -func runDoctorCheck(dc doctorCheck) doctorCheckResult { - if !dc.Enabled() { - return doctorCheckResult{ok: true} - } - ok, err := dc.Check() - if err != nil { - return doctorCheckResult{result: err.Error()} - } - var prefix string - switch { - case ok: - prefix = okPrefix - case !ok && !dc.MustSucceed(): - prefix = warningPrefix - default: - prefix = errorPrefix - } - return doctorCheckResult{ - ok: ok, - prefix: prefix, - result: dc.Result(), - } -} - -func (c *doctorBinaryCheck) Check() (bool, error) { - var err error - c.path, err = exec.LookPath(c.binaryName) - if err != nil { - return false, nil - } - - if c.versionRegexp != nil { - //nolint:gosec - output, err := exec.Command(c.path, c.versionArgs...).CombinedOutput() - if err != nil { - return false, err - } - version, err := c.getVersionFromOutput(output) - if err != nil { - return false, nil - } - c.version = version - if c.minVersion != nil && c.version.LessThan(*c.minVersion) { - return false, nil - } - } - - return true, nil -} - -func (c *doctorBinaryCheck) Enabled() bool { - return c.binaryName != "" -} - -func (c *doctorBinaryCheck) MustSucceed() bool { - return c.mustSucceed -} - -func (c *doctorBinaryCheck) Result() string { - if c.path == "" { - return fmt.Sprintf("%s (%s, not found)", c.binaryName, c.name) - } - s := fmt.Sprintf("%s (%s", c.path, c.name) - if c.version != nil { - s += ", version " + c.version.String() - if c.minVersion != nil && c.version.LessThan(*c.minVersion) { - s += ", want version >=" + c.minVersion.String() - } - } - s += ")" - return s -} - -func (c *doctorBinaryCheck) Skip() bool { - return false -} - -func (c *doctorBinaryCheck) getVersionFromOutput(output []byte) (*semver.Version, error) { - m := c.versionRegexp.FindSubmatch(output) - if m == nil { - return nil, fmt.Errorf("%s: could not extract version from %q", c.path, output) - } - return semver.NewVersion(string(m[1])) -} - -func (c *doctorDirectoryCheck) Check() (bool, error) { - c.info, c.err = os.Stat(c.path) - if c.err != nil && os.IsNotExist(c.err) { - return false, nil - } else if c.err != nil { - return false, c.err - } - if c.info.Mode()&os.ModePerm&c.dontWantPerm != 0 { - return false, nil - } - return true, nil -} - -func (c *doctorDirectoryCheck) Enabled() bool { - return true -} - -func (c *doctorDirectoryCheck) MustSucceed() bool { - return true -} - -func (c *doctorDirectoryCheck) Result() string { - switch { - case os.IsNotExist(c.err): - return fmt.Sprintf("%s: (%s, not found)", c.path, c.name) - case c.err != nil: - return fmt.Sprintf("%s: (%s, %v)", c.path, c.name, c.err) - default: - return fmt.Sprintf("%s (%s, perm %03o)", c.path, c.name, c.info.Mode()&os.ModePerm) - } -} - -func (c *doctorDirectoryCheck) Skip() bool { - return false -} - -func (c *doctorFileCheck) Check() (bool, error) { - if c.path == "" { - return false, nil - } - var err error - c.info, err = os.Stat(c.path) - if err != nil && os.IsNotExist(err) { - return false, nil - } else if err != nil { - return false, err - } - return true, nil -} - -func (c *doctorFileCheck) Enabled() bool { - return true -} - -func (c *doctorFileCheck) MustSucceed() bool { - return c.mustSucceed -} - -func (c *doctorFileCheck) Result() string { - if c.path == "" { - return fmt.Sprintf("not set (%s)", c.name) - } - return fmt.Sprintf("%s (%s)", c.path, c.name) -} - -func (c *doctorFileCheck) Skip() bool { - return c.canSkip && c.path == "" -} - -func (doctorRuntimeCheck) Check() (bool, error) { - return true, nil -} - -func (doctorRuntimeCheck) Enabled() bool { - return true -} - -func (doctorRuntimeCheck) MustSucceed() bool { - return true -} - -func (doctorRuntimeCheck) Result() string { - return fmt.Sprintf("runtime.GOOS %s, runtime.GOARCH %s", runtime.GOOS, runtime.GOARCH) -} - -func (doctorRuntimeCheck) Skip() bool { - return false -} - -func (c *doctorSuspiciousFilesCheck) Check() (bool, error) { - if err := filepath.Walk(c.path, func(path string, info os.FileInfo, err error) error { - if err != nil { - return err - } - if c.filenames[info.Name()] { - c.found = append(c.found, path) - } - return nil - }); err != nil { - return false, err - } - return len(c.found) == 0, nil -} - -func (c *doctorSuspiciousFilesCheck) Enabled() bool { - return len(c.filenames) > 0 -} - -func (c *doctorSuspiciousFilesCheck) MustSucceed() bool { - return false -} - -func (c *doctorSuspiciousFilesCheck) Result() string { - if len(c.found) == 0 { - return "" - } - return fmt.Sprintf("%s (suspicious filenames)", strings.Join(c.found, ", ")) -} - -func (c *doctorSuspiciousFilesCheck) Skip() bool { - return false -} - -func (doctorVersionCheck) Check() (bool, error) { - if VersionStr == "" || Commit == "" || Date == "" { - return false, nil - } - return true, nil -} - -func (doctorVersionCheck) Enabled() bool { - return true -} - -func (doctorVersionCheck) MustSucceed() bool { - return false -} - -func (doctorVersionCheck) Result() string { - return "version " + rootCmd.Version -} - -func (doctorVersionCheck) Skip() bool { - return false -} diff --git a/cmd/doctor_test.go b/cmd/doctor_test.go deleted file mode 100644 index a5cc912d23a..00000000000 --- a/cmd/doctor_test.go +++ /dev/null @@ -1,68 +0,0 @@ -package cmd - -import ( - "strings" - "testing" - - "github.com/coreos/go-semver/semver" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestDoctorBinaryCheck(t *testing.T) { - for _, tc := range []struct { - name string - check *doctorBinaryCheck - output string - expected *semver.Version - }{ - { - name: "gnupg_2.2.16", - check: gpgBinaryCheck, - output: strings.Join([]string{ - "gpg (GnuPG) 2.2.16", - "libgcrypt 1.8.4", - "Copyright (C) 2019 Free Software Foundation, Inc.", - "License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>", - "This is free software: you are free to change and redistribute it.", - "There is NO WARRANTY, to the extent permitted by law.", - "", - "Home: /Users/username/.gnupg", - "Supported algorithms:", - "Pubkey: RSA, ELG, DSA, ECDH, ECDSA, EDDSA", - "Cipher: IDEA, 3DES, CAST5, BLOWFISH, AES, AES192, AES256, TWOFISH,", - " CAMELLIA128, CAMELLIA192, CAMELLIA256", - "Hash: SHA1, RIPEMD160, SHA256, SHA384, SHA512, SHA224", - "Compression: Uncompressed, ZIP, ZLIB, BZIP2", - }, "\n"), - expected: semver.New("2.2.16"), - }, - { - name: "issue_335", - check: gpgBinaryCheck, - output: strings.Join([]string{ - "gpg (GnuPG/MacGPG2) 2.2.10", - "libgcrypt 1.8.3", - "Copyright (C) 2018 Free Software Foundation, Inc.", - "License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>", - "This is free software: you are free to change and redistribute it.", - "There is NO WARRANTY, to the extent permitted by law.", - "", - "Home: /Users/username/.gnupg", - "Supported algorithms:", - "Pubkey: RSA, ELG, DSA, ECDH, ECDSA, EDDSA", - "Cipher: IDEA, 3DES, CAST5, BLOWFISH, AES, AES192, AES256, TWOFISH,", - " CAMELLIA128, CAMELLIA192, CAMELLIA256", - "Hash: SHA1, RIPEMD160, SHA256, SHA384, SHA512, SHA224", - "Compression: Uncompressed, ZIP, ZLIB, BZIP2", - }, "\n"), - expected: semver.New("2.2.10"), - }, - } { - t.Run(tc.name, func(t *testing.T) { - actual, err := tc.check.getVersionFromOutput([]byte(tc.output)) - require.NoError(t, err) - assert.Equal(t, tc.expected, actual) - }) - } -} diff --git a/chezmoi2/cmd/doctorcmd.go b/cmd/doctorcmd.go similarity index 97% rename from chezmoi2/cmd/doctorcmd.go rename to cmd/doctorcmd.go index 2270ac604be..194055fb3ca 100644 --- a/chezmoi2/cmd/doctorcmd.go +++ b/cmd/doctorcmd.go @@ -3,7 +3,6 @@ package cmd import ( "errors" "fmt" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -17,8 +16,8 @@ import ( "github.com/spf13/cobra" "github.com/twpayne/go-shell" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoilog" + "github.com/twpayne/chezmoi/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoilog" ) // A checkResult is the result of a check. @@ -288,7 +287,7 @@ func (c *dirCheck) Name() string { } func (c *dirCheck) Run() (checkResult, string) { - if _, err := ioutil.ReadDir(c.dirname); err != nil { + if _, err := os.ReadDir(c.dirname); err != nil { return checkError, fmt.Sprintf("%s: %v", c.dirname, err) } return checkOK, fmt.Sprintf("%s is a directory", c.dirname) @@ -303,7 +302,7 @@ func (c *fileCheck) Run() (checkResult, string) { return checkWarning, "not set" } - _, err := ioutil.ReadFile(c.filename) + _, err := os.ReadFile(c.filename) switch { case os.IsNotExist(err): return c.ifNotExist, fmt.Sprintf("%s does not exist", c.filename) diff --git a/cmd/dump.go b/cmd/dump.go deleted file mode 100644 index e5645343823..00000000000 --- a/cmd/dump.go +++ /dev/null @@ -1,68 +0,0 @@ -package cmd - -import ( - "fmt" - "os" - "strings" - - "github.com/spf13/cobra" -) - -type dumpCmdConfig struct { - format string - recursive bool -} - -var dumpCmd = &cobra.Command{ - Use: "dump [targets...]", - Short: "Write a dump of the target state to stdout", - Long: mustGetLongHelp("dump"), - Example: getExample("dump"), - PreRunE: config.ensureNoError, - RunE: config.runDumpCmd, -} - -func init() { - rootCmd.AddCommand(dumpCmd) - - persistentFlags := dumpCmd.PersistentFlags() - persistentFlags.StringVarP(&config.dump.format, "format", "f", "json", "format (JSON, TOML, or YAML)") - persistentFlags.BoolVarP(&config.dump.recursive, "recursive", "r", true, "recursive") - - markRemainingZshCompPositionalArgumentsAsFiles(dumpCmd, 1) -} - -func (c *Config) runDumpCmd(cmd *cobra.Command, args []string) error { - format, ok := formatMap[strings.ToLower(c.dump.format)] - if !ok { - return fmt.Errorf("%s: unknown format", c.dump.format) - } - ts, err := c.getTargetState(nil) - if err != nil { - return err - } - var concreteValue interface{} - if len(args) == 0 { - concreteValue, err = ts.ConcreteValue(c.dump.recursive) - if err != nil { - return err - } - } else { - entries, err := c.getEntries(ts, args) - if err != nil { - return err - } - var concreteValues []interface{} - for _, entry := range entries { - entryConcreteValue, err := entry.ConcreteValue(ts.TargetIgnore.Match, ts.SourceDir, os.FileMode(c.Umask), c.dump.recursive) - if err != nil { - return err - } - if entryConcreteValue != nil { - concreteValues = append(concreteValues, entryConcreteValue) - } - } - concreteValue = concreteValues - } - return format(c.Stdout, concreteValue) -} diff --git a/cmd/dump_test.go b/cmd/dump_test.go deleted file mode 100644 index 187da2002ae..00000000000 --- a/cmd/dump_test.go +++ /dev/null @@ -1,62 +0,0 @@ -package cmd - -import ( - "bytes" - "encoding/json" - "path/filepath" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/twpayne/go-vfs/vfst" -) - -func TestDumpCmd(t *testing.T) { - fs, cleanup, err := vfst.NewTestFS(map[string]interface{}{ - "/home/user/.local/share/chezmoi/dir/file": "contents", - "/home/user/.local/share/chezmoi/symlink_symlink": "target", - }) - require.NoError(t, err) - defer cleanup() - stdout := &bytes.Buffer{} - c := newTestConfig( - fs, - withDumpCmdConfig(dumpCmdConfig{ - format: "json", - recursive: true, - }), - withStdout(stdout), - ) - assert.NoError(t, c.runDumpCmd(nil, nil)) - var actual interface{} - assert.NoError(t, json.NewDecoder(stdout).Decode(&actual)) - expected := []interface{}{ - map[string]interface{}{ - "type": "dir", - "sourcePath": filepath.Join("/", "home", "user", ".local", "share", "chezmoi", "dir"), - "targetPath": "dir", - "exact": false, - "perm": float64(0o755), - "entries": []interface{}{ - map[string]interface{}{ - "type": "file", - "sourcePath": filepath.Join("/", "home", "user", ".local", "share", "chezmoi", "dir", "file"), - "targetPath": filepath.Join("dir", "file"), - "empty": false, - "encrypted": false, - "perm": float64(0o644), - "template": false, - "contents": "contents", - }, - }, - }, - map[string]interface{}{ - "type": "symlink", - "sourcePath": filepath.Join("/", "home", "user", ".local", "share", "chezmoi", "symlink_symlink"), - "targetPath": "symlink", - "template": false, - "linkname": "target", - }, - } - assert.Equal(t, expected, actual) -} diff --git a/chezmoi2/cmd/dumpcmd.go b/cmd/dumpcmd.go similarity index 92% rename from chezmoi2/cmd/dumpcmd.go rename to cmd/dumpcmd.go index 0ce588136a6..c5a1979ffab 100644 --- a/chezmoi2/cmd/dumpcmd.go +++ b/cmd/dumpcmd.go @@ -3,12 +3,12 @@ package cmd import ( "github.com/spf13/cobra" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoi" ) type dumpCmdConfig struct { format string - include *chezmoi.IncludeSet + include *chezmoi.EntryTypeSet recursive bool } diff --git a/cmd/edit.go b/cmd/edit.go deleted file mode 100644 index 0f0345cf551..00000000000 --- a/cmd/edit.go +++ /dev/null @@ -1,197 +0,0 @@ -package cmd - -import ( - "fmt" - "io/ioutil" - "os" - "path/filepath" - - "github.com/spf13/cobra" - vfs "github.com/twpayne/go-vfs" - - "github.com/twpayne/chezmoi/internal/chezmoi" -) - -var editCmd = &cobra.Command{ - Use: "edit targets...", - Short: "Edit the source state of a target", - Long: mustGetLongHelp("edit"), - Example: getExample("edit"), - PreRunE: config.ensureNoError, - RunE: config.runEditCmd, - PostRunE: config.autoCommitAndAutoPush, -} - -type editCmdConfig struct { - apply bool - diff bool - prompt bool -} - -func init() { - rootCmd.AddCommand(editCmd) - - persistentFlags := editCmd.PersistentFlags() - persistentFlags.BoolVarP(&config.edit.apply, "apply", "a", false, "apply edit after editing") - persistentFlags.BoolVarP(&config.edit.diff, "diff", "d", false, "print diff after editing") - persistentFlags.BoolVarP(&config.edit.prompt, "prompt", "p", false, "prompt before applying (implies --diff)") - - markRemainingZshCompPositionalArgumentsAsFiles(editCmd, 1) -} - -type encryptedFile struct { - index int - file *chezmoi.File - ciphertextPath string - plaintextPath string -} - -func (c *Config) runEditCmd(cmd *cobra.Command, args []string) error { - if len(args) == 0 { - if c.edit.apply { - cmd.Printf("warning: --apply is currently ignored when edit is run with no arguments\n") - } - if c.edit.diff { - cmd.Printf("warning: --diff is currently ignored when edit is run with no arguments\n") - } - if c.edit.prompt { - cmd.Printf("warning: --prompt is currently ignored when edit is run with no arguments\n") - } - return c.runEditor(c.SourceDir) - } - - if c.edit.prompt { - c.edit.diff = true - } - - ts, err := c.getTargetState(&chezmoi.PopulateOptions{ - ExecuteTemplates: false, - }) - if err != nil { - return err - } - - entries, err := c.getEntries(ts, args) - if err != nil { - return err - } - - // Build a list of source file names to pass to the editor. Check that each - // is either a file or a symlink. If the entry is an encrypted file then - // remember it. - argv := make([]string, len(entries)) - var encryptedFiles []encryptedFile - for i, entry := range entries { - argv[i] = filepath.Join(c.SourceDir, entry.SourceName()) - if file, ok := entry.(*chezmoi.File); ok { - if file.Encrypted { - ef := encryptedFile{ - index: i, - file: file, - ciphertextPath: argv[i], - } - encryptedFiles = append(encryptedFiles, ef) - } - } else if _, ok := entry.(*chezmoi.Symlink); !ok { - return fmt.Errorf("%s: not a file or symlink", args[i]) - } - } - - // If any of the files are encrypted, create a temporary directory to store - // the plaintext contents, decrypt each of them, and update argv to point to - // the plaintext file. - if len(encryptedFiles) != 0 { - tempDir, err := ioutil.TempDir("", "chezmoi") - if err != nil { - return err - } - defer os.RemoveAll(tempDir) - for i := range encryptedFiles { - ef := &encryptedFiles[i] - plaintext, err := ef.file.Contents() - if err != nil { - return err - } - ef.plaintextPath = filepath.Join(tempDir, ef.file.SourceName()) - if err := os.MkdirAll(filepath.Dir(ef.plaintextPath), 0o700&^os.FileMode(c.Umask)); err != nil { - return err - } - if err := writeFile(ef.plaintextPath, plaintext, 0o600&^os.FileMode(c.Umask)); err != nil { - return err - } - argv[ef.index] = ef.plaintextPath - } - } - - if err := c.runEditor(argv...); err != nil { - return err - } - - // Re-encrypt any encrypted files. - for _, ef := range encryptedFiles { - plaintext, err := ioutil.ReadFile(ef.plaintextPath) - if err != nil { - return err - } - ciphertext, err := ts.GPG.Encrypt(ef.plaintextPath, plaintext) - if err != nil { - return err - } - if err := writeFile(ef.ciphertextPath, ciphertext, 0o644); err != nil { - return err - } - } - - // Recompute the target state and entries after editing. - ts, err = c.getTargetState(nil) - if err != nil { - return err - } - - entries, err = c.getEntries(ts, args) - if err != nil { - return err - } - - readOnlyFS := vfs.NewReadOnlyFS(c.fs) - applyOptions := chezmoi.ApplyOptions{ - DestDir: ts.DestDir, - DryRun: c.DryRun, - Ignore: ts.TargetIgnore.Match, - ScriptStateBucket: c.scriptStateBucket, - Stdout: c.Stdout, - Umask: ts.Umask, - Verbose: c.Verbose, - } - for i, entry := range entries { - anyMutator := chezmoi.NewAnyMutator(chezmoi.NullMutator{}) - var mutator chezmoi.Mutator = anyMutator - if c.edit.diff { - mutator = chezmoi.NewVerboseMutator(c.Stdout, mutator, c.colored, c.maxDiffDataSize) - } - if err := entry.Apply(readOnlyFS, mutator, c.Follow, &applyOptions); err != nil { - return err - } - if c.edit.apply && anyMutator.Mutated() { - if c.edit.prompt { - choice, err := c.prompt(fmt.Sprintf("Apply %s", args[i]), "ynqa") - if err != nil { - return err - } - switch choice { - case 'y': - case 'n': - continue - case 'q': - return nil - case 'a': - c.edit.prompt = false - } - } - if err := entry.Apply(readOnlyFS, c.mutator, c.Follow, &applyOptions); err != nil { - return err - } - } - } - return nil -} diff --git a/chezmoi2/cmd/editcmd.go b/cmd/editcmd.go similarity index 96% rename from chezmoi2/cmd/editcmd.go rename to cmd/editcmd.go index 7c2cc933d22..79d52baaccb 100644 --- a/chezmoi2/cmd/editcmd.go +++ b/cmd/editcmd.go @@ -1,19 +1,19 @@ package cmd import ( - "io/ioutil" + "os" "runtime" "github.com/spf13/cobra" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoi" ) type editCmdConfig struct { Command string `mapstructure:"command"` Args []string `mapstructure:"args"` apply bool - include *chezmoi.IncludeSet + include *chezmoi.EntryTypeSet } func (c *Config) newEditCmd() *cobra.Command { @@ -77,7 +77,7 @@ func (c *Config) runEditCmd(cmd *cobra.Command, args []string, sourceState *chez var editorArg string if sourceStateFile, ok := sourceStateEntry.(*chezmoi.SourceStateFile); ok && sourceStateFile.Attr.Encrypted { if decryptedDirAbsPath == "" { - decryptedDir, err := ioutil.TempDir("", "chezmoi-decrypted") + decryptedDir, err := os.MkdirTemp("", "chezmoi-decrypted") if err != nil { return err } diff --git a/cmd/editconfig.go b/cmd/editconfig.go deleted file mode 100644 index 8558a516b93..00000000000 --- a/cmd/editconfig.go +++ /dev/null @@ -1,48 +0,0 @@ -package cmd - -import ( - "os" - "path/filepath" - - "github.com/spf13/cobra" - "github.com/spf13/viper" - vfs "github.com/twpayne/go-vfs" - vfsafero "github.com/twpayne/go-vfsafero" -) - -var editConfigCommand = &cobra.Command{ - Use: "edit-config", - Args: cobra.NoArgs, - Short: "Edit the configuration file", - Long: mustGetLongHelp("edit-config"), - Example: getExample("edit-config"), - RunE: config.runEditConfigCmd, -} - -func init() { - rootCmd.AddCommand(editConfigCommand) -} - -func (c *Config) runEditConfigCmd(cmd *cobra.Command, args []string) error { - if err := vfs.MkdirAll(c.mutator, filepath.Dir(c.configFile), 0o777&^os.FileMode(c.Umask)); err != nil { - return err - } - - if err := c.runEditor(c.configFile); err != nil { - return err - } - - // Warn the user of any errors reading the config file. - v := viper.New() - v.SetFs(vfsafero.NewAferoFS(c.fs)) - v.SetConfigFile(c.configFile) - err := v.ReadInConfig() - if err == nil { - err = v.Unmarshal(&Config{}) - } - if err != nil { - cmd.Printf("warning: %s: %v\n", c.configFile, err) - } - - return nil -} diff --git a/chezmoi2/cmd/editconfigcmd.go b/cmd/editconfigcmd.go similarity index 100% rename from chezmoi2/cmd/editconfigcmd.go rename to cmd/editconfigcmd.go diff --git a/cmd/executetemplate.go b/cmd/executetemplate.go deleted file mode 100644 index e727d6c208f..00000000000 --- a/cmd/executetemplate.go +++ /dev/null @@ -1,102 +0,0 @@ -package cmd - -import ( - "io/ioutil" - "strconv" - "strings" - - "github.com/spf13/cobra" -) - -type executeTemplateCmdConfig struct { - init bool - output string - promptBool map[string]string - promptInt map[string]int - promptString map[string]string -} - -var executeTemplateCmd = &cobra.Command{ - Use: "execute-template [templates...]", - Short: "Write the result of executing the given template(s) to stdout", - Long: mustGetLongHelp("execute-template"), - Example: getExample("execute-template"), - PreRunE: config.ensureNoError, - RunE: config.runExecuteTemplateCmd, -} - -func init() { - rootCmd.AddCommand(executeTemplateCmd) - - persistentFlags := executeTemplateCmd.PersistentFlags() - persistentFlags.BoolVarP(&config.executeTemplate.init, "init", "i", false, "simulate chezmoi init") - persistentFlags.StringVarP(&config.executeTemplate.output, "output", "o", "", "output filename") - persistentFlags.StringToStringVar(&config.executeTemplate.promptBool, "promptBool", config.executeTemplate.promptBool, "simulate promptBool") - persistentFlags.StringToIntVar(&config.executeTemplate.promptInt, "promptInt", config.executeTemplate.promptInt, "simulate promptInt") - persistentFlags.StringToStringVarP(&config.executeTemplate.promptString, "promptString", "p", nil, "simulate promptString") -} - -func (c *Config) runExecuteTemplateCmd(cmd *cobra.Command, args []string) error { - promptBool := make(map[string]bool) - for key, valueStr := range c.executeTemplate.promptBool { - value, err := parseBool(valueStr) - if err != nil { - return err - } - promptBool[key] = value - } - if c.executeTemplate.init { - for name, f := range map[string]interface{}{ - "promptBool": func(prompt string) bool { - return promptBool[prompt] - }, - "promptInt": func(prompt string) int { - return c.executeTemplate.promptInt[prompt] - }, - "promptString": func(prompt string) string { - if value, ok := c.executeTemplate.promptString[prompt]; ok { - return value - } - return prompt - }, - } { - c.templateFuncs[name] = f - } - } - - ts, err := c.getTargetState(nil) - if err != nil { - return err - } - output := &strings.Builder{} - switch len(args) { - case 0: - data, err := ioutil.ReadAll(c.Stdin) - if err != nil { - return err - } - result, err := ts.ExecuteTemplateData("stdin", data) - if err != nil { - return err - } - if _, err = output.Write(result); err != nil { - return err - } - default: - for i, arg := range args { - result, err := ts.ExecuteTemplateData("arg"+strconv.Itoa(i+1), []byte(arg)) - if err != nil { - return err - } - if _, err := output.Write(result); err != nil { - return err - } - } - } - - if c.executeTemplate.output == "" { - _, err = c.Stdout.Write([]byte(output.String())) - return err - } - return c.fs.WriteFile(c.executeTemplate.output, []byte(output.String()), 0o666) -} diff --git a/chezmoi2/cmd/executetemplatecmd.go b/cmd/executetemplatecmd.go similarity index 95% rename from chezmoi2/cmd/executetemplatecmd.go rename to cmd/executetemplatecmd.go index 9bf3fb27496..6e0dee8c06c 100644 --- a/chezmoi2/cmd/executetemplatecmd.go +++ b/cmd/executetemplatecmd.go @@ -1,13 +1,13 @@ package cmd import ( - "io/ioutil" + "io" "strconv" "strings" "github.com/spf13/cobra" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoi" ) type executeTemplateCmdConfig struct { @@ -62,7 +62,7 @@ func (c *Config) runExecuteTemplateCmd(cmd *cobra.Command, args []string, source } if len(args) == 0 { - data, err := ioutil.ReadAll(c.stdin) + data, err := io.ReadAll(c.stdin) if err != nil { return err } diff --git a/cmd/forget.go b/cmd/forget.go deleted file mode 100644 index c3943bac8b4..00000000000 --- a/cmd/forget.go +++ /dev/null @@ -1,42 +0,0 @@ -package cmd - -import ( - "path/filepath" - - "github.com/spf13/cobra" -) - -var forgetCmd = &cobra.Command{ - Use: "forget targets...", - Aliases: []string{"unmanage"}, - Args: cobra.MinimumNArgs(1), - Short: "Remove a target from the source state", - Long: mustGetLongHelp("forget"), - Example: getExample("forget"), - PreRunE: config.ensureNoError, - RunE: config.runForgetCmd, - PostRunE: config.autoCommitAndAutoPush, -} - -func init() { - rootCmd.AddCommand(forgetCmd) - - markRemainingZshCompPositionalArgumentsAsFiles(forgetCmd, 1) -} - -func (c *Config) runForgetCmd(cmd *cobra.Command, args []string) error { - ts, err := c.getTargetState(nil) - if err != nil { - return err - } - entries, err := c.getEntries(ts, args) - if err != nil { - return err - } - for _, entry := range entries { - if err := c.mutator.RemoveAll(filepath.Join(c.SourceDir, entry.SourceName())); err != nil { - return err - } - } - return nil -} diff --git a/chezmoi2/cmd/forgetcmd.go b/cmd/forgetcmd.go similarity index 95% rename from chezmoi2/cmd/forgetcmd.go rename to cmd/forgetcmd.go index 2b1618dbd95..9051d13f277 100644 --- a/chezmoi2/cmd/forgetcmd.go +++ b/cmd/forgetcmd.go @@ -5,7 +5,7 @@ import ( "github.com/spf13/cobra" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoi" ) func (c *Config) newForgetCmd() *cobra.Command { diff --git a/cmd/git.go b/cmd/git.go deleted file mode 100644 index a7ea7dddf5d..00000000000 --- a/cmd/git.go +++ /dev/null @@ -1,27 +0,0 @@ -package cmd - -import ( - "path/filepath" - - "github.com/spf13/cobra" -) - -var gitCmd = &cobra.Command{ - Use: "git [args...]", - Short: "Run git in the source directory", - Long: mustGetLongHelp("git"), - Example: getExample("git"), - RunE: config.runGitCmd, -} - -func init() { - rootCmd.AddCommand(gitCmd) -} - -func (c *Config) runGitCmd(cmd *cobra.Command, args []string) error { - name := "git" - if trimExecutableSuffix(filepath.Base(c.SourceVCS.Command)) == "git" { - name = c.SourceVCS.Command - } - return c.run(c.SourceDir, name, args...) -} diff --git a/chezmoi2/cmd/gitcmd.go b/cmd/gitcmd.go similarity index 100% rename from chezmoi2/cmd/gitcmd.go rename to cmd/gitcmd.go diff --git a/chezmoi2/cmd/githubtemplatefuncs.go b/cmd/githubtemplatefuncs.go similarity index 100% rename from chezmoi2/cmd/githubtemplatefuncs.go rename to cmd/githubtemplatefuncs.go diff --git a/cmd/gitvcs.go b/cmd/gitvcs.go deleted file mode 100644 index fcde63e45c5..00000000000 --- a/cmd/gitvcs.go +++ /dev/null @@ -1,65 +0,0 @@ -package cmd - -import ( - "os" - "path/filepath" - "regexp" - - "github.com/twpayne/chezmoi/internal/git" -) - -var gitVersionRegexp = regexp.MustCompile(`^git version (\d+\.\d+\.\d+)`) - -type gitVCS struct{} - -func (gitVCS) AddArgs(path string) []string { - return []string{"add", path} -} - -func (gitVCS) CloneArgs(repo, dir string) []string { - return []string{"clone", repo, dir} -} - -func (gitVCS) CommitArgs(message string) []string { - return []string{"commit", "--message", message} -} - -func (gitVCS) InitArgs() []string { - return []string{"init"} -} - -func (gitVCS) Initialized(dir string) (bool, error) { - info, err := os.Stat(filepath.Join(dir, ".git")) - switch { - case err == nil: - return info.IsDir(), nil - case os.IsNotExist(err): - return false, nil - default: - return false, err - } -} - -func (gitVCS) ParseStatusOutput(output []byte) (interface{}, error) { - return git.ParseStatusPorcelainV2(output) -} - -func (gitVCS) PullArgs() []string { - return []string{"pull", "--rebase"} -} - -func (gitVCS) PushArgs() []string { - return []string{"push"} -} - -func (gitVCS) StatusArgs() []string { - return []string{"status", "--porcelain=v2"} -} - -func (gitVCS) VersionArgs() []string { - return []string{"version"} -} - -func (gitVCS) VersionRegexp() *regexp.Regexp { - return gitVersionRegexp -} diff --git a/chezmoi2/cmd/gopasstemplatefuncs.go b/cmd/gopasstemplatefuncs.go similarity index 97% rename from chezmoi2/cmd/gopasstemplatefuncs.go rename to cmd/gopasstemplatefuncs.go index 8dbc7c326ef..e6d7b3fcbc3 100644 --- a/chezmoi2/cmd/gopasstemplatefuncs.go +++ b/cmd/gopasstemplatefuncs.go @@ -8,7 +8,7 @@ import ( "github.com/coreos/go-semver/semver" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoi" ) var ( diff --git a/cmd/help.go b/cmd/help.go deleted file mode 100644 index 2b8fb7de0ba..00000000000 --- a/cmd/help.go +++ /dev/null @@ -1,31 +0,0 @@ -package cmd - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" -) - -var helpCmd = &cobra.Command{ - Use: "help [command]", - Short: "Print help about a command", - Long: mustGetLongHelp("help"), - Example: getExample("help"), - RunE: config.runHelpCmd, -} - -func init() { - rootCmd.SetHelpCommand(helpCmd) -} - -func (c *Config) runHelpCmd(cmd *cobra.Command, args []string) error { - subCmd, _, err := rootCmd.Find(args) - if err != nil { - return err - } - if subCmd == nil { - return fmt.Errorf("unknown command: %q", strings.Join(args, " ")) - } - return subCmd.Help() -} diff --git a/chezmoi2/cmd/helpcmd.go b/cmd/helpcmd.go similarity index 100% rename from chezmoi2/cmd/helpcmd.go rename to cmd/helpcmd.go diff --git a/cmd/helps.gen.go b/cmd/helps.gen.go deleted file mode 100644 index 08826fa5675..00000000000 --- a/cmd/helps.gen.go +++ /dev/null @@ -1,536 +0,0 @@ -// Code generated by github.com/twpayne/chezmoi/internal/cmd/generate-helps. DO NOT EDIT. - -package cmd - -type help struct { - long string - example string -} - -var helps = map[string]help{ - "add": { - long: "" + - "Description:\n" + - " Add *targets* to the source state. If any target is already in the source\n" + - " state, then its source state is replaced with its current state in the\n" + - " destination directory. The `add` command accepts additional flags:\n" + - "\n" + - " `--autotemplate`\n" + - "\n" + - " Automatically generate a template by replacing strings with variable names\n" + - " from the `data` section of the config file. Longer substitutions occur\n" + - " before shorter ones. This implies the `--template` option.\n" + - "\n" + - " `-e`, `--empty`\n" + - "\n" + - " Set the `empty` attribute on added files.\n" + - "\n" + - " `-f`, `--force`\n" + - "\n" + - " Add *targets*, even if doing so would cause a source template to be\n" + - " overwritten.\n" + - "\n" + - " `-x`, `--exact`\n" + - "\n" + - " Set the `exact` attribute on added directories.\n" + - "\n" + - " `-p`, `--prompt`\n" + - "\n" + - " Interactively prompt before adding each file.\n" + - "\n" + - " `-r`, `--recursive`\n" + - "\n" + - " Recursively add all files, directories, and symlinks.\n" + - "\n" + - " `-T`, `--template`\n" + - "\n" + - " Set the `template` attribute on added files and symlinks.", - example: "" + - " chezmoi add ~/.bashrc\n" + - " chezmoi add ~/.gitconfig --template\n" + - " chezmoi add ~/.vim --recursive\n" + - " chezmoi add ~/.oh-my-zsh --exact --recursive", - }, - "apply": { - long: "" + - "Description:\n" + - " Ensure that *targets* are in the target state, updating them if necessary.\n" + - " If no targets are specified, the state of all targets are ensured.", - example: "" + - " chezmoi apply\n" + - " chezmoi apply --dry-run --verbose\n" + - " chezmoi apply ~/.bashrc", - }, - "archive": { - long: "" + - "Description:\n" + - " Generate a tar archive of the target state. This can be piped into `tar` to\n" + - " inspect the target state.\n" + - "\n" + - " `--output`, `-o` *filename*\n" + - "\n" + - " Write the output to *filename* instead of stdout.", - example: "" + - " chezmoi archive | tar tvf -\n" + - " chezmoi archive --output=dotfiles.tar", - }, - "cat": { - long: "" + - "Description:\n" + - " Write the target state of *targets* to stdout. *targets* must be files or\n" + - " symlinks. For files, the target file contents are written. For symlinks, the\n" + - " target target is written.", - example: "" + - " chezmoi cat ~/.bashrc", - }, - "cd": { - long: "" + - "Description:\n" + - " Launch a shell in the source directory. chezmoi will launch the command set\n" + - " by the `cd.command` configuration variable with any extra arguments\n" + - " specified by `cd.args`. If this is not set, chezmoi will attempt to detect\n" + - " your shell and will finally fall back to an OS-specific default.", - example: "" + - " chezmoi cd", - }, - "chattr": { - long: "" + - "Description:\n" + - " Change the attributes of *targets*. *attributes* specifies which attributes\n" + - " to modify. Add attributes by specifying them or their abbreviations\n" + - " directly, optionally prefixed with a plus sign (`+`). Remove attributes by\n" + - " prefixing them or their attributes with the string `no` or a minus sign (`-\n" + - " `). The available attributes and their abbreviations are:\n" + - "\n" + - " ATTRIBUTE | ABBREVIATION\n" + - " -------------+---------------\n" + - " empty | e\n" + - " encrypted | none\n" + - " exact | none\n" + - " executable | x\n" + - " private | p\n" + - " template | t\n" + - "\n" + - " Multiple attributes modifications may be specified by separating them with a\n" + - " comma (`,`).", - example: "" + - " chezmoi chattr template ~/.bashrc\n" + - " chezmoi chattr noempty ~/.profile\n" + - " chezmoi chattr private,template ~/.netrc", - }, - "completion": { - long: "" + - "Description:\n" + - " Generate shell completion code for the specified shell (`bash`, `fish`,\n" + - " `powershell`, or `zsh`).\n" + - "\n" + - " `--output`, `-o` *filename*\n" + - "\n" + - " Write the shell completion code to *filename* instead of stdout.", - example: "" + - " chezmoi completion bash\n" + - " chezmoi completion fish --output ~/.config/fish/completions/chezmoi.fish", - }, - "data": { - long: "" + - "Description:\n" + - " Write the computed template data in JSON format to stdout. The `data`\n" + - " command accepts additional flags:\n" + - "\n" + - " `-f`, `--format` *format*\n" + - "\n" + - " Print the computed template data in the given format. The accepted formats\n" + - " are `json` (JSON), `toml` (TOML), and `yaml` (YAML).", - example: "" + - " chezmoi data\n" + - " chezmoi data --format=yaml", - }, - "diff": { - long: "" + - "Description:\n" + - " Print the difference between the target state and the destination state for\n" + - " *targets*. If no targets are specified, print the differences for all\n" + - " targets.\n" + - "\n" + - " If a `diff.pager` command is set in the configuration file then the output\n" + - " will be piped into it.\n" + - "\n" + - " `-f`, `--format` *format*\n" + - "\n" + - " Print the diff in *format*. The format can be set with the `diff.format`\n" + - " variable in the configuration file. Valid formats are:\n" + - "\n" + - " ##### `chezmoi`\n" + - "\n" + - " A mix of unified diffs and pseudo shell commands, including scripts,\n" + - " equivalent to `chezmoi apply --dry-run --verbose`.\n" + - "\n" + - " ##### `git`\n" + - "\n" + - " A git format diff https://git-scm.com/docs/diff-format, excluding scripts. In\n" + - " version 2.0.0 of chezmoi, `git` format diffs will become the default and\n" + - " include scripts and the `chezmoi` format will be removed.\n" + - "\n" + - " `--no-pager`\n" + - "\n" + - " Do not use the pager.", - example: "" + - " chezmoi diff\n" + - " chezmoi diff ~/.bashrc\n" + - " chezmoi diff --format=git", - }, - "docs": { - long: "" + - "Description:\n" + - " Print the documentation page matching the regular expression *regexp*.\n" + - " Matching is case insensitive. If no pattern is given, print `REFERENCE.md`.", - example: "" + - " chezmoi docs\n" + - " chezmoi docs faq\n" + - " chezmoi docs howto", - }, - "doctor": { - long: "" + - "Description:\n" + - " Check for potential problems.", - example: "" + - " chezmoi doctor", - }, - "dump": { - long: "" + - "Description:\n" + - " Dump the target state in JSON format. If no targets are specified, then the\n" + - " entire target state. The `dump` command accepts additional arguments:\n" + - "\n" + - " `-f`, `--format` *format*\n" + - "\n" + - " Print the target state in the given format. The accepted formats are `json`\n" + - " (JSON) and `yaml` (YAML).", - example: "" + - " chezmoi dump ~/.bashrc\n" + - " chezmoi dump --format=yaml", - }, - "edit": { - long: "" + - "Description:\n" + - " Edit the source state of *targets*, which must be files or symlinks. If no\n" + - " targets are given the the source directory itself is opened with `$EDITOR`.\n" + - " The `edit` command accepts additional arguments:\n" + - "\n" + - " `-a`, `--apply`\n" + - "\n" + - " Apply target immediately after editing. Ignored if there are no targets.\n" + - "\n" + - " `-d`, `--diff`\n" + - "\n" + - " Print the difference between the target state and the actual state after\n" + - " editing.. Ignored if there are no targets.\n" + - "\n" + - " `-p`, `--prompt`\n" + - "\n" + - " Prompt before applying each target.. Ignored if there are no targets.", - example: "" + - " chezmoi edit ~/.bashrc\n" + - " chezmoi edit ~/.bashrc --apply --prompt\n" + - " chezmoi edit", - }, - "edit-config": { - long: "" + - "Description:\n" + - " Edit the configuration file.\n" + - "\n" + - " `edit-config` examples\n" + - "\n" + - " chezmoi edit-config", - }, - "execute-template": { - long: "" + - "Description:\n" + - " Execute *templates*. This is useful for testing templates or for calling\n" + - " chezmoi from other scripts. *templates* are interpreted as literal\n" + - " templates, with no whitespace added to the output between arguments. If no\n" + - " templates are specified, the template is read from stdin.\n" + - "\n" + - " `--init`, `-i`\n" + - "\n" + - " Include simulated functions only available during `chezmoi init`.\n" + - "\n" + - " `--output`, `-o` *filename*\n" + - "\n" + - " Write the output to *filename* instead of stdout.\n" + - "\n" + - " `--promptBool` *pairs*\n" + - "\n" + - " Simulate the `promptBool` function with a function that returns values from\n" + - " *pairs*. *pairs* is a comma-separated list of *prompt*`=`*value* pairs. If\n" + - " `promptBool` is called with a *prompt* that does not match any of *pairs*,\n" + - " then it returns false.\n" + - "\n" + - " `--promptInt`, `-p` *pairs*\n" + - "\n" + - " Simulate the `promptInt` function with a function that returns values from\n" + - " *pairs*. *pairs* is a comma-separated list of *prompt*`=`*value* pairs. If\n" + - " `promptInt` is called with a *prompt* that does not match any of *pairs*,\n" + - " then it returns zero.\n" + - "\n" + - " `--promptString`, `-p` *pairs*\n" + - "\n" + - " Simulate the `promptString` function with a function that returns values\n" + - " from *pairs*. *pairs* is a comma-separated list of *prompt*`=`*value* pairs.\n" + - " If `promptString` is called with a *prompt* that does not match any of\n" + - " *pairs*, then it returns *prompt* unchanged.\n" + - "\n" + - " `execute-template` examples\n" + - "\n" + - " chezmoi execute-template '{{ .chezmoi.sourceDir }}'\n" + - " chezmoi execute-template '{{ .chezmoi.os }}' / '{{ .chezmoi.arch }}'\n" + - " echo '{{ .chezmoi | toJson }}' | chezmoi execute-template\n" + - " chezmoi execute-template --init --promptString [email protected] <\n" + - " ~/.local/share/chezmoi/.chezmoi.toml.tmpl", - }, - "forget": { - long: "" + - "Description:\n" + - " Remove *targets* from the source state, i.e. stop managing them.", - example: "" + - " chezmoi forget ~/.bashrc", - }, - "git": { - long: "" + - "Description:\n" + - " Run `git` *arguments* in the source directory. Note that flags in\n" + - " *arguments* must occur after `--` to prevent chezmoi from interpreting them.", - example: "" + - " chezmoi git add .\n" + - " chezmoi git add dot_gitconfig\n" + - " chezmoi git -- commit -m \"Add .gitconfig\"", - }, - "help": { - long: "" + - "Description:\n" + - " Print the help associated with *command*.", - }, - "hg": { - long: "" + - "Description:\n" + - " Run `hg` *arguments* in the source directory. Note that flags in *arguments*\n" + - " must occur after `--` to prevent chezmoi from interpreting them.", - example: "" + - " chezmoi hg -- pull --rebase --update", - }, - "import": { - long: "" + - "Description:\n" + - " Import the source state from an archive file in to a directory in the source\n" + - " state. This is primarily used to make subdirectories of your home directory\n" + - " exactly match the contents of a downloaded archive. You will generally\n" + - " always want to set the `--destination`, `--exact`, and `--remove-destination`\n" + - " flags.\n" + - "\n" + - " The only supported archive format is `.tar.gz`.\n" + - "\n" + - " `--destination` *directory*\n" + - "\n" + - " Set the destination (in the source state) where the archive will be\n" + - " imported.\n" + - "\n" + - " `-x`, `--exact`\n" + - "\n" + - " Set the `exact` attribute on all imported directories.\n" + - "\n" + - " `-r`, `--remove-destination`\n" + - "\n" + - " Remove destination (in the source state) before importing.\n" + - "\n" + - " `--strip-components` *n*\n" + - "\n" + - " Strip *n* leading components from paths.", - example: "" + - " curl -s -L -o oh-my-zsh-master.tar.gz https://github.com/robbyrussell/oh-my-\n" + - "zsh/archive/master.tar.gz\n" + - " chezmoi import --strip-components 1 --destination ~/.oh-my-zsh oh-my-zsh-master.tar.gz", - }, - "init": { - long: "" + - "Description:\n" + - " Setup the source directory and update the destination directory to match the\n" + - " target state.\n" + - "\n" + - " First, if the source directory is not already contain a repository, then if\n" + - " *repo* is given it is checked out into the source directory, otherwise a new\n" + - " repository is initialized in the source directory.\n" + - "\n" + - " Second, if a file called `.chezmoi.format.tmpl` exists, where `format` is\n" + - " one of the supported file formats (e.g. `json`, `toml`, or `yaml`) then a\n" + - " new configuration file is created using that file as a template.\n" + - "\n" + - " Finally, if the `--apply` flag is passed, `chezmoi apply` is run.\n" + - "\n" + - " `--apply`\n" + - "\n" + - " Run `chezmoi apply` after checking out the repo and creating the config\n" + - " file. This is `false` by default.", - example: "" + - " chezmoi init https://github.com/user/dotfiles.git\n" + - " chezmoi init https://github.com/user/dotfiles.git --apply", - }, - "manage": { - long: "" + - "Description:\n" + - " `manage` is an alias for `add` for symmetry with `unmanage`.", - }, - "managed": { - long: "" + - "Description:\n" + - " List all managed entries in the destination directory in alphabetical order.\n" + - "\n" + - " `-i`, `--include` *types*\n" + - "\n" + - " Only list entries of type *types*. *types* is a comma-separated list of types\n" + - " of entry to include. Valid types are `dirs`, `files`, and `symlinks` which\n" + - " can be abbreviated to `d`, `f`, and `s` respectively. By default, `manage`\n" + - " will list entries of all types.", - example: "" + - " chezmoi managed\n" + - " chezmoi managed --include=files\n" + - " chezmoi managed --include=files,symlinks\n" + - " chezmoi managed -i d\n" + - " chezmoi managed -i d,f", - }, - "merge": { - long: "" + - "Description:\n" + - " Perform a three-way merge between the destination state, the source state,\n" + - " and the target state. The merge tool is defined by the `merge.command`\n" + - " configuration variable, and defaults to `vimdiff`. If multiple targets are\n" + - " specified the merge tool is invoked for each target. If the target state\n" + - " cannot be computed (for example if source is a template containing errors or\n" + - " an encrypted file that cannot be decrypted) a two-way merge is performed\n" + - " instead.", - example: "" + - " chezmoi merge ~/.bashrc", - }, - "purge": { - long: "" + - "Description:\n" + - " Remove chezmoi's configuration, state, and source directory, but leave the\n" + - " target state intact.\n" + - "\n" + - " `-f`, `--force`\n" + - "\n" + - " Remove without prompting.", - example: "" + - " chezmoi purge\n" + - " chezmoi purge --force", - }, - "remove": { - long: "" + - "Description:\n" + - " Remove *targets* from both the source state and the destination directory.\n" + - "\n" + - " `-f`, `--force`\n" + - "\n" + - " Remove without prompting.", - }, - "rm": { - long: "" + - "Description:\n" + - " `rm` is an alias for `remove`.", - }, - "secret": { - long: "" + - "Description:\n" + - " Run a secret manager's CLI, passing any extra arguments to the secret\n" + - " manager's CLI. This is primarily for verifying chezmoi's integration with\n" + - " your secret manager. Normally you would use template functions to retrieve\n" + - " secrets. Note that if you want to pass flags to the secret manager's CLI you\n" + - " will need to separate them with `--` to prevent chezmoi from interpreting\n" + - " them.\n" + - "\n" + - " To get a full list of available commands run:\n" + - "\n" + - " chezmoi secret help", - example: "" + - " chezmoi secret bitwarden list items\n" + - " chezmoi secret keyring set --service service --user user\n" + - " chezmoi secret keyring get --service service --user user\n" + - " chezmoi secret lastpass ls\n" + - " chezmoi secret lastpass -- show --format=json id\n" + - " chezmoi secret onepassword list items\n" + - " chezmoi secret onepassword get item id\n" + - " chezmoi secret pass show id\n" + - " chezmoi secret vault -- kv get -format=json id", - }, - "source": { - long: "" + - "Description:\n" + - " Execute the source version control system in the source directory with\n" + - " *args*. Note that any flags for the source version control system must be\n" + - " separated with a `--` to stop chezmoi from reading them.", - example: "" + - " chezmoi source init\n" + - " chezmoi source add .\n" + - " chezmoi source commit -- -m \"Initial commit\"", - }, - "source-path": { - long: "" + - "Description:\n" + - " Print the path to each target's source state. If no targets are specified\n" + - " then print the source directory.\n" + - "\n" + - " `source-path` examples\n" + - "\n" + - " chezmoi source-path\n" + - " chezmoi source-path ~/.bashrc", - }, - "unmanage": { - long: "" + - "Description:\n" + - " `unmanage` is an alias for `forget` for symmetry with `manage`.", - }, - "unmanaged": { - long: "" + - "Description:\n" + - " List all unmanaged files in the destination directory.", - example: "" + - " chezmoi unmanaged", - }, - "update": { - long: "" + - "Description:\n" + - " Pull changes from the source VCS and apply any changes.", - example: "" + - " chezmoi update", - }, - "upgrade": { - long: "" + - "Description:\n" + - " Upgrade chezmoi by downloading and installing the latest released version.\n" + - " This will call the GitHub API to determine if there is a new version of\n" + - " chezmoi available, and if so, download and attempt to install it in the same\n" + - " way as chezmoi was previously installed.\n" + - "\n" + - " If chezmoi was installed with a package manager (`dpkg` or `rpm`) then\n" + - " `upgrade` will download a new package and install it, using `sudo` if it is\n" + - " installed. Otherwise, chezmoi will download the latest executable and\n" + - " replace the existing executable with the new version.\n" + - "\n" + - " If the `CHEZMOI_GITHUB_API_TOKEN` environment variable is set, then its\n" + - " value will be used to authenticate requests to the GitHub API, otherwise\n" + - " unauthenticated requests are used which are subject to stricter rate\n" + - " limiting https://developer.github.com/v3/#rate-limiting. Unauthenticated\n" + - " requests should be sufficient for most cases.", - example: "" + - " chezmoi upgrade", - }, - "verify": { - long: "" + - "Description:\n" + - " Verify that all *targets* match their target state. chezmoi exits with code\n" + - " 0 (success) if all targets match their target state, or 1 (failure)\n" + - " otherwise. If no targets are specified then all targets are checked.", - example: "" + - " chezmoi verify\n" + - " chezmoi verify ~/.bashrc", - }, -} diff --git a/cmd/hg.go b/cmd/hg.go deleted file mode 100644 index a6d03992783..00000000000 --- a/cmd/hg.go +++ /dev/null @@ -1,27 +0,0 @@ -package cmd - -import ( - "path/filepath" - - "github.com/spf13/cobra" -) - -var hgCmd = &cobra.Command{ - Use: "hg [args...]", - Short: "Run mercurial in the source directory", - Long: mustGetLongHelp("hg"), - Example: getExample("hg"), - RunE: config.runHgCmd, -} - -func init() { - rootCmd.AddCommand(hgCmd) -} - -func (c *Config) runHgCmd(cmd *cobra.Command, args []string) error { - name := "hg" - if trimExecutableSuffix(filepath.Base(c.SourceVCS.Command)) == "hg" { - name = c.SourceVCS.Command - } - return c.run(c.SourceDir, name, args...) -} diff --git a/cmd/hgvcs.go b/cmd/hgvcs.go deleted file mode 100644 index 76d9fb09b43..00000000000 --- a/cmd/hgvcs.go +++ /dev/null @@ -1,63 +0,0 @@ -package cmd - -import ( - "os" - "path/filepath" - "regexp" -) - -var hgVersionRegexp = regexp.MustCompile(`^Mercurial Distributed SCM \(version (\d+\.\d+(\.\d+)?\))`) - -type hgVCS struct{} - -func (hgVCS) AddArgs(path string) []string { - return nil -} - -func (hgVCS) CloneArgs(repo, dir string) []string { - return []string{"clone", repo, dir} -} - -func (hgVCS) CommitArgs(message string) []string { - return nil -} - -func (hgVCS) InitArgs() []string { - return []string{"init"} -} - -func (hgVCS) Initialized(dir string) (bool, error) { - info, err := os.Stat(filepath.Join(dir, ".hg")) - switch { - case err == nil: - return info.IsDir(), nil - case os.IsNotExist(err): - return false, nil - default: - return false, err - } -} - -func (hgVCS) ParseStatusOutput(output []byte) (interface{}, error) { - return nil, nil -} - -func (hgVCS) PullArgs() []string { - return []string{"pull", "--update"} -} - -func (hgVCS) PushArgs() []string { - return nil -} - -func (hgVCS) StatusArgs() []string { - return nil -} - -func (hgVCS) VersionArgs() []string { - return []string{"version"} -} - -func (hgVCS) VersionRegexp() *regexp.Regexp { - return hgVersionRegexp -} diff --git a/cmd/import.go b/cmd/import.go deleted file mode 100644 index 83b2f570471..00000000000 --- a/cmd/import.go +++ /dev/null @@ -1,87 +0,0 @@ -package cmd - -import ( - "archive/tar" - "compress/bzip2" - "compress/gzip" - "fmt" - "io" - "os" - "path/filepath" - "strings" - - "github.com/spf13/cobra" - - "github.com/twpayne/chezmoi/internal/chezmoi" -) - -var _importCmd = &cobra.Command{ - Use: "import [filename]", - Args: cobra.MaximumNArgs(1), - Short: "Import a tar archive into the source state", - Long: mustGetLongHelp("import"), - Example: getExample("import"), - PreRunE: config.ensureNoError, - RunE: config.runImportCmd, -} - -type importCmdConfig struct { - removeDestination bool - importTAROptions chezmoi.ImportTAROptions -} - -func init() { - rootCmd.AddCommand(_importCmd) - - persistentFlags := _importCmd.PersistentFlags() - persistentFlags.StringVarP(&config._import.importTAROptions.DestinationDir, "destination", "d", "", "destination prefix") - persistentFlags.BoolVarP(&config._import.importTAROptions.Exact, "exact", "x", false, "import directories exactly") - persistentFlags.IntVar(&config._import.importTAROptions.StripComponents, "strip-components", 0, "strip components") - persistentFlags.BoolVarP(&config._import.removeDestination, "remove-destination", "r", false, "remove destination before import") - - panicOnError(_importCmd.MarkZshCompPositionalArgumentFile(1, "*.tar", "*.tar.bz2", "*.tar.gz", "*.tgz")) -} - -func (c *Config) runImportCmd(cmd *cobra.Command, args []string) error { - ts, err := c.getTargetState(nil) - if err != nil { - return err - } - var r io.Reader - if len(args) == 0 { - r = c.Stdin - } else { - arg := args[0] - f, err := c.fs.Open(arg) - if err != nil { - return err - } - defer f.Close() - switch { - case strings.HasSuffix(arg, ".tar.gz") || strings.HasSuffix(arg, ".tgz"): - r, err = gzip.NewReader(f) - if err != nil { - return err - } - case strings.HasSuffix(arg, ".tar.bz2"): - r = bzip2.NewReader(f) - case strings.HasSuffix(arg, ".tar"): - r = f - default: - return fmt.Errorf("%s: unknown format", arg) - } - } - if c._import.removeDestination { - entry, err := ts.Get(c.fs, c._import.importTAROptions.DestinationDir) - switch { - case err == nil: - if err := c.mutator.RemoveAll(filepath.Join(c.SourceDir, entry.SourceName())); err != nil { - return err - } - case os.IsNotExist(err): - default: - return err - } - } - return ts.ImportTAR(tar.NewReader(r), c._import.importTAROptions, c.mutator) -} diff --git a/cmd/import_test.go b/cmd/import_test.go deleted file mode 100644 index ec2bb18d3d3..00000000000 --- a/cmd/import_test.go +++ /dev/null @@ -1,61 +0,0 @@ -package cmd - -import ( - "archive/tar" - "bytes" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/twpayne/go-vfs/vfst" -) - -func TestImportCmd(t *testing.T) { - b := &bytes.Buffer{} - w := tar.NewWriter(b) - assert.NoError(t, w.WriteHeader(&tar.Header{ - Typeflag: tar.TypeDir, - Name: "dir", - Mode: 0o755, - })) - assert.NoError(t, w.WriteHeader(&tar.Header{ - Typeflag: tar.TypeReg, - Name: "dir/file", - Size: int64(len("contents")), - Mode: 0o644, - })) - _, err := w.Write([]byte("contents")) - assert.NoError(t, err) - assert.NoError(t, w.WriteHeader(&tar.Header{ - Typeflag: tar.TypeSymlink, - Name: "symlink", - Linkname: "target", - })) - assert.NoError(t, w.Close()) - - fs, cleanup, err := vfst.NewTestFS(map[string]interface{}{ - "/home/user/.local/share/chezmoi": &vfst.Dir{Perm: 0o700}, - }) - require.NoError(t, err) - defer cleanup() - - c := newTestConfig( - fs, - withStdin(b), - ) - assert.NoError(t, c.runImportCmd(nil, nil)) - - vfst.RunTests(t, fs, "test", - vfst.TestPath("/home/user/.local/share/chezmoi/dir", - vfst.TestIsDir, - ), - vfst.TestPath("/home/user/.local/share/chezmoi/dir/file", - vfst.TestModeIsRegular, - vfst.TestContentsString("contents"), - ), - vfst.TestPath("/home/user/.local/share/chezmoi/symlink_symlink", - vfst.TestModeIsRegular, - vfst.TestContentsString("target"), - ), - ) -} diff --git a/chezmoi2/cmd/importcmd.go b/cmd/importcmd.go similarity index 93% rename from chezmoi2/cmd/importcmd.go rename to cmd/importcmd.go index f1a003d9b0b..437f150b31d 100644 --- a/chezmoi2/cmd/importcmd.go +++ b/cmd/importcmd.go @@ -13,13 +13,13 @@ import ( "github.com/spf13/cobra" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoi" ) type importCmdConfig struct { destination string exact bool - include *chezmoi.IncludeSet + include *chezmoi.EntryTypeSet removeDestination bool stripComponents int } @@ -41,7 +41,7 @@ func (c *Config) newImportCmd() *cobra.Command { flags := importCmd.Flags() flags.StringVarP(&c._import.destination, "destination", "d", c._import.destination, "destination prefix") - flags.BoolVarP(&c._import.exact, "exact", "x", c._import.exact, "import directories exactly") + flags.BoolVar(&c._import.exact, "exact", c._import.exact, "import directories exactly") flags.VarP(c._import.include, "include", "i", "include entry types") flags.BoolVarP(&c._import.removeDestination, "remove-destination", "r", c._import.removeDestination, "remove destination before import") flags.IntVar(&c._import.stripComponents, "strip-components", c._import.stripComponents, "strip components") diff --git a/chezmoi2/cmd/importcmd_test.go b/cmd/importcmd_test.go similarity index 97% rename from chezmoi2/cmd/importcmd_test.go rename to cmd/importcmd_test.go index f2639035cc2..15e3e853a36 100644 --- a/chezmoi2/cmd/importcmd_test.go +++ b/cmd/importcmd_test.go @@ -8,10 +8,10 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/twpayne/go-vfs" - "github.com/twpayne/go-vfs/vfst" + "github.com/twpayne/go-vfs/v2" + "github.com/twpayne/go-vfs/v2/vfst" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoitest" + "github.com/twpayne/chezmoi/internal/chezmoitest" ) func TestImportCmd(t *testing.T) { diff --git a/cmd/init.go b/cmd/init.go deleted file mode 100644 index 49fc85a2741..00000000000 --- a/cmd/init.go +++ /dev/null @@ -1,211 +0,0 @@ -package cmd - -import ( - "bufio" - "bytes" - "fmt" - "os" - "path/filepath" - "strconv" - "strings" - "text/template" - - "github.com/spf13/cobra" - "github.com/spf13/viper" - vfs "github.com/twpayne/go-vfs" - - "github.com/twpayne/chezmoi/internal/chezmoi" -) - -var initCmd = &cobra.Command{ - Args: cobra.MaximumNArgs(1), - Use: "init [repo]", - Short: "Setup the source directory and update the destination directory to match the target state", - Long: mustGetLongHelp("init"), - Example: getExample("init"), - PreRunE: config.ensureNoError, - RunE: config.runInitCmd, -} - -type initCmdConfig struct { - apply bool -} - -func init() { - rootCmd.AddCommand(initCmd) - - persistentFlags := initCmd.PersistentFlags() - persistentFlags.BoolVar(&config.init.apply, "apply", false, "update destination directory") -} - -func (c *Config) runInitCmd(cmd *cobra.Command, args []string) error { - vcs, err := c.getVCS() - if err != nil { - return err - } - - if err := c.ensureSourceDirectory(); err != nil { - return err - } - - rawSourceDir, err := c.fs.RawPath(c.SourceDir) - if err != nil { - return err - } - - initialized, err := vcs.Initialized(c.SourceDir) - if err != nil { - return err - } - if !initialized { - switch len(args) { - case 0: // init - var initArgs []string - if c.SourceVCS.Init != nil { - switch v := c.SourceVCS.Init.(type) { - case string: - initArgs = strings.Split(v, " ") - case []string: - initArgs = v - default: - return fmt.Errorf("sourceVCS.init: cannot parse value") - } - } else { - initArgs = vcs.InitArgs() - } - if err := c.run(c.SourceDir, c.SourceVCS.Command, initArgs...); err != nil { - return err - } - case 1: // clone - cloneArgs := vcs.CloneArgs(args[0], rawSourceDir) - if cloneArgs == nil { - return fmt.Errorf("%s: cloning not supported", c.SourceVCS.Command) - } - if err := c.run("", c.SourceVCS.Command, cloneArgs...); err != nil { - return err - } - // FIXME this should be part of VCS - if filepath.Base(c.SourceVCS.Command) == "git" { - if _, err := c.fs.Stat(filepath.Join(c.SourceDir, ".gitmodules")); err == nil { - for _, args := range [][]string{ - {"submodule", "init"}, - {"submodule", "update"}, - } { - if err := c.run(c.SourceDir, c.SourceVCS.Command, args...); err != nil { - return err - } - } - } - } - } - } - - if err := c.createConfigFile(); err != nil { - return err - } - - if c.init.apply { - persistentState, err := c.getPersistentState(nil) - if err != nil { - return err - } - if err := c.applyArgs(nil, persistentState); err != nil { - return err - } - } - - return nil -} - -func (c *Config) createConfigFile() error { - filename, ext, data, err := c.findConfigTemplate() - if err != nil { - return err - } - - if filename == "" { - // no config template file exists - return nil - } - - funcMap := make(template.FuncMap) - for key, value := range c.templateFuncs { - funcMap[key] = value - } - for key, value := range map[string]interface{}{ - "promptBool": c.promptBool, - "promptInt": c.promptInt, - "promptString": c.promptString, - } { - funcMap[key] = value - } - t, err := template.New(filename).Funcs(funcMap).Parse(data) - if err != nil { - return err - } - - defaultData, err := c.getDefaultData() - if err != nil { - return err - } - - contents := &bytes.Buffer{} - if err = t.Execute(contents, map[string]interface{}{ - "chezmoi": defaultData, - }); err != nil { - return err - } - - configDir := filepath.Join(c.bds.ConfigHome, "chezmoi") - if err := vfs.MkdirAll(c.mutator, configDir, 0o777&^os.FileMode(c.Umask)); err != nil { - return err - } - - configPath := filepath.Join(configDir, filename) - if err := c.mutator.WriteFile(configPath, contents.Bytes(), 0o600&^os.FileMode(c.Umask), nil); err != nil { - return err - } - - viper.SetConfigType(ext) - if err := viper.ReadConfig(contents); err != nil { - return err - } - return viper.Unmarshal(c) -} - -func (c *Config) findConfigTemplate() (string, string, string, error) { - for _, ext := range viper.SupportedExts { - contents, err := c.fs.ReadFile(filepath.Join(c.SourceDir, ".chezmoi."+ext+chezmoi.TemplateSuffix)) - switch { - case os.IsNotExist(err): - continue - case err != nil: - return "", "", "", err - } - return "chezmoi." + ext, ext, string(contents), nil - } - return "", "", "", nil -} - -func (c *Config) promptBool(field string) bool { - value, err := parseBool(c.promptString(field)) - if err != nil { - panic(err) - } - return value -} - -func (c *Config) promptInt(field string) int64 { - value, err := strconv.ParseInt(c.promptString(field), 10, 64) - if err != nil { - panic(err) - } - return value -} - -func (c *Config) promptString(field string) string { - fmt.Fprintf(c.Stdout, "%s? ", field) - value, err := bufio.NewReader(c.Stdin).ReadString('\n') - panicOnError(err) - return strings.TrimSpace(value) -} diff --git a/cmd/init_test.go b/cmd/init_test.go deleted file mode 100644 index 73a3645a30e..00000000000 --- a/cmd/init_test.go +++ /dev/null @@ -1,153 +0,0 @@ -package cmd - -import ( - "bytes" - "errors" - "os" - "os/exec" - "path/filepath" - "runtime" - "strings" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/twpayne/go-vfs/vfst" -) - -func TestPromptStringIgnoreWindowsNewline(t *testing.T) { - fs, cleanup, err := vfst.NewTestFS(map[string]interface{}{ - "/home/user/.local/share/chezmoi/.chezmoi.toml.tmpl": strings.Join([]string{ - `{{ $env := promptString "environment [work/home]" -}}`, - `[data]`, - ` environment = "{{ $env }}"`, - }, "\n"), - }) - require.NoError(t, err) - defer cleanup() - - c := newTestConfig( - fs, - withStdin(bytes.NewBufferString("home\r\n")), - ) - - require.NoError(t, c.createConfigFile()) - - vfst.RunTests(t, fs, "", - vfst.TestPath("/home/user/.config/chezmoi/chezmoi.toml", - vfst.TestModeIsRegular, - vfst.TestModePerm(0o600), - vfst.TestContentsString( - strings.Join([]string{ - `[data]`, - ` environment = "home"`, - }, "\n"), - ), - ), - ) - - assert.Equal(t, map[string]interface{}{ - "environment": "home", - }, c.Data) -} - -func TestCreateConfigFile(t *testing.T) { - fs, cleanup, err := vfst.NewTestFS(map[string]interface{}{ - "/home/user/.local/share/chezmoi/.chezmoi.yaml.tmpl": strings.Join([]string{ - `{{ $email := promptString "email" | trim -}}`, - `data:`, - ` email: "{{ $email }}"`, - ` mailtoURL: "mailto:{{ $email }}"`, - ` os: "{{ .chezmoi.os }}"`, - }, "\n"), - }) - require.NoError(t, err) - defer cleanup() - - c := newTestConfig( - fs, - withStdin(bytes.NewBufferString("[email protected] \n")), - ) - - require.NoError(t, c.createConfigFile()) - - vfst.RunTests(t, fs, "", - vfst.TestPath("/home/user/.config/chezmoi/chezmoi.yaml", - vfst.TestModeIsRegular, - vfst.TestModePerm(0o600), - vfst.TestContentsString(strings.Join([]string{ - `data:`, - ` email: "[email protected]"`, - ` mailtoURL: "mailto:[email protected]"`, - ` os: "` + runtime.GOOS + `"`, - }, "\n")), - ), - ) - - assert.Equal(t, map[string]interface{}{ - "email": "[email protected]", - "mailtourl": "mailto:[email protected]", - "os": runtime.GOOS, - }, c.Data) -} - -func TestInit(t *testing.T) { - fs, cleanup, err := vfst.NewTestFS(map[string]interface{}{ - "/home/user": &vfst.Dir{Perm: 0o755}, - }) - require.NoError(t, err) - defer cleanup() - - c := newTestConfig(fs) - require.NoError(t, c.runInitCmd(nil, nil)) - vfst.RunTests(t, fs, "", - vfst.TestPath("/home/user/.local/share/chezmoi", - vfst.TestIsDir, - ), - vfst.TestPath("/home/user/.local/share/chezmoi/.git", - vfst.TestIsDir, - ), - vfst.TestPath("/home/user/.local/share/chezmoi/.git/HEAD", - vfst.TestModeIsRegular, - ), - ) -} - -func TestInitRepo(t *testing.T) { - switch _, err := exec.LookPath("git"); { - case errors.Is(err, exec.ErrNotFound): - t.Skip("git not found in $PATH") - default: - require.NoError(t, err) - } - - fs, cleanup, err := vfst.NewTestFS(map[string]interface{}{ - "/home/user": &vfst.Dir{Perm: 0o755}, - }) - require.NoError(t, err) - defer cleanup() - - c := newTestConfig(fs) - wd, err := os.Getwd() - require.NoError(t, err) - require.NoError(t, c.runInitCmd(nil, []string{filepath.Join(wd, "testdata/gitrepo")})) - vfst.RunTests(t, fs, "", - vfst.TestPath("/home/user/.local/share/chezmoi", - vfst.TestIsDir, - ), - vfst.TestPath("/home/user/.local/share/chezmoi/.git", - vfst.TestIsDir, - ), - vfst.TestPath("/home/user/.local/share/chezmoi/.git/HEAD", - vfst.TestModeIsRegular, - ), - vfst.TestPath("/home/user/.local/share/chezmoi/dot_bashrc", - vfst.TestModeIsRegular, - vfst.TestContentsString(lines("# contents of .bashrc\n")), - ), - vfst.TestPath("/home/user/.config/chezmoi/chezmoi.toml", - vfst.TestModeIsRegular, - vfst.TestContentsString(lines("# contents of chezmoi.toml\n")), - ), - ) -} diff --git a/chezmoi2/cmd/initcmd.go b/cmd/initcmd.go similarity index 91% rename from chezmoi2/cmd/initcmd.go rename to cmd/initcmd.go index 2ca4ed36bea..eb61db203d5 100644 --- a/chezmoi2/cmd/initcmd.go +++ b/cmd/initcmd.go @@ -15,16 +15,15 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoi" ) type initCmdConfig struct { - apply bool - depth int - oneShot bool - purge bool - purgeBinary bool - skipEncrypted bool + apply bool + depth int + oneShot bool + purge bool + purgeBinary bool } var dotfilesRepoGuesses = []struct { @@ -87,7 +86,6 @@ func (c *Config) newInitCmd() *cobra.Command { flags.BoolVar(&c.init.oneShot, "one-shot", c.init.oneShot, "one shot") flags.BoolVarP(&c.init.purge, "purge", "p", c.init.purge, "purge config and source directories") flags.BoolVarP(&c.init.purgeBinary, "purge-binary", "P", c.init.purgeBinary, "purge chezmoi binary") - flags.BoolVar(&c.init.skipEncrypted, "skip-encrypted", c.init.skipEncrypted, "skip encrypted files") return initCmd } @@ -157,13 +155,17 @@ func (c *Config) runInitCmd(cmd *cobra.Command, args []string) error { } // Find config template, execute it, and create config file. - filename, ext, configTemplateContents, err := c.findConfigTemplate() + configTemplateRelPath, ext, configTemplateContents, err := c.findConfigTemplate() if err != nil { return err } var configFileContents []byte - if filename != "" { - configFileContents, err = c.createConfigFile(filename, configTemplateContents) + if configTemplateRelPath == "" { + if err := c.persistentState.Delete(chezmoi.ConfigStateBucket, configStateKey); err != nil { + return err + } + } else { + configFileContents, err = c.createConfigFile(configTemplateRelPath, configTemplateContents) if err != nil { return err } @@ -179,7 +181,7 @@ func (c *Config) runInitCmd(cmd *cobra.Command, args []string) error { } // Reload config if it was created. - if filename != "" { + if configTemplateRelPath != "" { viper.SetConfigType(ext) if err := viper.ReadConfig(bytes.NewBuffer(configFileContents)); err != nil { return err @@ -192,11 +194,10 @@ func (c *Config) runInitCmd(cmd *cobra.Command, args []string) error { // Apply. if c.init.apply { if err := c.applyArgs(c.destSystem, c.destDirAbsPath, noArgs, applyArgsOptions{ - include: chezmoi.NewIncludeSet(chezmoi.IncludeAll), - recursive: false, - umask: c.Umask, - preApplyFunc: c.defaultPreApplyFunc, - skipEncrypted: c.init.skipEncrypted, + include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll), + recursive: false, + umask: c.Umask, + preApplyFunc: c.defaultPreApplyFunc, }); err != nil { return err } diff --git a/chezmoi2/cmd/initcmd_test.go b/cmd/initcmd_test.go similarity index 100% rename from chezmoi2/cmd/initcmd_test.go rename to cmd/initcmd_test.go diff --git a/cmd/ioreg.go b/cmd/ioreg.go deleted file mode 100644 index d7bd26cd22d..00000000000 --- a/cmd/ioreg.go +++ /dev/null @@ -1,12 +0,0 @@ -//+build !darwin - -package cmd - -//nolint:unused -type ioregData struct{} - -func init() { - config.addTemplateFunc("ioreg", func() map[string]interface{} { - return nil - }) -} diff --git a/cmd/ioreg_darwin.go b/cmd/ioreg_darwin.go deleted file mode 100644 index 7602d3fb17e..00000000000 --- a/cmd/ioreg_darwin.go +++ /dev/null @@ -1,35 +0,0 @@ -package cmd - -import ( - "fmt" - "os/exec" - - "howett.net/plist" -) - -type ioregData struct { - value map[string]interface{} -} - -func init() { - config.addTemplateFunc("ioreg", config.ioregFunc) -} - -func (c *Config) ioregFunc() map[string]interface{} { - if c.ioregData.value != nil { - return c.ioregData.value - } - - cmd := exec.Command("ioreg", "-a", "-l") - output, err := c.mutator.IdempotentCmdOutput(cmd) - if err != nil { - panic(fmt.Errorf("ioreg: %w", err)) - } - - var value map[string]interface{} - if _, err := plist.Unmarshal(output, &value); err != nil { - panic(fmt.Errorf("ioreg: %w", err)) - } - c.ioregData.value = value - return value -} diff --git a/chezmoi2/cmd/keepassxctemplatefuncs.go b/cmd/keepassxctemplatefuncs.go similarity index 98% rename from chezmoi2/cmd/keepassxctemplatefuncs.go rename to cmd/keepassxctemplatefuncs.go index 7ef72b03745..89b2448ce77 100644 --- a/chezmoi2/cmd/keepassxctemplatefuncs.go +++ b/cmd/keepassxctemplatefuncs.go @@ -11,7 +11,7 @@ import ( "github.com/coreos/go-semver/semver" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoi" ) type keepassxcAttributeCacheKey struct { diff --git a/chezmoi2/cmd/keyringtemplatefuncs.go b/cmd/keyringtemplatefuncs.go similarity index 100% rename from chezmoi2/cmd/keyringtemplatefuncs.go rename to cmd/keyringtemplatefuncs.go diff --git a/chezmoi2/cmd/lastpasstemplatefuncs.go b/cmd/lastpasstemplatefuncs.go similarity index 100% rename from chezmoi2/cmd/lastpasstemplatefuncs.go rename to cmd/lastpasstemplatefuncs.go diff --git a/chezmoi2/cmd/lastpasstemplatefuncs_test.go b/cmd/lastpasstemplatefuncs_test.go similarity index 95% rename from chezmoi2/cmd/lastpasstemplatefuncs_test.go rename to cmd/lastpasstemplatefuncs_test.go index edd004aa9af..86214d1bc0c 100644 --- a/chezmoi2/cmd/lastpasstemplatefuncs_test.go +++ b/cmd/lastpasstemplatefuncs_test.go @@ -5,7 +5,7 @@ import ( "github.com/stretchr/testify/assert" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoitest" + "github.com/twpayne/chezmoi/internal/chezmoitest" ) func Test_lastpassParseNote(t *testing.T) { diff --git a/cmd/managed.go b/cmd/managed.go deleted file mode 100644 index c74de4ae13b..00000000000 --- a/cmd/managed.go +++ /dev/null @@ -1,83 +0,0 @@ -package cmd - -import ( - "fmt" - "path/filepath" - "sort" - - "github.com/spf13/cobra" - - "github.com/twpayne/chezmoi/internal/chezmoi" -) - -var managedCmd = &cobra.Command{ - Use: "managed", - Args: cobra.NoArgs, - Short: "List the managed files in the destination directory", - Long: mustGetLongHelp("managed"), - Example: getExample("managed"), - PreRunE: config.ensureNoError, - RunE: config.runManagedCmd, -} - -type managedCmdConfig struct { - include []string -} - -func init() { - rootCmd.AddCommand(managedCmd) - - persistentFlags := managedCmd.PersistentFlags() - persistentFlags.StringSliceVarP(&config.managed.include, "include", "i", []string{"dirs", "files", "symlinks"}, "include") -} - -func (c *Config) runManagedCmd(cmd *cobra.Command, args []string) error { - ts, err := c.getTargetState(nil) - if err != nil { - return err - } - - var ( - includeDirs = false - includeFiles = false - includeSymlinks = false - ) - for _, what := range c.managed.include { - switch what { - case "dirs", "d": - includeDirs = true - case "files", "f": - includeFiles = true - case "symlinks", "s": - includeSymlinks = true - default: - return fmt.Errorf("unrecognized include: %q", what) - } - } - - allEntries := ts.AllEntries() - - targetNames := make([]string, 0, len(allEntries)) - for _, entry := range allEntries { - if _, ok := entry.(*chezmoi.Dir); ok && !includeDirs { - continue - } - if _, ok := entry.(*chezmoi.File); ok && !includeFiles { - continue - } - if _, ok := entry.(*chezmoi.Symlink); ok && !includeSymlinks { - continue - } - targetNames = append(targetNames, entry.TargetName()) - } - - sort.Strings(targetNames) - for _, targetName := range targetNames { - if ts.TargetIgnore.Match(targetName) { - continue - } - fmt.Fprintln(c.Stdout, filepath.Join(ts.DestDir, targetName)) - } - - return nil -} diff --git a/cmd/managed_test.go b/cmd/managed_test.go deleted file mode 100644 index 5266d733554..00000000000 --- a/cmd/managed_test.go +++ /dev/null @@ -1,119 +0,0 @@ -package cmd - -import ( - "bufio" - "bytes" - "path/filepath" - "strings" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/twpayne/go-vfs/vfst" -) - -func TestManagedCmd(t *testing.T) { - for _, tc := range []struct { - include []string - expectedTargetNames []string - }{ - { - include: []string{"dirs", "files", "symlinks"}, - expectedTargetNames: []string{ - "/home/user/dir", - "/home/user/dir/file1", - "/home/user/dir/subdir", - "/home/user/dir/subdir/file2", - "/home/user/symlink", - }, - }, - { - include: []string{"d", "f", "s"}, - expectedTargetNames: []string{ - "/home/user/dir", - "/home/user/dir/file1", - "/home/user/dir/subdir", - "/home/user/dir/subdir/file2", - "/home/user/symlink", - }, - }, - { - include: []string{"dirs"}, - expectedTargetNames: []string{ - "/home/user/dir", - "/home/user/dir/subdir", - }, - }, - { - include: []string{"files"}, - expectedTargetNames: []string{ - "/home/user/dir/file1", - "/home/user/dir/subdir/file2", - }, - }, - { - include: []string{"symlinks"}, - expectedTargetNames: []string{ - "/home/user/symlink", - }, - }, - { - include: []string{"f", "s"}, - expectedTargetNames: []string{ - "/home/user/dir/file1", - "/home/user/dir/subdir/file2", - "/home/user/symlink", - }, - }, - } { - t.Run(strings.Join(tc.include, "_"), func(t *testing.T) { - fs, cleanup, err := vfst.NewTestFS(map[string]interface{}{ - "/home/user/.local/share/chezmoi": map[string]interface{}{ - "dir/file1": "contents", - "dir/subdir/file2": "contents", - "symlink_symlink": "target", - }, - }) - require.NoError(t, err) - defer cleanup() - stdout := &bytes.Buffer{} - c := newTestConfig( - fs, - withStdout(stdout), - withManaged(managedCmdConfig{ - include: tc.include, - }), - ) - assert.NoError(t, c.runManagedCmd(nil, nil)) - posixTargetNames, err := extractPOSIXTargetNames(stdout.Bytes()) - require.NoError(t, err) - assert.Equal(t, tc.expectedTargetNames, posixTargetNames) - }) - } -} - -// extractPOSIXTargetNames extracts all target names from b and coverts them to -// POSIX-like names. -func extractPOSIXTargetNames(b []byte) ([]string, error) { - var targetNames []string - s := bufio.NewScanner(bytes.NewBuffer(b)) - for s.Scan() { - targetNames = append(targetNames, posixify(s.Text())) - } - if err := s.Err(); err != nil { - return nil, err - } - return targetNames, nil -} - -// posixify returns a POSIX-like path based on path, stripping any volume name -// and converting backward slashes. -func posixify(path string) string { - return filepath.ToSlash(strings.TrimPrefix(path, filepath.VolumeName(path))) -} - -func withManaged(managed managedCmdConfig) configOption { - return func(c *Config) { - c.managed = managed - } -} diff --git a/chezmoi2/cmd/managedcmd.go b/cmd/managedcmd.go similarity index 87% rename from chezmoi2/cmd/managedcmd.go rename to cmd/managedcmd.go index cdf30f42260..5007fdfc39b 100644 --- a/chezmoi2/cmd/managedcmd.go +++ b/cmd/managedcmd.go @@ -7,11 +7,11 @@ import ( "github.com/spf13/cobra" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoi" ) type managedCmdConfig struct { - include *chezmoi.IncludeSet + include *chezmoi.EntryTypeSet } func (c *Config) newManagedCmd() *cobra.Command { @@ -31,6 +31,7 @@ func (c *Config) newManagedCmd() *cobra.Command { } func (c *Config) runManagedCmd(cmd *cobra.Command, args []string, sourceState *chezmoi.SourceState) error { + include := c.managed.include.Sub(c.exclude) entries := sourceState.Entries() targetRelPaths := make(chezmoi.RelPaths, 0, len(entries)) for targetRelPath, sourceStateEntry := range entries { @@ -38,7 +39,7 @@ func (c *Config) runManagedCmd(cmd *cobra.Command, args []string, sourceState *c if err != nil { return err } - if !c.managed.include.IncludeTargetStateEntry(targetStateEntry) { + if !include.IncludeTargetStateEntry(targetStateEntry) { continue } targetRelPaths = append(targetRelPaths, targetRelPath) diff --git a/cmd/merge.go b/cmd/merge.go deleted file mode 100644 index 7264e168cbe..00000000000 --- a/cmd/merge.go +++ /dev/null @@ -1,97 +0,0 @@ -package cmd - -import ( - "fmt" - "io/ioutil" - "os" - "path/filepath" - - "github.com/spf13/cobra" - - "github.com/twpayne/chezmoi/internal/chezmoi" -) - -var mergeCmd = &cobra.Command{ - Use: "merge targets...", - Args: cobra.MinimumNArgs(1), - Short: "Perform a three-way merge between the destination state, the source state, and the target state", - Long: mustGetLongHelp("merge"), - Example: getExample("merge"), - PreRunE: config.ensureNoError, - RunE: config.runMergeCmd, -} - -type mergeConfig struct { - Command string - Args []string -} - -func init() { - rootCmd.AddCommand(mergeCmd) - - markRemainingZshCompPositionalArgumentsAsFiles(mergeCmd, 1) -} - -func (c *Config) runMergeCmd(cmd *cobra.Command, args []string) error { - ts, err := c.getTargetState(nil) - if err != nil { - return err - } - - entries, err := c.getEntries(ts, args) - if err != nil { - return err - } - - // Create a temporary directory to store the target state and ensure that it - // is removed afterwards. We cannot use fs as it lacks TempDir - // functionality. - tempDir, err := ioutil.TempDir("", "chezmoi") - if err != nil { - return err - } - defer os.RemoveAll(tempDir) - - for i, entry := range entries { - if err := c.runMergeCommand(cmd, args[i], entry, tempDir); err != nil { - return err - } - } - - return nil -} - -func (c *Config) runMergeCommand(cmd *cobra.Command, arg string, entry chezmoi.Entry, tempDir string) error { - file, ok := entry.(*chezmoi.File) - if !ok { - return fmt.Errorf("%s: not a file", arg) - } - - // By default, perform a two-way merge between the destination state and the - // source state. - args := append( - append([]string{}, c.Merge.Args...), - filepath.Join(c.DestDir, file.TargetName()), - filepath.Join(c.SourceDir, file.SourceName()), - ) - - // Try to evaluate the target state. If this succeeds, perform a three-way - // merge between the destination state, the source state, and the target - // state. Target state evaluation might fail if the source state contains - // template errors or cannot be decrypted. - if contents, err := file.Contents(); err != nil { - cmd.Printf("warning: %s: cannot evaluate target state: %v\n", arg, err) - } else { - targetStatePath := filepath.Join(tempDir, filepath.Base(file.TargetName())) - if err := ioutil.WriteFile(targetStatePath, contents, 0o600); err != nil { - return err - } - args = append(args, targetStatePath) - } - - if err := c.run("", c.Merge.Command, args...); err != nil { - return fmt.Errorf("%s: %w", arg, err) - } - - return nil -} diff --git a/chezmoi2/cmd/mergecmd.go b/cmd/mergecmd.go similarity index 95% rename from chezmoi2/cmd/mergecmd.go rename to cmd/mergecmd.go index ae7cf622fdf..03b950b36ca 100644 --- a/chezmoi2/cmd/mergecmd.go +++ b/cmd/mergecmd.go @@ -2,12 +2,11 @@ package cmd import ( "fmt" - "io/ioutil" "os" "github.com/spf13/cobra" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoi" ) type mergeCmdConfig struct { @@ -44,7 +43,7 @@ func (c *Config) runMergeCmd(cmd *cobra.Command, args []string, sourceState *che // Create a temporary directory to store the target state and ensure that it // is removed afterwards. We cannot use fs as it lacks TempDir // functionality. - tempDir, err := ioutil.TempDir("", "chezmoi") + tempDir, err := os.MkdirTemp("", "chezmoi") if err != nil { return err } diff --git a/cmd/noupgrade.go b/cmd/noupgrade.go deleted file mode 100644 index 83b2b88ce8a..00000000000 --- a/cmd/noupgrade.go +++ /dev/null @@ -1,5 +0,0 @@ -// +build noupgrade windows - -package cmd - -type upgradeCmdConfig struct{} diff --git a/chezmoi2/cmd/onepasswordtemplatefuncs.go b/cmd/onepasswordtemplatefuncs.go similarity index 98% rename from chezmoi2/cmd/onepasswordtemplatefuncs.go rename to cmd/onepasswordtemplatefuncs.go index 70ef7b1f3ee..8f78ad20cfe 100644 --- a/chezmoi2/cmd/onepasswordtemplatefuncs.go +++ b/cmd/onepasswordtemplatefuncs.go @@ -6,7 +6,7 @@ import ( "os/exec" "strings" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoi" ) type onepasswordConfig struct { diff --git a/chezmoi2/cmd/passtemplatefuncs.go b/cmd/passtemplatefuncs.go similarity index 93% rename from chezmoi2/cmd/passtemplatefuncs.go rename to cmd/passtemplatefuncs.go index 93f68e5eafd..91ae3b0db92 100644 --- a/chezmoi2/cmd/passtemplatefuncs.go +++ b/cmd/passtemplatefuncs.go @@ -5,7 +5,7 @@ import ( "fmt" "os/exec" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoi" ) type passConfig struct { diff --git a/cmd/permvalue.go b/cmd/permvalue.go deleted file mode 100644 index 791e17cf17c..00000000000 --- a/cmd/permvalue.go +++ /dev/null @@ -1,30 +0,0 @@ -package cmd - -import ( - "fmt" - "strconv" -) - -// An permValue is an int that is scanned and printed in octal. It implements -// the pflag.Value interface for use as a command line flag. -type permValue int - -func (p *permValue) Set(s string) error { - v, err := strconv.ParseInt(s, 8, 64) - if err != nil { - return err - } - if v < 0o000 || 0o777 < v { - return fmt.Errorf("%s: invalid permission value", s) - } - *p = permValue(v) - return err -} - -func (p *permValue) String() string { - return fmt.Sprintf("%03o", *p) -} - -func (p *permValue) Type() string { - return "int" -} diff --git a/cmd/permvalue_test.go b/cmd/permvalue_test.go deleted file mode 100644 index 4e8e0aa2c2f..00000000000 --- a/cmd/permvalue_test.go +++ /dev/null @@ -1,20 +0,0 @@ -package cmd - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestPermValue(t *testing.T) { - for s, expected := range map[string]string{ - "0": "000", - "644": "644", - "755": "755", - } { - var p permValue - assert.NoError(t, p.Set(s)) - assert.Equal(t, expected, p.String()) - assert.Equal(t, "int", p.Type()) - } -} diff --git a/cmd/purge.go b/cmd/purge.go deleted file mode 100644 index dfb9f57f90e..00000000000 --- a/cmd/purge.go +++ /dev/null @@ -1,78 +0,0 @@ -package cmd - -import ( - "fmt" - "os" - "path/filepath" - - "github.com/spf13/cobra" -) - -var purgeCmd = &cobra.Command{ - Use: "purge", - Args: cobra.NoArgs, - Short: "Purge all of chezmoi's configuration and data", - Long: mustGetLongHelp("purge"), - Example: getExample("purge"), - RunE: config.runPurgeCmd, -} - -type purgeCmdConfig struct { - force bool -} - -func init() { - rootCmd.AddCommand(purgeCmd) - - persistentFlags := purgeCmd.PersistentFlags() - persistentFlags.BoolVarP(&config.purge.force, "force", "f", false, "remove without prompting") -} - -func (c *Config) runPurgeCmd(cmd *cobra.Command, args []string) error { - // Build a list of chezmoi-related paths. - var paths []string - for _, dirs := range [][]string{ - c.bds.ConfigDirs, - c.bds.DataDirs, - } { - for _, dir := range dirs { - paths = append(paths, filepath.Join(dir, "chezmoi")) - } - } - paths = append(paths, - c.configFile, - c.getPersistentStateFile(), - c.SourceDir, - ) - - // Remove all paths that exist. -PATH: - for _, path := range paths { - _, err := c.fs.Stat(path) - switch { - case os.IsNotExist(err): - continue PATH - case err != nil: - return err - } - if !c.purge.force { - choice, err := c.prompt(fmt.Sprintf("Remove %s", path), "ynqa") - if err != nil { - return err - } - switch choice { - case 'a': - c.purge.force = true - case 'n': - continue PATH - case 'q': - return nil - } - } - if err := c.mutator.RemoveAll(path); err != nil { - return err - } - } - - return nil -} diff --git a/chezmoi2/cmd/purgecmd.go b/cmd/purgecmd.go similarity index 100% rename from chezmoi2/cmd/purgecmd.go rename to cmd/purgecmd.go diff --git a/cmd/remove.go b/cmd/remove.go deleted file mode 100644 index d4dc6d98bcc..00000000000 --- a/cmd/remove.go +++ /dev/null @@ -1,71 +0,0 @@ -package cmd - -import ( - "fmt" - "os" - "path/filepath" - - "github.com/spf13/cobra" -) - -type removeCmdConfig struct { - force bool -} - -var removeCmd = &cobra.Command{ - Use: "remove targets...", - Aliases: []string{"rm"}, - Args: cobra.MinimumNArgs(1), - Short: "Remove a target from the source state and the destination directory", - Long: mustGetLongHelp("remove"), - Example: getExample("remove"), - PreRunE: config.ensureNoError, - RunE: config.runRemoveCmd, - PostRunE: config.autoCommitAndAutoPush, -} - -func init() { - rootCmd.AddCommand(removeCmd) - - persistentFlags := removeCmd.PersistentFlags() - persistentFlags.BoolVarP(&config.remove.force, "force", "f", false, "remove without prompting") - - markRemainingZshCompPositionalArgumentsAsFiles(removeCmd, 1) -} - -func (c *Config) runRemoveCmd(cmd *cobra.Command, args []string) error { - ts, err := c.getTargetState(nil) - if err != nil { - return err - } - entries, err := c.getEntries(ts, args) - if err != nil { - return nil - } - for _, entry := range entries { - destDirPath := filepath.Join(c.DestDir, entry.TargetName()) - sourceDirPath := filepath.Join(c.SourceDir, entry.SourceName()) - if !c.remove.force { - choice, err := c.prompt(fmt.Sprintf("Remove %s and %s", destDirPath, sourceDirPath), "ynqa") - if err != nil { - return err - } - switch choice { - case 'y': - case 'n': - continue - case 'q': - return nil - case 'a': - c.remove.force = true - } - } - if err := c.mutator.RemoveAll(destDirPath); err != nil && !os.IsNotExist(err) { - return err - } - if err := c.mutator.RemoveAll(sourceDirPath); err != nil && !os.IsNotExist(err) { - return err - } - } - return nil -} diff --git a/chezmoi2/cmd/removecmd.go b/cmd/removecmd.go similarity index 96% rename from chezmoi2/cmd/removecmd.go rename to cmd/removecmd.go index 22453effe1c..c07cbcffa33 100644 --- a/chezmoi2/cmd/removecmd.go +++ b/cmd/removecmd.go @@ -6,7 +6,7 @@ import ( "github.com/spf13/cobra" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoi" ) func (c *Config) newRemoveCmd() *cobra.Command { diff --git a/cmd/root.go b/cmd/root.go deleted file mode 100644 index 2640a0d8744..00000000000 --- a/cmd/root.go +++ /dev/null @@ -1,244 +0,0 @@ -package cmd - -import ( - "errors" - "fmt" - "os" - "path/filepath" - "runtime" - "strconv" - "strings" - - "github.com/coreos/go-semver/semver" - "github.com/spf13/cobra" - "github.com/spf13/viper" - vfs "github.com/twpayne/go-vfs" - xdg "github.com/twpayne/go-xdg/v3" - "golang.org/x/term" - - "github.com/twpayne/chezmoi/internal/chezmoi" -) - -var config = newConfig() - -// Version information. -var ( - VersionStr string - Commit string - Date string - BuiltBy string - Version *semver.Version -) - -var rootCmd = &cobra.Command{ - Use: "chezmoi", - Short: "Manage your dotfiles across multiple diverse machines, securely", - SilenceErrors: true, - SilenceUsage: true, - PersistentPreRunE: config.persistentPreRunRootE, -} - -var ( - errExitFailure = errors.New("") - initErr error -) - -func init() { - homeDir, err := os.UserHomeDir() - if err != nil { - initErr = err - return - } - - config.bds, err = xdg.NewBaseDirectorySpecification() - if err != nil { - initErr = err - return - } - - persistentFlags := rootCmd.PersistentFlags() - - persistentFlags.StringVarP(&config.configFile, "config", "c", getDefaultConfigFile(config.bds), "config file") - panicOnError(rootCmd.MarkPersistentFlagFilename("config")) - - persistentFlags.BoolVarP(&config.DryRun, "dry-run", "n", false, "dry run") - panicOnError(viper.BindPFlag("dry-run", persistentFlags.Lookup("dry-run"))) - - persistentFlags.BoolVar(&config.Follow, "follow", false, "follow symlinks") - panicOnError(viper.BindPFlag("follow", persistentFlags.Lookup("follow"))) - - persistentFlags.BoolVar(&config.Remove, "remove", false, "remove targets") - panicOnError(viper.BindPFlag("remove", persistentFlags.Lookup("remove"))) - - persistentFlags.StringVarP(&config.SourceDir, "source", "S", getDefaultSourceDir(config.bds), "source directory") - panicOnError(viper.BindPFlag("source", persistentFlags.Lookup("source"))) - panicOnError(rootCmd.MarkPersistentFlagDirname("source")) - - persistentFlags.StringVarP(&config.DestDir, "destination", "D", homeDir, "destination directory") - panicOnError(viper.BindPFlag("destination", persistentFlags.Lookup("destination"))) - panicOnError(rootCmd.MarkPersistentFlagDirname("destination")) - - persistentFlags.BoolVarP(&config.Verbose, "verbose", "v", false, "verbose") - panicOnError(viper.BindPFlag("verbose", persistentFlags.Lookup("verbose"))) - - persistentFlags.StringVar(&config.Color, "color", "auto", "colorize diffs") - panicOnError(viper.BindPFlag("color", persistentFlags.Lookup("color"))) - - persistentFlags.BoolVar(&config.Debug, "debug", false, "write debug logs") - panicOnError(viper.BindPFlag("debug", persistentFlags.Lookup("debug"))) - - cobra.OnInitialize(func() { - _, err := os.Stat(config.configFile) - switch { - case err == nil: - viper.SetConfigFile(config.configFile) - config.err = viper.ReadInConfig() - if config.err == nil { - config.err = viper.Unmarshal(&config) - } - if config.err == nil { - config.err = config.validateData() - } - if config.err != nil { - rootCmd.Printf("warning: %s: %v\n", config.configFile, config.err) - } - if config.GPGRecipient != "" { - rootCmd.Printf("" + - "warning: your config file uses gpgRecipient which will be deprecated in v2\n" + - "warning: to disable this warning, set gpg.recipient in your config file instead\n", - ) - } - if config.SourceVCS.Command != "" && !config.SourceVCS.NotGit && !strings.Contains(filepath.Base(config.SourceVCS.Command), "git") { - rootCmd.Printf("" + - "warning: it looks like you are using a version control system that is not git which will be deprecated in v2\n" + - "warning: please report this at https://github.com/twpayne/chezmoi/issues/459\n" + - "warning: to disable this warning, set sourceVCS.notGit = true in your config file\n", - ) - } - case os.IsNotExist(err): - default: - initErr = err - } - }) -} - -// Execute executes the root command. -func Execute() error { - if initErr != nil { - return initErr - } - - var versionComponents []string - if VersionStr != "" { - var err error - Version, err = semver.NewVersion(strings.TrimPrefix(VersionStr, "v")) - if err != nil { - return err - } - versionComponents = append(versionComponents, VersionStr) - } else { - versionComponents = append(versionComponents, "dev") - } - if Commit != "" { - versionComponents = append(versionComponents, "commit "+Commit) - } - if Date != "" { - versionComponents = append(versionComponents, "built at "+Date) - } - if BuiltBy != "" { - versionComponents = append(versionComponents, "built by "+BuiltBy) - } - rootCmd.Version = strings.Join(versionComponents, ", ") - - return rootCmd.Execute() -} - -func (c *Config) persistentPreRunRootE(cmd *cobra.Command, args []string) error { - if colored, err := strconv.ParseBool(c.Color); err == nil { - c.colored = colored - } else { - switch c.Color { - case "on": - c.colored = true - case "off": - c.colored = false - case "auto": - if _, ok := os.LookupEnv("NO_COLOR"); ok { - c.colored = false - } else if stdout, ok := c.Stdout.(*os.File); ok { - c.colored = term.IsTerminal(int(stdout.Fd())) - } else { - c.colored = false - } - default: - return fmt.Errorf("invalid --color value: %s", c.Color) - } - } - - if c.colored { - if err := enableVirtualTerminalProcessingOnWindows(c.Stdout); err != nil { - return err - } - } - - c.fs = vfs.OSFS - c.mutator = chezmoi.NewFSMutator(config.fs) - if c.DryRun { - c.mutator = chezmoi.NullMutator{} - } - if c.Debug { - c.mutator = chezmoi.NewDebugMutator(c.mutator) - } - if c.Verbose { - c.mutator = chezmoi.NewVerboseMutator(c.Stdout, c.mutator, c.colored, c.maxDiffDataSize) - } - - if runtime.GOOS == "linux" && c.bds.RuntimeDir != "" { - // Snap sets the $XDG_RUNTIME_DIR environment variable to - // /run/user/$uid/snap.$snap_name, but does not create this directory. - // Consequently, any spawned processes that need $XDG_DATA_DIR will - // fail. As a work-around, create the directory if it does not exist. - // See - // https://forum.snapcraft.io/t/wayland-dconf-and-xdg-runtime-dir/186/13. - if err := os.MkdirAll(c.bds.RuntimeDir, 0o700); err != nil { - return err - } - } - - return nil -} - -func getExample(command string) string { - return helps[command].example -} - -func markRemainingZshCompPositionalArgumentsAsFiles(cmd *cobra.Command, from int) { - // As far as I can tell, there is no way to mark all remaining positional - // arguments as files. Marking the first eight positional arguments as files - // should be enough for everybody. - // FIXME mark all remaining positional arguments as files - for i := 0; i < 8; i++ { - panicOnError(cmd.MarkZshCompPositionalArgumentFile(from + i)) - } -} - -func mustGetLongHelp(command string) string { - help, ok := helps[command] - if !ok { - panic(fmt.Sprintf("no long help for %s", command)) - } - return help.long -} - -// parseBool is like strconv.ParseBool but also accepts on, ON, y, Y, yes, YES, -// n, N, no, NO, off, and OFF. -func parseBool(str string) (bool, error) { - switch strings.ToLower(strings.TrimSpace(str)) { - case "n", "no", "off": - return false, nil - case "on", "y", "yes": - return true, nil - default: - return strconv.ParseBool(str) - } -} diff --git a/cmd/secret.go b/cmd/secret.go deleted file mode 100644 index fd1e5653d81..00000000000 --- a/cmd/secret.go +++ /dev/null @@ -1,15 +0,0 @@ -package cmd - -import "github.com/spf13/cobra" - -var secretCmd = &cobra.Command{ - Use: "secret", - Args: cobra.NoArgs, - Short: "Interact with a secret manager", - Long: mustGetLongHelp("secret"), - Example: getExample("secret"), -} - -func init() { - rootCmd.AddCommand(secretCmd) -} diff --git a/cmd/secretbitwarden.go b/cmd/secretbitwarden.go deleted file mode 100644 index 008690c197c..00000000000 --- a/cmd/secretbitwarden.go +++ /dev/null @@ -1,88 +0,0 @@ -package cmd - -import ( - "encoding/json" - "fmt" - "os" - "os/exec" - "strings" - - "github.com/spf13/cobra" - - "github.com/twpayne/chezmoi/internal/chezmoi" -) - -var bitwardenCmd = &cobra.Command{ - Use: "bitwarden [args...]", - Short: "Execute the Bitwarden CLI (bw)", - PreRunE: config.ensureNoError, - RunE: config.runBitwardenCmd, -} - -type bitwardenCmdConfig struct { - Command string -} - -var bitwardenOutputCache = make(map[string][]byte) - -func init() { - config.Bitwarden.Command = "bw" - config.addTemplateFunc("bitwarden", config.bitwardenFunc) - config.addTemplateFunc("bitwardenAttachment", config.bitwardenAttachmentFunc) - config.addTemplateFunc("bitwardenFields", config.bitwardenFieldsFunc) - - secretCmd.AddCommand(bitwardenCmd) -} - -func (c *Config) runBitwardenCmd(cmd *cobra.Command, args []string) error { - return c.run("", c.Bitwarden.Command, args...) -} - -func (c *Config) bitwardenOutput(args []string) []byte { - key := strings.Join(args, "\x00") - if output, ok := bitwardenOutputCache[key]; ok { - return output - } - - //nolint:gosec - cmd := exec.Command(c.Bitwarden.Command, args...) - cmd.Stdin = os.Stdin - cmd.Stderr = os.Stderr - output, err := c.mutator.IdempotentCmdOutput(cmd) - if err != nil { - panic(fmt.Errorf("%s %s: %w\n%s", c.Bitwarden.Command, chezmoi.ShellQuoteArgs(args), err, output)) - } - - bitwardenOutputCache[key] = output - return output -} - -func (c *Config) bitwardenFunc(args ...string) map[string]interface{} { - output := c.bitwardenOutput(append([]string{"get"}, args...)) - var data map[string]interface{} - if err := json.Unmarshal(output, &data); err != nil { - panic(fmt.Errorf("%s %s: %w\n%s", c.Bitwarden.Command, chezmoi.ShellQuoteArgs(args), err, output)) - } - return data -} - -func (c *Config) bitwardenFieldsFunc(args ...string) map[string]interface{} { - output := c.bitwardenOutput(append([]string{"get"}, args...)) - var data struct { - Fields []map[string]interface{} `json:"fields"` - } - if err := json.Unmarshal(output, &data); err != nil { - panic(fmt.Errorf("%s %s: %w\n%s", c.Bitwarden.Command, chezmoi.ShellQuoteArgs(args), err, output)) - } - result := make(map[string]interface{}) - for _, field := range data.Fields { - if name, ok := field["name"].(string); ok { - result[name] = field - } - } - return result -} - -func (c *Config) bitwardenAttachmentFunc(name, itemid string) string { - return string(c.bitwardenOutput([]string{"get", "attachment", name, "--itemid", itemid, "--raw"})) -} diff --git a/chezmoi2/cmd/secretcmd.go b/cmd/secretcmd.go similarity index 100% rename from chezmoi2/cmd/secretcmd.go rename to cmd/secretcmd.go diff --git a/cmd/secretgeneric.go b/cmd/secretgeneric.go deleted file mode 100644 index ac499dbf26b..00000000000 --- a/cmd/secretgeneric.go +++ /dev/null @@ -1,80 +0,0 @@ -package cmd - -import ( - "bytes" - "encoding/json" - "fmt" - "os" - "os/exec" - "strings" - - "github.com/spf13/cobra" - - "github.com/twpayne/chezmoi/internal/chezmoi" -) - -var genericSecretCmd = &cobra.Command{ - Use: "generic [args...]", - Short: "Execute a generic secret command", - PreRunE: config.ensureNoError, - RunE: config.runGenericSecretCmd, -} - -type genericSecretCmdConfig struct { - Command string -} - -var ( - secretCache = make(map[string]string) - secretJSONCache = make(map[string]interface{}) -) - -func init() { - config.addTemplateFunc("secret", config.secretFunc) - config.addTemplateFunc("secretJSON", config.secretJSONFunc) - - secretCmd.AddCommand(genericSecretCmd) -} - -func (c *Config) runGenericSecretCmd(cmd *cobra.Command, args []string) error { - return c.run("", c.GenericSecret.Command, args...) -} - -func (c *Config) secretFunc(args ...string) string { - key := strings.Join(args, "\x00") - if value, ok := secretCache[key]; ok { - return value - } - name := c.GenericSecret.Command - cmd := exec.Command(name, args...) - cmd.Stdin = os.Stdin - cmd.Stderr = os.Stderr - output, err := c.mutator.IdempotentCmdOutput(cmd) - if err != nil { - panic(fmt.Errorf("%s %s: %w\n%s", name, chezmoi.ShellQuoteArgs(args), err, output)) - } - value := string(bytes.TrimSpace(output)) - secretCache[key] = value - return value -} - -func (c *Config) secretJSONFunc(args ...string) interface{} { - key := strings.Join(args, "\x00") - if value, ok := secretJSONCache[key]; ok { - return value - } - name := c.GenericSecret.Command - cmd := exec.Command(name, args...) - cmd.Stdin = os.Stdin - cmd.Stderr = os.Stderr - output, err := c.mutator.IdempotentCmdOutput(cmd) - if err != nil { - panic(fmt.Errorf("%s %s: %w\n%s", name, chezmoi.ShellQuoteArgs(args), err, output)) - } - var value interface{} - if err := json.Unmarshal(output, &value); err != nil { - panic(fmt.Errorf("%s %s: %w\n%s", name, chezmoi.ShellQuoteArgs(args), err, output)) - } - secretJSONCache[key] = value - return value -} diff --git a/cmd/secretgeneric_posix_test.go b/cmd/secretgeneric_posix_test.go deleted file mode 100644 index 52d1513f14f..00000000000 --- a/cmd/secretgeneric_posix_test.go +++ /dev/null @@ -1,23 +0,0 @@ -// +build !windows - -package cmd - -import "github.com/twpayne/chezmoi/internal/chezmoi" - -func getSecretTestConfig() (*Config, []string) { - return newConfig( - withMutator(chezmoi.NullMutator{}), - withGenericSecretCmdConfig(genericSecretCmdConfig{ - Command: "date", - }), - ), []string{"+%Y-%M-%DT%H:%M:%SZ"} -} - -func getSecretJSONTestConfig() (*Config, []string) { - return newConfig( - withMutator(chezmoi.NullMutator{}), - withGenericSecretCmdConfig(genericSecretCmdConfig{ - Command: "date", - }), - ), []string{`+{"date":"%Y-%M-%DT%H:%M:%SZ"}`} -} diff --git a/cmd/secretgeneric_test.go b/cmd/secretgeneric_test.go deleted file mode 100644 index 19865741697..00000000000 --- a/cmd/secretgeneric_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package cmd - -import ( - "testing" - "time" - - "github.com/stretchr/testify/assert" -) - -func TestSecretFunc(t *testing.T) { - t.Parallel() - - c, args := getSecretTestConfig() - - var value interface{} - assert.NotPanics(t, func() { - value = c.secretFunc(args...) - }) - time.Sleep(1100 * time.Millisecond) - assert.Equal(t, value, c.secretFunc(args...)) -} - -func TestSecretJSONFunc(t *testing.T) { - t.Parallel() - - c, args := getSecretJSONTestConfig() - - var value interface{} - assert.NotPanics(t, func() { - value = c.secretJSONFunc(args...) - }) - time.Sleep(1100 * time.Millisecond) - assert.Equal(t, value, c.secretJSONFunc(args...)) -} diff --git a/cmd/secretgeneric_windows_test.go b/cmd/secretgeneric_windows_test.go deleted file mode 100644 index cd9064a5418..00000000000 --- a/cmd/secretgeneric_windows_test.go +++ /dev/null @@ -1,27 +0,0 @@ -// +build windows - -package cmd - -import "github.com/twpayne/chezmoi/internal/chezmoi" - -func getSecretTestConfig() (*Config, []string) { - // Windows doesn't (usually) have "date", but PowerShell is included with - // all versions of Windows v7 or newer. - return newConfig( - withMutator(chezmoi.NullMutator{}), - withGenericSecretCmdConfig(genericSecretCmdConfig{ - Command: "powershell.exe", - }), - ), - []string{"-NoProfile", "-NonInteractive", "-Command", "Get-Date"} -} - -func getSecretJSONTestConfig() (*Config, []string) { - return newConfig( - withMutator(chezmoi.NullMutator{}), - withGenericSecretCmdConfig(genericSecretCmdConfig{ - Command: "powershell.exe", - }), - ), - []string{"-NoProfile", "-NonInteractive", "-Command", "Get-Date | ConvertTo-Json"} -} diff --git a/cmd/secretgopass.go b/cmd/secretgopass.go deleted file mode 100644 index 987e1fca0e4..00000000000 --- a/cmd/secretgopass.go +++ /dev/null @@ -1,97 +0,0 @@ -package cmd - -import ( - "bytes" - "fmt" - "os" - "os/exec" - "regexp" - "sync" - - "github.com/coreos/go-semver/semver" - "github.com/spf13/cobra" -) - -var ( - // chezmoi uses gopass show --password which was added in - // https://github.com/gopasspw/gopass/commit/8fa13d84e3656cfc4ee6717f5f485c9e471ad996 - // and the first tag containing that commit is v1.6.1. - gopassMinVersion = semver.Version{Major: 1, Minor: 6, Patch: 1} - gopassVersionArgs = []string{"--version"} - gopassVersionRegexp = regexp.MustCompile(`gopass\s+(\d+\.\d+\.\d+)`) -) - -var gopassCmd = &cobra.Command{ - Use: "gopass [args...]", - Short: "Execute the gopass CLI", - PreRunE: config.ensureNoError, - RunE: config.runSecretGopassCmd, -} - -type gopassCmdConfig struct { - Command string - versionCheckOnce sync.Once -} - -var gopassCache = make(map[string]string) - -func init() { - secretCmd.AddCommand(gopassCmd) - - config.Gopass.Command = "gopass" - config.addTemplateFunc("gopass", config.gopassFunc) -} - -func (c *Config) runSecretGopassCmd(cmd *cobra.Command, args []string) error { - return c.run("", c.Gopass.Command, args...) -} - -func (c *Config) gopassOutput(args ...string) ([]byte, error) { - name := c.Gopass.Command - cmd := exec.Command(name, args...) - cmd.Stdin = os.Stdin - cmd.Stderr = os.Stderr - output, err := c.mutator.IdempotentCmdOutput(cmd) - if err != nil { - return nil, err - } - return output, nil -} - -func (c *Config) gopassFunc(id string) string { - c.Gopass.versionCheckOnce.Do(func() { - panicOnError(c.gopassVersionCheck()) - }) - if s, ok := gopassCache[id]; ok { - return s - } - output, err := c.gopassOutput("show", "--password", id) - panicOnError(err) - var password string - if index := bytes.IndexByte(output, '\n'); index != -1 { - password = string(output[:index]) - } else { - password = string(output) - } - gopassCache[id] = password - return gopassCache[id] -} - -func (c *Config) gopassVersionCheck() error { - output, err := c.gopassOutput(gopassVersionArgs...) - if err != nil { - return err - } - m := gopassVersionRegexp.FindSubmatch(output) - if m == nil { - return fmt.Errorf("could not extract version from %q", output) - } - version, err := semver.NewVersion(string(m[1])) - if err != nil { - return err - } - if version.LessThan(gopassMinVersion) { - return fmt.Errorf("version %s found, need version %s or later", version, gopassMinVersion) - } - return nil -} diff --git a/cmd/secretkeepassxc.go b/cmd/secretkeepassxc.go deleted file mode 100644 index d71ea617b9c..00000000000 --- a/cmd/secretkeepassxc.go +++ /dev/null @@ -1,193 +0,0 @@ -package cmd - -import ( - "bufio" - "bytes" - "errors" - "fmt" - "io" - "os" - "os/exec" - "regexp" - "strings" - - "github.com/coreos/go-semver/semver" - "github.com/spf13/cobra" - "golang.org/x/term" - - "github.com/twpayne/chezmoi/internal/chezmoi" -) - -var keePassXCCmd = &cobra.Command{ - Use: "keepassxc [args...]", - Short: "Execute the KeePassXC CLI (keepassxc-cli)", - PreRunE: config.ensureNoError, - RunE: config.runKeePassXCCmd, -} - -type keePassXCCmdConfig struct { - Command string - Database string - Args []string -} - -type keePassXCAttributeCacheKey struct { - entry string - attribute string -} - -var ( - keePassXCVersion *semver.Version - keePassXCCache = make(map[string]map[string]string) - keePassXCAttributeCache = make(map[keePassXCAttributeCacheKey]string) - keePassXCPairRegexp = regexp.MustCompile(`^([^:]+):\s*(.*)$`) - keePassXCPassword string - keePassXCNeedShowProtectedArgVersion = semver.Version{Major: 2, Minor: 5, Patch: 1} -) - -func init() { - config.KeePassXC.Command = "keepassxc-cli" - config.addTemplateFunc("keepassxc", config.keePassXCFunc) - config.addTemplateFunc("keepassxcAttribute", config.keePassXCAttributeFunc) - - secretCmd.AddCommand(keePassXCCmd) -} - -func (c *Config) runKeePassXCCmd(cmd *cobra.Command, args []string) error { - return c.run("", c.KeePassXC.Command, args...) -} - -func (c *Config) getKeePassXCVersion() *semver.Version { - if keePassXCVersion != nil { - return keePassXCVersion - } - name := c.KeePassXC.Command - args := []string{"--version"} - cmd := exec.Command(name, args...) - output, err := c.mutator.IdempotentCmdOutput(cmd) - if err != nil { - panic(fmt.Errorf("%s %s: %w", name, chezmoi.ShellQuoteArgs(args), err)) - } - keePassXCVersion, err = semver.NewVersion(string(bytes.TrimSpace(output))) - if err != nil { - panic(fmt.Errorf("cannot parse version %q: %w", output, err)) - } - return keePassXCVersion -} - -func (c *Config) keePassXCFunc(entry string) map[string]string { - if data, ok := keePassXCCache[entry]; ok { - return data - } - if c.KeePassXC.Database == "" { - panic(errors.New("keepassxc.database not set")) - } - name := c.KeePassXC.Command - args := []string{"show"} - if c.getKeePassXCVersion().Compare(keePassXCNeedShowProtectedArgVersion) >= 0 { - args = append(args, "--show-protected") - } - args = append(args, c.KeePassXC.Args...) - args = append(args, c.KeePassXC.Database, entry) - output, err := c.runKeePassXCCLICommand(name, args) - if err != nil { - panic(fmt.Errorf("%s %s: %w", name, chezmoi.ShellQuoteArgs(args), err)) - } - data, err := parseKeyPassXCOutput(output) - if err != nil { - panic(fmt.Errorf("%s %s: %w", name, chezmoi.ShellQuoteArgs(args), err)) - } - keePassXCCache[entry] = data - return data -} - -func (c *Config) keePassXCAttributeFunc(entry, attribute string) string { - key := keePassXCAttributeCacheKey{ - entry: entry, - attribute: attribute, - } - if data, ok := keePassXCAttributeCache[key]; ok { - return data - } - if c.KeePassXC.Database == "" { - panic(errors.New("keepassxc.database not set")) - } - name := c.KeePassXC.Command - args := []string{"show", "--attributes", attribute, "--quiet"} - if c.getKeePassXCVersion().Compare(keePassXCNeedShowProtectedArgVersion) >= 0 { - args = append(args, "--show-protected") - } - args = append(args, c.KeePassXC.Args...) - args = append(args, c.KeePassXC.Database, entry) - output, err := c.runKeePassXCCLICommand(name, args) - if err != nil { - panic(fmt.Errorf("%s %s: %w", name, chezmoi.ShellQuoteArgs(args), err)) - } - outputStr := strings.TrimSpace(string(output)) - keePassXCAttributeCache[key] = outputStr - return outputStr -} - -func readPassword(prompt string) (pw []byte, err error) { - if fd := int(os.Stdin.Fd()); term.IsTerminal(fd) { - fmt.Print(prompt) - pw, err = term.ReadPassword(fd) - fmt.Println() - return - } - - var b [1]byte - for { - n, err := os.Stdin.Read(b[:]) - // term.ReadPassword discards any '\r', so do the same. - if n > 0 && b[0] != '\r' { - if b[0] == '\n' { - return pw, nil - } - pw = append(pw, b[0]) - // limit size, so that a wrong input won't fill up the memory. - if len(pw) > 1024 { - err = errors.New("password too long") - } - } - if err != nil { - // term.ReadPassword accepts EOF-terminated passwords if non-empty, - // so do the same. - if errors.Is(err, io.EOF) && len(pw) > 0 { - err = nil - } - return pw, err - } - } -} - -func (c *Config) runKeePassXCCLICommand(name string, args []string) ([]byte, error) { - if keePassXCPassword == "" { - password, err := readPassword(fmt.Sprintf("Insert password to unlock %s: ", c.KeePassXC.Database)) - fmt.Println() - if err != nil { - return nil, err - } - keePassXCPassword = string(password) - } - cmd := exec.Command(name, args...) - cmd.Stdin = bytes.NewBufferString(keePassXCPassword + "\n") - cmd.Stderr = c.Stderr - return c.mutator.IdempotentCmdOutput(cmd) -} - -func parseKeyPassXCOutput(output []byte) (map[string]string, error) { - data := make(map[string]string) - s := bufio.NewScanner(bytes.NewReader(output)) - for i := 0; s.Scan(); i++ { - if i == 0 { - continue - } - match := keePassXCPairRegexp.FindStringSubmatch(s.Text()) - if match == nil { - return nil, fmt.Errorf("cannot parse %q", s.Text()) - } - data[match[1]] = match[2] - } - return data, s.Err() -} diff --git a/cmd/secretkeyring.go b/cmd/secretkeyring.go deleted file mode 100644 index 2fe9b83defa..00000000000 --- a/cmd/secretkeyring.go +++ /dev/null @@ -1,57 +0,0 @@ -package cmd - -import ( - "fmt" - - "github.com/spf13/cobra" - keyring "github.com/zalando/go-keyring" -) - -var keyringCmd = &cobra.Command{ - Use: "keyring", - Args: cobra.NoArgs, - Short: "Interact with keyring", -} - -type keyringCmdConfig struct { - service string - user string - value string -} - -type keyringKey struct { - service string - user string -} - -var keyringCache = make(map[keyringKey]string) - -func init() { - secretCmd.AddCommand(keyringCmd) - - persistentFlags := keyringCmd.PersistentFlags() - - persistentFlags.StringVar(&config.keyring.service, "service", "", "service") - panicOnError(keyringCmd.MarkPersistentFlagRequired("service")) - - persistentFlags.StringVar(&config.keyring.user, "user", "", "user") - panicOnError(keyringCmd.MarkPersistentFlagRequired("user")) - - config.addTemplateFunc("keyring", config.keyringFunc) -} - -func (*Config) keyringFunc(service, user string) string { - key := keyringKey{ - service: service, - user: user, - } - if password, ok := keyringCache[key]; ok { - return password - } - password, err := keyring.Get(service, user) - if err != nil { - panic(fmt.Errorf("%q %q: %w", service, user, err)) - } - keyringCache[key] = password - return password -} diff --git a/chezmoi2/cmd/secretkeyringcmd.go b/cmd/secretkeyringcmd.go similarity index 100% rename from chezmoi2/cmd/secretkeyringcmd.go rename to cmd/secretkeyringcmd.go diff --git a/cmd/secretkeyringget.go b/cmd/secretkeyringget.go deleted file mode 100644 index d50bc8ce25e..00000000000 --- a/cmd/secretkeyringget.go +++ /dev/null @@ -1,29 +0,0 @@ -package cmd - -import ( - "fmt" - - "github.com/spf13/cobra" - keyring "github.com/zalando/go-keyring" -) - -var keyringGetCmd = &cobra.Command{ - Use: "get", - Args: cobra.NoArgs, - Short: "Get a value from keyring", - PreRunE: config.ensureNoError, - RunE: config.runKeyringGetCmd, -} - -func init() { - keyringCmd.AddCommand(keyringGetCmd) -} - -func (c *Config) runKeyringGetCmd(cmd *cobra.Command, args []string) error { - value, err := keyring.Get(c.keyring.service, c.keyring.user) - if err != nil { - return err - } - fmt.Println(value) - return nil -} diff --git a/cmd/secretkeyringset.go b/cmd/secretkeyringset.go deleted file mode 100644 index 8157b137971..00000000000 --- a/cmd/secretkeyringset.go +++ /dev/null @@ -1,38 +0,0 @@ -package cmd - -import ( - "fmt" - "os" - - "github.com/spf13/cobra" - keyring "github.com/zalando/go-keyring" - "golang.org/x/term" -) - -var keyringSetCmd = &cobra.Command{ - Use: "set", - Args: cobra.NoArgs, - Short: "Set a value in keyring", - PreRunE: config.ensureNoError, - RunE: config.runKeyringSetCmd, -} - -func init() { - keyringCmd.AddCommand(keyringSetCmd) - - persistentFlags := keyringSetCmd.PersistentFlags() - persistentFlags.StringVar(&config.keyring.value, "value", "", "value") -} - -func (c *Config) runKeyringSetCmd(cmd *cobra.Command, args []string) error { - valueStr := c.keyring.value - if valueStr == "" { - fmt.Print("Value: ") - value, err := term.ReadPassword(int(os.Stdin.Fd())) - if err != nil { - return err - } - valueStr = string(value) - } - return keyring.Set(c.keyring.service, c.keyring.user, valueStr) -} diff --git a/cmd/secretlastpass.go b/cmd/secretlastpass.go deleted file mode 100644 index ccd60fc797a..00000000000 --- a/cmd/secretlastpass.go +++ /dev/null @@ -1,133 +0,0 @@ -package cmd - -import ( - "bufio" - "bytes" - "encoding/json" - "fmt" - "os" - "os/exec" - "regexp" - "strings" - "sync" - "unicode" - - "github.com/coreos/go-semver/semver" - "github.com/spf13/cobra" -) - -var lastpassCmd = &cobra.Command{ - Use: "lastpass [args...]", - Short: "Execute the LastPass CLI (lpass)", - PreRunE: config.ensureNoError, - RunE: config.runLastpassCmd, -} - -var ( - // chezmoi uses lpass show --json which was added in - // https://github.com/lastpass/lastpass-cli/commit/e5a22e2eeef31ab6c54595616e0f57ca0a1c162d - // and the first tag containing that commit is v1.3.0~6. - lastpassMinVersion = semver.Version{Major: 1, Minor: 3, Patch: 0} - lastpassParseNoteRegexp = regexp.MustCompile(`\A([ A-Za-z]*):(.*)\z`) - lastpassVersionArgs = []string{"--version"} - lastpassVersionRegexp = regexp.MustCompile(`^LastPass CLI v(\d+\.\d+\.\d+)`) -) - -type lastpassCmdConfig struct { - Command string - versionCheckOnce sync.Once -} - -var lastPassCache = make(map[string][]map[string]interface{}) - -func init() { - config.Lastpass.Command = "lpass" - config.addTemplateFunc("lastpass", config.lastpassFunc) - config.addTemplateFunc("lastpassRaw", config.lastpassRawFunc) - - secretCmd.AddCommand(lastpassCmd) -} - -func (c *Config) runLastpassCmd(cmd *cobra.Command, args []string) error { - return c.run("", c.Lastpass.Command, args...) -} - -func (c *Config) lastpassOutput(args ...string) ([]byte, error) { - name := c.Lastpass.Command - cmd := exec.Command(name, args...) - cmd.Stdin = os.Stdin - cmd.Stderr = os.Stderr - output, err := c.mutator.IdempotentCmdOutput(cmd) - if err != nil { - return nil, err - } - return output, nil -} - -func (c *Config) lastpassRawFunc(id string) []map[string]interface{} { - c.Lastpass.versionCheckOnce.Do(func() { - panicOnError(c.lastpassVersionCheck()) - }) - if data, ok := lastPassCache[id]; ok { - return data - } - output, err := c.lastpassOutput("show", "--json", id) - panicOnError(err) - var data []map[string]interface{} - if err := json.Unmarshal(output, &data); err != nil { - panic(fmt.Errorf("parse error: %w\n%q", err, output)) - } - lastPassCache[id] = data - return data -} - -func (c *Config) lastpassFunc(id string) []map[string]interface{} { - data := c.lastpassRawFunc(id) - for _, d := range data { - if note, ok := d["note"].(string); ok { - d["note"] = lastpassParseNote(note) - } - } - return data -} - -func (c *Config) lastpassVersionCheck() error { - output, err := c.lastpassOutput(lastpassVersionArgs...) - if err != nil { - return err - } - m := lastpassVersionRegexp.FindSubmatch(output) - if m == nil { - return fmt.Errorf("could not extract version from %q", output) - } - version, err := semver.NewVersion(string(m[1])) - if err != nil { - return err - } - if version.LessThan(lastpassMinVersion) { - return fmt.Errorf("version %s found, need version %s or later", version, lastpassMinVersion) - } - return nil -} - -func lastpassParseNote(note string) map[string]string { - result := make(map[string]string) - s := bufio.NewScanner(bytes.NewBufferString(note)) - key := "" - for s.Scan() { - if m := lastpassParseNoteRegexp.FindStringSubmatch(s.Text()); m != nil { - keyComponents := strings.Split(m[1], " ") - firstComponentRunes := []rune(keyComponents[0]) - firstComponentRunes[0] = unicode.ToLower(firstComponentRunes[0]) - keyComponents[0] = string(firstComponentRunes) - key = strings.Join(keyComponents, "") - result[key] = m[2] + "\n" - } else { - result[key] += s.Text() + "\n" - } - } - if err := s.Err(); err != nil { - panic(fmt.Errorf("lastpassParseNote: %w", err)) - } - return result -} diff --git a/cmd/secretlastpass_test.go b/cmd/secretlastpass_test.go deleted file mode 100644 index a5167cf815f..00000000000 --- a/cmd/secretlastpass_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package cmd - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func Test_lastpassParseNote(t *testing.T) { - for _, tc := range []struct { - note string - want map[string]string - }{ - { - note: "Foo:bar\n", - want: map[string]string{ - "foo": "bar\n", - }, - }, - { - note: "Foo:bar\nbaz\n", - want: map[string]string{ - "foo": "bar\nbaz\n", - }, - }, - { - note: "NoteType:SSH Key\nLanguage:en-US\nBit Strength:2048\nFormat:RSA\nPassphrase:Passphrase\nPrivate Key:-----BEGIN OPENSSH PRIVATE KEY-----\n-----END OPENSSH PRIVATE KEY-----\nPublic Key:ssh-rsa public-key user@host\nHostname:Hostname\nDate:Date\nNotes:", - want: map[string]string{ - "noteType": "SSH Key\n", - "language": "en-US\n", - "bitStrength": "2048\n", - "format": "RSA\n", - "passphrase": "Passphrase\n", - "privateKey": "-----BEGIN OPENSSH PRIVATE KEY-----\n-----END OPENSSH PRIVATE KEY-----\n", - "publicKey": "ssh-rsa public-key user@host\n", - "hostname": "Hostname\n", - "date": "Date\n", - "notes": "\n", - }, - }, - } { - assert.Equal(t, tc.want, lastpassParseNote(tc.note)) - } -} diff --git a/cmd/secretonepassword.go b/cmd/secretonepassword.go deleted file mode 100644 index 0511e33d378..00000000000 --- a/cmd/secretonepassword.go +++ /dev/null @@ -1,147 +0,0 @@ -package cmd - -import ( - "bytes" - "encoding/json" - "fmt" - "os" - "os/exec" - "strings" - - "github.com/coreos/go-semver/semver" - "github.com/spf13/cobra" - - "github.com/twpayne/chezmoi/internal/chezmoi" -) - -var onepasswordCmd = &cobra.Command{ - Use: "onepassword [args...]", - Short: "Execute the 1Password CLI (op)", - PreRunE: config.ensureNoError, - RunE: config.runOnepasswordCmd, -} - -type onepasswordCmdConfig struct { - Command string - Cache bool -} - -var ( - onepasswordVersion *semver.Version - onepasswordOutputCache = make(map[string][]byte) - onepasswordCacheArgVersion = semver.Version{Major: 1, Minor: 8, Patch: 0} -) - -func init() { - config.Onepassword.Command = "op" - config.Onepassword.Cache = true - config.addTemplateFunc("onepassword", config.onepasswordFunc) - config.addTemplateFunc("onepasswordDocument", config.onepasswordDocumentFunc) - config.addTemplateFunc("onepasswordDetailsFields", config.onepasswordDetailsFieldsFunc) - - secretCmd.AddCommand(onepasswordCmd) -} - -func (c *Config) getOnepasswordVersion() *semver.Version { - if onepasswordVersion != nil { - return onepasswordVersion - } - name := c.Onepassword.Command - args := []string{"--version"} - cmd := exec.Command(name, args...) - output, err := c.mutator.IdempotentCmdOutput(cmd) - if err != nil { - panic(fmt.Errorf("%s %s: %w", name, chezmoi.ShellQuoteArgs(args), err)) - } - onepasswordVersion, err = semver.NewVersion(string(bytes.TrimSpace(output))) - if err != nil { - panic(fmt.Errorf("cannot parse version %q: %w", output, err)) - } - return onepasswordVersion -} - -func (c *Config) runOnepasswordCmd(cmd *cobra.Command, args []string) error { - return c.run("", c.Onepassword.Command, args...) -} - -func (c *Config) onepasswordOutput(args []string) []byte { - if c.Onepassword.Cache && c.getOnepasswordVersion().Compare(onepasswordCacheArgVersion) >= 0 { - args = append(args, "--cache") - } - - key := strings.Join(args, "\x00") - if output, ok := onepasswordOutputCache[key]; ok { - return output - } - - name := c.Onepassword.Command - cmd := exec.Command(name, args...) - cmd.Stdin = os.Stdin - cmd.Stderr = os.Stderr - output, err := c.mutator.IdempotentCmdOutput(cmd) - if err != nil { - panic(fmt.Errorf("%s %s: %w\n%s", name, chezmoi.ShellQuoteArgs(args), err, output)) - } - - onepasswordOutputCache[key] = output - return output -} - -func (c *Config) onepasswordFunc(args ...string) map[string]interface{} { - key, vault := onepasswordGetKeyAndVault(args) - onepasswordArgs := []string{"get", "item", key} - if vault != "" { - onepasswordArgs = append(onepasswordArgs, "--vault", vault) - } - output := c.onepasswordOutput(onepasswordArgs) - var data map[string]interface{} - if err := json.Unmarshal(output, &data); err != nil { - panic(fmt.Errorf("%s %s: %w\n%s", c.Onepassword.Command, chezmoi.ShellQuoteArgs(onepasswordArgs), err, output)) - } - return data -} - -func (c *Config) onepasswordDocumentFunc(args ...string) string { - key, vault := onepasswordGetKeyAndVault(args) - onepasswordArgs := []string{"get", "document", key} - if vault != "" { - onepasswordArgs = append(onepasswordArgs, "--vault", vault) - } - output := c.onepasswordOutput(onepasswordArgs) - return string(output) -} - -func (c *Config) onepasswordDetailsFieldsFunc(args ...string) map[string]interface{} { - key, vault := onepasswordGetKeyAndVault(args) - onepasswordArgs := []string{"get", "item", key} - if vault != "" { - onepasswordArgs = append(onepasswordArgs, "--vault", vault) - } - output := c.onepasswordOutput(onepasswordArgs) - var data struct { - Details struct { - Fields []map[string]interface{} `json:"fields"` - } `json:"details"` - } - if err := json.Unmarshal(output, &data); err != nil { - panic(fmt.Errorf("%s %s: %w\n%s", c.Onepassword.Command, chezmoi.ShellQuoteArgs(onepasswordArgs), err, output)) - } - result := make(map[string]interface{}) - for _, field := range data.Details.Fields { - if designation, ok := field["designation"].(string); ok { - result[designation] = field - } - } - return result -} - -func onepasswordGetKeyAndVault(args []string) (string, string) { - switch len(args) { - case 1: - return args[0], "" - case 2: - return args[0], args[1] - default: - panic(fmt.Sprintf("expected 1 or 2 arguments, got %d", len(args))) - } -} diff --git a/cmd/secretpass.go b/cmd/secretpass.go deleted file mode 100644 index f762b5d6be6..00000000000 --- a/cmd/secretpass.go +++ /dev/null @@ -1,59 +0,0 @@ -package cmd - -import ( - "bytes" - "fmt" - "os" - "os/exec" - - "github.com/spf13/cobra" - - "github.com/twpayne/chezmoi/internal/chezmoi" -) - -var passCmd = &cobra.Command{ - Use: "pass [args...]", - Short: "Execute the pass CLI", - PreRunE: config.ensureNoError, - RunE: config.runSecretPassCmd, -} - -type passCmdConfig struct { - Command string -} - -var passCache = make(map[string]string) - -func init() { - secretCmd.AddCommand(passCmd) - - config.Pass.Command = "pass" - config.addTemplateFunc("pass", config.passFunc) -} - -func (c *Config) runSecretPassCmd(cmd *cobra.Command, args []string) error { - return c.run("", c.Pass.Command, args...) -} - -func (c *Config) passFunc(id string) string { - if s, ok := passCache[id]; ok { - return s - } - name := c.Pass.Command - args := []string{"show", id} - cmd := exec.Command(name, args...) - cmd.Stdin = os.Stdin - cmd.Stderr = os.Stderr - output, err := c.mutator.IdempotentCmdOutput(cmd) - if err != nil { - panic(fmt.Errorf("%s %s: %w", name, chezmoi.ShellQuoteArgs(args), err)) - } - var password string - if index := bytes.IndexByte(output, '\n'); index != -1 { - password = string(output[:index]) - } else { - password = string(output) - } - passCache[id] = password - return passCache[id] -} diff --git a/chezmoi2/cmd/secrettemplatefuncs.go b/cmd/secrettemplatefuncs.go similarity index 96% rename from chezmoi2/cmd/secrettemplatefuncs.go rename to cmd/secrettemplatefuncs.go index 0edb04516cc..51ce05e2911 100644 --- a/chezmoi2/cmd/secrettemplatefuncs.go +++ b/cmd/secrettemplatefuncs.go @@ -7,7 +7,7 @@ import ( "os/exec" "strings" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoi" ) type secretConfig struct { diff --git a/cmd/secretvault.go b/cmd/secretvault.go deleted file mode 100644 index adf11700568..00000000000 --- a/cmd/secretvault.go +++ /dev/null @@ -1,57 +0,0 @@ -package cmd - -import ( - "encoding/json" - "fmt" - "os" - "os/exec" - - "github.com/spf13/cobra" - - "github.com/twpayne/chezmoi/internal/chezmoi" -) - -var vaultCmd = &cobra.Command{ - Use: "vault [args...]", - Short: "Execute the Hashicorp Vault CLI (vault)", - PreRunE: config.ensureNoError, - RunE: config.runVaultCmd, -} - -type vaultCmdConfig struct { - Command string -} - -var vaultCache = make(map[string]interface{}) - -func init() { - config.Vault.Command = "vault" - config.addTemplateFunc("vault", config.vaultFunc) - - secretCmd.AddCommand(vaultCmd) -} - -func (c *Config) runVaultCmd(cmd *cobra.Command, args []string) error { - return c.run("", c.Vault.Command, args...) -} - -func (c *Config) vaultFunc(key string) interface{} { - if data, ok := vaultCache[key]; ok { - return data - } - name := c.Vault.Command - args := []string{"kv", "get", "-format=json", key} - cmd := exec.Command(name, args...) - cmd.Stdin = os.Stdin - cmd.Stderr = os.Stderr - output, err := c.mutator.IdempotentCmdOutput(cmd) - if err != nil { - panic(fmt.Errorf("%s %s: %w\n%s", name, chezmoi.ShellQuoteArgs(args), err, output)) - } - var data interface{} - if err := json.Unmarshal(output, &data); err != nil { - panic(fmt.Errorf("%s %s: %w\n%s", name, chezmoi.ShellQuoteArgs(args), err, output)) - } - vaultCache[key] = data - return data -} diff --git a/cmd/source.go b/cmd/source.go deleted file mode 100644 index aa1bbbdac4d..00000000000 --- a/cmd/source.go +++ /dev/null @@ -1,22 +0,0 @@ -package cmd - -import ( - "github.com/spf13/cobra" -) - -var sourceCmd = &cobra.Command{ - Use: "source [args...]", - Short: "Run the source version control system command in the source directory", - Long: mustGetLongHelp("source"), - Example: getExample("source"), - PreRunE: config.ensureNoError, - RunE: config.runSourceCmd, -} - -func init() { - rootCmd.AddCommand(sourceCmd) -} - -func (c *Config) runSourceCmd(cmd *cobra.Command, args []string) error { - return c.run(c.SourceDir, c.SourceVCS.Command, args...) -} diff --git a/cmd/sourcepath.go b/cmd/sourcepath.go deleted file mode 100644 index 7eae1ccc2da..00000000000 --- a/cmd/sourcepath.go +++ /dev/null @@ -1,44 +0,0 @@ -package cmd - -import ( - "fmt" - "path/filepath" - - "github.com/spf13/cobra" -) - -var sourcePathCmd = &cobra.Command{ - Use: "source-path [targets...]", - Short: "Print the path of a target in the source state", - Long: mustGetLongHelp("source-path"), - Example: getExample("source-path"), - PreRunE: config.ensureNoError, - RunE: config.runSourcePathCmd, -} - -func init() { - rootCmd.AddCommand(sourcePathCmd) - - markRemainingZshCompPositionalArgumentsAsFiles(sourcePathCmd, 1) -} - -func (c *Config) runSourcePathCmd(cmd *cobra.Command, args []string) error { - ts, err := c.getTargetState(nil) - if err != nil { - return err - } - if len(args) == 0 { - _, err := fmt.Println(ts.SourceDir) - return err - } - entries, err := c.getEntries(ts, args) - if err != nil { - return err - } - for _, entry := range entries { - if _, err := fmt.Println(filepath.Join(ts.SourceDir, entry.SourceName())); err != nil { - return err - } - } - return nil -} diff --git a/chezmoi2/cmd/sourcepathcmd.go b/cmd/sourcepathcmd.go similarity index 93% rename from chezmoi2/cmd/sourcepathcmd.go rename to cmd/sourcepathcmd.go index f8d3c89e5d0..9972815b02b 100644 --- a/chezmoi2/cmd/sourcepathcmd.go +++ b/cmd/sourcepathcmd.go @@ -6,7 +6,7 @@ import ( "github.com/spf13/cobra" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoi" ) func (c *Config) newSourcePathCmd() *cobra.Command { diff --git a/chezmoi2/cmd/statecmd.go b/cmd/statecmd.go similarity index 96% rename from chezmoi2/cmd/statecmd.go rename to cmd/statecmd.go index bffc01eb3d5..face9897e4d 100644 --- a/chezmoi2/cmd/statecmd.go +++ b/cmd/statecmd.go @@ -6,7 +6,7 @@ import ( "github.com/spf13/cobra" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoi" ) type stateCmdConfig struct { diff --git a/chezmoi2/cmd/statuscmd.go b/cmd/statuscmd.go similarity index 96% rename from chezmoi2/cmd/statuscmd.go rename to cmd/statuscmd.go index ec8c18408f6..4d8cb46903d 100644 --- a/chezmoi2/cmd/statuscmd.go +++ b/cmd/statuscmd.go @@ -6,11 +6,11 @@ import ( "github.com/spf13/cobra" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoi" ) type statusCmdConfig struct { - include *chezmoi.IncludeSet + include *chezmoi.EntryTypeSet recursive bool } diff --git a/chezmoi2/cmd/statuscmd_test.go b/cmd/statuscmd_test.go similarity index 93% rename from chezmoi2/cmd/statuscmd_test.go rename to cmd/statuscmd_test.go index bc34dddfbcf..7b0a3cbfc41 100644 --- a/chezmoi2/cmd/statuscmd_test.go +++ b/cmd/statuscmd_test.go @@ -6,10 +6,10 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - vfs "github.com/twpayne/go-vfs" - "github.com/twpayne/go-vfs/vfst" + vfs "github.com/twpayne/go-vfs/v2" + "github.com/twpayne/go-vfs/v2/vfst" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoitest" + "github.com/twpayne/chezmoi/internal/chezmoitest" ) func TestStatusCmd(t *testing.T) { diff --git a/cmd/templatefuncs.go b/cmd/templatefuncs.go index 4a80239b22d..39cfd33d913 100644 --- a/cmd/templatefuncs.go +++ b/cmd/templatefuncs.go @@ -2,31 +2,60 @@ package cmd import ( "errors" + "fmt" "os" "os/exec" "path/filepath" + "runtime" + + "howett.net/plist" + + "github.com/twpayne/chezmoi/internal/chezmoi" ) -func init() { - config.addTemplateFunc("include", config.includeFunc) - config.addTemplateFunc("joinPath", config.joinPathFunc) - config.addTemplateFunc("lookPath", config.lookPathFunc) - config.addTemplateFunc("stat", config.statFunc) +type ioregData struct { + value map[string]interface{} } -func (c *Config) includeFunc(filename string) string { - contents, err := c.fs.ReadFile(filepath.Join(c.SourceDir, filename)) +func (c *Config) includeTemplateFunc(filename string) string { + contents, err := c.fs.ReadFile(string(c.sourceDirAbsPath.Join(chezmoi.RelPath(filename)))) if err != nil { - panic(err) + returnTemplateError(err) + return "" } return string(contents) } -func (c *Config) joinPathFunc(elem ...string) string { +func (c *Config) ioregTemplateFunc() map[string]interface{} { + if runtime.GOOS != "darwin" { + return nil + } + + if c.ioregData.value != nil { + return c.ioregData.value + } + + cmd := exec.Command("ioreg", "-a", "-l") + output, err := c.baseSystem.IdempotentCmdOutput(cmd) + if err != nil { + returnTemplateError(fmt.Errorf("ioreg: %w", err)) + return nil + } + + var value map[string]interface{} + if _, err := plist.Unmarshal(output, &value); err != nil { + returnTemplateError(fmt.Errorf("ioreg: %w", err)) + return nil + } + c.ioregData.value = value + return value +} + +func (c *Config) joinPathTemplateFunc(elem ...string) string { return filepath.Join(elem...) } -func (c *Config) lookPathFunc(file string) string { +func (c *Config) lookPathTemplateFunc(file string) string { path, err := exec.LookPath(file) switch { case err == nil: @@ -34,11 +63,12 @@ func (c *Config) lookPathFunc(file string) string { case errors.Is(err, exec.ErrNotFound): return "" default: - panic(err) + returnTemplateError(err) + return "" } } -func (c *Config) statFunc(name string) interface{} { +func (c *Config) statTemplateFunc(name string) interface{} { info, err := c.fs.Stat(name) switch { case err == nil: @@ -53,6 +83,11 @@ func (c *Config) statFunc(name string) interface{} { case os.IsNotExist(err): return nil default: - panic(err) + returnTemplateError(err) + return nil } } + +func returnTemplateError(err error) { + panic(err) +} diff --git a/cmd/templates.gen.go b/cmd/templates.gen.go deleted file mode 100644 index f331042e250..00000000000 --- a/cmd/templates.gen.go +++ /dev/null @@ -1,31 +0,0 @@ -// Code generated by github.com/twpayne/chezmoi/internal/cmd/generate-assets. DO NOT EDIT. - -package cmd - -func init() { - assets["assets/templates/COMMIT_MESSAGE.tmpl"] = []byte("" + - "{{- /* FIXME generate commit summary */ -}}\n" + - "\n" + - "{{- range .Ordinary -}}\n" + - "{{ if and (eq .X 'A') (eq .Y '.') -}}Add {{ .Path }}\n" + - "{{ else if and (eq .X 'D') (eq .Y '.') -}}Remove {{ .Path }}\n" + - "{{ else if and (eq .X 'M') (eq .Y '.') -}}Update {{ .Path }}\n" + - "{{ else }}{{with (printf \"unsupported XY: %q\" (printf \"%c%c\" .X .Y)) }}{{ fail . }}{{ end }}\n" + - "{{ end }}\n" + - "{{- end -}}\n" + - "\n" + - "{{- range .RenamedOrCopied -}}\n" + - "{{ if and (eq .X 'R') (eq .Y '.') }}Rename {{ .OrigPath }} to {{ .Path }}\n" + - "{{ else }}{{with (printf \"unsupported XY: %q\" (printf \"%c%c\" .X .Y)) }}{{ fail . }}{{ end }}\n" + - "{{ end }}\n" + - "{{- end -}}\n" + - "\n" + - "{{- range .Unmerged -}}\n" + - "{{ fail \"unmerged files\" }}\n" + - "{{- end -}}\n" + - "\n" + - "{{- range .Untracked -}}\n" + - "{{ fail \"untracked files\" }}\n" + - "{{- end -}}\n" + - "\n") -} diff --git a/chezmoi2/cmd/terminal.go b/cmd/terminal.go similarity index 100% rename from chezmoi2/cmd/terminal.go rename to cmd/terminal.go diff --git a/cmd/testdata/gitrepo/COMMIT_EDITMSG b/cmd/testdata/gitrepo/COMMIT_EDITMSG deleted file mode 100644 index 9a7e7303f13..00000000000 --- a/cmd/testdata/gitrepo/COMMIT_EDITMSG +++ /dev/null @@ -1 +0,0 @@ -Add .chezmoi.toml.tmpl diff --git a/cmd/testdata/gitrepo/HEAD b/cmd/testdata/gitrepo/HEAD deleted file mode 100644 index cb089cd89a7..00000000000 --- a/cmd/testdata/gitrepo/HEAD +++ /dev/null @@ -1 +0,0 @@ -ref: refs/heads/master diff --git a/cmd/testdata/gitrepo/config b/cmd/testdata/gitrepo/config deleted file mode 100644 index 6c9406b7d93..00000000000 --- a/cmd/testdata/gitrepo/config +++ /dev/null @@ -1,7 +0,0 @@ -[core] - repositoryformatversion = 0 - filemode = true - bare = false - logallrefupdates = true - ignorecase = true - precomposeunicode = true diff --git a/cmd/testdata/gitrepo/description b/cmd/testdata/gitrepo/description deleted file mode 100644 index 498b267a8c7..00000000000 --- a/cmd/testdata/gitrepo/description +++ /dev/null @@ -1 +0,0 @@ -Unnamed repository; edit this file 'description' to name the repository. diff --git a/cmd/testdata/gitrepo/index b/cmd/testdata/gitrepo/index deleted file mode 100644 index 8ce54bbf7df..00000000000 Binary files a/cmd/testdata/gitrepo/index and /dev/null differ diff --git a/cmd/testdata/gitrepo/info/exclude b/cmd/testdata/gitrepo/info/exclude deleted file mode 100644 index a5196d1be8f..00000000000 --- a/cmd/testdata/gitrepo/info/exclude +++ /dev/null @@ -1,6 +0,0 @@ -# git ls-files --others --exclude-from=.git/info/exclude -# Lines that start with '#' are comments. -# For a project mostly in C, the following would be a good set of -# exclude patterns (uncomment them if you want to use them): -# *.[oa] -# *~ diff --git a/cmd/testdata/gitrepo/logs/HEAD b/cmd/testdata/gitrepo/logs/HEAD deleted file mode 100644 index e749a3de7c8..00000000000 --- a/cmd/testdata/gitrepo/logs/HEAD +++ /dev/null @@ -1,2 +0,0 @@ -0000000000000000000000000000000000000000 86609dbf1c1514d1328efd7c29b69d517dcd440d Tom Payne <[email protected]> 1567807201 +0200 commit (initial): Add .bashrc -86609dbf1c1514d1328efd7c29b69d517dcd440d b3b74aaf7c352e16f1de71dea4cd20b65b0a8e78 Tom Payne <[email protected]> 1567868879 +0200 commit: Add .chezmoi.toml.tmpl diff --git a/cmd/testdata/gitrepo/logs/refs/heads/master b/cmd/testdata/gitrepo/logs/refs/heads/master deleted file mode 100644 index e749a3de7c8..00000000000 --- a/cmd/testdata/gitrepo/logs/refs/heads/master +++ /dev/null @@ -1,2 +0,0 @@ -0000000000000000000000000000000000000000 86609dbf1c1514d1328efd7c29b69d517dcd440d Tom Payne <[email protected]> 1567807201 +0200 commit (initial): Add .bashrc -86609dbf1c1514d1328efd7c29b69d517dcd440d b3b74aaf7c352e16f1de71dea4cd20b65b0a8e78 Tom Payne <[email protected]> 1567868879 +0200 commit: Add .chezmoi.toml.tmpl diff --git a/cmd/testdata/gitrepo/objects/13/faef3591002a9d38fe869ca0e205ca472fac73 b/cmd/testdata/gitrepo/objects/13/faef3591002a9d38fe869ca0e205ca472fac73 deleted file mode 100644 index ce01b76c5d9..00000000000 Binary files a/cmd/testdata/gitrepo/objects/13/faef3591002a9d38fe869ca0e205ca472fac73 and /dev/null differ diff --git a/cmd/testdata/gitrepo/objects/35/3d7a9de061787533636c2574bb50220c155395 b/cmd/testdata/gitrepo/objects/35/3d7a9de061787533636c2574bb50220c155395 deleted file mode 100644 index fe0bd7bc753..00000000000 Binary files a/cmd/testdata/gitrepo/objects/35/3d7a9de061787533636c2574bb50220c155395 and /dev/null differ diff --git a/cmd/testdata/gitrepo/objects/86/609dbf1c1514d1328efd7c29b69d517dcd440d b/cmd/testdata/gitrepo/objects/86/609dbf1c1514d1328efd7c29b69d517dcd440d deleted file mode 100644 index c9305743a61..00000000000 --- a/cmd/testdata/gitrepo/objects/86/609dbf1c1514d1328efd7c29b69d517dcd440d +++ /dev/null @@ -1,2 +0,0 @@ -x•K -Â0@]ç³ÊdÆÉ´ ¢7páòÃŒ‘oo=‚»ÇƒÇ‹µ”¥ƒUÜô–3°pR?¥ŒÎê¨ÂìØE݅ H„ÑŠð$Æ¿ú\\j³ÿÜ3ìûûñƒãµøå6ÄZ`ÅéˆJha‹„hV»îzþ;4§”`þ9·h¾Øø5 \ No newline at end of file diff --git a/cmd/testdata/gitrepo/objects/b1/ba266399ff20c75b9ac2d22fe4938c328b3bb3 b/cmd/testdata/gitrepo/objects/b1/ba266399ff20c75b9ac2d22fe4938c328b3bb3 deleted file mode 100644 index d0527d752de..00000000000 Binary files a/cmd/testdata/gitrepo/objects/b1/ba266399ff20c75b9ac2d22fe4938c328b3bb3 and /dev/null differ diff --git a/cmd/testdata/gitrepo/objects/b3/b74aaf7c352e16f1de71dea4cd20b65b0a8e78 b/cmd/testdata/gitrepo/objects/b3/b74aaf7c352e16f1de71dea4cd20b65b0a8e78 deleted file mode 100644 index 00bd84b658e..00000000000 --- a/cmd/testdata/gitrepo/objects/b3/b74aaf7c352e16f1de71dea4cd20b65b0a8e78 +++ /dev/null @@ -1,2 +0,0 @@ -x•ŽA -Â0E]ç³Ê$¶ÉDô.¼@œ™h¡1¥DDOo=‚›ÇçÁ‡Çµ”±sqÓU`ÉÌ순eÌ! †¤ìzT¶+yõÁÌiÑGò£\³e;Ø^ìΑf ìâÕGl–¾G1éÙîuK-pNï‡Â¾½æß8ÞJ§Žk9€| O"lÑ!šÕ®yMÿ>š“t|×O©c×j™ºVæÉ|ØHç \ No newline at end of file diff --git a/cmd/testdata/gitrepo/objects/cd/fccc2882d88f0d0f77007aec240ec1240c8f07 b/cmd/testdata/gitrepo/objects/cd/fccc2882d88f0d0f77007aec240ec1240c8f07 deleted file mode 100644 index f72b1b97f9c..00000000000 Binary files a/cmd/testdata/gitrepo/objects/cd/fccc2882d88f0d0f77007aec240ec1240c8f07 and /dev/null differ diff --git a/cmd/testdata/gitrepo/refs/heads/master b/cmd/testdata/gitrepo/refs/heads/master deleted file mode 100644 index d8c91296b4f..00000000000 --- a/cmd/testdata/gitrepo/refs/heads/master +++ /dev/null @@ -1 +0,0 @@ -b3b74aaf7c352e16f1de71dea4cd20b65b0a8e78 diff --git a/cmd/unmanaged.go b/cmd/unmanaged.go deleted file mode 100644 index c3c9d5f4012..00000000000 --- a/cmd/unmanaged.go +++ /dev/null @@ -1,50 +0,0 @@ -package cmd - -import ( - "fmt" - "os" - "path/filepath" - "strings" - - "github.com/spf13/cobra" - vfs "github.com/twpayne/go-vfs" -) - -var unmanagedCmd = &cobra.Command{ - Use: "unmanaged", - Args: cobra.NoArgs, - Short: "List the unmanaged files in the destination directory", - Long: mustGetLongHelp("unmanaged"), - Example: getExample("unmanaged"), - PreRunE: config.ensureNoError, - RunE: config.runUnmanagedCmd, -} - -func init() { - rootCmd.AddCommand(unmanagedCmd) -} - -func (c *Config) runUnmanagedCmd(cmd *cobra.Command, args []string) error { - ts, err := c.getTargetState(nil) - if err != nil { - return err - } - return vfs.Walk(c.fs, c.DestDir, func(path string, info os.FileInfo, err error) error { - if err != nil { - return err - } - if path == c.DestDir { - return nil - } - entry, _ := ts.Get(c.fs, path) - managed := entry != nil - ignored := ts.TargetIgnore.Match(strings.TrimPrefix(path, c.DestDir+"/")) - if !managed && !ignored { - fmt.Println(path) - } - if info.IsDir() && (!managed || ignored) { - return filepath.SkipDir - } - return nil - }) -} diff --git a/chezmoi2/cmd/unmanagedcmd.go b/cmd/unmanagedcmd.go similarity index 93% rename from chezmoi2/cmd/unmanagedcmd.go rename to cmd/unmanagedcmd.go index 70893dc9f7a..862072c9004 100644 --- a/chezmoi2/cmd/unmanagedcmd.go +++ b/cmd/unmanagedcmd.go @@ -5,9 +5,9 @@ import ( "strings" "github.com/spf13/cobra" - vfs "github.com/twpayne/go-vfs" + vfs "github.com/twpayne/go-vfs/v2" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoi" ) func (c *Config) newUnmanagedCmd() *cobra.Command { diff --git a/cmd/update.go b/cmd/update.go deleted file mode 100644 index 4da6281c633..00000000000 --- a/cmd/update.go +++ /dev/null @@ -1,69 +0,0 @@ -package cmd - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" -) - -type updateCmdConfig struct { - apply bool -} - -var updateCmd = &cobra.Command{ - Use: "update", - Args: cobra.NoArgs, - Short: "Pull changes from the source VCS and apply any changes", - Long: mustGetLongHelp("update"), - Example: getExample("update"), - PreRunE: config.ensureNoError, - RunE: config.runUpdateCmd, -} - -func init() { - rootCmd.AddCommand(updateCmd) - - persistentFlags := updateCmd.PersistentFlags() - persistentFlags.BoolVarP(&config.update.apply, "apply", "a", true, "apply after pulling") -} - -func (c *Config) runUpdateCmd(cmd *cobra.Command, args []string) error { - vcs, err := c.getVCS() - if err != nil { - return err - } - var pullArgs []string - if c.SourceVCS.Pull != nil { - switch v := c.SourceVCS.Pull.(type) { - case string: - pullArgs = strings.Split(v, " ") - case []string: - pullArgs = v - default: - return fmt.Errorf("sourceVCS.pull: cannot parse value") - } - } else { - pullArgs = vcs.PullArgs() - } - if pullArgs == nil { - return fmt.Errorf("%s: pull not supported", c.SourceVCS.Command) - } - - if err := c.run(c.SourceDir, c.SourceVCS.Command, pullArgs...); err != nil { - return err - } - - if c.update.apply { - persistentState, err := c.getPersistentState(nil) - if err != nil { - return err - } - defer persistentState.Close() - if err := c.applyArgs(nil, persistentState); err != nil { - return err - } - } - - return nil -} diff --git a/chezmoi2/cmd/updatecmd.go b/cmd/updatecmd.go similarity index 95% rename from chezmoi2/cmd/updatecmd.go rename to cmd/updatecmd.go index 8c85e5ccc5b..b883f5f5c45 100644 --- a/chezmoi2/cmd/updatecmd.go +++ b/cmd/updatecmd.go @@ -6,12 +6,12 @@ import ( "github.com/go-git/go-git/v5" "github.com/spf13/cobra" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoi" ) type updateCmdConfig struct { apply bool - include *chezmoi.IncludeSet + include *chezmoi.EntryTypeSet recursive bool } diff --git a/cmd/upgrade.go b/cmd/upgrade.go deleted file mode 100644 index cf8cf888541..00000000000 --- a/cmd/upgrade.go +++ /dev/null @@ -1,471 +0,0 @@ -// +build !noupgrade -// +build !windows - -package cmd - -import ( - "archive/tar" - "bufio" - "bytes" - "compress/gzip" - "context" - "crypto/sha256" - "encoding/hex" - "errors" - "fmt" - "io" - "io/ioutil" - "net/http" - "os" - "os/exec" - "path/filepath" - "regexp" - "runtime" - "strings" - "syscall" - - "github.com/coreos/go-semver/semver" - "github.com/google/go-github/v33/github" - "github.com/spf13/cobra" - vfs "github.com/twpayne/go-vfs" - "golang.org/x/oauth2" -) - -const ( - methodReplaceExecutable = "replace-executable" - methodSnapRefresh = "snap-refresh" - methodUpgradePackage = "upgrade-package" - methodSudoPrefix = "sudo-" - - packageTypeNone = "" - packageTypeAUR = "aur" - packageTypeDEB = "deb" - packageTypeRPM = "rpm" -) - -var ( - packageTypeByID = map[string]string{ - "amzn": packageTypeRPM, - "arch": packageTypeAUR, - "centos": packageTypeRPM, - "fedora": packageTypeRPM, - "opensuse": packageTypeRPM, - "debian": packageTypeDEB, - "rhel": packageTypeRPM, - "sles": packageTypeRPM, - "ubuntu": packageTypeDEB, - } - - archReplacements = map[string]map[string]string{ - packageTypeDEB: { - "386": "i386", - "arm": "armel", - }, - packageTypeRPM: { - "amd64": "x86_64", - "386": "i686", - "arm": "armfp", - "arm64": "aarch64", - }, - } - - checksumRegexp = regexp.MustCompile(`\A([0-9a-f]{64})\s+(\S+)\z`) -) - -var upgradeCmd = &cobra.Command{ - Use: "upgrade", - Args: cobra.NoArgs, - Short: "Upgrade chezmoi to the latest released version", - Long: mustGetLongHelp("upgrade"), - Example: getExample("upgrade"), - RunE: config.runUpgradeCmd, -} - -type upgradeCmdConfig struct { - force bool - method string - owner string - repo string -} - -func init() { - rootCmd.AddCommand(upgradeCmd) - - persistentFlags := upgradeCmd.PersistentFlags() - persistentFlags.BoolVarP(&config.upgrade.force, "force", "f", false, "force upgrade") - persistentFlags.StringVarP(&config.upgrade.method, "method", "m", "", "set method") - persistentFlags.StringVarP(&config.upgrade.owner, "owner", "o", "twpayne", "set owner") - persistentFlags.StringVarP(&config.upgrade.repo, "repo", "r", "chezmoi", "set repo") -} - -func (c *Config) runUpgradeCmd(cmd *cobra.Command, args []string) error { - ctx := context.Background() - - if VersionStr == "" && !config.upgrade.force { - return errors.New("cannot upgrade dev version to latest released version unless --force is set") - } - - // Use a GitHub API token, if set. - var httpClient *http.Client - if accessToken, ok := os.LookupEnv(strings.ToUpper(c.upgrade.repo) + "_GITHUB_API_TOKEN"); ok { - httpClient = oauth2.NewClient(ctx, oauth2.StaticTokenSource(&oauth2.Token{ - AccessToken: accessToken, - })) - } - - client := github.NewClient(httpClient) - - // Get the latest release. - rr, _, err := client.Repositories.GetLatestRelease(ctx, c.upgrade.owner, c.upgrade.repo) - if err != nil { - return err - } - releaseVersion, err := semver.NewVersion(strings.TrimPrefix(rr.GetName(), "v")) - if err != nil { - return err - } - - // If the upgrade is not forced, stop if we're already the latest version. - // Print a message and return no error so the command exits with success. - if !c.upgrade.force && !Version.LessThan(*releaseVersion) { - fmt.Fprintf(c.Stdout, "chezmoi: already at the latest version (%s)\n", Version) - return nil - } - - // Determine the upgrade method to use. - executableFilename, err := os.Executable() - if err != nil { - return err - } - method := c.upgrade.method - if method == "" { - method, err = getMethod(c.fs, executableFilename) - if err != nil { - return err - } - } - - // Replace the executable with the updated version. - switch method { - case methodReplaceExecutable: - if err := c.replaceExecutable(executableFilename, releaseVersion, rr); err != nil { - return err - } - case methodSnapRefresh: - if err := c.snapRefresh(); err != nil { - return err - } - case methodUpgradePackage: - if err := c.upgradePackage(rr, false); err != nil { - return err - } - case methodSudoPrefix + methodUpgradePackage: - if err := c.upgradePackage(rr, true); err != nil { - return err - } - default: - return fmt.Errorf("invalid --method value: %s", method) - } - - // Find the executable. If we replaced the executable directly, then use - // that, otherwise look in $PATH. - path := executableFilename - if method != methodReplaceExecutable { - path, err = exec.LookPath(c.upgrade.repo) - if err != nil { - return err - } - } - - // Execute the new version. - if c.Verbose { - fmt.Printf("exec %s --version\n", path) - } - return syscall.Exec(path, []string{path, "--version"}, os.Environ()) -} - -func (c *Config) getChecksums(rr *github.RepositoryRelease) (map[string][]byte, error) { - name := fmt.Sprintf("%s_%s_checksums.txt", c.upgrade.repo, strings.TrimPrefix(rr.GetTagName(), "v")) - releaseAsset := getReleaseAssetByName(rr, name) - if releaseAsset == nil { - return nil, fmt.Errorf("%s: cannot find release asset", name) - } - - data, err := c.downloadURL(releaseAsset.GetBrowserDownloadURL()) - if err != nil { - return nil, err - } - - checksums := make(map[string][]byte) - s := bufio.NewScanner(bytes.NewReader(data)) - for s.Scan() { - m := checksumRegexp.FindStringSubmatch(s.Text()) - if m == nil { - return nil, fmt.Errorf("%q: cannot parse checksum", s.Text()) - } - checksums[m[2]], _ = hex.DecodeString(m[1]) - } - return checksums, s.Err() -} - -func (c *Config) downloadURL(url string) ([]byte, error) { - if c.Verbose { - fmt.Fprintf(c.Stdout, "curl -s -L %s\n", url) - } - //nolint:gosec - resp, err := http.Get(url) - if err != nil { - return nil, err - } - if resp.StatusCode != http.StatusOK { - _ = resp.Body.Close() - return nil, fmt.Errorf("%s: got a non-200 OK response: %d %s", url, resp.StatusCode, resp.Status) - } - data, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - if err := resp.Body.Close(); err != nil { - return nil, err - } - return data, nil -} - -func (c *Config) replaceExecutable(executableFilename string, releaseVersion *semver.Version, rr *github.RepositoryRelease) error { - name := fmt.Sprintf("%s_%s_%s_%s.tar.gz", c.upgrade.repo, releaseVersion, runtime.GOOS, runtime.GOARCH) - releaseAsset := getReleaseAssetByName(rr, name) - if releaseAsset == nil { - return fmt.Errorf("%s: cannot find release asset", name) - } - - data, err := c.downloadURL(releaseAsset.GetBrowserDownloadURL()) - if err != nil { - return err - } - if err := c.verifyChecksum(rr, releaseAsset.GetName(), data); err != nil { - return err - } - - // Extract the executable from the archive. - gzipr, err := gzip.NewReader(bytes.NewReader(data)) - if err != nil { - return err - } - defer gzipr.Close() - tr := tar.NewReader(gzipr) - var executableData []byte -FOR: - for { - h, err := tr.Next() - switch { - case err == nil && h.Name == c.upgrade.repo: - executableData, err = ioutil.ReadAll(tr) - if err != nil { - return err - } - break FOR - case errors.Is(err, io.EOF): - return fmt.Errorf("%s: could not find header", c.upgrade.repo) - } - } - - return c.mutator.WriteFile(executableFilename, executableData, 0o755, nil) -} - -func (c *Config) snapRefresh() error { - return c.run("", "snap", "refresh", c.upgrade.repo) -} - -func (c *Config) upgradePackage(rr *github.RepositoryRelease, useSudo bool) error { - switch runtime.GOOS { - case "darwin": - return c.run("", "brew", "upgrade", c.upgrade.repo) - case "linux": - // Determine the package type and architecture. - packageType, err := getPackageType(c.fs) - if err != nil { - return err - } - arch := runtime.GOARCH - if archReplacement, ok := archReplacements[packageType]; ok { - arch = archReplacement[arch] - } - - // chezmoi does not build and distribute AUR packages, so instead rely - // on pacman and the communnity package. - if packageType == packageTypeAUR { - var args []string - if useSudo { - args = append(args, "sudo") - } - args = append(args, "pacman", "-S", c.upgrade.repo) - return c.run("", args[0], args[1:]...) - } - - // Find the corresponding release asset. - var releaseAsset *github.ReleaseAsset - suffix := arch + "." + packageType - for i, ra := range rr.Assets { - if strings.HasSuffix(ra.GetName(), suffix) { - releaseAsset = rr.Assets[i] - break - } - } - if releaseAsset == nil { - return fmt.Errorf("cannot find release asset (arch=%q, packageType=%q)", arch, packageType) - } - - // Create a temporary directory for the package. - var tempDir string - if c.DryRun { - tempDir = os.TempDir() - } else { - tempDir, err = ioutil.TempDir("", "chezmoi") - if c.Verbose { - fmt.Fprintf(c.Stdout, "mkdir -p %s\n", tempDir) - } - if err != nil { - return err - } - defer func() { - _ = c.mutator.RemoveAll(tempDir) - }() - } - - data, err := c.downloadURL(releaseAsset.GetBrowserDownloadURL()) - if err != nil { - return err - } - if err := c.verifyChecksum(rr, releaseAsset.GetName(), data); err != nil { - return err - } - - packageFilename := filepath.Join(tempDir, releaseAsset.GetName()) - if err := c.mutator.WriteFile(packageFilename, data, 0o644, nil); err != nil { - return err - } - - // Install the package from disk. - var args []string - if useSudo { - args = append(args, "sudo") - } - switch packageType { - case packageTypeDEB: - args = append(args, "dpkg", "-i", packageFilename) - case packageTypeRPM: - args = append(args, "rpm", "-U", packageFilename) - } - return c.run("", args[0], args[1:]...) - default: - return fmt.Errorf("%s: unsupported GOOS", runtime.GOOS) - } -} - -func (c *Config) verifyChecksum(rr *github.RepositoryRelease, name string, data []byte) error { - checksums, err := c.getChecksums(rr) - if err != nil { - return err - } - expectedChecksum, ok := checksums[name] - if !ok { - return fmt.Errorf("%s: checksum not found", name) - } - checksum := sha256.Sum256(data) - if !bytes.Equal(checksum[:], expectedChecksum) { - return fmt.Errorf("%s: checksum failed (want %s, got %s)", name, hex.EncodeToString(expectedChecksum), hex.EncodeToString(checksum[:])) - } - return nil -} - -func getMethod(fs vfs.Stater, executableFilename string) (string, error) { - if ok, _ := vfs.Contains(fs, executableFilename, "/snap"); ok { - return methodSnapRefresh, nil - } - info, err := fs.Stat(executableFilename) - if err != nil { - return "", err - } - userHomeDir, err := os.UserHomeDir() - if err != nil { - return "", err - } - executableInUserHomeDir, err := vfs.Contains(fs, executableFilename, userHomeDir) - if err != nil { - return "", err - } - executableIsInTempDir, err := vfs.Contains(fs, executableFilename, os.TempDir()) - if err != nil { - return "", err - } - - executableStat := info.Sys().(*syscall.Stat_t) - uid := os.Getuid() - switch runtime.GOOS { - case "darwin": - if int(executableStat.Uid) != uid { - return "", fmt.Errorf("%s: cannot upgrade executable owned by non-current user", executableFilename) - } - if executableInUserHomeDir || executableIsInTempDir { - return methodReplaceExecutable, nil - } - return methodUpgradePackage, nil - case "freebsd": - return methodReplaceExecutable, nil - case "linux": - if uid == 0 { - if executableStat.Uid != 0 { - return "", fmt.Errorf("%s: cannot upgrade executable owned by non-root user when running as root", executableFilename) - } - if executableInUserHomeDir || executableIsInTempDir { - return methodReplaceExecutable, nil - } - return methodUpgradePackage, nil - } - switch int(executableStat.Uid) { - case 0: - method := methodUpgradePackage - if _, err := exec.LookPath("sudo"); err == nil { - method = methodSudoPrefix + method - } - return method, nil - case uid: - return methodReplaceExecutable, nil - default: - return "", fmt.Errorf("%s: cannot upgrade executable owned by non-current non-root user", executableFilename) - } - case "openbsd": - return methodReplaceExecutable, nil - default: - return "", fmt.Errorf("%s: unsupported GOOS", runtime.GOOS) - } -} - -func getPackageType(fs vfs.FS) (string, error) { - osRelease, err := getOSRelease(fs) - if err != nil { - return packageTypeNone, err - } - if id, ok := osRelease["ID"]; ok { - if packageType, ok := packageTypeByID[id]; ok { - return packageType, nil - } - } - if idLikes, ok := osRelease["ID_LIKE"]; ok { - for _, id := range strings.Split(idLikes, " ") { - if packageType, ok := packageTypeByID[id]; ok { - return packageType, nil - } - } - } - return packageTypeNone, fmt.Errorf("could not determine package type (ID=%q, ID_LIKE=%q)", osRelease["ID"], osRelease["ID_LIKE"]) -} - -func getReleaseAssetByName(rr *github.RepositoryRelease, name string) *github.ReleaseAsset { - for i, ra := range rr.Assets { - if ra.GetName() == name { - return rr.Assets[i] - } - } - return nil -} diff --git a/chezmoi2/cmd/util.go b/cmd/util.go similarity index 98% rename from chezmoi2/cmd/util.go rename to cmd/util.go index 93f556e6580..a581455df5e 100644 --- a/chezmoi2/cmd/util.go +++ b/cmd/util.go @@ -8,10 +8,10 @@ import ( "unicode" "github.com/spf13/viper" - "github.com/twpayne/go-vfs" + "github.com/twpayne/go-vfs/v2" "github.com/twpayne/go-xdg/v3" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoi" ) var ( diff --git a/cmd/util_posix.go b/cmd/util_posix.go deleted file mode 100644 index 7602f9c9f00..00000000000 --- a/cmd/util_posix.go +++ /dev/null @@ -1,23 +0,0 @@ -// +build !windows - -package cmd - -import ( - "io" - "os" - - "github.com/google/renameio" -) - -// enableVirtualTerminalProcessingOnWindows does nothing on POSIX systems. -func enableVirtualTerminalProcessingOnWindows(w io.Writer) error { - return nil -} - -func trimExecutableSuffix(s string) string { - return s -} - -func writeFile(filename string, data []byte, perm os.FileMode) error { - return renameio.WriteFile(filename, data, perm) -} diff --git a/cmd/util_posix_test.go b/cmd/util_posix_test.go deleted file mode 100644 index df968515fd3..00000000000 --- a/cmd/util_posix_test.go +++ /dev/null @@ -1,7 +0,0 @@ -//+build !windows - -package cmd - -func lines(s string) string { - return s -} diff --git a/chezmoi2/cmd/util_test.go b/cmd/util_test.go similarity index 100% rename from chezmoi2/cmd/util_test.go rename to cmd/util_test.go diff --git a/chezmoi2/cmd/util_unix.go b/cmd/util_unix.go similarity index 100% rename from chezmoi2/cmd/util_unix.go rename to cmd/util_unix.go diff --git a/cmd/util_windows.go b/cmd/util_windows.go index 06f84d2caf8..dd5b6adceb0 100644 --- a/cmd/util_windows.go +++ b/cmd/util_windows.go @@ -2,17 +2,14 @@ package cmd import ( "io" - "io/ioutil" "os" - "strings" "golang.org/x/sys/windows" ) -// enableVirtualTerminalProcessingOnWindows enables virtual terminal processing -// on Windows. See +// enableVirtualTerminalProcessing enables virtual terminal processing. See // https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences. -func enableVirtualTerminalProcessingOnWindows(w io.Writer) error { +func enableVirtualTerminalProcessing(w io.Writer) error { f, ok := w.(*os.File) if !ok { return nil @@ -23,11 +20,3 @@ func enableVirtualTerminalProcessingOnWindows(w io.Writer) error { } return windows.SetConsoleMode(windows.Handle(f.Fd()), dwMode|windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING) } - -func trimExecutableSuffix(s string) string { - return strings.TrimSuffix(s, ".exe") -} - -func writeFile(filename string, data []byte, perm os.FileMode) error { - return ioutil.WriteFile(filename, data, perm) -} diff --git a/cmd/util_windows_test.go b/cmd/util_windows_test.go deleted file mode 100644 index 750fedf7067..00000000000 --- a/cmd/util_windows_test.go +++ /dev/null @@ -1,9 +0,0 @@ -//+build windows - -package cmd - -import "strings" - -func lines(s string) string { - return strings.Replace(s, "\n", "\r\n", -1) -} diff --git a/chezmoi2/cmd/vaulttemplatefuncs.go b/cmd/vaulttemplatefuncs.go similarity index 94% rename from chezmoi2/cmd/vaulttemplatefuncs.go rename to cmd/vaulttemplatefuncs.go index edc25aef21e..9fe0bdd35a6 100644 --- a/chezmoi2/cmd/vaulttemplatefuncs.go +++ b/cmd/vaulttemplatefuncs.go @@ -5,7 +5,7 @@ import ( "fmt" "os/exec" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoi" ) type vaultConfig struct { diff --git a/cmd/vcs.go b/cmd/vcs.go deleted file mode 100644 index c022b677fdd..00000000000 --- a/cmd/vcs.go +++ /dev/null @@ -1,23 +0,0 @@ -package cmd - -import "regexp" - -// A VCS is a version control system. -type VCS interface { - AddArgs(string) []string - CloneArgs(string, string) []string - CommitArgs(string) []string - InitArgs() []string - Initialized(string) (bool, error) - ParseStatusOutput([]byte) (interface{}, error) - PullArgs() []string - PushArgs() []string - StatusArgs() []string - VersionArgs() []string - VersionRegexp() *regexp.Regexp -} - -var vcses = map[string]VCS{ - "git": gitVCS{}, - "hg": hgVCS{}, -} diff --git a/cmd/verify.go b/cmd/verify.go deleted file mode 100644 index 3ab40f5c8bb..00000000000 --- a/cmd/verify.go +++ /dev/null @@ -1,44 +0,0 @@ -package cmd - -import ( - "github.com/spf13/cobra" - bolt "go.etcd.io/bbolt" - - "github.com/twpayne/chezmoi/internal/chezmoi" -) - -var verifyCmd = &cobra.Command{ - Use: "verify [targets...]", - Short: "Exit with success if the destination state matches the target state, fail otherwise", - Long: mustGetLongHelp("verify"), - Example: getExample("verify"), - PreRunE: config.ensureNoError, - RunE: config.runVerifyCmd, -} - -func init() { - rootCmd.AddCommand(verifyCmd) - - markRemainingZshCompPositionalArgumentsAsFiles(verifyCmd, 1) -} - -func (c *Config) runVerifyCmd(cmd *cobra.Command, args []string) error { - mutator := chezmoi.NewAnyMutator(chezmoi.NullMutator{}) - c.mutator = mutator - - persistentState, err := c.getPersistentState(&bolt.Options{ - ReadOnly: true, - }) - if err != nil { - return err - } - defer persistentState.Close() - - if err := c.applyArgs(args, persistentState); err != nil { - return err - } - if mutator.Mutated() { - return errExitFailure - } - return nil -} diff --git a/chezmoi2/cmd/verifycmd.go b/cmd/verifycmd.go similarity index 92% rename from chezmoi2/cmd/verifycmd.go rename to cmd/verifycmd.go index f08fcbac234..bcca20df46a 100644 --- a/chezmoi2/cmd/verifycmd.go +++ b/cmd/verifycmd.go @@ -3,11 +3,11 @@ package cmd import ( "github.com/spf13/cobra" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoi" ) type verifyCmdConfig struct { - include *chezmoi.IncludeSet + include *chezmoi.EntryTypeSet recursive bool } diff --git a/chezmoi2/cmd/verifycmd_test.go b/cmd/verifycmd_test.go similarity index 86% rename from chezmoi2/cmd/verifycmd_test.go rename to cmd/verifycmd_test.go index 57fc17b02d1..b5a23e57e11 100644 --- a/chezmoi2/cmd/verifycmd_test.go +++ b/cmd/verifycmd_test.go @@ -4,10 +4,10 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/twpayne/go-vfs" - "github.com/twpayne/go-vfs/vfst" + "github.com/twpayne/go-vfs/v2" + "github.com/twpayne/go-vfs/v2/vfst" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoitest" + "github.com/twpayne/chezmoi/internal/chezmoitest" ) func TestVerifyCmd(t *testing.T) { diff --git a/completions/chezmoi-completion.bash b/completions/chezmoi-completion.bash index e331c37cc23..c33aa5a9265 100644 --- a/completions/chezmoi-completion.bash +++ b/completions/chezmoi-completion.bash @@ -369,19 +369,30 @@ _chezmoi_add() flags+=("--autotemplate") flags+=("-a") + local_nonpersistent_flags+=("--autotemplate") + local_nonpersistent_flags+=("-a") + flags+=("--create") + local_nonpersistent_flags+=("--create") flags+=("--empty") flags+=("-e") + local_nonpersistent_flags+=("--empty") + local_nonpersistent_flags+=("-e") flags+=("--encrypt") + local_nonpersistent_flags+=("--encrypt") flags+=("--exact") - flags+=("-x") - flags+=("--force") + local_nonpersistent_flags+=("--exact") + flags+=("--follow") flags+=("-f") - flags+=("--prompt") - flags+=("-p") + local_nonpersistent_flags+=("--follow") + local_nonpersistent_flags+=("-f") flags+=("--recursive") flags+=("-r") + local_nonpersistent_flags+=("--recursive") + local_nonpersistent_flags+=("-r") flags+=("--template") flags+=("-T") + local_nonpersistent_flags+=("--template") + local_nonpersistent_flags+=("-T") flags+=("--color=") two_word_flags+=("--color") flags+=("--config=") @@ -391,6 +402,10 @@ _chezmoi_add() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -401,7 +416,21 @@ _chezmoi_add() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") flags+=("--source=") two_word_flags+=("--source") @@ -410,6 +439,9 @@ _chezmoi_add() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") @@ -432,6 +464,16 @@ _chezmoi_apply() flags_with_completion=() flags_completion=() + flags+=("--include=") + two_word_flags+=("--include") + two_word_flags+=("-i") + local_nonpersistent_flags+=("--include") + local_nonpersistent_flags+=("--include=") + local_nonpersistent_flags+=("-i") + flags+=("--recursive") + flags+=("-r") + local_nonpersistent_flags+=("--recursive") + local_nonpersistent_flags+=("-r") flags+=("--color=") two_word_flags+=("--color") flags+=("--config=") @@ -441,6 +483,10 @@ _chezmoi_apply() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -451,7 +497,21 @@ _chezmoi_apply() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") flags+=("--source=") two_word_flags+=("--source") @@ -460,6 +520,9 @@ _chezmoi_apply() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") @@ -482,13 +545,24 @@ _chezmoi_archive() flags_with_completion=() flags_completion=() - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") + flags+=("--format=") + two_word_flags+=("--format") + local_nonpersistent_flags+=("--format") + local_nonpersistent_flags+=("--format=") + flags+=("--gzip") + flags+=("-z") + local_nonpersistent_flags+=("--gzip") + local_nonpersistent_flags+=("-z") + flags+=("--include=") + two_word_flags+=("--include") + two_word_flags+=("-i") + local_nonpersistent_flags+=("--include") + local_nonpersistent_flags+=("--include=") + local_nonpersistent_flags+=("-i") + flags+=("--recursive") + flags+=("-r") + local_nonpersistent_flags+=("--recursive") + local_nonpersistent_flags+=("-r") flags+=("--color=") two_word_flags+=("--color") flags+=("--config=") @@ -498,6 +572,10 @@ _chezmoi_archive() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -508,7 +586,21 @@ _chezmoi_archive() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") flags+=("--source=") two_word_flags+=("--source") @@ -517,6 +609,9 @@ _chezmoi_archive() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") @@ -548,6 +643,10 @@ _chezmoi_cat() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -558,7 +657,21 @@ _chezmoi_cat() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") flags+=("--source=") two_word_flags+=("--source") @@ -567,6 +680,9 @@ _chezmoi_cat() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") @@ -598,6 +714,10 @@ _chezmoi_cd() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -608,7 +728,21 @@ _chezmoi_cd() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") flags+=("--source=") two_word_flags+=("--source") @@ -617,6 +751,9 @@ _chezmoi_cd() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") @@ -648,6 +785,10 @@ _chezmoi_chattr() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -658,7 +799,21 @@ _chezmoi_chattr() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") flags+=("--source=") two_word_flags+=("--source") @@ -667,11 +822,78 @@ _chezmoi_chattr() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") must_have_one_flag=() must_have_one_noun=() + must_have_one_noun+=("+a") + must_have_one_noun+=("+after") + must_have_one_noun+=("+b") + must_have_one_noun+=("+before") + must_have_one_noun+=("+e") + must_have_one_noun+=("+empty") + must_have_one_noun+=("+encrypted") + must_have_one_noun+=("+exact") + must_have_one_noun+=("+executable") + must_have_one_noun+=("+o") + must_have_one_noun+=("+once") + must_have_one_noun+=("+p") + must_have_one_noun+=("+private") + must_have_one_noun+=("+t") + must_have_one_noun+=("+template") + must_have_one_noun+=("+x") + must_have_one_noun+=("-a") + must_have_one_noun+=("-after") + must_have_one_noun+=("-b") + must_have_one_noun+=("-before") + must_have_one_noun+=("-e") + must_have_one_noun+=("-empty") + must_have_one_noun+=("-encrypted") + must_have_one_noun+=("-exact") + must_have_one_noun+=("-executable") + must_have_one_noun+=("-o") + must_have_one_noun+=("-once") + must_have_one_noun+=("-p") + must_have_one_noun+=("-private") + must_have_one_noun+=("-t") + must_have_one_noun+=("-template") + must_have_one_noun+=("-x") + must_have_one_noun+=("a") + must_have_one_noun+=("after") + must_have_one_noun+=("b") + must_have_one_noun+=("before") + must_have_one_noun+=("e") + must_have_one_noun+=("empty") + must_have_one_noun+=("encrypted") + must_have_one_noun+=("exact") + must_have_one_noun+=("executable") + must_have_one_noun+=("noa") + must_have_one_noun+=("noafter") + must_have_one_noun+=("nob") + must_have_one_noun+=("nobefore") + must_have_one_noun+=("noe") + must_have_one_noun+=("noempty") + must_have_one_noun+=("noencrypted") + must_have_one_noun+=("noexact") + must_have_one_noun+=("noexecutable") + must_have_one_noun+=("noo") + must_have_one_noun+=("noonce") + must_have_one_noun+=("nop") + must_have_one_noun+=("noprivate") + must_have_one_noun+=("not") + must_have_one_noun+=("notemplate") + must_have_one_noun+=("nox") + must_have_one_noun+=("o") + must_have_one_noun+=("once") + must_have_one_noun+=("p") + must_have_one_noun+=("private") + must_have_one_noun+=("t") + must_have_one_noun+=("template") + must_have_one_noun+=("x") noun_aliases=() } @@ -693,13 +915,6 @@ _chezmoi_completion() flags+=("-h") local_nonpersistent_flags+=("--help") local_nonpersistent_flags+=("-h") - flags+=("--output=") - two_word_flags+=("--output") - flags_with_completion+=("--output") - flags_completion+=("_filedir") - two_word_flags+=("-o") - flags_with_completion+=("-o") - flags_completion+=("_filedir") flags+=("--color=") two_word_flags+=("--color") flags+=("--config=") @@ -709,6 +924,10 @@ _chezmoi_completion() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -719,7 +938,21 @@ _chezmoi_completion() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") flags+=("--source=") two_word_flags+=("--source") @@ -728,6 +961,9 @@ _chezmoi_completion() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") @@ -756,7 +992,6 @@ _chezmoi_data() flags+=("--format=") two_word_flags+=("--format") - two_word_flags+=("-f") flags+=("--color=") two_word_flags+=("--color") flags+=("--config=") @@ -766,6 +1001,10 @@ _chezmoi_data() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -776,7 +1015,21 @@ _chezmoi_data() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") flags+=("--source=") two_word_flags+=("--source") @@ -785,6 +1038,9 @@ _chezmoi_data() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") @@ -807,10 +1063,16 @@ _chezmoi_diff() flags_with_completion=() flags_completion=() - flags+=("--format=") - two_word_flags+=("--format") - two_word_flags+=("-f") - flags+=("--no-pager") + flags+=("--include=") + two_word_flags+=("--include") + two_word_flags+=("-i") + local_nonpersistent_flags+=("--include") + local_nonpersistent_flags+=("--include=") + local_nonpersistent_flags+=("-i") + flags+=("--recursive") + flags+=("-r") + local_nonpersistent_flags+=("--recursive") + local_nonpersistent_flags+=("-r") flags+=("--color=") two_word_flags+=("--color") flags+=("--config=") @@ -820,6 +1082,10 @@ _chezmoi_diff() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -830,7 +1096,21 @@ _chezmoi_diff() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") flags+=("--source=") two_word_flags+=("--source") @@ -839,6 +1119,9 @@ _chezmoi_diff() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") @@ -870,6 +1153,10 @@ _chezmoi_docs() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -880,7 +1167,21 @@ _chezmoi_docs() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") flags+=("--source=") two_word_flags+=("--source") @@ -889,6 +1190,9 @@ _chezmoi_docs() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") @@ -920,6 +1224,10 @@ _chezmoi_doctor() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -930,7 +1238,21 @@ _chezmoi_doctor() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") flags+=("--source=") two_word_flags+=("--source") @@ -939,6 +1261,9 @@ _chezmoi_doctor() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") @@ -964,8 +1289,19 @@ _chezmoi_dump() flags+=("--format=") two_word_flags+=("--format") two_word_flags+=("-f") + local_nonpersistent_flags+=("--format") + local_nonpersistent_flags+=("--format=") + local_nonpersistent_flags+=("-f") + flags+=("--include=") + two_word_flags+=("--include") + two_word_flags+=("-i") + local_nonpersistent_flags+=("--include") + local_nonpersistent_flags+=("--include=") + local_nonpersistent_flags+=("-i") flags+=("--recursive") flags+=("-r") + local_nonpersistent_flags+=("--recursive") + local_nonpersistent_flags+=("-r") flags+=("--color=") two_word_flags+=("--color") flags+=("--config=") @@ -975,6 +1311,10 @@ _chezmoi_dump() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -985,7 +1325,21 @@ _chezmoi_dump() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") flags+=("--source=") two_word_flags+=("--source") @@ -994,6 +1348,9 @@ _chezmoi_dump() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") @@ -1018,10 +1375,14 @@ _chezmoi_edit() flags+=("--apply") flags+=("-a") - flags+=("--diff") - flags+=("-d") - flags+=("--prompt") - flags+=("-p") + local_nonpersistent_flags+=("--apply") + local_nonpersistent_flags+=("-a") + flags+=("--include=") + two_word_flags+=("--include") + two_word_flags+=("-i") + local_nonpersistent_flags+=("--include") + local_nonpersistent_flags+=("--include=") + local_nonpersistent_flags+=("-i") flags+=("--color=") two_word_flags+=("--color") flags+=("--config=") @@ -1031,6 +1392,10 @@ _chezmoi_edit() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -1041,7 +1406,21 @@ _chezmoi_edit() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") flags+=("--source=") two_word_flags+=("--source") @@ -1050,6 +1429,9 @@ _chezmoi_edit() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") @@ -1081,6 +1463,10 @@ _chezmoi_edit-config() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -1091,7 +1477,21 @@ _chezmoi_edit-config() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") flags+=("--source=") two_word_flags+=("--source") @@ -1100,6 +1500,9 @@ _chezmoi_edit-config() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") @@ -1124,16 +1527,22 @@ _chezmoi_execute-template() flags+=("--init") flags+=("-i") - flags+=("--output=") - two_word_flags+=("--output") - two_word_flags+=("-o") + local_nonpersistent_flags+=("--init") + local_nonpersistent_flags+=("-i") flags+=("--promptBool=") two_word_flags+=("--promptBool") + local_nonpersistent_flags+=("--promptBool") + local_nonpersistent_flags+=("--promptBool=") flags+=("--promptInt=") two_word_flags+=("--promptInt") + local_nonpersistent_flags+=("--promptInt") + local_nonpersistent_flags+=("--promptInt=") flags+=("--promptString=") two_word_flags+=("--promptString") two_word_flags+=("-p") + local_nonpersistent_flags+=("--promptString") + local_nonpersistent_flags+=("--promptString=") + local_nonpersistent_flags+=("-p") flags+=("--color=") two_word_flags+=("--color") flags+=("--config=") @@ -1143,6 +1552,10 @@ _chezmoi_execute-template() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -1153,7 +1566,21 @@ _chezmoi_execute-template() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") flags+=("--source=") two_word_flags+=("--source") @@ -1162,6 +1589,9 @@ _chezmoi_execute-template() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") @@ -1193,6 +1623,10 @@ _chezmoi_forget() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -1203,7 +1637,21 @@ _chezmoi_forget() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") flags+=("--source=") two_word_flags+=("--source") @@ -1212,6 +1660,9 @@ _chezmoi_forget() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") @@ -1243,6 +1694,10 @@ _chezmoi_git() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -1253,7 +1708,21 @@ _chezmoi_git() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") flags+=("--source=") two_word_flags+=("--source") @@ -1262,6 +1731,9 @@ _chezmoi_git() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") @@ -1293,6 +1765,10 @@ _chezmoi_help() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -1303,7 +1779,21 @@ _chezmoi_help() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") flags+=("--source=") two_word_flags+=("--source") @@ -1312,6 +1802,9 @@ _chezmoi_help() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") @@ -1320,59 +1813,9 @@ _chezmoi_help() noun_aliases=() } -_chezmoi_hg() +_chezmoi_import() { - last_command="chezmoi_hg" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--follow") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi_import() -{ - last_command="chezmoi_import" + last_command="chezmoi_import" command_aliases=() @@ -1385,11 +1828,21 @@ _chezmoi_import() flags_completion=() flags+=("--exact") - flags+=("-x") + local_nonpersistent_flags+=("--exact") + flags+=("--include=") + two_word_flags+=("--include") + two_word_flags+=("-i") + local_nonpersistent_flags+=("--include") + local_nonpersistent_flags+=("--include=") + local_nonpersistent_flags+=("-i") flags+=("--remove-destination") flags+=("-r") + local_nonpersistent_flags+=("--remove-destination") + local_nonpersistent_flags+=("-r") flags+=("--strip-components=") two_word_flags+=("--strip-components") + local_nonpersistent_flags+=("--strip-components") + local_nonpersistent_flags+=("--strip-components=") flags+=("--color=") two_word_flags+=("--color") flags+=("--config=") @@ -1399,6 +1852,10 @@ _chezmoi_import() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -1409,7 +1866,21 @@ _chezmoi_import() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") flags+=("--source=") two_word_flags+=("--source") @@ -1418,6 +1889,9 @@ _chezmoi_import() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") @@ -1441,6 +1915,25 @@ _chezmoi_init() flags_completion=() flags+=("--apply") + flags+=("-a") + local_nonpersistent_flags+=("--apply") + local_nonpersistent_flags+=("-a") + flags+=("--depth=") + two_word_flags+=("--depth") + two_word_flags+=("-d") + local_nonpersistent_flags+=("--depth") + local_nonpersistent_flags+=("--depth=") + local_nonpersistent_flags+=("-d") + flags+=("--one-shot") + local_nonpersistent_flags+=("--one-shot") + flags+=("--purge") + flags+=("-p") + local_nonpersistent_flags+=("--purge") + local_nonpersistent_flags+=("-p") + flags+=("--purge-binary") + flags+=("-P") + local_nonpersistent_flags+=("--purge-binary") + local_nonpersistent_flags+=("-P") flags+=("--color=") two_word_flags+=("--color") flags+=("--config=") @@ -1450,6 +1943,10 @@ _chezmoi_init() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -1460,7 +1957,21 @@ _chezmoi_init() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") flags+=("--source=") two_word_flags+=("--source") @@ -1469,6 +1980,9 @@ _chezmoi_init() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") @@ -1494,6 +2008,9 @@ _chezmoi_managed() flags+=("--include=") two_word_flags+=("--include") two_word_flags+=("-i") + local_nonpersistent_flags+=("--include") + local_nonpersistent_flags+=("--include=") + local_nonpersistent_flags+=("-i") flags+=("--color=") two_word_flags+=("--color") flags+=("--config=") @@ -1503,55 +2020,9 @@ _chezmoi_managed() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--follow") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi_merge() -{ - last_command="chezmoi_merge" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") @@ -1563,111 +2034,21 @@ _chezmoi_merge() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi_purge() -{ - last_command="chezmoi_purge" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") flags+=("--force") - flags+=("-f") - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--follow") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi_remove() -{ - last_command="chezmoi_remove" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--force") - flags+=("-f") - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") + two_word_flags+=("-o") + flags_with_completion+=("-o") flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--follow") flags+=("--remove") flags+=("--source=") two_word_flags+=("--source") @@ -1676,6 +2057,9 @@ _chezmoi_remove() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") @@ -1684,9 +2068,9 @@ _chezmoi_remove() noun_aliases=() } -_chezmoi_secret_bitwarden() +_chezmoi_merge() { - last_command="chezmoi_secret_bitwarden" + last_command="chezmoi_merge" command_aliases=() @@ -1707,55 +2091,9 @@ _chezmoi_secret_bitwarden() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--follow") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi_secret_generic() -{ - last_command="chezmoi_secret_generic" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") @@ -1767,107 +2105,21 @@ _chezmoi_secret_generic() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi_secret_gopass() -{ - last_command="chezmoi_secret_gopass" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") - flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") - flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--follow") - flags+=("--remove") - flags+=("--source=") - two_word_flags+=("--source") - flags_with_completion+=("--source") - flags_completion+=("_filedir -d") - two_word_flags+=("-S") - flags_with_completion+=("-S") - flags_completion+=("_filedir -d") - flags+=("--verbose") - flags+=("-v") - - must_have_one_flag=() - must_have_one_noun=() - noun_aliases=() -} - -_chezmoi_secret_keepassxc() -{ - last_command="chezmoi_secret_keepassxc" - - command_aliases=() - - commands=() - - flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - - flags+=("--color=") - two_word_flags+=("--color") - flags+=("--config=") - two_word_flags+=("--config") - flags_with_completion+=("--config") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") flags_completion+=("_filedir") - two_word_flags+=("-c") - flags_with_completion+=("-c") + two_word_flags+=("-o") + flags_with_completion+=("-o") flags_completion+=("_filedir") - flags+=("--debug") - flags+=("--destination=") - two_word_flags+=("--destination") - flags_with_completion+=("--destination") - flags_completion+=("_filedir -d") - two_word_flags+=("-D") - flags_with_completion+=("-D") - flags_completion+=("_filedir -d") - flags+=("--dry-run") - flags+=("-n") - flags+=("--follow") flags+=("--remove") flags+=("--source=") two_word_flags+=("--source") @@ -1876,6 +2128,9 @@ _chezmoi_secret_keepassxc() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") @@ -1884,9 +2139,9 @@ _chezmoi_secret_keepassxc() noun_aliases=() } -_chezmoi_secret_keyring_get() +_chezmoi_purge() { - last_command="chezmoi_secret_keyring_get" + last_command="chezmoi_purge" command_aliases=() @@ -1898,6 +2153,10 @@ _chezmoi_secret_keyring_get() flags_with_completion=() flags_completion=() + flags+=("--binary") + flags+=("-P") + local_nonpersistent_flags+=("--binary") + local_nonpersistent_flags+=("-P") flags+=("--color=") two_word_flags+=("--color") flags+=("--config=") @@ -1907,6 +2166,10 @@ _chezmoi_secret_keyring_get() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -1917,10 +2180,22 @@ _chezmoi_secret_keyring_get() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") - flags+=("--service=") - two_word_flags+=("--service") flags+=("--source=") two_word_flags+=("--source") flags_with_completion+=("--source") @@ -1928,8 +2203,9 @@ _chezmoi_secret_keyring_get() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") - flags+=("--user=") - two_word_flags+=("--user") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") @@ -1938,9 +2214,9 @@ _chezmoi_secret_keyring_get() noun_aliases=() } -_chezmoi_secret_keyring_set() +_chezmoi_remove() { - last_command="chezmoi_secret_keyring_set" + last_command="chezmoi_remove" command_aliases=() @@ -1952,8 +2228,6 @@ _chezmoi_secret_keyring_set() flags_with_completion=() flags_completion=() - flags+=("--value=") - two_word_flags+=("--value") flags+=("--color=") two_word_flags+=("--color") flags+=("--config=") @@ -1963,6 +2237,10 @@ _chezmoi_secret_keyring_set() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -1973,10 +2251,22 @@ _chezmoi_secret_keyring_set() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") - flags+=("--service=") - two_word_flags+=("--service") flags+=("--source=") two_word_flags+=("--source") flags_with_completion+=("--source") @@ -1984,8 +2274,9 @@ _chezmoi_secret_keyring_set() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") - flags+=("--user=") - two_word_flags+=("--user") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") @@ -1994,15 +2285,13 @@ _chezmoi_secret_keyring_set() noun_aliases=() } -_chezmoi_secret_keyring() +_chezmoi_secret_keyring_get() { - last_command="chezmoi_secret_keyring" + last_command="chezmoi_secret_keyring_get" command_aliases=() commands=() - commands+=("get") - commands+=("set") flags=() two_word_flags=() @@ -2010,10 +2299,6 @@ _chezmoi_secret_keyring() flags_with_completion=() flags_completion=() - flags+=("--service=") - two_word_flags+=("--service") - flags+=("--user=") - two_word_flags+=("--user") flags+=("--color=") two_word_flags+=("--color") flags+=("--config=") @@ -2023,6 +2308,10 @@ _chezmoi_secret_keyring() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -2033,8 +2322,24 @@ _chezmoi_secret_keyring() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") + flags+=("--service=") + two_word_flags+=("--service") flags+=("--source=") two_word_flags+=("--source") flags_with_completion+=("--source") @@ -2042,19 +2347,22 @@ _chezmoi_secret_keyring() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") + flags+=("--user=") + two_word_flags+=("--user") flags+=("--verbose") flags+=("-v") must_have_one_flag=() - must_have_one_flag+=("--service=") - must_have_one_flag+=("--user=") must_have_one_noun=() noun_aliases=() } -_chezmoi_secret_lastpass() +_chezmoi_secret_keyring_set() { - last_command="chezmoi_secret_lastpass" + last_command="chezmoi_secret_keyring_set" command_aliases=() @@ -2075,6 +2383,10 @@ _chezmoi_secret_lastpass() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -2085,8 +2397,24 @@ _chezmoi_secret_lastpass() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") + flags+=("--service=") + two_word_flags+=("--service") flags+=("--source=") two_word_flags+=("--source") flags_with_completion+=("--source") @@ -2094,6 +2422,11 @@ _chezmoi_secret_lastpass() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") + flags+=("--user=") + two_word_flags+=("--user") flags+=("--verbose") flags+=("-v") @@ -2102,13 +2435,15 @@ _chezmoi_secret_lastpass() noun_aliases=() } -_chezmoi_secret_onepassword() +_chezmoi_secret_keyring() { - last_command="chezmoi_secret_onepassword" + last_command="chezmoi_secret_keyring" command_aliases=() commands=() + commands+=("get") + commands+=("set") flags=() two_word_flags=() @@ -2116,6 +2451,10 @@ _chezmoi_secret_onepassword() flags_with_completion=() flags_completion=() + flags+=("--service=") + two_word_flags+=("--service") + flags+=("--user=") + two_word_flags+=("--user") flags+=("--color=") two_word_flags+=("--color") flags+=("--config=") @@ -2125,6 +2464,10 @@ _chezmoi_secret_onepassword() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -2135,7 +2478,21 @@ _chezmoi_secret_onepassword() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") flags+=("--source=") two_word_flags+=("--source") @@ -2144,21 +2501,27 @@ _chezmoi_secret_onepassword() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") must_have_one_flag=() + must_have_one_flag+=("--service=") + must_have_one_flag+=("--user=") must_have_one_noun=() noun_aliases=() } -_chezmoi_secret_pass() +_chezmoi_secret() { - last_command="chezmoi_secret_pass" + last_command="chezmoi_secret" command_aliases=() commands=() + commands+=("keyring") flags=() two_word_flags=() @@ -2175,6 +2538,10 @@ _chezmoi_secret_pass() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -2185,7 +2552,21 @@ _chezmoi_secret_pass() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") flags+=("--source=") two_word_flags+=("--source") @@ -2194,6 +2575,9 @@ _chezmoi_secret_pass() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") @@ -2202,9 +2586,9 @@ _chezmoi_secret_pass() noun_aliases=() } -_chezmoi_secret_vault() +_chezmoi_source-path() { - last_command="chezmoi_secret_vault" + last_command="chezmoi_source-path" command_aliases=() @@ -2225,6 +2609,10 @@ _chezmoi_secret_vault() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -2235,7 +2623,21 @@ _chezmoi_secret_vault() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") flags+=("--source=") two_word_flags+=("--source") @@ -2244,6 +2646,9 @@ _chezmoi_secret_vault() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") @@ -2252,22 +2657,13 @@ _chezmoi_secret_vault() noun_aliases=() } -_chezmoi_secret() +_chezmoi_state_dump() { - last_command="chezmoi_secret" + last_command="chezmoi_state_dump" command_aliases=() commands=() - commands+=("bitwarden") - commands+=("generic") - commands+=("gopass") - commands+=("keepassxc") - commands+=("keyring") - commands+=("lastpass") - commands+=("onepassword") - commands+=("pass") - commands+=("vault") flags=() two_word_flags=() @@ -2275,6 +2671,9 @@ _chezmoi_secret() flags_with_completion=() flags_completion=() + flags+=("--format=") + two_word_flags+=("--format") + two_word_flags+=("-f") flags+=("--color=") two_word_flags+=("--color") flags+=("--config=") @@ -2284,6 +2683,10 @@ _chezmoi_secret() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -2294,7 +2697,21 @@ _chezmoi_secret() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") flags+=("--source=") two_word_flags+=("--source") @@ -2303,6 +2720,9 @@ _chezmoi_secret() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") @@ -2311,9 +2731,9 @@ _chezmoi_secret() noun_aliases=() } -_chezmoi_source() +_chezmoi_state_reset() { - last_command="chezmoi_source" + last_command="chezmoi_state_reset" command_aliases=() @@ -2334,6 +2754,10 @@ _chezmoi_source() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -2344,7 +2768,21 @@ _chezmoi_source() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") flags+=("--source=") two_word_flags+=("--source") @@ -2353,6 +2791,9 @@ _chezmoi_source() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") @@ -2361,13 +2802,15 @@ _chezmoi_source() noun_aliases=() } -_chezmoi_source-path() +_chezmoi_state() { - last_command="chezmoi_source-path" + last_command="chezmoi_state" command_aliases=() commands=() + commands+=("dump") + commands+=("reset") flags=() two_word_flags=() @@ -2384,6 +2827,10 @@ _chezmoi_source-path() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -2394,7 +2841,21 @@ _chezmoi_source-path() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") flags+=("--source=") two_word_flags+=("--source") @@ -2403,6 +2864,9 @@ _chezmoi_source-path() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") @@ -2411,9 +2875,9 @@ _chezmoi_source-path() noun_aliases=() } -_chezmoi_unmanaged() +_chezmoi_status() { - last_command="chezmoi_unmanaged" + last_command="chezmoi_status" command_aliases=() @@ -2425,6 +2889,16 @@ _chezmoi_unmanaged() flags_with_completion=() flags_completion=() + flags+=("--include=") + two_word_flags+=("--include") + two_word_flags+=("-i") + local_nonpersistent_flags+=("--include") + local_nonpersistent_flags+=("--include=") + local_nonpersistent_flags+=("-i") + flags+=("--recursive") + flags+=("-r") + local_nonpersistent_flags+=("--recursive") + local_nonpersistent_flags+=("-r") flags+=("--color=") two_word_flags+=("--color") flags+=("--config=") @@ -2434,6 +2908,10 @@ _chezmoi_unmanaged() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -2444,7 +2922,21 @@ _chezmoi_unmanaged() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") flags+=("--source=") two_word_flags+=("--source") @@ -2453,6 +2945,9 @@ _chezmoi_unmanaged() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") @@ -2461,9 +2956,9 @@ _chezmoi_unmanaged() noun_aliases=() } -_chezmoi_update() +_chezmoi_unmanaged() { - last_command="chezmoi_update" + last_command="chezmoi_unmanaged" command_aliases=() @@ -2475,8 +2970,6 @@ _chezmoi_update() flags_with_completion=() flags_completion=() - flags+=("--apply") - flags+=("-a") flags+=("--color=") two_word_flags+=("--color") flags+=("--config=") @@ -2486,6 +2979,10 @@ _chezmoi_update() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -2496,7 +2993,21 @@ _chezmoi_update() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") flags+=("--source=") two_word_flags+=("--source") @@ -2505,6 +3016,9 @@ _chezmoi_update() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") @@ -2513,9 +3027,9 @@ _chezmoi_update() noun_aliases=() } -_chezmoi_upgrade() +_chezmoi_update() { - last_command="chezmoi_upgrade" + last_command="chezmoi_update" command_aliases=() @@ -2527,17 +3041,20 @@ _chezmoi_upgrade() flags_with_completion=() flags_completion=() - flags+=("--force") - flags+=("-f") - flags+=("--method=") - two_word_flags+=("--method") - two_word_flags+=("-m") - flags+=("--owner=") - two_word_flags+=("--owner") - two_word_flags+=("-o") - flags+=("--repo=") - two_word_flags+=("--repo") - two_word_flags+=("-r") + flags+=("--apply") + flags+=("-a") + local_nonpersistent_flags+=("--apply") + local_nonpersistent_flags+=("-a") + flags+=("--include=") + two_word_flags+=("--include") + two_word_flags+=("-i") + local_nonpersistent_flags+=("--include") + local_nonpersistent_flags+=("--include=") + local_nonpersistent_flags+=("-i") + flags+=("--recursive") + flags+=("-r") + local_nonpersistent_flags+=("--recursive") + local_nonpersistent_flags+=("-r") flags+=("--color=") two_word_flags+=("--color") flags+=("--config=") @@ -2547,6 +3064,10 @@ _chezmoi_upgrade() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -2557,7 +3078,21 @@ _chezmoi_upgrade() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") flags+=("--source=") two_word_flags+=("--source") @@ -2566,6 +3101,9 @@ _chezmoi_upgrade() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") @@ -2588,6 +3126,16 @@ _chezmoi_verify() flags_with_completion=() flags_completion=() + flags+=("--include=") + two_word_flags+=("--include") + two_word_flags+=("-i") + local_nonpersistent_flags+=("--include") + local_nonpersistent_flags+=("--include=") + local_nonpersistent_flags+=("-i") + flags+=("--recursive") + flags+=("-r") + local_nonpersistent_flags+=("--recursive") + local_nonpersistent_flags+=("-r") flags+=("--color=") two_word_flags+=("--color") flags+=("--config=") @@ -2597,6 +3145,10 @@ _chezmoi_verify() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -2607,7 +3159,21 @@ _chezmoi_verify() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") flags+=("--source=") two_word_flags+=("--source") @@ -2616,6 +3182,9 @@ _chezmoi_verify() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") @@ -2657,7 +3226,6 @@ _chezmoi_root_command() fi commands+=("git") commands+=("help") - commands+=("hg") commands+=("import") commands+=("init") commands+=("managed") @@ -2669,11 +3237,11 @@ _chezmoi_root_command() aliashash["rm"]="remove" fi commands+=("secret") - commands+=("source") commands+=("source-path") + commands+=("state") + commands+=("status") commands+=("unmanaged") commands+=("update") - commands+=("upgrade") commands+=("verify") flags=() @@ -2691,6 +3259,10 @@ _chezmoi_root_command() two_word_flags+=("-c") flags_with_completion+=("-c") flags_completion+=("_filedir") + flags+=("--cpu-profile=") + two_word_flags+=("--cpu-profile") + flags_with_completion+=("--cpu-profile") + flags_completion+=("_filedir") flags+=("--debug") flags+=("--destination=") two_word_flags+=("--destination") @@ -2701,7 +3273,21 @@ _chezmoi_root_command() flags_completion+=("_filedir -d") flags+=("--dry-run") flags+=("-n") - flags+=("--follow") + flags+=("--exclude=") + two_word_flags+=("--exclude") + two_word_flags+=("-x") + flags+=("--force") + flags+=("--keep-going") + flags+=("-k") + flags+=("--no-pager") + flags+=("--no-tty") + flags+=("--output=") + two_word_flags+=("--output") + flags_with_completion+=("--output") + flags_completion+=("_filedir") + two_word_flags+=("-o") + flags_with_completion+=("-o") + flags_completion+=("_filedir") flags+=("--remove") flags+=("--source=") two_word_flags+=("--source") @@ -2710,6 +3296,9 @@ _chezmoi_root_command() two_word_flags+=("-S") flags_with_completion+=("-S") flags_completion+=("_filedir -d") + flags+=("--source-path") + flags+=("--use-builtin-git=") + two_word_flags+=("--use-builtin-git") flags+=("--verbose") flags+=("-v") diff --git a/completions/chezmoi.ps1 b/completions/chezmoi.ps1 index f69dd053769..d5a28904f8c 100644 --- a/completions/chezmoi.ps1 +++ b/completions/chezmoi.ps1 @@ -1,225 +1,300 @@ -# powershell completion for chezmoi -*- shell-script -*- - -function __chezmoi_debug { - if ($env:BASH_COMP_DEBUG_FILE) { - "$args" | Out-File -Append -FilePath "$env:BASH_COMP_DEBUG_FILE" - } -} - -filter __chezmoi_escapeStringWithSpecialChars { - $_ -replace '\s|#|@|\$|;|,|''|\{|\}|\(|\)|"|`|\||<|>|&','`$&' -} - -Register-ArgumentCompleter -CommandName 'chezmoi' -ScriptBlock { - param( - $WordToComplete, - $CommandAst, - $CursorPosition - ) - - # Get the current command line and convert into a string - $Command = $CommandAst.CommandElements - $Command = "$Command" - - __chezmoi_debug "" - __chezmoi_debug "========= starting completion logic ==========" - __chezmoi_debug "WordToComplete: $WordToComplete Command: $Command CursorPosition: $CursorPosition" - - # The user could have moved the cursor backwards on the command-line. - # We need to trigger completion from the $CursorPosition location, so we need - # to truncate the command-line ($Command) up to the $CursorPosition location. - # Make sure the $Command is longer then the $CursorPosition before we truncate. - # This happens because the $Command does not include the last space. - if ($Command.Length -gt $CursorPosition) { - $Command=$Command.Substring(0,$CursorPosition) - } - __chezmoi_debug "Truncated command: $Command" - - $ShellCompDirectiveError=1 - $ShellCompDirectiveNoSpace=2 - $ShellCompDirectiveNoFileComp=4 - $ShellCompDirectiveFilterFileExt=8 - $ShellCompDirectiveFilterDirs=16 - - # Prepare the command to request completions for the program. - # Split the command at the first space to separate the program and arguments. - $Program,$Arguments = $Command.Split(" ",2) - $RequestComp="$Program __completeNoDesc $Arguments" - __chezmoi_debug "RequestComp: $RequestComp" - - # we cannot use $WordToComplete because it - # has the wrong values if the cursor was moved - # so use the last argument - if ($WordToComplete -ne "" ) { - $WordToComplete = $Arguments.Split(" ")[-1] - } - __chezmoi_debug "New WordToComplete: $WordToComplete" - - - # Check for flag with equal sign - $IsEqualFlag = ($WordToComplete -Like "--*=*" ) - if ( $IsEqualFlag ) { - __chezmoi_debug "Completing equal sign flag" - # Remove the flag part - $Flag,$WordToComplete = $WordToComplete.Split("=",2) - } - - if ( $WordToComplete -eq "" -And ( -Not $IsEqualFlag )) { - # If the last parameter is complete (there is a space following it) - # We add an extra empty parameter so we can indicate this to the go method. - __chezmoi_debug "Adding extra empty parameter" - # We need to use `"`" to pass an empty argument a "" or '' does not work!!! - $RequestComp="$RequestComp" + ' `"`"' - } - - __chezmoi_debug "Calling $RequestComp" - #call the command store the output in $out and redirect stderr and stdout to null - # $Out is an array contains each line per element - Invoke-Expression -OutVariable out "$RequestComp" 2>&1 | Out-Null - - - # get directive from last line - [int]$Directive = $Out[-1].TrimStart(':') - if ($Directive -eq "") { - # There is no directive specified - $Directive = 0 - } - __chezmoi_debug "The completion directive is: $Directive" - - # remove directive (last element) from out - $Out = $Out | Where-Object { $_ -ne $Out[-1] } - __chezmoi_debug "The completions are: $Out" - - if (($Directive -band $ShellCompDirectiveError) -ne 0 ) { - # Error code. No completion. - __chezmoi_debug "Received error from custom completion go code" - return - } - - $Longest = 0 - $Values = $Out | ForEach-Object { - #Split the output in name and description - $Name, $Description = $_.Split("`t",2) - __chezmoi_debug "Name: $Name Description: $Description" - - # Look for the longest completion so that we can format things nicely - if ($Longest -lt $Name.Length) { - $Longest = $Name.Length - } - - # Set the description to a one space string if there is none set. - # This is needed because the CompletionResult does not accept an empty string as argument - if (-Not $Description) { - $Description = " " - } - @{Name="$Name";Description="$Description"} - } - - - $Space = " " - if (($Directive -band $ShellCompDirectiveNoSpace) -ne 0 ) { - # remove the space here - __chezmoi_debug "ShellCompDirectiveNoSpace is called" - $Space = "" - } - - if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) { - __chezmoi_debug "ShellCompDirectiveNoFileComp is called" - - if ($Values.Length -eq 0) { - # Just print an empty string here so the - # shell does not start to complete paths. - # We cannot use CompletionResult here because - # it does not accept an empty string as argument. - "" - return - } - } - - if ((($Directive -band $ShellCompDirectiveFilterFileExt) -ne 0 ) -or - (($Directive -band $ShellCompDirectiveFilterDirs) -ne 0 )) { - __chezmoi_debug "ShellCompDirectiveFilterFileExt ShellCompDirectiveFilterDirs are not supported" - - # return here to prevent the completion of the extensions - return - } - - $Values = $Values | Where-Object { - # filter the result - $_.Name -like "$WordToComplete*" - - # Join the flag back if we have a equal sign flag - if ( $IsEqualFlag ) { - __chezmoi_debug "Join the equal sign flag back to the completion value" - $_.Name = $Flag + "=" + $_.Name - } - } - - # Get the current mode - $Mode = (Get-PSReadLineKeyHandler | Where-Object {$_.Key -eq "Tab" }).Function - __chezmoi_debug "Mode: $Mode" - - $Values | ForEach-Object { - - # store temporay because switch will overwrite $_ - $comp = $_ - - # PowerShell supports three different completion modes - # - TabCompleteNext (default windows style - on each key press the next option is displayed) - # - Complete (works like bash) - # - MenuComplete (works like zsh) - # You set the mode with Set-PSReadLineKeyHandler -Key Tab -Function <mode> - - # CompletionResult Arguments: - # 1) CompletionText text to be used as the auto completion result - # 2) ListItemText text to be displayed in the suggestion list - # 3) ResultType type of completion result - # 4) ToolTip text for the tooltip with details about the object - - switch ($Mode) { - - # bash like - "Complete" { - - if ($Values.Length -eq 1) { - __chezmoi_debug "Only one completion left" - - # insert space after value - [System.Management.Automation.CompletionResult]::new($($comp.Name | __chezmoi_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)") - - } else { - # Add the proper number of spaces to align the descriptions - while($comp.Name.Length -lt $Longest) { - $comp.Name = $comp.Name + " " - } - - # Check for empty description and only add parentheses if needed - if ($($comp.Description) -eq " " ) { - $Description = "" - } else { - $Description = " ($($comp.Description))" - } - - [System.Management.Automation.CompletionResult]::new("$($comp.Name)$Description", "$($comp.Name)$Description", 'ParameterValue', "$($comp.Description)") - } - } - - # zsh like - "MenuComplete" { - # insert space after value - # MenuComplete will automatically show the ToolTip of - # the highlighted value at the bottom of the suggestions. - [System.Management.Automation.CompletionResult]::new($($comp.Name | __chezmoi_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)") - } - - # TabCompleteNext and in case we get something unknown - Default { - # Like MenuComplete but we don't want to add a space here because - # the user need to press space anyway to get the completion. - # Description will not be shown because thats not possible with TabCompleteNext - [System.Management.Automation.CompletionResult]::new($($comp.Name | __chezmoi_escapeStringWithSpecialChars), "$($comp.Name)", 'ParameterValue', "$($comp.Description)") +using namespace System.Management.Automation +using namespace System.Management.Automation.Language +Register-ArgumentCompleter -Native -CommandName 'chezmoi' -ScriptBlock { + param($wordToComplete, $commandAst, $cursorPosition) + $commandElements = $commandAst.CommandElements + $command = @( + 'chezmoi' + for ($i = 1; $i -lt $commandElements.Count; $i++) { + $element = $commandElements[$i] + if ($element -isnot [StringConstantExpressionAst] -or + $element.StringConstantType -ne [StringConstantType]::BareWord -or + $element.Value.StartsWith('-')) { + break } + $element.Value + } + ) -join ';' + $completions = @(switch ($command) { + 'chezmoi' { + [CompletionResult]::new('--color', 'color', [CompletionResultType]::ParameterName, 'colorize diffs') + [CompletionResult]::new('-c', 'c', [CompletionResultType]::ParameterName, 'config file') + [CompletionResult]::new('--config', 'config', [CompletionResultType]::ParameterName, 'config file') + [CompletionResult]::new('--cpu-profile', 'cpu-profile', [CompletionResultType]::ParameterName, 'write CPU profile to file') + [CompletionResult]::new('--debug', 'debug', [CompletionResultType]::ParameterName, 'write debug logs') + [CompletionResult]::new('-D', 'D', [CompletionResultType]::ParameterName, 'destination directory') + [CompletionResult]::new('--destination', 'destination', [CompletionResultType]::ParameterName, 'destination directory') + [CompletionResult]::new('-n', 'n', [CompletionResultType]::ParameterName, 'dry run') + [CompletionResult]::new('--dry-run', 'dry-run', [CompletionResultType]::ParameterName, 'dry run') + [CompletionResult]::new('-x', 'x', [CompletionResultType]::ParameterName, 'exclude entry types') + [CompletionResult]::new('--exclude', 'exclude', [CompletionResultType]::ParameterName, 'exclude entry types') + [CompletionResult]::new('--force', 'force', [CompletionResultType]::ParameterName, 'force') + [CompletionResult]::new('-k', 'k', [CompletionResultType]::ParameterName, 'keep going as far as possible after an error') + [CompletionResult]::new('--keep-going', 'keep-going', [CompletionResultType]::ParameterName, 'keep going as far as possible after an error') + [CompletionResult]::new('--no-pager', 'no-pager', [CompletionResultType]::ParameterName, 'do not use the pager') + [CompletionResult]::new('--no-tty', 'no-tty', [CompletionResultType]::ParameterName, 'don''t attempt to get a TTY for reading passwords') + [CompletionResult]::new('-o', 'o', [CompletionResultType]::ParameterName, 'output file') + [CompletionResult]::new('--output', 'output', [CompletionResultType]::ParameterName, 'output file') + [CompletionResult]::new('--remove', 'remove', [CompletionResultType]::ParameterName, 'remove targets') + [CompletionResult]::new('-S', 'S', [CompletionResultType]::ParameterName, 'source directory') + [CompletionResult]::new('--source', 'source', [CompletionResultType]::ParameterName, 'source directory') + [CompletionResult]::new('--source-path', 'source-path', [CompletionResultType]::ParameterName, 'specify targets by source path') + [CompletionResult]::new('--use-builtin-git', 'use-builtin-git', [CompletionResultType]::ParameterName, 'use builtin git') + [CompletionResult]::new('-v', 'v', [CompletionResultType]::ParameterName, 'verbose') + [CompletionResult]::new('--verbose', 'verbose', [CompletionResultType]::ParameterName, 'verbose') + [CompletionResult]::new('add', 'add', [CompletionResultType]::ParameterValue, 'Add an existing file, directory, or symlink to the source state') + [CompletionResult]::new('apply', 'apply', [CompletionResultType]::ParameterValue, 'Update the destination directory to match the target state') + [CompletionResult]::new('archive', 'archive', [CompletionResultType]::ParameterValue, 'Generate a tar archive of the target state') + [CompletionResult]::new('cat', 'cat', [CompletionResultType]::ParameterValue, 'Print the target contents of a file or symlink') + [CompletionResult]::new('cd', 'cd', [CompletionResultType]::ParameterValue, 'Launch a shell in the source directory') + [CompletionResult]::new('chattr', 'chattr', [CompletionResultType]::ParameterValue, 'Change the attributes of a target in the source state') + [CompletionResult]::new('completion', 'completion', [CompletionResultType]::ParameterValue, 'Generate shell completion code') + [CompletionResult]::new('data', 'data', [CompletionResultType]::ParameterValue, 'Print the template data') + [CompletionResult]::new('diff', 'diff', [CompletionResultType]::ParameterValue, 'Print the diff between the target state and the destination state') + [CompletionResult]::new('docs', 'docs', [CompletionResultType]::ParameterValue, 'Print documentation') + [CompletionResult]::new('doctor', 'doctor', [CompletionResultType]::ParameterValue, 'Check your system for potential problems') + [CompletionResult]::new('dump', 'dump', [CompletionResultType]::ParameterValue, 'Generate a dump of the target state') + [CompletionResult]::new('edit', 'edit', [CompletionResultType]::ParameterValue, 'Edit the source state of a target') + [CompletionResult]::new('edit-config', 'edit-config', [CompletionResultType]::ParameterValue, 'Edit the configuration file') + [CompletionResult]::new('execute-template', 'execute-template', [CompletionResultType]::ParameterValue, 'Execute the given template(s)') + [CompletionResult]::new('forget', 'forget', [CompletionResultType]::ParameterValue, 'Remove a target from the source state') + [CompletionResult]::new('git', 'git', [CompletionResultType]::ParameterValue, 'Run git in the source directory') + [CompletionResult]::new('help', 'help', [CompletionResultType]::ParameterValue, 'Print help about a command') + [CompletionResult]::new('import', 'import', [CompletionResultType]::ParameterValue, 'Import a tar archive into the source state') + [CompletionResult]::new('init', 'init', [CompletionResultType]::ParameterValue, 'Setup the source directory and update the destination directory to match the target state') + [CompletionResult]::new('managed', 'managed', [CompletionResultType]::ParameterValue, 'List the managed entries in the destination directory') + [CompletionResult]::new('merge', 'merge', [CompletionResultType]::ParameterValue, 'Perform a three-way merge between the destination state, the source state, and the target state') + [CompletionResult]::new('purge', 'purge', [CompletionResultType]::ParameterValue, 'Purge chezmoi''s configuration and data') + [CompletionResult]::new('remove', 'remove', [CompletionResultType]::ParameterValue, 'Remove a target from the source state and the destination directory') + [CompletionResult]::new('secret', 'secret', [CompletionResultType]::ParameterValue, 'Interact with a secret manager') + [CompletionResult]::new('source-path', 'source-path', [CompletionResultType]::ParameterValue, 'Print the path of a target in the source state') + [CompletionResult]::new('state', 'state', [CompletionResultType]::ParameterValue, 'Manipulate the persistent state') + [CompletionResult]::new('status', 'status', [CompletionResultType]::ParameterValue, 'Show the status of targets') + [CompletionResult]::new('unmanaged', 'unmanaged', [CompletionResultType]::ParameterValue, 'List the unmanaged files in the destination directory') + [CompletionResult]::new('update', 'update', [CompletionResultType]::ParameterValue, 'Pull and apply any changes') + [CompletionResult]::new('verify', 'verify', [CompletionResultType]::ParameterValue, 'Exit with success if the destination state matches the target state, fail otherwise') + break + } + 'chezmoi;add' { + [CompletionResult]::new('-a', 'a', [CompletionResultType]::ParameterName, 'auto generate the template when adding files as templates') + [CompletionResult]::new('--autotemplate', 'autotemplate', [CompletionResultType]::ParameterName, 'auto generate the template when adding files as templates') + [CompletionResult]::new('--create', 'create', [CompletionResultType]::ParameterName, 'add files that should exist, irrespective of their contents') + [CompletionResult]::new('-e', 'e', [CompletionResultType]::ParameterName, 'add empty files') + [CompletionResult]::new('--empty', 'empty', [CompletionResultType]::ParameterName, 'add empty files') + [CompletionResult]::new('--encrypt', 'encrypt', [CompletionResultType]::ParameterName, 'encrypt files') + [CompletionResult]::new('--exact', 'exact', [CompletionResultType]::ParameterName, 'add directories exactly') + [CompletionResult]::new('-f', 'f', [CompletionResultType]::ParameterName, 'add symlink targets instead of symlinks') + [CompletionResult]::new('--follow', 'follow', [CompletionResultType]::ParameterName, 'add symlink targets instead of symlinks') + [CompletionResult]::new('-r', 'r', [CompletionResultType]::ParameterName, 'recursive') + [CompletionResult]::new('--recursive', 'recursive', [CompletionResultType]::ParameterName, 'recursive') + [CompletionResult]::new('-T', 'T', [CompletionResultType]::ParameterName, 'add files as templates') + [CompletionResult]::new('--template', 'template', [CompletionResultType]::ParameterName, 'add files as templates') + break + } + 'chezmoi;apply' { + [CompletionResult]::new('-i', 'i', [CompletionResultType]::ParameterName, 'include entry types') + [CompletionResult]::new('--include', 'include', [CompletionResultType]::ParameterName, 'include entry types') + [CompletionResult]::new('-r', 'r', [CompletionResultType]::ParameterName, 'recursive') + [CompletionResult]::new('--recursive', 'recursive', [CompletionResultType]::ParameterName, 'recursive') + break + } + 'chezmoi;archive' { + [CompletionResult]::new('--format', 'format', [CompletionResultType]::ParameterName, 'format (tar or zip)') + [CompletionResult]::new('-z', 'z', [CompletionResultType]::ParameterName, 'compress the output with gzip') + [CompletionResult]::new('--gzip', 'gzip', [CompletionResultType]::ParameterName, 'compress the output with gzip') + [CompletionResult]::new('-i', 'i', [CompletionResultType]::ParameterName, 'include entry types') + [CompletionResult]::new('--include', 'include', [CompletionResultType]::ParameterName, 'include entry types') + [CompletionResult]::new('-r', 'r', [CompletionResultType]::ParameterName, 'recursive') + [CompletionResult]::new('--recursive', 'recursive', [CompletionResultType]::ParameterName, 'recursive') + break + } + 'chezmoi;cat' { + break + } + 'chezmoi;cd' { + break + } + 'chezmoi;chattr' { + break + } + 'chezmoi;completion' { + [CompletionResult]::new('--color', 'color', [CompletionResultType]::ParameterName, 'colorize diffs') + [CompletionResult]::new('-c', 'c', [CompletionResultType]::ParameterName, 'config file') + [CompletionResult]::new('--config', 'config', [CompletionResultType]::ParameterName, 'config file') + [CompletionResult]::new('--cpu-profile', 'cpu-profile', [CompletionResultType]::ParameterName, 'write CPU profile to file') + [CompletionResult]::new('--debug', 'debug', [CompletionResultType]::ParameterName, 'write debug logs') + [CompletionResult]::new('-D', 'D', [CompletionResultType]::ParameterName, 'destination directory') + [CompletionResult]::new('--destination', 'destination', [CompletionResultType]::ParameterName, 'destination directory') + [CompletionResult]::new('-n', 'n', [CompletionResultType]::ParameterName, 'dry run') + [CompletionResult]::new('--dry-run', 'dry-run', [CompletionResultType]::ParameterName, 'dry run') + [CompletionResult]::new('-x', 'x', [CompletionResultType]::ParameterName, 'exclude entry types') + [CompletionResult]::new('--exclude', 'exclude', [CompletionResultType]::ParameterName, 'exclude entry types') + [CompletionResult]::new('--force', 'force', [CompletionResultType]::ParameterName, 'force') + [CompletionResult]::new('-h', 'h', [CompletionResultType]::ParameterName, 'help for completion') + [CompletionResult]::new('--help', 'help', [CompletionResultType]::ParameterName, 'help for completion') + [CompletionResult]::new('-k', 'k', [CompletionResultType]::ParameterName, 'keep going as far as possible after an error') + [CompletionResult]::new('--keep-going', 'keep-going', [CompletionResultType]::ParameterName, 'keep going as far as possible after an error') + [CompletionResult]::new('--no-pager', 'no-pager', [CompletionResultType]::ParameterName, 'do not use the pager') + [CompletionResult]::new('--no-tty', 'no-tty', [CompletionResultType]::ParameterName, 'don''t attempt to get a TTY for reading passwords') + [CompletionResult]::new('-o', 'o', [CompletionResultType]::ParameterName, 'output file') + [CompletionResult]::new('--output', 'output', [CompletionResultType]::ParameterName, 'output file') + [CompletionResult]::new('--remove', 'remove', [CompletionResultType]::ParameterName, 'remove targets') + [CompletionResult]::new('-S', 'S', [CompletionResultType]::ParameterName, 'source directory') + [CompletionResult]::new('--source', 'source', [CompletionResultType]::ParameterName, 'source directory') + [CompletionResult]::new('--source-path', 'source-path', [CompletionResultType]::ParameterName, 'specify targets by source path') + [CompletionResult]::new('--use-builtin-git', 'use-builtin-git', [CompletionResultType]::ParameterName, 'use builtin git') + [CompletionResult]::new('-v', 'v', [CompletionResultType]::ParameterName, 'verbose') + [CompletionResult]::new('--verbose', 'verbose', [CompletionResultType]::ParameterName, 'verbose') + break + } + 'chezmoi;data' { + break + } + 'chezmoi;diff' { + [CompletionResult]::new('-i', 'i', [CompletionResultType]::ParameterName, 'include entry types') + [CompletionResult]::new('--include', 'include', [CompletionResultType]::ParameterName, 'include entry types') + [CompletionResult]::new('-r', 'r', [CompletionResultType]::ParameterName, 'recursive') + [CompletionResult]::new('--recursive', 'recursive', [CompletionResultType]::ParameterName, 'recursive') + break + } + 'chezmoi;docs' { + break + } + 'chezmoi;doctor' { + break + } + 'chezmoi;dump' { + [CompletionResult]::new('-f', 'f', [CompletionResultType]::ParameterName, 'format (json or yaml)') + [CompletionResult]::new('--format', 'format', [CompletionResultType]::ParameterName, 'format (json or yaml)') + [CompletionResult]::new('-i', 'i', [CompletionResultType]::ParameterName, 'include entry types') + [CompletionResult]::new('--include', 'include', [CompletionResultType]::ParameterName, 'include entry types') + [CompletionResult]::new('-r', 'r', [CompletionResultType]::ParameterName, 'recursive') + [CompletionResult]::new('--recursive', 'recursive', [CompletionResultType]::ParameterName, 'recursive') + break + } + 'chezmoi;edit' { + [CompletionResult]::new('-a', 'a', [CompletionResultType]::ParameterName, 'apply edit after editing') + [CompletionResult]::new('--apply', 'apply', [CompletionResultType]::ParameterName, 'apply edit after editing') + [CompletionResult]::new('-i', 'i', [CompletionResultType]::ParameterName, 'include entry types') + [CompletionResult]::new('--include', 'include', [CompletionResultType]::ParameterName, 'include entry types') + break + } + 'chezmoi;edit-config' { + break + } + 'chezmoi;execute-template' { + [CompletionResult]::new('-i', 'i', [CompletionResultType]::ParameterName, 'simulate chezmoi init') + [CompletionResult]::new('--init', 'init', [CompletionResultType]::ParameterName, 'simulate chezmoi init') + [CompletionResult]::new('--promptBool', 'promptBool', [CompletionResultType]::ParameterName, 'simulate promptBool') + [CompletionResult]::new('--promptInt', 'promptInt', [CompletionResultType]::ParameterName, 'simulate promptInt') + [CompletionResult]::new('-p', 'p', [CompletionResultType]::ParameterName, 'simulate promptString') + [CompletionResult]::new('--promptString', 'promptString', [CompletionResultType]::ParameterName, 'simulate promptString') + break + } + 'chezmoi;forget' { + break + } + 'chezmoi;git' { + break + } + 'chezmoi;help' { + break + } + 'chezmoi;import' { + [CompletionResult]::new('-d', 'd', [CompletionResultType]::ParameterName, 'destination prefix') + [CompletionResult]::new('--destination', 'destination', [CompletionResultType]::ParameterName, 'destination prefix') + [CompletionResult]::new('--exact', 'exact', [CompletionResultType]::ParameterName, 'import directories exactly') + [CompletionResult]::new('-i', 'i', [CompletionResultType]::ParameterName, 'include entry types') + [CompletionResult]::new('--include', 'include', [CompletionResultType]::ParameterName, 'include entry types') + [CompletionResult]::new('-r', 'r', [CompletionResultType]::ParameterName, 'remove destination before import') + [CompletionResult]::new('--remove-destination', 'remove-destination', [CompletionResultType]::ParameterName, 'remove destination before import') + [CompletionResult]::new('--strip-components', 'strip-components', [CompletionResultType]::ParameterName, 'strip components') + break + } + 'chezmoi;init' { + [CompletionResult]::new('-a', 'a', [CompletionResultType]::ParameterName, 'update destination directory') + [CompletionResult]::new('--apply', 'apply', [CompletionResultType]::ParameterName, 'update destination directory') + [CompletionResult]::new('-d', 'd', [CompletionResultType]::ParameterName, 'create a shallow clone') + [CompletionResult]::new('--depth', 'depth', [CompletionResultType]::ParameterName, 'create a shallow clone') + [CompletionResult]::new('--one-shot', 'one-shot', [CompletionResultType]::ParameterName, 'one shot') + [CompletionResult]::new('-p', 'p', [CompletionResultType]::ParameterName, 'purge config and source directories') + [CompletionResult]::new('--purge', 'purge', [CompletionResultType]::ParameterName, 'purge config and source directories') + [CompletionResult]::new('-P', 'P', [CompletionResultType]::ParameterName, 'purge chezmoi binary') + [CompletionResult]::new('--purge-binary', 'purge-binary', [CompletionResultType]::ParameterName, 'purge chezmoi binary') + break + } + 'chezmoi;managed' { + [CompletionResult]::new('-i', 'i', [CompletionResultType]::ParameterName, 'include entry types') + [CompletionResult]::new('--include', 'include', [CompletionResultType]::ParameterName, 'include entry types') + break + } + 'chezmoi;merge' { + break + } + 'chezmoi;purge' { + [CompletionResult]::new('-P', 'P', [CompletionResultType]::ParameterName, 'purge chezmoi executable') + [CompletionResult]::new('--binary', 'binary', [CompletionResultType]::ParameterName, 'purge chezmoi executable') + break + } + 'chezmoi;remove' { + break + } + 'chezmoi;secret' { + [CompletionResult]::new('keyring', 'keyring', [CompletionResultType]::ParameterValue, 'Interact with keyring') + break + } + 'chezmoi;secret;keyring' { + [CompletionResult]::new('get', 'get', [CompletionResultType]::ParameterValue, 'Get a value from keyring') + [CompletionResult]::new('set', 'set', [CompletionResultType]::ParameterValue, 'Set a value in keyring') + break + } + 'chezmoi;secret;keyring;get' { + break + } + 'chezmoi;secret;keyring;set' { + break + } + 'chezmoi;source-path' { + break + } + 'chezmoi;state' { + [CompletionResult]::new('dump', 'dump', [CompletionResultType]::ParameterValue, 'Generate a dump of the persistent state') + [CompletionResult]::new('reset', 'reset', [CompletionResultType]::ParameterValue, 'Reset the persistent state') + break + } + 'chezmoi;state;dump' { + break + } + 'chezmoi;state;reset' { + break + } + 'chezmoi;status' { + [CompletionResult]::new('-i', 'i', [CompletionResultType]::ParameterName, 'include entry types') + [CompletionResult]::new('--include', 'include', [CompletionResultType]::ParameterName, 'include entry types') + [CompletionResult]::new('-r', 'r', [CompletionResultType]::ParameterName, 'recursive') + [CompletionResult]::new('--recursive', 'recursive', [CompletionResultType]::ParameterName, 'recursive') + break + } + 'chezmoi;unmanaged' { + break + } + 'chezmoi;update' { + [CompletionResult]::new('-a', 'a', [CompletionResultType]::ParameterName, 'apply after pulling') + [CompletionResult]::new('--apply', 'apply', [CompletionResultType]::ParameterName, 'apply after pulling') + [CompletionResult]::new('-i', 'i', [CompletionResultType]::ParameterName, 'include entry types') + [CompletionResult]::new('--include', 'include', [CompletionResultType]::ParameterName, 'include entry types') + [CompletionResult]::new('-r', 'r', [CompletionResultType]::ParameterName, 'recursive') + [CompletionResult]::new('--recursive', 'recursive', [CompletionResultType]::ParameterName, 'recursive') + break + } + 'chezmoi;verify' { + [CompletionResult]::new('-i', 'i', [CompletionResultType]::ParameterName, 'include entry types') + [CompletionResult]::new('--include', 'include', [CompletionResultType]::ParameterName, 'include entry types') + [CompletionResult]::new('-r', 'r', [CompletionResultType]::ParameterName, 'recursive') + [CompletionResult]::new('--recursive', 'recursive', [CompletionResultType]::ParameterName, 'recursive') + break } - - } -} + }) + $completions.Where{ $_.CompletionText -like "$wordToComplete*" } | + Sort-Object -Property ListItemText +} \ No newline at end of file diff --git a/docs/CHANGES.md b/docs/CHANGES.md index 1d4f455a87c..32e66ad6431 100644 --- a/docs/CHANGES.md +++ b/docs/CHANGES.md @@ -1,28 +1,102 @@ # chezmoi Changes <!--- toc ---> -* [Upcoming](#upcoming) - * [Default diff format changing from `chezmoi` to `git`.](#default-diff-format-changing-from-chezmoi-to-git) - * [`gpgRecipient` config variable changing to `gpg.recipient`](#gpgrecipient-config-variable-changing-to-gpgrecipient) +* [Go to chezmoi.io](#go-to-chezmoiio) +* [Version 2](#version-2) + * [New features in version 2](#new-features-in-version-2) + * [Changes from version 1](#changes-from-version-1) -## Upcoming +## Go to chezmoi.io -### Default diff format changing from `chezmoi` to `git`. +You are looking at documentation for chezmoi version 2, which hasn't been +released yet. Documentation for the current version of chezmoi is at +[chezmoi.io](https://chezmoi.io/docs/changes/). -Currently chezmoi outputs diffs in its own format, containing a mix of unified -diffs and shell commands. This will be replaced with a [git format -diff](https://git-scm.com/docs/diff-format) in version 2.0.0. +## Version 2 -### `gpgRecipient` config variable changing to `gpg.recipient` +chezmoi version 2 brings many new features and fixes a few corner-case bugs. +Very few, if any, changes should be required to your source directory, +templates, or config file. -The `gpgRecipient` config variable is changing to `gpg.recipient`. To update, -change your config from: +### New features in version 2 - gpgRecipient = "..." +* The new `chezmoi status` command shows you a concise list of differences, much + like `git status`. +* The `chezmoi apply` command warns you if a file has been modified by something + other than chezmoi since chezmoi last wrote it. This makes chezmoi "safe by + default". +* The `chezmoi init` command will try to guess your dotfile repository if you + give it a short argument. For example, `chezmoi init username` is the + equivalent of `chezmoi init https://github.com/username/dotfiles.git`. +* chezmoi includes a builtin `git` command which it will use if it cannot find + `git`. This means that you don't even have to install `git` to setup your + dotfiles on a new machine. +* The new `create_` attribute allows you to create a file with initial content, + but not have it overwritten by `chezmoi apply`. +* The new `modify_` attribute allows you to modify an existing file with a + script, so you can use chezmoi to manage parts, but not all, of a file. +* The new script attributes `before_` and `after_` control when scripts are run + relative to when your files are updated. +* The new `--exclude` option allows you to control what types of target will be + updated. For example `chezmoi apply --exclude=scripts` will cause chezmoi to + not run any scripts and `chezmoi init --apply --exclude=encrypted` will + exclude encrypted files. +* The new `--keep-going` option causes chezmoi to keep going as far as possible + rather than stopping at the first error it encounters. +* The new `--source-path` options allows you to specify targets by source path, + which is useful for editor hooks. +* The new `gitHubKeys` template function allows you to populate your + `~/.ssh/authorized_keys` from your public SSH keys on GitHub. +* The `promptBool` function now also recognizes `y`, `yes`, `on`, `n`, `no`, and + `off` as boolean values. +* The `chezmoi archive` command now includes scripts in the generated archive, + and can generate `.zip` files. +* The new `edit.command` and `edit.args` configuration variables give you more + control over the command invoked by `chezmoi edit`. +* The `chezmoi init` command has a new `--one-shot` option which does a shallow + clone of your dotfiles repo, runs `chezmoi apply`, and then removes your + source and configuration directories. It's the fastest way to set up your + dotfiles on a emphemeral machine and then remove all traces of chezmoi. +* Standard template variables are set on a best-effort basis. If errors are + encountered, chezmoi leaves the variable unset rather than terminating with + the error. +* The new `.chezmoi.version` template variable contains the version of chezmoi. + You can compare versions using [version comparison + functions](https://masterminds.github.io/sprig/semver.html). +* The new `.chezmoi.fqdnHostname` template variables contains the + fully-qualified domain name of the machine, if it can be determined. +* You can now encrypt whole files with + [age](https://github.com/FiloSottile/age). -to: +### Changes from version 1 - [gpg] - recipient = "..." +chezmoi version 2 includes a few minor changes from version 1, mainly to enable +the new functionality and for consistency: -Support for the `gpgRecipient` config variable will be removed in version 2.0.0. +* chezmoi uses a different format to persist its state. Specifically, this means + that all your `run_once_` scripts will be run again the first time you run + `chezmoi apply`. +* `chezmoi add`, and many other commands, are now recursive by default. +* `chezmoi apply` will warn if a file in the destination directory has been + modified since chezmoi last wrote it. To force overwritting, pass the + `--force` option. +* `chezmoi edit` no longer supports the `--prompt` option. +* The only diff format is now `git`. The `diff.format` configuration variable is + ignored. +* Diffs include the contents of scripts that would be run. +* Mercurial support has been removed. +* The `chezmoi source` command has been removed, used `chezmoi git` instead. +* The `sourceVCS` configuration group has been renamed to `git`. +* The order of files for a three-way merge passed to `merge.command` is now + actual file, target state, source state. +* The `chezmoi keyring` command has been moved to `chezmoi secret keyring`. +* The `genericSecret` configuration group has been renamed to `secret`. +* The `chezmoi chattr` command uses `encrypted` instead of `encrypt` as the + attribute for encrypted files. +* No encryption tool is configured by default. To use gpg, set the `encryption` + configuration variable to `gpg`. +* The gpg recipient is configured with the `gpg.recipient` configuration + variable, `gpgRecipient` is no longer used. +* The structure of data output by `chezmoi dump` has changed. +* The `.chezmoi.homedir` template variable has been renamed to + `.chezmoi.homeDir`. diff --git a/docs/COMPARISON.md b/docs/COMPARISON.md index 54a1bbe5b9a..608bbb27a85 100644 --- a/docs/COMPARISON.md +++ b/docs/COMPARISON.md @@ -1,6 +1,7 @@ # chezmoi Comparison guide <!--- toc ---> +* [Go to chezmoi.io](#go-to-chezmoiio) * [Comparison table](#comparison-table) * [I already have a system to manage my dotfiles, why should I use chezmoi?](#i-already-have-a-system-to-manage-my-dotfiles-why-should-i-use-chezmoi) * [...if coping with differences between machines requires special care](#if-coping-with-differences-between-machines-requires-special-care) @@ -8,6 +9,11 @@ * [...if your needs are outgrowing your current tool](#if-your-needs-are-outgrowing-your-current-tool) * [...if setting up your dotfiles requires more than two short commands](#if-setting-up-your-dotfiles-requires-more-than-two-short-commands) +## Go to chezmoi.io + +You are looking at documentation for chezmoi version 2, which hasn't been +released yet. Documentation for the current version of chezmoi is at +[chezmoi.io](https://chezmoi.io/docs/comparison/). ## Comparison table [chezmoi]: https://chezmoi.io/ @@ -24,7 +30,7 @@ | Install method | Multiple | git submodule | Multiple | Ruby gem | Multiple | n/a | | Non-root install on bare system | Yes | Difficult | Difficult | Difficult | Yes | Yes | | Windows support | Yes | No | No | No | No | Yes | -| Bootstrap requirements | git | Python, git | Perl, git | Ruby, git | git | git | +| Bootstrap requirements | None | Python, git | Perl, git | Ruby, git | git | git | | Source repos | Single | Single | Multiple | Single | Single | Single | | Method | File | Symlink | File | Symlink | File | File | | Config file | Optional | Required | Optional | None | None | No | @@ -36,6 +42,7 @@ | Custom variables in templates | Yes | n/a | n/a | n/a | No | No | | Executable files | Yes | Yes | Yes | Yes | No | Yes | | File creation with initial contents | Yes | No | No | No | No | No | +| Manage partial files | Yes | No | No | No | No | No | | File removal | Yes | Manual | No | No | No | No | | Directory creation | Yes | Yes | Yes | No | No | Yes | | Run scripts | Yes | Yes | Yes | No | No | No | diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md index 55f1d4df9ec..c4f9fa1c2ad 100644 --- a/docs/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -17,8 +17,7 @@ checked out chezmoi locally. ## Developing locally -chezmoi requires Go 1.14 or later and Go modules enabled. Enable Go modules by -setting the environment variable `GO111MODULE=on`. +chezmoi requires Go 1.16 or later. chezmoi is a standard Go project, using standard Go tooling, with a few extra tools. Ensure that these extra tools are installed with: @@ -39,15 +38,13 @@ Run chezmoi: ## Generated code -chezmoi generates help text, shell completions, embedded files, and the website -from a single source of truth. You must run +chezmoi generates shell completions, embedded files, and the website from a +single source of truth. You must run - go generate + make completions if you change includes any of the following: -* Modify any documentation in the `docs/` directory. -* Modify any files in the `assets/templates/` directory. * Add or modify a command. * Add or modify a command's flags. diff --git a/docs/FAQ.md b/docs/FAQ.md index 5818b3240ac..e26391805ae 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -1,6 +1,7 @@ # chezmoi Frequently Asked Questions <!--- toc ---> +* [Go to chezmoi.io](#go-to-chezmoiio) * [How can I quickly check for problems with chezmoi on my machine?](#how-can-i-quickly-check-for-problems-with-chezmoi-on-my-machine) * [What are the consequences of "bare" modifications to the target files? If my `.zshrc` is managed by chezmoi and I edit `~/.zshrc` without using `chezmoi edit`, what happens?](#what-are-the-consequences-of-bare-modifications-to-the-target-files-if-my-zshrc-is-managed-by-chezmoi-and-i-edit-zshrc-without-using-chezmoi-edit-what-happens) * [How can I tell what dotfiles in my home directory aren't managed by chezmoi? Is there an easy way to have chezmoi manage a subset of them?](#how-can-i-tell-what-dotfiles-in-my-home-directory-arent-managed-by-chezmoi-is-there-an-easy-way-to-have-chezmoi-manage-a-subset-of-them) @@ -26,6 +27,12 @@ * [Where do I ask a question that isn't answered here?](#where-do-i-ask-a-question-that-isnt-answered-here) * [I like chezmoi. How do I say thanks?](#i-like-chezmoi-how-do-i-say-thanks) +## Go to chezmoi.io + +You are looking at documentation for chezmoi version 2, which hasn't been +released yet. Documentation for the current version of chezmoi is at +[chezmoi.io](https://chezmoi.io/docs/faq/). + ## How can I quickly check for problems with chezmoi on my machine? Run: @@ -72,13 +79,10 @@ You have several options: * `chezmoi cd` opens a shell in the source directory, where you can run your usual version control commands, like `git add` and `git commit`. -* `chezmoi git` and `chezmoi hg` run `git` and `hg` respectively in the source +* `chezmoi git` runs `git` in the source directory and pass extra arguments to the command. If you're passing any flags, you'll need to use `--` to prevent chezmoi from consuming them, for example `chezmoi git -- commit -m "Update dotfiles"`. -* `chezmoi source` runs your configured version control system in your source - directory. It works in the same way as the `chezmoi git` and `chezmoi hg` - commands, but uses `sourceVCS.command`. ## How do I only run a script when a file has changed? @@ -333,15 +337,10 @@ GitHub](https://github.com/twpayne/chezmoi/issues/new/choose). ## I'm getting errors trying to build chezmoi from source -chezmoi requires Go version 1.14 or later and Go modules enabled. You can check -the version of Go with: +chezmoi requires Go version 1.16 or later. You can check the version of Go with: go version -Enable Go modules by setting `GO111MODULE=on` when running `go get`: - - GO111MODULE=on go get -u github.com/twpayne/chezmoi - For more details on building chezmoi, see the [Contributing Guide](CONTRIBUTING.md). diff --git a/docs/HOWTO.md b/docs/HOWTO.md index 058a960ed93..51bacdb72bf 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -1,6 +1,7 @@ # chezmoi How-To Guide <!--- toc ---> +* [Go to chezmoi.io](#go-to-chezmoiio) * [Use a hosted repo to manage your dotfiles across multiple machines](#use-a-hosted-repo-to-manage-your-dotfiles-across-multiple-machines) * [Pull the latest changes from your repo and apply them](#pull-the-latest-changes-from-your-repo-and-apply-them) * [Pull the latest changes from your repo and see what would change, without actually applying the changes](#pull-the-latest-changes-from-your-repo-and-see-what-would-change-without-actually-applying-the-changes) @@ -9,6 +10,8 @@ * [Use completely separate config files on different machines](#use-completely-separate-config-files-on-different-machines) * [Without using symlinks](#without-using-symlinks) * [Create a config file on a new machine automatically](#create-a-config-file-on-a-new-machine-automatically) +* [Re-create your config file](#re-create-your-config-file) +* [Populate `~/.ssh/authorized_keys` with your public SSH keys from GitHub](#populate-sshauthorized_keys-with-your-public-ssh-keys-from-github) * [Have chezmoi create a directory, but ignore its contents](#have-chezmoi-create-a-directory-but-ignore-its-contents) * [Ensure that a target is removed](#ensure-that-a-target-is-removed) * [Include a subdirectory from another repository, like Oh My Zsh](#include-a-subdirectory-from-another-repository-like-oh-my-zsh) @@ -34,11 +37,16 @@ * [Run a PowerShell script as admin on Windows](#run-a-powershell-script-as-admin-on-windows) * [Import archives](#import-archives) * [Export archives](#export-archives) -* [Use a non-git version control system](#use-a-non-git-version-control-system) * [Customize the `diff` command](#customize-the-diff-command) * [Use a merge tool other than vimdiff](#use-a-merge-tool-other-than-vimdiff) * [Migrate from a dotfile manager that uses symlinks](#migrate-from-a-dotfile-manager-that-uses-symlinks) +## Go to chezmoi.io + +You are looking at documentation for chezmoi version 2, which hasn't been +released yet. Documentation for the current version of chezmoi is at +[chezmoi.io](https://chezmoi.io/docs/how-to/). + ## Use a hosted repo to manage your dotfiles across multiple machines chezmoi relies on your version control system and hosted repo to share changes @@ -81,7 +89,7 @@ This runs `git pull --rebase` in your source directory and then `chezmoi apply`. Run: - chezmoi source pull -- --rebase && chezmoi diff + chezmoi git pull -- --rebase && chezmoi diff This runs `git pull --rebase` in your source directory and `chezmoi diff` then shows the difference between the target state computed from your @@ -99,9 +107,9 @@ chezmoi can automatically commit and push changes to your source directory to your repo. This feature is disabled by default. To enable it, add the following to your config file: - [sourceVCS] - autoCommit = true - autoPush = true + [git] + autoCommit = true + autoPush = true Whenever a change is made to your source directory, chezmoi will commit the changes with an automatically-generated commit message (if `autoCommit` is true) @@ -296,10 +304,10 @@ The same thing can be achieved using the include function. `dot_bashrc.tmpl` {{ if eq .chezmoi.os "darwin" }} - {{ include ".bashrc_darwin" }} + {{ include ".bashrc_darwin" }} {{ end }} {{ if eq .chezmoi.os "linux" }} - {{ include ".bashrc_linux" }} + {{ include ".bashrc_linux" }} {{ end }} @@ -315,7 +323,7 @@ Specifically, if you have `.chezmoi.toml.tmpl` that looks like this: {{- $email := promptString "email" -}} [data] - email = "{{ $email }}" + email = {{ $email | quote }} Then `chezmoi init` will create an initial `chezmoi.toml` using this template. `promptString` is a special function that prompts the user (you) for a value. @@ -325,6 +333,50 @@ To test this template, use `chezmoi execute-template` with the `--init` and chezmoi execute-template --init --promptString [email protected] < ~/.local/share/chezmoi/.chezmoi.toml.tmpl +## Re-create your config file + +If you change your config file template, chezmoi will warn you if your current +config file was not generated from that template. You can re-generate your +config file by running: + + chezmoi init + +If you are using any `prompt*` template functions in your config file template +you will be prompted again. However, you can avoid this with the following +example template logic: + + {{- $email := get . "email" -}} + {{- if not $email -}} + {{- $email = promptString "email" -}} + {{- end -}} + + [data] + email = {{ $email | quote }} + +This will cause chezmoi to first try to re-use the existing `$email` variable +and fallback to `promptString` only if it is not set. + +For boolean variables you can use: + + {{- $var := false -}} + {{- if (hasKey . "var") -}} + {{- $var = get "." "var" -}} + {{- end -}} + + [data] + var = $var + +## Populate `~/.ssh/authorized_keys` with your public SSH keys from GitHub + +chezmoi can retrieve your public SSH keys from GitHub, which can be useful for +populating your `~/.ssh/authorized_keys`. Put the following in your +`~/.local/share/chezmoi/dot_ssh/authorized_keys.tmpl`, where `username` is your +GitHub username: + + {{ range (gitHubKeys "username") -}} + {{ .Key }} + {{ end -}} + ## Have chezmoi create a directory, but ignore its contents If you want chezmoi to create a directory, but ignore its contents, say `~/src`, @@ -512,6 +564,7 @@ it afterwards. Specify the encryption key to use in your configuration file (`chezmoi.toml`) with the `gpg.recipient` key: + encryption = "gpg" [gpg] recipient = "..." @@ -530,6 +583,7 @@ decrypted when generating the target state. Specify symmetric encryption in your configuration file: + encryption = "gpg" [gpg] symmetric = true @@ -571,7 +625,7 @@ Windows Credentials Manager (on Windows) via the Set values with: - $ chezmoi keyring set --service=<service> --user=<user> + $ chezmoi secret keyring set --service=<service> --user=<user> Value: xxxxxxxx The value can then be used in templates using the `keyring` function which takes @@ -579,7 +633,7 @@ the service and user as arguments. For example, save a GitHub access token in keyring with: - $ chezmoi keyring set --service=github --user=<github-username> + $ chezmoi secret keyring set --service=github --user=<github-username> Value: xxxxxxxx and then include it in your `~/.gitconfig` file with: @@ -590,7 +644,7 @@ and then include it in your `~/.gitconfig` file with: You can query the keyring from the command line: - chezmoi keyring get --service=github --user=<github-username> + chezmoi secret keyring get --service=github --user=<github-username> ### Use LastPass to keep your secrets @@ -701,20 +755,19 @@ language to extract the data you want. For example: ### Use a generic tool to keep your secrets You can use any command line tool that outputs secrets either as a string or in -JSON format. Choose the binary by setting `genericSecret.command` in your -configuration file. You can then invoke this command with the `secret` and -`secretJSON` template functions which return the raw output and JSON-decoded -output respectively. All of the above secret managers can be supported in this -way: - -| Secret Manager | `genericSecret.command` | Template skeleton | -| --------------- | ----------------------- | ------------------------------------------------- | -| 1Password | `op` | `{{ secretJSON "get" "item" <id> }}` | -| Bitwarden | `bw` | `{{ secretJSON "get" <id> }}` | -| Hashicorp Vault | `vault` | `{{ secretJSON "kv" "get" "-format=json" <id> }}` | -| LastPass | `lpass` | `{{ secretJSON "show" "--json" <id> }}` | -| KeePassXC | `keepassxc-cli` | Not possible (interactive command only) | -| pass | `pass` | `{{ secret "show" <id> }}` | +JSON format. Choose the binary by setting `secret.command` in your configuration +file. You can then invoke this command with the `secret` and `secretJSON` +template functions which return the raw output and JSON-decoded output +respectively. All of the above secret managers can be supported in this way: + +| Secret Manager | `secret.command` | Template skeleton | +| --------------- | ---------------- | ------------------------------------------------- | +| 1Password | `op` | `{{ secretJSON "get" "item" <id> }}` | +| Bitwarden | `bw` | `{{ secretJSON "get" <id> }}` | +| Hashicorp Vault | `vault` | `{{ secretJSON "kv" "get" "-format=json" <id> }}` | +| LastPass | `lpass` | `{{ secretJSON "show" "--json" <id> }}` | +| KeePassXC | `keepassxc-cli` | Not possible (interactive command only) | +| pass | `pass` | `{{ secret "show" <id> }}` | ### Use templates variables to keep your secrets @@ -902,22 +955,28 @@ WSL can be detected by looking for the string `Microsoft` in WSL 1: ``` -{{ if (contains "Microsoft" .chezmoi.kernel.osrelease) }} +{{ if (eq .chezmoi.os "linux") }} +{{ if (contains "Microsoft" .chezmoi.kernel.osrelease) }} # WSL-specific code +{{ end }} {{ end }} ``` WSL 2: ``` -{{ if (contains "microsoft" .chezmoi.kernel.osrelease) }} +{{ if (eq .chezmoi.os "linux") }} +{{ if (contains "microsoft" .chezmoi.kernel.osrelease) }} # WSL-specific code +{{ end }} {{ end }} ``` WSL 2 since version 4.19.112: ``` -{{ if (contains "microsoft-WSL2" .chezmoi.kernel.osrelease) }} +{{ if (eq .chezmoi.os "linux") }} +{{ if (contains "microsoft-WSL2" .chezmoi.kernel.osrelease) }} # WSL-specific code +{{ end }} {{ end }} ``` @@ -963,20 +1022,6 @@ target state. A particularly useful command is: which lists all the targets in the target state. -## Use a non-git version control system - -By default, chezmoi uses git, but you can use any version control system of your -choice. In your config file, specify the command to use. For example, to use -Mercurial specify: - - [sourceVCS] - command = "hg" - -The source VCS command is used in the chezmoi commands `init`, `source`, and -`update`, and support for VCSes other than git is limited but easy to add. If -you'd like to see your VCS better supported, please [open an issue on -GitHub](https://github.com/twpayne/chezmoi/issues/new/choose). - ## Customize the `diff` command By default, chezmoi uses a built-in diff. You can change the format, and/or pipe @@ -984,8 +1029,8 @@ the output into a pager of your choice. For example, to use [`diff-so-fancy`](https://github.com/so-fancy/diff-so-fancy) specify: [diff] - format = "git" - pager = "diff-so-fancy" + format = "git" + pager = "diff-so-fancy" The format can also be set with the `--format` option to the `diff` command, and the pager can be disabled using `--no-pager`. diff --git a/docs/INSTALL.md b/docs/INSTALL.md index 2a6f2d4367e..820b828dddb 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -1,13 +1,19 @@ # chezmoi Install Guide <!--- toc ---> +* [Go to chezmoi.io](#go-to-chezmoiio) * [One-line binary install](#one-line-binary-install) * [One-line package install](#one-line-package-install) * [Pre-built Linux packages](#pre-built-linux-packages) * [Pre-built binaries](#pre-built-binaries) * [All pre-built Linux packages and binaries](#all-pre-built-linux-packages-and-binaries) * [From source](#from-source) -* [Upgrading](#upgrading) + +## Go to chezmoi.io + +You are looking at documentation for chezmoi version 2, which hasn't been +released yet. Documentation for the current version of chezmoi is at +[chezmoi.io](https://chezmoi.io/docs/install/). ## One-line binary install @@ -24,7 +30,7 @@ Or on systems with Powershell, you can use this command: # To install in another location '$params = "-BinDir ~/other"', (iwr https://git.io/chezmoi.ps1).Content | powershell -c - - # For information about other options, try this: + # For information about other options, run '$params = "-?"', (iwr https://git.io/chezmoi.ps1).Content | powershell -c - ## One-line package install @@ -67,7 +73,7 @@ documentation, and shell completions. | ---------- | --------------------------------------------------- | -------------------------------------------------------------- | | FreeBSD | `amd64`, `arm`, `arm64`, `i386` | [`tar.gz`](https://github.com/twpayne/chezmoi/releases/latest) | | Linux | `amd64`, `arm`, `arm64`, `i386`, `ppc64`, `ppc64le` | [`tar.gz`](https://github.com/twpayne/chezmoi/releases/latest) | -| macOS | `amd64` | [`tar.gz`](https://github.com/twpayne/chezmoi/releases/latest) | +| macOS | `amd64`, `arm64` | [`tar.gz`](https://github.com/twpayne/chezmoi/releases/latest) | | OpenBSD | `amd64`, `arm`, `arm64`, `i386` | [`tar.gz`](https://github.com/twpayne/chezmoi/releases/latest) | | Windows | `amd64`, `i386` | [`zip`](https://github.com/twpayne/chezmoi/releases/latest) | @@ -80,19 +86,6 @@ page](https://github.com/twpayne/chezmoi/releases/latest). Download, build, and install chezmoi for your system: - cd $(mktemp -d) - git clone --depth=1 https://github.com/twpayne/chezmoi.git - cd chezmoi - go install - -Building chezmoi requires Go 1.14 or later. - -## Upgrading - -If you have installed a pre-built binary of chezmoi, you can upgrade it to the -latest release with: - - chezmoi upgrade + go install github.com/twpayne/chezmoi@latest -This will re-use whichever mechanism you used to install chezmoi to install the -latest release. +Building chezmoi requires Go 1.16 or later. diff --git a/docs/MEDIA.md b/docs/MEDIA.md index a37c579b78d..3202ed14269 100644 --- a/docs/MEDIA.md +++ b/docs/MEDIA.md @@ -10,6 +10,7 @@ Recommended podcast: [FLOSS weekly episode 556: chezmoi](https://twit.tv/shows/f | Date | Version | Format | Link | | ---------- | ------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 2021-02-17 | 1.8.11 | Text (JP) | [chezmoi で dotfiles を手軽に柔軟にセキュアに管理する](https://zenn.dev/ryo_kawamata/articles/introduce-chezmoi) | | 2021-02-06 | 1.8.10 | Video | [chezmoi: manage your dotfiles across multiple, diverse machines, securely](https://fosdem.org/2021/schedule/event/chezmoi/) | | 2021-01-12 | 1.8.10 | Text | [Automating the Setup of a New Mac With All Your Apps, Preferences, and Development Tools](https://www.moncefbelyamani.com/automating-the-setup-of-a-new-mac-with-all-your-apps-preferences-and-development-tools/) | | 2020-11-06 | 1.8.8 | Text | [Chezmoi – Securely Manage dotfiles across multiple machines](https://computingforgeeks.com/chezmoi-manage-dotfiles-across-multiple-machines/) | diff --git a/docs/QUICKSTART.md b/docs/QUICKSTART.md index f1463428f4f..a07aafd551b 100644 --- a/docs/QUICKSTART.md +++ b/docs/QUICKSTART.md @@ -1,11 +1,18 @@ # chezmoi Quick Start Guide <!--- toc ---> +* [Go to chezmoi.io](#go-to-chezmoiio) * [Concepts](#concepts) * [Start using chezmoi on your current machine](#start-using-chezmoi-on-your-current-machine) * [Using chezmoi across multiple machines](#using-chezmoi-across-multiple-machines) * [Next steps](#next-steps) +## Go to chezmoi.io + +You are looking at documentation for chezmoi version 2, which hasn't been +released yet. Documentation for the current version of chezmoi is at +[chezmoi.io](https://chezmoi.io/docs/quickstart/). + ## Concepts chezmoi stores the desired state of your dotfiles in the directory diff --git a/docs/REFERENCE.md b/docs/REFERENCE.md index da00991c6c9..2d7c44576c3 100644 --- a/docs/REFERENCE.md +++ b/docs/REFERENCE.md @@ -3,23 +3,40 @@ Manage your dotfiles securely across multiple machines. <!--- toc ---> +* [Go to chezmoi.io](#go-to-chezmoiio) * [Concepts](#concepts) * [Global command line flags](#global-command-line-flags) * [`--color` *value*](#--color-value) * [`-c`, `--config` *filename*](#-c---config-filename) + * [`--cpu-profile` *filename*](#--cpu-profile-filename) * [`--debug`](#--debug) * [`-D`, `--destination` *directory*](#-d---destination-directory) - * [`--follow`](#--follow) * [`-n`, `--dry-run`](#-n---dry-run) + * [`-x`, `--exclude` *types*](#-x---exclude-types) + * [`--force`](#--force) * [`-h`, `--help`](#-h---help) + * [`-k`, `--keep-going`](#-k---keep-going) + * [`--no-pager`](#--no-pager) + * [`--no-tty`](#--no-tty) + * [`-o`, `--output` *filename*](#-o---output-filename) * [`-r`. `--remove`](#-r---remove) * [`-S`, `--source` *directory*](#-s---source-directory) + * [`--use-builtin-git` *value*](#--use-builtin-git-value) * [`-v`, `--verbose`](#-v---verbose) * [`--version`](#--version) +* [Common command line flags](#common-command-line-flags) + * [`--format` *format*](#--format-format) + * [`--include` *types*](#--include-types) + * [`-r`, `--recursive`](#-r---recursive) * [Configuration file](#configuration-file) * [Variables](#variables) * [Examples](#examples) * [Source state attributes](#source-state-attributes) +* [Target types](#target-types) + * [Files](#files) + * [Directories](#directories) + * [Symbolic links](#symbolic-links) + * [Scripts](#scripts) * [Special files and directories](#special-files-and-directories) * [`.chezmoi.<format>.tmpl`](#chezmoiformattmpl) * [`.chezmoiignore`](#chezmoiignore) @@ -45,7 +62,6 @@ Manage your dotfiles securely across multiple machines. * [`forget` *targets*](#forget-targets) * [`git` [*arguments*]](#git-arguments) * [`help` *command*](#help-command) - * [`hg` [*arguments*]](#hg-arguments) * [`init` [*repo*]](#init-repo) * [`import` *filename*](#import-filename) * [`manage` *targets*](#manage-targets) @@ -55,12 +71,12 @@ Manage your dotfiles securely across multiple machines. * [`remove` *targets*](#remove-targets) * [`rm` *targets*](#rm-targets) * [`secret`](#secret) - * [`source` [*args*]](#source-args) * [`source-path` [*targets*]](#source-path-targets) + * [`state`](#state) + * [`status`](#status) * [`unmanage` *targets*](#unmanage-targets) * [`unmanaged`](#unmanaged) * [`update`](#update) - * [`upgrade`](#upgrade) * [`verify` [*targets*]](#verify-targets) * [Editor configuration](#editor-configuration) * [Umask configuration](#umask-configuration) @@ -70,6 +86,7 @@ Manage your dotfiles securely across multiple machines. * [`bitwarden` [*args*]](#bitwarden-args) * [`bitwardenAttachment` *filename* *itemid*](#bitwardenattachment-filename-itemid) * [`bitwardenFields` [*args*]](#bitwardenfields-args) + * [`gitHubKeys` *user*](#githubkeys-user) * [`gopass` *gopass-name*](#gopass-gopass-name) * [`include` *filename*](#include-filename) * [`ioreg`](#ioreg) @@ -92,6 +109,12 @@ Manage your dotfiles securely across multiple machines. * [`stat` *name*](#stat-name) * [`vault` *key*](#vault-key) +## Go to chezmoi.io + +You are looking at documentation for chezmoi version 2, which hasn't been +released yet. Documentation for the current version of chezmoi is at +[chezmoi.io](https://chezmoi.io/docs/reference/). + ## Concepts chezmoi evaluates the source state for the current machine and then updates the @@ -123,15 +146,17 @@ Command line flags override any values set in the configuration file. ### `--color` *value* Colorize diffs, *value* can be `on`, `off`, `auto`, or any boolean-like value -recognized by -[`strconv.ParseBool`](https://pkg.go.dev/strconv?tab=doc#ParseBool). The default -value is `auto` which will colorize diffs only if the the environment variable -`NO_COLOR` is not set and stdout is a terminal. +recognized by `parseBool`. The default is `auto` which will colorize diffs only +if the the environment variable `NO_COLOR` is not set and stdout is a terminal. ### `-c`, `--config` *filename* Read the configuration from *filename*. +### `--cpu-profile` *filename* + +Write a [CPU profile](https://blog.golang.org/pprof) to *filename*. + ### `--debug` Log information helpful for debugging. @@ -140,21 +165,44 @@ Log information helpful for debugging. Use *directory* as the destination directory. -### `--follow` - -If the last part of a target is a symlink, deal with what the symlink -references, rather than the symlink itself. - ### `-n`, `--dry-run` Set dry run mode. In dry run mode, the destination directory is never modified. This is most useful in combination with the `-v` (verbose) flag to print changes that would be made without making them. +### `-x`, `--exclude` *types* + +Exclude target state entries of type *types*. *types* is a comma-separated list +of target states (`all`, `dirs`, `files`, `remove`, `scripts`, `symlinks`, and +`encrypted`). For example, `--exclude=scripts` will cause the command to not run +scripts and `--exclude=encrypted` will exclude encrypted files. + +### `--force` + +Make changes without prompting. + ### `-h`, `--help` Print help. +### `-k`, `--keep-going` + +Keep going as far as possible after a encountering an error. + +### `--no-pager` + +Do not use the pager. + +### `--no-tty` + +Do not attempt to get a TTY to read input and passwords. Instead, read them from +stdin. + +### `-o`, `--output` *filename* + +Write the output to *filename* instead of stdout. + ### `-r`. `--remove` Also remove targets according to `.chezmoiremove`. @@ -163,6 +211,13 @@ Also remove targets according to `.chezmoiremove`. Use *directory* as the source directory. +### `--use-builtin-git` *value* + +Use chezmoi's builtin git instead of `git.command` for the `init` and `update` +commands. *value* can be `on`, `off`, `auto`, or any boolean-like value +recognized by `parseBool`. The default is `auto` which will only use the builtin +git if `git.command` cannot be found in `$PATH`. + ### `-v`, `--verbose` Set verbose mode. In verbose mode, chezmoi prints the changes that it is making @@ -174,7 +229,27 @@ state and the destination set are printed as unified diffs. Print the version of chezmoi, the commit at which it was built, and the build timestamp. -## Configuration file +## Common command line flags + +The following flags apply to multiple commands where they are relevant. + +### `--format` *format* + +Set the output format. *format* can be `json` or `yaml`. + +### `--include` *types* + +Only operate on target state entries of type *types*. *types* is a +comma-separated list of target states (`all`, `dirs`, `files`, `remove`, +`scripts`, `symlinks`, and `encrypted`) and can be excluded by preceeding them +with a `no`. For example, `--include=dirs,files` will cause the command to apply +to directories and files only. + +### `-r`, `--recursive` + +Recurse into subdirectories, `true` by default. + + ## Configuration file chezmoi searches for its configuration file according to the [XDG Base Directory Specification](https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html) @@ -189,41 +264,54 @@ of the config file is `chezmoi`, and the first config file found is used. The following configuration variables are available: -| Section | Variable | Type | Default value | Description | -| --------------- | ------------ | -------- | ------------------------- | --------------------------------------------------- | -| Top level | `color` | string | `auto` | Colorize diffs | -| | `data` | any | *none* | Template data | -| | `destDir` | string | `~` | Destination directory | -| | `dryRun` | bool | `false` | Dry run mode | -| | `follow` | bool | `false` | Follow symlinks | -| | `remove` | bool | `false` | Remove targets | -| | `sourceDir` | string | `~/.local/share/chezmoi` | Source directory | -| | `umask` | int | *from system* | Umask | -| | `verbose` | bool | `false` | Verbose mode | -| `bitwarden` | `command` | string | `bw` | Bitwarden CLI command | -| `cd` | `args` | []string | *none* | Extra args to shell in `cd` command | -| | `command` | string | *none* | Shell to run in `cd` command | -| `diff` | `format` | string | `chezmoi` | Diff format, either `chezmoi` or `git` | -| | `pager` | string | *none* | Pager | -| `genericSecret` | `command` | string | *none* | Generic secret command | -| `gopass` | `command` | string | `gopass` | gopass CLI command | -| `gpg` | `command` | string | `gpg` | GPG CLI command | -| | `recipient` | string | *none* | GPG recipient | -| | `symmetric` | bool | `false` | Use symmetric GPG encryption | -| `keepassxc` | `args` | []string | *none* | Extra args to KeePassXC CLI command | -| | `command` | string | `keepassxc-cli` | KeePassXC CLI command | -| | `database` | string | *none* | KeePassXC database | -| `lastpass` | `command` | string | `lpass` | Lastpass CLI command | -| `merge` | `args` | []string | *none* | Extra args to 3-way merge command | -| | `command` | string | `vimdiff` | 3-way merge command | -| `onepassword` | `cache` | bool | `true` | Enable optional caching provided by `op` | -| | `command` | string | `op` | 1Password CLI command | -| `pass` | `command` | string | `pass` | Pass CLI command | -| `sourceVCS` | `autoCommit` | bool | `false` | Commit changes to the source state after any change | -| | `autoPush` | bool | `false` | Push changes to the source state after any change | -| | `command` | string | `git` | Source version control system | -| `template` | `options` | []string | `["missingkey=error"]` | Template options | -| `vault` | `command` | string | `vault` | Vault CLI command | +| Section | Variable | Type | Default value | Description | +| ------------- | ----------------- | -------- | ------------------------- | ------------------------------------------------------ | +| Top level | `color` | string | `auto` | Colorize output | +| | `data` | any | *none* | Template data | +| | `destDir` | string | `~` | Destination directory | +| | `encryption` | string | *none* | Encryption tool, either `age` or `gpg` | +| | `format` | string | `json` | Format for data output, either `json` or `yaml` | +| | `remove` | bool | `false` | Remove targets | +| | `sourceDir` | string | `~/.local/share/chezmoi` | Source directory | +| | `umask` | int | *from system* | Umask | +| | `useBuiltinGit` | string | `auto` | Use builtin git if `git` command is not found in $PATH | +| `age` | `args` | []string | *none* | Extra args to age CLI command | +| | `command` | string | `age` | age CLI command | +| | `identity` | string | *none* | age identity file | +| | `identities` | []string | *none* | age identity files | +| | `recipient` | string | *none* | age recipient | +| | `recipients` | []string | *none* | age recipients | +| | `recipientsFile` | []string | *none* | age recipients file | +| | `recipientsFiles` | []string | *none* | age receipients files | +| | `suffix` | string | `.age` | Suffix appended to age-encrypted files | +| `bitwarden` | `command` | string | `bw` | Bitwarden CLI command | +| `cd` | `args` | []string | *none* | Extra args to shell in `cd` command | +| | `command` | string | *none* | Shell to run in `cd` command | +| `diff` | `pager` | string | `$PAGER` / `less` | Pager | +| `edit` | `args` | []string | *none* | Extra args to edit command | +| | `command` | string | `$EDITOR` / `$VISUAL` | Edit command | +| `secret` | `command` | string | *none* | Generic secret command | +| `git` | `autoAdd ` | bool | `false` | Add changes to the source state after any change | +| | `autoCommit` | bool | `false` | Commit changes to the source state after any change | +| | `autoPush` | bool | `false` | Push changes to the source state after any change | +| | `command` | string | `git` | Source version control system | +| `gopass` | `command` | string | `gopass` | gopass CLI command | +| `gpg` | `args` | []string | *none* | Extra args to GPG CLI command | +| | `command` | string | `gpg` | GPG CLI command | +| | `recipient` | string | *none* | GPG recipient | +| | `suffix` | string | `.asc` | Suffix appended to GPG-encrypted files | +| | `symmetric` | bool | `false` | Use symmetric GPG encryption | +| `keepassxc` | `args` | []string | *none* | Extra args to KeePassXC CLI command | +| | `command` | string | `keepassxc-cli` | KeePassXC CLI command | +| | `database` | string | *none* | KeePassXC database | +| `lastpass` | `command` | string | `lpass` | Lastpass CLI command | +| `merge` | `args` | []string | *none* | Extra args to 3-way merge command | +| | `command` | string | `vimdiff` | 3-way merge command | +| `onepassword` | `cache` | bool | `true` | Enable optional caching provided by `op` | +| | `command` | string | `op` | 1Password CLI command | +| `pass` | `command` | string | `pass` | Pass CLI command | +| `template` | `options` | []string | `["missingkey=error"]` | Template options | +| `vault` | `command` | string | `vault` | Vault CLI command | ### Examples @@ -232,8 +320,8 @@ The following configuration variables are available: ```json { "sourceDir": "/home/user/.dotfiles", - "diff": { - "format": "git" + "git": { + "autoPush": true } } ``` @@ -242,16 +330,16 @@ The following configuration variables are available: ```toml sourceDir = "/home/user/.dotfiles" -[diff] - format = "git" +[git] + autoPush = true ``` #### YAML ```yaml sourceDir: /home/user/.dotfiles -diff: - format: git +git: + autoPush: true ``` ## Source state attributes @@ -266,31 +354,102 @@ special, and are collectively referred to as "attributes": | Prefix | Effect | | ------------ | ------------------------------------------------------------------------------ | -| `encrypted_` | Encrypt the file in the source state. | -| `once_` | Only run script once. | -| `private_` | Remove all group and world permissions from the target file or directory. | +| `after_` | Run script after updating the destination. | +| `before_` | Run script before updating the desintation. | +| `create_` | Ensure that the file exists, and create it with contents if it does not. | +| `dot_` | Rename to use a leading dot, e.g. `dot_foo` becomes `.foo`. | | `empty_` | Ensure the file exists, even if is empty. By default, empty files are removed. | +| `encrypted_` | Encrypt the file in the source state. | | `exact_` | Remove anything not managed by chezmoi. | | `executable_`| Add executable permissions to the target file. | +| `modify_` | Treat the contents as a script that modifies an existing file. | +| `once_` | Run script once. | +| `private_` | Remove all group and world permissions from the target file or directory. | | `run_` | Treat the contents as a script to run. | | `symlink_` | Create a symlink instead of a regular file. | -| `dot_` | Rename to use a leading dot, e.g. `dot_foo` becomes `.foo`. | | Suffix | Effect | | ------- | ---------------------------------------------------- | | `.tmpl` | Treat the contents of the source file as a template. | -Order of prefixes is important, the order is `run_`, `exact_`, `private_`, -`empty_`, `executable_`, `symlink_`, `once_`, `dot_`. +The order of prefixes is important, the order is `run_`, `create_`, `modify_`, +`before_`, `after_`, `exact_`, `private_`, `empty_`, `executable_`, `symlink_`, +`once_`, `dot_`. Different target types allow different prefixes and suffixes: -| Target type | Allowed prefixes | Allowed suffixes | -| ------------- | --------------------------------------------------------- | ---------------- | -| Directory | `exact_`, `private_`, `dot_` | *none* | -| Regular file | `encrypted_`, `private_`, `empty_`, `executable_`, `dot_` | `.tmpl` | -| Script | `run_`, `once_` | `.tmpl` | -| Symbolic link | `symlink_`, `dot_`, | `.tmpl` | +| Target type | Allowed prefixes | Allowed suffixes | +| ------------- | --------------------------------------------------------------------- | ---------------- | +| Directory | `exact_`, `private_`, `dot_` | *none* | +| Regular file | `encrypted_`, `private_`, `executable_`, `dot_` | `.tmpl` | +| Create file | `create_`, `encrypted_`, `private_`, `executable_`, `dot_` | `.tmpl` | +| Modify file | `modify_`, `encrypted_`, `private_`, `executable_`, `dot_` | `.tmpl` | +| Script | `run_`, `once_`, `before_` or `after_` | `.tmpl` | +| Symbolic link | `symlink_`, `dot_`, | `.tmpl` | + +In addition, if the source file is encrypted, the suffix `.age` (when age +encryption is used) or `.asc` (when gpg encryption is used) is stripped. These +suffixes can be overridden with the `age.suffix` and `gpg.suffix` configuration +variables. + +## Target types + +chezmoi will create, update, and delete files, directories, and symbolic links +in the destination directory, and run scripts. chezmoi deterministically +performs actions in ASCII order of their target name. For example, given a file +`dot_a`, a script `run_z`, and a directory `exact_dot_c`, chezmoi will first +create `.a`, create `.c`, and then execute `run_z`. + +### Files + +Files are represented by regular files in the source state. The `encrypted_` +attribute determines whether the file in the source state is encrypted. The +`executable_` attribute will set the executable bits when the file is written to +the target state, and the `private_` attribute will clear all group and world +permissions. Files with the `.tmpl` suffix will be interpreted as templates. + +#### Create file + +Files with the `create_` prefix will be created in the target state with the +contents of the file in the source state if they do not already exist. If the +file in the destination state already exists then its contents will be left +unchanged. + +#### Modify file + +Files with the `modify_` prefix are treated as scripts that modify an existing +file. The contents of the existing file (which maybe empty if the existing file +does not exist or is empty) are passed to the script's standard input, and the +new contents are read from the scripts standard output. + +### Directories + +Directories are represented by regular directories in the source state. The +`exact_` attribute causes chezmoi to remove any entries in the target state that +are not explicitly specified in the source state, and the `private_` attribute +causes chezmoi to clear all group and world permssions. + +### Symbolic links + +Symbolic links are represented by regular files in the source state with the +prefix `symlink_`. The contents of the file will have a trailing newline +stripped, and the result be interpreted as the target of the symbolic link. +Symbolic links with the `.tmpl` suffix in the source state are interpreted as +templates. + +### Scripts + +Scripts are represented as regular files in the source state with prefix `run_`. +The file's contents (after being interpreted as a template if it has a `.tmpl` +suffix) are executed. Scripts are executed on every `chezmoi apply`, unless they +have the `once_` attribute, in which case they are only executed when they are +first found or when their contents have changed. + +Scripts with the `before_` attribute are executed before any files, directories, +or symlinks are updated. Scripts with the `after_` attribute are executed after +all files, directories, and symlinks have been updated. Scripts without an +`before_` or `after_` attribute are executed in ASCII order of their target +names with respect to files, directories, and symlinks. ## Special files and directories @@ -333,6 +492,7 @@ ignored on different machines. *.txt # ignore *.txt in the target directory */*.txt # ignore *.txt in subdirectories of the target directory + backups/** # ignore backups folder in chezmoi directory and all its contents # but not in subdirectories of subdirectories; # so a/b/c.txt would *not* be ignored backups/** # ignore all contents of backups folder in chezmoi directory @@ -404,10 +564,19 @@ Set the `empty` attribute on added files. Add *targets*, even if doing so would cause a source template to be overwritten. -#### `-x`, `--exact` +#### `--follow` + +If the last part of a target is a symlink, add the target of the symlink instead +of the symlink itself. + +#### `--exact` Set the `exact` attribute on added directories. +#### `-i`, `--include` *types* + +Only add entries of type *types*. + #### `-p`, `--prompt` Interactively prompt before adding each file. @@ -430,7 +599,18 @@ Set the `template` attribute on added files and symlinks. ### `apply` [*targets*] Ensure that *targets* are in the target state, updating them if necessary. If no -targets are specified, the state of all targets are ensured. +targets are specified, the state of all targets are ensured. If a target has +been modified since chezmoi last wrote it then the user will be prompted if they +want to overwrite the file. + +#### `-i`, `--include` *types* + +Only add entries of type *types*. + +#### `--source-path` + +Specify targets by source path, rather than target path. This is useful for +applying changes after editing. #### `apply` examples @@ -438,19 +618,32 @@ targets are specified, the state of all targets are ensured. chezmoi apply --dry-run --verbose chezmoi apply ~/.bashrc +In `~/.vimrc`: + + autocmd BufWritePost ~/.local/share/chezmoi/* ! chezmoi apply --source-path % + ### `archive` Generate a tar archive of the target state. This can be piped into `tar` to inspect the target state. -#### `--output`, `-o` *filename* +#### `--format` *format* -Write the output to *filename* instead of stdout. +Write the archive in *format*. *format* can be either `tar` (the default) or `zip`. + +#### `-i`, `--include` *types* + +Only include entries of type *types*. + +#### `-z`, `--gzip` + +Compress the output with gzip. #### `archive` examples chezmoi archive | tar tvf - chezmoi archive --output=dotfiles.tar + chezmoi archive --format=zip --output=dotfiles.zip ### `cat` *targets* @@ -504,24 +697,14 @@ comma (`,`). Generate shell completion code for the specified shell (`bash`, `fish`, `powershell`, or `zsh`). -#### `--output`, `-o` *filename* - -Write the shell completion code to *filename* instead of stdout. - #### `completion` examples chezmoi completion bash - chezmoi completion fish --output ~/.config/fish/completions/chezmoi.fish + chezmoi completion fish --output=~/.config/fish/completions/chezmoi.fish ### `data` -Write the computed template data in JSON format to stdout. The `data` command -accepts additional flags: - -#### `-f`, `--format` *format* - -Print the computed template data in the given format. The accepted formats are -`json` (JSON), `toml` (TOML), and `yaml` (YAML). +Write the computed template data to stdout. #### `data` examples @@ -536,31 +719,10 @@ Print the difference between the target state and the destination state for If a `diff.pager` command is set in the configuration file then the output will be piped into it. -#### `-f`, `--format` *format* - -Print the diff in *format*. The format can be set with the `diff.format` -variable in the configuration file. Valid formats are: - -##### `chezmoi` - -A mix of unified diffs and pseudo shell commands, including scripts, equivalent -to `chezmoi apply --dry-run --verbose`. - -##### `git` - -A [git format diff](https://git-scm.com/docs/diff-format), excluding scripts. In -version 2.0.0 of chezmoi, `git` format diffs will become the default and include -scripts and the `chezmoi` format will be removed. - -#### `--no-pager` - -Do not use the pager. - #### `diff` examples chezmoi diff chezmoi diff ~/.bashrc - chezmoi diff --format=git ### `docs` [*regexp*] @@ -583,13 +745,12 @@ Check for potential problems. ### `dump` [*targets*] -Dump the target state in JSON format. If no targets are specified, then the -entire target state. The `dump` command accepts additional arguments: +Dump the target state. If no targets are specified, then the entire target +state. -#### `-f`, `--format` *format* +#### `-i`, `--include` *types* -Print the target state in the given format. The accepted formats are `json` -(JSON) and `yaml` (YAML). +Only include entries of type *types*. #### `dump` examples @@ -606,19 +767,10 @@ targets are given the the source directory itself is opened with `$EDITOR`. The Apply target immediately after editing. Ignored if there are no targets. -#### `-d`, `--diff` - -Print the difference between the target state and the actual state after -editing.. Ignored if there are no targets. - -#### `-p`, `--prompt` - -Prompt before applying each target.. Ignored if there are no targets. - #### `edit` examples chezmoi edit ~/.bashrc - chezmoi edit ~/.bashrc --apply --prompt + chezmoi edit ~/.bashrc --apply chezmoi edit ### `edit-config` @@ -640,10 +792,6 @@ the template is read from stdin. Include simulated functions only available during `chezmoi init`. -#### `--output`, `-o` *filename* - -Write the output to *filename* instead of stdout. - #### `--promptBool` *pairs* Simulate the `promptBool` function with a function that returns values from @@ -695,39 +843,66 @@ must occur after `--` to prevent chezmoi from interpreting them. Print the help associated with *command*. -### `hg` [*arguments*] - -Run `hg` *arguments* in the source directory. Note that flags in *arguments* -must occur after `--` to prevent chezmoi from interpreting them. - -#### `hg` examples - - chezmoi hg -- pull --rebase --update - ### `init` [*repo*] -Setup the source directory and update the destination directory to match the -target state. +Setup the source directory, generate the config file, and optionally update +the destination directory to match the target state. *repo* is expanded to a +full git repo URL using the following rules: + +| Pattern | Repo | +| ------------------ | -------------------------------------- | +| `user` | `https://github.com/user/dotfiles.git` | +| `user/repo` | `https://github.com/user/repo.git` | +| `site/user/repo` | `https://site/user/repo.git` | +| `~sr.ht/user` | `https://git.sr.ht/~user/dotfiles` | +| `~sr.ht/user/repo` | `https://git.sr.ht/~user/repo` | First, if the source directory is not already contain a repository, then if *repo* is given it is checked out into the source directory, otherwise a new repository is initialized in the source directory. -Second, if a file called `.chezmoi.format.tmpl` exists, where `format` is one of -the supported file formats (e.g. `json`, `toml`, or `yaml`) then a new +Second, if a file called `.chezmoi.<format>.tmpl` exists, where `<format>` is +one of the supported file formats (e.g. `json`, `toml`, or `yaml`) then a new configuration file is created using that file as a template. -Finally, if the `--apply` flag is passed, `chezmoi apply` is run. +Then, if the `--apply` flag is passed, `chezmoi apply` is run. + +Then, if the `--purge` flag is passed, chezmoi will remove the source directory +and its config directory. + +Finally, if the `--purge-binary` is passed, chezmoi will attempt to remove its +own binary. #### `--apply` Run `chezmoi apply` after checking out the repo and creating the config file. -This is `false` by default. + +#### `--depth` *depth* + +Clone the repo with depth *depth*. + +#### `--one-shot` + +`--one-shot` is the equivalent of `--apply`, `--depth=1`, `--purge`, +`--purge-binary`. It attempts to install your dotfiles with chezmoi and then +remove all traces of chezmoi from the system. This is useful for setting up +temporary environments (e.g. Docker containers). + +#### `--purge` + +Remove the source and config directories after applying. + +#### `--purge-binary` + +Attempt to remove the chezmoi binary after applying. #### `init` examples - chezmoi init https://github.com/user/dotfiles.git - chezmoi init https://github.com/user/dotfiles.git --apply + chezmoi init user + chezmoi init user --apply + chezmoi init user --apply --purge + chezmoi init user/dots + chezmoi init gitlab.com/user ### `import` *filename* @@ -742,7 +917,7 @@ The only supported archive format is `.tar.gz`. Set the destination (in the source state) where the archive will be imported. -#### `-x`, `--exact` +#### `--exact` Set the `exact` attribute on all imported directories. @@ -769,10 +944,7 @@ List all managed entries in the destination directory in alphabetical order. #### `-i`, `--include` *types* -Only list entries of type *types*. *types* is a comma-separated list of types of -entry to include. Valid types are `dirs`, `files`, and `symlinks` which can be -abbreviated to `d`, `f`, and `s` respectively. By default, `manage` will list -entries of all types. +Only include entries of type *types*. #### `managed` examples @@ -784,8 +956,8 @@ entries of all types. ### `merge` *targets* -Perform a three-way merge between the destination state, the source state, and -the target state. The merge tool is defined by the `merge.command` configuration +Perform a three-way merge between the destination state, the target state, and +the source state. The merge tool is defined by the `merge.command` configuration variable, and defaults to `vimdiff`. If multiple targets are specified the merge tool is invoked for each target. If the target state cannot be computed (for example if source is a template containing errors or an encrypted file that @@ -835,27 +1007,8 @@ To get a full list of available commands run: #### `secret` examples - chezmoi secret bitwarden list items - chezmoi secret keyring set --service service --user user - chezmoi secret keyring get --service service --user user - chezmoi secret lastpass ls - chezmoi secret lastpass -- show --format=json id - chezmoi secret onepassword list items - chezmoi secret onepassword get item id - chezmoi secret pass show id - chezmoi secret vault -- kv get -format=json id - -### `source` [*args*] - -Execute the source version control system in the source directory with *args*. -Note that any flags for the source version control system must be separated with -a `--` to stop chezmoi from reading them. - -#### `source` examples - - chezmoi source init - chezmoi source add . - chezmoi source commit -- -m "Initial commit" + chezmoi secret keyring set --service=service --user=user --value=password + chezmoi secret keyring get --service=service --user=user ### `source-path` [*targets*] @@ -867,6 +1020,32 @@ print the source directory. chezmoi source-path chezmoi source-path ~/.bashrc +### `state` + +Manipulate the persistent state. + +#### `state` examples + + chezmoi state dump + chemzoi state reset + +### `status` + +Print the status of the files and scripts managed by chezmoi in a format similar +to [`git status`](https://git-scm.com/docs/git-status). + +The first column of output indicates the difference between the last state +written by chezmoi and the actual state. The second column indicates the +difference between the actual state and the target state. + +#### `-i`, `--include` *types* + +Only include entries of type *types*. + +#### `status` examples + + chezmoi status + ### `unmanage` *targets* `unmanage` is an alias for `forget` for symmetry with `manage`. @@ -883,31 +1062,13 @@ List all unmanaged files in the destination directory. Pull changes from the source VCS and apply any changes. -#### `update` examples - - chezmoi update - -### `upgrade` - -Upgrade chezmoi by downloading and installing the latest released version. This -will call the GitHub API to determine if there is a new version of chezmoi -available, and if so, download and attempt to install it in the same way as -chezmoi was previously installed. - -If chezmoi was installed with a package manager (`dpkg` or `rpm`) then `upgrade` -will download a new package and install it, using `sudo` if it is installed. -Otherwise, chezmoi will download the latest executable and replace the existing -executable with the new version. +#### `-i`, `--include` *types* -If the `CHEZMOI_GITHUB_API_TOKEN` environment variable is set, then its value -will be used to authenticate requests to the GitHub API, otherwise -unauthenticated requests are used which are subject to stricter [rate -limiting](https://developer.github.com/v3/#rate-limiting). Unauthenticated -requests should be sufficient for most cases. +Only update entries of type *types*. -#### `upgrade` examples +#### `update` examples - chezmoi upgrade + chezmoi update ### `verify` [*targets*] @@ -915,6 +1076,10 @@ Verify that all *targets* match their target state. chezmoi exits with code 0 (success) if all targets match their target state, or 1 (failure) otherwise. If no targets are specified then all targets are checked. +#### `-i`, `--include` *types* + +Only include entries of type *types*. + #### `verify` examples chezmoi verify @@ -967,20 +1132,21 @@ For a full list of options, see ## Template variables -chezmoi provides the following automatically populated variables: +chezmoi provides the following automatically-populated variables: | Variable | Value | | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------- | | `.chezmoi.arch` | Architecture, e.g. `amd64`, `arm`, etc. as returned by [runtime.GOARCH](https://pkg.go.dev/runtime?tab=doc#pkg-constants). | -| `.chezmoi.fullHostname` | The full hostname of the machine chezmoi is running on. | +| `.chezmoi.fqdnHostname` | The fully-qualified domain name hostname of the machine chezmoi is running on. | | `.chezmoi.group` | The group of the user running chezmoi. | -| `.chezmoi.homedir` | The home directory of the user running chezmoi. | +| `.chezmoi.homeDir` | The home directory of the user running chezmoi. | | `.chezmoi.hostname` | The hostname of the machine chezmoi is running on, up to the first `.`. | | `.chezmoi.kernel` | Contains information from `/proc/sys/kernel`. Linux only, useful for detecting specific kernels (i.e. Microsoft's WSL kernel). | | `.chezmoi.os` | Operating system, e.g. `darwin`, `linux`, etc. as returned by [runtime.GOOS](https://pkg.go.dev/runtime?tab=doc#pkg-constants). | | `.chezmoi.osRelease` | The information from `/etc/os-release`, Linux only, run `chezmoi data` to see its output. | | `.chezmoi.sourceDir` | The source directory. | | `.chezmoi.username` | The username of the user running chezmoi. | +| `.chezmoi.version` | The version of chezmoi. | Additional variables can be defined in the config file in the `data` section. Variable names must consist of a letter and be followed by zero or more letters @@ -1086,6 +1252,20 @@ the same arguments will only invoke `bw get` once. {{ (bitwardenFields "item" "<itemid>").token.value }} +### `gitHubKeys` *user* + +`gitHubKeys` returns *user*'s public SSH keys from GitHub using the GitHub API. +If any of the environment variables `CHEZMOI_GITHUB_ACCESS_TOKEN`, +`GITHUB_ACCESS_TOKEN`, or `GITHUB_TOKEN` are found, then the first one found +will be used to authenticate the API request, otherwise an anonymous API request +will be used, which may be subject to lower rate limits. + +#### `gitHubKeys` examples + + {{ range (gitHubKeys "user") }} + {{- .Key }} + {{- end }} + ### `gopass` *gopass-name* `gopass` returns passwords stored in [gopass](https://www.gopass.pw/) using the @@ -1129,7 +1309,7 @@ first non-empty element is a UNC path. #### `joinPath` examples - {{ joinPath .chezmoi.homedir ".zshrc" }} + {{ joinPath .chezmoi.homeDir ".zshrc" }} ### `keepassxc` *entry* @@ -1327,19 +1507,24 @@ the same *pass-name* will only invoke `pass` once. ### `promptBool` *prompt* `promptBool` prompts the user with *prompt* and returns the user's response with -interpreted as a boolean. It is only available when generating the initial -config file. +interpreted as a boolean. It is only available when generating the initial +config file. The user's response is interpreted as follows (case insensitive): + +| Response | Result | +| ----------------------- | ------- | +| 1, on, t, true, y, yes | `true` | +| 0, off, f, false, n, no | `false` | ### `promptInt` *prompt* `promptInt` prompts the user with *prompt* and returns the user's response with -interpreted as an integer. It is only available when generating the initial +interpreted as an integer. It is only available when generating the initial config file. ### `promptString` *prompt* `promptString` prompts the user with *prompt* and returns the user's response -with all leading and trailing spaces stripped. It is only available when +with all leading and trailing spaces stripped. It is only available when generating the initial config file. #### `promptString` examples @@ -1351,16 +1536,16 @@ generating the initial config file. ### `secret` [*args*] `secret` returns the output of the generic secret command defined by the -`genericSecret.command` configuration variable with *args* with leading and -trailing whitespace removed. The output is cached so multiple calls to `secret` -with the same *args* will only invoke the generic secret command once. +`secret.command` configuration variable with *args* with leading and trailing +whitespace removed. The output is cached so multiple calls to `secret` with the +same *args* will only invoke the generic secret command once. ### `secretJSON` [*args*] `secretJSON` returns structured data from the generic secret command defined by -the `genericSecret.command` configuration variable with *args*. The output is -parsed as JSON. The output is cached so multiple calls to `secret` with the same -*args* will only invoke the generic secret command once. +the `secret.command` configuration variable with *args*. The output is parsed as +JSON. The output is cached so multiple calls to `secret` with the same *args* +will only invoke the generic secret command once. ### `stat` *name* @@ -1376,7 +1561,7 @@ templates. #### `stat` examples - {{ if stat (joinPath .chezmoi.homedir ".pyenv") }} + {{ if stat (joinPath .chezmoi.homeDir ".pyenv") }} # ~/.pyenv exists {{ end }} diff --git a/docs/docs.go b/docs/docs.go new file mode 100644 index 00000000000..d25784f4cc8 --- /dev/null +++ b/docs/docs.go @@ -0,0 +1,8 @@ +// Package docs contains chezmoi's documentation. +package docs + +import "embed" + +// FS contains all docs. +//go:embed *.md +var FS embed.FS diff --git a/go.mod b/go.mod index 1f1d032816f..98d9848e710 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/twpayne/chezmoi -go 1.14 +go 1.16 require ( github.com/Masterminds/sprig/v3 v3.2.2 @@ -28,33 +28,31 @@ require ( github.com/mitchellh/copystructure v1.1.1 // indirect github.com/mitchellh/mapstructure v1.4.1 // indirect github.com/muesli/combinator v0.3.0 - github.com/olekukonko/tablewriter v0.0.5 // indirect github.com/pelletier/go-toml v1.8.1 - github.com/pkg/diff v0.0.0-20200914180035-5b29258ca4f7 github.com/rivo/uniseg v0.2.0 // indirect github.com/rogpeppe/go-internal v1.7.0 github.com/rs/zerolog v1.20.0 github.com/sergi/go-diff v1.1.0 github.com/smartystreets/assertions v1.2.0 // indirect github.com/spf13/afero v1.5.1 // indirect - github.com/spf13/cobra v1.1.3 + github.com/spf13/cobra v1.1.1 github.com/spf13/jwalterweatherman v1.1.0 // indirect github.com/spf13/viper v1.7.1 github.com/stretchr/objx v0.3.0 // indirect github.com/stretchr/testify v1.7.0 github.com/twpayne/go-shell v0.3.0 - github.com/twpayne/go-vfs v1.7.2 - github.com/twpayne/go-vfsafero v1.0.0 + github.com/twpayne/go-vfs v1.7.3-0.20210129215858-658742f25bb8 // indirect + github.com/twpayne/go-vfs/v2 v2.0.0 + github.com/twpayne/go-vfsafero/v2 v2.0.0 github.com/twpayne/go-xdg/v3 v3.1.0 github.com/xanzy/ssh-agent v0.3.0 // indirect - github.com/yuin/goldmark v1.3.2 // indirect github.com/zalando/go-keyring v0.1.1 go.etcd.io/bbolt v1.3.5 go.uber.org/multierr v1.6.0 golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad // indirect golang.org/x/net v0.0.0-20210119194325-5f4716e94777 // indirect - golang.org/x/oauth2 v0.0.0-20210216194517-16ff1888fd2e - golang.org/x/sys v0.0.0-20210216163648-f7da38b97c65 + golang.org/x/oauth2 v0.0.0-20210201163806-010130855d6c + golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c golang.org/x/term v0.0.0-20201210144234-2321bbc49cbf golang.org/x/text v0.3.5 // indirect google.golang.org/appengine v1.6.7 // indirect diff --git a/go.sum b/go.sum index f6eb5b4de40..498bd1d877a 100644 --- a/go.sum +++ b/go.sum @@ -32,7 +32,6 @@ cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohl cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= -github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI= @@ -41,7 +40,6 @@ github.com/Masterminds/semver/v3 v3.1.1 h1:hLg3sBzpNErnxhQtUy/mmLR2I9foDujNK030I github.com/Masterminds/semver/v3 v3.1.1/go.mod h1:VPu/7SZ7ePZ3QOrcuXROw5FAcLl4a0cBrbBpGY/8hQs= github.com/Masterminds/sprig/v3 v3.2.2 h1:17jRggJu518dr3QaafizSXOjKYp94wKfABxUmyxvxX8= github.com/Masterminds/sprig/v3 v3.2.2/go.mod h1:UoaO7Yp8KlPnJIYWTFkMaqPUYKTfGFPhxNuwnnxkKlk= -github.com/Microsoft/go-winio v0.4.14 h1:+hMXMk01us9KgxGb7ftKQt2Xpf5hH/yky+TDA+qxleU= github.com/Microsoft/go-winio v0.4.14/go.mod h1:qXqCSQ3Xa7+6tgxaGTIe4Kpcdsi+P8jBhyzoq1bpyYA= github.com/Microsoft/go-winio v0.4.16 h1:FtSW/jqD+l4ba5iPBj9CODVtgfYAD8w2wS923g/cFDk= github.com/Microsoft/go-winio v0.4.16/go.mod h1:XB6nPKklQyQ7GC9LdcBEcBl8PF76WugXOPRXwdLnMv0= @@ -53,12 +51,10 @@ github.com/alecthomas/assert v0.0.0-20170929043011-405dbfeb8e38/go.mod h1:r7bzyV github.com/alecthomas/chroma v0.8.1/go.mod h1:sko8vR34/90zvl5QdcUdvzL3J8NKjAUx9va9jPuFNoM= github.com/alecthomas/chroma v0.8.2 h1:x3zkuE2lUk/RIekyAJ3XRqSCP4zwWDfcw/YJCuCAACg= github.com/alecthomas/chroma v0.8.2/go.mod h1:sko8vR34/90zvl5QdcUdvzL3J8NKjAUx9va9jPuFNoM= -github.com/alecthomas/colour v0.0.0-20160524082231-60882d9e2721 h1:JHZL0hZKJ1VENNfmXvHbgYlbUOvpzYzvy2aZU5gXVeo= github.com/alecthomas/colour v0.0.0-20160524082231-60882d9e2721/go.mod h1:QO9JBoKquHd+jz9nshCh40fOfO+JzsoXy8qTHF68zU0= github.com/alecthomas/colour v0.1.0 h1:nOE9rJm6dsZ66RGWYSFrXw461ZIt9A6+nHgL7FRrDUk= github.com/alecthomas/colour v0.1.0/go.mod h1:QO9JBoKquHd+jz9nshCh40fOfO+JzsoXy8qTHF68zU0= github.com/alecthomas/kong v0.2.4/go.mod h1:kQOmtJgV+Lb4aj+I2LEn40cbtawdWJ9Y8QLq+lElKxE= -github.com/alecthomas/repr v0.0.0-20180818092828-117648cd9897 h1:p9Sln00KOTlrYkxI1zYWl1QLnEqAqEARBEYa8FQnQcY= github.com/alecthomas/repr v0.0.0-20180818092828-117648cd9897/go.mod h1:xTS7Pm1pD1mvyM075QCDSRqH6qRLXylzS24ZTpRiSzQ= github.com/alecthomas/repr v0.0.0-20201120212035-bb82daffcca2 h1:G5TeG64Ox4OWq2YwlsxS7nOedU8vbGgNRTRDAjGvDCk= github.com/alecthomas/repr v0.0.0-20201120212035-bb82daffcca2/go.mod h1:2kn6fqh/zIyPLmm3ugklbEi5hg5wS435eygvNfaDQL8= @@ -107,7 +103,6 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= -github.com/dlclark/regexp2 v1.2.0 h1:8sAhBGEM0dRWogWqWyQeIJnxjWO6oIjl8FKqREDsGfk= github.com/dlclark/regexp2 v1.2.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc= github.com/dlclark/regexp2 v1.4.0 h1:F1rxgk7p4uKjwIQxBs9oAXe5CqrXlCduYEJvrF4u93E= github.com/dlclark/regexp2 v1.4.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc= @@ -118,9 +113,7 @@ github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.m github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= -github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568 h1:BHsljHzVlRcyQhjrss6TZTdY2VfCqZPbv5k3iBFa2ZQ= github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc= -github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= @@ -158,9 +151,7 @@ github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= -github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.1 h1:YF8+flBXS5eO826T4nzqPrxfhQThhXl0YzfuUPu4SBg= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= @@ -170,10 +161,8 @@ github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= -github.com/golang/protobuf v1.4.0 h1:oOuy+ugB+P/kBdUnG5QaMXSIyJ1q38wWSojYCb3z5VQ= github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= -github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0= github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.4.3 h1:JjCZWpVbqXDqFVmTfYWEVTMIYrL/NPdPSCHPJ0T/raM= github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= @@ -182,12 +171,9 @@ github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.4.0 h1:xsAVV57WRhGj6kEIi8ReJzQlHHqcBYCElAvkovg3B/4= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.0 h1:/QaMHBdZ26BB3SSst0Iwl10Epc+xhTquomWX0oZEB6w= github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.1 h1:JFrFEBb2xKufg6XkJsJr+WbKb4FQlURi5RUcBveYu9k= github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.4 h1:L8R9j+yAqZuZjsqh/z+F1NCffTKKLShY6zXTItVIZ8M= github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= @@ -204,17 +190,14 @@ github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hf github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/renameio v0.1.0 h1:GOZbcHa3HfsPKPlmyPyN2KEohoMXOhdMbHrvbpl2QaA= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= github.com/google/renameio v1.0.0 h1:xhp2CnJmgQmpJU4RY8chagahUq5mbPPAbiSQstKpVMA= github.com/google/renameio v1.0.0/go.mod h1:t/HQoYBZSsWSNK35C6CO/TpPLDVWvxOHboWUAweKUpk= -github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.2.0 h1:qJYtXnJRWmpe7m/3XlyhrsLrEURqHRM2kxzoxXqyUDs= github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= -github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gopherjs/gopherjs v0.0.0-20200217142428-fce0ec30dd00 h1:l5lAOZEym3oK3SQ2HBHWsJUfbNBiTXJDeW2QDxw9AQ0= github.com/gopherjs/gopherjs v0.0.0-20200217142428-fce0ec30dd00/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= @@ -249,7 +232,6 @@ github.com/huandu/xstrings v1.3.1/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq github.com/huandu/xstrings v1.3.2 h1:L18LIDzqlW6xN2rEkpdV8+oL/IXWJ1APd+vsdYy4Wdw= github.com/huandu/xstrings v1.3.2/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= -github.com/imdario/mergo v0.3.9 h1:UauaLniWCFHWd+Jp9oCEkTBj8VO/9DKg3PV3VCNMDIg= github.com/imdario/mergo v0.3.9/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= github.com/imdario/mergo v0.3.11 h1:3tnifQM4i+fbajXKBHXWEH+KvNHqojZ778UH75j3bGA= github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= @@ -265,7 +247,6 @@ github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/X github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= -github.com/kevinburke/ssh_config v0.0.0-20190725054713-01f96b0aa0cd h1:Coekwdh0v2wtGp9Gmz1Ze3eVRAWJMLokvN3QjdzCHLY= github.com/kevinburke/ssh_config v0.0.0-20190725054713-01f96b0aa0cd/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM= github.com/kevinburke/ssh_config v0.0.0-20201106050909-4977a11b4351 h1:DowS9hvgyYSX4TO5NpyC606/Z4SxnNYbT+WX27or6Ck= github.com/kevinburke/ssh_config v0.0.0-20201106050909-4977a11b4351/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM= @@ -274,20 +255,16 @@ github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+o github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= -github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/lucasb-eyer/go-colorful v1.0.3 h1:QIbQXiugsb+q10B+MI+7DI1oQLdmnep86tWFlaaUAac= github.com/lucasb-eyer/go-colorful v1.0.3/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= -github.com/magiconair/properties v1.8.1 h1:ZC2Vc7/ZFkGmsVC9KvOjumD+G5lXy2RtTKyzRKO2BQ4= github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.4 h1:8KGKTcQQGm0Kv7vEbKFErAoAOFyyacLStRtQSeYtvkY= github.com/magiconair/properties v1.8.4/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= @@ -296,9 +273,7 @@ github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= -github.com/mattn/go-runewidth v0.0.7 h1:Ei8KR0497xHyKJPAv59M1dkC+rOZCMBJ+t3fZ+twI54= github.com/mattn/go-runewidth v0.0.7/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= -github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.10 h1:CoZ3S2P7pvtP45xOtBw+/mDL2z0RKI576gSkzRRpdGg= github.com/mattn/go-runewidth v0.0.10/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= @@ -307,7 +282,6 @@ github.com/microcosm-cc/bluemonday v1.0.4 h1:p0L+CTpo/PLFdkoPcJemLXG+fpMD7pYOoDE github.com/microcosm-cc/bluemonday v1.0.4/go.mod h1:8iwZnFn2CDDNZ0r6UXhF4xawGvzaqzCRa1n3/lO3W2w= github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= -github.com/mitchellh/copystructure v1.0.0 h1:Laisrj+bAB6b/yJwB5Bt3ITZhGJdqmxquMKeZ+mmkFQ= github.com/mitchellh/copystructure v1.0.0/go.mod h1:SNtv71yrdKgLRyLFxmLdkAbkKEFWgYaq1OVrnRcwhnw= github.com/mitchellh/copystructure v1.1.1 h1:Bp6x9R1Wn16SIz3OfeDr0b7RnCG2OB66Y7PQyC/cvq4= github.com/mitchellh/copystructure v1.1.1/go.mod h1:EBArHfARyrSWO/+Wyr9zwEkc6XMFB9XyNgFNmRkZZU4= @@ -318,11 +292,9 @@ github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eI github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg= github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY= github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= -github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.4.1 h1:CpVNEelQCZBooIPDn+AR3NpivK/TIKU8bDxdASFVQag= github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= -github.com/mitchellh/reflectwalk v1.0.0 h1:9D+8oIskB4VJBN5SFlmc27fSlIBZaov1Wpk/IfikLNY= github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= github.com/mitchellh/reflectwalk v1.0.1 h1:FVzMWA5RllMAKIdUSC8mdWo3XtwoecrH79BY70sEEpE= github.com/mitchellh/reflectwalk v1.0.1/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= @@ -335,20 +307,14 @@ github.com/muesli/reflow v0.2.0/go.mod h1:qT22vjVmM9MIUeLgsVYe/Ye7eZlbv9dZjL3dVh github.com/muesli/termenv v0.7.4 h1:/pBqvU5CpkY53tU0vVn+xgs2ZTX63aH5nY+SSps5Xa8= github.com/muesli/termenv v0.7.4/go.mod h1:pZ7qY9l3F7e5xsAOS0zCew2tME+p7bWeBkotCEcIIcc= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= -github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= github.com/olekukonko/tablewriter v0.0.4 h1:vHD/YYe1Wolo78koG299f7V/VAS08c6IpCLn+Ejf/w8= github.com/olekukonko/tablewriter v0.0.4/go.mod h1:zq6QwlOf5SlnkVbMSr5EoBv3636FWnp+qbPhuoO21uA= -github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= -github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= -github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pelletier/go-toml v1.8.1 h1:1Nf83orprkJyknT6h7zbuEGUEjcyVlCxSUGTENmNCRM= github.com/pelletier/go-toml v1.8.1/go.mod h1:T2/BmBdy8dvIRq1a/8aqjN41wvWlN4lrapLU/GW4pbc= -github.com/pkg/diff v0.0.0-20200914180035-5b29258ca4f7 h1:+/+DxvQaYifJ+grD4klzrS5y+KJXldn/2YTl5JG+vZ8= -github.com/pkg/diff v0.0.0-20200914180035-5b29258ca4f7/go.mod h1:zO8QMzTeZd5cpnIkz/Gn6iK0jDfGicM1nynOkkPIl28= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= @@ -367,7 +333,6 @@ github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y8 github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= -github.com/rivo/uniseg v0.1.0 h1:+2KBaVoUmb9XzDsrx/Ct0W/EYOSFf/nWTauy++DprtY= github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= @@ -381,17 +346,14 @@ github.com/rs/zerolog v1.20.0/go.mod h1:IzD0RJ65iWH0w97OQQebJEvTZYvsCUm9WVLWBQrJ github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= -github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ= github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0= github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= github.com/shopspring/decimal v1.2.0 h1:abSATXmQEYyShuxI4/vyW3tV1MrKAJzCZ/0zLUXYbsQ= github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= -github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= -github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/assertions v1.2.0 h1:42S6lae5dvLc7BrLu/0ugRtcFVjoJNMC/N3yZFZkDFs= github.com/smartystreets/assertions v1.2.0/go.mod h1:tcbTF8ujkAEcZ8TElKY+i30BzYlVhC/LOxJk7iOWnoo= @@ -399,21 +361,17 @@ github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIK github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= -github.com/spf13/afero v1.1.2 h1:m8/z1t7/fwjysjQRYbP0RD+bUIF/8tJwPdEZsI83ACI= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= github.com/spf13/afero v1.5.1 h1:VHu76Lk0LSP1x254maIu2bplkWpfBWI+B+6fdoZprcg= github.com/spf13/afero v1.5.1/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I= -github.com/spf13/cast v1.3.0 h1:oget//CVOEoFewqQxwr0Ej5yjygnqGkvggSE/gB35Q8= github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng= github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= -github.com/spf13/cobra v1.1.3 h1:xghbfqPkxzxP3C/f3n5DdpAbdKLj4ZE4BWQI362l53M= -github.com/spf13/cobra v1.1.3/go.mod h1:pGADOWyqRD/YMrPZigI/zbliZ2wVD/23d+is3pSWzOo= -github.com/spf13/jwalterweatherman v1.0.0 h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9Gc1vn7yk= +github.com/spf13/cobra v1.1.1 h1:KfztREH0tPxJJ+geloSLaAkaPkr4ki2Er5quFV1TDo4= +github.com/spf13/cobra v1.1.1/go.mod h1:WnodtKOvamDL/PwE2M4iKs8aMDBZ5Q5klgD3qfVJQMI= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= -github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= @@ -421,15 +379,11 @@ github.com/spf13/viper v1.7.0/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5q github.com/spf13/viper v1.7.1 h1:pM5oEahlgWv/WnHXpgbKz7iLIxRf65tye2Ci+XFK5sk= github.com/spf13/viper v1.7.1/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.1.1 h1:2vfRuCMp5sSVIDSqO8oNnWJq7mPa6KVP3iPIwFBuy8A= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.3.0 h1:NGXK3lHquSN08v5vWalVI/L8XU9hdzE/G6xsrze47As= github.com/stretchr/objx v0.3.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= -github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= @@ -439,15 +393,15 @@ github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69 github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/twpayne/go-shell v0.3.0 h1:nhDM9cQTqWwA0jGPOnqzsw8lke2jcKpvxDgnDO8Lq9o= github.com/twpayne/go-shell v0.3.0/go.mod h1:H/gzux0DOH5jsjQSHXs6rs2Onxy+V4j6ycZTOulC0l8= -github.com/twpayne/go-vfs v1.0.1/go.mod h1:OIXA6zWkcn7Jk46XT7ceYqBMeIkfzJ8WOBhGJM0W4y8= github.com/twpayne/go-vfs v1.0.5/go.mod h1:OIXA6zWkcn7Jk46XT7ceYqBMeIkfzJ8WOBhGJM0W4y8= -github.com/twpayne/go-vfs v1.7.2 h1:ZNYMAXcu2Av8c109USrSGYm8dIIIV0xPlG19I2088Kw= -github.com/twpayne/go-vfs v1.7.2/go.mod h1:1eni2ntkiiAHZG27xfLOO4CYvMR4Kw8V7rYiLeeolsQ= -github.com/twpayne/go-vfsafero v1.0.0 h1:ZlH32HF4OoVX/aRqc5bZa+2+M+/ezmJ4XYpT0ShtZNc= -github.com/twpayne/go-vfsafero v1.0.0/go.mod h1:rs2H15b2z0euJzwyoBS63eUHZgBhNXVQfIFfRp8DKEk= +github.com/twpayne/go-vfs v1.7.3-0.20210129215858-658742f25bb8 h1:8hYlLPrl1WFtURPQV0aOecX3lKQBwJHJSmAlqZdD9s0= +github.com/twpayne/go-vfs v1.7.3-0.20210129215858-658742f25bb8/go.mod h1:MC0lC+P5tifCoaO/eG2o8WKCIitKXX3H1z0nM55hTt8= +github.com/twpayne/go-vfs/v2 v2.0.0 h1:5d+ZV/CykPJ6j6rWZM2ryDpxpZ/4CHCGI25wYHYIWnw= +github.com/twpayne/go-vfs/v2 v2.0.0/go.mod h1:3GuKRK08/13III2MHAoZICcJ27R24cA7ww25zmYkXhc= +github.com/twpayne/go-vfsafero/v2 v2.0.0 h1:tjyzcCqvGiGCM3QfEFjOQyxcrpnDWmd12E4om5d2UJg= +github.com/twpayne/go-vfsafero/v2 v2.0.0/go.mod h1:koxNu1Og/cUvP8IhNihhaOMO1txRitlBONUYIKcevEQ= github.com/twpayne/go-xdg/v3 v3.1.0 h1:AxX5ZLJIzqYHJh+4uGxWT97ySh1ND1bJLjqMxdYF+xs= github.com/twpayne/go-xdg/v3 v3.1.0/go.mod h1:z6/LkoG2gtuzrsxEqPRoEjccS5Q35GK+lguVP0K3L9o= -github.com/xanzy/ssh-agent v0.2.1 h1:TCbipTQL2JiiCprBWx9frJ2eJlCYT00NmctrHxVAr70= github.com/xanzy/ssh-agent v0.2.1/go.mod h1:mLlQY/MoOhWBj+gOGMQkOeiEvkx+8pJSI+0Bx9h2kr4= github.com/xanzy/ssh-agent v0.3.0 h1:wUMzuKtKilRgBAD1sUb8gOwwRr2FGoBVumcjoOACClI= github.com/xanzy/ssh-agent v0.3.0/go.mod h1:3s9xbODqPuuhK9JV1R321M/FlMZSBvE5aY6eAcqrDh0= @@ -458,8 +412,6 @@ github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.1 h1:eVwehsLsZlCJCwXyGLgg+Q4iFWE/eTIMG0e8waCmm/I= github.com/yuin/goldmark v1.3.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= -github.com/yuin/goldmark v1.3.2 h1:YjHC5TgyMmHpicTgEqDN0Q96Xo8K6tLXPnmNOHXCgs0= -github.com/yuin/goldmark v1.3.2/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark-emoji v1.0.1 h1:ctuWEyzGBwiucEqxzwe0SOYDXPAucOrE9NQC18Wa1os= github.com/yuin/goldmark-emoji v1.0.1/go.mod h1:2w1E6FEWLcDQkoTE+7HU6QF1F6SLlNGjRIBbIZQFqkQ= github.com/zalando/go-keyring v0.1.1 h1:w2V9lcx/Uj4l+dzAf1m9s+DJ1O8ROkEHnynonHjTcYE= @@ -472,11 +424,9 @@ go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -go.uber.org/atomic v1.4.0 h1:cxzIVoETapQEqDhQu3QfnvXAV4AlzcvUCxkVUFw3+EU= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= -go.uber.org/multierr v1.1.0 h1:HoEmRHQPVSqub6w2z2d2EOVs2fjyFRGyofhKuyDq0QI= go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= go.uber.org/multierr v1.6.0 h1:y6IPFStTAIT5Ytl7/XYmHvzXQ7S3g/IeZW9hyZ5thw4= go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= @@ -484,7 +434,6 @@ go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190219172222-a4c6cb3142f2/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= @@ -492,7 +441,6 @@ golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200414173820-0848c9571904/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad h1:DN0cp81fZ3njFcrLCytUHRSUkqBjfTo4Tx9RJTWs0EY= golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= @@ -534,9 +482,7 @@ golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73r golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190311183353-d8887717615a h1:oWX7TPOiFAMXLq8o0ikBYfCJVlRHBcsciT5bXOrH628= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 h1:0GoQqolDA55aaLxZyTzK/Y2ePZzZTUrRacwib7cNsYQ= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= @@ -557,23 +503,19 @@ golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/ golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= -golang.org/x/net v0.0.0-20200822124328-c89045814202 h1:VvcQYSHwXgi7W+TpUR6A9g6Up98WAHf3f/ulnJ62IyA= golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20210119194325-5f4716e94777 h1:003p0dJM77cxMSyCPFphvZf/Y5/NXf5fzg6ufd1/Oew= golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be h1:vEDujvNQGv4jgYKudGeI/+DAX4Jffq6hpD55MmoEvKs= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d h1:TzXSXBo42m9gQenoE3b9BGiEpg5IG2JkU5FkPIawgtw= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20210216194517-16ff1888fd2e h1:xxTKAjlluPXFVQnUNoBO7OvmNNE/RpmyUeLVFSYiQQ0= -golang.org/x/oauth2 v0.0.0-20210216194517-16ff1888fd2e/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210201163806-010130855d6c h1:HiAZXo96zOhVhtFHchj/ojzoxCFiPrp9/j0GtS38V3g= +golang.org/x/oauth2 v0.0.0-20210201163806-010130855d6c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6 h1:bjcUS9ztw9kFmmIxJInhon/0Is3p+EHBKNgquIzo1OI= golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -616,23 +558,16 @@ golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201223074533-0d417f636930 h1:vRgIt+nup/B/BwIS0g2oC0haq0iqbV3ZA+u6+0TlNCo= -golang.org/x/sys v0.0.0-20201223074533-0d417f636930/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210216163648-f7da38b97c65 h1:pTMjDVnP5eVRRlWO76rEWJ8JoC6Lf1CmyjPZXRiy2Sw= -golang.org/x/sys v0.0.0-20210216163648-f7da38b97c65/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/term v0.0.0-20201117132131-f5c789dd3221 h1:/ZHdbVpdR/jk3g30/d4yUL0JU9kksj8+F/bnQUVLGDM= +golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c h1:VwygUrnw9jn88c4u8GD3rZQbqrP/tgas88tPUbBxQrk= +golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 h1:v+OssWQX+hTHEmOBgwxdZxK4zHq3yOs8F9J7mk0PY8E= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20201210144234-2321bbc49cbf h1:MZ2shdL+ZM/XzY3ZGOnh4Nlpnxz5GSOhOmtHo3iPU6M= golang.org/x/term v0.0.0-20201210144234-2321bbc49cbf/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= -golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5 h1:i6eZZ+zk0SOf0xgBpEpPD18qWcJda6q1sxt3S0kzyUQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= @@ -685,7 +620,6 @@ golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -705,13 +639,11 @@ google.golang.org/api v0.24.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0M google.golang.org/api v0.28.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= google.golang.org/api v0.29.0/go.mod h1:Lcubydp8VUV7KeIHD9z2Bys/sm/vGKnG1UHuDBSrHWM= google.golang.org/api v0.30.0/go.mod h1:QGmEvQ87FHZNiUVJkT14jQNYJ4ZJjdRF23ZXz5138Fc= -google.golang.org/appengine v1.1.0 h1:igQkv0AAhEIvTEpD5LIpAfav2eeVO9HBTjvKHVJPRSs= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/appengine v1.6.6 h1:lMO5rYAqUxkmaj76jAkRUvt5JZgFymx/+Q5Mzfivuhc= google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= @@ -760,28 +692,22 @@ google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLY google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= -google.golang.org/protobuf v1.21.0 h1:qdOKuR/EIArgaWNjetjgTzgVTAZ+S/WXVrq9HW9zimw= google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.23.0 h1:4MY060fB1DLGMB/7MBTLnwQUY6+F09GEiz6SsrNqyzM= google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= google.golang.org/protobuf v1.25.0 h1:Ejskq+SyPohKW+1uil0JJMtmHCgJPJ/qWTxr8qp+R4c= google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/errgo.v2 v2.1.0 h1:0vLT13EuvQ0hNvakwLuFZ/jYrLp5F3kcWHXdRggjCE8= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= -gopkg.in/ini.v1 v1.51.0 h1:AQvPpx3LzTDM0AjnIRlVFwFFGC+npRopjZxLJj6gdno= gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/ini.v1 v1.62.0 h1:duBzk771uxoUuOlyRLkHsygud9+5lrlGjdFBb4mSKDU= gopkg.in/ini.v1 v1.62.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= @@ -790,15 +716,12 @@ gopkg.in/warnings.v0 v0.1.2 h1:wFXVbFY8DY5/xOe1ECiWdKCzZlxgshcYVNkBHstARME= gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI= gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.4 h1:/eiJrUcujPVeJ3xlSWaiNi3uSVmDGBK1pDHUHAnao1I= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/chezmoi2/internal/chezmoi/actualstateentry.go b/internal/chezmoi/actualstateentry.go similarity index 100% rename from chezmoi2/internal/chezmoi/actualstateentry.go rename to internal/chezmoi/actualstateentry.go diff --git a/chezmoi2/internal/chezmoi/ageencryption.go b/internal/chezmoi/ageencryption.go similarity index 97% rename from chezmoi2/internal/chezmoi/ageencryption.go rename to internal/chezmoi/ageencryption.go index 751dbadaffc..77dc2134ac9 100644 --- a/chezmoi2/internal/chezmoi/ageencryption.go +++ b/internal/chezmoi/ageencryption.go @@ -6,7 +6,7 @@ import ( "github.com/rs/zerolog/log" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoilog" + "github.com/twpayne/chezmoi/internal/chezmoilog" ) // An AGEEncryption uses age for encryption and decryption. See diff --git a/chezmoi2/internal/chezmoi/ageencryption_test.go b/internal/chezmoi/ageencryption_test.go similarity index 92% rename from chezmoi2/internal/chezmoi/ageencryption_test.go rename to internal/chezmoi/ageencryption_test.go index 5a91bd9e090..6d5f4d0d46e 100644 --- a/chezmoi2/internal/chezmoi/ageencryption_test.go +++ b/internal/chezmoi/ageencryption_test.go @@ -10,7 +10,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoitest" + "github.com/twpayne/chezmoi/internal/chezmoitest" ) func TestAGEEncryption(t *testing.T) { diff --git a/internal/chezmoi/anymutator.go b/internal/chezmoi/anymutator.go deleted file mode 100644 index 512cb492999..00000000000 --- a/internal/chezmoi/anymutator.go +++ /dev/null @@ -1,78 +0,0 @@ -package chezmoi - -import ( - "os" - "os/exec" -) - -// An AnyMutator wraps another Mutator and records if any of its mutating -// methods are called. -type AnyMutator struct { - m Mutator - mutated bool -} - -// NewAnyMutator returns a new AnyMutator. -func NewAnyMutator(m Mutator) *AnyMutator { - return &AnyMutator{ - m: m, - mutated: false, - } -} - -// Chmod implements Mutator.Chmod. -func (m *AnyMutator) Chmod(name string, mode os.FileMode) error { - m.mutated = true - return m.m.Chmod(name, mode) -} - -// IdempotentCmdOutput implements Mutator.IdempotentCmdOutput. -func (m *AnyMutator) IdempotentCmdOutput(cmd *exec.Cmd) ([]byte, error) { - return m.m.IdempotentCmdOutput(cmd) -} - -// Mkdir implements Mutator.Mkdir. -func (m *AnyMutator) Mkdir(name string, perm os.FileMode) error { - m.mutated = true - return m.m.Mkdir(name, perm) -} - -// Mutated returns true if any of its methods have been called. -func (m *AnyMutator) Mutated() bool { - return m.mutated -} - -// RemoveAll implements Mutator.RemoveAll. -func (m *AnyMutator) RemoveAll(name string) error { - m.mutated = true - return m.m.RemoveAll(name) -} - -// Rename implements Mutator.Rename. -func (m *AnyMutator) Rename(oldpath, newpath string) error { - m.mutated = true - return m.m.Rename(oldpath, newpath) -} - -// RunCmd implements Mutator.RunCmd. -func (m *AnyMutator) RunCmd(cmd *exec.Cmd) error { - m.mutated = true - return m.m.RunCmd(cmd) -} - -// Stat implements Mutator.Stat. -func (m *AnyMutator) Stat(path string) (os.FileInfo, error) { - return m.m.Stat(path) -} - -// WriteFile implements Mutator.WriteFile. -func (m *AnyMutator) WriteFile(name string, data []byte, perm os.FileMode, currData []byte) error { - m.mutated = true - return m.m.WriteFile(name, data, perm, currData) -} - -// WriteSymlink implements Mutator.WriteSymlink. -func (m *AnyMutator) WriteSymlink(oldname, newname string) error { - m.mutated = true - return m.m.WriteSymlink(oldname, newname) -} diff --git a/chezmoi2/internal/chezmoi/attr.go b/internal/chezmoi/attr.go similarity index 100% rename from chezmoi2/internal/chezmoi/attr.go rename to internal/chezmoi/attr.go diff --git a/chezmoi2/internal/chezmoi/attr_test.go b/internal/chezmoi/attr_test.go similarity index 100% rename from chezmoi2/internal/chezmoi/attr_test.go rename to internal/chezmoi/attr_test.go diff --git a/internal/chezmoi/autotemplate.go b/internal/chezmoi/autotemplate.go index dbb1c723e17..4f0e70d32d1 100644 --- a/internal/chezmoi/autotemplate.go +++ b/internal/chezmoi/autotemplate.go @@ -1,28 +1,28 @@ package chezmoi import ( - "regexp" "sort" "strings" ) -var delimiterRegexp = regexp.MustCompile(`\{\{+|\}\}+`) - +// A templateVariable is a template variable. It is used instead of a +// map[string]string so that we can control order. type templateVariable struct { name string value string } +// byValueLength implements sort.Interface for a slice of templateVariables, +// sorting by value length. type byValueLength []templateVariable func (b byValueLength) Len() int { return len(b) } func (b byValueLength) Less(i, j int) bool { switch { - case len(b[i].value) < len(b[j].value): + case len(b[i].value) < len(b[j].value): // First sort by value length. return true case len(b[i].value) == len(b[j].value): - // Fallback to name - return b[i].name > b[j].name + return b[i].name > b[j].name // Second sort by value name. default: return false } @@ -30,12 +30,12 @@ func (b byValueLength) Less(i, j int) bool { func (b byValueLength) Swap(i, j int) { b[i], b[j] = b[j], b[i] } func autoTemplate(contents []byte, data map[string]interface{}) []byte { - // FIXME this naive approach will generate incorrect templates if the - // variable names match variable values - // FIXME the algorithm here is probably O(N^2), we can do better - variables := extractVariables(nil, nil, data) + // This naive approach will generate incorrect templates if the variable + // names match variable values. The algorithm here is probably O(N^2), we + // can do better. + variables := extractVariables(data) sort.Sort(sort.Reverse(byValueLength(variables))) - contentsStr := string(templateEscape(contents)) + contentsStr := string(contents) for _, variable := range variables { if variable.value == "" { continue @@ -49,8 +49,8 @@ func autoTemplate(contents []byte, data map[string]interface{}) []byte { contentsStr = contentsStr[:index] + replacement + contentsStr[index+len(variable.value):] index += len(replacement) } else { - // Otherwise, keep looking. Consume at least one byte so we - // make progress. + // Otherwise, keep looking. Consume at least one byte so we make + // progress. index++ } // Look for the next occurrence of variable.value. @@ -67,7 +67,14 @@ func autoTemplate(contents []byte, data map[string]interface{}) []byte { return []byte(contentsStr) } -func extractVariables(variables []templateVariable, parent []string, data map[string]interface{}) []templateVariable { +// extractVariables extracts all template variables from data. +func extractVariables(data map[string]interface{}) []templateVariable { + return extractVariablesHelper(nil /* variables */, nil /* parent */, data) +} + +// extractVariablesHelper appends all template variables in data to variables +// and returns variables. data is assumed to be rooted at parent. +func extractVariablesHelper(variables []templateVariable, parent []string, data map[string]interface{}) []templateVariable { for name, value := range data { switch value := value.(type) { case string: @@ -76,7 +83,7 @@ func extractVariables(variables []templateVariable, parent []string, data map[st value: value, }) case map[string]interface{}: - variables = extractVariables(variables, append(parent, name), value) + variables = extractVariablesHelper(variables, append(parent, name), value) } } return variables @@ -91,14 +98,3 @@ func inWord(s string, i int) bool { func isWord(b byte) bool { return '0' <= b && b <= '9' || 'A' <= b && b <= 'Z' || 'a' <= b && b <= 'z' } - -// templateEscape escapes any template delimiters in data. -func templateEscape(data []byte) []byte { - return delimiterRegexp.ReplaceAllFunc(data, func(match []byte) []byte { - result := make([]byte, 0, len(match)+8) - result = append(result, '{', '{', ' ', '"') - result = append(result, match...) - result = append(result, '"', ' ', '}', '}') - return result - }) -} diff --git a/internal/chezmoi/autotemplate_test.go b/internal/chezmoi/autotemplate_test.go index f923f40636e..ca84a9ac1c1 100644 --- a/internal/chezmoi/autotemplate_test.go +++ b/internal/chezmoi/autotemplate_test.go @@ -11,15 +11,15 @@ func TestAutoTemplate(t *testing.T) { name string contentsStr string data map[string]interface{} - wantStr string + expected string }{ { name: "simple", - contentsStr: "email = [email protected]\n", + contentsStr: "email = [email protected]\n", data: map[string]interface{}{ - "email": "[email protected]", + "email": "[email protected]", }, - wantStr: "email = {{ .email }}\n", + expected: "email = {{ .email }}\n", }, { name: "longest_first", @@ -28,7 +28,9 @@ func TestAutoTemplate(t *testing.T) { "name": "John Smith", "firstName": "John", }, - wantStr: "name = {{ .name }}\nfirstName = {{ .firstName }}\n", + expected: "" + + "name = {{ .name }}\n" + + "firstName = {{ .firstName }}\n", }, { name: "alphabetical_first", @@ -38,17 +40,17 @@ func TestAutoTemplate(t *testing.T) { "beta": "John Smith", "gamma": "John Smith", }, - wantStr: "name = {{ .alpha }}\n", + expected: "name = {{ .alpha }}\n", }, { name: "nested_values", - contentsStr: "email = [email protected]\n", + contentsStr: "email = [email protected]\n", data: map[string]interface{}{ "personal": map[string]interface{}{ - "email": "[email protected]", + "email": "[email protected]", }, }, - wantStr: "email = {{ .personal.email }}\n", + expected: "email = {{ .personal.email }}\n", }, { name: "only_replace_words", @@ -56,39 +58,39 @@ func TestAutoTemplate(t *testing.T) { data: map[string]interface{}{ "os": "darwin", }, - wantStr: "darwinian evolution", // not "{{ .os }}ian evolution" + expected: "darwinian evolution", // not "{{ .os }}ian evolution" }, { name: "longest_match_first", contentsStr: "/home/user", data: map[string]interface{}{ - "homedir": "/home/user", + "homeDir": "/home/user", }, - wantStr: "{{ .homedir }}", + expected: "{{ .homeDir }}", }, { name: "longest_match_first_prefix", contentsStr: "HOME=/home/user", data: map[string]interface{}{ - "homedir": "/home/user", + "homeDir": "/home/user", }, - wantStr: "HOME={{ .homedir }}", + expected: "HOME={{ .homeDir }}", }, { name: "longest_match_first_suffix", contentsStr: "/home/user/something", data: map[string]interface{}{ - "homedir": "/home/user", + "homeDir": "/home/user", }, - wantStr: "{{ .homedir }}/something", + expected: "{{ .homeDir }}/something", }, { name: "longest_match_first_prefix_and_suffix", contentsStr: "HOME=/home/user/something", data: map[string]interface{}{ - "homedir": "/home/user", + "homeDir": "/home/user", }, - wantStr: "HOME={{ .homedir }}/something", + expected: "HOME={{ .homeDir }}/something", }, { name: "words_only", @@ -96,7 +98,7 @@ func TestAutoTemplate(t *testing.T) { data: map[string]interface{}{ "alpha": "a", }, - wantStr: "aaa aa {{ .alpha }} aa aaa aa {{ .alpha }} aa aaa", + expected: "aaa aa {{ .alpha }} aa aaa aa {{ .alpha }} aa aaa", }, { name: "words_only_2", @@ -104,7 +106,7 @@ func TestAutoTemplate(t *testing.T) { data: map[string]interface{}{ "alpha": "aa", }, - wantStr: "aaa {{ .alpha }} a {{ .alpha }} aaa {{ .alpha }} a {{ .alpha }} aaa", + expected: "aaa {{ .alpha }} a {{ .alpha }} aaa {{ .alpha }} a {{ .alpha }} aaa", }, { name: "words_only_3", @@ -112,7 +114,7 @@ func TestAutoTemplate(t *testing.T) { data: map[string]interface{}{ "alpha": "aaa", }, - wantStr: "{{ .alpha }} aa a aa {{ .alpha }} aa a aa {{ .alpha }}", + expected: "{{ .alpha }} aa a aa {{ .alpha }} aa a aa {{ .alpha }}", }, { name: "skip_empty", @@ -120,91 +122,49 @@ func TestAutoTemplate(t *testing.T) { data: map[string]interface{}{ "empty": "", }, - wantStr: "a", + expected: "a", }, } { t.Run(tc.name, func(t *testing.T) { - assert.Equal(t, tc.wantStr, string(autoTemplate([]byte(tc.contentsStr), tc.data))) + assert.Equal(t, tc.expected, string(autoTemplate([]byte(tc.contentsStr), tc.data))) }) } } func TestInWord(t *testing.T) { for _, tc := range []struct { - s string - i int - want bool + s string + i int + expected bool }{ - {s: "", i: 0, want: false}, - {s: "a", i: 0, want: false}, - {s: "a", i: 1, want: false}, - {s: "ab", i: 0, want: false}, - {s: "ab", i: 1, want: true}, - {s: "ab", i: 2, want: false}, - {s: "abc", i: 0, want: false}, - {s: "abc", i: 1, want: true}, - {s: "abc", i: 2, want: true}, - {s: "abc", i: 3, want: false}, - {s: " abc ", i: 0, want: false}, - {s: " abc ", i: 1, want: false}, - {s: " abc ", i: 2, want: true}, - {s: " abc ", i: 3, want: true}, - {s: " abc ", i: 4, want: false}, - {s: " abc ", i: 5, want: false}, - {s: "/home/user", i: 0, want: false}, - {s: "/home/user", i: 1, want: false}, - {s: "/home/user", i: 2, want: true}, - {s: "/home/user", i: 3, want: true}, - {s: "/home/user", i: 4, want: true}, - {s: "/home/user", i: 5, want: false}, - {s: "/home/user", i: 6, want: false}, - {s: "/home/user", i: 7, want: true}, - {s: "/home/user", i: 8, want: true}, - {s: "/home/user", i: 9, want: true}, - {s: "/home/user", i: 10, want: false}, + {s: "", i: 0, expected: false}, + {s: "a", i: 0, expected: false}, + {s: "a", i: 1, expected: false}, + {s: "ab", i: 0, expected: false}, + {s: "ab", i: 1, expected: true}, + {s: "ab", i: 2, expected: false}, + {s: "abc", i: 0, expected: false}, + {s: "abc", i: 1, expected: true}, + {s: "abc", i: 2, expected: true}, + {s: "abc", i: 3, expected: false}, + {s: " abc ", i: 0, expected: false}, + {s: " abc ", i: 1, expected: false}, + {s: " abc ", i: 2, expected: true}, + {s: " abc ", i: 3, expected: true}, + {s: " abc ", i: 4, expected: false}, + {s: " abc ", i: 5, expected: false}, + {s: "/home/user", i: 0, expected: false}, + {s: "/home/user", i: 1, expected: false}, + {s: "/home/user", i: 2, expected: true}, + {s: "/home/user", i: 3, expected: true}, + {s: "/home/user", i: 4, expected: true}, + {s: "/home/user", i: 5, expected: false}, + {s: "/home/user", i: 6, expected: false}, + {s: "/home/user", i: 7, expected: true}, + {s: "/home/user", i: 8, expected: true}, + {s: "/home/user", i: 9, expected: true}, + {s: "/home/user", i: 10, expected: false}, } { - assert.Equal(t, tc.want, inWord(tc.s, tc.i)) - } -} - -func TestTemplateEscape(t *testing.T) { - for _, tc := range []struct { - inputStr string - expectedStr string - }{ - { - inputStr: "{", - expectedStr: "{", - }, - { - inputStr: "{{", - expectedStr: `{{ "{{" }}`, - }, - { - inputStr: "{{{", - expectedStr: `{{ "{{{" }}`, - }, - { - inputStr: "}", - expectedStr: "}", - }, - { - inputStr: "}}", - expectedStr: `{{ "}}" }}`, - }, - { - inputStr: "}}}", - expectedStr: `{{ "}}}" }}`, - }, - { - inputStr: "}}}", - expectedStr: `{{ "}}}" }}`, - }, - { - inputStr: `" vim: set foldmethod=marker foldmarker={{,}}`, - expectedStr: `" vim: set foldmethod=marker foldmarker={{ "{{" }},{{ "}}" }}`, - }, - } { - assert.Equal(t, tc.expectedStr, string(templateEscape([]byte(tc.inputStr)))) + assert.Equal(t, tc.expected, inWord(tc.s, tc.i)) } } diff --git a/internal/chezmoi/boltpersistentstate.go b/internal/chezmoi/boltpersistentstate.go index 6407a00b44c..70bf2c5f190 100644 --- a/internal/chezmoi/boltpersistentstate.go +++ b/internal/chezmoi/boltpersistentstate.go @@ -2,38 +2,53 @@ package chezmoi import ( "os" - "path/filepath" + "time" - vfs "github.com/twpayne/go-vfs" - bolt "go.etcd.io/bbolt" + "go.etcd.io/bbolt" +) + +// A BoltPersistentStateMode is a mode for opening a PersistentState. +type BoltPersistentStateMode int + +// PersistentStateModes. +const ( + BoltPersistentStateReadOnly BoltPersistentStateMode = iota + BoltPersistentStateReadWrite ) // A BoltPersistentState is a state persisted with bolt. type BoltPersistentState struct { - fs vfs.FS - path string - options *bolt.Options - db *bolt.DB + db *bbolt.DB } // NewBoltPersistentState returns a new BoltPersistentState. -func NewBoltPersistentState(fs vfs.FS, path string, options *bolt.Options) (*BoltPersistentState, error) { - b := &BoltPersistentState{ - fs: fs, - path: path, - options: options, - } - _, err := fs.Stat(b.path) - switch { - case err == nil: - if err := b.openDB(); err != nil { +func NewBoltPersistentState(system System, path AbsPath, mode BoltPersistentStateMode) (*BoltPersistentState, error) { + if _, err := system.Stat(path); os.IsNotExist(err) { + if mode == BoltPersistentStateReadOnly { + return &BoltPersistentState{}, nil + } + if err := MkdirAll(system, path.Dir(), 0o777); err != nil { return nil, err } - case os.IsNotExist(err): - default: + } + options := bbolt.Options{ + OpenFile: func(name string, flag int, perm os.FileMode) (*os.File, error) { + rawPath, err := system.RawPath(AbsPath(name)) + if err != nil { + return nil, err + } + return os.OpenFile(string(rawPath), flag, perm) + }, + ReadOnly: mode == BoltPersistentStateReadOnly, + Timeout: time.Second, + } + db, err := bbolt.Open(string(path), 0o600, &options) + if err != nil { return nil, err } - return b, nil + return &BoltPersistentState{ + db: db, + }, nil } // Close closes b. @@ -41,57 +56,77 @@ func (b *BoltPersistentState) Close() error { if b.db == nil { return nil } - if err := b.db.Close(); err != nil { - return err + return b.db.Close() +} + +// CopyTo copies b to p. +func (b *BoltPersistentState) CopyTo(p PersistentState) error { + if b.db == nil { + return nil } - b.db = nil - return nil + + return b.db.View(func(tx *bbolt.Tx) error { + return tx.ForEach(func(bucket []byte, b *bbolt.Bucket) error { + return b.ForEach(func(key, value []byte) error { + return p.Set(copyByteSlice(bucket), copyByteSlice(key), copyByteSlice(value)) + }) + }) + }) } // Delete deletes the value associate with key in bucket. If bucket or key does // not exist then Delete does nothing. func (b *BoltPersistentState) Delete(bucket, key []byte) error { + return b.db.Update(func(tx *bbolt.Tx) error { + b := tx.Bucket(bucket) + if b == nil { + return nil + } + return b.Delete(key) + }) +} + +// ForEach calls fn for each key, value pair in bucket. +func (b *BoltPersistentState) ForEach(bucket []byte, fn func(k, v []byte) error) error { if b.db == nil { return nil } - return b.db.Update(func(tx *bolt.Tx) error { + + return b.db.View(func(tx *bbolt.Tx) error { b := tx.Bucket(bucket) if b == nil { return nil } - return b.Delete(key) + return b.ForEach(func(k, v []byte) error { + return fn(copyByteSlice(k), copyByteSlice(v)) + }) }) } // Get returns the value associated with key in bucket. func (b *BoltPersistentState) Get(bucket, key []byte) ([]byte, error) { - var value []byte if b.db == nil { - return value, nil + return nil, nil } - return value, b.db.View(func(tx *bolt.Tx) error { + + var value []byte + if err := b.db.View(func(tx *bbolt.Tx) error { b := tx.Bucket(bucket) if b == nil { return nil } - v := b.Get(key) - if v != nil { - value = make([]byte, len(v)) - copy(value, v) - } + value = copyByteSlice(b.Get(key)) return nil - }) + }); err != nil { + return nil, err + } + return value, nil } // Set sets the value associated with key in bucket. bucket will be created if // it does not already exist. func (b *BoltPersistentState) Set(bucket, key, value []byte) error { - if b.db == nil { - if err := b.openDB(); err != nil { - return err - } - } - return b.db.Update(func(tx *bolt.Tx) error { + return b.db.Update(func(tx *bbolt.Tx) error { b, err := tx.CreateBucketIfNotExists(bucket) if err != nil { return err @@ -100,19 +135,11 @@ func (b *BoltPersistentState) Set(bucket, key, value []byte) error { }) } -func (b *BoltPersistentState) openDB() error { - if err := vfs.MkdirAll(b.fs, filepath.Dir(b.path), 0o777); err != nil { - return err - } - var options bolt.Options - if b.options != nil { - options = *b.options - } - options.OpenFile = b.fs.OpenFile - db, err := bolt.Open(b.path, 0o666, &options) - if err != nil { - return err +func copyByteSlice(value []byte) []byte { + if value == nil { + return nil } - b.db = db - return err + result := make([]byte, len(value)) + copy(result, value) + return result } diff --git a/internal/chezmoi/boltpersistentstate_test.go b/internal/chezmoi/boltpersistentstate_test.go index 7d8d83cf6dc..ae21ede00cf 100644 --- a/internal/chezmoi/boltpersistentstate_test.go +++ b/internal/chezmoi/boltpersistentstate_test.go @@ -2,119 +2,143 @@ package chezmoi import ( "testing" - "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/twpayne/go-vfs/vfst" - bolt "go.etcd.io/bbolt" + "github.com/twpayne/go-vfs/v2" + "github.com/twpayne/go-vfs/v2/vfst" + + "github.com/twpayne/chezmoi/internal/chezmoitest" ) var _ PersistentState = &BoltPersistentState{} func TestBoltPersistentState(t *testing.T) { - fs, cleanup, err := vfst.NewTestFS(map[string]interface{}{ - "/home/user/.config/chezmoi": &vfst.Dir{Perm: 0o755}, + chezmoitest.WithTestFS(t, nil, func(fs vfs.FS) { + var ( + s = NewRealSystem(fs) + path = AbsPath("/home/user/.config/chezmoi/chezmoistate.boltdb") + bucket = []byte("bucket") + key = []byte("key") + value = []byte("value") + ) + + b1, err := NewBoltPersistentState(s, path, BoltPersistentStateReadWrite) + require.NoError(t, err) + vfst.RunTests(t, fs, "", + vfst.TestPath(string(path), + vfst.TestModeIsRegular, + ), + ) + + actualValue, err := b1.Get(bucket, key) + require.NoError(t, err) + assert.Equal(t, []byte(nil), actualValue) + + assert.NoError(t, b1.Set(bucket, key, value)) + actualValue, err = b1.Get(bucket, key) + require.NoError(t, err) + assert.Equal(t, value, actualValue) + + visited := false + require.NoError(t, b1.ForEach(bucket, func(k, v []byte) error { + visited = true + assert.Equal(t, key, k) + assert.Equal(t, value, v) + return nil + })) + require.True(t, visited) + + require.NoError(t, b1.Close()) + + b2, err := NewBoltPersistentState(s, path, BoltPersistentStateReadWrite) + require.NoError(t, err) + + require.NoError(t, b2.Delete(bucket, key)) + + actualValue, err = b2.Get(bucket, key) + require.NoError(t, err) + assert.Equal(t, []byte(nil), actualValue) }) - require.NoError(t, err) - defer cleanup() - - path := "/home/user/.config/chezmoi/chezmoistate.boltdb" - b, err := NewBoltPersistentState(fs, path, nil) - require.NoError(t, err) - vfst.RunTests(t, fs, "", - vfst.TestPath(path, - vfst.TestDoesNotExist, - ), - ) - - var ( - bucket = []byte("bucket") - key = []byte("key") - value = []byte("value") - ) - - require.NoError(t, b.Delete(bucket, key)) - vfst.RunTests(t, fs, "", - vfst.TestPath(path, - vfst.TestDoesNotExist, - ), - ) - - actualValue, err := b.Get(bucket, key) - require.NoError(t, err) - assert.Equal(t, []byte(nil), actualValue) - vfst.RunTests(t, fs, "", - vfst.TestPath(path, - vfst.TestDoesNotExist, - ), - ) - - assert.NoError(t, b.Set(bucket, key, value)) - vfst.RunTests(t, fs, "", - vfst.TestPath(path, - vfst.TestModeIsRegular, - ), - ) - - actualValue, err = b.Get(bucket, key) - require.NoError(t, err) - assert.Equal(t, value, actualValue) - - require.NoError(t, b.Close()) - - b, err = NewBoltPersistentState(fs, path, nil) - require.NoError(t, err) - - require.NoError(t, b.Delete(bucket, key)) - - actualValue, err = b.Get(bucket, key) - require.NoError(t, err) - assert.Equal(t, []byte(nil), actualValue) } -func TestBoltPersistentStateReadOnly(t *testing.T) { - fs, cleanup, err := vfst.NewTestFS(map[string]interface{}{ - "/home/user/.config/chezmoi": &vfst.Dir{Perm: 0o755}, - }) - require.NoError(t, err) - defer cleanup() - - path := "/home/user/.config/chezmoi/chezmoistate.boltdb" - bucket := []byte("bucket") - key := []byte("key") - value := []byte("value") - - a, err := NewBoltPersistentState(fs, path, nil) - require.NoError(t, err) - require.NoError(t, a.Set(bucket, key, value)) - require.NoError(t, a.Close()) - - b, err := NewBoltPersistentState(fs, path, &bolt.Options{ - ReadOnly: true, - Timeout: 1 * time.Second, +func TestBoltPersistentStateMock(t *testing.T) { + chezmoitest.WithTestFS(t, nil, func(fs vfs.FS) { + var ( + s = NewRealSystem(fs) + path = AbsPath("/home/user/.config/chezmoi/chezmoistate.boltdb") + bucket = []byte("bucket") + key = []byte("key") + value1 = []byte("value1") + value2 = []byte("value2") + ) + + b, err := NewBoltPersistentState(s, path, BoltPersistentStateReadWrite) + require.NoError(t, err) + require.NoError(t, b.Set(bucket, key, value1)) + + m := NewMockPersistentState() + require.NoError(t, b.CopyTo(m), err) + + actualValue, err := m.Get(bucket, key) + require.NoError(t, err) + assert.Equal(t, value1, actualValue) + + require.NoError(t, m.Set(bucket, key, value2)) + actualValue, err = m.Get(bucket, key) + require.NoError(t, err) + assert.Equal(t, value2, actualValue) + actualValue, err = b.Get(bucket, key) + require.NoError(t, err) + assert.Equal(t, value1, actualValue) + + require.NoError(t, m.Delete(bucket, key)) + actualValue, err = m.Get(bucket, key) + require.NoError(t, err) + assert.Nil(t, actualValue) + actualValue, err = b.Get(bucket, key) + require.NoError(t, err) + assert.Equal(t, value1, actualValue) + + require.NoError(t, b.Close()) }) - require.NoError(t, err) - defer b.Close() +} - c, err := NewBoltPersistentState(fs, path, &bolt.Options{ - ReadOnly: true, - Timeout: 1 * time.Second, +func TestBoltPersistentStateReadOnly(t *testing.T) { + chezmoitest.WithTestFS(t, nil, func(fs vfs.FS) { + var ( + s = NewRealSystem(fs) + path = AbsPath("/home/user/.config/chezmoi/chezmoistate.boltdb") + bucket = []byte("bucket") + key = []byte("key") + value = []byte("value") + ) + + b1, err := NewBoltPersistentState(s, path, BoltPersistentStateReadWrite) + require.NoError(t, err) + require.NoError(t, b1.Set(bucket, key, value)) + require.NoError(t, b1.Close()) + + b2, err := NewBoltPersistentState(s, path, BoltPersistentStateReadOnly) + require.NoError(t, err) + defer b2.Close() + + b3, err := NewBoltPersistentState(s, path, BoltPersistentStateReadOnly) + require.NoError(t, err) + defer b3.Close() + + actualValueB, err := b2.Get(bucket, key) + require.NoError(t, err) + assert.Equal(t, value, actualValueB) + + actualValueC, err := b3.Get(bucket, key) + require.NoError(t, err) + assert.Equal(t, value, actualValueC) + + assert.Error(t, b2.Set(bucket, key, value)) + assert.Error(t, b3.Set(bucket, key, value)) + + require.NoError(t, b2.Close()) + require.NoError(t, b3.Close()) }) - require.NoError(t, err) - defer c.Close() - - actualValueB, err := b.Get(bucket, key) - require.NoError(t, err) - assert.Equal(t, value, actualValueB) - - actualValueC, err := c.Get(bucket, key) - require.NoError(t, err) - assert.Equal(t, value, actualValueC) - - assert.Error(t, b.Set(bucket, key, value)) - assert.Error(t, c.Set(bucket, key, value)) - - require.NoError(t, b.Close()) - require.NoError(t, c.Close()) } diff --git a/internal/chezmoi/chezmoi.go b/internal/chezmoi/chezmoi.go index 892584439b8..6be51f8cd91 100644 --- a/internal/chezmoi/chezmoi.go +++ b/internal/chezmoi/chezmoi.go @@ -1,24 +1,38 @@ +// Package chezmoi contains chezmoi's core logic. package chezmoi import ( - "archive/tar" "bytes" - "io" + "crypto/sha256" + "fmt" "os" "path/filepath" - "sort" "strings" +) + +var ( + // DefaultTemplateOptions are the default template options. + DefaultTemplateOptions = []string{"missingkey=error"} - vfs "github.com/twpayne/go-vfs" + // Skip indicates that entry should be skipped. + Skip = filepath.SkipDir + + // Umask is the process's umask. + Umask = os.FileMode(0) ) // Suffixes and prefixes. const ( + ignorePrefix = "." + afterPrefix = "after_" + beforePrefix = "before_" + createPrefix = "create_" dotPrefix = "dot_" emptyPrefix = "empty_" encryptedPrefix = "encrypted_" exactPrefix = "exact_" executablePrefix = "executable_" + modifyPrefix = "modify_" oncePrefix = "once_" privatePrefix = "private_" runPrefix = "run_" @@ -26,100 +40,125 @@ const ( TemplateSuffix = ".tmpl" ) -// A PersistentState is an interface to a persistent state. -type PersistentState interface { - Close() error - Delete(bucket, key []byte) error - Get(bucket, key []byte) ([]byte, error) - Set(bucket, key, value []byte) error -} - -// An ApplyOptions is a big ball of mud for things that affect Entry.Apply. -type ApplyOptions struct { - DestDir string - DryRun bool - Ignore func(string) bool - PersistentState PersistentState - Remove bool - ScriptStateBucket []byte - Stdout io.Writer - Umask os.FileMode - Verbose bool -} - -// An Entry is either a Dir, a File, or a Symlink. -type Entry interface { - AppendAllEntries(allEntries []Entry) []Entry - Apply(fs vfs.FS, mutator Mutator, follow bool, applyOptions *ApplyOptions) error - ConcreteValue(ignore func(string) bool, sourceDir string, umask os.FileMode, recursive bool) (interface{}, error) - Evaluate(ignore func(string) bool) error - SourceName() string - TargetName() string - archive(w *tar.Writer, ignore func(string) bool, headerTemplate *tar.Header, umask os.FileMode) error -} - -type parsedSourceFilePath struct { - dirAttributes []DirAttributes - fileAttributes *FileAttributes - scriptAttributes *ScriptAttributes -} - -// dirNames returns the dir names from dirAttributes. -func dirNames(dirAttributes []DirAttributes) []string { - dns := make([]string, len(dirAttributes)) - for i, da := range dirAttributes { - dns[i] = da.Name - } - return dns +// Special file names. +const ( + Prefix = ".chezmoi" + + dataName = Prefix + "data" + ignoreName = Prefix + "ignore" + removeName = Prefix + "remove" + templatesDirName = Prefix + "templates" + versionName = Prefix + "version" +) + +var knownPrefixedFiles = map[string]bool{ + Prefix + ".json" + TemplateSuffix: true, + Prefix + ".toml" + TemplateSuffix: true, + Prefix + ".yaml" + TemplateSuffix: true, + dataName: true, + ignoreName: true, + removeName: true, + versionName: true, } -// isEmpty returns true if b should be considered empty. -func isEmpty(b []byte) bool { - return len(bytes.TrimSpace(b)) == 0 +var modeTypeNames = map[os.FileMode]string{ + 0: "file", + os.ModeDir: "dir", + os.ModeSymlink: "symlink", + os.ModeNamedPipe: "named pipe", + os.ModeSocket: "socket", + os.ModeDevice: "device", + os.ModeCharDevice: "char device", } -// parseDirNameComponents parses multiple directory name components. -func parseDirNameComponents(components []string) []DirAttributes { - das := []DirAttributes{} - for _, component := range components { - da := ParseDirAttributes(component) - das = append(das, da) +type errDuplicateTarget struct { + targetRelPath RelPath + sourceRelPaths SourceRelPaths +} + +func (e *errDuplicateTarget) Error() string { + sourceRelPathStrs := make([]string, 0, len(e.sourceRelPaths)) + for _, sourceRelPath := range e.sourceRelPaths { + sourceRelPathStrs = append(sourceRelPathStrs, sourceRelPath.String()) } - return das -} - -// parseSourceFilePath parses a single source file path. -func parseSourceFilePath(path string) parsedSourceFilePath { - components := splitPathList(path) - das := parseDirNameComponents(components[0 : len(components)-1]) - sourceName := components[len(components)-1] - if strings.HasPrefix(sourceName, runPrefix) { - sa := ParseScriptAttributes(sourceName) - return parsedSourceFilePath{ - dirAttributes: das, - scriptAttributes: &sa, - } + return fmt.Sprintf("%s: duplicate source state entries (%s)", e.targetRelPath, strings.Join(sourceRelPathStrs, ", ")) +} + +type errNotInAbsDir struct { + pathAbsPath AbsPath + dirAbsPath AbsPath +} + +func (e *errNotInAbsDir) Error() string { + return fmt.Sprintf("%s: not in %s", e.pathAbsPath, e.dirAbsPath) +} + +type errNotInRelDir struct { + pathRelPath RelPath + dirRelPath RelPath +} + +func (e *errNotInRelDir) Error() string { + return fmt.Sprintf("%s: not in %s", e.pathRelPath, e.dirRelPath) +} + +type errUnsupportedFileType struct { + absPath AbsPath + mode os.FileMode +} + +func (e *errUnsupportedFileType) Error() string { + return fmt.Sprintf("%s: unsupported file type %s", e.absPath, modeTypeName(e.mode)) +} + +// SHA256Sum returns the SHA256 sum of data. +func SHA256Sum(data []byte) []byte { + sha256SumArr := sha256.Sum256(data) + return sha256SumArr[:] +} + +// SuspiciousSourceDirEntry returns true if base is a suspicous dir entry. +func SuspiciousSourceDirEntry(base string, info os.FileInfo) bool { + //nolint:exhaustive + switch info.Mode() & os.ModeType { + case 0: + return strings.HasPrefix(base, Prefix) && !knownPrefixedFiles[base] + case os.ModeDir: + return strings.HasPrefix(base, Prefix) && base != templatesDirName + case os.ModeSymlink: + return strings.HasPrefix(base, Prefix) + default: + return true } - fa := ParseFileAttributes(components[len(components)-1]) - return parsedSourceFilePath{ - dirAttributes: das, - fileAttributes: &fa, +} + +// isEmpty returns true if data is empty after trimming whitespace from both +// ends. +func isEmpty(data []byte) bool { + return len(bytes.TrimSpace(data)) == 0 +} + +func modeTypeName(mode os.FileMode) string { + if name, ok := modeTypeNames[mode&os.ModeType]; ok { + return name } + return fmt.Sprintf("0o%o: unknown type", mode&os.ModeType) } -// sortedEntryNames returns a sorted slice of all entry names. -func sortedEntryNames(entries map[string]Entry) []string { - entryNames := []string{} - for entryName := range entries { - entryNames = append(entryNames, entryName) +// mustTrimPrefix is like strings.TrimPrefix but panics if s is not prefixed by +// prefix. +func mustTrimPrefix(s, prefix string) string { + if !strings.HasPrefix(s, prefix) { + panic(fmt.Sprintf("%s: not prefixed by %s", s, prefix)) } - sort.Strings(entryNames) - return entryNames + return s[len(prefix):] } -func splitPathList(path string) []string { - if strings.HasPrefix(path, string(filepath.Separator)) { - path = strings.TrimPrefix(path, string(filepath.Separator)) +// mustTrimSuffix is like strings.TrimSuffix but panics if s is not suffixed by +// suffix. +func mustTrimSuffix(s, suffix string) string { + if !strings.HasSuffix(s, suffix) { + panic(fmt.Sprintf("%s: not suffixed by %s", s, suffix)) } - return strings.Split(path, string(filepath.Separator)) + return s[:len(s)-len(suffix)] } diff --git a/internal/chezmoi/chezmoi_test.go b/internal/chezmoi/chezmoi_test.go index ba1c1c1ec7b..858c016d295 100644 --- a/internal/chezmoi/chezmoi_test.go +++ b/internal/chezmoi/chezmoi_test.go @@ -1,32 +1,17 @@ package chezmoi import ( - "errors" - "testing" + "os" - "github.com/stretchr/testify/assert" + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" + "github.com/rs/zerolog/pkgerrors" ) -func TestReturnTemplateError(t *testing.T) { - funcs := map[string]interface{}{ - "returnTemplateError": func() string { - panic(errors.New("error")) - }, - } - for name, dataString := range map[string]string{ - "syntax_error": "{{", - "unknown_field": "{{ .Unknown }}", - "unknown_func": "{{ func }}", - "func_returning_error": "{{ returnTemplateError }}", - } { - t.Run(name, func(t *testing.T) { - ts := NewTargetState( - WithDestDir("/home/user"), - WithSourceDir("/home/user/.chezmoi"), - WithTemplateFuncs(funcs), - ) - _, err := ts.ExecuteTemplateData(name, []byte(dataString)) - assert.Error(t, err) - }) - } +func init() { + log.Logger = log.Output(zerolog.ConsoleWriter{ + Out: os.Stderr, + NoColor: true, + }) + zerolog.ErrorStackMarshaler = pkgerrors.MarshalStack } diff --git a/internal/chezmoi/chezmoi_unix.go b/internal/chezmoi/chezmoi_unix.go index 2db3b95e230..b0fd4424119 100644 --- a/internal/chezmoi/chezmoi_unix.go +++ b/internal/chezmoi/chezmoi_unix.go @@ -3,24 +3,72 @@ package chezmoi import ( + "bufio" + "bytes" + "net" "os" + "regexp" + "strings" "syscall" + + vfs "github.com/twpayne/go-vfs/v2" ) -var umask os.FileMode +var whitespaceRx = regexp.MustCompile(`\s+`) func init() { - umask = os.FileMode(syscall.Umask(0)) - syscall.Umask(int(umask)) + Umask = os.FileMode(syscall.Umask(0)) + syscall.Umask(int(Umask)) +} + +// FQDNHostname returns the FQDN hostname. +func FQDNHostname(fs vfs.FS) (string, error) { + if fqdnHostname, err := etcHostsFQDNHostname(fs); err == nil && fqdnHostname != "" { + return fqdnHostname, nil + } + return lookupAddrFQDNHostname() +} + +// etcHostsFQDNHostname returns the FQDN hostname from parsing /etc/hosts. +func etcHostsFQDNHostname(fs vfs.FS) (string, error) { + etcHostsContents, err := fs.ReadFile("/etc/hosts") + if err != nil { + return "", err + } + s := bufio.NewScanner(bytes.NewReader(etcHostsContents)) + for s.Scan() { + text := s.Text() + text = strings.TrimSpace(text) + if index := strings.IndexByte(text, '#'); index != -1 { + text = text[:index] + } + fields := whitespaceRx.Split(text, -1) + if len(fields) >= 2 && fields[0] == "127.0.1.1" { + return fields[1], nil + } + } + return "", s.Err() +} + +// isExecutable returns if info is executable. +func isExecutable(info os.FileInfo) bool { + return info.Mode().Perm()&0o111 != 0 } -// GetUmask returns the umask. -func GetUmask() os.FileMode { - return umask +// isPrivate returns if info is private. +func isPrivate(info os.FileInfo) bool { + return info.Mode().Perm()&0o77 == 0 } -// SetUmask sets the umask. -func SetUmask(newUmask os.FileMode) { - umask = newUmask - syscall.Umask(int(umask)) +// lookupAddrFQDNHostname returns the FQDN hostname by doing a reverse lookup of +// 127.0.1.1. +func lookupAddrFQDNHostname() (string, error) { + names, err := net.LookupAddr("127.0.1.1") + if err != nil { + return "", err + } + if len(names) == 0 { + return "", nil + } + return strings.TrimSuffix(names[0], "."), nil } diff --git a/chezmoi2/internal/chezmoi/chezmoi_unix_test.go b/internal/chezmoi/chezmoi_unix_test.go similarity index 95% rename from chezmoi2/internal/chezmoi/chezmoi_unix_test.go rename to internal/chezmoi/chezmoi_unix_test.go index 558e5221fdb..5a63dff5ffe 100644 --- a/chezmoi2/internal/chezmoi/chezmoi_unix_test.go +++ b/internal/chezmoi/chezmoi_unix_test.go @@ -7,9 +7,9 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - vfs "github.com/twpayne/go-vfs" + vfs "github.com/twpayne/go-vfs/v2" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoitest" + "github.com/twpayne/chezmoi/internal/chezmoitest" ) func TestEtcHostsFQDNHostname(t *testing.T) { diff --git a/internal/chezmoi/chezmoi_windows.go b/internal/chezmoi/chezmoi_windows.go index 4e3f5b20d1a..7ef79307c4d 100644 --- a/internal/chezmoi/chezmoi_windows.go +++ b/internal/chezmoi/chezmoi_windows.go @@ -1,11 +1,39 @@ package chezmoi -import "os" +import ( + "errors" + "os" + "unicode/utf16" -// GetUmask returns the umask. -func GetUmask() os.FileMode { - return os.FileMode(0) + vfs "github.com/twpayne/go-vfs/v2" + "golang.org/x/sys/windows" +) + +// FQDNHostname returns the machine's fully-qualified DNS domain name. +func FQDNHostname(fs vfs.FS) (string, error) { + n := uint32(windows.MAX_COMPUTERNAME_LENGTH + 1) + buf := make([]uint16, n) + err := windows.GetComputerNameEx(windows.ComputerNameDnsFullyQualified, &buf[0], &n) + if errors.Is(err, windows.ERROR_MORE_DATA) { + buf = make([]uint16, n) + err = windows.GetComputerNameEx(windows.ComputerNameDnsFullyQualified, &buf[0], &n) + } + if err != nil { + return "", err + } + return string(utf16.Decode(buf[0:n])), nil +} + +// isExecutable returns false on Windows. +func isExecutable(info os.FileInfo) bool { + return false } -// SetUmask sets the umask. -func SetUmask(os.FileMode) {} +// isPrivate returns false on Windows. +func isPrivate(info os.FileInfo) bool { + return false +} + +func isSlash(c uint8) bool { + return c == '\\' || c == '/' +} diff --git a/chezmoi2/internal/chezmoi/data_linux.go b/internal/chezmoi/data_linux.go similarity index 98% rename from chezmoi2/internal/chezmoi/data_linux.go rename to internal/chezmoi/data_linux.go index 18bd512a4db..2342fb79ed5 100644 --- a/chezmoi2/internal/chezmoi/data_linux.go +++ b/internal/chezmoi/data_linux.go @@ -11,7 +11,7 @@ import ( "strings" "unicode" - "github.com/twpayne/go-vfs" + "github.com/twpayne/go-vfs/v2" ) // KernelInfo returns the kernel information parsed from /proc/sys/kernel. diff --git a/chezmoi2/internal/chezmoi/data_linux_test.go b/internal/chezmoi/data_linux_test.go similarity index 98% rename from chezmoi2/internal/chezmoi/data_linux_test.go rename to internal/chezmoi/data_linux_test.go index 9210fe6eec0..1ec7e7712ef 100644 --- a/chezmoi2/internal/chezmoi/data_linux_test.go +++ b/internal/chezmoi/data_linux_test.go @@ -5,10 +5,10 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/twpayne/go-vfs" - "github.com/twpayne/go-vfs/vfst" + "github.com/twpayne/go-vfs/v2" + "github.com/twpayne/go-vfs/v2/vfst" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoitest" + "github.com/twpayne/chezmoi/internal/chezmoitest" ) func TestKernelInfo(t *testing.T) { diff --git a/chezmoi2/internal/chezmoi/data_notlinux.go b/internal/chezmoi/data_notlinux.go similarity index 90% rename from chezmoi2/internal/chezmoi/data_notlinux.go rename to internal/chezmoi/data_notlinux.go index 60c0c1d621c..af2fd378a82 100644 --- a/chezmoi2/internal/chezmoi/data_notlinux.go +++ b/internal/chezmoi/data_notlinux.go @@ -3,7 +3,7 @@ package chezmoi import ( - "github.com/twpayne/go-vfs" + "github.com/twpayne/go-vfs/v2" ) // KernelInfo returns nothing on non-Linux systems. diff --git a/chezmoi2/internal/chezmoi/debugencryption.go b/internal/chezmoi/debugencryption.go similarity index 96% rename from chezmoi2/internal/chezmoi/debugencryption.go rename to internal/chezmoi/debugencryption.go index 9b1e9339849..64c6a84cea8 100644 --- a/chezmoi2/internal/chezmoi/debugencryption.go +++ b/internal/chezmoi/debugencryption.go @@ -3,7 +3,7 @@ package chezmoi import ( "github.com/rs/zerolog/log" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoilog" + "github.com/twpayne/chezmoi/internal/chezmoilog" ) // A DebugEncryption logs all calls to an Encryption. diff --git a/internal/chezmoi/debugmutator.go b/internal/chezmoi/debugmutator.go deleted file mode 100644 index 1c5e9daf3f4..00000000000 --- a/internal/chezmoi/debugmutator.go +++ /dev/null @@ -1,120 +0,0 @@ -package chezmoi - -import ( - "log" - "os" - "os/exec" - "time" -) - -// A DebugMutator wraps a Mutator and logs all of the actions it executes. -type DebugMutator struct { - m Mutator -} - -// NewDebugMutator returns a new DebugMutator. -func NewDebugMutator(m Mutator) *DebugMutator { - return &DebugMutator{ - m: m, - } -} - -// Chmod implements Mutator.Chmod. -func (m *DebugMutator) Chmod(name string, mode os.FileMode) error { - return Debugf("Chmod(%q, 0%o)", []interface{}{name, mode}, func() error { - return m.m.Chmod(name, mode) - }) -} - -// IdempotentCmdOutput implements Mutator.IdempotentCmdOutput. -func (m *DebugMutator) IdempotentCmdOutput(cmd *exec.Cmd) ([]byte, error) { - var output []byte - cmdStr := ShellQuoteArgs(append([]string{cmd.Path}, cmd.Args[1:]...)) - err := Debugf("IdempotentCmdOutput(%q)", []interface{}{cmdStr}, func() error { - var err error - output, err = m.m.IdempotentCmdOutput(cmd) - return err - }) - return output, err -} - -// Mkdir implements Mutator.Mkdir. -func (m *DebugMutator) Mkdir(name string, perm os.FileMode) error { - return Debugf("Mkdir(%q, 0%o)", []interface{}{name, perm}, func() error { - return m.m.Mkdir(name, perm) - }) -} - -// RemoveAll implements Mutator.RemoveAll. -func (m *DebugMutator) RemoveAll(name string) error { - return Debugf("RemoveAll(%q)", []interface{}{name}, func() error { - return m.m.RemoveAll(name) - }) -} - -// Rename implements Mutator.Rename. -func (m *DebugMutator) Rename(oldpath, newpath string) error { - return Debugf("Rename(%q, %q)", []interface{}{oldpath, newpath}, func() error { - return m.Rename(oldpath, newpath) - }) -} - -// RunCmd implements Mutator.RunCmd. -func (m *DebugMutator) RunCmd(cmd *exec.Cmd) error { - cmdStr := ShellQuoteArgs(append([]string{cmd.Path}, cmd.Args[1:]...)) - return Debugf("Run(%q)", []interface{}{cmdStr}, func() error { - return m.m.RunCmd(cmd) - }) -} - -// Stat implements Mutator.Stat. -func (m *DebugMutator) Stat(name string) (os.FileInfo, error) { - var fi os.FileInfo - err := Debugf("Stat(%q)", []interface{}{name}, func() error { - var err error - fi, err = m.m.Stat(name) - return err - }) - return fi, err -} - -// WriteFile implements Mutator.WriteFile. -func (m *DebugMutator) WriteFile(name string, data []byte, perm os.FileMode, currData []byte) error { - return Debugf("WriteFile(%q, _, 0%o, _)", []interface{}{name, perm}, func() error { - return m.m.WriteFile(name, data, perm, currData) - }) -} - -// WriteSymlink implements Mutator.WriteSymlink. -func (m *DebugMutator) WriteSymlink(oldname, newname string) error { - return Debugf("WriteSymlink(%q, %q)", []interface{}{oldname, newname}, func() error { - return m.m.WriteSymlink(oldname, newname) - }) -} - -// Debugf logs debugging information about calling f. -func Debugf(format string, args []interface{}, f func() error) error { - errChan := make(chan error) - start := time.Now() - go func(errChan chan<- error) { - errChan <- f() - }(errChan) - select { - case err := <-errChan: - if err == nil { - log.Printf(format+" (%s)", append(args, time.Since(start))...) - } else { - log.Printf(format+" == %v (%s)", append(args, err, time.Since(start))...) - } - return err - case <-time.After(1 * time.Second): - log.Printf(format, args...) - err := <-errChan - if err == nil { - log.Printf(format+" (%s)", append(args, time.Since(start))...) - } else { - log.Printf(format+" == %v (%s)", append(args, err, time.Since(start))...) - } - return err - } -} diff --git a/chezmoi2/internal/chezmoi/debugpersistentstate.go b/internal/chezmoi/debugpersistentstate.go similarity index 100% rename from chezmoi2/internal/chezmoi/debugpersistentstate.go rename to internal/chezmoi/debugpersistentstate.go diff --git a/chezmoi2/internal/chezmoi/debugsystem.go b/internal/chezmoi/debugsystem.go similarity index 92% rename from chezmoi2/internal/chezmoi/debugsystem.go rename to internal/chezmoi/debugsystem.go index 5e404b54095..052c8a393f0 100644 --- a/chezmoi2/internal/chezmoi/debugsystem.go +++ b/internal/chezmoi/debugsystem.go @@ -5,9 +5,9 @@ import ( "os/exec" "github.com/rs/zerolog/log" - vfs "github.com/twpayne/go-vfs" + vfs "github.com/twpayne/go-vfs/v2" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoilog" + "github.com/twpayne/chezmoi/internal/chezmoilog" ) // A DebugSystem logs all calls to a System. @@ -83,20 +83,20 @@ func (s *DebugSystem) RawPath(path AbsPath) (AbsPath, error) { } // ReadDir implements System.ReadDir. -func (s *DebugSystem) ReadDir(name AbsPath) ([]os.FileInfo, error) { - infos, err := s.system.ReadDir(name) +func (s *DebugSystem) ReadDir(name AbsPath) ([]os.DirEntry, error) { + dirEntries, err := s.system.ReadDir(name) log.Logger.Debug(). Str("name", string(name)). Err(err). Msg("ReadDir") - return infos, err + return dirEntries, err } // ReadFile implements System.ReadFile. -func (s *DebugSystem) ReadFile(filename AbsPath) ([]byte, error) { - data, err := s.system.ReadFile(filename) +func (s *DebugSystem) ReadFile(name AbsPath) ([]byte, error) { + data, err := s.system.ReadFile(name) log.Logger.Debug(). - Str("filename", string(filename)). + Str("filename", string(name)). Bytes("data", chezmoilog.FirstFewBytes(data)). Err(err). Msg("ReadFile") diff --git a/chezmoi2/internal/chezmoi/debugsystem_test.go b/internal/chezmoi/debugsystem_test.go similarity index 100% rename from chezmoi2/internal/chezmoi/debugsystem_test.go rename to internal/chezmoi/debugsystem_test.go diff --git a/chezmoi2/internal/chezmoi/diff.go b/internal/chezmoi/diff.go similarity index 100% rename from chezmoi2/internal/chezmoi/diff.go rename to internal/chezmoi/diff.go diff --git a/internal/chezmoi/dir.go b/internal/chezmoi/dir.go deleted file mode 100644 index 0477c7bf1ca..00000000000 --- a/internal/chezmoi/dir.go +++ /dev/null @@ -1,227 +0,0 @@ -package chezmoi - -import ( - "archive/tar" - "os" - "path/filepath" - "strings" - - vfs "github.com/twpayne/go-vfs" -) - -// DirAttributes holds attributes parsed from a source directory name. -type DirAttributes struct { - Name string - Exact bool - Perm os.FileMode -} - -// A Dir represents the target state of a directory. -type Dir struct { - sourceName string - targetName string - Exact bool - Perm os.FileMode - Entries map[string]Entry -} - -type dirConcreteValue struct { - Type string `json:"type" yaml:"type"` - SourcePath string `json:"sourcePath" yaml:"sourcePath"` - TargetPath string `json:"targetPath" yaml:"targetPath"` - Exact bool `json:"exact" yaml:"exact"` - Perm int `json:"perm" yaml:"perm"` - Entries []interface{} `json:"entries" yaml:"entries"` -} - -// ParseDirAttributes parses a single directory name. -func ParseDirAttributes(sourceName string) DirAttributes { - name := sourceName - perm := os.FileMode(0o777) - exact := false - if strings.HasPrefix(name, exactPrefix) { - name = strings.TrimPrefix(name, exactPrefix) - exact = true - } - if strings.HasPrefix(name, privatePrefix) { - name = strings.TrimPrefix(name, privatePrefix) - perm &= 0o700 - } - if strings.HasPrefix(name, dotPrefix) { - name = "." + strings.TrimPrefix(name, dotPrefix) - } - return DirAttributes{ - Name: name, - Exact: exact, - Perm: perm, - } -} - -// SourceName returns da's source name. -func (da DirAttributes) SourceName() string { - sourceName := "" - if da.Exact { - sourceName += exactPrefix - } - if da.Perm&os.FileMode(0o77) == os.FileMode(0) { - sourceName += privatePrefix - } - if strings.HasPrefix(da.Name, ".") { - sourceName += dotPrefix + strings.TrimPrefix(da.Name, ".") - } else { - sourceName += da.Name - } - return sourceName -} - -// newDir returns a new directory state. -func newDir(sourceName, targetName string, exact bool, perm os.FileMode) *Dir { - return &Dir{ - sourceName: sourceName, - targetName: targetName, - Exact: exact, - Perm: perm, - Entries: make(map[string]Entry), - } -} - -// AppendAllEntries appends all Entries in d to allEntries. -func (d *Dir) AppendAllEntries(allEntries []Entry) []Entry { - allEntries = append(allEntries, d) - for _, entry := range d.Entries { - allEntries = entry.AppendAllEntries(allEntries) - } - return allEntries -} - -// Apply ensures that destDir in fs matches d. -func (d *Dir) Apply(fs vfs.FS, mutator Mutator, follow bool, applyOptions *ApplyOptions) error { - if applyOptions.Ignore(d.targetName) { - return nil - } - targetPath := filepath.Join(applyOptions.DestDir, d.targetName) - var info os.FileInfo - var err error - if follow { - info, err = fs.Stat(targetPath) - } else { - info, err = fs.Lstat(targetPath) - } - switch { - case err == nil && info.IsDir(): - if info.Mode().Perm() != d.Perm&^applyOptions.Umask { - if err := mutator.Chmod(targetPath, d.Perm&^applyOptions.Umask); err != nil { - return err - } - } - case err == nil: - if err := mutator.RemoveAll(targetPath); err != nil { - return err - } - fallthrough - case os.IsNotExist(err): - if err := mutator.Mkdir(targetPath, d.Perm&^applyOptions.Umask); err != nil { - return err - } - default: - return err - } - for _, entryName := range sortedEntryNames(d.Entries) { - if err := d.Entries[entryName].Apply(fs, mutator, follow, applyOptions); err != nil { - return err - } - } - if d.Exact { - infos, err := fs.ReadDir(targetPath) - if err != nil { - return err - } - for _, info := range infos { - name := info.Name() - if _, ok := d.Entries[name]; !ok { - if applyOptions.Ignore(filepath.Join(d.targetName, name)) { - continue - } - if err := mutator.RemoveAll(filepath.Join(targetPath, name)); err != nil { - return err - } - } - } - } - return nil -} - -// ConcreteValue implements Entry.ConcreteValue. -func (d *Dir) ConcreteValue(ignore func(string) bool, sourceDir string, umask os.FileMode, recursive bool) (interface{}, error) { - if ignore(d.targetName) { - return nil, nil - } - var entryConcreteValues []interface{} - if recursive { - for _, entryName := range sortedEntryNames(d.Entries) { - entryConcreteValue, err := d.Entries[entryName].ConcreteValue(ignore, sourceDir, umask, recursive) - if err != nil { - return nil, err - } - if entryConcreteValue != nil { - entryConcreteValues = append(entryConcreteValues, entryConcreteValue) - } - } - } - return &dirConcreteValue{ - Type: "dir", - SourcePath: filepath.Join(sourceDir, d.SourceName()), - TargetPath: d.TargetName(), - Exact: d.Exact, - Perm: int(d.Perm &^ umask), - Entries: entryConcreteValues, - }, nil -} - -// Evaluate evaluates all entries in d. -func (d *Dir) Evaluate(ignore func(string) bool) error { - if ignore(d.targetName) { - return nil - } - for _, entryName := range sortedEntryNames(d.Entries) { - if err := d.Entries[entryName].Evaluate(ignore); err != nil { - return err - } - } - return nil -} - -// Private returns true if d is private. -func (d *Dir) Private() bool { - return d.Perm&0o77 == 0 -} - -// SourceName implements Entry.SourceName. -func (d *Dir) SourceName() string { - return d.sourceName -} - -// TargetName implements Entry.TargetName. -func (d *Dir) TargetName() string { - return d.targetName -} - -// archive writes d to w. -func (d *Dir) archive(w *tar.Writer, ignore func(string) bool, headerTemplate *tar.Header, umask os.FileMode) error { - if ignore(d.targetName) { - return nil - } - header := *headerTemplate - header.Typeflag = tar.TypeDir - header.Name = d.targetName + "/" - header.Mode = int64(d.Perm &^ umask) - if err := w.WriteHeader(&header); err != nil { - return err - } - for _, entryName := range sortedEntryNames(d.Entries) { - if err := d.Entries[entryName].archive(w, ignore, headerTemplate, umask); err != nil { - return err - } - } - return nil -} diff --git a/internal/chezmoi/dir_test.go b/internal/chezmoi/dir_test.go deleted file mode 100644 index 1147adf64cf..00000000000 --- a/internal/chezmoi/dir_test.go +++ /dev/null @@ -1,64 +0,0 @@ -package chezmoi - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestDirAttributes(t *testing.T) { - for _, tc := range []struct { - sourceName string - da DirAttributes - }{ - { - sourceName: "foo", - da: DirAttributes{ - Name: "foo", - Perm: 0o777, - }, - }, - { - sourceName: "dot_foo", - da: DirAttributes{ - Name: ".foo", - Perm: 0o777, - }, - }, - { - sourceName: "private_foo", - da: DirAttributes{ - Name: "foo", - Perm: 0o700, - }, - }, - { - sourceName: "exact_foo", - da: DirAttributes{ - Name: "foo", - Exact: true, - Perm: 0o777, - }, - }, - { - sourceName: "private_dot_foo", - da: DirAttributes{ - Name: ".foo", - Perm: 0o700, - }, - }, - { - sourceName: "exact_private_dot_foo", - da: DirAttributes{ - Name: ".foo", - Exact: true, - Perm: 0o700, - }, - }, - } { - t.Run(tc.sourceName, func(t *testing.T) { - assert.Equal(t, tc.da, ParseDirAttributes(tc.sourceName)) - assert.Equal(t, tc.sourceName, tc.da.SourceName()) - }) - } -} diff --git a/internal/chezmoi/doublestaros.go b/internal/chezmoi/doublestaros.go index 02471c17ff8..df35f8daad3 100644 --- a/internal/chezmoi/doublestaros.go +++ b/internal/chezmoi/doublestaros.go @@ -1,12 +1,21 @@ package chezmoi import ( + "os" + "github.com/bmatcuk/doublestar/v3" - vfs "github.com/twpayne/go-vfs" + vfs "github.com/twpayne/go-vfs/v2" ) +// A doubleStarOS embeds a vfs.FS into a value that implements doublestar.OS. type doubleStarOS struct { vfs.FS } -func (os doubleStarOS) Open(name string) (doublestar.File, error) { return os.FS.Open(name) } +func (os doubleStarOS) Lstat(name string) (os.FileInfo, error) { + return os.FS.Lstat(name) +} + +func (os doubleStarOS) Open(name string) (doublestar.File, error) { + return os.FS.Open(name) +} diff --git a/chezmoi2/internal/chezmoi/dryrunsystem.go b/internal/chezmoi/dryrunsystem.go similarity index 91% rename from chezmoi2/internal/chezmoi/dryrunsystem.go rename to internal/chezmoi/dryrunsystem.go index ca52e9ceb55..86e1222831e 100644 --- a/chezmoi2/internal/chezmoi/dryrunsystem.go +++ b/internal/chezmoi/dryrunsystem.go @@ -4,7 +4,7 @@ import ( "os" "os/exec" - vfs "github.com/twpayne/go-vfs" + vfs "github.com/twpayne/go-vfs/v2" ) // DryRunSystem is an System that reads from, but does not write to, to @@ -60,13 +60,13 @@ func (s *DryRunSystem) RawPath(path AbsPath) (AbsPath, error) { } // ReadDir implements System.ReadDir. -func (s *DryRunSystem) ReadDir(dirname AbsPath) ([]os.FileInfo, error) { - return s.system.ReadDir(dirname) +func (s *DryRunSystem) ReadDir(name AbsPath) ([]os.DirEntry, error) { + return s.system.ReadDir(name) } // ReadFile implements System.ReadFile. -func (s *DryRunSystem) ReadFile(filename AbsPath) ([]byte, error) { - return s.system.ReadFile(filename) +func (s *DryRunSystem) ReadFile(name AbsPath) ([]byte, error) { + return s.system.ReadFile(name) } // Readlink implements System.Readlink. diff --git a/chezmoi2/internal/chezmoi/dryrunsystem_test.go b/internal/chezmoi/dryrunsystem_test.go similarity index 100% rename from chezmoi2/internal/chezmoi/dryrunsystem_test.go rename to internal/chezmoi/dryrunsystem_test.go diff --git a/chezmoi2/internal/chezmoi/dumpsystem.go b/internal/chezmoi/dumpsystem.go similarity index 98% rename from chezmoi2/internal/chezmoi/dumpsystem.go rename to internal/chezmoi/dumpsystem.go index e17f14b62e7..2f51d397fa5 100644 --- a/chezmoi2/internal/chezmoi/dumpsystem.go +++ b/internal/chezmoi/dumpsystem.go @@ -3,7 +3,7 @@ package chezmoi import ( "os" - vfs "github.com/twpayne/go-vfs" + vfs "github.com/twpayne/go-vfs/v2" ) // A dataType is a data type. diff --git a/chezmoi2/internal/chezmoi/dumpsystem_test.go b/internal/chezmoi/dumpsystem_test.go similarity index 91% rename from chezmoi2/internal/chezmoi/dumpsystem_test.go rename to internal/chezmoi/dumpsystem_test.go index be605e16298..764cc47879d 100644 --- a/chezmoi2/internal/chezmoi/dumpsystem_test.go +++ b/internal/chezmoi/dumpsystem_test.go @@ -5,9 +5,9 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - vfs "github.com/twpayne/go-vfs" + vfs "github.com/twpayne/go-vfs/v2" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoitest" + "github.com/twpayne/chezmoi/internal/chezmoitest" ) var _ System = &DumpSystem{} @@ -39,7 +39,9 @@ func TestDumpSystem(t *testing.T) { dumpSystem := NewDumpSystem() persistentState := NewMockPersistentState() - require.NoError(t, s.applyAll(dumpSystem, system, persistentState, "", ApplyOptions{})) + require.NoError(t, s.applyAll(dumpSystem, system, persistentState, "", ApplyOptions{ + Include: NewEntryTypeSet(EntryTypesAll), + })) expectedData := map[AbsPath]interface{}{ ".dir": &dirData{ Type: dataTypeDir, diff --git a/chezmoi2/internal/chezmoi/encryption.go b/internal/chezmoi/encryption.go similarity index 100% rename from chezmoi2/internal/chezmoi/encryption.go rename to internal/chezmoi/encryption.go diff --git a/chezmoi2/internal/chezmoi/encryption_test.go b/internal/chezmoi/encryption_test.go similarity index 89% rename from chezmoi2/internal/chezmoi/encryption_test.go rename to internal/chezmoi/encryption_test.go index 02299e2be87..9da7dc1686e 100644 --- a/chezmoi2/internal/chezmoi/encryption_test.go +++ b/internal/chezmoi/encryption_test.go @@ -1,7 +1,6 @@ package chezmoi import ( - "io/ioutil" "math/rand" "os" "path/filepath" @@ -22,7 +21,7 @@ func (e *xorEncryption) Decrypt(ciphertext []byte) ([]byte, error) { } func (e *xorEncryption) DecryptToFile(filename string, ciphertext []byte) error { - return ioutil.WriteFile(filename, e.xorWithKey(ciphertext), 0o666) + return os.WriteFile(filename, e.xorWithKey(ciphertext), 0o666) } func (e *xorEncryption) Encrypt(plaintext []byte) ([]byte, error) { @@ -30,7 +29,7 @@ func (e *xorEncryption) Encrypt(plaintext []byte) ([]byte, error) { } func (e *xorEncryption) EncryptFile(filename string) ([]byte, error) { - plaintext, err := ioutil.ReadFile(filename) + plaintext, err := os.ReadFile(filename) if err != nil { return nil, err } @@ -59,7 +58,7 @@ func testEncryptionDecryptToFile(t *testing.T, encryption Encryption) { require.NotEmpty(t, actualCiphertext) assert.NotEqual(t, expectedPlaintext, actualCiphertext) - tempDir, err := ioutil.TempDir("", "chezmoi-test-encryption") + tempDir, err := os.MkdirTemp("", "chezmoi-test-encryption") require.NoError(t, err) defer func() { assert.NoError(t, os.RemoveAll(tempDir)) @@ -68,7 +67,7 @@ func testEncryptionDecryptToFile(t *testing.T, encryption Encryption) { require.NoError(t, encryption.DecryptToFile(filename, actualCiphertext)) - actualPlaintext, err := ioutil.ReadFile(filename) + actualPlaintext, err := os.ReadFile(filename) require.NoError(t, err) require.NotEmpty(t, actualPlaintext) assert.Equal(t, expectedPlaintext, actualPlaintext) @@ -97,13 +96,13 @@ func testEncryptionEncryptFile(t *testing.T, encryption Encryption) { t.Run("EncryptFile", func(t *testing.T) { expectedPlaintext := []byte("plaintext\n") - tempDir, err := ioutil.TempDir("", "chezmoi-test-encryption") + tempDir, err := os.MkdirTemp("", "chezmoi-test-encryption") require.NoError(t, err) defer func() { assert.NoError(t, os.RemoveAll(tempDir)) }() filename := filepath.Join(tempDir, "filename") - require.NoError(t, ioutil.WriteFile(filename, expectedPlaintext, 0o666)) + require.NoError(t, os.WriteFile(filename, expectedPlaintext, 0o666)) actualCiphertext, err := encryption.EncryptFile(filename) require.NoError(t, err) diff --git a/chezmoi2/internal/chezmoi/entrystate.go b/internal/chezmoi/entrystate.go similarity index 100% rename from chezmoi2/internal/chezmoi/entrystate.go rename to internal/chezmoi/entrystate.go diff --git a/chezmoi2/internal/chezmoi/entrystate_test.go b/internal/chezmoi/entrystate_test.go similarity index 100% rename from chezmoi2/internal/chezmoi/entrystate_test.go rename to internal/chezmoi/entrystate_test.go diff --git a/internal/chezmoi/entrytypeset.go b/internal/chezmoi/entrytypeset.go new file mode 100644 index 00000000000..052a7575f3b --- /dev/null +++ b/internal/chezmoi/entrytypeset.go @@ -0,0 +1,177 @@ +package chezmoi + +// FIXME Add IncludeEncrypted + +import ( + "fmt" + "os" + "strings" +) + +// An EntryTypeSet is a set of entry types. It parses and prints as a +// comma-separated list of strings, but is internally represented as a bitmask. +// *EntryTypeSet implements the github.com/spf13/pflag.Value interface. +type EntryTypeSet struct { + bits EntryTypeBits +} + +// An EntryTypeBits is a bitmask of entry types. +type EntryTypeBits int + +// Entry type bits. +const ( + EntryTypeDirs EntryTypeBits = 1 << iota + EntryTypeFiles + EntryTypeRemove + EntryTypeScripts + EntryTypeSymlinks + EntryTypeEncrypted + + // EntryTypesAll is all entry types. + EntryTypesAll EntryTypeBits = EntryTypeDirs | EntryTypeFiles | EntryTypeRemove | EntryTypeScripts | EntryTypeSymlinks | EntryTypeEncrypted + + // EntryTypesNone is no entry types. + EntryTypesNone EntryTypeBits = 0 +) + +// entryTypeBits is a map from human-readable strings to EntryTypeBits. +var entryTypeBits = map[string]EntryTypeBits{ + "all": EntryTypesAll, + "dirs": EntryTypeDirs, + "files": EntryTypeFiles, + "remove": EntryTypeRemove, + "scripts": EntryTypeScripts, + "symlinks": EntryTypeSymlinks, + "encrypted": EntryTypeEncrypted, +} + +// NewEntryTypeSet returns a new IncludeSet. +func NewEntryTypeSet(bits EntryTypeBits) *EntryTypeSet { + return &EntryTypeSet{ + bits: bits, + } +} + +// IncludeActualStateEntry returns true if the type of actualStateEntry is a member. +func (s *EntryTypeSet) IncludeActualStateEntry(actualStateEntry ActualStateEntry) bool { + switch actualStateEntry.(type) { + case *ActualStateAbsent: + return s.bits&EntryTypeRemove != 0 + case *ActualStateDir: + return s.bits&EntryTypeDirs != 0 + case *ActualStateFile: + return s.bits&EntryTypeFiles != 0 + case *ActualStateSymlink: + return s.bits&EntryTypeSymlinks != 0 + default: + return false + } +} + +// IncludeEncrypted returns true if s includes encrypted files. +func (s *EntryTypeSet) IncludeEncrypted() bool { + return s.bits&EntryTypeEncrypted != 0 +} + +// IncludeFileInfo returns true if the type of info is a member. +func (s *EntryTypeSet) IncludeFileInfo(info os.FileInfo) bool { + switch { + case info.IsDir(): + return s.bits&EntryTypeDirs != 0 + case info.Mode().IsRegular(): + return s.bits&EntryTypeFiles != 0 + case info.Mode()&os.ModeType == os.ModeSymlink: + return s.bits&EntryTypeSymlinks != 0 + default: + return false + } +} + +// IncludeTargetStateEntry returns true if type of targetStateEntry is a member. +func (s *EntryTypeSet) IncludeTargetStateEntry(targetStateEntry TargetStateEntry) bool { + switch targetStateEntry.(type) { + case *TargetStateDir: + return s.bits&EntryTypeDirs != 0 + case *TargetStateFile: + return s.bits&EntryTypeFiles != 0 + case *TargetStateRemove: + return s.bits&EntryTypeRemove != 0 + case *TargetStateScript: + return s.bits&EntryTypeScripts != 0 + case *TargetStateSymlink: + return s.bits&EntryTypeSymlinks != 0 + case *targetStateRenameDir: + return s.bits&EntryTypeDirs != 0 + default: + return false + } +} + +// Set implements github.com/spf13/pflag.Value.Set. +func (s *EntryTypeSet) Set(str string) error { + if str == "none" { + s.bits = EntryTypesNone + return nil + } + + var bits EntryTypeBits + for i, element := range strings.Split(str, ",") { + if element == "" { + continue + } + exclude := false + if strings.HasPrefix(element, "no") { + exclude = true + element = element[2:] + } + bit, ok := entryTypeBits[element] + if !ok { + return fmt.Errorf("%s: unknown entry type", element) + } + if i == 0 && exclude { + bits = EntryTypesAll + } + if exclude { + bits &^= bit + } else { + bits |= bit + } + } + s.bits = bits + return nil +} + +func (s *EntryTypeSet) String() string { + //nolint:exhaustive + switch s.bits { + case EntryTypesAll: + return "all" + case EntryTypesNone: + return "none" + } + var elements []string + for i, element := range []string{ + "dirs", + "files", + "remove", + "scripts", + "symlinks", + } { + if s.bits&(1<<i) != 0 { + elements = append(elements, element) + } + } + return strings.Join(elements, ",") +} + +// Sub returns a copy of s with the elements of other removed. +func (s *EntryTypeSet) Sub(other *EntryTypeSet) *EntryTypeSet { + return &EntryTypeSet{ + bits: (s.bits &^ other.bits) & EntryTypesAll, + } +} + +// Type implements github.com/spf13/pflag.Value.Type. +func (s *EntryTypeSet) Type() string { + return "entry type set" +} diff --git a/chezmoi2/internal/chezmoi/includeset_test.go b/internal/chezmoi/entrytypeset_test.go similarity index 50% rename from chezmoi2/internal/chezmoi/includeset_test.go rename to internal/chezmoi/entrytypeset_test.go index 62d16185034..86c5f5a5ebf 100644 --- a/chezmoi2/internal/chezmoi/includeset_test.go +++ b/internal/chezmoi/entrytypeset_test.go @@ -10,32 +10,40 @@ import ( func TestIncludeMaskSet(t *testing.T) { for _, tc := range []struct { s string - expected *IncludeSet + expected *EntryTypeSet expectedErr bool }{ { s: "", - expected: NewIncludeSet(includeNone), + expected: NewEntryTypeSet(EntryTypesNone), }, { s: "none", - expected: NewIncludeSet(includeNone), + expected: NewEntryTypeSet(EntryTypesNone), }, { s: "dirs,files", - expected: NewIncludeSet(IncludeDirs | IncludeFiles), + expected: NewEntryTypeSet(EntryTypeDirs | EntryTypeFiles), }, { s: "all", - expected: NewIncludeSet(IncludeAll), + expected: NewEntryTypeSet(EntryTypesAll), }, { - s: "all,!scripts", - expected: NewIncludeSet(IncludeDirs | IncludeFiles | IncludeRemove | IncludeSymlinks), + s: "all,noscripts", + expected: NewEntryTypeSet(EntryTypeDirs | EntryTypeFiles | EntryTypeRemove | EntryTypeSymlinks | EntryTypeEncrypted), + }, + { + s: "noscripts", + expected: NewEntryTypeSet(EntryTypesAll &^ EntryTypeScripts), + }, + { + s: "noscripts,nosymlinks", + expected: NewEntryTypeSet(EntryTypesAll &^ (EntryTypeScripts | EntryTypeSymlinks)), }, { s: "symlinks,,", - expected: NewIncludeSet(IncludeSymlinks), + expected: NewEntryTypeSet(EntryTypeSymlinks), }, { s: "devices", @@ -43,7 +51,7 @@ func TestIncludeMaskSet(t *testing.T) { }, } { t.Run(tc.s, func(t *testing.T) { - actual := NewIncludeSet(includeNone) + actual := NewEntryTypeSet(EntryTypesNone) err := actual.Set(tc.s) if tc.expectedErr { require.Error(t, err) @@ -57,44 +65,44 @@ func TestIncludeMaskSet(t *testing.T) { func TestIncludeMaskStringSlice(t *testing.T) { for _, tc := range []struct { - bits IncludeBits + bits EntryTypeBits expected string }{ { - bits: IncludeAll, + bits: EntryTypesAll, expected: "all", }, { - bits: IncludeDirs, + bits: EntryTypeDirs, expected: "dirs", }, { - bits: IncludeFiles, + bits: EntryTypeFiles, expected: "files", }, { - bits: IncludeRemove, + bits: EntryTypeRemove, expected: "remove", }, { - bits: IncludeScripts, + bits: EntryTypeScripts, expected: "scripts", }, { - bits: IncludeSymlinks, + bits: EntryTypeSymlinks, expected: "symlinks", }, { - bits: includeNone, + bits: EntryTypesNone, expected: "none", }, { - bits: IncludeDirs | IncludeFiles, + bits: EntryTypeDirs | EntryTypeFiles, expected: "dirs,files", }, } { t.Run(tc.expected, func(t *testing.T) { - assert.Equal(t, tc.expected, NewIncludeSet(tc.bits).String()) + assert.Equal(t, tc.expected, NewEntryTypeSet(tc.bits).String()) }) } } diff --git a/internal/chezmoi/file.go b/internal/chezmoi/file.go deleted file mode 100644 index 41f308a112c..00000000000 --- a/internal/chezmoi/file.go +++ /dev/null @@ -1,264 +0,0 @@ -package chezmoi - -import ( - "archive/tar" - "bytes" - "fmt" - "os" - "path/filepath" - "strings" - - vfs "github.com/twpayne/go-vfs" -) - -// A FileAttributes holds attributes parsed from a source file name. -type FileAttributes struct { - Name string - Mode os.FileMode - Empty bool - Encrypted bool - Template bool -} - -// A File represents the target state of a file. -type File struct { - sourceName string - targetName string - Empty bool - Encrypted bool - Perm os.FileMode - Template bool - contents []byte - contentsErr error - evaluateContents func() ([]byte, error) -} - -type fileConcreteValue struct { - Type string `json:"type" yaml:"type"` - SourcePath string `json:"sourcePath" yaml:"sourcePath"` - TargetPath string `json:"targetPath" yaml:"targetPath"` - Empty bool `json:"empty" yaml:"empty"` - Encrypted bool `json:"encrypted" yaml:"encrypted"` - Perm int `json:"perm" yaml:"perm"` - Template bool `json:"template" yaml:"template"` - Contents string `json:"contents" yaml:"contents"` -} - -// ParseFileAttributes parses a source file name. -func ParseFileAttributes(sourceName string) FileAttributes { - name := sourceName - mode := os.FileMode(0o666) - empty := false - encrypted := false - template := false - if strings.HasPrefix(name, symlinkPrefix) { - name = strings.TrimPrefix(name, symlinkPrefix) - mode |= os.ModeSymlink - } else { - private := false - if strings.HasPrefix(name, encryptedPrefix) { - name = strings.TrimPrefix(name, encryptedPrefix) - encrypted = true - } - if strings.HasPrefix(name, privatePrefix) { - name = strings.TrimPrefix(name, privatePrefix) - private = true - } - if strings.HasPrefix(name, emptyPrefix) { - name = strings.TrimPrefix(name, emptyPrefix) - empty = true - } - if strings.HasPrefix(name, executablePrefix) { - name = strings.TrimPrefix(name, executablePrefix) - mode |= 0o111 - } - if private { - mode &= 0o700 - } - } - if strings.HasPrefix(name, dotPrefix) { - name = "." + strings.TrimPrefix(name, dotPrefix) - } - if strings.HasSuffix(name, TemplateSuffix) { - name = strings.TrimSuffix(name, TemplateSuffix) - template = true - } - return FileAttributes{ - Name: name, - Mode: mode, - Empty: empty, - Encrypted: encrypted, - Template: template, - } -} - -// SourceName returns fa's source name. -func (fa FileAttributes) SourceName() string { - sourceName := "" - //nolint:exhaustive - switch fa.Mode & os.ModeType { - case 0: - if fa.Encrypted { - sourceName += encryptedPrefix - } - if fa.Mode.Perm()&os.FileMode(0o77) == os.FileMode(0) { - sourceName += privatePrefix - } - if fa.Empty { - sourceName += emptyPrefix - } - if fa.Mode.Perm()&os.FileMode(0o111) != os.FileMode(0) { - sourceName += executablePrefix - } - case os.ModeSymlink: - sourceName = symlinkPrefix - default: - panic(fmt.Sprintf("%+v: unsupported type", fa)) - } - if strings.HasPrefix(fa.Name, ".") { - sourceName += dotPrefix + strings.TrimPrefix(fa.Name, ".") - } else { - sourceName += fa.Name - } - if fa.Template { - sourceName += TemplateSuffix - } - return sourceName -} - -// AppendAllEntries appends all f to allEntries. -func (f *File) AppendAllEntries(allEntries []Entry) []Entry { - return append(allEntries, f) -} - -// Apply ensures that the state of targetPath in fs matches f. -func (f *File) Apply(fs vfs.FS, mutator Mutator, follow bool, applyOptions *ApplyOptions) error { - if applyOptions.Ignore(f.targetName) { - return nil - } - contents, err := f.Contents() - if err != nil { - return err - } - targetPath := filepath.Join(applyOptions.DestDir, f.targetName) - var info os.FileInfo - if follow { - info, err = fs.Stat(targetPath) - } else { - info, err = fs.Lstat(targetPath) - } - var currData []byte - switch { - case err == nil && info.Mode().IsRegular(): - if isEmpty(contents) && !f.Empty { - return mutator.RemoveAll(targetPath) - } - currData, err = fs.ReadFile(targetPath) - if err != nil { - return err - } - if !bytes.Equal(currData, contents) { - break - } - if info.Mode().Perm() != f.Perm&^applyOptions.Umask { - if err := mutator.Chmod(targetPath, f.Perm&^applyOptions.Umask); err != nil { - return err - } - } - return nil - case err == nil: - if err := mutator.RemoveAll(targetPath); err != nil { - return err - } - case os.IsNotExist(err): - default: - return err - } - if isEmpty(contents) && !f.Empty { - return nil - } - return mutator.WriteFile(targetPath, contents, f.Perm&^applyOptions.Umask, currData) -} - -// ConcreteValue implements Entry.ConcreteValue. -func (f *File) ConcreteValue(ignore func(string) bool, sourceDir string, umask os.FileMode, recursive bool) (interface{}, error) { - if ignore(f.targetName) { - return nil, nil - } - contents, err := f.Contents() - if err != nil { - return nil, err - } - return &fileConcreteValue{ - Type: "file", - SourcePath: filepath.Join(sourceDir, f.SourceName()), - TargetPath: f.TargetName(), - Empty: f.Empty, - Encrypted: f.Encrypted, - Perm: int(f.Perm &^ umask), - Template: f.Template, - Contents: string(contents), - }, nil -} - -// Contents returns f's contents. -func (f *File) Contents() ([]byte, error) { - if f.evaluateContents != nil { - f.contents, f.contentsErr = f.evaluateContents() - f.evaluateContents = nil - } - return f.contents, f.contentsErr -} - -// Evaluate evaluates f's contents. -func (f *File) Evaluate(ignore func(string) bool) error { - if ignore(f.targetName) { - return nil - } - _, err := f.Contents() - return err -} - -// Executable returns true is f is executable. -func (f *File) Executable() bool { - return f.Perm&0o111 != 0 -} - -// Private returns true if f is private. -func (f *File) Private() bool { - return f.Perm&0o77 == 0 -} - -// SourceName implements Entry.SourceName. -func (f *File) SourceName() string { - return f.sourceName -} - -// TargetName implements Entry.TargetName. -func (f *File) TargetName() string { - return f.targetName -} - -// archive writes f to w. -func (f *File) archive(w *tar.Writer, ignore func(string) bool, headerTemplate *tar.Header, umask os.FileMode) error { - if ignore(f.targetName) { - return nil - } - contents, err := f.Contents() - if err != nil { - return err - } - if len(contents) == 0 && !f.Empty { - return nil - } - header := *headerTemplate - header.Typeflag = tar.TypeReg - header.Name = f.targetName - header.Size = int64(len(contents)) - header.Mode = int64(f.Perm &^ umask) - if err := w.WriteHeader(&header); err != nil { - return nil - } - _, err = w.Write(contents) - return err -} diff --git a/internal/chezmoi/file_test.go b/internal/chezmoi/file_test.go deleted file mode 100644 index dbd3d0d874d..00000000000 --- a/internal/chezmoi/file_test.go +++ /dev/null @@ -1,123 +0,0 @@ -package chezmoi - -import ( - "os" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestFileAttributes(t *testing.T) { - for _, tc := range []struct { - sourceName string - fa FileAttributes - }{ - { - sourceName: "foo", - fa: FileAttributes{ - Name: "foo", - Mode: 0o666, - Empty: false, - Template: false, - }, - }, - { - sourceName: "dot_foo", - fa: FileAttributes{ - Name: ".foo", - Mode: 0o666, - Empty: false, - Template: false, - }, - }, - { - sourceName: "private_foo", - fa: FileAttributes{ - Name: "foo", - Mode: 0o600, - Empty: false, - Template: false, - }, - }, - { - sourceName: "private_dot_foo", - fa: FileAttributes{ - Name: ".foo", - Mode: 0o600, - Empty: false, - Template: false, - }, - }, - { - sourceName: "empty_foo", - fa: FileAttributes{ - Name: "foo", - Mode: 0o666, - Empty: true, - Template: false, - }, - }, - { - sourceName: "executable_foo", - fa: FileAttributes{ - Name: "foo", - Mode: 0o777, - Empty: false, - Template: false, - }, - }, - { - sourceName: "foo.tmpl", - fa: FileAttributes{ - Name: "foo", - Mode: 0o666, - Empty: false, - Template: true, - }, - }, - { - sourceName: "private_executable_dot_foo.tmpl", - fa: FileAttributes{ - Name: ".foo", - Mode: 0o700, - Empty: false, - Template: true, - }, - }, - { - sourceName: "symlink_foo", - fa: FileAttributes{ - Name: "foo", - Mode: os.ModeSymlink | 0o666, - }, - }, - { - sourceName: "symlink_dot_foo", - fa: FileAttributes{ - Name: ".foo", - Mode: os.ModeSymlink | 0o666, - }, - }, - { - sourceName: "symlink_foo.tmpl", - fa: FileAttributes{ - Name: "foo", - Mode: os.ModeSymlink | 0o666, - Template: true, - }, - }, - { - sourceName: "encrypted_private_dot_secret_file", - fa: FileAttributes{ - Name: ".secret_file", - Mode: 0o600, - Encrypted: true, - }, - }, - } { - t.Run(tc.sourceName, func(t *testing.T) { - assert.Equal(t, tc.fa, ParseFileAttributes(tc.sourceName)) - assert.Equal(t, tc.sourceName, tc.fa.SourceName()) - }) - } -} diff --git a/chezmoi2/internal/chezmoi/format.go b/internal/chezmoi/format.go similarity index 100% rename from chezmoi2/internal/chezmoi/format.go rename to internal/chezmoi/format.go diff --git a/chezmoi2/internal/chezmoi/format_test.go b/internal/chezmoi/format_test.go similarity index 100% rename from chezmoi2/internal/chezmoi/format_test.go rename to internal/chezmoi/format_test.go diff --git a/internal/chezmoi/fsmutator.go b/internal/chezmoi/fsmutator.go deleted file mode 100644 index 9e9abaa6efd..00000000000 --- a/internal/chezmoi/fsmutator.go +++ /dev/null @@ -1,33 +0,0 @@ -package chezmoi - -import ( - "os/exec" - - vfs "github.com/twpayne/go-vfs" -) - -// An FSMutator makes changes to a vfs.FS. -type FSMutator struct { - vfs.FS - devCache map[string]uint // devCache maps directories to device numbers. - tempDirCache map[uint]string // tempDir maps device numbers to renameio temporary directories. -} - -// NewFSMutator returns an mutator that acts on fs. -func NewFSMutator(fs vfs.FS) *FSMutator { - return &FSMutator{ - FS: fs, - devCache: make(map[string]uint), - tempDirCache: make(map[uint]string), - } -} - -// IdempotentCmdOutput implements Mutator.IdempotentCmdOutput. -func (m *FSMutator) IdempotentCmdOutput(cmd *exec.Cmd) ([]byte, error) { - return cmd.Output() -} - -// RunCmd implements Mutator.RunCmd. -func (m *FSMutator) RunCmd(cmd *exec.Cmd) error { - return cmd.Run() -} diff --git a/internal/chezmoi/fsmutator_posix.go b/internal/chezmoi/fsmutator_posix.go deleted file mode 100644 index 4532fc168a8..00000000000 --- a/internal/chezmoi/fsmutator_posix.go +++ /dev/null @@ -1,66 +0,0 @@ -// +build !windows - -package chezmoi - -import ( - "errors" - "os" - "path/filepath" - "syscall" - - "github.com/google/renameio" - vfs "github.com/twpayne/go-vfs" -) - -// WriteFile implements Mutator.WriteFile. -func (m *FSMutator) WriteFile(name string, data []byte, perm os.FileMode, currData []byte) error { - // Special case: if writing to the real filesystem, use github.com/google/renameio - if m.FS == vfs.OSFS { - dir := filepath.Dir(name) - dev, ok := m.devCache[dir] - if !ok { - info, err := m.Stat(dir) - if err != nil { - return err - } - statT, ok := info.Sys().(*syscall.Stat_t) - if !ok { - return errors.New("os.FileInfo.Sys() cannot be converted to a *syscall.Stat_t") - } - dev = uint(statT.Dev) - m.devCache[dir] = dev - } - tempDir, ok := m.tempDirCache[dev] - if !ok { - tempDir = renameio.TempDir(dir) - m.tempDirCache[dev] = tempDir - } - t, err := renameio.TempFile(tempDir, name) - if err != nil { - return err - } - defer func() { - _ = t.Cleanup() - }() - if err := t.Chmod(perm); err != nil { - return err - } - if _, err := t.Write(data); err != nil { - return err - } - return t.CloseAtomicallyReplace() - } - return m.FS.WriteFile(name, data, perm) -} - -// WriteSymlink implements Mutator.WriteSymlink. -func (m *FSMutator) WriteSymlink(oldname, newname string) error { - // Special case: if writing to the real filesystem, use github.com/google/renameio - if m.FS == vfs.OSFS { - return renameio.Symlink(oldname, newname) - } - if err := m.FS.RemoveAll(newname); err != nil && !os.IsNotExist(err) { - return err - } - return m.FS.Symlink(oldname, newname) -} diff --git a/internal/chezmoi/fsmutator_windows.go b/internal/chezmoi/fsmutator_windows.go deleted file mode 100644 index 971812eabfd..00000000000 --- a/internal/chezmoi/fsmutator_windows.go +++ /dev/null @@ -1,20 +0,0 @@ -// +build windows - -package chezmoi - -import ( - "os" -) - -// WriteFile implements Mutator.WriteFile. -func (m *FSMutator) WriteFile(name string, data []byte, perm os.FileMode, currData []byte) error { - return m.FS.WriteFile(name, data, perm) -} - -// WriteSymlink implements Mutator.WriteSymlink. -func (m *FSMutator) WriteSymlink(oldname, newname string) error { - if err := m.FS.RemoveAll(newname); err != nil && !os.IsNotExist(err) { - return err - } - return m.FS.Symlink(oldname, newname) -} diff --git a/internal/chezmoi/gitdiffmutator.go b/internal/chezmoi/gitdiffmutator.go deleted file mode 100644 index ac170ecfad5..00000000000 --- a/internal/chezmoi/gitdiffmutator.go +++ /dev/null @@ -1,264 +0,0 @@ -package chezmoi - -import ( - "os" - "os/exec" - "strings" - "time" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/filemode" - "github.com/go-git/go-git/v5/plumbing/format/diff" - "github.com/sergi/go-diff/diffmatchpatch" -) - -// A GitDiffMutator wraps a Mutator and logs all of the actions it would execute -// as a git diff. -type GitDiffMutator struct { - m Mutator - prefix string - unifiedEncoder *diff.UnifiedEncoder -} - -// NewGitDiffMutator returns a new GitDiffMutator. -func NewGitDiffMutator(unifiedEncoder *diff.UnifiedEncoder, m Mutator, prefix string) *GitDiffMutator { - return &GitDiffMutator{ - m: m, - prefix: prefix, - unifiedEncoder: unifiedEncoder, - } -} - -// Chmod implements Mutator.Chmod. -func (m *GitDiffMutator) Chmod(name string, mode os.FileMode) error { - fromFileMode, info, err := m.getFileMode(name) - if err != nil { - return err - } - // Assume that we're only changing permissions. - toFileMode, err := filemode.NewFromOSFileMode(info.Mode()&^os.ModePerm | mode) - if err != nil { - return err - } - path := m.trimPrefix(name) - return m.unifiedEncoder.Encode(&gitDiffPatch{ - filePatches: []diff.FilePatch{ - &gitDiffFilePatch{ - from: &gitDiffFile{ - fileMode: fromFileMode, - path: path, - hash: plumbing.ZeroHash, - }, - to: &gitDiffFile{ - fileMode: toFileMode, - path: path, - hash: plumbing.ZeroHash, - }, - }, - }, - }) -} - -// IdempotentCmdOutput implements Mutator.IdempotentCmdOutput. -func (m *GitDiffMutator) IdempotentCmdOutput(cmd *exec.Cmd) ([]byte, error) { - return m.m.IdempotentCmdOutput(cmd) -} - -// Mkdir implements Mutator.Mkdir. -func (m *GitDiffMutator) Mkdir(name string, perm os.FileMode) error { - toFileMode, err := filemode.NewFromOSFileMode(os.ModeDir | perm) - if err != nil { - return err - } - return m.unifiedEncoder.Encode(&gitDiffPatch{ - filePatches: []diff.FilePatch{ - &gitDiffFilePatch{ - to: &gitDiffFile{ - fileMode: toFileMode, - path: m.trimPrefix(name), - hash: plumbing.ZeroHash, - }, - }, - }, - }) -} - -// RemoveAll implements Mutator.RemoveAll. -func (m *GitDiffMutator) RemoveAll(name string) error { - fromFileMode, _, err := m.getFileMode(name) - if err != nil { - return err - } - return m.unifiedEncoder.Encode(&gitDiffPatch{ - filePatches: []diff.FilePatch{ - &gitDiffFilePatch{ - from: &gitDiffFile{ - fileMode: fromFileMode, - path: m.trimPrefix(name), - hash: plumbing.ZeroHash, - }, - }, - }, - }) -} - -// RunCmd implements Mutator.RunCmd. -func (m *GitDiffMutator) RunCmd(cmd *exec.Cmd) error { - // FIXME write scripts to diff - return nil -} - -// Stat implements Mutator.Stat. -func (m *GitDiffMutator) Stat(name string) (os.FileInfo, error) { - return m.m.Stat(name) -} - -// Rename implements Mutator.Rename. -func (m *GitDiffMutator) Rename(oldpath, newpath string) error { - fileMode, _, err := m.getFileMode(oldpath) - if err != nil { - return err - } - return m.unifiedEncoder.Encode(&gitDiffPatch{ - filePatches: []diff.FilePatch{ - &gitDiffFilePatch{ - from: &gitDiffFile{ - fileMode: fileMode, - path: m.trimPrefix(oldpath), - hash: plumbing.ZeroHash, - }, - to: &gitDiffFile{ - fileMode: fileMode, - path: m.trimPrefix(newpath), - hash: plumbing.ZeroHash, - }, - }, - }, - }) -} - -// WriteFile implements Mutator.WriteFile. -func (m *GitDiffMutator) WriteFile(filename string, data []byte, perm os.FileMode, currData []byte) error { - fileMode, _, err := m.getFileMode(filename) - if err != nil { - return err - } - path := m.trimPrefix(filename) - isBinary := isBinary(currData) || isBinary(data) - var chunks []diff.Chunk - if !isBinary { - chunks = diffChunks(string(currData), string(data)) - } - return m.unifiedEncoder.Encode(&gitDiffPatch{ - filePatches: []diff.FilePatch{ - &gitDiffFilePatch{ - isBinary: isBinary, - from: &gitDiffFile{ - fileMode: fileMode, - path: path, - hash: plumbing.ComputeHash(plumbing.BlobObject, currData), - }, - to: &gitDiffFile{ - fileMode: fileMode, - path: path, - hash: plumbing.ComputeHash(plumbing.BlobObject, data), - }, - chunks: chunks, - }, - }, - }) -} - -// WriteSymlink implements Mutator.WriteSymlink. -func (m *GitDiffMutator) WriteSymlink(oldname, newname string) error { - return m.unifiedEncoder.Encode(&gitDiffPatch{ - filePatches: []diff.FilePatch{ - &gitDiffFilePatch{ - to: &gitDiffFile{ - fileMode: filemode.Symlink, - path: m.trimPrefix(newname), - hash: plumbing.ComputeHash(plumbing.BlobObject, []byte(oldname)), - }, - chunks: []diff.Chunk{ - &gitDiffChunk{ - content: oldname, - operation: diff.Add, - }, - }, - }, - }, - }) -} - -func (m *GitDiffMutator) getFileMode(name string) (filemode.FileMode, os.FileInfo, error) { - info, err := m.m.Stat(name) - if os.IsNotExist(err) { - return filemode.Empty, nil, nil - } else if err != nil { - return filemode.Empty, nil, err - } - fileMode, err := filemode.NewFromOSFileMode(info.Mode()) - return fileMode, info, err -} - -func (m *GitDiffMutator) trimPrefix(path string) string { - return strings.TrimPrefix(path, m.prefix) -} - -var gitDiffOperation = map[diffmatchpatch.Operation]diff.Operation{ - diffmatchpatch.DiffDelete: diff.Delete, - diffmatchpatch.DiffEqual: diff.Equal, - diffmatchpatch.DiffInsert: diff.Add, -} - -type gitDiffChunk struct { - content string - operation diff.Operation -} - -func (c *gitDiffChunk) Content() string { return c.content } -func (c *gitDiffChunk) Type() diff.Operation { return c.operation } - -type gitDiffFile struct { - hash plumbing.Hash - fileMode filemode.FileMode - path string -} - -func (f *gitDiffFile) Hash() plumbing.Hash { return f.hash } -func (f *gitDiffFile) Mode() filemode.FileMode { return f.fileMode } -func (f *gitDiffFile) Path() string { return f.path } - -type gitDiffFilePatch struct { - isBinary bool - from, to diff.File - chunks []diff.Chunk -} - -func (fp *gitDiffFilePatch) IsBinary() bool { return fp.isBinary } -func (fp *gitDiffFilePatch) Files() (diff.File, diff.File) { return fp.from, fp.to } -func (fp *gitDiffFilePatch) Chunks() []diff.Chunk { return fp.chunks } - -type gitDiffPatch struct { - filePatches []diff.FilePatch - message string -} - -func (p *gitDiffPatch) FilePatches() []diff.FilePatch { return p.filePatches } -func (p *gitDiffPatch) Message() string { return p.message } - -func diffChunks(from, to string) []diff.Chunk { - dmp := diffmatchpatch.New() - dmp.DiffTimeout = time.Second - fromRunes, toRunes, runesToLines := dmp.DiffLinesToRunes(from, to) - diffs := dmp.DiffCharsToLines(dmp.DiffMainRunes(fromRunes, toRunes, false), runesToLines) - chunks := make([]diff.Chunk, 0, len(diffs)) - for _, d := range diffs { - chunk := &gitDiffChunk{ - content: d.Text, - operation: gitDiffOperation[d.Type], - } - chunks = append(chunks, chunk) - } - return chunks -} diff --git a/internal/chezmoi/gitdiffmutator_test.go b/internal/chezmoi/gitdiffmutator_test.go deleted file mode 100644 index 6ed0eed113b..00000000000 --- a/internal/chezmoi/gitdiffmutator_test.go +++ /dev/null @@ -1,11 +0,0 @@ -package chezmoi - -import "github.com/go-git/go-git/v5/plumbing/format/diff" - -var ( - _ Mutator = &GitDiffMutator{} - _ diff.Chunk = &gitDiffChunk{} - _ diff.File = &gitDiffFile{} - _ diff.FilePatch = &gitDiffFilePatch{} - _ diff.Patch = &gitDiffPatch{} -) diff --git a/chezmoi2/internal/chezmoi/gitdiffsystem.go b/internal/chezmoi/gitdiffsystem.go similarity index 96% rename from chezmoi2/internal/chezmoi/gitdiffsystem.go rename to internal/chezmoi/gitdiffsystem.go index ade31de0483..9af4a4b0ad3 100644 --- a/chezmoi2/internal/chezmoi/gitdiffsystem.go +++ b/internal/chezmoi/gitdiffsystem.go @@ -8,7 +8,7 @@ import ( "github.com/go-git/go-git/v5/plumbing" "github.com/go-git/go-git/v5/plumbing/filemode" "github.com/go-git/go-git/v5/plumbing/format/diff" - vfs "github.com/twpayne/go-vfs" + vfs "github.com/twpayne/go-vfs/v2" ) // A GitDiffSystem wraps a System and logs all of the actions executed as a git @@ -92,13 +92,13 @@ func (s *GitDiffSystem) RawPath(path AbsPath) (AbsPath, error) { } // ReadDir implements System.ReadDir. -func (s *GitDiffSystem) ReadDir(dirname AbsPath) ([]os.FileInfo, error) { - return s.system.ReadDir(dirname) +func (s *GitDiffSystem) ReadDir(name AbsPath) ([]os.DirEntry, error) { + return s.system.ReadDir(name) } // ReadFile implements System.ReadFile. -func (s *GitDiffSystem) ReadFile(filename AbsPath) ([]byte, error) { - return s.system.ReadFile(filename) +func (s *GitDiffSystem) ReadFile(name AbsPath) ([]byte, error) { + return s.system.ReadFile(name) } // Readlink implements System.Readlink. diff --git a/chezmoi2/internal/chezmoi/gitdiffsystem_test.go b/internal/chezmoi/gitdiffsystem_test.go similarity index 100% rename from chezmoi2/internal/chezmoi/gitdiffsystem_test.go rename to internal/chezmoi/gitdiffsystem_test.go diff --git a/internal/chezmoi/gpg.go b/internal/chezmoi/gpg.go deleted file mode 100644 index ab650190229..00000000000 --- a/internal/chezmoi/gpg.go +++ /dev/null @@ -1,89 +0,0 @@ -package chezmoi - -import ( - "io/ioutil" - "os" - "os/exec" - "path/filepath" -) - -// GPG interfaces with gpg. -type GPG struct { - Command string - Recipient string - Symmetric bool -} - -// Decrypt decrypts ciphertext. filename is used as a hint for naming temporary -// files. -func (g *GPG) Decrypt(filename string, ciphertext []byte) ([]byte, error) { - tempDir, err := ioutil.TempDir("", "chezmoi-decrypt") - if err != nil { - return nil, err - } - defer os.RemoveAll(tempDir) - - outputFilename := filepath.Join(tempDir, filepath.Base(filename)) - inputFilename := outputFilename + ".gpg" - if err := ioutil.WriteFile(inputFilename, ciphertext, 0o600); err != nil { - return nil, err - } - - //nolint:gosec - cmd := exec.Command( - g.Command, - "--output", outputFilename, - "--quiet", - "--decrypt", inputFilename, - ) - cmd.Stdin = os.Stdin - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - if err := cmd.Run(); err != nil { - return nil, err - } - - return ioutil.ReadFile(outputFilename) -} - -// Encrypt encrypts plaintext for ts's recipient. filename is used as a hint for -// naming temporary files. -func (g *GPG) Encrypt(filename string, plaintext []byte) ([]byte, error) { - tempDir, err := ioutil.TempDir("", "chezmoi-encrypt") - if err != nil { - return nil, err - } - defer os.RemoveAll(tempDir) - - inputFilename := filepath.Join(tempDir, filepath.Base(filename)) - if err := ioutil.WriteFile(inputFilename, plaintext, 0o600); err != nil { - return nil, err - } - outputFilename := inputFilename + ".gpg" - - args := []string{ - "--armor", - "--output", outputFilename, - "--quiet", - } - if g.Symmetric { - args = append(args, "--symmetric") - } else { - if g.Recipient != "" { - args = append(args, "--recipient", g.Recipient) - } - args = append(args, "--encrypt") - } - args = append(args, filename) - - //nolint:gosec - cmd := exec.Command(g.Command, args...) - cmd.Stdin = os.Stdin - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - if err := cmd.Run(); err != nil { - return nil, err - } - - return ioutil.ReadFile(outputFilename) -} diff --git a/chezmoi2/internal/chezmoi/gpgencryption.go b/internal/chezmoi/gpgencryption.go similarity index 97% rename from chezmoi2/internal/chezmoi/gpgencryption.go rename to internal/chezmoi/gpgencryption.go index 7d7c6f84442..ed55ac98f05 100644 --- a/chezmoi2/internal/chezmoi/gpgencryption.go +++ b/internal/chezmoi/gpgencryption.go @@ -7,7 +7,7 @@ import ( "github.com/rs/zerolog/log" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoilog" + "github.com/twpayne/chezmoi/internal/chezmoilog" ) // A GPGEncryption uses gpg for encryption and decryption. See https://gnupg.org/. diff --git a/chezmoi2/internal/chezmoi/gpgencryption_test.go b/internal/chezmoi/gpgencryption_test.go similarity index 90% rename from chezmoi2/internal/chezmoi/gpgencryption_test.go rename to internal/chezmoi/gpgencryption_test.go index 7e56e48cb0b..638d06ad0bc 100644 --- a/chezmoi2/internal/chezmoi/gpgencryption_test.go +++ b/internal/chezmoi/gpgencryption_test.go @@ -2,14 +2,13 @@ package chezmoi import ( "errors" - "io/ioutil" "os" "os/exec" "testing" "github.com/stretchr/testify/require" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoitest" + "github.com/twpayne/chezmoi/internal/chezmoitest" ) func TestGPGEncryption(t *testing.T) { @@ -23,7 +22,7 @@ func TestGPGEncryption(t *testing.T) { } require.NoError(t, err) - tempDir, err := ioutil.TempDir("", "chezmoi-test-gpg") + tempDir, err := os.MkdirTemp("", "chezmoi-test-gpg") require.NoError(t, err) defer func() { require.NoError(t, os.RemoveAll(tempDir)) diff --git a/chezmoi2/internal/chezmoi/hexbytes.go b/internal/chezmoi/hexbytes.go similarity index 100% rename from chezmoi2/internal/chezmoi/hexbytes.go rename to internal/chezmoi/hexbytes.go diff --git a/chezmoi2/internal/chezmoi/hexbytes_test.go b/internal/chezmoi/hexbytes_test.go similarity index 100% rename from chezmoi2/internal/chezmoi/hexbytes_test.go rename to internal/chezmoi/hexbytes_test.go diff --git a/chezmoi2/internal/chezmoi/lazy.go b/internal/chezmoi/lazy.go similarity index 100% rename from chezmoi2/internal/chezmoi/lazy.go rename to internal/chezmoi/lazy.go diff --git a/internal/chezmoi/maybeshellquote.go b/internal/chezmoi/maybeshellquote.go index 6d527d16fe3..e09220c9270 100644 --- a/internal/chezmoi/maybeshellquote.go +++ b/internal/chezmoi/maybeshellquote.go @@ -5,19 +5,21 @@ import ( "strings" ) -var needShellQuoteRegexp = regexp.MustCompile(`[^+\-./0-9=A-Z_a-z]`) +// nonShellLiteralRx is a regular expression that matches anything that is not a +// shell literal. +var nonShellLiteralRx = regexp.MustCompile(`[^+\-./0-9=A-Z_a-z]`) -const ( - backslash = '\\' - singleQuote = '\'' -) +// maybeShellQuote returns s quoted as a shell argument, if necessary. +func maybeShellQuote(s string) string { + const ( + backslash = '\\' + singleQuote = '\'' + ) -// MaybeShellQuote returns s quoted as a shell argument, if necessary. -func MaybeShellQuote(s string) string { switch { case s == "": return "''" - case needShellQuoteRegexp.MatchString(s): + case nonShellLiteralRx.MatchString(s): result := make([]byte, 0, 2+len(s)) inSingleQuotes := false for _, b := range []byte(s) { @@ -33,7 +35,7 @@ func MaybeShellQuote(s string) string { result = append(result, singleQuote) inSingleQuotes = false } - result = append(result, backslash, singleQuote) + result = append(result, '\\', singleQuote) default: if !inSingleQuotes { result = append(result, singleQuote) @@ -55,7 +57,7 @@ func MaybeShellQuote(s string) string { func ShellQuoteArgs(args []string) string { shellQuotedArgs := make([]string, 0, len(args)) for _, arg := range args { - shellQuotedArgs = append(shellQuotedArgs, MaybeShellQuote(arg)) + shellQuotedArgs = append(shellQuotedArgs, maybeShellQuote(arg)) } return strings.Join(shellQuotedArgs, " ") } diff --git a/internal/chezmoi/maybeshellquote_test.go b/internal/chezmoi/maybeshellquote_test.go index cb145721cc0..37b174fb200 100644 --- a/internal/chezmoi/maybeshellquote_test.go +++ b/internal/chezmoi/maybeshellquote_test.go @@ -21,6 +21,28 @@ func TestMaybeShellQuote(t *testing.T) { `--arg`: `--arg`, `--arg=value`: `--arg=value`, } { - assert.Equal(t, expected, MaybeShellQuote(s), "quoting %q", s) + assert.Equal(t, expected, maybeShellQuote(s), "quoting %q", s) + } +} + +func TestShellQuoteArgs(t *testing.T) { + for _, tc := range []struct { + args []string + expected string + }{ + { + args: []string{}, + expected: "", + }, + { + args: []string{"foo"}, + expected: "foo", + }, + { + args: []string{"foo", "bar baz"}, + expected: "foo 'bar baz'", + }, + } { + assert.Equal(t, tc.expected, ShellQuoteArgs(tc.args)) } } diff --git a/chezmoi2/internal/chezmoi/mockpersistentstate.go b/internal/chezmoi/mockpersistentstate.go similarity index 100% rename from chezmoi2/internal/chezmoi/mockpersistentstate.go rename to internal/chezmoi/mockpersistentstate.go diff --git a/chezmoi2/internal/chezmoi/mockpersistentstate_test.go b/internal/chezmoi/mockpersistentstate_test.go similarity index 100% rename from chezmoi2/internal/chezmoi/mockpersistentstate_test.go rename to internal/chezmoi/mockpersistentstate_test.go diff --git a/internal/chezmoi/mutator.go b/internal/chezmoi/mutator.go deleted file mode 100644 index 9ead0eb0479..00000000000 --- a/internal/chezmoi/mutator.go +++ /dev/null @@ -1,19 +0,0 @@ -package chezmoi - -import ( - "os" - "os/exec" -) - -// A Mutator makes changes. -type Mutator interface { - Chmod(name string, mode os.FileMode) error - IdempotentCmdOutput(cmd *exec.Cmd) ([]byte, error) - Mkdir(name string, perm os.FileMode) error - RemoveAll(name string) error - Rename(oldpath, newpath string) error - RunCmd(cmd *exec.Cmd) error - Stat(name string) (os.FileInfo, error) - WriteFile(filename string, data []byte, perm os.FileMode, currData []byte) error - WriteSymlink(oldname, newname string) error -} diff --git a/chezmoi2/internal/chezmoi/noencryption.go b/internal/chezmoi/noencryption.go similarity index 100% rename from chezmoi2/internal/chezmoi/noencryption.go rename to internal/chezmoi/noencryption.go diff --git a/chezmoi2/internal/chezmoi/noencryption_test.go b/internal/chezmoi/noencryption_test.go similarity index 100% rename from chezmoi2/internal/chezmoi/noencryption_test.go rename to internal/chezmoi/noencryption_test.go diff --git a/internal/chezmoi/nullmutator.go b/internal/chezmoi/nullmutator.go deleted file mode 100644 index c43aff449cf..00000000000 --- a/internal/chezmoi/nullmutator.go +++ /dev/null @@ -1,58 +0,0 @@ -package chezmoi - -import ( - "os" - "os/exec" -) - -// NullMutator is an Mutator that does nothing. -type NullMutator struct{} - -// Chmod implements Mutator.Chmod. -func (NullMutator) Chmod(string, os.FileMode) error { - return nil -} - -// IdempotentCmdOutput implements Mutator.IdempotentCmdOutput. -func (NullMutator) IdempotentCmdOutput(cmd *exec.Cmd) ([]byte, error) { - return cmd.Output() -} - -// Mkdir implements Mutator.Mkdir. -func (NullMutator) Mkdir(string, os.FileMode) error { - return nil -} - -// RemoveAll implements Mutator.RemoveAll. -func (NullMutator) RemoveAll(string) error { - return nil -} - -// Rename implements Mutator.Rename. -func (NullMutator) Rename(string, string) error { - return nil -} - -// RunCmd implements Mutator.RunCmd. -func (NullMutator) RunCmd(cmd *exec.Cmd) error { - return nil -} - -// Stat implements Mutator.Stat. -func (NullMutator) Stat(path string) (os.FileInfo, error) { - return nil, &os.PathError{ - Op: "stat", - Path: path, - Err: os.ErrNotExist, - } -} - -// WriteFile implements Mutator.WriteFile. -func (NullMutator) WriteFile(string, []byte, os.FileMode, []byte) error { - return nil -} - -// WriteSymlink implements Mutator.WriteSymlink. -func (NullMutator) WriteSymlink(string, string) error { - return nil -} diff --git a/chezmoi2/internal/chezmoi/nullpersistentstate.go b/internal/chezmoi/nullpersistentstate.go similarity index 100% rename from chezmoi2/internal/chezmoi/nullpersistentstate.go rename to internal/chezmoi/nullpersistentstate.go diff --git a/chezmoi2/internal/chezmoi/path.go b/internal/chezmoi/path.go similarity index 100% rename from chezmoi2/internal/chezmoi/path.go rename to internal/chezmoi/path.go diff --git a/chezmoi2/internal/chezmoi/path_test.go b/internal/chezmoi/path_test.go similarity index 95% rename from chezmoi2/internal/chezmoi/path_test.go rename to internal/chezmoi/path_test.go index 9599dfd91ee..7851c8b74e7 100644 --- a/chezmoi2/internal/chezmoi/path_test.go +++ b/internal/chezmoi/path_test.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoitest" + "github.com/twpayne/chezmoi/internal/chezmoitest" ) func TestNewAbsPathFromExtPath(t *testing.T) { diff --git a/chezmoi2/internal/chezmoi/path_unix.go b/internal/chezmoi/path_unix.go similarity index 100% rename from chezmoi2/internal/chezmoi/path_unix.go rename to internal/chezmoi/path_unix.go diff --git a/chezmoi2/internal/chezmoi/path_windows.go b/internal/chezmoi/path_windows.go similarity index 100% rename from chezmoi2/internal/chezmoi/path_windows.go rename to internal/chezmoi/path_windows.go diff --git a/internal/chezmoi/patternset.go b/internal/chezmoi/patternset.go index 834585e3c69..6926fd5f69e 100644 --- a/internal/chezmoi/patternset.go +++ b/internal/chezmoi/patternset.go @@ -1,47 +1,108 @@ package chezmoi import ( + "path/filepath" + "sort" + "github.com/bmatcuk/doublestar/v3" + vfs "github.com/twpayne/go-vfs/v2" ) -// An PatternSet is a set of patterns. -type PatternSet struct { - includes map[string]struct{} - excludes map[string]struct{} +// A stringSet is a set of strings. +type stringSet map[string]struct{} + +// An patternSet is a set of patterns. +type patternSet struct { + includePatterns stringSet + excludePatterns stringSet } -// NewPatternSet returns a new PatternSet. -func NewPatternSet() *PatternSet { - return &PatternSet{ - includes: make(map[string]struct{}), - excludes: make(map[string]struct{}), +// newPatternSet returns a new patternSet. +func newPatternSet() *patternSet { + return &patternSet{ + includePatterns: newStringSet(), + excludePatterns: newStringSet(), } } -// Add adds a pattern to ps. -func (ps *PatternSet) Add(pattern string, include bool) error { - if _, err := doublestar.PathMatch(pattern, ""); err != nil { - return nil +// add adds a pattern to ps. +func (ps *patternSet) add(pattern string, include bool) error { + if _, err := doublestar.Match(pattern, ""); err != nil { + return err } if include { - ps.includes[pattern] = struct{}{} + ps.includePatterns.add(pattern) } else { - ps.excludes[pattern] = struct{}{} + ps.excludePatterns.add(pattern) } return nil } -// Match returns if name matches any pattern in ps. -func (ps *PatternSet) Match(name string) bool { - for pattern := range ps.excludes { - if ok, _ := doublestar.PathMatch(pattern, name); ok { +// glob returns all matches in fs. +func (ps *patternSet) glob(fs vfs.FS, prefix string) ([]string, error) { + // FIXME use AbsPath and RelPath + vos := doubleStarOS{FS: fs} + allMatches := newStringSet() + for includePattern := range ps.includePatterns { + matches, err := doublestar.GlobOS(vos, prefix+includePattern) + if err != nil { + return nil, err + } + allMatches.add(matches...) + } + for match := range allMatches { + for excludePattern := range ps.excludePatterns { + exclude, err := doublestar.PathMatchOS(vos, prefix+excludePattern, match) + if err != nil { + return nil, err + } + if exclude { + delete(allMatches, match) + } + } + } + matchesSlice := allMatches.elements() + for i, match := range matchesSlice { + matchesSlice[i] = mustTrimPrefix(filepath.ToSlash(match), prefix) + } + sort.Strings(matchesSlice) + return matchesSlice, nil +} + +// match returns if name matches any pattern in ps. +func (ps *patternSet) match(name string) bool { + for pattern := range ps.excludePatterns { + if ok, _ := doublestar.Match(pattern, name); ok { return false } } - for pattern := range ps.includes { - if ok, _ := doublestar.PathMatch(pattern, name); ok { + for pattern := range ps.includePatterns { + if ok, _ := doublestar.Match(pattern, name); ok { return true } } return false } + +// newStringSet returns a new StringSet containing elements. +func newStringSet(elements ...string) stringSet { + s := make(stringSet) + s.add(elements...) + return s +} + +// add adds elements to s. +func (s stringSet) add(elements ...string) { + for _, element := range elements { + s[element] = struct{}{} + } +} + +// elements returns all the elements of s. +func (s stringSet) elements() []string { + elements := make([]string, 0, len(s)) + for element := range s { + elements = append(elements, element) + } + return elements +} diff --git a/internal/chezmoi/patternset_test.go b/internal/chezmoi/patternset_test.go index db1480b1cd9..8a9f535f466 100644 --- a/internal/chezmoi/patternset_test.go +++ b/internal/chezmoi/patternset_test.go @@ -1,22 +1,24 @@ package chezmoi import ( - "path/filepath" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + vfs "github.com/twpayne/go-vfs/v2" + + "github.com/twpayne/chezmoi/internal/chezmoitest" ) func TestPatternSet(t *testing.T) { for _, tc := range []struct { name string - ps *PatternSet + ps *patternSet expectMatches map[string]bool }{ { name: "empty", - ps: NewPatternSet(), + ps: newPatternSet(), expectMatches: map[string]bool{ "foo": false, }, @@ -60,25 +62,87 @@ func TestPatternSet(t *testing.T) { "**/foo": true, }), expectMatches: map[string]bool{ - "foo": true, - filepath.Join("bar", "foo"): true, - filepath.Join("baz", "bar", "foo"): true, + "foo": true, + "bar/foo": true, + "baz/bar/foo": true, }, }, } { t.Run(tc.name, func(t *testing.T) { for s, expectMatch := range tc.expectMatches { - assert.Equal(t, expectMatch, tc.ps.Match(s)) + assert.Equal(t, expectMatch, tc.ps.match(s)) } }) } } -func mustNewPatternSet(t *testing.T, patterns map[string]bool) *PatternSet { +func TestPatternSetGlob(t *testing.T) { + for _, tc := range []struct { + name string + ps *patternSet + root interface{} + expectedMatches []string + }{ + { + name: "empty", + ps: newPatternSet(), + root: nil, + expectedMatches: []string{}, + }, + { + name: "simple", + ps: mustNewPatternSet(t, map[string]bool{ + "f*": true, + }), + root: map[string]interface{}{ + "foo": "", + }, + expectedMatches: []string{ + "foo", + }, + }, + { + name: "include_exclude", + ps: mustNewPatternSet(t, map[string]bool{ + "b*": true, + "*z": false, + }), + root: map[string]interface{}{ + "bar": "", + "baz": "", + }, + expectedMatches: []string{ + "bar", + }, + }, + { + name: "doublestar", + ps: mustNewPatternSet(t, map[string]bool{ + "**/f*": true, + }), + root: map[string]interface{}{ + "dir1/dir2/foo": "", + }, + expectedMatches: []string{ + "dir1/dir2/foo", + }, + }, + } { + t.Run(tc.name, func(t *testing.T) { + chezmoitest.WithTestFS(t, tc.root, func(fs vfs.FS) { + actualMatches, err := tc.ps.glob(fs, "/") + require.NoError(t, err) + assert.Equal(t, tc.expectedMatches, actualMatches) + }) + }) + } +} + +func mustNewPatternSet(t *testing.T, patterns map[string]bool) *patternSet { t.Helper() - ps := NewPatternSet() + ps := newPatternSet() for pattern, exclude := range patterns { - require.NoError(t, ps.Add(pattern, exclude)) + require.NoError(t, ps.add(pattern, exclude)) } return ps } diff --git a/chezmoi2/internal/chezmoi/persistentstate.go b/internal/chezmoi/persistentstate.go similarity index 100% rename from chezmoi2/internal/chezmoi/persistentstate.go rename to internal/chezmoi/persistentstate.go diff --git a/internal/chezmoi/private_posix.go b/internal/chezmoi/private_posix.go deleted file mode 100644 index eee5cbde444..00000000000 --- a/internal/chezmoi/private_posix.go +++ /dev/null @@ -1,16 +0,0 @@ -// +build !windows - -package chezmoi - -import ( - vfs "github.com/twpayne/go-vfs" -) - -// IsPrivate returns whether path should be considered private. -func IsPrivate(fs vfs.Stater, path string, want bool) (bool, error) { - info, err := fs.Stat(path) - if err != nil { - return false, err - } - return info.Mode().Perm()&0o77 == 0, nil -} diff --git a/internal/chezmoi/private_windows.go b/internal/chezmoi/private_windows.go deleted file mode 100644 index 7520a089b88..00000000000 --- a/internal/chezmoi/private_windows.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build windows - -package chezmoi - -import ( - vfs "github.com/twpayne/go-vfs" -) - -// IsPrivate always returns want on Windows. -func IsPrivate(fs vfs.Stater, path string, want bool) (bool, error) { - return want, nil -} diff --git a/chezmoi2/internal/chezmoi/readonlysystem.go b/internal/chezmoi/readonlysystem.go similarity index 85% rename from chezmoi2/internal/chezmoi/readonlysystem.go rename to internal/chezmoi/readonlysystem.go index 36dc8299ae6..e48e42da6e6 100644 --- a/chezmoi2/internal/chezmoi/readonlysystem.go +++ b/internal/chezmoi/readonlysystem.go @@ -4,7 +4,7 @@ import ( "os" "os/exec" - vfs "github.com/twpayne/go-vfs" + vfs "github.com/twpayne/go-vfs/v2" ) // A ReadOnlySystem is a system that may only be read from. @@ -41,13 +41,13 @@ func (s *ReadOnlySystem) RawPath(path AbsPath) (AbsPath, error) { } // ReadDir implements System.ReadDir. -func (s *ReadOnlySystem) ReadDir(dirname AbsPath) ([]os.FileInfo, error) { - return s.system.ReadDir(dirname) +func (s *ReadOnlySystem) ReadDir(name AbsPath) ([]os.DirEntry, error) { + return s.system.ReadDir(name) } // ReadFile implements System.ReadFile. -func (s *ReadOnlySystem) ReadFile(filename AbsPath) ([]byte, error) { - return s.system.ReadFile(filename) +func (s *ReadOnlySystem) ReadFile(name AbsPath) ([]byte, error) { + return s.system.ReadFile(name) } // Readlink implements System.Readlink. diff --git a/chezmoi2/internal/chezmoi/readonlysystem_test.go b/internal/chezmoi/readonlysystem_test.go similarity index 100% rename from chezmoi2/internal/chezmoi/readonlysystem_test.go rename to internal/chezmoi/readonlysystem_test.go diff --git a/chezmoi2/internal/chezmoi/realsystem.go b/internal/chezmoi/realsystem.go similarity index 87% rename from chezmoi2/internal/chezmoi/realsystem.go rename to internal/chezmoi/realsystem.go index 1815941dd07..a8e28a174a1 100644 --- a/chezmoi2/internal/chezmoi/realsystem.go +++ b/internal/chezmoi/realsystem.go @@ -1,17 +1,16 @@ package chezmoi import ( - "io/ioutil" "os" "os/exec" "runtime" "github.com/bmatcuk/doublestar/v3" "github.com/rs/zerolog/log" - vfs "github.com/twpayne/go-vfs" + vfs "github.com/twpayne/go-vfs/v2" "go.uber.org/multierr" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoilog" + "github.com/twpayne/chezmoi/internal/chezmoilog" ) // Glob implements System.Glob. @@ -49,13 +48,13 @@ func (s *RealSystem) RawPath(absPath AbsPath) (AbsPath, error) { } // ReadDir implements System.ReadDir. -func (s *RealSystem) ReadDir(dirname AbsPath) ([]os.FileInfo, error) { - return s.fs.ReadDir(string(dirname)) +func (s *RealSystem) ReadDir(name AbsPath) ([]os.DirEntry, error) { + return s.fs.ReadDir(string(name)) } // ReadFile implements System.ReadFile. -func (s *RealSystem) ReadFile(filename AbsPath) ([]byte, error) { - return s.fs.ReadFile(string(filename)) +func (s *RealSystem) ReadFile(name AbsPath) ([]byte, error) { + return s.fs.ReadFile(string(name)) } // RemoveAll implements System.RemoveAll. @@ -77,7 +76,7 @@ func (s *RealSystem) RunCmd(cmd *exec.Cmd) error { func (s *RealSystem) RunScript(scriptname RelPath, dir AbsPath, data []byte) (err error) { // Write the temporary script file. Put the randomness at the front of the // filename to preserve any file extension for Windows scripts. - f, err := ioutil.TempFile("", "*."+scriptname.Base()) + f, err := os.CreateTemp("", "*."+scriptname.Base()) if err != nil { return } diff --git a/chezmoi2/internal/chezmoi/realsystem_test.go b/internal/chezmoi/realsystem_test.go similarity index 93% rename from chezmoi2/internal/chezmoi/realsystem_test.go rename to internal/chezmoi/realsystem_test.go index 4eb77006395..7bc84202b07 100644 --- a/chezmoi2/internal/chezmoi/realsystem_test.go +++ b/internal/chezmoi/realsystem_test.go @@ -7,9 +7,9 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - vfs "github.com/twpayne/go-vfs" + vfs "github.com/twpayne/go-vfs/v2" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoitest" + "github.com/twpayne/chezmoi/internal/chezmoitest" ) var _ System = &RealSystem{} diff --git a/chezmoi2/internal/chezmoi/realsystem_unix.go b/internal/chezmoi/realsystem_unix.go similarity index 92% rename from chezmoi2/internal/chezmoi/realsystem_unix.go rename to internal/chezmoi/realsystem_unix.go index 93f074636db..74abdbcd261 100644 --- a/chezmoi2/internal/chezmoi/realsystem_unix.go +++ b/internal/chezmoi/realsystem_unix.go @@ -8,7 +8,7 @@ import ( "syscall" "github.com/google/renameio" - vfs "github.com/twpayne/go-vfs" + vfs "github.com/twpayne/go-vfs/v2" "go.uber.org/multierr" ) @@ -94,9 +94,9 @@ func (s *RealSystem) WriteSymlink(oldname string, newname AbsPath) error { return s.fs.Symlink(oldname, string(newname)) } -// writeFile is like ioutil.writeFile but always sets perm before writing data. -// ioutil.writeFile only sets the permissions when creating a new file. We need -// to ensure permissions, so we use our own implementation. +// writeFile is like os.WriteFile but always sets perm before writing data. +// os.WriteFile only sets the permissions when creating a new file. We need to +// ensure permissions, so we use our own implementation. func writeFile(fs vfs.FS, filename AbsPath, data []byte, perm os.FileMode) (err error) { // Create a new file, or truncate any existing one. f, err := fs.OpenFile(string(filename), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm) diff --git a/chezmoi2/internal/chezmoi/realsystem_windows.go b/internal/chezmoi/realsystem_windows.go similarity index 96% rename from chezmoi2/internal/chezmoi/realsystem_windows.go rename to internal/chezmoi/realsystem_windows.go index a9cb82a52a3..a853b2e04ab 100644 --- a/chezmoi2/internal/chezmoi/realsystem_windows.go +++ b/internal/chezmoi/realsystem_windows.go @@ -4,7 +4,7 @@ import ( "os" "path/filepath" - vfs "github.com/twpayne/go-vfs" + vfs "github.com/twpayne/go-vfs/v2" ) // An RealSystem is a System that writes to a filesystem and executes scripts. diff --git a/chezmoi2/internal/chezmoi/recursivemerge.go b/internal/chezmoi/recursivemerge.go similarity index 100% rename from chezmoi2/internal/chezmoi/recursivemerge.go rename to internal/chezmoi/recursivemerge.go diff --git a/chezmoi2/internal/chezmoi/recursivemerge_test.go b/internal/chezmoi/recursivemerge_test.go similarity index 100% rename from chezmoi2/internal/chezmoi/recursivemerge_test.go rename to internal/chezmoi/recursivemerge_test.go diff --git a/internal/chezmoi/script.go b/internal/chezmoi/script.go deleted file mode 100644 index ee39be23236..00000000000 --- a/internal/chezmoi/script.go +++ /dev/null @@ -1,242 +0,0 @@ -package chezmoi - -import ( - "archive/tar" - "bytes" - "crypto/sha256" - "encoding/hex" - "encoding/json" - "io/ioutil" - "os" - "os/exec" - "path/filepath" - "strings" - "time" - - vfs "github.com/twpayne/go-vfs" -) - -// FIXME allow encrypted scripts -// FIXME add pre- and post- attributes - -// A ScriptAttributes holds attributes parsed from a source script name. -type ScriptAttributes struct { - Name string - Once bool - Template bool -} - -// A ScriptState represents the state of a script. -type ScriptState struct { - Name string `json:"name"` - ExecutedAt time.Time `json:"executedAt"` -} - -// A Script represents a script to run. -type Script struct { - sourceName string - targetName string - Once bool - Template bool - contents []byte - contentsErr error - evaluateContents func() ([]byte, error) -} - -type scriptConcreteValue struct { - Type string `json:"type" yaml:"type"` - SourcePath string `json:"sourcePath" yaml:"sourcePath"` - TargetPath string `json:"targetPath" yaml:"targetPath"` - Once bool `json:"once" yaml:"once"` - Template bool `json:"template" yaml:"template"` - Contents string `json:"contents" yaml:"contents"` -} - -// ParseScriptAttributes parses a source script file name. -func ParseScriptAttributes(sourceName string) ScriptAttributes { - name := strings.TrimPrefix(sourceName, runPrefix) - once := false - template := false - if strings.HasPrefix(name, oncePrefix) { - once = true - name = strings.TrimPrefix(name, oncePrefix) - } - if strings.HasSuffix(name, TemplateSuffix) { - template = true - name = strings.TrimSuffix(name, TemplateSuffix) - } - return ScriptAttributes{ - Name: name, - Once: once, - Template: template, - } -} - -// SourceName returns sa's source name. -func (sa ScriptAttributes) SourceName() string { - sourceName := runPrefix - if sa.Once { - sourceName += oncePrefix - } - sourceName += sa.Name - if sa.Template { - sourceName += TemplateSuffix - } - return sourceName -} - -// AppendAllEntries returns allEntries unchanged. -func (s *Script) AppendAllEntries(allEntries []Entry) []Entry { - return allEntries -} - -// Apply runs s. -func (s *Script) Apply(fs vfs.FS, mutator Mutator, follow bool, applyOptions *ApplyOptions) error { - if applyOptions.Ignore(s.targetName) { - return nil - } - contents, err := s.Contents() - if err != nil { - return err - } - if len(bytes.TrimSpace(contents)) == 0 { - return nil - } - - var key []byte - if s.Once { - contentsKeyArr := sha256.Sum256(contents) - key = []byte(s.targetName + ":" + hex.EncodeToString(contentsKeyArr[:])) - scriptStateData, err := applyOptions.PersistentState.Get(applyOptions.ScriptStateBucket, key) - if err != nil { - return err - } - if scriptStateData != nil { - return nil - } - } - - if applyOptions.Verbose { - if _, err := applyOptions.Stdout.Write(contents); err != nil { - return err - } - } - if applyOptions.DryRun { - return nil - } - - // Write the temporary script file. Put the randomness on the front of the - // filename to preserve any file extension for Windows scripts. - f, err := ioutil.TempFile("", "*."+filepath.Base(s.targetName)) - if err != nil { - return err - } - - defer func() { - _ = os.RemoveAll(f.Name()) - }() - if err := os.Chmod(f.Name(), 0o700); err != nil { - return err - } - if _, err := f.Write(contents); err != nil { - return err - } - if err := f.Close(); err != nil { - return err - } - - // Run the temporary script file. - //nolint:gosec - c := exec.Command(f.Name()) - c.Dir = filepath.Join(applyOptions.DestDir, filepath.Dir(s.targetName)) - c.Stdout = os.Stdout - c.Stderr = os.Stderr - c.Stdin = os.Stdin - if err := c.Run(); err != nil { - return err - } - - if s.Once { - scriptState := &ScriptState{ - Name: s.sourceName, - ExecutedAt: time.Now(), - } - scriptStateData, err := json.Marshal(&scriptState) - if err != nil { - return err - } - if err := applyOptions.PersistentState.Set(applyOptions.ScriptStateBucket, key, scriptStateData); err != nil { - return err - } - } - - return err -} - -// ConcreteValue implements Entry.ConcreteValue. -func (s *Script) ConcreteValue(ignore func(string) bool, sourceDir string, umask os.FileMode, recursive bool) (interface{}, error) { - if ignore(s.targetName) { - return nil, nil - } - contents, err := s.Contents() - if err != nil { - return nil, err - } - return &scriptConcreteValue{ - Type: "script", - SourcePath: filepath.Join(sourceDir, s.SourceName()), - TargetPath: s.TargetName(), - Once: s.Once, - Template: s.Template, - Contents: string(contents), - }, nil -} - -// Contents returns s's contents. -func (s *Script) Contents() ([]byte, error) { - if s.evaluateContents != nil { - s.contents, s.contentsErr = s.evaluateContents() - s.evaluateContents = nil - } - return s.contents, s.contentsErr -} - -// Evaluate evaluates s's contents. -func (s *Script) Evaluate(ignore func(string) bool) error { - if ignore(s.targetName) { - return nil - } - _, err := s.Contents() - return err -} - -// SourceName implements Entry.SourceName. -func (s *Script) SourceName() string { - return s.sourceName -} - -// TargetName implements Entry.TargetName. -func (s *Script) TargetName() string { - return s.targetName -} - -// archive writes s to w. -func (s *Script) archive(w *tar.Writer, ignore func(string) bool, headerTemplate *tar.Header, umask os.FileMode) error { - if ignore(s.targetName) { - return nil - } - contents, err := s.Contents() - if err != nil { - return err - } - header := *headerTemplate - header.Typeflag = tar.TypeReg - header.Name = s.targetName - header.Size = int64(len(contents)) - header.Mode = int64(0o777 &^ umask) - if err := w.WriteHeader(&header); err != nil { - return nil - } - _, err = w.Write(contents) - return err -} diff --git a/chezmoi2/internal/chezmoi/sourcerelpath.go b/internal/chezmoi/sourcerelpath.go similarity index 100% rename from chezmoi2/internal/chezmoi/sourcerelpath.go rename to internal/chezmoi/sourcerelpath.go diff --git a/chezmoi2/internal/chezmoi/sourcerelpath_test.go b/internal/chezmoi/sourcerelpath_test.go similarity index 100% rename from chezmoi2/internal/chezmoi/sourcerelpath_test.go rename to internal/chezmoi/sourcerelpath_test.go diff --git a/chezmoi2/internal/chezmoi/sourcestate.go b/internal/chezmoi/sourcestate.go similarity index 99% rename from chezmoi2/internal/chezmoi/sourcestate.go rename to internal/chezmoi/sourcestate.go index 62f7ff836fc..00736f1cabb 100644 --- a/chezmoi2/internal/chezmoi/sourcestate.go +++ b/internal/chezmoi/sourcestate.go @@ -5,7 +5,6 @@ import ( "bytes" "errors" "fmt" - "io/ioutil" "os" "os/exec" "runtime" @@ -14,7 +13,7 @@ import ( "text/template" "github.com/coreos/go-semver/semver" - vfs "github.com/twpayne/go-vfs" + vfs "github.com/twpayne/go-vfs/v2" "go.uber.org/multierr" ) @@ -121,7 +120,7 @@ type AddOptions struct { Encrypt bool EncryptedSuffix string Exact bool - Include *IncludeSet + Include *EntryTypeSet RemoveDir RelPath Template bool } @@ -302,17 +301,16 @@ type PreApplyFunc func(targetRelPath RelPath, targetEntryState, lastWrittenEntry // ApplyOptions are options to SourceState.ApplyAll and SourceState.ApplyOne. type ApplyOptions struct { - Include *IncludeSet - PreApplyFunc PreApplyFunc - SkipEncrypted bool - Umask os.FileMode + Include *EntryTypeSet + PreApplyFunc PreApplyFunc + Umask os.FileMode } // Apply updates targetRelPath in targetDir in destSystem to match s. func (s *SourceState) Apply(targetSystem, destSystem System, persistentState PersistentState, targetDir AbsPath, targetRelPath RelPath, options ApplyOptions) error { sourceStateEntry := s.entries[targetRelPath] - if options.SkipEncrypted { + if !options.Include.IncludeEncrypted() { if sourceStateFile, ok := sourceStateEntry.(*SourceStateFile); ok && sourceStateFile.Attr.Encrypted { return nil } @@ -893,7 +891,7 @@ func (s *SourceState) newSourceStateFile(sourceRelPath SourceRelPath, fileAttr F // Write the modifier to a temporary file. var tempFile *os.File - tempFile, err = ioutil.TempFile("", "*."+fileAttr.TargetName) + tempFile, err = os.CreateTemp("", "*."+fileAttr.TargetName) if err != nil { return } diff --git a/chezmoi2/internal/chezmoi/sourcestate_test.go b/internal/chezmoi/sourcestate_test.go similarity index 96% rename from chezmoi2/internal/chezmoi/sourcestate_test.go rename to internal/chezmoi/sourcestate_test.go index 74cba924b18..ddff2be7287 100644 --- a/chezmoi2/internal/chezmoi/sourcestate_test.go +++ b/internal/chezmoi/sourcestate_test.go @@ -9,10 +9,10 @@ import ( "github.com/coreos/go-semver/semver" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - vfs "github.com/twpayne/go-vfs" - "github.com/twpayne/go-vfs/vfst" + vfs "github.com/twpayne/go-vfs/v2" + "github.com/twpayne/go-vfs/v2/vfst" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoitest" + "github.com/twpayne/chezmoi/internal/chezmoitest" ) func TestSourceStateAdd(t *testing.T) { @@ -29,7 +29,7 @@ func TestSourceStateAdd(t *testing.T) { "/home/user/.dir", }, addOptions: AddOptions{ - Include: NewIncludeSet(IncludeAll), + Include: NewEntryTypeSet(EntryTypesAll), }, tests: []interface{}{ vfst.TestPath("/home/user/.local/share/chezmoi/dot_dir", @@ -50,7 +50,7 @@ func TestSourceStateAdd(t *testing.T) { "/home/user/.dir", }, addOptions: AddOptions{ - Include: NewIncludeSet(IncludeAll), + Include: NewEntryTypeSet(EntryTypesAll), }, extraRoot: map[string]interface{}{ "/home/user": map[string]interface{}{ @@ -78,7 +78,7 @@ func TestSourceStateAdd(t *testing.T) { "/home/user/.dir/file", }, addOptions: AddOptions{ - Include: NewIncludeSet(IncludeAll), + Include: NewEntryTypeSet(EntryTypesAll), }, tests: []interface{}{ vfst.TestPath("/home/user/.local/share/chezmoi/dot_dir", @@ -98,7 +98,7 @@ func TestSourceStateAdd(t *testing.T) { "/home/user/.dir/file", }, addOptions: AddOptions{ - Include: NewIncludeSet(IncludeAll), + Include: NewEntryTypeSet(EntryTypesAll), }, extraRoot: map[string]interface{}{ "/home/user/.local/share/chezmoi/dot_dir": &vfst.Dir{Perm: 0o777}, @@ -116,7 +116,7 @@ func TestSourceStateAdd(t *testing.T) { "/home/user/.dir/subdir", }, addOptions: AddOptions{ - Include: NewIncludeSet(IncludeAll), + Include: NewEntryTypeSet(EntryTypesAll), }, tests: []interface{}{ vfst.TestPath("/home/user/.local/share/chezmoi/dot_dir", @@ -138,7 +138,7 @@ func TestSourceStateAdd(t *testing.T) { "/home/user/.dir/subdir/file", }, addOptions: AddOptions{ - Include: NewIncludeSet(IncludeAll), + Include: NewEntryTypeSet(EntryTypesAll), }, tests: []interface{}{ vfst.TestPath("/home/user/.local/share/chezmoi/dot_dir", @@ -165,7 +165,7 @@ func TestSourceStateAdd(t *testing.T) { "/home/user/.dir/subdir/file", }, addOptions: AddOptions{ - Include: NewIncludeSet(IncludeAll), + Include: NewEntryTypeSet(EntryTypesAll), }, extraRoot: map[string]interface{}{ "/home/user/.local/share/chezmoi/dot_dir/subdir": &vfst.Dir{Perm: 0o777}, @@ -183,7 +183,7 @@ func TestSourceStateAdd(t *testing.T) { "/home/user/.empty", }, addOptions: AddOptions{ - Include: NewIncludeSet(IncludeAll), + Include: NewEntryTypeSet(EntryTypesAll), }, tests: []interface{}{ vfst.TestPath("/home/user/.local/share/chezmoi/dot_empty", @@ -198,7 +198,7 @@ func TestSourceStateAdd(t *testing.T) { }, addOptions: AddOptions{ Empty: true, - Include: NewIncludeSet(IncludeAll), + Include: NewEntryTypeSet(EntryTypesAll), }, tests: []interface{}{ vfst.TestPath("/home/user/.local/share/chezmoi/empty_dot_empty", @@ -214,7 +214,7 @@ func TestSourceStateAdd(t *testing.T) { "/home/user/.executable", }, addOptions: AddOptions{ - Include: NewIncludeSet(IncludeAll), + Include: NewEntryTypeSet(EntryTypesAll), }, tests: []interface{}{ vfst.TestPath("/home/user/.local/share/chezmoi/executable_dot_executable", @@ -230,7 +230,7 @@ func TestSourceStateAdd(t *testing.T) { "/home/user/.executable", }, addOptions: AddOptions{ - Include: NewIncludeSet(IncludeAll), + Include: NewEntryTypeSet(EntryTypesAll), }, tests: []interface{}{ vfst.TestPath("/home/user/.local/share/chezmoi/dot_executable", @@ -247,7 +247,7 @@ func TestSourceStateAdd(t *testing.T) { }, addOptions: AddOptions{ Create: true, - Include: NewIncludeSet(IncludeAll), + Include: NewEntryTypeSet(EntryTypesAll), }, tests: []interface{}{ vfst.TestPath("/home/user/.local/share/chezmoi/create_dot_create", @@ -263,7 +263,7 @@ func TestSourceStateAdd(t *testing.T) { "/home/user/.file", }, addOptions: AddOptions{ - Include: NewIncludeSet(IncludeAll), + Include: NewEntryTypeSet(EntryTypesAll), }, tests: []interface{}{ vfst.TestPath("/home/user/.local/share/chezmoi/dot_file", @@ -279,7 +279,7 @@ func TestSourceStateAdd(t *testing.T) { "/home/user/.file", }, addOptions: AddOptions{ - Include: NewIncludeSet(IncludeAll), + Include: NewEntryTypeSet(EntryTypesAll), }, extraRoot: map[string]interface{}{ "/home/user/.local/share/chezmoi/executable_dot_file": "# contents of .file\n", @@ -301,7 +301,7 @@ func TestSourceStateAdd(t *testing.T) { "/home/user/.file", }, addOptions: AddOptions{ - Include: NewIncludeSet(IncludeAll), + Include: NewEntryTypeSet(EntryTypesAll), }, extraRoot: map[string]interface{}{ "/home/user/.local/share/chezmoi/dot_file": "# old contents of .file\n", @@ -320,7 +320,7 @@ func TestSourceStateAdd(t *testing.T) { "/home/user/.private", }, addOptions: AddOptions{ - Include: NewIncludeSet(IncludeAll), + Include: NewEntryTypeSet(EntryTypesAll), }, tests: []interface{}{ vfst.TestPath("/home/user/.local/share/chezmoi/private_dot_private", @@ -336,7 +336,7 @@ func TestSourceStateAdd(t *testing.T) { "/home/user/.private", }, addOptions: AddOptions{ - Include: NewIncludeSet(IncludeAll), + Include: NewEntryTypeSet(EntryTypesAll), }, tests: []interface{}{ vfst.TestPath("/home/user/.local/share/chezmoi/dot_private", @@ -352,7 +352,7 @@ func TestSourceStateAdd(t *testing.T) { "/home/user/.symlink", }, addOptions: AddOptions{ - Include: NewIncludeSet(IncludeAll), + Include: NewEntryTypeSet(EntryTypesAll), }, tests: []interface{}{ vfst.TestPath("/home/user/.local/share/chezmoi/symlink_dot_symlink", @@ -367,7 +367,7 @@ func TestSourceStateAdd(t *testing.T) { "/home/user/.symlink_windows", }, addOptions: AddOptions{ - Include: NewIncludeSet(IncludeAll), + Include: NewEntryTypeSet(EntryTypesAll), }, extraRoot: map[string]interface{}{ "/home/user": map[string]interface{}{ @@ -388,7 +388,7 @@ func TestSourceStateAdd(t *testing.T) { }, addOptions: AddOptions{ AutoTemplate: true, - Include: NewIncludeSet(IncludeAll), + Include: NewEntryTypeSet(EntryTypesAll), }, tests: []interface{}{ vfst.TestPath("/home/user/.local/share/chezmoi/dot_template.tmpl", @@ -405,7 +405,7 @@ func TestSourceStateAdd(t *testing.T) { "/home/user/.dir/file", }, addOptions: AddOptions{ - Include: NewIncludeSet(IncludeAll), + Include: NewEntryTypeSet(EntryTypesAll), }, tests: []interface{}{ vfst.TestPath("/home/user/.local/share/chezmoi/dot_dir", @@ -425,7 +425,7 @@ func TestSourceStateAdd(t *testing.T) { "/home/user/.dir/subdir/file", }, addOptions: AddOptions{ - Include: NewIncludeSet(IncludeAll), + Include: NewEntryTypeSet(EntryTypesAll), }, extraRoot: map[string]interface{}{ "/home/user/.local/share/chezmoi/dot_dir/exact_subdir": &vfst.Dir{Perm: 0o777}, @@ -708,7 +708,8 @@ func TestSourceStateApplyAll(t *testing.T) { require.NoError(t, s.Read()) requireEvaluateAll(t, s, system) require.NoError(t, s.applyAll(system, system, persistentState, "/home/user", ApplyOptions{ - Umask: chezmoitest.Umask, + Include: NewEntryTypeSet(EntryTypesAll), + Umask: chezmoitest.Umask, })) vfst.RunTests(t, fs, "", tc.tests...) diff --git a/chezmoi2/internal/chezmoi/sourcestateentry.go b/internal/chezmoi/sourcestateentry.go similarity index 100% rename from chezmoi2/internal/chezmoi/sourcestateentry.go rename to internal/chezmoi/sourcestateentry.go diff --git a/internal/chezmoi/symlink.go b/internal/chezmoi/symlink.go deleted file mode 100644 index 82d0543dcb1..00000000000 --- a/internal/chezmoi/symlink.go +++ /dev/null @@ -1,132 +0,0 @@ -package chezmoi - -import ( - "archive/tar" - "os" - "path/filepath" - "strings" - - vfs "github.com/twpayne/go-vfs" -) - -// A Symlink represents the target state of a symlink. -type Symlink struct { - sourceName string - targetName string - Template bool - linkname string - linknameErr error - evaluateLinkname func() (string, error) -} - -type symlinkConcreteValue struct { - Type string `json:"type" yaml:"type"` - SourcePath string `json:"sourcePath" yaml:"sourcePath"` - TargetPath string `json:"targetPath" yaml:"targetPath"` - Template bool `json:"template" yaml:"template"` - Linkname string `json:"linkname" yaml:"linkname"` -} - -// AppendAllEntries appends all f to allEntries. -func (s *Symlink) AppendAllEntries(allEntries []Entry) []Entry { - return append(allEntries, s) -} - -// Apply ensures that the state of s's target in fs matches s. -func (s *Symlink) Apply(fs vfs.FS, mutator Mutator, follow bool, applyOptions *ApplyOptions) error { - if applyOptions.Ignore(s.targetName) { - return nil - } - target, err := s.Linkname() - if err != nil { - return err - } - targetPath := filepath.Join(applyOptions.DestDir, s.targetName) - var info os.FileInfo - if follow { - info, err = fs.Stat(targetPath) - } else { - info, err = fs.Lstat(targetPath) - } - switch { - case err == nil && target == "": - return mutator.RemoveAll(targetPath) - case os.IsNotExist(err) && target == "": - return nil - case err == nil && info.Mode()&os.ModeType == os.ModeSymlink: - currentTarget, err := fs.Readlink(targetPath) - if err != nil { - return err - } - if currentTarget == target { - return nil - } - case err == nil: - case os.IsNotExist(err): - default: - return err - } - return mutator.WriteSymlink(target, targetPath) -} - -// ConcreteValue implements Entry.ConcreteValue. -func (s *Symlink) ConcreteValue(ignore func(string) bool, sourceDir string, umask os.FileMode, recursive bool) (interface{}, error) { - if ignore(s.targetName) { - return nil, nil - } - linkname, err := s.Linkname() - if err != nil { - return nil, err - } - return &symlinkConcreteValue{ - Type: "symlink", - SourcePath: filepath.Join(sourceDir, s.SourceName()), - TargetPath: s.TargetName(), - Template: s.Template, - Linkname: linkname, - }, nil -} - -// Evaluate evaluates s's target. -func (s *Symlink) Evaluate(ignore func(string) bool) error { - if ignore(s.targetName) { - return nil - } - _, err := s.Linkname() - return err -} - -// Linkname returns s's link name. -func (s *Symlink) Linkname() (string, error) { - if s.evaluateLinkname != nil { - s.linkname, s.linknameErr = s.evaluateLinkname() - s.evaluateLinkname = nil - } - return strings.TrimSpace(s.linkname), s.linknameErr -} - -// SourceName implements Entry.SourceName. -func (s *Symlink) SourceName() string { - return s.sourceName -} - -// TargetName implements Entry.TargetName. -func (s *Symlink) TargetName() string { - return s.targetName -} - -// archive writes s to w. -func (s *Symlink) archive(w *tar.Writer, ignore func(string) bool, headerTemplate *tar.Header, umask os.FileMode) error { - if ignore(s.targetName) { - return nil - } - linkname, err := s.Linkname() - if err != nil { - return err - } - header := *headerTemplate - header.Name = s.targetName - header.Typeflag = tar.TypeSymlink - header.Linkname = linkname - return w.WriteHeader(&header) -} diff --git a/chezmoi2/internal/chezmoi/system.go b/internal/chezmoi/system.go similarity index 92% rename from chezmoi2/internal/chezmoi/system.go rename to internal/chezmoi/system.go index 8287337a115..92fc4199949 100644 --- a/chezmoi2/internal/chezmoi/system.go +++ b/internal/chezmoi/system.go @@ -5,7 +5,7 @@ import ( "os/exec" "path/filepath" - vfs "github.com/twpayne/go-vfs" + vfs "github.com/twpayne/go-vfs/v2" ) // A System reads from and writes to a filesystem, executes idempotent commands, @@ -17,8 +17,8 @@ type System interface { Lstat(filename AbsPath) (os.FileInfo, error) Mkdir(name AbsPath, perm os.FileMode) error RawPath(absPath AbsPath) (AbsPath, error) - ReadDir(dirname AbsPath) ([]os.FileInfo, error) - ReadFile(filename AbsPath) ([]byte, error) + ReadDir(name AbsPath) ([]os.DirEntry, error) + ReadFile(name AbsPath) ([]byte, error) Readlink(name AbsPath) (string, error) RemoveAll(name AbsPath) error Rename(oldpath, newpath AbsPath) error @@ -37,8 +37,8 @@ func (emptySystemMixin) Glob(pattern string) ([]string, error) { ret func (emptySystemMixin) IdempotentCmdOutput(cmd *exec.Cmd) ([]byte, error) { return nil, nil } func (emptySystemMixin) Lstat(name AbsPath) (os.FileInfo, error) { return nil, os.ErrNotExist } func (emptySystemMixin) RawPath(path AbsPath) (AbsPath, error) { return path, nil } -func (emptySystemMixin) ReadDir(dirname AbsPath) ([]os.FileInfo, error) { return nil, os.ErrNotExist } -func (emptySystemMixin) ReadFile(filename AbsPath) ([]byte, error) { return nil, os.ErrNotExist } +func (emptySystemMixin) ReadDir(name AbsPath) ([]os.DirEntry, error) { return nil, os.ErrNotExist } +func (emptySystemMixin) ReadFile(name AbsPath) ([]byte, error) { return nil, os.ErrNotExist } func (emptySystemMixin) Readlink(name AbsPath) (string, error) { return "", os.ErrNotExist } func (emptySystemMixin) Stat(name AbsPath) (os.FileInfo, error) { return nil, os.ErrNotExist } func (emptySystemMixin) UnderlyingFS() vfs.FS { return nil } diff --git a/internal/chezmoi/targetstate.go b/internal/chezmoi/targetstate.go deleted file mode 100644 index 9f827062ab6..00000000000 --- a/internal/chezmoi/targetstate.go +++ /dev/null @@ -1,856 +0,0 @@ -package chezmoi - -import ( - "archive/tar" - "bufio" - "bytes" - "errors" - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" - "sort" - "strings" - "text/template" - - "github.com/bmatcuk/doublestar/v3" - "github.com/coreos/go-semver/semver" - vfs "github.com/twpayne/go-vfs" -) - -// DefaultTemplateOptions are the default template options. -var DefaultTemplateOptions = []string{"missingkey=error"} - -const ( - ignoreName = ".chezmoiignore" - removeName = ".chezmoiremove" - templatesDirName = ".chezmoitemplates" - versionName = ".chezmoiversion" -) - -// An AddOptions contains options for TargetState.Add. -type AddOptions struct { - Empty bool - Encrypt bool - Exact bool - Recursive bool - Template bool - AutoTemplate bool -} - -// An ImportTAROptions contains options for TargetState.ImportTAR. -type ImportTAROptions struct { - DestinationDir string - Exact bool - StripComponents int -} - -// A PopulateOptions contains options for TargetState.Populate. -type PopulateOptions struct { - ExecuteTemplates bool -} - -// A TargetState represents the root target state. -type TargetState struct { - DestDir string - Entries map[string]Entry - GPG *GPG - MinVersion *semver.Version - SourceDir string - TargetIgnore *PatternSet - TargetRemove *PatternSet - TemplateData map[string]interface{} - TemplateFuncs template.FuncMap - TemplateOptions []string - Templates map[string]*template.Template - Umask os.FileMode -} - -// A TargetStateOption sets an option on a TargeState. -type TargetStateOption func(*TargetState) - -// WithDestDir sets DestDir. -func WithDestDir(destDir string) TargetStateOption { - return func(ts *TargetState) { - ts.DestDir = destDir - } -} - -// WithEntries sets the entries. -func WithEntries(entries map[string]Entry) TargetStateOption { - return func(ts *TargetState) { - ts.Entries = entries - } -} - -// WithGPG sets the GPG options. -func WithGPG(gpg *GPG) TargetStateOption { - return func(ts *TargetState) { - ts.GPG = gpg - } -} - -// WithMinVersion sets the minimum version. -func WithMinVersion(minVersion *semver.Version) TargetStateOption { - return func(ts *TargetState) { - ts.MinVersion = minVersion - } -} - -// WithSourceDir sets the source directory. -func WithSourceDir(sourceDir string) TargetStateOption { - return func(ts *TargetState) { - ts.SourceDir = sourceDir - } -} - -// WithTargetIgnore sets the target patterns to ignore. -func WithTargetIgnore(targetIgnore *PatternSet) TargetStateOption { - return func(ts *TargetState) { - ts.TargetIgnore = targetIgnore - } -} - -// WithTargetRemove sets the target patterns to remove. -func WithTargetRemove(targetRemove *PatternSet) TargetStateOption { - return func(ts *TargetState) { - ts.TargetRemove = targetRemove - } -} - -// WithTemplateData sets the template data. -func WithTemplateData(templateData map[string]interface{}) TargetStateOption { - return func(ts *TargetState) { - ts.TemplateData = templateData - } -} - -// WithTemplateFuncs sets the template functions. -func WithTemplateFuncs(templateFuncs template.FuncMap) TargetStateOption { - return func(ts *TargetState) { - ts.TemplateFuncs = templateFuncs - } -} - -// WithTemplateOptions sets the template functions. -func WithTemplateOptions(templateOptions []string) TargetStateOption { - return func(ts *TargetState) { - ts.TemplateOptions = templateOptions - } -} - -// WithTemplates sets the templates. -func WithTemplates(templates map[string]*template.Template) TargetStateOption { - return func(ts *TargetState) { - ts.Templates = templates - } -} - -// WithUmask sets the umask. -func WithUmask(umask os.FileMode) TargetStateOption { - return func(ts *TargetState) { - ts.Umask = umask - } -} - -// NewTargetState creates a new TargetState with the given options. -func NewTargetState(options ...TargetStateOption) *TargetState { - ts := &TargetState{ - Entries: make(map[string]Entry), - TargetIgnore: NewPatternSet(), - TargetRemove: NewPatternSet(), - TemplateOptions: DefaultTemplateOptions, - } - for _, o := range options { - o(ts) - } - return ts -} - -// Add adds a new target to ts. -func (ts *TargetState) Add(fs vfs.FS, addOptions AddOptions, targetPath string, info os.FileInfo, follow bool, mutator Mutator) error { - contains, err := vfs.Contains(fs, targetPath, ts.DestDir) - if err != nil { - return err - } - if !contains { - return fmt.Errorf("%s: outside target directory", targetPath) - } - targetName, err := filepath.Rel(ts.DestDir, targetPath) - if err != nil { - return err - } - if info == nil { - var err error - if follow { - info, err = fs.Stat(targetPath) - } else { - info, err = fs.Lstat(targetPath) - } - if err != nil { - return err - } - } else if follow && info.Mode()&os.ModeType == os.ModeSymlink { - info, err = fs.Stat(targetPath) - if err != nil { - return err - } - } - - // Add the parent directories, if needed. - parentDirSourceName := "" - entries := ts.Entries - if parentDirName := filepath.Dir(targetName); parentDirName != "." { - parentEntry, err := ts.findEntry(parentDirName) - if err != nil && !os.IsNotExist(err) { - return err - } - if parentEntry == nil { - if err := ts.Add(fs, addOptions, filepath.Join(ts.DestDir, parentDirName), nil, follow, mutator); err != nil { - return err - } - parentEntry, err = ts.findEntry(parentDirName) - if err != nil { - return err - } - } else if _, ok := parentEntry.(*Dir); !ok { - return fmt.Errorf("%s: not a directory", parentDirName) - } - parentDir := parentEntry.(*Dir) - parentDirSourceName = parentDir.sourceName - entries = parentDir.Entries - } - - switch { - case info.IsDir(): - perm := info.Mode().Perm() - infos, err := fs.ReadDir(targetPath) - if err != nil { - return err - } - private, err := IsPrivate(fs, targetPath, perm&0o77 == 0) - if err != nil { - return err - } - if private { - perm &^= 0o77 - } - // If the directory is empty, or the directory was not added - // recursively, add a .keep file so the directory is managed by git. - // chezmoi will ignore the .keep file as it begins with a dot. - createKeepFile := len(infos) == 0 || !addOptions.Recursive - return ts.addDir(targetName, entries, parentDirSourceName, addOptions.Exact, perm, createKeepFile, mutator) - case info.Mode().IsRegular(): - if info.Size() == 0 && !addOptions.Empty { - entry, err := ts.Get(fs, targetPath) - switch { - case os.IsNotExist(err): - return nil - case err == nil: - return mutator.RemoveAll(filepath.Join(ts.SourceDir, entry.SourceName())) - default: - return err - } - } - contents, err := fs.ReadFile(targetPath) - if err != nil { - return err - } - if addOptions.Template && addOptions.AutoTemplate { - contents = autoTemplate(contents, ts.TemplateData) - } - if addOptions.Encrypt { - contents, err = ts.GPG.Encrypt(targetPath, contents) - if err != nil { - return err - } - } - perm := info.Mode().Perm() - private, err := IsPrivate(fs, targetPath, perm&0o77 == 0) - if err != nil { - return err - } - if private { - perm &^= 0o77 - } - return ts.addFile(targetName, entries, parentDirSourceName, info, perm, addOptions.Encrypt, addOptions.Template, contents, mutator) - case info.Mode()&os.ModeType == os.ModeSymlink: - linkname, err := fs.Readlink(targetPath) - if err != nil { - return err - } - return ts.addSymlink(targetName, entries, parentDirSourceName, linkname, mutator) - default: - return fmt.Errorf("%s: not a regular file, directory, or symlink", targetName) - } -} - -// AllEntries returns all Entrys in ts. -func (ts *TargetState) AllEntries() []Entry { - var allEntries []Entry - for _, entry := range ts.Entries { - allEntries = entry.AppendAllEntries(allEntries) - } - return allEntries -} - -// Apply ensures that ts.DestDir in fs matches ts. -func (ts *TargetState) Apply(fs vfs.FS, mutator Mutator, follow bool, applyOptions *ApplyOptions) error { - if applyOptions.Remove { - // Build a set of targets to remove. - targetsToRemove := make(map[string]struct{}) - includes := make([]string, 0, len(ts.TargetRemove.includes)) - for include := range ts.TargetRemove.includes { - includes = append(includes, include) - } - for _, include := range includes { - matches, err := doublestar.GlobOS(doubleStarOS{FS: fs}, filepath.Join(ts.DestDir, include)) - if err != nil { - return err - } - for _, match := range matches { - relPath := strings.TrimPrefix(match, ts.DestDir+string(filepath.Separator)) - // Don't remove targets that are ignored. - if ts.TargetIgnore.Match(relPath) { - continue - } - // Don't remove targets that are excluded from remove. - if !ts.TargetRemove.Match(relPath) { - continue - } - targetsToRemove[match] = struct{}{} - } - } - - // FIXME check that the set of targets to remove does not intersect wth - // the list of all entries. - - // Remove targets in reverse order so we remove children before their - // parents. - sortedTargetsToRemove := make([]string, 0, len(targetsToRemove)) - for target := range targetsToRemove { - sortedTargetsToRemove = append(sortedTargetsToRemove, target) - } - sort.Sort(sort.Reverse(sort.StringSlice(sortedTargetsToRemove))) - for _, target := range sortedTargetsToRemove { - if err := mutator.RemoveAll(target); err != nil { - return err - } - } - } - - for _, entryName := range sortedEntryNames(ts.Entries) { - if err := ts.Entries[entryName].Apply(fs, mutator, follow, applyOptions); err != nil { - return err - } - } - return nil -} - -// Archive writes ts to w. -func (ts *TargetState) Archive(w *tar.Writer, umask os.FileMode) error { - headerTemplate, err := ts.getTarHeaderTemplate() - if err != nil { - return err - } - - for _, entryName := range sortedEntryNames(ts.Entries) { - if err := ts.Entries[entryName].archive(w, ts.TargetIgnore.Match, headerTemplate, umask); err != nil { - return err - } - } - return nil -} - -// ConcreteValue returns a value suitable for serialization. -func (ts *TargetState) ConcreteValue(recursive bool) (interface{}, error) { - var entryConcreteValues []interface{} - for _, entryName := range sortedEntryNames(ts.Entries) { - entryConcreteValue, err := ts.Entries[entryName].ConcreteValue(ts.TargetIgnore.Match, ts.SourceDir, ts.Umask, recursive) - if err != nil { - return nil, err - } - if entryConcreteValue != nil { - entryConcreteValues = append(entryConcreteValues, entryConcreteValue) - } - } - return entryConcreteValues, nil -} - -// Evaluate evaluates all of the entries in ts. -func (ts *TargetState) Evaluate() error { - for _, entryName := range sortedEntryNames(ts.Entries) { - if err := ts.Entries[entryName].Evaluate(ts.TargetIgnore.Match); err != nil { - return err - } - } - return nil -} - -// ExecuteTemplateData returns the result of executing template data. -func (ts *TargetState) ExecuteTemplateData(name string, data []byte) ([]byte, error) { - tmpl, err := template.New(name).Option(ts.TemplateOptions...).Funcs(ts.TemplateFuncs).Parse(string(data)) - if err != nil { - return nil, err - } - for name, t := range ts.Templates { - tmpl, err = tmpl.AddParseTree(name, t.Tree) - if err != nil { - return nil, err - } - } - sb := &strings.Builder{} - if err = tmpl.ExecuteTemplate(sb, name, ts.TemplateData); err != nil { - return nil, err - } - return []byte(sb.String()), nil -} - -// Get returns the state of the given target, or nil if no such target is found. -func (ts *TargetState) Get(fs vfs.Stater, target string) (Entry, error) { - contains, err := vfs.Contains(fs, target, ts.DestDir) - if err != nil { - return nil, err - } - if !contains { - return nil, fmt.Errorf("%s: outside target directory", target) - } - targetName, err := filepath.Rel(ts.DestDir, target) - if err != nil { - return nil, err - } - return ts.findEntry(targetName) -} - -// ImportTAR imports a tar archive. -func (ts *TargetState) ImportTAR(r *tar.Reader, importTAROptions ImportTAROptions, mutator Mutator) error { - for { - header, err := r.Next() - if errors.Is(err, io.EOF) { - break - } else if err != nil { - return err - } - switch header.Typeflag { - case tar.TypeDir, tar.TypeReg, tar.TypeSymlink: - if err := ts.importHeader(r, importTAROptions, header, mutator); err != nil { - return err - } - case tar.TypeXGlobalHeader: - default: - return fmt.Errorf("%s: unspported typeflag '%c'", header.Name, header.Typeflag) - } - } - return nil -} - -// Populate walks fs from ts.SourceDir to populate ts. -func (ts *TargetState) Populate(fs vfs.FS, options *PopulateOptions) error { - return vfs.Walk(fs, ts.SourceDir, func(path string, info os.FileInfo, _ error) error { - relPath, err := filepath.Rel(ts.SourceDir, path) - if err != nil { - return err - } - if relPath == "." { - return nil - } - // Treat all files and directories beginning with "." specially. - if _, name := filepath.Split(relPath); strings.HasPrefix(name, ".") { - switch { - case info.Name() == ignoreName: - dns := dirNames(parseDirNameComponents(splitPathList(relPath))) - return ts.addPatterns(fs, ts.TargetIgnore, path, filepath.Join(dns...)) - case info.Name() == removeName: - dns := dirNames(parseDirNameComponents(splitPathList(relPath))) - return ts.addPatterns(fs, ts.TargetRemove, path, filepath.Join(dns...)) - case info.Name() == templatesDirName: - if err := ts.addTemplatesDir(fs, path); err != nil { - return err - } - return filepath.SkipDir - case info.Name() == versionName: - data, err := fs.ReadFile(path) - if err != nil { - return err - } - version, err := semver.NewVersion(strings.TrimSpace(string(data))) - if err != nil { - return err - } - if ts.MinVersion == nil || ts.MinVersion.LessThan(*version) { - ts.MinVersion = version - } - return nil - case info.IsDir(): - // Don't recurse into ignored subdirectories. - return filepath.SkipDir - } - // Ignore all other files and directories. - return nil - } - switch { - case info.IsDir(): - components := splitPathList(relPath) - das := parseDirNameComponents(components) - dns := dirNames(das) - targetName := filepath.Join(dns...) - entries, err := ts.findEntries(dns[:len(dns)-1]) - if err != nil { - return err - } - da := das[len(das)-1] - entries[da.Name] = newDir(relPath, targetName, da.Exact, da.Perm) - case info.Mode().IsRegular(): - psfp := parseSourceFilePath(relPath) - dns := dirNames(psfp.dirAttributes) - entries, err := ts.findEntries(dns) - if err != nil { - return err - } - switch { - case psfp.fileAttributes != nil && psfp.fileAttributes.Mode&os.ModeType == 0 || psfp.scriptAttributes != nil: - readFile := func() ([]byte, error) { - return fs.ReadFile(path) - } - evaluateContents := readFile - if psfp.fileAttributes != nil && psfp.fileAttributes.Encrypted { - prevEvaluateContents := evaluateContents - evaluateContents = func() ([]byte, error) { - ciphertext, err := prevEvaluateContents() - if err != nil { - return nil, err - } - return ts.GPG.Decrypt(path, ciphertext) - } - } - if psfp.fileAttributes != nil && psfp.fileAttributes.Template || psfp.scriptAttributes != nil && psfp.scriptAttributes.Template { - if options == nil || options.ExecuteTemplates { - prevEvaluateContents := evaluateContents - evaluateContents = func() ([]byte, error) { - data, err := prevEvaluateContents() - if err != nil { - return nil, err - } - return ts.ExecuteTemplateData(path, data) - } - } - } - switch { - case psfp.fileAttributes != nil: - entry := &File{ - sourceName: relPath, - targetName: filepath.Join(append(dns, psfp.fileAttributes.Name)...), - Empty: psfp.fileAttributes.Empty, - Encrypted: psfp.fileAttributes.Encrypted, - Perm: psfp.fileAttributes.Mode.Perm(), - Template: psfp.fileAttributes.Template, - evaluateContents: evaluateContents, - } - entries[psfp.fileAttributes.Name] = entry - case psfp.scriptAttributes != nil: - entry := &Script{ - sourceName: relPath, - targetName: filepath.Join(append(dns, psfp.scriptAttributes.Name)...), - Once: psfp.scriptAttributes.Once, - Template: psfp.scriptAttributes.Template, - evaluateContents: evaluateContents, - } - entries[psfp.scriptAttributes.Name] = entry - } - case psfp.fileAttributes != nil && psfp.fileAttributes.Mode&os.ModeType == os.ModeSymlink: - evaluateLinkname := func() (string, error) { - data, err := fs.ReadFile(path) - return string(data), err - } - if psfp.fileAttributes.Template { - evaluateLinkname = func() (string, error) { - data, err := ts.executeTemplate(fs, path) - return string(data), err - } - } - entry := &Symlink{ - sourceName: relPath, - targetName: filepath.Join(append(dns, psfp.fileAttributes.Name)...), - Template: psfp.fileAttributes.Template, - evaluateLinkname: evaluateLinkname, - } - entries[psfp.fileAttributes.Name] = entry - default: - return fmt.Errorf("%s: unsupported file type", path) - } - default: - return fmt.Errorf("%s: unsupported file type", path) - } - return nil - }) -} - -func (ts *TargetState) addDir(targetName string, entries map[string]Entry, parentDirSourceName string, exact bool, perm os.FileMode, createKeepFile bool, mutator Mutator) error { - name := filepath.Base(targetName) - if entry, ok := entries[name]; ok { - if _, ok = entry.(*Dir); !ok { - return fmt.Errorf("%s: already added and not a directory", targetName) - } - return nil - } - sourceName := DirAttributes{ - Name: name, - Exact: exact, - Perm: perm, - }.SourceName() - if parentDirSourceName != "" { - sourceName = filepath.Join(parentDirSourceName, sourceName) - } - dir := newDir(sourceName, targetName, exact, perm) - if err := mutator.Mkdir(filepath.Join(ts.SourceDir, sourceName), 0o777&^ts.Umask); err != nil { - return err - } - if createKeepFile { - if err := mutator.WriteFile(filepath.Join(ts.SourceDir, sourceName, ".keep"), nil, 0o666&^ts.Umask, nil); err != nil { - return err - } - } - entries[name] = dir - return nil -} - -func (ts *TargetState) addFile(targetName string, entries map[string]Entry, parentDirSourceName string, info os.FileInfo, perm os.FileMode, encrypted, template bool, contents []byte, mutator Mutator) error { - name := filepath.Base(targetName) - var existingFile *File - var existingContents []byte - if entry, ok := entries[name]; ok { - existingFile, ok = entry.(*File) - if !ok { - return fmt.Errorf("%s: already added and not a regular file", targetName) - } - var err error - existingContents, err = existingFile.Contents() - if err != nil { - return err - } - } - - empty := info.Size() == 0 - sourceName := FileAttributes{ - Name: name, - Mode: perm, - Empty: empty, - Encrypted: encrypted, - Template: template, - }.SourceName() - if parentDirSourceName != "" { - sourceName = filepath.Join(parentDirSourceName, sourceName) - } - file := &File{ - sourceName: sourceName, - targetName: targetName, - Empty: empty, - Encrypted: encrypted, - Perm: perm, - Template: template, - contents: contents, - } - if existingFile != nil { - if bytes.Equal(existingFile.contents, file.contents) { - if existingFile.sourceName == file.sourceName { - return nil - } - return mutator.Rename(filepath.Join(ts.SourceDir, existingFile.sourceName), filepath.Join(ts.SourceDir, file.sourceName)) - } - if err := mutator.RemoveAll(filepath.Join(ts.SourceDir, existingFile.sourceName)); err != nil { - return err - } - } - entries[name] = file - return mutator.WriteFile(filepath.Join(ts.SourceDir, sourceName), contents, 0o666&^ts.Umask, existingContents) -} - -func (ts *TargetState) addPatterns(fs vfs.FS, ps *PatternSet, path, relPath string) error { - data, err := ts.executeTemplate(fs, path) - if err != nil { - return err - } - dir := filepath.Dir(relPath) - s := bufio.NewScanner(bytes.NewReader(data)) - for s.Scan() { - text := s.Text() - if index := strings.IndexRune(text, '#'); index != -1 { - text = text[:index] - } - text = strings.TrimSpace(text) - if text == "" { - continue - } - include := true - if strings.HasPrefix(text, "!") { - include = false - text = strings.TrimPrefix(text, "!") - } - pattern := filepath.Join(dir, text) - if err := ps.Add(pattern, include); err != nil { - return fmt.Errorf("%s: %w", path, err) - } - } - if err := s.Err(); err != nil { - return fmt.Errorf("%s: %w", path, err) - } - return nil -} - -func (ts *TargetState) addSymlink(targetName string, entries map[string]Entry, parentDirSourceName, linkname string, mutator Mutator) error { - name := filepath.Base(targetName) - var existingSymlink *Symlink - var existingLinkname string - if entry, ok := entries[name]; ok { - existingSymlink, ok = entry.(*Symlink) - if !ok { - return fmt.Errorf("%s: already added and not a symlink", targetName) - } - var err error - existingLinkname, err = existingSymlink.Linkname() - if err != nil { - return err - } - } - sourceName := FileAttributes{ - Name: name, - Mode: os.ModeSymlink, - }.SourceName() - if parentDirSourceName != "" { - sourceName = filepath.Join(parentDirSourceName, sourceName) - } - symlink := &Symlink{ - sourceName: sourceName, - targetName: targetName, - linkname: linkname, - } - if existingSymlink != nil { - if existingSymlink.linkname == symlink.linkname { - if existingSymlink.sourceName == symlink.sourceName { - return nil - } - return mutator.Rename(filepath.Join(ts.SourceDir, existingSymlink.sourceName), filepath.Join(ts.SourceDir, symlink.sourceName)) - } - if err := mutator.RemoveAll(filepath.Join(ts.SourceDir, existingSymlink.sourceName)); err != nil { - return err - } - } - entries[name] = symlink - return mutator.WriteFile(filepath.Join(ts.SourceDir, symlink.sourceName), []byte(symlink.linkname), 0o666&^ts.Umask, []byte(existingLinkname)) -} - -func (ts *TargetState) addTemplatesDir(fs vfs.FS, path string) error { - prefix := filepath.ToSlash(path) + "/" - return vfs.Walk(fs, path, func(path string, info os.FileInfo, err error) error { - if err != nil { - return err - } - switch { - case info.Mode().IsRegular(): - contents, err := fs.ReadFile(path) - if err != nil { - return err - } - name := strings.TrimPrefix(filepath.ToSlash(path), prefix) - tmpl, err := template.New(name).Option(ts.TemplateOptions...).Funcs(ts.TemplateFuncs).Parse(string(contents)) - if err != nil { - return err - } - if ts.Templates == nil { - ts.Templates = make(map[string]*template.Template) - } - ts.Templates[name] = tmpl - return nil - case info.IsDir(): - return nil - default: - return fmt.Errorf("unsupported file in %s: %s", templatesDirName, path) - } - }) -} - -func (ts *TargetState) executeTemplate(fs vfs.FS, path string) ([]byte, error) { - data, err := fs.ReadFile(path) - if err != nil { - return nil, err - } - return ts.ExecuteTemplateData(path, data) -} - -func (ts *TargetState) findEntries(dirNames []string) (map[string]Entry, error) { - entries := ts.Entries - for i, dirName := range dirNames { - if entry, ok := entries[dirName]; !ok { - return nil, os.ErrNotExist - } else if dir, ok := entry.(*Dir); ok { - entries = dir.Entries - } else { - return nil, fmt.Errorf("%s: not a directory", filepath.Join(dirNames[:i+1]...)) - } - } - return entries, nil -} - -func (ts *TargetState) findEntry(name string) (Entry, error) { - names := splitPathList(name) - entries, err := ts.findEntries(names[:len(names)-1]) - if err != nil { - return nil, err - } - entry, ok := entries[names[len(names)-1]] - if !ok { - return nil, os.ErrNotExist - } - return entry, nil -} - -func (ts *TargetState) importHeader(r io.Reader, importTAROptions ImportTAROptions, header *tar.Header, mutator Mutator) error { - targetPath := header.Name - if importTAROptions.StripComponents > 0 { - targetPath = filepath.Join(strings.Split(targetPath, string(os.PathSeparator))[importTAROptions.StripComponents:]...) - } - if importTAROptions.DestinationDir != "" { - //nolint:gosec - targetPath = filepath.Join(importTAROptions.DestinationDir, targetPath) - } else { - //nolint:gosec - targetPath = filepath.Join(ts.DestDir, targetPath) - } - targetName, err := filepath.Rel(ts.DestDir, targetPath) - if err != nil { - return err - } - parentDirSourceName := "" - entries := ts.Entries - if parentDirName := filepath.Dir(targetName); parentDirName != "." { - parentEntry, err := ts.findEntry(parentDirName) - if err != nil { - return err - } - parentDir, ok := parentEntry.(*Dir) - if !ok { - return fmt.Errorf("%s: parent is not a directory", targetName) - } - parentDirSourceName = parentDir.sourceName - entries = parentDir.Entries - } - switch header.Typeflag { - case tar.TypeDir: - perm := os.FileMode(header.Mode).Perm() - createKeepFile := false // FIXME don't assume that we don't need a keep file - return ts.addDir(targetName, entries, parentDirSourceName, importTAROptions.Exact, perm, createKeepFile, mutator) - case tar.TypeReg: - info := header.FileInfo() - contents, err := ioutil.ReadAll(r) - if err != nil { - return err - } - return ts.addFile(targetName, entries, parentDirSourceName, info, info.Mode().Perm(), false, false, contents, mutator) - case tar.TypeSymlink: - linkname := header.Linkname - return ts.addSymlink(targetName, entries, parentDirSourceName, linkname, mutator) - default: - return fmt.Errorf("%s: unspported typeflag '%c'", header.Name, header.Typeflag) - } -} diff --git a/internal/chezmoi/targetstate_posix.go b/internal/chezmoi/targetstate_posix.go deleted file mode 100644 index ad21bdfa463..00000000000 --- a/internal/chezmoi/targetstate_posix.go +++ /dev/null @@ -1,42 +0,0 @@ -// +build !windows - -package chezmoi - -import ( - "archive/tar" - "os/user" - "strconv" - "time" -) - -func (ts *TargetState) getTarHeaderTemplate() (*tar.Header, error) { - currentUser, err := user.Current() - if err != nil { - return nil, err - } - - now := time.Now() - - uid, err := strconv.Atoi(currentUser.Uid) - if err != nil { - return nil, err - } - gid, err := strconv.Atoi(currentUser.Gid) - if err != nil { - return nil, err - } - group, err := user.LookupGroupId(currentUser.Gid) - if err != nil { - return nil, err - } - - return &tar.Header{ - Uid: uid, - Gid: gid, - Uname: currentUser.Username, - Gname: group.Name, - ModTime: now, - AccessTime: now, - ChangeTime: now, - }, nil -} diff --git a/internal/chezmoi/targetstate_test.go b/internal/chezmoi/targetstate_test.go deleted file mode 100644 index a5d45daca8e..00000000000 --- a/internal/chezmoi/targetstate_test.go +++ /dev/null @@ -1,490 +0,0 @@ -package chezmoi - -import ( - "os" - "path/filepath" - "testing" - "text/template" - - "github.com/coreos/go-semver/semver" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "github.com/twpayne/go-vfs/vfst" -) - -func TestEndToEnd(t *testing.T) { - for _, tc := range []struct { - name string - root interface{} - sourceDir string - follow bool - data map[string]interface{} - templateFuncs template.FuncMap - destDir string - umask os.FileMode - tests interface{} - }{ - { - name: "all", - root: map[string]interface{}{ - "/home/user": map[string]interface{}{ - ".bashrc": "foo", - "dir": map[string]interface{}{ - "foo": "foo", - "bar": "bar", - "qux": "qux", - }, - "replace_symlink": &vfst.Symlink{Target: "foo"}, - }, - "/home/user/.local/share/chezmoi": map[string]interface{}{ - ".git/HEAD": "HEAD", - ".chezmoiignore": "{{ .ignore }} # comment\n", - "README.md": "contents of README.md\n", - "dot_bashrc": "bar", - "dot_hgrc.tmpl": "[ui]\nusername = {{ .name }} <{{ .email }}>\n", - "empty.tmpl": "{{ if false }}foo{{ end }}", - "empty_foo": "", - "exact_dir/foo": "foo", - "exact_dir/.chezmoiignore": "qux\n", - "whitespace": " ", - "symlink_bar": "empty", - "symlink_replace_symlink": "bar", - }, - }, - sourceDir: "/home/user/.local/share/chezmoi", - data: map[string]interface{}{ - "name": "John Smith", - "email": "[email protected]", - "ignore": "README.md", - }, - destDir: "/home/user", - umask: 0o22, - tests: []vfst.Test{ - vfst.TestPath("/home/user/.bashrc", - vfst.TestModeIsRegular, - vfst.TestContentsString("bar"), - ), - vfst.TestPath("/home/user/.hgrc", - vfst.TestModeIsRegular, - vfst.TestContentsString("[ui]\nusername = John Smith <[email protected]>\n"), - ), - vfst.TestPath("/home/user/foo", - vfst.TestModeIsRegular, - vfst.TestContents(nil), - ), - vfst.TestPath("/home/user/bar", - vfst.TestModeType(os.ModeSymlink), - vfst.TestSymlinkTarget("empty"), - ), - vfst.TestPath("/home/user/whitespace", - vfst.TestDoesNotExist), - vfst.TestPath("/home/user/replace_symlink", - vfst.TestModeType(os.ModeSymlink), - vfst.TestSymlinkTarget("bar"), - ), - vfst.TestPath("/home/user/dir/bar", - vfst.TestDoesNotExist, - ), - vfst.TestPath("/home/user/dir/qux", - vfst.TestModeIsRegular, - vfst.TestContentsString("qux"), - ), - vfst.TestPath("/home/user/README.md", - vfst.TestDoesNotExist, - ), - }, - }, - } { - t.Run(tc.name, func(t *testing.T) { - fs, cleanup, err := vfst.NewTestFS(tc.root) - require.NoError(t, err) - defer cleanup() - ts := NewTargetState( - WithDestDir(tc.destDir), - WithSourceDir(tc.sourceDir), - WithTemplateData(tc.data), - WithTemplateFuncs(tc.templateFuncs), - WithUmask(tc.umask), - ) - assert.NoError(t, ts.Populate(fs, nil)) - applyOptions := &ApplyOptions{ - DestDir: ts.DestDir, - Ignore: ts.TargetIgnore.Match, - ScriptStateBucket: []byte("script"), - Stdout: os.Stdout, - Umask: 0o22, - } - assert.NoError(t, ts.Apply(fs, NewVerboseMutator(os.Stderr, NewFSMutator(fs), false, 0), tc.follow, applyOptions)) - vfst.RunTests(t, fs, "", tc.tests) - }) - } -} - -func TestTargetStatePopulate(t *testing.T) { - for _, tc := range []struct { - name string - root interface{} - sourceDir string - data map[string]interface{} - templateFuncs template.FuncMap - want *TargetState - }{ - { - name: "simple_file", - root: map[string]interface{}{ - "/foo": "bar", - }, - sourceDir: "/", - want: NewTargetState( - WithDestDir("/"), - WithSourceDir("/"), - WithEntries(map[string]Entry{ - "foo": &File{ - sourceName: "foo", - targetName: "foo", - Perm: 0o666, - contents: []byte("bar"), - }, - }), - ), - }, - { - name: "dot_file", - root: map[string]interface{}{ - "/dot_foo": "bar", - }, - sourceDir: "/", - want: NewTargetState( - WithDestDir("/"), - WithEntries(map[string]Entry{ - ".foo": &File{ - sourceName: "dot_foo", - targetName: ".foo", - Perm: 0o666, - contents: []byte("bar"), - }, - }), - WithSourceDir("/"), - ), - }, - { - name: "private_file", - root: map[string]interface{}{ - "/private_foo": "bar", - }, - sourceDir: "/", - want: NewTargetState( - WithDestDir("/"), - WithEntries(map[string]Entry{ - "foo": &File{ - sourceName: "private_foo", - targetName: "foo", - Perm: 0o600, - contents: []byte("bar"), - }, - }), - WithSourceDir("/"), - ), - }, - { - name: "file_in_subdir", - root: map[string]interface{}{ - "/foo/bar": "baz", - }, - sourceDir: "/", - want: NewTargetState( - WithDestDir("/"), - WithEntries(map[string]Entry{ - "foo": &Dir{ - sourceName: "foo", - targetName: "foo", - Exact: false, - Perm: 0o777, - Entries: map[string]Entry{ - "bar": &File{ - sourceName: filepath.Join("foo", "bar"), - targetName: filepath.Join("foo", "bar"), - Perm: 0o666, - contents: []byte("baz"), - }, - }, - }, - }), - WithSourceDir("/"), - ), - }, - { - name: "file_in_private_dot_subdir", - root: map[string]interface{}{ - "/private_dot_foo/bar": "baz", - }, - sourceDir: "/", - want: NewTargetState( - WithDestDir("/"), - WithEntries(map[string]Entry{ - ".foo": &Dir{ - sourceName: "private_dot_foo", - targetName: ".foo", - Exact: false, - Perm: 0o700, - Entries: map[string]Entry{ - "bar": &File{ - sourceName: filepath.Join("private_dot_foo", "bar"), - targetName: filepath.Join(".foo", "bar"), - Perm: 0o666, - contents: []byte("baz"), - }, - }, - }, - }), - WithSourceDir("/"), - ), - }, - { - name: "template_dot_file", - root: map[string]interface{}{ - "/dot_gitconfig.tmpl": "[user]\n\temail = {{.Email}}\n", - }, - sourceDir: "/", - data: map[string]interface{}{ - "Email": "[email protected]", - }, - want: NewTargetState( - WithDestDir("/"), - WithEntries(map[string]Entry{ - ".gitconfig": &File{ - sourceName: "dot_gitconfig.tmpl", - targetName: ".gitconfig", - Perm: 0o666, - Template: true, - contents: []byte("[user]\n\temail = [email protected]\n"), - }, - }), - WithSourceDir("/"), - WithTemplateData(map[string]interface{}{ - "Email": "[email protected]", - }), - ), - }, - { - name: "file_in_exact_dir", - root: map[string]interface{}{ - "/exact_dir/foo": "bar", - }, - sourceDir: "/", - want: NewTargetState( - WithDestDir("/"), - WithEntries(map[string]Entry{ - "dir": &Dir{ - sourceName: "exact_dir", - targetName: "dir", - Exact: true, - Perm: 0o777, - Entries: map[string]Entry{ - "foo": &File{ - sourceName: filepath.Join("exact_dir", "foo"), - targetName: filepath.Join("dir", "foo"), - Perm: 0o666, - contents: []byte("bar"), - }, - }, - }, - }), - WithSourceDir("/"), - ), - }, - { - name: "symlink", - root: map[string]interface{}{ - "/symlink_foo": "bar", - }, - sourceDir: "/", - want: NewTargetState( - WithDestDir("/"), - WithEntries(map[string]Entry{ - "foo": &Symlink{ - sourceName: "symlink_foo", - targetName: "foo", - linkname: "bar", - }, - }), - WithSourceDir("/"), - ), - }, - { - name: "symlink_dot_foo", - root: map[string]interface{}{ - "/symlink_dot_foo": "bar", - }, - sourceDir: "/", - want: NewTargetState( - WithDestDir("/"), - WithEntries(map[string]Entry{ - ".foo": &Symlink{ - sourceName: "symlink_dot_foo", - targetName: ".foo", - linkname: "bar", - }, - }), - WithSourceDir("/"), - ), - }, - { - name: "symlink_template", - root: map[string]interface{}{ - "/symlink_foo.tmpl": "bar-{{ .host }}", - }, - sourceDir: "/", - data: map[string]interface{}{ - "host": "example.com", - }, - want: NewTargetState( - WithDestDir("/"), - WithEntries(map[string]Entry{ - "foo": &Symlink{ - sourceName: "symlink_foo.tmpl", - targetName: "foo", - Template: true, - linkname: "bar-example.com", - }, - }), - WithSourceDir("/"), - WithTemplateData(map[string]interface{}{ - "host": "example.com", - }), - ), - }, - { - name: "ignore_pattern", - root: map[string]interface{}{ - "/.chezmoiignore": "" + - "f*\n" + - "!g\n", - }, - sourceDir: "/", - want: NewTargetState( - WithDestDir("/"), - WithSourceDir("/"), - WithTargetIgnore(&PatternSet{ - includes: map[string]struct{}{ - "f*": {}, - }, - excludes: map[string]struct{}{ - "g": {}, - }, - }), - ), - }, - { - name: "remove_pattern", - root: map[string]interface{}{ - "/.chezmoiremove": "" + - "f*\n" + - "!g\n", - }, - sourceDir: "/", - want: NewTargetState( - WithDestDir("/"), - WithSourceDir("/"), - WithTargetRemove(&PatternSet{ - includes: map[string]struct{}{ - "f*": {}, - }, - excludes: map[string]struct{}{ - "g": {}, - }, - }), - ), - }, - { - name: "ignore_subdir", - root: map[string]interface{}{ - "/dir/.chezmoiignore": "" + - "foo\n" + - "!bar\n", - }, - sourceDir: "/", - want: NewTargetState( - WithDestDir("/"), - WithEntries(map[string]Entry{ - "dir": &Dir{ - sourceName: "dir", - targetName: "dir", - Perm: 0o777, - Entries: map[string]Entry{}, - }, - }), - WithSourceDir("/"), - WithTargetIgnore(&PatternSet{ - includes: map[string]struct{}{ - filepath.Join("dir", "foo"): {}, - }, - excludes: map[string]struct{}{ - filepath.Join("dir", "bar"): {}, - }, - }), - ), - }, - { - name: "min_version", - root: map[string]interface{}{ - "/.chezmoiversion": "1.2.3\n", - "/foo": "bar", - }, - sourceDir: "/", - want: NewTargetState( - WithDestDir("/"), - WithEntries(map[string]Entry{ - "foo": &File{ - sourceName: "foo", - targetName: "foo", - Perm: 0o666, - contents: []byte("bar"), - }, - }), - WithMinVersion(semver.Must(semver.NewVersion("1.2.3"))), - WithSourceDir("/"), - ), - }, - { - name: "empty_template_dir", - root: map[string]interface{}{ - "/.chezmoitemplates": &vfst.Dir{Perm: 0o755}, - }, - sourceDir: "/", - want: NewTargetState( - WithDestDir("/"), - WithSourceDir("/"), - ), - }, - { - name: "template_dir", - root: map[string]interface{}{ - "/.chezmoitemplates/foo": "bar", - }, - sourceDir: "/", - want: NewTargetState( - WithDestDir("/"), - WithSourceDir("/"), - WithTemplates(map[string]*template.Template{ - "foo": template.Must(template.New("foo").Option("missingkey=error").Parse("bar")), - }), - ), - }, - } { - t.Run(tc.name, func(t *testing.T) { - fs, cleanup, err := vfst.NewTestFS(tc.root) - require.NoError(t, err) - defer cleanup() - ts := NewTargetState( - WithDestDir("/"), - WithSourceDir(tc.sourceDir), - WithTemplateData(tc.data), - WithTemplateFuncs(tc.templateFuncs), - ) - assert.NoError(t, ts.Populate(fs, nil)) - assert.NoError(t, ts.Evaluate()) - assert.Equal(t, tc.want, ts) - }) - } -} diff --git a/internal/chezmoi/targetstate_windows.go b/internal/chezmoi/targetstate_windows.go deleted file mode 100644 index e34e7a8bba7..00000000000 --- a/internal/chezmoi/targetstate_windows.go +++ /dev/null @@ -1,25 +0,0 @@ -// +build windows - -package chezmoi - -import ( - "archive/tar" - "os/user" - "time" -) - -func (ts *TargetState) getTarHeaderTemplate() (*tar.Header, error) { - currentUser, err := user.Current() - if err != nil { - return nil, err - } - - now := time.Now() - - return &tar.Header{ - Uname: currentUser.Username, - ModTime: now, - AccessTime: now, - ChangeTime: now, - }, nil -} diff --git a/chezmoi2/internal/chezmoi/targetstateentry.go b/internal/chezmoi/targetstateentry.go similarity index 100% rename from chezmoi2/internal/chezmoi/targetstateentry.go rename to internal/chezmoi/targetstateentry.go diff --git a/chezmoi2/internal/chezmoi/targetstateentry_test.go b/internal/chezmoi/targetstateentry_test.go similarity index 96% rename from chezmoi2/internal/chezmoi/targetstateentry_test.go rename to internal/chezmoi/targetstateentry_test.go index 8df3856dab5..815a41c7828 100644 --- a/chezmoi2/internal/chezmoi/targetstateentry_test.go +++ b/internal/chezmoi/targetstateentry_test.go @@ -8,10 +8,10 @@ import ( "github.com/muesli/combinator" "github.com/stretchr/testify/require" - vfs "github.com/twpayne/go-vfs" - "github.com/twpayne/go-vfs/vfst" + vfs "github.com/twpayne/go-vfs/v2" + "github.com/twpayne/go-vfs/v2/vfst" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoitest" + "github.com/twpayne/chezmoi/internal/chezmoitest" ) func TestTargetStateEntryApplyAndEqual(t *testing.T) { diff --git a/chezmoi2/internal/chezmoi/tarreadersystem.go b/internal/chezmoi/tarreadersystem.go similarity index 91% rename from chezmoi2/internal/chezmoi/tarreadersystem.go rename to internal/chezmoi/tarreadersystem.go index 6062de5dcb0..b208ebdac32 100644 --- a/chezmoi2/internal/chezmoi/tarreadersystem.go +++ b/internal/chezmoi/tarreadersystem.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "os" "strings" ) @@ -57,7 +56,7 @@ FOR: s.fileInfos[nameAbsPath] = header.FileInfo() case tar.TypeReg: s.fileInfos[nameAbsPath] = header.FileInfo() - contents, err := ioutil.ReadAll(tarReader) + contents, err := io.ReadAll(tarReader) if err != nil { return nil, err } @@ -88,11 +87,11 @@ func (s *TARReaderSystem) Lstat(filename AbsPath) (os.FileInfo, error) { } // ReadFile implements System.ReadFile. -func (s *TARReaderSystem) ReadFile(filename AbsPath) ([]byte, error) { - if contents, ok := s.contents[filename]; ok { +func (s *TARReaderSystem) ReadFile(name AbsPath) ([]byte, error) { + if contents, ok := s.contents[name]; ok { return contents, nil } - if _, ok := s.fileInfos[filename]; ok { + if _, ok := s.fileInfos[name]; ok { return nil, os.ErrInvalid } return nil, os.ErrNotExist diff --git a/chezmoi2/internal/chezmoi/tarreadersystem_test.go b/internal/chezmoi/tarreadersystem_test.go similarity index 100% rename from chezmoi2/internal/chezmoi/tarreadersystem_test.go rename to internal/chezmoi/tarreadersystem_test.go diff --git a/chezmoi2/internal/chezmoi/tarwritersystem.go b/internal/chezmoi/tarwritersystem.go similarity index 100% rename from chezmoi2/internal/chezmoi/tarwritersystem.go rename to internal/chezmoi/tarwritersystem.go diff --git a/chezmoi2/internal/chezmoi/tarwritersystem_test.go b/internal/chezmoi/tarwritersystem_test.go similarity index 92% rename from chezmoi2/internal/chezmoi/tarwritersystem_test.go rename to internal/chezmoi/tarwritersystem_test.go index 6a5305424ff..c8fe71f8f6d 100644 --- a/chezmoi2/internal/chezmoi/tarwritersystem_test.go +++ b/internal/chezmoi/tarwritersystem_test.go @@ -4,14 +4,13 @@ import ( "archive/tar" "bytes" "io" - "io/ioutil" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - vfs "github.com/twpayne/go-vfs" + vfs "github.com/twpayne/go-vfs/v2" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoitest" + "github.com/twpayne/chezmoi/internal/chezmoitest" ) var _ System = &TARWriterSystem{} @@ -44,7 +43,9 @@ func TestTARWriterSystem(t *testing.T) { b := &bytes.Buffer{} tarWriterSystem := NewTARWriterSystem(b, tar.Header{}) persistentState := NewMockPersistentState() - require.NoError(t, s.applyAll(tarWriterSystem, system, persistentState, "", ApplyOptions{})) + require.NoError(t, s.applyAll(tarWriterSystem, system, persistentState, "", ApplyOptions{ + Include: NewEntryTypeSet(EntryTypesAll), + })) require.NoError(t, tarWriterSystem.Close()) r := tar.NewReader(b) @@ -87,7 +88,7 @@ func TestTARWriterSystem(t *testing.T) { assert.Equal(t, tc.expectedLinkname, header.Linkname) assert.Equal(t, int64(len(tc.expectedContents)), header.Size) if tc.expectedContents != nil { - actualContents, err := ioutil.ReadAll(r) + actualContents, err := io.ReadAll(r) require.NoError(t, err) assert.Equal(t, tc.expectedContents, actualContents) } diff --git a/internal/chezmoi/verbosemutator.go b/internal/chezmoi/verbosemutator.go deleted file mode 100644 index 06679563974..00000000000 --- a/internal/chezmoi/verbosemutator.go +++ /dev/null @@ -1,162 +0,0 @@ -package chezmoi - -import ( - "fmt" - "io" - "net/http" - "os" - "os/exec" - "path/filepath" - "strings" - - "github.com/pkg/diff" - "github.com/pkg/diff/write" -) - -// A VerboseMutator wraps an Mutator and logs all of the actions it executes and -// any errors as pseudo shell commands. -type VerboseMutator struct { - m Mutator - w io.Writer - colored bool - maxDiffDataSize int -} - -// NewVerboseMutator returns a new VerboseMutator. -func NewVerboseMutator(w io.Writer, m Mutator, colored bool, maxDiffDataSize int) *VerboseMutator { - return &VerboseMutator{ - m: m, - w: w, - colored: colored, - maxDiffDataSize: maxDiffDataSize, - } -} - -// Chmod implements Mutator.Chmod. -func (m *VerboseMutator) Chmod(name string, mode os.FileMode) error { - action := fmt.Sprintf("chmod %o %s", mode, MaybeShellQuote(name)) - err := m.m.Chmod(name, mode) - if err == nil { - _, _ = fmt.Fprintln(m.w, action) - } else { - _, _ = fmt.Fprintf(m.w, "%s: %v\n", action, err) - } - return err -} - -// IdempotentCmdOutput implements Mutator.IdempotentCmdOutput. -func (m *VerboseMutator) IdempotentCmdOutput(cmd *exec.Cmd) ([]byte, error) { - action := cmdString(cmd) - output, err := m.m.IdempotentCmdOutput(cmd) - if err != nil { - _, _ = fmt.Fprintf(m.w, "%s: %v\n", action, err) - } - return output, err -} - -// Mkdir implements Mutator.Mkdir. -func (m *VerboseMutator) Mkdir(name string, perm os.FileMode) error { - action := fmt.Sprintf("mkdir -m %o %s", perm, MaybeShellQuote(name)) - err := m.m.Mkdir(name, perm) - if err == nil { - _, _ = fmt.Fprintln(m.w, action) - } else { - _, _ = fmt.Fprintf(m.w, "%s: %v\n", action, err) - } - return err -} - -// RemoveAll implements Mutator.RemoveAll. -func (m *VerboseMutator) RemoveAll(name string) error { - action := fmt.Sprintf("rm -rf %s", MaybeShellQuote(name)) - err := m.m.RemoveAll(name) - if err == nil { - _, _ = fmt.Fprintln(m.w, action) - } else { - _, _ = fmt.Fprintf(m.w, "%s: %v\n", action, err) - } - return err -} - -// Rename implements Mutator.Rename. -func (m *VerboseMutator) Rename(oldpath, newpath string) error { - action := fmt.Sprintf("mv %s %s", MaybeShellQuote(oldpath), MaybeShellQuote(newpath)) - err := m.m.Rename(oldpath, newpath) - if err == nil { - _, _ = fmt.Fprintln(m.w, action) - } else { - _, _ = fmt.Fprintf(m.w, "%s: %v\n", action, err) - } - return err -} - -// RunCmd implements Mutator.RunCmd. -func (m *VerboseMutator) RunCmd(cmd *exec.Cmd) error { - action := cmdString(cmd) - err := m.m.RunCmd(cmd) - if err == nil { - _, _ = fmt.Fprintln(m.w, action) - } else { - _, _ = fmt.Fprintf(m.w, "%s: %v\n", action, err) - } - return err -} - -// Stat implements Mutator.Stat. -func (m *VerboseMutator) Stat(name string) (os.FileInfo, error) { - return m.m.Stat(name) -} - -// WriteFile implements Mutator.WriteFile. -func (m *VerboseMutator) WriteFile(name string, data []byte, perm os.FileMode, currData []byte) error { - action := fmt.Sprintf("install -m %o /dev/null %s", perm, MaybeShellQuote(name)) - err := m.m.WriteFile(name, data, perm, currData) - if err == nil { - _, _ = fmt.Fprintln(m.w, action) - // Don't print diffs if either file is binary. - if isBinary(currData) || isBinary(data) { - return nil - } - // Don't print diffs if either file is too large. - if m.maxDiffDataSize != 0 { - if len(currData) > m.maxDiffDataSize || len(data) > m.maxDiffDataSize { - return nil - } - } - var opts []write.Option - if m.colored { - opts = append(opts, write.TerminalColor()) - } - if err := diff.Text(filepath.Join("a", name), filepath.Join("b", name), string(currData), string(data), m.w, opts...); err != nil { - return err - } - } else { - _, _ = fmt.Fprintf(m.w, "%s: %v\n", action, err) - } - return err -} - -// WriteSymlink implements Mutator.WriteSymlink. -func (m *VerboseMutator) WriteSymlink(oldname, newname string) error { - action := fmt.Sprintf("ln -sf %s %s", MaybeShellQuote(oldname), MaybeShellQuote(newname)) - err := m.m.WriteSymlink(oldname, newname) - if err == nil { - _, _ = fmt.Fprintln(m.w, action) - } else { - _, _ = fmt.Fprintf(m.w, "%s: %v\n", action, err) - } - return err -} - -// cmdString returns a string representation of cmd. -func cmdString(cmd *exec.Cmd) string { - s := ShellQuoteArgs(append([]string{cmd.Path}, cmd.Args[1:]...)) - if cmd.Dir == "" { - return s - } - return fmt.Sprintf("( cd %s && %s )", MaybeShellQuote(cmd.Dir), s) -} - -func isBinary(data []byte) bool { - return len(data) != 0 && !strings.HasPrefix(http.DetectContentType(data), "text/") -} diff --git a/chezmoi2/internal/chezmoi/zipwritersystem.go b/internal/chezmoi/zipwritersystem.go similarity index 100% rename from chezmoi2/internal/chezmoi/zipwritersystem.go rename to internal/chezmoi/zipwritersystem.go diff --git a/chezmoi2/internal/chezmoi/zipwritersystem_test.go b/internal/chezmoi/zipwritersystem_test.go similarity index 91% rename from chezmoi2/internal/chezmoi/zipwritersystem_test.go rename to internal/chezmoi/zipwritersystem_test.go index f8d1ed56991..b80bea28f36 100644 --- a/chezmoi2/internal/chezmoi/zipwritersystem_test.go +++ b/internal/chezmoi/zipwritersystem_test.go @@ -3,16 +3,16 @@ package chezmoi import ( "archive/zip" "bytes" - "io/ioutil" + "io" "os" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - vfs "github.com/twpayne/go-vfs" + vfs "github.com/twpayne/go-vfs/v2" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoitest" + "github.com/twpayne/chezmoi/internal/chezmoitest" ) var _ System = &ZIPWriterSystem{} @@ -45,7 +45,9 @@ func TestZIPWriterSystem(t *testing.T) { b := &bytes.Buffer{} zipWriterSystem := NewZIPWriterSystem(b, time.Now().UTC()) persistentState := NewMockPersistentState() - require.NoError(t, s.applyAll(zipWriterSystem, system, persistentState, "", ApplyOptions{})) + require.NoError(t, s.applyAll(zipWriterSystem, system, persistentState, "", ApplyOptions{ + Include: NewEntryTypeSet(EntryTypesAll), + })) require.NoError(t, zipWriterSystem.Close()) r, err := zip.NewReader(bytes.NewReader(b.Bytes()), int64(b.Len())) @@ -88,7 +90,7 @@ func TestZIPWriterSystem(t *testing.T) { if expectedFile.contents != nil { rc, err := actualFile.Open() require.NoError(t, err) - actualContents, err := ioutil.ReadAll(rc) + actualContents, err := io.ReadAll(rc) require.NoError(t, err) assert.Equal(t, expectedFile.contents, actualContents) } diff --git a/chezmoi2/internal/chezmoilog/chezmoilog.go b/internal/chezmoilog/chezmoilog.go similarity index 98% rename from chezmoi2/internal/chezmoilog/chezmoilog.go rename to internal/chezmoilog/chezmoilog.go index a0077266083..306c9777a62 100644 --- a/chezmoi2/internal/chezmoilog/chezmoilog.go +++ b/internal/chezmoilog/chezmoilog.go @@ -1,3 +1,4 @@ +// Package chezmoilog contains support for chezmoi logging. package chezmoilog import ( diff --git a/chezmoi2/internal/chezmoitest/chezmoitest.go b/internal/chezmoitest/chezmoitest.go similarity index 88% rename from chezmoi2/internal/chezmoitest/chezmoitest.go rename to internal/chezmoitest/chezmoitest.go index ff7ed9a4f71..db545f4bd4e 100644 --- a/chezmoi2/internal/chezmoitest/chezmoitest.go +++ b/internal/chezmoitest/chezmoitest.go @@ -1,8 +1,8 @@ +// Package chezmoitest contains test helper functions for chezmoi. package chezmoitest import ( "fmt" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -13,10 +13,10 @@ import ( "github.com/rs/zerolog/log" "github.com/stretchr/testify/require" - "github.com/twpayne/go-vfs" - "github.com/twpayne/go-vfs/vfst" + "github.com/twpayne/go-vfs/v2" + "github.com/twpayne/go-vfs/v2/vfst" - "github.com/twpayne/chezmoi/chezmoi2/internal/chezmoilog" + "github.com/twpayne/chezmoi/internal/chezmoilog" ) var ( @@ -31,7 +31,7 @@ var ( func AGEGenerateKey(filename string) (publicKey, privateKeyFile string, err error) { if filename == "" { var tempDir string - tempDir, err = ioutil.TempDir("", "chezmoi-test-age-key") + tempDir, err = os.MkdirTemp("", "chezmoi-test-age-key") if err != nil { return "", "", err } @@ -93,6 +93,11 @@ func GPGGenerateKey(command, homeDir string) (key, passphrase string, err error) return string(submatch[1]), passphrase, nil } +// GitHubActionsOnMacOS returns if running in GitHub Actions on macOS. +func GitHubActionsOnMacOS() bool { + return runtime.GOOS == "darwin" && os.Getenv("GITHUB_ACTIONS") == "true" +} + // GitHubActionsOnWindows returns if running in GitHub Actions on Windows. func GitHubActionsOnWindows() bool { return runtime.GOOS == "windows" && os.Getenv("GITHUB_ACTIONS") == "true" diff --git a/chezmoi2/internal/chezmoitest/chezmoitest_unix.go b/internal/chezmoitest/chezmoitest_unix.go similarity index 100% rename from chezmoi2/internal/chezmoitest/chezmoitest_unix.go rename to internal/chezmoitest/chezmoitest_unix.go diff --git a/chezmoi2/internal/chezmoitest/chezmoitest_windows.go b/internal/chezmoitest/chezmoitest_windows.go similarity index 100% rename from chezmoi2/internal/chezmoitest/chezmoitest_windows.go rename to internal/chezmoitest/chezmoitest_windows.go diff --git a/internal/cmd/generate-assets/main.go b/internal/cmd/generate-assets/main.go deleted file mode 100644 index 1fcc50fa6fa..00000000000 --- a/internal/cmd/generate-assets/main.go +++ /dev/null @@ -1,83 +0,0 @@ -package main - -import ( - "bytes" - "flag" - "fmt" - "go/format" - "io/ioutil" - "os" - "strings" - "text/template" -) - -var ( - outputTemplate = template.Must(template.New("output").Funcs(template.FuncMap{ - "printMultiLineString": printMultiLineString, - }).Parse(`// Code generated by github.com/twpayne/chezmoi/internal/cmd/generate-assets. DO NOT EDIT. -{{- if .Tags}} -// +build {{ .Tags }} -{{- end }} - -package cmd - -func init() { -{{- range $key, $value := .Assets }} - assets[{{ printf "%q" $key }}] = []byte("" + - {{ printMultiLineString $value }}) -{{- end }} -}`)) - - output = flag.String("o", "/dev/stdout", "output") - trimPrefix = flag.String("trimprefix", "", "trim prefix") - tags = flag.String("tags", "", "tags") -) - -func printMultiLineString(s []byte) string { - sb := &strings.Builder{} - for i, line := range bytes.Split(s, []byte{'\n'}) { - if i != 0 { - sb.WriteString(" +\n") - } - sb.WriteString(fmt.Sprintf("%q", append(line, '\n'))) - } - return sb.String() -} - -func run() error { - flag.Parse() - - assets := make(map[string][]byte) - for _, arg := range flag.Args() { - var err error - assets[strings.TrimPrefix(arg, *trimPrefix)], err = ioutil.ReadFile(arg) - if err != nil { - return err - } - } - - sb := &strings.Builder{} - if err := outputTemplate.Execute(sb, struct { - Tags string - Assets map[string][]byte - }{ - Tags: *tags, - Assets: assets, - }); err != nil { - return err - } - - formattedSource, err := format.Source([]byte(sb.String())) - if err != nil { - return err - } - - return ioutil.WriteFile(*output, formattedSource, 0o666) -} - -func main() { - if err := run(); err != nil { - fmt.Println(err) - os.Exit(1) - } -} diff --git a/internal/cmd/generate-install.sh/main.go b/internal/cmd/generate-install.sh/main.go index be0ed0076f0..bdc97721183 100644 --- a/internal/cmd/generate-install.sh/main.go +++ b/internal/cmd/generate-install.sh/main.go @@ -4,7 +4,6 @@ import ( "encoding/json" "flag" "fmt" - "io/ioutil" "os" "os/exec" "sort" @@ -58,7 +57,7 @@ func run() error { flag.Parse() // Read goreleaser config. - data, err := ioutil.ReadFile(".goreleaser.yaml") + data, err := os.ReadFile(".goreleaser.yaml") if err != nil { return err } @@ -117,15 +116,11 @@ func run() error { if err != nil { return err } - if err := installShTemplate.ExecuteTemplate(os.Stdout, "install.sh.tmpl", struct { + return installShTemplate.ExecuteTemplate(os.Stdout, "install.sh.tmpl", struct { Platforms []platform }{ Platforms: sortedPlatforms, - }); err != nil { - return err - } - - return nil + }) } func main() { diff --git a/internal/cmd/lint-whitespace/main.go b/internal/cmd/lint-whitespace/main.go index 37c9eee1f5f..be0efdfbf33 100644 --- a/internal/cmd/lint-whitespace/main.go +++ b/internal/cmd/lint-whitespace/main.go @@ -3,7 +3,6 @@ package main import ( "bytes" "fmt" - "io/ioutil" "net/http" "os" "path/filepath" @@ -20,7 +19,6 @@ var ( regexp.MustCompile(`\A\.devcontainer/library-scripts\z`), regexp.MustCompile(`\A\.git\z`), regexp.MustCompile(`\Aassets/scripts/install\.ps1\z`), - regexp.MustCompile(`\Achezmoi2/completions/chezmoi2\.ps1\z`), regexp.MustCompile(`\Acompletions/chezmoi\.ps1\z`), regexp.MustCompile(`\Achezmoi\.io/public\z`), regexp.MustCompile(`\Achezmoi\.io/resources\z`), @@ -31,7 +29,7 @@ var ( ) func lintFile(filename string) error { - data, err := ioutil.ReadFile(filename) + data, err := os.ReadFile(filename) if err != nil { return err } diff --git a/internal/git/git.go b/internal/git/git.go new file mode 100644 index 00000000000..09311b6df94 --- /dev/null +++ b/internal/git/git.go @@ -0,0 +1,2 @@ +// Package git contains functions for interacting with git. +package git diff --git a/main.go b/main.go index d40624946f3..482c27a25da 100644 --- a/main.go +++ b/main.go @@ -1,41 +1,25 @@ -//go:generate go run ./internal/cmd/generate-assets -o cmd/docs.gen.go -tags=!noembeddocs docs/CHANGES.md docs/COMPARISON.md docs/CONTRIBUTING.md docs/FAQ.md docs/HOWTO.md docs/INSTALL.md docs/MEDIA.md docs/QUICKSTART.md docs/REFERENCE.md docs/TEMPLATING.md -//go:generate go run ./internal/cmd/generate-assets -o cmd/templates.gen.go assets/templates/COMMIT_MESSAGE.tmpl -//go:generate go run ./internal/cmd/generate-helps -o cmd/helps.gen.go -i docs/REFERENCE.md -//go:generate go run . completion bash -o completions/chezmoi-completion.bash -//go:generate go run . completion fish -o completions/chezmoi.fish -//go:generate go run . completion powershell -o completions/chezmoi.ps1 -//go:generate go run . completion zsh -o completions/chezmoi.zsh - package main import ( - "fmt" "os" "github.com/twpayne/chezmoi/cmd" ) var ( - version = "" - commit = "" - date = "" - builtBy = "" + version string + commit string + date string + builtBy string ) -func run() error { - cmd.VersionStr = version - cmd.Commit = commit - cmd.Date = date - cmd.BuiltBy = builtBy - return cmd.Execute() -} - func main() { - if err := run(); err != nil { - if s := err.Error(); s != "" { - //nolint:forbidigo - fmt.Printf("chezmoi: %s\n", s) - } - os.Exit(1) + if exitCode := cmd.Main(cmd.VersionInfo{ + Version: version, + Commit: commit, + Date: date, + BuiltBy: builtBy, + }, os.Args[1:]); exitCode != 0 { + os.Exit(exitCode) } } diff --git a/main_test.go b/main_test.go index a63d493fd96..5ab61e8fdb4 100644 --- a/main_test.go +++ b/main_test.go @@ -1,39 +1,36 @@ package main import ( + "bufio" + "bytes" "fmt" - "io/ioutil" "os" + "path" "path/filepath" "runtime" "strconv" "strings" "testing" + "time" "github.com/rogpeppe/go-internal/testscript" - "github.com/twpayne/go-vfs" - "github.com/twpayne/go-vfs/vfst" + "github.com/twpayne/go-vfs/v2" + "github.com/twpayne/go-vfs/v2/vfst" "github.com/twpayne/chezmoi/cmd" - "github.com/twpayne/chezmoi/internal/chezmoi" + "github.com/twpayne/chezmoi/internal/chezmoitest" ) -// umask is the umask used in tests. The umask applies to the process and so -// cannot be overridden in individual tests. -const umask = 0o22 - //nolint:interfacer func TestMain(m *testing.M) { - chezmoi.SetUmask(umask) os.Exit(testscript.RunMain(m, map[string]func() int{ "chezmoi": func() int { - if err := cmd.Execute(); err != nil { - if s := err.Error(); s != "" { - fmt.Fprintf(os.Stderr, "chezmoi: %s\n", s) - } - return 1 - } - return 0 + return cmd.Main(cmd.VersionInfo{ + Version: "v2.0.0+test", + Commit: "HEAD", + Date: time.Now().UTC().Format(time.RFC3339), + BuiltBy: "testscript", + }, os.Args[1:]) }, })) } @@ -42,18 +39,29 @@ func TestScript(t *testing.T) { testscript.Run(t, testscript.Params{ Dir: filepath.Join("testdata", "scripts"), Cmds: map[string]func(*testscript.TestScript, bool, []string){ + "appendline": cmdAppendLine, "chhome": cmdChHome, "cmpmod": cmdCmpMod, "edit": cmdEdit, "mkfile": cmdMkFile, + "mkageconfig": cmdMkAGEConfig, + "mkgitconfig": cmdMkGitConfig, + "mkgpgconfig": cmdMkGPGConfig, "mkhomedir": cmdMkHomeDir, "mksourcedir": cmdMkSourceDir, "rmfinalnewline": cmdRmFinalNewline, + "unix2dos": cmdUNIX2DOS, }, Condition: func(cond string) (bool, error) { switch cond { case "darwin": return runtime.GOOS == "darwin", nil + case "freebsd": + return runtime.GOOS == "freebsd", nil + case "githubactionsonmacos": + return chezmoitest.GitHubActionsOnMacOS(), nil + case "githubactionsonwindows": + return chezmoitest.GitHubActionsOnWindows(), nil case "windows": return runtime.GOOS == "windows", nil default: @@ -65,8 +73,23 @@ func TestScript(t *testing.T) { }) } +// cmdAppendLine appends lines to a file. +func cmdAppendLine(ts *testscript.TestScript, neg bool, args []string) { + if neg { + ts.Fatalf("unsupported: ! appendline") + } + if len(args) != 2 { + ts.Fatalf("usage: appendline file line") + } + filename := ts.MkAbs(args[0]) + data, err := os.ReadFile(filename) + ts.Check(err) + data = append(data, append([]byte(args[1]), '\n')...) + ts.Check(os.WriteFile(filename, data, 0o666)) +} + // cmdChHome changes the home directory to its argument, creating the directory -// if it does not already exists. It updates the HOME environment variable, and, +// if it does not already exist. It updates the HOME environment variable, and, // if running on Windows, USERPROFILE too. func cmdChHome(ts *testscript.TestScript, neg bool, args []string) { if neg { @@ -77,8 +100,8 @@ func cmdChHome(ts *testscript.TestScript, neg bool, args []string) { } var ( homeDir = ts.MkAbs(args[0]) - chezmoiConfigDir = filepath.Join(homeDir, ".config", "chezmoi") - chezmoiSourceDir = filepath.Join(homeDir, ".local", "share", "chezmoi") + chezmoiConfigDir = path.Join(homeDir, ".config", "chezmoi") + chezmoiSourceDir = path.Join(homeDir, ".local", "share", "chezmoi") ) ts.Check(os.MkdirAll(homeDir, 0o777)) ts.Setenv("HOME", homeDir) @@ -105,13 +128,12 @@ func cmdCmpMod(ts *testscript.TestScript, neg bool, args []string) { if err != nil { ts.Fatalf("%s: %v", args[1], err) } - umask := chezmoi.GetUmask() - equal := info.Mode().Perm()&^umask == os.FileMode(mode64)&^umask + equal := info.Mode().Perm() == os.FileMode(mode64)&^chezmoitest.Umask if neg && equal { ts.Fatalf("%s unexpectedly has mode %03o", args[1], info.Mode().Perm()) } if !neg && !equal { - ts.Fatalf("%s has mode %03o, expected %03o", args[1], info.Mode().Perm(), os.FileMode(mode64)) + ts.Fatalf("%s has mode %03o, expected %03o", args[1], info.Mode().Perm(), os.FileMode(mode64)&^chezmoitest.Umask) } } @@ -122,12 +144,12 @@ func cmdEdit(ts *testscript.TestScript, neg bool, args []string) { } for _, arg := range args { filename := ts.MkAbs(arg) - data, err := ioutil.ReadFile(filename) + data, err := os.ReadFile(filename) if err != nil { ts.Fatalf("edit: %v", err) } data = append(data, []byte("# edited\n")...) - if err := ioutil.WriteFile(filename, data, 0o666); err != nil { + if err := os.WriteFile(filename, data, 0o666); err != nil { ts.Fatalf("edit: %v", err) } } @@ -157,12 +179,102 @@ func cmdMkFile(ts *testscript.TestScript, neg bool, args []string) { case !os.IsNotExist(err): ts.Fatalf("%s: %v", arg, err) } - if err := ioutil.WriteFile(filename, nil, perm); err != nil { + if err := os.WriteFile(filename, nil, perm); err != nil { ts.Fatalf("%s: %v", arg, err) } } } +// cmdMkAGEConfig creates a AGE key and a chezmoi configuration file. +func cmdMkAGEConfig(ts *testscript.TestScript, neg bool, args []string) { + if neg { + ts.Fatalf("unupported: ! mkageconfig") + } + if len(args) > 0 { + ts.Fatalf("usage: mkageconfig") + } + homeDir := ts.Getenv("HOME") + ts.Check(os.MkdirAll(homeDir, 0o777)) + privateKeyFile := filepath.Join(homeDir, "key.txt") + publicKey, _, err := chezmoitest.AGEGenerateKey(ts.MkAbs(privateKeyFile)) + ts.Check(err) + configFile := filepath.Join(homeDir, ".config", "chezmoi", "chezmoi.toml") + ts.Check(os.MkdirAll(filepath.Dir(configFile), 0o777)) + ts.Check(os.WriteFile(configFile, []byte(fmt.Sprintf(chezmoitest.JoinLines( + `encryption = "age"`, + `[age]`, + ` identity = %q`, + ` recipient = %q`, + ), privateKeyFile, publicKey)), 0o666)) +} + +// cmdMkGitConfig makes a .gitconfig file in the home directory. +func cmdMkGitConfig(ts *testscript.TestScript, neg bool, args []string) { + if neg { + ts.Fatalf("unsupported: ! mkgitconfig") + } + if len(args) > 1 { + ts.Fatalf(("usage: mkgitconfig [path]")) + } + path := filepath.Join(ts.Getenv("HOME"), ".gitconfig") + if len(args) > 0 { + path = ts.MkAbs(args[0]) + } + ts.Check(os.MkdirAll(filepath.Dir(path), 0o777)) + ts.Check(os.WriteFile(path, []byte(chezmoitest.JoinLines( + `[core]`, + ` autocrlf = false`, + `[user]`, + ` name = User`, + ` email = [email protected]`, + )), 0o666)) +} + +// cmdMkGPGConfig creates a GPG key and a chezmoi configuration file. +func cmdMkGPGConfig(ts *testscript.TestScript, neg bool, args []string) { + if neg { + ts.Fatalf("unupported: ! mkgpgconfig") + } + if len(args) > 0 { + ts.Fatalf("usage: mkgpgconfig") + } + + // Create a new directory for GPG. We can't use a subdirectory of the + // testscript's working directory because on darwin the absolute path can + // exceed GPG's limit of sockaddr_un.sun_path (107 characters, see man + // unix(7)). The limit exists because GPG creates a UNIX domain socket in + // its home directory and UNIX domain socket paths are limited to + // sockaddr_un.sun_path characters. + gpgHomeDir, err := os.MkdirTemp("", "chezmoi-test-gpg-homedir") + ts.Check(err) + ts.Defer(func() { + os.RemoveAll(gpgHomeDir) + }) + if runtime.GOOS != "windows" { + ts.Check(os.Chmod(gpgHomeDir, 0o700)) + } + + command, err := chezmoitest.GPGCommand() + ts.Check(err) + + key, passphrase, err := chezmoitest.GPGGenerateKey(command, gpgHomeDir) + ts.Check(err) + + configFile := filepath.Join(ts.Getenv("HOME"), ".config", "chezmoi", "chezmoi.toml") + ts.Check(os.MkdirAll(filepath.Dir(configFile), 0o777)) + ts.Check(os.WriteFile(configFile, []byte(fmt.Sprintf(chezmoitest.JoinLines( + `encryption = "gpg"`, + `[gpg]`, + ` args = [`, + ` "--homedir", %q,`, + ` "--no-tty",`, + ` "--passphrase", %q,`, + ` "--pinentry-mode", "loopback",`, + ` ]`, + ` recipient = %q`, + ), gpgHomeDir, passphrase, key)), 0o666)) +} + // cmdMkHomeDir makes and populates a home directory. func cmdMkHomeDir(ts *testscript.TestScript, neg bool, args []string) { if neg { @@ -178,29 +290,27 @@ func cmdMkHomeDir(ts *testscript.TestScript, neg bool, args []string) { workDir := ts.Getenv("WORK") relPath, err := filepath.Rel(workDir, path) ts.Check(err) - if err := newBuilder().Build(vfs.NewPathFS(vfs.OSFS, workDir), map[string]interface{}{ + if err := vfst.NewBuilder().Build(vfs.NewPathFS(vfs.OSFS, workDir), map[string]interface{}{ relPath: map[string]interface{}{ - ".bashrc": "# contents of .bashrc\n", - ".binary": &vfst.File{ - Perm: 0o777, - Contents: []byte("#!/bin/sh\n"), - }, - ".gitconfig": "" + - "[core]\n" + - " autocrlf = false\n" + - "[user]\n" + - " email = [email protected]\n" + - " name = Your Name\n", - ".hushlogin": "", - ".ssh": &vfst.Dir{ - Perm: 0o700, - Entries: map[string]interface{}{ - "config": "# contents of .ssh/config\n", + ".create": "# contents of .create\n", + ".dir": map[string]interface{}{ + "file": "# contents of .dir/file\n", + "subdir": map[string]interface{}{ + "file": "# contents of .dir/subdir/file\n", }, }, - ".symlink": &vfst.Symlink{ - Target: ".bashrc", + ".empty": "", + ".executable": &vfst.File{ + Perm: 0o777, + Contents: []byte("# contents of .executable\n"), + }, + ".file": "# contents of .file\n", + ".private": &vfst.File{ + Perm: 0o600, + Contents: []byte("# contents of .private\n"), }, + ".symlink": &vfst.Symlink{Target: ".dir/subdir/file"}, + ".template": "key = value\n", }, }); err != nil { ts.Fatalf("mkhomedir: %v", err) @@ -222,22 +332,24 @@ func cmdMkSourceDir(ts *testscript.TestScript, neg bool, args []string) { workDir := ts.Getenv("WORK") relPath, err := filepath.Rel(workDir, sourceDir) ts.Check(err) - err = newBuilder().Build(vfs.NewPathFS(vfs.OSFS, workDir), map[string]interface{}{ + err = vfst.NewBuilder().Build(vfs.NewPathFS(vfs.OSFS, workDir), map[string]interface{}{ relPath: map[string]interface{}{ - "dot_absent": "", - "empty_dot_hushlogin": "", - "executable_dot_binary": "#!/bin/sh\n", - "dot_bashrc": "# contents of .bashrc\n", - "dot_gitconfig.tmpl": "" + - "[core]\n" + - " autocrlf = false\n" + - "[user]\n" + - " email = {{ \"[email protected]\" }}\n" + - " name = Your Name\n", - "private_dot_ssh": map[string]interface{}{ - "config": "# contents of .ssh/config\n", + "create_dot_create": "# contents of .create\n", + "dot_dir": map[string]interface{}{ + "file": "# contents of .dir/file\n", + "subdir": map[string]interface{}{ + "file": "# contents of .dir/subdir/file\n", + }, }, - "symlink_dot_symlink": ".bashrc\n", + "dot_remove": "", + "empty_dot_empty": "", + "executable_dot_executable": "# contents of .executable\n", + "dot_file": "# contents of .file\n", + "private_dot_private": "# contents of .private\n", + "symlink_dot_symlink": ".dir/subdir/file\n", + "dot_template.tmpl": chezmoitest.JoinLines( + `key = {{ "value" }}`, + ), }, }) if err != nil { @@ -255,21 +367,37 @@ func cmdRmFinalNewline(ts *testscript.TestScript, neg bool, args []string) { } for _, arg := range args { filename := ts.MkAbs(arg) - data, err := ioutil.ReadFile(filename) + data, err := os.ReadFile(filename) if err != nil { ts.Fatalf("%s: %v", filename, err) } if len(data) == 0 || data[len(data)-1] != '\n' { continue } - if err := ioutil.WriteFile(filename, data[:len(data)-1], 0o666); err != nil { + if err := os.WriteFile(filename, data[:len(data)-1], 0o666); err != nil { ts.Fatalf("%s: %v", filename, err) } } } -func newBuilder() *vfst.Builder { - return vfst.NewBuilder(vfst.BuilderUmask(umask)) +// cmdUNIX2DOS converts files from UNIX line endings to DOS line endings. +func cmdUNIX2DOS(ts *testscript.TestScript, neg bool, args []string) { + if neg { + ts.Fatalf("unsupported: ! unix2dos") + } + if len(args) < 1 { + ts.Fatalf("usage: unix2dos paths...") + } + for _, arg := range args { + filename := ts.MkAbs(arg) + data, err := os.ReadFile(filename) + ts.Check(err) + dosData, err := unix2DOS(data) + ts.Check(err) + if err := os.WriteFile(filename, dosData, 0o666); err != nil { + ts.Fatalf("%s: %v", filename, err) + } + } } func prependDirToPath(dir, path string) string { @@ -278,10 +406,19 @@ func prependDirToPath(dir, path string) string { func setup(env *testscript.Env) error { var ( - binDir = filepath.Join(env.WorkDir, "bin") - homeDir = filepath.Join(env.WorkDir, "home", "user") - chezmoiConfigDir = filepath.Join(homeDir, ".config", "chezmoi") - chezmoiSourceDir = filepath.Join(homeDir, ".local", "share", "chezmoi") + binDir = filepath.Join(env.WorkDir, "bin") + homeDir = filepath.Join(env.WorkDir, "home", "user") + ) + + absHomeDir, err := filepath.Abs(homeDir) + if err != nil { + return err + } + absSlashHomeDir := filepath.ToSlash(absHomeDir) + + var ( + chezmoiConfigDir = path.Join(absSlashHomeDir, ".config", "chezmoi") + chezmoiSourceDir = path.Join(absSlashHomeDir, ".local", "share", "chezmoi") ) env.Setenv("HOME", homeDir) @@ -303,36 +440,72 @@ func setup(env *testscript.Env) error { switch runtime.GOOS { case "windows": root["/bin"] = map[string]interface{}{ - // editor.cmd a non-interactive script that appends "# edited\n" to - // the end of each file. - "editor.cmd": "@for %%x in (%*) do echo # edited >> %%x\r\n", + // editor.cmd is a non-interactive script that appends "# edited\n" + // to the end of each file and creates an empty .edited file in each + // directory. + "editor.cmd": &vfst.File{ + Contents: []byte(chezmoitest.JoinLines( + `@echo off`, + `:loop`, + `IF EXIST %~s1\NUL (`, + ` copy /y NUL "%~1\.edited" >NUL`, + `) ELSE (`, + ` echo # edited >> "%~1"`, + `)`, + `shift`, + `IF NOT "%~1"=="" goto loop`, + )), + }, } default: root["/bin"] = map[string]interface{}{ - // editor a non-interactive script that appends "# edited\n" to the - // end of each file. + // editor is a non-interactive script that appends "# edited\n" to + // the end of each file and creates an empty .edited file in each + // directory. "editor": &vfst.File{ Perm: 0o755, - Contents: []byte(strings.Join([]string{ - "#!/bin/sh", - "", - "for filename in $*; do", - " echo '# edited' >> $filename", - "done", - }, "\n")), + Contents: []byte(chezmoitest.JoinLines( + `#!/bin/sh`, + ``, + `for name in $*; do`, + ` if [ -d $name ]; then`, + ` touch $name/.edited`, + ` else`, + ` echo "# edited" >> $name`, + ` fi`, + `done`, + )), }, // shell is a non-interactive script that appends the directory in // which it was launched to $WORK/shell.log. "shell": &vfst.File{ Perm: 0o755, - Contents: []byte(strings.Join([]string{ - "#!/bin/sh", - "", - "echo $PWD >> '" + filepath.Join(env.WorkDir, "shell.log") + "'", - }, "\n")), + Contents: []byte(chezmoitest.JoinLines( + `#!/bin/sh`, + ``, + `echo $PWD >> '`+filepath.Join(env.WorkDir, "shell.log")+`'`, + )), }, } } - return newBuilder().Build(vfs.NewPathFS(vfs.OSFS, env.WorkDir), root) + return vfst.NewBuilder().Build(vfs.NewPathFS(vfs.OSFS, env.WorkDir), root) +} + +// unix2DOS returns data with UNIX line endings converted to DOS line endings. +func unix2DOS(data []byte) ([]byte, error) { + sb := strings.Builder{} + s := bufio.NewScanner(bytes.NewReader(data)) + for s.Scan() { + if _, err := sb.Write(s.Bytes()); err != nil { + return nil, err + } + if _, err := sb.WriteString("\r\n"); err != nil { + return nil, err + } + } + if err := s.Err(); err != nil { + return nil, err + } + return []byte(sb.String()), nil } diff --git a/testdata/scripts/add.txt b/testdata/scripts/add.txt index 5eae8bd70d4..12e7df3f1c2 100644 --- a/testdata/scripts/add.txt +++ b/testdata/scripts/add.txt @@ -1,33 +1,46 @@ mkhomedir mksourcedir golden -rmfinalnewline golden/symlink_dot_symlink -# test adding a normal file -chezmoi add $HOME${/}.bashrc -cmp $CHEZMOISOURCEDIR/dot_bashrc golden/dot_bashrc +# test chezmoi add --create +chezmoi add --create $HOME${/}.create +cmp $CHEZMOISOURCEDIR/create_dot_create golden/create_dot_create -[short] stop +# test adding a file in a directory +chezmoi add $HOME${/}.dir/file +cmp $CHEZMOISOURCEDIR/dot_dir/file golden/dot_dir/file -# test adding an executable file -chezmoi add $HOME${/}.binary -[!windows] cmp $CHEZMOISOURCEDIR/executable_dot_binary golden/executable_dot_binary -[windows] cmp $CHEZMOISOURCEDIR/dot_binary golden/executable_dot_binary +# test adding a subdirectory +chezmoi add $HOME${/}.dir/subdir +cmp $CHEZMOISOURCEDIR/dot_dir/subdir/file golden/dot_dir/subdir/file # test adding an empty file without --empty -chezmoi add $HOME${/}.hushlogin -! exists $CHEZMOISOURCEDIR/dot_hushlogin +chezmoi add $HOME${/}.empty +! exists $CHEZMOISOURCEDIR/dot_empty # test adding an empty file with --empty -chezmoi add --empty $HOME${/}.hushlogin -cmp $CHEZMOISOURCEDIR/empty_dot_hushlogin golden/empty_dot_hushlogin +chezmoi add --empty $HOME${/}.empty +cmp $CHEZMOISOURCEDIR/empty_dot_empty golden/empty_dot_empty + +# test adding an executable file +chezmoi add $HOME${/}.executable +[!windows] cmp $CHEZMOISOURCEDIR/executable_dot_executable golden/executable_dot_executable +[windows] cmp $CHEZMOISOURCEDIR/dot_executable golden/executable_dot_executable + +# test adding a private file +chezmoi add $HOME${/}.private +[!windows] cmp $CHEZMOISOURCEDIR/private_dot_private $HOME/.private +[windows] cmp $CHEZMOISOURCEDIR/dot_private $HOME/.private # test adding a symlink chezmoi add $HOME${/}.symlink cmp $CHEZMOISOURCEDIR/symlink_dot_symlink golden/symlink_dot_symlink -# test adding a private directory -chezmoi add $HOME${/}.ssh -[!windows] exists $CHEZMOISOURCEDIR/private_dot_ssh -[windows] exists $CHEZMOISOURCEDIR/dot_ssh -stop # FIXME -cmp $CHEZMOISOURCEDIR/private_dot_ssh/config $HOME/.ssh/config +# test adding a symlink with a separator +symlink $HOME${/}.symlink2 -> .dir${/}subdir${/}file +chezmoi add $HOME${/}.symlink2 +cmp $CHEZMOISOURCEDIR/symlink_dot_symlink2 golden/symlink_dot_symlink + +# test adding a symlink with --follow +symlink $HOME${/}.symlink3 -> .file +chezmoi add --follow $HOME${/}.symlink3 +cmp $CHEZMOISOURCEDIR/dot_symlink3 golden/dot_file diff --git a/testdata/scripts/addautotemplate.txt b/testdata/scripts/addautotemplate.txt index d6dc88a5035..90085da336f 100644 --- a/testdata/scripts/addautotemplate.txt +++ b/testdata/scripts/addautotemplate.txt @@ -1,17 +1,18 @@ -[short] stop - -mkhomedir - # test adding a file with --autotemplate -chezmoi add --autotemplate $HOME${/}.gitconfig -cmp $CHEZMOISOURCEDIR/dot_gitconfig.tmpl golden/dot_gitconfig.tmpl +chezmoi add --autotemplate $HOME${/}.template +cmp $CHEZMOISOURCEDIR/dot_template.tmpl golden/dot_template.tmpl + +# test adding a symlink with --autotemplate +symlink $HOME/.symlink -> .target-value +chezmoi add --autotemplate $HOME${/}.symlink +cmp $CHEZMOISOURCEDIR/symlink_dot_symlink.tmpl golden/symlink_dot_symlink.tmpl --- golden/dot_gitconfig.tmpl -- -[core] - autocrlf = false -[user] - email = {{ .email }} - name = Your Name +-- golden/dot_template.tmpl -- +key = {{ .variable }} +-- golden/symlink_dot_symlink.tmpl -- +.target-{{ .variable }} -- home/user/.config/chezmoi/chezmoi.toml -- [data] - email = "[email protected]" + variable = "value" +-- home/user/.template -- +key = value diff --git a/chezmoi2/testdata/scripts/age.txt b/testdata/scripts/age.txt similarity index 100% rename from chezmoi2/testdata/scripts/age.txt rename to testdata/scripts/age.txt diff --git a/testdata/scripts/apply.txt b/testdata/scripts/apply.txt index 294db42dae5..490176b67f7 100644 --- a/testdata/scripts/apply.txt +++ b/testdata/scripts/apply.txt @@ -1,31 +1,71 @@ mkhomedir golden mksourcedir -# test --dry-run -chezmoi apply --dry-run -! exists $HOME/.bashrc -! exists $HOME/.binary -! exists $HOME/.gitconfig -! exists $HOME/.hushlogin -! exists $HOME/.ssh -! exists $HOME/.symlink - -# test apply file -chezmoi apply $HOME${/}.bashrc -cmp $HOME/.bashrc golden/.bashrc -! exists $HOME/.binary -! exists $HOME/.gitconfig -! exists $HOME/.hushlogin -! exists $HOME/.ssh -! exists $HOME/.symlink - -[short] stop - -# test apply all -chezmoi apply -cmp $HOME/.bashrc golden/.bashrc -cmp $HOME/.binary golden/.binary -cmp $HOME/.gitconfig golden/.gitconfig -cmp $HOME/.hushlogin golden/.hushlogin -cmp $HOME/.ssh/config golden/.ssh/config -cmp $HOME/.symlink golden/.bashrc +# test that chezmoi apply --dry-run does not create any files +chezmoi apply --dry-run --force +! exists $HOME/.create +! exists $HOME/.dir +! exists $HOME/.dir/file +! exists $HOME/.dir/subdir +! exists $HOME/.dir/subdir/file +! exists $HOME/.empty +! exists $HOME/.executable +! exists $HOME/.file +! exists $HOME/.private +! exists $HOME/.remove +! exists $HOME/.template + +# test that chezmoi apply file creates a single file only +chezmoi apply --force $HOME${/}.file +! exists $HOME/.create +! exists $HOME/.dir +! exists $HOME/.dir/file +! exists $HOME/.dir/subdir +! exists $HOME/.dir/subdir/file +! exists $HOME/.empty +! exists $HOME/.executable +exists $HOME/.file +! exists $HOME/.private +! exists $HOME/.remove +! exists $HOME/.template + +# test that chezmoi apply dir --recursive=false creates only the directory +chezmoi apply --force --recursive=false $HOME${/}.dir +exists $HOME/.dir +! exists $HOME/.dir/file +! exists $HOME/.dir/subdir +! exists $HOME/.dir/subdir/file + +# test that chezmoi apply dir creates all files in the directory +chezmoi apply --force $HOME${/}.dir +exists $HOME/.dir +exists $HOME/.dir/file +exists $HOME/.dir/subdir +exists $HOME/.dir/subdir/file + +# test that chezmoi apply creates all files +chezmoi apply --force +exists $HOME/.create +exists $HOME/.dir +exists $HOME/.dir/file +exists $HOME/.dir/subdir +exists $HOME/.dir/subdir/file +exists $HOME/.empty +exists $HOME/.executable +exists $HOME/.file +exists $HOME/.private +! exists $HOME/.remove +exists $HOME/.template + +# test apply after edit +edit $CHEZMOISOURCEDIR/dot_file +chezmoi apply --force +cmp $HOME/.file $CHEZMOISOURCEDIR/dot_file + +# test that chezmoi apply --source-path applies a file based on its source path +edit $CHEZMOISOURCEDIR/dot_file +chezmoi apply --force --source-path $CHEZMOISOURCEDIR/dot_file +grep -count=2 '# edited' $HOME/.file + +# test that chezmoi apply --source-path fails when called with a targetDirAbsPath +! chezmoi apply --force --source-path $HOME${/}.file diff --git a/testdata/scripts/applychmod.txt b/testdata/scripts/applychmod.txt index 3eef296a021..f6f82a30612 100644 --- a/testdata/scripts/applychmod.txt +++ b/testdata/scripts/applychmod.txt @@ -1,22 +1,20 @@ [windows] stop -[short] stop - mkhomedir golden mkhomedir mksourcedir # test change file mode -chmod 777 $HOME${/}.bashrc -chezmoi apply -cmpmod 666 $HOME/.bashrc +chmod 777 $HOME${/}.file +chezmoi apply --force +cmpmod 666 $HOME/.file # test change executable file mode -chmod 666 $HOME/.binary -chezmoi apply -cmpmod 777 $HOME/.binary +chmod 666 $HOME/.executable +chezmoi apply --force +cmpmod 777 $HOME/.executable # test change directory mode -chmod 777 $HOME/.ssh -chezmoi apply -cmpmod 700 $HOME/.ssh +chmod 700 $HOME/.dir +chezmoi apply --force +cmpmod 777 $HOME/.dir diff --git a/testdata/scripts/applyexact.txt b/testdata/scripts/applyexact.txt index 668edc36f96..ea1c71ee574 100644 --- a/testdata/scripts/applyexact.txt +++ b/testdata/scripts/applyexact.txt @@ -1,14 +1,20 @@ -[short] stop +# test that chezmoi apply --dry-run does not remove entries from exact directories +chezmoi apply --dry-run --force +exists $HOME/.dir/file1 +exists $HOME/.dir/file2 +exists $HOME/.dir/subdir/file -chezmoi apply -exists $HOME/dir/foo +# test that chezmoi apply removes entries from exact directories +chezmoi apply --force +exists $HOME/.dir/file1 +! exists $HOME/.dir/file2 +! exists $HOME/.dir/subdir/file -cp golden/empty $HOME/dir/bar -chezmoi apply --dry-run -exists $HOME/dir/bar -chezmoi apply -! exists $HOME/dir/bar - --- golden/empty -- --- home/user/.local/share/chezmoi/exact_dir/foo -- -# contents of foo +-- home/user/.dir/file1 -- +# contents of .dir/file1 +-- home/user/.dir/file2 -- +# contents of .dir/file2 +-- home/user/.dir/subdir/file -- +# contents of .dir/subdir/file +-- home/user/.local/share/chezmoi/exact_dot_dir/file1 -- +# contents of .dir/file1 diff --git a/testdata/scripts/applyremove.txt b/testdata/scripts/applyremove.txt index 7a9dbfd20ad..9af27848d48 100644 --- a/testdata/scripts/applyremove.txt +++ b/testdata/scripts/applyremove.txt @@ -1,11 +1,27 @@ -[short] stop +# test that chezmoi apply --dry-run --remove does not remove entries +chezmoi apply --dry-run --force --remove +exists $HOME/.dir/file +exists $HOME/.file1 +exists $HOME/.file2 -chezmoi apply --dry-run --remove -exists $HOME${/}.bashrc -chezmoi apply --remove -! exists $HOME${/}.bashrc +# test that chezmoi apply --remove file removes only file +chezmoi apply --force --remove $HOME${/}.file1 +exists $HOME/.dir/file +! exists $HOME/.file1 +exists $HOME/.file2 --- home/user/.bashrc -- -# contents of .bashrc +# test that chezmoi apply --remove removes all entries +chezmoi apply --force --remove +! exists $HOME/.dir/file +! exists $HOME/.file1 +! exists $HOME/.file2 + +-- home/user/.dir/file -- +# contents of .dir/file +-- home/user/.file1 -- +# contents of .file1 +-- home/user/.file2 -- +# contents of .file2 -- home/user/.local/share/chezmoi/.chezmoiremove -- -.bashrc +.dir +.file* diff --git a/chezmoi2/testdata/scripts/applyignoreencrypted.txt b/testdata/scripts/applyskipencrypted.txt similarity index 74% rename from chezmoi2/testdata/scripts/applyignoreencrypted.txt rename to testdata/scripts/applyskipencrypted.txt index 0bb006653a9..3a706de8a05 100644 --- a/chezmoi2/testdata/scripts/applyignoreencrypted.txt +++ b/testdata/scripts/applyskipencrypted.txt @@ -1,16 +1,17 @@ [!exec:gpg] skip 'gpg not found in $PATH' +[githubactionsonmacos] skip 'gpg is broken in GitHub Actions on macOS' [githubactionsonwindows] skip 'gpg is broken in GitHub Actions on Windows' mkhomedir mkgpgconfig -# test that chezmoi apply --ignore-encrypted does not apply encrypted files +# test that chezmoi apply --exclude=encrypted does not apply encrypted files cp golden/.encrypted $HOME chezmoi add --encrypt $HOME${/}.encrypted rm $HOME/.encrypted cp $CHEZMOICONFIGDIR/chezmoi.toml golden/chezmoi.toml rm $CHEZMOICONFIGDIR/chezmoi.toml -chezmoi apply --force --ignore-encrypted +chezmoi apply --force --exclude=encrypted ! exists $HOME/.encrypted # test that chezmoi apply applies the encrypted file diff --git a/testdata/scripts/applytype.txt b/testdata/scripts/applytype.txt index 42590e1f7c8..f9ac8fa5027 100644 --- a/testdata/scripts/applytype.txt +++ b/testdata/scripts/applytype.txt @@ -1,25 +1,22 @@ -# FIXME add more combinations - -[short] stop - mkhomedir golden mkhomedir mksourcedir # test replace directory with file -rm $HOME/.bashrc -mkdir $HOME/.bashrc -chezmoi apply -cmp $HOME/.bashrc golden/.bashrc +rm $HOME/.file +mkdir $HOME/.file +chezmoi apply --force +cmp $HOME/.file golden/.file # test replace file with directory -rm $HOME/.ssh -mkfile $HOME/.ssh -chezmoi apply -cmp $HOME/.ssh/config golden/.ssh/config +rm $HOME/.dir +mkfile $HOME/.dir +chezmoi apply --force +cmp $HOME/.dir/file golden/.dir/file +cmp $HOME/.dir/subdir/file golden/.dir/subdir/file # test replace file with symlink rm $HOME/.symlink mkfile $HOME/.symlink -chezmoi apply -cmp $HOME/.symlink golden/.bashrc +chezmoi apply --force +cmp $HOME/.symlink golden/.symlink diff --git a/testdata/scripts/archive.txt b/testdata/scripts/archive.txt deleted file mode 100644 index 4afec9518de..00000000000 --- a/testdata/scripts/archive.txt +++ /dev/null @@ -1,25 +0,0 @@ -[windows] stop -[!exec:tar] stop - -mksourcedir - -[windows] unix2dos golden/archive - -chezmoi archive --output=archive.tar -exec tar -tf archive.tar -cmp stdout golden/archive - -[short] stop - -chezmoi archive --output=archive.tar -exec tar -tf archive.tar -cmp stdout golden/archive - --- golden/archive -- -.bashrc -.binary -.gitconfig -.hushlogin -.ssh/ -.ssh/config -.symlink diff --git a/chezmoi2/testdata/scripts/archivetar.txt b/testdata/scripts/archivetar.txt similarity index 100% rename from chezmoi2/testdata/scripts/archivetar.txt rename to testdata/scripts/archivetar.txt diff --git a/chezmoi2/testdata/scripts/archivezip.txt b/testdata/scripts/archivezip.txt similarity index 100% rename from chezmoi2/testdata/scripts/archivezip.txt rename to testdata/scripts/archivezip.txt diff --git a/testdata/scripts/autocommit.txt b/testdata/scripts/autocommit.txt index 10896c87f48..7fa2535377b 100644 --- a/testdata/scripts/autocommit.txt +++ b/testdata/scripts/autocommit.txt @@ -1,28 +1,26 @@ -[windows] stop -[!exec:git] stop +[!exec:git] skip 'git not found in $PATH' +mkgitconfig mkhomedir golden mkhomedir chezmoi init # test that chezmoi add creates and pushes a commit -chezmoi add $HOME${/}.bashrc +chezmoi add $HOME${/}.file exec git --git-dir=$CHEZMOISOURCEDIR/.git show HEAD -stdout 'Add dot_bashrc' - -[short] stop +stdout 'Add dot_file' # test that chezmoi edit creates and pushes a commit -chezmoi edit $HOME${/}.bashrc +chezmoi edit $HOME${/}.file exec git --git-dir=$CHEZMOISOURCEDIR/.git show HEAD -stdout 'Update dot_bashrc' +stdout 'Update dot_file' # test that chezmoi forget creates and pushes a commit -chezmoi forget $HOME${/}.bashrc +chezmoi forget --force $HOME${/}.file exec git --git-dir=$CHEZMOISOURCEDIR/.git show HEAD -stdout 'Remove dot_bashrc' +stdout 'Remove dot_file' -- home/user/.config/chezmoi/chezmoi.toml -- -[sourceVCS] +[git] autoCommit = true diff --git a/testdata/scripts/autopush.txt b/testdata/scripts/autopush.txt index d4634ce561b..59ba04bf2fa 100644 --- a/testdata/scripts/autopush.txt +++ b/testdata/scripts/autopush.txt @@ -1,7 +1,6 @@ -stop # FIXME - -[!exec:git] stop +[!exec:git] skip 'git not found in $PATH' +mkgitconfig mkhomedir golden mkhomedir @@ -10,22 +9,20 @@ exec git init --bare $WORK/dotfiles.git chezmoi init file://$WORK/dotfiles.git # test that chezmoi add creates and pushes a commit -chezmoi add $HOME${/}.bashrc +chezmoi add $HOME${/}.file exec git --git-dir=$WORK/dotfiles.git show HEAD -stdout 'Add dot_bashrc' - -[short] stop +stdout 'Add dot_file' # test that chezmoi edit creates and pushes a commit -chezmoi edit $HOME${/}.bashrc +chezmoi edit $HOME${/}.file exec git --git-dir=$WORK/dotfiles.git show HEAD -stdout 'Update dot_bashrc' +stdout 'Update dot_file' # test that chezmoi forget creates and pushes a commit -chezmoi forget $HOME${/}.bashrc +chezmoi forget --force $HOME${/}.file exec git --git-dir=$WORK/dotfiles.git show HEAD -stdout 'Remove dot_bashrc' +stdout 'Remove dot_file' -- home/user/.config/chezmoi/chezmoi.toml -- -[sourceVCS] +[git] autoPush = true diff --git a/testdata/scripts/bitwarden.txt b/testdata/scripts/bitwarden.txt index 236a6d0c3c0..f37759a5e0b 100644 --- a/testdata/scripts/bitwarden.txt +++ b/testdata/scripts/bitwarden.txt @@ -1,16 +1,15 @@ [!windows] chmod 755 bin/bw [windows] unix2dos bin/bw.cmd +# test bitwarden template function chezmoi execute-template '{{ (bitwarden "item" "example.com").login.password }}' stdout password-value -[short] stop - +# test bitwardenFields template function chezmoi execute-template '{{ (bitwardenFields "item" "example.com").Hidden.value }}' stdout hidden-value -[short] stop - +# test bitwardenAttachment template function chezmoi execute-template '{{ (bitwardenAttachment "filename" "item-id") }}' stdout hidden-file-value diff --git a/chezmoi2/testdata/scripts/builtingit.txt b/testdata/scripts/builtingit.txt similarity index 100% rename from chezmoi2/testdata/scripts/builtingit.txt rename to testdata/scripts/builtingit.txt diff --git a/testdata/scripts/cat.txt b/testdata/scripts/cat.txt index 035fa029f1a..4ee1c25c8b1 100644 --- a/testdata/scripts/cat.txt +++ b/testdata/scripts/cat.txt @@ -1,23 +1,32 @@ mkhomedir golden mksourcedir -chezmoi cat $HOME${/}.bashrc -cmp stdout golden/.bashrc +# test that chezmoi cat prints an empty file +chezmoi cat $HOME${/}.empty +cmp stdout golden/.empty -[short] stop - -chezmoi cat $HOME${/}.gitconfig -cmp stdout golden/.gitconfig +# test that chezmoi cat prints a file +chezmoi cat $HOME${/}.file +cmp stdout golden/.file +# test that chezmoi cat prints a symlink chezmoi cat $HOME${/}.symlink -stdout '\.bashrc' +stdout '\.dir/subdir/file' + +# test that chezmoi cat prints a template +chezmoi cat $HOME${/}.template +cmp stdout golden/.template -! chezmoi cat $HOME${/}.ssh +# test that chezmoi cat does not print directories +! chezmoi cat $HOME${/}.dir stderr 'not a file or symlink' +# test that chezmoi cat does not print files outside the destination directory ! chezmoi cat ${/}etc${/}passwd -stderr 'outside target directory' +stderr 'not in' -cd $HOME -chezmoi cat .gitconfig -cmp stdout $WORK/golden/.gitconfig +# test that chezmoi cat uses relative paths +mkdir $HOME/.dir +cd $HOME/.dir +chezmoi cat file +cmp stdout $WORK/golden/.dir/file diff --git a/testdata/scripts/cd.txt b/testdata/scripts/cd.txt deleted file mode 100644 index 13455581efa..00000000000 --- a/testdata/scripts/cd.txt +++ /dev/null @@ -1,17 +0,0 @@ -# There is currently not a way to override the shell for testing on Windows -[windows] skip - -# test chezmoi cd -chezmoi cd -grep -count=1 ${CHEZMOISOURCEDIR@R} shell.log - -# test chezmoi cd with command with args -[!exec:bash] stop -chhome home2${/}user -chezmoi cd -stdout version - --- home2/user/.config/chezmoi/chezmoi.toml -- -[cd] - command = "bash" - args = ["--version"] diff --git a/testdata/scripts/cd_unix.txt b/testdata/scripts/cd_unix.txt index 394910a2db0..4affc462f7b 100644 --- a/testdata/scripts/cd_unix.txt +++ b/testdata/scripts/cd_unix.txt @@ -9,7 +9,7 @@ grep -count=1 ${CHEZMOISOURCEDIR@R} shell.log chezmoi cd grep -count=2 ${CHEZMOISOURCEDIR@R} shell.log -[!exec:bash] stop +[!exec:bash] stop 'bash not found in $PATH' # test chezmoi cd with command with args chhome home2/user diff --git a/testdata/scripts/chattr.txt b/testdata/scripts/chattr.txt index b2ba3149898..d207275da46 100644 --- a/testdata/scripts/chattr.txt +++ b/testdata/scripts/chattr.txt @@ -1,33 +1,39 @@ mksourcedir -exists $CHEZMOISOURCEDIR/dot_bashrc -chezmoi chattr empty $HOME${/}.bashrc -! exists $CHEZMOISOURCEDIR/dot_bashrc -exists $CHEZMOISOURCEDIR/empty_dot_bashrc +exists $CHEZMOISOURCEDIR/dot_file +chezmoi chattr empty $HOME${/}.file +! exists $CHEZMOISOURCEDIR/dot_file +exists $CHEZMOISOURCEDIR/empty_dot_file -[short] stop +chezmoi chattr +p $HOME${/}.file +! exists $CHEZMOISOURCEDIR/empty_dot_file +exists $CHEZMOISOURCEDIR/private_empty_dot_file -chezmoi chattr +p $HOME${/}.bashrc -! exists $CHEZMOISOURCEDIR/empty_dot_bashrc -exists $CHEZMOISOURCEDIR/private_empty_dot_bashrc +chezmoi chattr t,-e $HOME${/}.file +! exists $CHEZMOISOURCEDIR/private_empty_dot_file +exists $CHEZMOISOURCEDIR/private_dot_file.tmpl -chezmoi chattr t,-e $HOME${/}.bashrc -! exists $CHEZMOISOURCEDIR/private_empty_dot_bashrc -exists $CHEZMOISOURCEDIR/private_dot_bashrc.tmpl +exists $CHEZMOISOURCEDIR/executable_dot_executable +chezmoi chattr nox $HOME${/}.executable +! exists $CHEZMOISOURCEDIR/executable_dot_executable +exists $CHEZMOISOURCEDIR/dot_executable -exists $CHEZMOISOURCEDIR/executable_dot_binary -chezmoi chattr nox $HOME${/}.binary -! exists $CHEZMOISOURCEDIR/executable_dot_binary -exists $CHEZMOISOURCEDIR/dot_binary +chezmoi chattr x $HOME${/}.executable +! exists $CHEZMOISOURCEDIR/dot_executable +exists $CHEZMOISOURCEDIR/executable_dot_executable -chezmoi chattr x $HOME${/}.binary -! exists $CHEZMOISOURCEDIR/dot_binary -exists $CHEZMOISOURCEDIR/executable_dot_binary +chezmoi chattr +private $HOME${/}.create +! exists $CHEZMOISOURCEDIR/create_dot_create +exists $CHEZMOISOURCEDIR/create_private_dot_create -exists $CHEZMOISOURCEDIR/private_dot_ssh -chezmoi chattr exact $HOME/.ssh -! exists $CHEZMOISOURCEDIR/private_dot_ssh -exists $CHEZMOISOURCEDIR/exact_private_dot_ssh +chezmoi chattr noprivate $HOME${/}.create +! exists $CHEZMOISOURCEDIR/create_private_dot_create +exists $CHEZMOISOURCEDIR/create_dot_create + +exists $CHEZMOISOURCEDIR/dot_dir +chezmoi chattr exact $HOME/.dir +! exists $CHEZMOISOURCEDIR/dot_dir +exists $CHEZMOISOURCEDIR/exact_dot_dir exists $CHEZMOISOURCEDIR/symlink_dot_symlink chezmoi chattr +t $HOME${/}.symlink @@ -37,3 +43,26 @@ exists $CHEZMOISOURCEDIR/symlink_dot_symlink.tmpl chezmoi chattr -- -t $HOME${/}.symlink ! exists $CHEZMOISOURCEDIR/symlink_dot_symlink.tmpl exists $CHEZMOISOURCEDIR/symlink_dot_symlink + +chezmoi chattr -- before $HOME/script +! exists $CHEZMOISOURCEDIR/run_script +exists $CHEZMOISOURCEDIR/run_before_script + +chezmoi chattr -- once $HOME/script +! exists $CHEZMOISOURCEDIR/run_before_script +exists $CHEZMOISOURCEDIR/run_once_before_script + +chezmoi chattr -- after $HOME/script +! exists $CHEZMOISOURCEDIR/run_once_before_script +exists $CHEZMOISOURCEDIR/run_once_after_script + +chezmoi chattr -- -o $HOME/script +! exists $CHEZMOISOURCEDIR/run_once_after_script +exists $CHEZMOISOURCEDIR/run_after_script + +chezmoi chattr -- -a $HOME/script +! exists $CHEZMOISOURCEDIR/run_after_script +exists $CHEZMOISOURCEDIR/run_script + +-- home/user/.local/share/chezmoi/run_script -- +#!/bin/sh diff --git a/testdata/scripts/chezmoiignore.txt b/testdata/scripts/chezmoiignore.txt deleted file mode 100644 index 1d98d5c44f8..00000000000 --- a/testdata/scripts/chezmoiignore.txt +++ /dev/null @@ -1,12 +0,0 @@ -chezmoi data - --- home/user/.config/chezmoi/chezmoi.toml -- -[data] - config = "home" --- home/user/.local/share/chezmoi/.chezmoiignore -- -.home -{{ if ne .config "work" }} -.work -{{ end }} --- home/user/.local/share/chezmoi/empty_dot_home -- --- home/user/.local/share/chezmoi/empty_dot_work -- diff --git a/testdata/scripts/completion.txt b/testdata/scripts/completion.txt index 17f48a76287..3cabb6b6944 100644 --- a/testdata/scripts/completion.txt +++ b/testdata/scripts/completion.txt @@ -1,8 +1,6 @@ chezmoi completion bash stdout '# bash completion for chezmoi' -[short] stop - chezmoi completion fish stdout '# fish completion for chezmoi' diff --git a/chezmoi2/testdata/scripts/config.txt b/testdata/scripts/config.txt similarity index 78% rename from chezmoi2/testdata/scripts/config.txt rename to testdata/scripts/config.txt index 78a3134fff0..b0de2ba56d5 100644 --- a/chezmoi2/testdata/scripts/config.txt +++ b/testdata/scripts/config.txt @@ -13,10 +13,10 @@ chezmoi data --format=yaml stdout 'sourceDir: .*/config/source' # test that the config file can be set -chezmoi data --config=$CHEZMOICONFIGDIR/chezmoi2.toml --format=yaml +chezmoi data --config=$CHEZMOICONFIGDIR/chezmoi.yaml --format=yaml stdout 'sourceDir: .*/config2/source' -- home2/user/.config/chezmoi/chezmoi.toml -- sourceDir = "/config/source" --- home2/user/.config/chezmoi/chezmoi2.toml -- -sourceDir = "/config2/source" +-- home2/user/.config/chezmoi/chezmoi.yaml -- +sourceDir: /config2/source diff --git a/chezmoi2/testdata/scripts/configstate.txt b/testdata/scripts/configstate.txt similarity index 76% rename from chezmoi2/testdata/scripts/configstate.txt rename to testdata/scripts/configstate.txt index 47a5f582bfe..476772f74c0 100644 --- a/chezmoi2/testdata/scripts/configstate.txt +++ b/testdata/scripts/configstate.txt @@ -3,9 +3,11 @@ chezmoi init cmp $CHEZMOICONFIGDIR/chezmoi.toml golden/chezmoi.toml chezmoi state dump --format=yaml cmp stdout golden/state-dump.yaml +! stderr . # test that chezmoi apply succeeds chezmoi apply +! stderr . # test that chezmoi apply prints a warning if the config file template has been changed cp golden/.chezmoi.toml.tmpl $CHEZMOISOURCEDIR/.chezmoi.toml.tmpl @@ -15,6 +17,7 @@ stderr 'warning: config file template has changed' # test that chezmoi init re-generates the config file chezmoi init cmp $CHEZMOICONFIGDIR/chezmoi.toml golden/chezmoi.toml +! stderr . # test that chezmoi apply no longer prints a warning after the config file is regenerated chezmoi apply @@ -27,6 +30,20 @@ chezmoi apply --force ! stderr . ! grep '# edited' $CHEZMOICONFIGDIR/chezmoi.toml +chhome home2/user + +# test that chezmoi diff prints a warning when a config file template is added +chezmoi diff +! stderr . +cp golden/chezmoi.toml $CHEZMOISOURCEDIR/.chezmoi.toml.tmpl +chezmoi diff +stderr 'warning: config file template has changed' + +# test that chezmoi diff does not print a warning when the config file template is removed +rm $CHEZMOISOURCEDIR/.chezmoi.toml.tmpl +chezmoi diff +! stderr . + -- golden/.chezmoi.toml.tmpl -- {{ $email := get . "email" -}} {{ if not $email -}} @@ -47,3 +64,5 @@ scriptState: {} [data] email = "[email protected]" -- home/user/.local/share/chezmoi/.git/.keep -- +-- home2/user/.local/share/chezmoi/.keep -- + diff --git a/testdata/scripts/data.txt b/testdata/scripts/data.txt index d72a3bcaede..b66f24d8b39 100644 --- a/testdata/scripts/data.txt +++ b/testdata/scripts/data.txt @@ -1,17 +1,17 @@ +# test that chezmoi data includes data set in config file chezmoi data stdout '"chezmoi":' -stdout 'uniquekey.*uniqueValue' # viper downcases uniqueKey - -[short] stop +stdout '"uniquekey": "uniqueValue"' # viper downcases uniqueKey +# test that chezmoi data --format=json includes data set in config file chezmoi data --format=json stdout '"chezmoi":' +stdout '"uniquekey": "uniqueValue"' -chezmoi data --format=toml -stdout '[chezmoi]' - +# test that chezmoi data --format=yaml includes data set in config file chezmoi data --format=yaml stdout 'chezmoi:' +stdout 'uniquekey: uniqueValue' -- home/user/.config/chezmoi/chezmoi.toml -- [data] diff --git a/testdata/scripts/diff.txt b/testdata/scripts/diff.txt index 5d27f55945f..8eb172a2127 100644 --- a/testdata/scripts/diff.txt +++ b/testdata/scripts/diff.txt @@ -1,5 +1,3 @@ -[windows] stop - mkhomedir golden mkhomedir mksourcedir @@ -9,103 +7,116 @@ chezmoi diff ! stdout . # test that chezmoi diff generates a diff when a file is added to the source state -cp golden/dot_inputrc $CHEZMOISOURCEDIR/dot_inputrc +cp golden/dot_newfile $CHEZMOISOURCEDIR/dot_newfile chezmoi diff -cmp stdout golden/add-file-diff -rm $CHEZMOISOURCEDIR/dot_inputrc - -[short] stop +[!windows] cmp stdout golden/add-newfile-diff-unix +[windows] cmp stdout golden/add-newfile-diff-windows +rm $CHEZMOISOURCEDIR/dot_newfile # test that chezmoi diff generates a diff when a file is edited -edit $HOME/.bashrc +edit $HOME/.file chezmoi diff -cmp stdout golden/modify-file-diff -chezmoi diff --color=on -cmp stdout golden/modify-file-diff-color -cp golden/.bashrc $HOME +[!windows] cmp stdout golden/modify-file-diff-unix +[windows] cmp stdout golden/modify-file-diff-windows +chezmoi apply --force $HOME${/}.file # test that chezmoi diff generates a diff when a file is removed from the destination directory -rm $HOME/.bashrc +rm $HOME/.file chezmoi diff -cmp stdout golden/remove-file-diff -cp golden/.bashrc $HOME +[!windows] cmp stdout golden/restore-file-diff-unix +[windows] cmp stdout golden/restore-file-diff-windows +chezmoi apply --force $HOME${/}.file # test that chezmoi diff generates a diff when a directory is removed from the destination directory -rm $HOME/.ssh -chezmoi diff -cmp stdout golden/remove-dir-diff -mkdir $HOME/.ssh -chmod 700 $HOME/.ssh -cp golden/.ssh/config $HOME/.ssh/config - -# FIXME remove test +rm $HOME/.dir +chezmoi diff --recursive=false $HOME${/}.dir +[!windows] cmp stdout golden/restore-dir-diff-unix +[windows] cmp stdout golden/restore-dir-diff-windows +chezmoi apply --force $HOME${/}.dir [windows] stop 'remaining tests use file modes' # test that chezmoi diff generates a diff when a file's permissions are changed -chmod 777 $HOME/.bashrc +chmod 777 $HOME/.file chezmoi diff cmp stdout golden/chmod-file-diff -chmod 666 $HOME/.bashrc +chezmoi apply --force $HOME${/}.file # test that chezmoi diff generates a diff when a dir's permissions are changed -# FIXME show changes to permissions in diff -chmod 755 $HOME/.ssh +chmod 700 $HOME/.dir chezmoi diff cmp stdout golden/chmod-dir-diff -chmod 700 $HOME/.ssh +chezmoi apply --force --recursive=false $HOME${/}.dir --- home/user/.config/chezmoi/chezmoi.toml -- -[diff] - format="git" --- golden/add-file-diff -- -diff --git a/.inputrc b/.inputrc -index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..3e8778ee8061d7afb917f3d5f1ee17580dc96c99 0 ---- a/.inputrc -+++ b/.inputrc +-- golden/add-newfile-diff-unix -- +diff --git a/.newfile b/.newfile +new file mode 100644 +index 0000000000000000000000000000000000000000..06e05235fdd12fd5c367b6d629fef94536c85525 +--- /dev/null ++++ b/.newfile +@@ -0,0 +1 @@ ++# contents of .newfile +-- golden/add-newfile-diff-windows -- +diff --git a/.newfile b/.newfile +new file mode 100666 +index 0000000000000000000000000000000000000000..06e05235fdd12fd5c367b6d629fef94536c85525 +--- /dev/null ++++ b/.newfile @@ -0,0 +1 @@ -+# contents of .inputrc --- golden/modify-file-diff -- -diff --git a/.bashrc b/.bashrc -index e9a9fc3629d099c17bce71f43c2b5c773ed3ba45..13faef3591002a9d38fe869ca0e205ca472fac73 100644 ---- a/.bashrc -+++ b/.bashrc ++# contents of .newfile +-- golden/modify-file-diff-unix -- +diff --git a/.file b/.file +index 5d2730a8850a2db479af83de87cc8345437aef06..8a52cb9ce9551221716a53786ad74104c5902362 100644 +--- a/.file ++++ b/.file +@@ -1,2 +1 @@ + # contents of .file +-# edited +-- golden/modify-file-diff-windows -- +diff --git a/.file b/.file +index 5d2730a8850a2db479af83de87cc8345437aef06..8a52cb9ce9551221716a53786ad74104c5902362 100666 +--- a/.file ++++ b/.file @@ -1,2 +1 @@ - # contents of .bashrc + # contents of .file -# edited --- golden/modify-file-diff-color -- -diff --git a/.bashrc b/.bashrc -index e9a9fc3629d099c17bce71f43c2b5c773ed3ba45..13faef3591002a9d38fe869ca0e205ca472fac73 100644 ---- a/.bashrc -+++ b/.bashrc -@@ -1,2 +1 @@ - # contents of .bashrc --# edited --- golden/remove-file-diff -- -diff --git a/.bashrc b/.bashrc -index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..13faef3591002a9d38fe869ca0e205ca472fac73 0 ---- a/.bashrc -+++ b/.bashrc +-- golden/restore-file-diff-unix -- +diff --git a/.file b/.file +new file mode 100644 +index 0000000000000000000000000000000000000000..8a52cb9ce9551221716a53786ad74104c5902362 +--- /dev/null ++++ b/.file @@ -0,0 +1 @@ -+# contents of .bashrc --- golden/remove-dir-diff -- -diff --git a/.ssh b/.ssh -new file mode 40000 -index 0000000000000000000000000000000000000000..0000000000000000000000000000000000000000 ++# contents of .file +-- golden/restore-file-diff-windows -- +diff --git a/.file b/.file +new file mode 100666 +index 0000000000000000000000000000000000000000..8a52cb9ce9551221716a53786ad74104c5902362 --- /dev/null -+++ b/.ssh -diff --git a/.ssh/config b/.ssh/config -index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..24222eaee40f73342b927474372b1632a65cef01 0 ---- a/.ssh/config -+++ b/.ssh/config ++++ b/.file @@ -0,0 +1 @@ -+# contents of .ssh/config ++# contents of .file +-- golden/restore-dir-diff-unix -- +diff --git a/.dir b/.dir +new file mode 40755 +index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 +--- /dev/null ++++ b/.dir +-- golden/restore-dir-diff-windows -- +diff --git a/.dir b/.dir +new file mode 40777 +index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 +--- /dev/null ++++ b/.dir +-- golden/dot_newfile -- +# contents of .newfile -- golden/chmod-file-diff -- -diff --git a/.bashrc b/.bashrc -old mode 100755 +diff --git a/.file b/.file +old mode 100777 new mode 100644 -- golden/chmod-dir-diff -- -diff --git a/.bashrc b/.bashrc -diff --git a/.ssh b/.ssh --- golden/dot_inputrc -- -# contents of .inputrc +diff --git a/.dir b/.dir +old mode 40700 +new mode 40755 +-- golden/dot_newfile -- +# contents of .newfile diff --git a/testdata/scripts/docs.txt b/testdata/scripts/docs.txt index 19954779a33..9a5276c213d 100644 --- a/testdata/scripts/docs.txt +++ b/testdata/scripts/docs.txt @@ -1,15 +1,13 @@ chezmoi docs stdout 'chezmoi Reference Manual' -[short] stop - chezmoi docs faq stdout 'chezmoi Frequently Asked Questions' chezmoi docs quickstart stdout 'chezmoi Quick Start Guide' -! chezmoi docs a +! chezmoi docs c stderr 'ambiguous pattern' ! chezmoi docs z diff --git a/chezmoi2/testdata/scripts/doctor.txt b/testdata/scripts/doctor.txt similarity index 100% rename from chezmoi2/testdata/scripts/doctor.txt rename to testdata/scripts/doctor.txt diff --git a/testdata/scripts/dump.txt b/testdata/scripts/dump.txt deleted file mode 100644 index c6f7365b383..00000000000 --- a/testdata/scripts/dump.txt +++ /dev/null @@ -1,215 +0,0 @@ -[windows] stop - -mksourcedir - -chezmoi dump --format=json -cmpenv stdout golden/dump.json - -chezmoi dump --format=json $HOME${/}.bashrc -cmpenv stdout golden/dump-bashrc.json - -chezmoi dump --format=json $HOME${/}.ssh -cmpenv stdout golden/dump-ssh.json - -chezmoi dump --format=json --recursive=false $HOME${/}.ssh -cmpenv stdout golden/dump-ssh-non-recursive.json - -chezmoi dump --format=yaml -cmpenv stdout golden/dump.yaml - -! chezmoi dump $HOME${/}.inputrc -stderr 'file does not exist' - --- golden/dump.json -- -[ - { - "type": "file", - "sourcePath": "$WORK/home/user/.local/share/chezmoi/dot_absent", - "targetPath": ".absent", - "empty": false, - "encrypted": false, - "perm": 420, - "template": false, - "contents": "" - }, - { - "type": "file", - "sourcePath": "$WORK/home/user/.local/share/chezmoi/dot_bashrc", - "targetPath": ".bashrc", - "empty": false, - "encrypted": false, - "perm": 420, - "template": false, - "contents": "# contents of .bashrc\n" - }, - { - "type": "file", - "sourcePath": "$WORK/home/user/.local/share/chezmoi/executable_dot_binary", - "targetPath": ".binary", - "empty": false, - "encrypted": false, - "perm": 493, - "template": false, - "contents": "#!/bin/sh\n" - }, - { - "type": "file", - "sourcePath": "$WORK/home/user/.local/share/chezmoi/dot_gitconfig.tmpl", - "targetPath": ".gitconfig", - "empty": false, - "encrypted": false, - "perm": 420, - "template": true, - "contents": "[core]\n autocrlf = false\n[user]\n email = [email protected]\n name = Your Name\n" - }, - { - "type": "file", - "sourcePath": "$WORK/home/user/.local/share/chezmoi/empty_dot_hushlogin", - "targetPath": ".hushlogin", - "empty": true, - "encrypted": false, - "perm": 420, - "template": false, - "contents": "" - }, - { - "type": "dir", - "sourcePath": "$WORK/home/user/.local/share/chezmoi/private_dot_ssh", - "targetPath": ".ssh", - "exact": false, - "perm": 448, - "entries": [ - { - "type": "file", - "sourcePath": "$WORK/home/user/.local/share/chezmoi/private_dot_ssh/config", - "targetPath": ".ssh/config", - "empty": false, - "encrypted": false, - "perm": 420, - "template": false, - "contents": "# contents of .ssh/config\n" - } - ] - }, - { - "type": "symlink", - "sourcePath": "$WORK/home/user/.local/share/chezmoi/symlink_dot_symlink", - "targetPath": ".symlink", - "template": false, - "linkname": ".bashrc" - } -] --- golden/dump-bashrc.json -- -[ - { - "type": "file", - "sourcePath": "$WORK/home/user/.local/share/chezmoi/dot_bashrc", - "targetPath": ".bashrc", - "empty": false, - "encrypted": false, - "perm": 420, - "template": false, - "contents": "# contents of .bashrc\n" - } -] --- golden/dump-ssh.json -- -[ - { - "type": "dir", - "sourcePath": "$WORK/home/user/.local/share/chezmoi/private_dot_ssh", - "targetPath": ".ssh", - "exact": false, - "perm": 448, - "entries": [ - { - "type": "file", - "sourcePath": "$WORK/home/user/.local/share/chezmoi/private_dot_ssh/config", - "targetPath": ".ssh/config", - "empty": false, - "encrypted": false, - "perm": 420, - "template": false, - "contents": "# contents of .ssh/config\n" - } - ] - } -] --- golden/dump-ssh-non-recursive.json -- -[ - { - "type": "dir", - "sourcePath": "$WORK/home/user/.local/share/chezmoi/private_dot_ssh", - "targetPath": ".ssh", - "exact": false, - "perm": 448, - "entries": null - } -] --- golden/dump.yaml -- -- type: file - sourcePath: $WORK/home/user/.local/share/chezmoi/dot_absent - targetPath: .absent - empty: false - encrypted: false - perm: 420 - template: false - contents: "" -- type: file - sourcePath: $WORK/home/user/.local/share/chezmoi/dot_bashrc - targetPath: .bashrc - empty: false - encrypted: false - perm: 420 - template: false - contents: | - # contents of .bashrc -- type: file - sourcePath: $WORK/home/user/.local/share/chezmoi/executable_dot_binary - targetPath: .binary - empty: false - encrypted: false - perm: 493 - template: false - contents: | - #!/bin/sh -- type: file - sourcePath: $WORK/home/user/.local/share/chezmoi/dot_gitconfig.tmpl - targetPath: .gitconfig - empty: false - encrypted: false - perm: 420 - template: true - contents: | - [core] - autocrlf = false - [user] - email = [email protected] - name = Your Name -- type: file - sourcePath: $WORK/home/user/.local/share/chezmoi/empty_dot_hushlogin - targetPath: .hushlogin - empty: true - encrypted: false - perm: 420 - template: false - contents: "" -- type: dir - sourcePath: $WORK/home/user/.local/share/chezmoi/private_dot_ssh - targetPath: .ssh - exact: false - perm: 448 - entries: - - type: file - sourcePath: $WORK/home/user/.local/share/chezmoi/private_dot_ssh/config - targetPath: .ssh/config - empty: false - encrypted: false - perm: 420 - template: false - contents: | - # contents of .ssh/config -- type: symlink - sourcePath: $WORK/home/user/.local/share/chezmoi/symlink_dot_symlink - targetPath: .symlink - template: false - linkname: .bashrc diff --git a/chezmoi2/testdata/scripts/dumpjson.txt b/testdata/scripts/dumpjson.txt similarity index 100% rename from chezmoi2/testdata/scripts/dumpjson.txt rename to testdata/scripts/dumpjson.txt diff --git a/chezmoi2/testdata/scripts/dumpyaml.txt b/testdata/scripts/dumpyaml.txt similarity index 52% rename from chezmoi2/testdata/scripts/dumpyaml.txt rename to testdata/scripts/dumpyaml.txt index 2152236500f..eec60fa88a4 100644 --- a/chezmoi2/testdata/scripts/dumpyaml.txt +++ b/testdata/scripts/dumpyaml.txt @@ -3,6 +3,9 @@ mksourcedir chezmoi dump --format=yaml cmp stdout golden/dump.yaml +chezmoi dump --exclude=dirs --format=yaml +cmp stdout golden/dump-except-dirs.yaml + -- golden/dump.yaml -- .create: type: file @@ -63,3 +66,55 @@ cmp stdout golden/dump.yaml contents: | key = value perm: 438 +-- golden/dump-except-dirs.yaml -- +.create: + type: file + name: .create + contents: | + # contents of .create + perm: 438 +.dir/file: + type: file + name: .dir/file + contents: | + # contents of .dir/file + perm: 438 +.dir/subdir/file: + type: file + name: .dir/subdir/file + contents: | + # contents of .dir/subdir/file + perm: 438 +.empty: + type: file + name: .empty + contents: "" + perm: 438 +.executable: + type: file + name: .executable + contents: | + # contents of .executable + perm: 511 +.file: + type: file + name: .file + contents: | + # contents of .file + perm: 438 +.private: + type: file + name: .private + contents: | + # contents of .private + perm: 384 +.symlink: + type: symlink + name: .symlink + linkname: .dir/subdir/file +.template: + type: file + name: .template + contents: | + key = value + perm: 438 diff --git a/chezmoi2/testdata/scripts/edgecases.txt b/testdata/scripts/edgecases.txt similarity index 100% rename from chezmoi2/testdata/scripts/edgecases.txt rename to testdata/scripts/edgecases.txt diff --git a/testdata/scripts/edit.txt b/testdata/scripts/edit.txt index af1f74feda3..66ec652e726 100644 --- a/testdata/scripts/edit.txt +++ b/testdata/scripts/edit.txt @@ -1,29 +1,31 @@ mkhomedir mksourcedir -chezmoi edit $HOME${/}.bashrc -grep -count=1 '# edited' $CHEZMOISOURCEDIR/dot_bashrc -! grep '# edited' $HOME/.bashrc +chezmoi edit $HOME${/}.file +grep -count=1 '# edited' $CHEZMOISOURCEDIR/dot_file +! grep '# edited' $HOME/.file -[short] stop - -chezmoi edit --apply $HOME${/}.bashrc -grep -count=2 '# edited' $CHEZMOISOURCEDIR/dot_bashrc -grep -count=2 '# edited' $HOME/.bashrc +chezmoi edit --apply --force $HOME${/}.file +grep -count=2 '# edited' $CHEZMOISOURCEDIR/dot_file +grep -count=2 '# edited' $HOME/.file chezmoi edit $HOME${/}.symlink grep -count=1 '# edited' $CHEZMOISOURCEDIR/symlink_dot_symlink -chezmoi edit $HOME${/}.bashrc $HOME${/}.symlink -grep -count=3 '# edited' $CHEZMOISOURCEDIR/dot_bashrc +chezmoi edit -v $HOME${/}script +grep -count=1 '# edited' $CHEZMOISOURCEDIR/run_script + +chezmoi edit $HOME${/}.file $HOME${/}.symlink +grep -count=3 '# edited' $CHEZMOISOURCEDIR/dot_file grep -count=2 '# edited' $CHEZMOISOURCEDIR/symlink_dot_symlink -# FIXME refine edit directory test -! chezmoi edit $HOME${/}.ssh +chezmoi edit +exists $CHEZMOISOURCEDIR/.edited + +[windows] stop 'remaining tests use file modes' -# FIXME --apply tests -# FIXME --prompt tests -# FIXME --verify tests +chezmoi edit $HOME${/}.dir +exists $CHEZMOISOURCEDIR/dot_dir/.edited -- home/user/.local/share/chezmoi/run_script -- #!/bin/sh diff --git a/testdata/scripts/editconfig.txt b/testdata/scripts/editconfig.txt index ccad10358a6..f038a976c74 100644 --- a/testdata/scripts/editconfig.txt +++ b/testdata/scripts/editconfig.txt @@ -2,8 +2,6 @@ chezmoi edit-config grep -count=1 '# edited' $CHEZMOICONFIGDIR/chezmoi.toml -[short] stop - # test that edit-config edits an existing config file chezmoi edit-config grep -count=2 '# edited' $CHEZMOICONFIGDIR/chezmoi.toml @@ -22,6 +20,6 @@ grep -count=1 '# edited' $CHEZMOICONFIGDIR/chezmoi.json -- home2/user/.config/chezmoi/chezmoi.yaml -- data: - email: "[email protected]" + email: "[email protected]" -- home3/user/.config/chezmoi/chezmoi.json -- -{"data":{"email":"[email protected]"}} +{"data":{"email":"[email protected]"}} diff --git a/testdata/scripts/errors.txt b/testdata/scripts/errors.txt index 07bef83a9ad..94da73c42d3 100644 --- a/testdata/scripts/errors.txt +++ b/testdata/scripts/errors.txt @@ -1,8 +1,39 @@ -[short] stop +mksourcedir + +# test duplicate source state entry detection +cp $CHEZMOISOURCEDIR/dot_file $CHEZMOISOURCEDIR/empty_dot_file +! chezmoi verify +stderr 'duplicate source state entries' # test invalid config +chhome home2/user ! chezmoi verify -stderr 'config contains errors' +stderr 'invalid config' + +# test source directory is not a directory +chhome home3/user +! chezmoi verify +stderr 'not a directory' + +# test that chezmoi checks .chezmoiversion +chhome home4/user +! chezmoi verify +stderr 'source state requires version' + +# test duplicate script detection +chhome home5/user +! chezmoi verify +stderr 'duplicate source state entries' + +# FIXME add more tests --- home/user/.config/chezmoi/chezmoi.json -- +-- home2/user/.config/chezmoi/chezmoi.json -- { +-- home3/user/.local/share/chezmoi -- +# contents of .local/share/chezmoi +-- home4/user/.local/share/chezmoi/.chezmoiversion -- +3.0.0 +-- home5/user/.local/share/chezmoi/run_install_packages -- +# contents of install_packages +-- home5/user/.local/share/chezmoi/run_once_install_packages -- +# contents of install_packages diff --git a/testdata/scripts/executetemplate.txt b/testdata/scripts/executetemplate.txt index 19da72add9a..c7eab180f94 100644 --- a/testdata/scripts/executetemplate.txt +++ b/testdata/scripts/executetemplate.txt @@ -2,8 +2,6 @@ chezmoi execute-template '{{ "arg-template" }}' stdout arg-template -[short] stop - # test reading from stdin stdin golden/stdin.tmpl chezmoi execute-template @@ -13,6 +11,31 @@ stdout stdin-template chezmoi execute-template '{{ template "partial" }}' stdout 'hello world' +# FIXME merge the following tests into a single test + +chezmoi execute-template '{{ .last.config }}' +stdout 'chezmoi\.toml' + +# test that template data are read from .chezmoidata.json +chezmoi execute-template '{{ .last.json }}' +stdout '\.chezmoidata\.json' + +# test that template data are read from .chezmoidata.toml +chezmoi execute-template '{{ .last.toml }}' +stdout '\.chezmoidata\.toml' + +# test that template data are read from .chezmoidata.yaml +chezmoi execute-template '{{ .last.yaml }}' +stdout '\.chezmoidata\.yaml' + +# test that the last .chezmoidata.<format> file read wins +chezmoi execute-template '{{ .last.format }}' +stdout '\.chezmoidata\.yaml' + +# test that the config file wins over .chezmoidata.<format> +chezmoi execute-template '{{ .last.global }}' +stdout chezmoi.toml + # test --init --promptBool chezmoi execute-template --init --promptBool value=yes '{{ promptBool "value" }}' stdout true @@ -26,8 +49,8 @@ stdout 1 stderr 'invalid syntax' # test --init --promptString -chezmoi execute-template --init --promptString [email protected] '{{ promptString "email" }}' -stdout '[email protected]' +chezmoi execute-template --init --promptString [email protected] '{{ promptString "email" }}' +stdout '[email protected]' -- golden/stdin.tmpl -- {{ "stdin-template" }} @@ -35,5 +58,23 @@ stdout '[email protected]' [data.last] config = "chezmoi.toml" global = "chezmoi.toml" +-- home/user/.local/share/chezmoi/.chezmoidata.json -- +{ + "last": { + "format": ".chezmoidata.json", + "global": ".chezmoidata.json", + "json": ".chezmoidata.json" + } +} +-- home/user/.local/share/chezmoi/.chezmoidata.toml -- +[last] + format = ".chezmoidata.toml" + global = ".chezmoidata.toml" + toml = ".chezmoidata.toml" +-- home/user/.local/share/chezmoi/.chezmoidata.yaml -- +last: + format: ".chezmoidata.yaml" + global: ".chezmoidata.yaml" + yaml: ".chezmoidata.yaml" -- home/user/.local/share/chezmoi/.chezmoitemplates/partial -- {{ cat "hello" "world" }} diff --git a/testdata/scripts/forget.txt b/testdata/scripts/forget.txt index f8d72d677fd..1e368f9d92d 100644 --- a/testdata/scripts/forget.txt +++ b/testdata/scripts/forget.txt @@ -1,9 +1,11 @@ mksourcedir -chezmoi forget $HOME${/}.bashrc -! exists $CHEZMOISOURCEDIR/dot_bashrc -exists $CHEZMOISOURCEDIR/private_dot_ssh -exists $CHEZMOISOURCEDIR/private_dot_ssh/config +# test that chezmoi forget file forgets a file +exists $CHEZMOISOURCEDIR/dot_file +chezmoi forget --force $HOME${/}.file +! exists $CHEZMOISOURCEDIR/dot_file -chezmoi forget $HOME${/}.ssh -! exists $CHEZMOISOURCEDIR/private_dot_ssh +# test that chezmoi forget dir forgets a dir +exists $CHEZMOISOURCEDIR/dot_dir +chezmoi forget --force $HOME${/}.dir +! exists $CHEZMOISOURCEDIR/dot_dir diff --git a/testdata/scripts/git.txt b/testdata/scripts/git.txt index 82c7b099797..47bc8604597 100644 --- a/testdata/scripts/git.txt +++ b/testdata/scripts/git.txt @@ -1,9 +1,8 @@ [!windows] chmod 755 bin/git [windows] unix2dos bin/git.cmd -mksourcedir - chezmoi git hello +exists $CHEZMOISOURCEDIR stdout hello -- bin/git -- diff --git a/testdata/scripts/gopass.txt b/testdata/scripts/gopass.txt index f733ebf65ad..35057f0874e 100644 --- a/testdata/scripts/gopass.txt +++ b/testdata/scripts/gopass.txt @@ -1,42 +1,32 @@ -[windows] skip # FIXME - [!windows] chmod 755 bin/gopass [windows] unix2dos bin/gopass.cmd -chezmoi apply -cmp $HOME/.netrc golden/.netrc +# test gopass template function +chezmoi execute-template '{{ gopass "misc/example.com" }}' +stdout examplepassword -- bin/gopass -- #!/bin/sh case "$*" in +"--version") + echo "gopass 1.10.1 go1.15 linux amd64" + ;; "show --password misc/example.com") echo "examplepassword" ;; -"--version") - echo "gopass 1.10.1 go1.15 darwin amd64" - ;; *) echo "gopass: invalid command: $*" exit 1 esac -- bin/gopass.cmd -- @echo off -IF "%*" == "show --password misc/example.com" ( +IF "%*" == "--version" ( + echo "gopass 1.10.1 go1.15 windows amd64" +) ELSE IF "%*" == "show --password misc/example.com" ( echo | set /p=examplepassword exit /b 0 -) ELSE IF "$*" == "--version" ( - echo "gopass 1.10.1 go1.15 darwin amd64" - exit /b 0 ) ELSE ( echo gopass: invalid command: %* exit /b 1 ) --- home/user/.local/share/chezmoi/private_dot_netrc.tmpl -- -machine example.com -login examplelogin -password {{ gopass "misc/example.com" }} --- golden/.netrc -- -machine example.com -login examplelogin -password examplepassword diff --git a/chezmoi2/testdata/scripts/gpg.txt b/testdata/scripts/gpg.txt similarity index 90% rename from chezmoi2/testdata/scripts/gpg.txt rename to testdata/scripts/gpg.txt index 7b5cf1ac494..ba158d850ad 100644 --- a/chezmoi2/testdata/scripts/gpg.txt +++ b/testdata/scripts/gpg.txt @@ -1,4 +1,5 @@ [!exec:gpg] skip 'gpg not found in $PATH' +[githubactionsonmacos] skip 'gpg is broken in GitHub Actions on macOS' [githubactionsonwindows] skip 'gpg is broken in GitHub Actions on Windows' mkhomedir diff --git a/chezmoi2/testdata/scripts/gpgencryption.txt b/testdata/scripts/gpgencryption.txt similarity index 84% rename from chezmoi2/testdata/scripts/gpgencryption.txt rename to testdata/scripts/gpgencryption.txt index 26ec25bad68..db918e67a4f 100644 --- a/chezmoi2/testdata/scripts/gpgencryption.txt +++ b/testdata/scripts/gpgencryption.txt @@ -1,4 +1,5 @@ [!exec:gpg] stop +[githubactionsonmacos] skip 'gpg is broken in GitHub Actions on macOS' [githubactionsonwindows] skip 'gpg is broken in GitHub Actions on Windows' mkgpgconfig diff --git a/testdata/scripts/help.txt b/testdata/scripts/help.txt index a13500d0013..249c15596b6 100644 --- a/testdata/scripts/help.txt +++ b/testdata/scripts/help.txt @@ -1,7 +1,5 @@ chezmoi help stdout 'Manage your dotfiles across multiple diverse machines, securely' -[short] stop - chezmoi help add stdout 'Add \*targets\* to the source state\.' diff --git a/testdata/scripts/hg.txt b/testdata/scripts/hg.txt deleted file mode 100644 index 446c3925f21..00000000000 --- a/testdata/scripts/hg.txt +++ /dev/null @@ -1,44 +0,0 @@ -[!exec:hg] stop - -# test that chezmoi init creates a mercurial repo -chezmoi init -exists $CHEZMOISOURCEDIR${/}.hg - -# test that source runs hg -chezmoi source -- --version -stdout 'Mercurial Distributed SCM' - -# create a commit -chezmoi add $HOME${/}.bashrc -chezmoi hg -- add dot_bashrc -chezmoi hg -- commit -m 'Add dot_bashrc' - -[windows] stop 'Backslash characters in file:// URLs confuse hg on Windows' - -# test that chezmoi init clones a mercurial repo -chhome home2${/}user -chezmoi init --apply file://$WORK/home/user/.local/share/chezmoi -exists $CHEZMOISOURCEDIR${/}.hg -cmp $HOME${/}.bashrc $WORK${/}home${/}user${/}.bashrc - -# create another commit -chhome home${/}user -edit $CHEZMOISOURCEDIR${/}dot_bashrc -chezmoi hg -- add dot_bashrc -chezmoi hg -- commit -m 'Update dot_bashrc' - -# test that chezmoi update pulls from a mercurial repo -chhome home2${/}user -chezmoi update -grep '# edited' $HOME${/}.bashrc - --- home/user/.bashrc -- -# contents of .bashrc --- home/user/.config/chezmoi/chezmoi.toml -- -[sourceVCS] - command = "hg" - notGit = true --- home2/user/.config/chezmoi/chezmoi.toml -- -[sourceVCS] - command = "hg" - notGit = true diff --git a/chezmoi2/testdata/scripts/ignore.txt b/testdata/scripts/ignore.txt similarity index 100% rename from chezmoi2/testdata/scripts/ignore.txt rename to testdata/scripts/ignore.txt diff --git a/chezmoi2/testdata/scripts/import.txt b/testdata/scripts/import.txt similarity index 100% rename from chezmoi2/testdata/scripts/import.txt rename to testdata/scripts/import.txt diff --git a/testdata/scripts/init.txt b/testdata/scripts/init.txt index ea08c0f723a..760413ee286 100644 --- a/testdata/scripts/init.txt +++ b/testdata/scripts/init.txt @@ -1,5 +1,6 @@ [!exec:git] stop +mkgitconfig mkhomedir golden mkhomedir @@ -7,37 +8,51 @@ mkhomedir chezmoi init exists $CHEZMOISOURCEDIR/.git -[short] stop - # create a commit -cp golden/.bashrc $CHEZMOISOURCEDIR/dot_bashrc -chezmoi git add dot_bashrc -chezmoi git commit -- --message 'Add dot_bashrc' +cp golden/.file $CHEZMOISOURCEDIR/dot_file +chezmoi git add dot_file +chezmoi git commit -- --message 'Add dot_file' # test that chezmoi init fetches git repo but does not apply chhome home2/user +mkgitconfig chezmoi init file://$WORK/home/user/.local/share/chezmoi exists $CHEZMOISOURCEDIR/.git -! exists $HOME/.bashrc +! exists $HOME/.file # test that chezmoi init --apply fetches a git repo and runs chezmoi apply chhome home3/user -chezmoi init --apply file://$WORK/home/user/.local/share/chezmoi +mkgitconfig +chezmoi init --apply --force file://$WORK/home/user/.local/share/chezmoi exists $CHEZMOISOURCEDIR/.git -cmp $HOME/.bashrc golden/.bashrc +cmp $HOME/.file golden/.file + +# test that chezmoi init --apply --depth 1 --force --purge clones, applies, and purges +chhome home4/user +mkgitconfig +exists $CHEZMOICONFIGDIR +! exists $CHEZMOISOURCEDIR +chezmoi init --apply --depth 1 --force --purge file://$WORK/home/user/.local/share/chezmoi +cmp $HOME/.file golden/.file +! exists $CHEZMOICONFIGDIR +! exists $CHEZMOISOURCEDIR # test that chezmoi init does not clone the repo if it is already checked out but does create the config file -chhome home4${/}user +chhome home5/user +mkgitconfig chezmoi init --source=$HOME/dotfiles file://$WORK/nonexistentrepo exists $CHEZMOICONFIGDIR/chezmoi.toml --- home2/user/.gitconfig -- -[core] - autocrlf = false --- home3/user/.gitconfig -- -[core] - autocrlf = false --- home4/user/dotfiles/.git/.keep -- --- home4/user/dotfiles/.chezmoi.toml.tmpl -- +# test chezmoi init --one-shot +chhome home6/user +mkgitconfig +chezmoi init --one-shot file://$WORK/home/user/.local/share/chezmoi +cmp $HOME/.file golden/.file +! exists $CHEZMOICONFIGDIR +! exists $CHEZMOISOURCEDIR + +-- home4/user/.config/chezmoi/chezmoi.toml -- +-- home5/user/dotfiles/.git/.keep -- +-- home5/user/dotfiles/.chezmoi.toml.tmpl -- [data] email = "[email protected]" diff --git a/chezmoi2/testdata/scripts/issue-796.txt b/testdata/scripts/issue-796.txt similarity index 100% rename from chezmoi2/testdata/scripts/issue-796.txt rename to testdata/scripts/issue-796.txt diff --git a/chezmoi2/testdata/scripts/keep-going.txt b/testdata/scripts/keep-going.txt similarity index 100% rename from chezmoi2/testdata/scripts/keep-going.txt rename to testdata/scripts/keep-going.txt diff --git a/testdata/scripts/keepassxc.txt b/testdata/scripts/keepassxc.txt index 0bb5e3947b6..c0ed68ee74d 100644 --- a/testdata/scripts/keepassxc.txt +++ b/testdata/scripts/keepassxc.txt @@ -1,9 +1,15 @@ [!windows] chmod 755 bin/keepass-test [windows] unix2dos bin/keepass-test.cmd +# test keepassxcAttribute template function stdin $HOME/input -chezmoi apply -cmp $HOME/.netrc golden/.netrc +chezmoi execute-template --no-tty '{{ keepassxcAttribute "example.com" "host-name" }}' +stdout example.com + +# test keepassxc template function and that password is only requested once +stdin $HOME/input +chezmoi execute-template --no-tty '{{ (keepassxc "example.com").UserName }}/{{ (keepassxc "example.com").Password }}' +stdout examplelogin/examplepassword -- bin/keepass-test -- #!/bin/sh @@ -50,11 +56,3 @@ fakepassword [keepassxc] command = "keepass-test" database = "secrets.kdbx" --- home/user/.local/share/chezmoi/private_dot_netrc.tmpl -- -machine {{ keepassxcAttribute "example.com" "host-name" }} -login {{ (keepassxc "example.com").UserName }} -password {{ (keepassxc "example.com").Password }} --- golden/.netrc -- -machine example.com -login examplelogin -password examplepassword diff --git a/testdata/scripts/lastpass.txt b/testdata/scripts/lastpass.txt index 2be3f650bb8..7956903116e 100644 --- a/testdata/scripts/lastpass.txt +++ b/testdata/scripts/lastpass.txt @@ -1,14 +1,14 @@ [!windows] chmod 755 bin/lpass [windows] unix2dos bin/lpass.cmd -chezmoi apply -cmp $HOME/.netrc golden/.netrc - -[short] stop +# test lastpass template function +chezmoi execute-template '{{ (index (lastpass "example.com") 0).password }}' +stdout examplepassword +# test lastpass version check chmod 755 $WORK/bin2/lpass env PATH=$WORK${/}bin2${:}$PATH -! chezmoi apply +! chezmoi execute-template '{{ (index (lastpass "example.com") 0).password }}' stderr 'need version 1\.3\.0 or later' -- bin/lpass -- @@ -82,11 +82,3 @@ IF "%*" == "--version" ( echo lpass: invalid command: %* exit /b 1 ) --- home/user/.local/share/chezmoi/private_dot_netrc.tmpl -- -machine example.com -login {{ (index (lastpass "example.com") 0).username }} -password {{ (index (lastpass "example.com") 0).password }} --- golden/.netrc -- -machine example.com -login examplelogin -password examplepassword diff --git a/testdata/scripts/managed.txt b/testdata/scripts/managed.txt index 618bd35b103..65c7f90ecc3 100644 --- a/testdata/scripts/managed.txt +++ b/testdata/scripts/managed.txt @@ -3,7 +3,11 @@ mksourcedir chezmoi managed cmpenv stdout golden/managed -[short] stop +chezmoi managed --include=all +cmpenv stdout golden/managed-all + +chezmoi managed --include=remove +cmpenv stdout golden/managed-remove chezmoi managed --include=dirs cmpenv stdout golden/managed-dirs @@ -14,23 +18,51 @@ cmpenv stdout golden/managed-files chezmoi managed --include=symlinks cmpenv stdout golden/managed-symlinks +chezmoi managed --exclude=files +cmpenv stdout golden/managed-except-files + -- golden/managed -- -$HOME${/}.absent -$HOME${/}.bashrc -$HOME${/}.binary -$HOME${/}.gitconfig -$HOME${/}.hushlogin -$HOME${/}.ssh -$HOME${/}.ssh${/}config -$HOME${/}.symlink +.create +.dir +.dir/file +.dir/subdir +.dir/subdir/file +.empty +.executable +.file +.private +.symlink +.template +-- golden/managed-all -- +.create +.dir +.dir/file +.dir/subdir +.dir/subdir/file +.empty +.executable +.file +.private +.remove +.symlink +.template -- golden/managed-dirs -- -$HOME${/}.ssh +.dir +.dir/subdir -- golden/managed-files -- -$HOME${/}.absent -$HOME${/}.bashrc -$HOME${/}.binary -$HOME${/}.gitconfig -$HOME${/}.hushlogin -$HOME${/}.ssh${/}config +.create +.dir/file +.dir/subdir/file +.empty +.executable +.file +.private +.template +-- golden/managed-remove -- +.remove -- golden/managed-symlinks -- -$HOME${/}.symlink +.symlink +-- golden/managed-except-files -- +.dir +.dir/subdir +.symlink diff --git a/chezmoi2/testdata/scripts/merge.txt b/testdata/scripts/merge.txt similarity index 100% rename from chezmoi2/testdata/scripts/merge.txt rename to testdata/scripts/merge.txt diff --git a/chezmoi2/testdata/scripts/modify.txt b/testdata/scripts/modify.txt similarity index 100% rename from chezmoi2/testdata/scripts/modify.txt rename to testdata/scripts/modify.txt diff --git a/chezmoi2/testdata/scripts/noencryption.txt b/testdata/scripts/noencryption.txt similarity index 100% rename from chezmoi2/testdata/scripts/noencryption.txt rename to testdata/scripts/noencryption.txt diff --git a/testdata/scripts/onepassword.txt b/testdata/scripts/onepassword.txt index 9e9d5c25e5f..bd99e09816a 100644 --- a/testdata/scripts/onepassword.txt +++ b/testdata/scripts/onepassword.txt @@ -1,9 +1,11 @@ [!windows] chmod 755 bin/op [windows] unix2dos bin/op.cmd +# test onepassword template function chezmoi execute-template '{{ (onepassword "ExampleLogin").uuid }}' stdout '^wxcplh5udshnonkzg2n4qx262y$' +# test onepasswordDetailsFields template function chezmoi execute-template '{{ (onepasswordDetailsFields "ExampleLogin").password.value }}' stdout '^L8rm1JXJIE1b8YUDWq7h$' diff --git a/testdata/scripts/pass.txt b/testdata/scripts/pass.txt index 7d5c999c53b..2db7e67b258 100644 --- a/testdata/scripts/pass.txt +++ b/testdata/scripts/pass.txt @@ -1,8 +1,9 @@ [!windows] chmod 755 bin/pass [windows] unix2dos bin/pass.cmd -chezmoi apply -cmp $HOME/.netrc golden/.netrc +# test pass template function +chezmoi execute-template '{{ pass "misc/example.com" }}' +stdout examplepassword -- bin/pass -- #!/bin/sh @@ -24,11 +25,3 @@ IF "%*" == "show misc/example.com" ( echo pass: invalid command: %* exit /b 1 ) --- home/user/.local/share/chezmoi/private_dot_netrc.tmpl -- -machine example.com -login examplelogin -password {{ pass "misc/example.com" }} --- golden/.netrc -- -machine example.com -login examplelogin -password examplepassword diff --git a/testdata/scripts/remove.txt b/testdata/scripts/remove.txt index 2346799ab1c..61d79803d10 100644 --- a/testdata/scripts/remove.txt +++ b/testdata/scripts/remove.txt @@ -1,12 +1,18 @@ mkhomedir mksourcedir -exists $HOME/.bashrc -chezmoi remove --force $HOME${/}.bashrc -! exists $HOME/.bashrc +# test that chezmoi remove file removes a file +exists $HOME/.file +chezmoi remove --force $HOME${/}.file +! exists $HOME/.file -[short] stop +# test that chezmoi remove dir removes a directory +exists $HOME/.dir +chezmoi remove --force $HOME${/}.dir +! exists $HOME/.dir -exists $HOME/.ssh/config -chezmoi remove --force $HOME${/}.ssh -! exists $HOME/.ssh/config +# test that if any chezmoi remove stops on any error +exists $HOME/.executable +! chezmoi remove --force $HOME${/}.newfile $HOME${/}.executable +stderr 'not in source state' +exists $HOME/.executable diff --git a/testdata/scripts/runscriptdir_unix.txt b/testdata/scripts/runscriptdir_unix.txt index 2815e249509..b132e0b015d 100644 --- a/testdata/scripts/runscriptdir_unix.txt +++ b/testdata/scripts/runscriptdir_unix.txt @@ -3,11 +3,9 @@ chezmoi apply cmpenv stdout golden/apply -[short] stop - env $=$ chezmoi dump -cmpenv stdout golden/dump +cmp stdout golden/dump [!exec:tar] stop @@ -21,25 +19,18 @@ $HOME${/}dir dir/ dir/script -- golden/dump -- -[ - { +{ + "dir": { "type": "dir", - "sourcePath": "$WORK/home/user/.local/share/chezmoi/dir", - "targetPath": "dir", - "exact": false, - "perm": 493, - "entries": [ - { - "type": "script", - "sourcePath": "$WORK/home/user/.local/share/chezmoi/dir/run_script", - "targetPath": "dir/script", - "once": false, - "template": false, - "contents": "#!/bin/sh\n\necho ${$}PWD\n" - } - ] + "name": "dir", + "perm": 511 + }, + "dir/script": { + "type": "script", + "name": "dir/script", + "contents": "#!/bin/sh\n\necho $PWD\n" } -] +} -- home/user/.local/share/chezmoi/dir/run_script -- #!/bin/sh diff --git a/testdata/scripts/script_unix.txt b/testdata/scripts/script_unix.txt index 3d4894ca32e..61df8268b7d 100644 --- a/testdata/scripts/script_unix.txt +++ b/testdata/scripts/script_unix.txt @@ -1,33 +1,51 @@ [windows] skip 'UNIX only' -chezmoi apply -stdout evidence +# test that chezmoi status prints that it will run the script +chezmoi status +cmp stdout golden/status -[short] stop +# test that chezmoi apply runs the script +chezmoi apply --force +stdout ${HOME@R} +# test that chezmoi status prints that it will run the script again +chezmoi status +cmp stdout golden/status + +# test that chezmoi apply runs the script even if it has run before +chezmoi apply --force +stdout ${HOME@R} + +# test that chezmoi dump includes the script chezmoi dump -cmpenv stdout golden/dump.json +cmp stdout golden/dump.json -[!exec:tar] stop +# test that chezmoi managed includes the script +chezmoi managed --include=scripts +cmpenv stdout golden/managed -chezmoi archive --output=archive.tar -exec tar -tf archive.tar +[!exec:tar] stop 'tar not found in $PATH' + +# test that chezmoi archive includes the script in the archive +chezmoi archive --format=tar --gzip --output=archive.tar.gz +exec tar -tzf archive.tar.gz cmp stdout golden/archive -- golden/archive -- script -- golden/dump.json -- -[ - { +{ + "script": { "type": "script", - "sourcePath": "$WORK/home/user/.local/share/chezmoi/run_script", - "targetPath": "script", - "once": false, - "template": false, - "contents": "#!/bin/sh\n\necho evidence\n" + "name": "script", + "contents": "#!/bin/sh\n\necho $PWD\n" } -] +} +-- golden/managed -- +script +-- golden/status -- + R script -- home/user/.local/share/chezmoi/run_script -- #!/bin/sh -echo evidence +echo $PWD diff --git a/testdata/scripts/script_windows.txt b/testdata/scripts/script_windows.txt index 90f3c4f9f8b..9d030c16fc8 100644 --- a/testdata/scripts/script_windows.txt +++ b/testdata/scripts/script_windows.txt @@ -1,38 +1,32 @@ -[windows] skip # FIXME [!windows] skip 'Windows only' -chezmoi apply +chezmoi apply --force stdout evidence -[short] stop - chezmoi dump -cmpenv stdout golden/dump.json +cmp stdout golden/dump.json chezmoi managed --include=scripts cmpenv stdout golden/managed -[!exec:tar] stop +[!exec:tar] 'tar not found in $PATH' -chezmoi archive --output=archive.tar -exec tar -tf archive.tar +chezmoi archive --gzip --output=archive.tar.gz +exec tar -tzf archive.tar.gz [windows] unix2dos golden/archive cmp stdout golden/archive -- golden/archive -- script.cmd -- golden/dump.json -- -[ - { +{ + "script.cmd": { "type": "script", - "sourcePath": "$WORK\\home\\user\\.local\\share\\chezmoi\\run_script.cmd", - "targetPath": "script.cmd", - "once": false, - "template": false, + "name": "script.cmd", "contents": "echo evidence\n" } -] +} -- golden/managed -- -$HOME\\script.cmd +script.cmd -- home/user/.local/share/chezmoi/run_script.cmd -- echo evidence diff --git a/chezmoi2/testdata/scripts/scriptonce_unix.txt b/testdata/scripts/scriptonce_unix.txt similarity index 100% rename from chezmoi2/testdata/scripts/scriptonce_unix.txt rename to testdata/scripts/scriptonce_unix.txt diff --git a/chezmoi2/testdata/scripts/scriptonce_windows.txt b/testdata/scripts/scriptonce_windows.txt similarity index 100% rename from chezmoi2/testdata/scripts/scriptonce_windows.txt rename to testdata/scripts/scriptonce_windows.txt diff --git a/chezmoi2/testdata/scripts/scriptorder_unix.txt b/testdata/scripts/scriptorder_unix.txt similarity index 100% rename from chezmoi2/testdata/scripts/scriptorder_unix.txt rename to testdata/scripts/scriptorder_unix.txt diff --git a/chezmoi2/testdata/scripts/scriptorder_windows.txt b/testdata/scripts/scriptorder_windows.txt similarity index 100% rename from chezmoi2/testdata/scripts/scriptorder_windows.txt rename to testdata/scripts/scriptorder_windows.txt diff --git a/chezmoi2/testdata/scripts/scriptsubdir_unix.txt b/testdata/scripts/scriptsubdir_unix.txt similarity index 100% rename from chezmoi2/testdata/scripts/scriptsubdir_unix.txt rename to testdata/scripts/scriptsubdir_unix.txt diff --git a/chezmoi2/testdata/scripts/scriptsubdir_windows.txt b/testdata/scripts/scriptsubdir_windows.txt similarity index 100% rename from chezmoi2/testdata/scripts/scriptsubdir_windows.txt rename to testdata/scripts/scriptsubdir_windows.txt diff --git a/chezmoi2/testdata/scripts/secret.txt b/testdata/scripts/secret.txt similarity index 100% rename from chezmoi2/testdata/scripts/secret.txt rename to testdata/scripts/secret.txt diff --git a/testdata/scripts/secretgeneric.txt b/testdata/scripts/secretgeneric.txt deleted file mode 100644 index 17c571eadbd..00000000000 --- a/testdata/scripts/secretgeneric.txt +++ /dev/null @@ -1,41 +0,0 @@ -[!windows] chmod 755 bin/secret -[windows] unix2dos bin/secret.cmd - -chezmoi secret generic examplepassword -stdout examplepassword - -chezmoi apply -cmp $HOME/.netrc golden/.netrc - -[short] stop - --- bin/secret -- -#!/bin/sh - -echo "$*" --- bin/secret.cmd -- -@echo off -setlocal -set out=%* -set out=%out:\=% -echo %out% -endlocal --- golden/.netrc -- -machine example.com -login examplelogin -password examplepassword - -machine example2.com -login examplelogin2 -password examplepassword2 --- home/user/.config/chezmoi/chezmoi.toml -- -[genericSecret] - command = "secret" --- home/user/.local/share/chezmoi/private_dot_netrc.tmpl -- -machine example.com -login examplelogin -password {{ secret "examplepassword" }} - -machine example2.com -login {{ (secretJSON "{\"username\":\"examplelogin2\",\"password\":\"examplepassword2\"}").username }} -password {{ (secretJSON "{\"username\":\"examplelogin2\",\"password\":\"examplepassword2\"}").password }} diff --git a/testdata/scripts/secretgopass.txt b/testdata/scripts/secretgopass.txt deleted file mode 100644 index 28a9433e30b..00000000000 --- a/testdata/scripts/secretgopass.txt +++ /dev/null @@ -1,45 +0,0 @@ -[windows] skip # FIXME - -[!windows] chmod 755 bin/gopass -[windows] unix2dos bin/gopass.cmd - -chezmoi -v secret gopass -- show --password misc/example.com -stdout examplepassword - -chezmoi apply -cmp $HOME/.netrc golden/.netrc - --- bin/gopass -- -#!/bin/sh - -case "$*" in -"show --password misc/example.com") - echo "examplepassword" - ;; -"--version") - echo "gopass 1.10.1 go1.15 darwin amd64" - ;; -*) - echo "gopass: invalid command: $*" - exit 1 -esac --- bin/gopass.cmd -- -@echo off -IF "%*" == "show --password misc/example.com" ( - echo | set /p=examplepassword - exit /b 0 -) ELSE IF "$*" == "--version" ( - echo "gopass 1.10.1 go1.15 darwin amd64" - exit /b 0 -) ELSE ( - echo gopass: invalid command: %* - exit /b 1 -) --- home/user/.local/share/chezmoi/private_dot_netrc.tmpl -- -machine example.com -login examplelogin -password {{ gopass "misc/example.com" }} --- golden/.netrc -- -machine example.com -login examplelogin -password examplepassword diff --git a/testdata/scripts/secretkeepassxc.txt b/testdata/scripts/secretkeepassxc.txt deleted file mode 100644 index 167a9364d59..00000000000 --- a/testdata/scripts/secretkeepassxc.txt +++ /dev/null @@ -1,69 +0,0 @@ -[!windows] chmod 755 bin/keepass-test -[windows] unix2dos bin/keepass-test.cmd - -stdin $HOME/input -chezmoi secret keepassxc -- show --show-protected secrets.kdbx example.com -stdout examplelogin - -stdin $HOME/input -chezmoi secret keepassxc -- show --attributes host-name --quiet --show-protected secrets.kdbx example.com -stdout example.com - -stdin $HOME/input -chezmoi apply -cmp $HOME/.netrc golden/.netrc - --- bin/keepass-test -- -#!/bin/sh - -case "$*" in -"--version") - echo "2.5.4" - ;; -"show --show-protected secrets.kdbx example.com") - cat <<EOF -Title: example.com -UserName: examplelogin -Password: examplepassword -URL: -Notes: -EOF - ;; -"show --attributes host-name --quiet --show-protected secrets.kdbx example.com") - echo "example.com" - ;; -*) - echo "keepass-test: invalid command: $*" - exit 1 -esac --- bin/keepass-test.cmd -- -@echo off -IF "%*" == "--version" ( - echo 2.5.4 -) ELSE IF "%*" == "show --show-protected secrets.kdbx example.com" ( - echo.Title: example.com - echo.UserName: examplelogin - echo.Password: examplepassword - echo.URL: - echo.Notes: -) ELSE IF "%*" == "show --attributes host-name --quiet --show-protected secrets.kdbx example.com" ( - echo.example.com -) ELSE ( - echo keepass-test: invalid command: %* - echo "show --show-protected --attributes host-name secrets.kdbx example.com" - exit /b 1 -) --- home/user/input -- -fakepassword --- home/user/.config/chezmoi/chezmoi.toml -- -[keepassxc] - command = "keepass-test" - database = "secrets.kdbx" --- home/user/.local/share/chezmoi/private_dot_netrc.tmpl -- -machine {{ keepassxcAttribute "example.com" "host-name" }} -login {{ (keepassxc "example.com").UserName }} -password {{ (keepassxc "example.com").Password }} --- golden/.netrc -- -machine example.com -login examplelogin -password examplepassword diff --git a/testdata/scripts/secretlastpass.txt b/testdata/scripts/secretlastpass.txt deleted file mode 100644 index 49b5d879970..00000000000 --- a/testdata/scripts/secretlastpass.txt +++ /dev/null @@ -1,69 +0,0 @@ -[!windows] chmod 755 bin/lpass -[windows] unix2dos bin/lpass.cmd - -chezmoi secret lastpass -- show --json example.com -stdout examplelogin - -chezmoi apply -cmp $HOME/.netrc golden/.netrc - --- bin/lpass -- -#!/bin/sh - -case "$*" in -"--version") - echo "LastPass CLI v1.3.3.GIT" - ;; -"show --json example.com") - cat <<EOF -[ - { - "id": "0", - "name": "example.com", - "fullname": "Examples/example.com", - "username": "examplelogin", - "password": "examplepassword", - "last_modified_gmt": "0", - "last_touch": "0", - "group": "Examples", - "url": "", - "note": "" - } -] -EOF - ;; -*) - echo "lpass: invalid command: $*" - exit 1 -esac --- bin/lpass.cmd -- -@echo off -IF "%*" == "--version" ( - echo LastPass CLI v1.3.3.GIT -) ELSE IF "%*" == "show --json example.com" ( - echo.[ - echo. { - echo. "id": "0", - echo. "name": "example.com", - echo. "fullname": "Examples/example.com", - echo. "username": "examplelogin", - echo. "password": "examplepassword", - echo. "last_modified_gmt": "0", - echo. "last_touch": "0", - echo. "group": "Examples", - echo. "url": "", - echo. "note": "" - echo. } - echo.] -) ELSE ( - echo lpass: invalid command: %* - exit /b 1 -) --- home/user/.local/share/chezmoi/private_dot_netrc.tmpl -- -machine example.com -login {{ (index (lastpass "example.com") 0).username }} -password {{ (index (lastpass "example.com") 0).password }} --- golden/.netrc -- -machine example.com -login examplelogin -password examplepassword diff --git a/testdata/scripts/secretonepassword.txt b/testdata/scripts/secretonepassword.txt deleted file mode 100644 index 9e9d5c25e5f..00000000000 --- a/testdata/scripts/secretonepassword.txt +++ /dev/null @@ -1,33 +0,0 @@ -[!windows] chmod 755 bin/op -[windows] unix2dos bin/op.cmd - -chezmoi execute-template '{{ (onepassword "ExampleLogin").uuid }}' -stdout '^wxcplh5udshnonkzg2n4qx262y$' - -chezmoi execute-template '{{ (onepasswordDetailsFields "ExampleLogin").password.value }}' -stdout '^L8rm1JXJIE1b8YUDWq7h$' - --- bin/op -- -#!/bin/sh - -case "$*" in -"--version") - echo 1.3.0 - ;; -"get item ExampleLogin") - echo '{"uuid":"wxcplh5udshnonkzg2n4qx262y","templateUuid":"001","trashed":"N","createdAt":"2020-07-28T13:44:57Z","updatedAt":"2020-07-28T14:27:46Z","changerUuid":"VBDXOA4MPVHONK5IIJVKUQGLXM","itemVersion":2,"vaultUuid":"tscpxgi6s7c662jtqn3vmw4n5a","details":{"fields":[{"designation":"username","name":"username","type":"T","value":"exampleuser"},{"designation":"password","name":"password","type":"P","value":"L8rm1JXJIE1b8YUDWq7h"}],"notesPlain":"","passwordHistory":[],"sections":[]},"overview":{"URLs":[{"l":"website","u":"https://www.example.com/"}],"ainfo":"exampleuser","pbe":119.083926,"pgrng":true,"ps":100,"tags":[],"title":"ExampleLogin","url":"https://www.example.com/"}}' - ;; -*) - echo [ERROR] 2020/01/01 00:00:00 unknown command \"$*\" for \"op\" - exit 1 -esac --- bin/op.cmd -- -@echo off -IF "%*" == "--version" ( - echo 1.3.0 -) ELSE IF "%*" == "get item ExampleLogin" ( - echo.{"uuid":"wxcplh5udshnonkzg2n4qx262y","templateUuid":"001","trashed":"N","createdAt":"2020-07-28T13:44:57Z","updatedAt":"2020-07-28T14:27:46Z","changerUuid":"VBDXOA4MPVHONK5IIJVKUQGLXM","itemVersion":2,"vaultUuid":"tscpxgi6s7c662jtqn3vmw4n5a","details":{"fields":[{"designation":"username","name":"username","type":"T","value":"exampleuser"},{"designation":"password","name":"password","type":"P","value":"L8rm1JXJIE1b8YUDWq7h"}],"notesPlain":"","passwordHistory":[],"sections":[]},"overview":{"URLs":[{"l":"website","u":"https://www.example.com/"}],"ainfo":"exampleuser","pbe":119.083926,"pgrng":true,"ps":100,"tags":[],"title":"ExampleLogin","url":"https://www.example.com/"}} -) ELSE ( - echo.[ERROR] 2020/01/01 00:00:00 unknown command "%*" for "op" - exit /b 1 -) diff --git a/testdata/scripts/secretpass.txt b/testdata/scripts/secretpass.txt deleted file mode 100644 index 07ab46473fa..00000000000 --- a/testdata/scripts/secretpass.txt +++ /dev/null @@ -1,37 +0,0 @@ -[!windows] chmod 755 bin/pass -[windows] unix2dos bin/pass.cmd - -chezmoi -v secret pass show misc/example.com -stdout examplepassword - -chezmoi apply -cmp $HOME/.netrc golden/.netrc - --- bin/pass -- -#!/bin/sh - -case "$*" in -"show misc/example.com") - echo "examplepassword" - ;; -*) - echo "pass: invalid command: $*" - exit 1 -esac --- bin/pass.cmd -- -@echo off -IF "%*" == "show misc/example.com" ( - echo | set /p=examplepassword - exit /b 0 -) ELSE ( - echo pass: invalid command: %* - exit /b 1 -) --- home/user/.local/share/chezmoi/private_dot_netrc.tmpl -- -machine example.com -login examplelogin -password {{ pass "misc/example.com" }} --- golden/.netrc -- -machine example.com -login examplelogin -password examplepassword diff --git a/testdata/scripts/source.txt b/testdata/scripts/source.txt deleted file mode 100644 index a2339a5c830..00000000000 --- a/testdata/scripts/source.txt +++ /dev/null @@ -1,6 +0,0 @@ -[!exec:git] stop - -chezmoi init - -chezmoi source -- --version -stdout 'git version' diff --git a/testdata/scripts/sourcepath.txt b/testdata/scripts/sourcepath.txt index 62c3edf9bea..c12938ff146 100644 --- a/testdata/scripts/sourcepath.txt +++ b/testdata/scripts/sourcepath.txt @@ -3,16 +3,16 @@ mksourcedir chezmoi source-path cmpenv stdout golden/source-path -chezmoi source-path $HOME${/}.bashrc -cmpenv stdout golden/source-path-bashrc +chezmoi source-path $HOME${/}.file +cmpenv stdout golden/source-path-file -! chezmoi source-path $HOME${/}.inputrc -stderr 'file does not exist' +! chezmoi source-path $HOME${/}.newfile +stderr 'not in source state' ! chezmoi source-path $WORK${/}etc${/}passwd -stderr 'outside target directory' +stderr 'not in' -- golden/source-path -- -$HOME${/}.local${/}share${/}chezmoi --- golden/source-path-bashrc -- -$HOME${/}.local${/}share${/}chezmoi${/}dot_bashrc +$CHEZMOISOURCEDIR +-- golden/source-path-file -- +$CHEZMOISOURCEDIR/dot_file diff --git a/chezmoi2/testdata/scripts/state_unix.txt b/testdata/scripts/state_unix.txt similarity index 100% rename from chezmoi2/testdata/scripts/state_unix.txt rename to testdata/scripts/state_unix.txt diff --git a/chezmoi2/testdata/scripts/state_windows.txt b/testdata/scripts/state_windows.txt similarity index 100% rename from chezmoi2/testdata/scripts/state_windows.txt rename to testdata/scripts/state_windows.txt diff --git a/chezmoi2/testdata/scripts/status.txt b/testdata/scripts/status.txt similarity index 100% rename from chezmoi2/testdata/scripts/status.txt rename to testdata/scripts/status.txt diff --git a/chezmoi2/testdata/scripts/tilde.txt b/testdata/scripts/tilde.txt similarity index 100% rename from chezmoi2/testdata/scripts/tilde.txt rename to testdata/scripts/tilde.txt diff --git a/testdata/scripts/unmanaged.txt b/testdata/scripts/unmanaged.txt index 10d1cbab41c..dde48b07f1f 100644 --- a/testdata/scripts/unmanaged.txt +++ b/testdata/scripts/unmanaged.txt @@ -2,24 +2,22 @@ mkhomedir mksourcedir chezmoi unmanaged -cmpenv stdout golden/unmanaged +cmp stdout golden/unmanaged -[short] stop - -rm $CHEZMOISOURCEDIR/dot_bashrc +rm $CHEZMOISOURCEDIR/dot_dir chezmoi unmanaged -cmpenv stdout golden/unmanaged-bashrc +cmp stdout golden/unmanaged-dir -rm $CHEZMOISOURCEDIR/private_dot_ssh +rm $CHEZMOISOURCEDIR/dot_file chezmoi unmanaged -cmpenv stdout golden/unmanaged-bashrc-ssh +cmp stdout golden/unmanaged-dir-file -- golden/unmanaged -- -$HOME${/}.local --- golden/unmanaged-bashrc -- -$HOME${/}.bashrc -$HOME${/}.local --- golden/unmanaged-bashrc-ssh -- -$HOME${/}.bashrc -$HOME${/}.local -$HOME${/}.ssh +.local +-- golden/unmanaged-dir -- +.dir +.local +-- golden/unmanaged-dir-file -- +.dir +.file +.local diff --git a/testdata/scripts/update.txt b/testdata/scripts/update.txt index 58657d9601b..7d59b887e9b 100644 --- a/testdata/scripts/update.txt +++ b/testdata/scripts/update.txt @@ -1,6 +1,6 @@ -[windows] stop -[!exec:git] stop +[!exec:git] skip 'git not found in $PATH' +mkgitconfig mkhomedir golden mkhomedir @@ -9,46 +9,38 @@ exec git init --bare $WORK/dotfiles.git chezmoi init file://$WORK/dotfiles.git # create a commit -chezmoi add $HOME${/}.bashrc -chezmoi git add dot_bashrc -chezmoi git commit -- --message 'Add dot_bashrc' +chezmoi add $HOME${/}.file +chezmoi git add dot_file +chezmoi git commit -- --message 'Add dot_file' chezmoi git push chhome home2/user -chezmoi init --apply file://$WORK/dotfiles.git -cmp $HOME/.bashrc golden/.bashrc +mkgitconfig +chezmoi init --apply --force file://$WORK/dotfiles.git +cmp $HOME/.file golden/.file # create and push a new commit chhome home/user -edit $CHEZMOISOURCEDIR/dot_bashrc -chezmoi git -- add dot_bashrc -chezmoi git -- commit -m 'Update dot_bashrc' +edit $CHEZMOISOURCEDIR/dot_file +chezmoi git -- add dot_file +chezmoi git -- commit -m 'Update dot_file' chezmoi git -- push # test chezmoi update chhome home2/user chezmoi update -grep -count=1 '# edited' $HOME/.bashrc - -[short] stop +grep -count=1 '# edited' $HOME/.file # create and push a new commit chhome home/user -edit $CHEZMOISOURCEDIR/dot_bashrc -chezmoi git -- add dot_bashrc -chezmoi git -- commit -m 'Update dot_bashrc' +edit $CHEZMOISOURCEDIR/dot_file +chezmoi git -- add dot_file +chezmoi git -- commit -m 'Update dot_file' chezmoi git -- push # test chezmoi update --apply=false chhome home2/user chezmoi update --apply=false -grep -count=1 '# edited' $HOME/.bashrc -chezmoi apply -grep -count=2 '# edited' $HOME/.bashrc - --- home2/user/.gitconfig -- -[core] - autocrlf = false --- home3/user/.gitconfig -- -[core] - autocrlf = false +grep -count=1 '# edited' $HOME/.file +chezmoi apply --force +grep -count=2 '# edited' $HOME/.file diff --git a/testdata/scripts/updategit.txt b/testdata/scripts/updategit.txt deleted file mode 100644 index faff2a393fb..00000000000 --- a/testdata/scripts/updategit.txt +++ /dev/null @@ -1,32 +0,0 @@ -[windows] stop -[!exec:git] stop - -mkhomedir - -# create a repo -chezmoi init -chezmoi add $HOME${/}.bashrc -chezmoi git -- add dot_bashrc -chezmoi git -- commit -m 'Add dot_bashrc' - -# test chezmoi init --apply -chhome home2${/}user -chezmoi init --apply file://$WORK/home/user/.local/share/chezmoi -cmp $HOME${/}.bashrc $WORK${/}home${/}user${/}.bashrc - -# create a new commit -chhome home${/}user -edit $CHEZMOISOURCEDIR${/}dot_bashrc -chezmoi git -- add dot_bashrc -chezmoi git -- commit -m 'Update dot_bashrc' - -# test chezmoi update -chhome home2${/}user -chezmoi update -grep '# edited' $HOME${/}.bashrc - --- home/user/.bashrc -- -# contents of .bashrc --- home2/user/.gitconfig -- -[core] - autocrlf = false diff --git a/chezmoi2/testdata/scripts/vault.txt b/testdata/scripts/vault.txt similarity index 100% rename from chezmoi2/testdata/scripts/vault.txt rename to testdata/scripts/vault.txt diff --git a/testdata/scripts/verify.txt b/testdata/scripts/verify.txt index 13d6fd1e90d..baac57fcbde 100644 --- a/testdata/scripts/verify.txt +++ b/testdata/scripts/verify.txt @@ -1,5 +1,3 @@ -[windows] stop - mkhomedir golden mkhomedir mksourcedir @@ -7,47 +5,44 @@ mksourcedir # test that chezmoi verify succeeds chezmoi verify -[short] stop - # test that chezmoi verify fails when a file is added to the source state -cp golden/dot_inputrc $CHEZMOISOURCEDIR/dot_inputrc +cp golden/dot_newfile $CHEZMOISOURCEDIR/dot_newfile ! chezmoi verify -rm $CHEZMOISOURCEDIR/dot_inputrc +chezmoi forget --force $HOME${/}.newfile chezmoi verify # test that chezmoi verify fails when a file is edited -edit $HOME/.bashrc +edit $HOME/.file ! chezmoi verify -cp $CHEZMOISOURCEDIR/dot_bashrc $HOME/.bashrc +chezmoi apply --force $HOME${/}.file chezmoi verify # test that chezmoi verify fails when a file is removed from the destination directory -rm $HOME/.bashrc +rm $HOME/.file ! chezmoi verify -cp $CHEZMOISOURCEDIR/dot_bashrc $HOME/.bashrc +chezmoi apply --force $HOME${/}.file chezmoi verify # test that chezmoi verify fails when a directory is removed from the destination directory -rm $HOME/.ssh +rm $HOME/.dir ! chezmoi verify -mkdir $HOME/.ssh -chmod 700 $HOME/.ssh -cp $CHEZMOISOURCEDIR/private_dot_ssh/config $HOME/.ssh/config +mkdir $HOME/.dir +chezmoi apply --force $HOME${/}.dir chezmoi verify [windows] stop 'remaining tests use file modes' # test that chezmoi verify fails when a file's permissions are changed -chmod 777 $HOME/.bashrc +chmod 777 $HOME/.file ! chezmoi verify -chmod 644 $HOME/.bashrc +chezmoi apply --force $HOME${/}.file chezmoi verify # test that chezmoi verify fails when a dir's permissions are changed -chmod 777 $HOME/.ssh +chmod 700 $HOME/.dir ! chezmoi verify -chmod 700 $HOME/.ssh +chezmoi apply --force $HOME${/}.dir chezmoi verify --- golden/dot_inputrc -- -# contents of .inputrc +-- golden/dot_newfile -- +# contents of .newfile diff --git a/testdata/scripts/version.txt b/testdata/scripts/version.txt index 136ff427e43..9176b2fa4eb 100644 --- a/testdata/scripts/version.txt +++ b/testdata/scripts/version.txt @@ -1,2 +1,2 @@ chezmoi --version -stdout 'chezmoi version' +stdout 'chezmoi version v2\.0\.0'
megacommit
move to Go 1.16 and replace chezmoi with v2
3a171018f76c814f0e1c88136058e5627f2d8d35
2024-09-09 03:32:15
Tom Payne
docs: Add links to articles
false
diff --git a/assets/chezmoi.io/docs/links/articles.md.yaml b/assets/chezmoi.io/docs/links/articles.md.yaml index 68ca27be86b..85c837f3afa 100644 --- a/assets/chezmoi.io/docs/links/articles.md.yaml +++ b/assets/chezmoi.io/docs/links/articles.md.yaml @@ -421,6 +421,10 @@ articles: lang: TH title: 'จัดการ dotfiles ด้วย chezmoi' url: https://www.anuwong.com/blog/manage-dotfiles-with-chezmoi/ +- date: '2024-05-27' + version: 2.48.1 + title: Managing Dotfiles with Chezmoi + url: https://1729.org.uk/posts/managing-dotfiles-with-chezmoi/ - date: '2024-06-26' version: 2.49.1 title: 'Automate Your Dotfiles with Chezmoi' @@ -438,3 +442,7 @@ articles: lang: JP title: 'dotfiles管理をchezmoiに移行する' url: https://nsakki55.hatenablog.com/entry/2024/08/30/125246 +- date: '2024-09-08' + version: 2.52.1 + title: Managing dotfiles with chezmoi + url: https://stoddart.github.io/2024/09/08/managing-dotfiles-with-chezmoi.html
docs
Add links to articles
413d20de4a31cd13cd1ccb4fae2c3ba2fbe51a26
2022-10-20 01:43:47
Tom Payne
chore: Tidy up template directives
false
diff --git a/pkg/chezmoi/sourcestate.go b/pkg/chezmoi/sourcestate.go index 9546544cf48..eb70172f4a7 100644 --- a/pkg/chezmoi/sourcestate.go +++ b/pkg/chezmoi/sourcestate.go @@ -665,7 +665,7 @@ func (s *SourceState) ExecuteTemplateData(options ExecuteTemplateDataOptions) ([ templateOptions := options.TemplateOptions templateOptions.Options = append([]string(nil), s.templateOptions...) - tmpl, err := NewConfiguredTemplate(options.Name, options.Data, s.templateFuncs, templateOptions) + tmpl, err := ParseTemplate(options.Name, options.Data, s.templateFuncs, templateOptions) if err != nil { return nil, err } @@ -1254,7 +1254,7 @@ func (s *SourceState) addTemplatesDir(ctx context.Context, templatesDirAbsPath A templateRelPath := templateAbsPath.MustTrimDirPrefix(templatesDirAbsPath) name := templateRelPath.String() - tmpl, err := NewConfiguredTemplate( + tmpl, err := ParseTemplate( name, contents, s.templateFuncs, @@ -2176,25 +2176,15 @@ func (e *External) OriginString() string { return e.URL + " defined in " + e.sourceAbsPath.String() } -func NewConfiguredTemplate( - name string, - data []byte, - funcs template.FuncMap, - options ...TemplateOptions, +// ParseTemplate parses a template named name from data with the given funcs and +// templateOptions. +func ParseTemplate( + name string, data []byte, funcs template.FuncMap, templateOptions TemplateOptions, ) (*template.Template, error) { - var o TemplateOptions - - if len(options) > 0 { - o = options[0] - } else { - o = TemplateOptions{} - } - - contents := o.parseDirectives(data) - + contents := templateOptions.parseDirectives(data) return template.New(name). - Option(o.Options...). - Delims(o.LeftDelimiter, o.RightDelimiter). + Option(templateOptions.Options...). + Delims(templateOptions.LeftDelimiter, templateOptions.RightDelimiter). Funcs(funcs). Parse(string(contents)) } diff --git a/pkg/cmd/config.go b/pkg/cmd/config.go index 34c670fe214..c2f0fb4d28b 100644 --- a/pkg/cmd/config.go +++ b/pkg/cmd/config.go @@ -692,7 +692,9 @@ func (c *Config) createConfigFile(filename chezmoi.RelPath, data []byte) ([]byte } chezmoi.RecursiveMerge(funcMap, initTemplateFuncs) - t, err := chezmoi.NewConfiguredTemplate(filename.String(), data, funcMap) + t, err := chezmoi.ParseTemplate(filename.String(), data, funcMap, chezmoi.TemplateOptions{ + Options: append([]string(nil), c.Template.Options...), + }) if err != nil { return nil, err } @@ -1277,7 +1279,10 @@ func (c *Config) gitAutoCommit(status *git.Status) error { funcMap["targetRelPath"] = func(source string) string { return chezmoi.NewSourceRelPath(source).TargetRelPath(c.encryption.EncryptedSuffix()).String() } - commitMessageTmpl, err := chezmoi.NewConfiguredTemplate("commit_message", commitMessageTemplate, funcMap) + templateOptions := chezmoi.TemplateOptions{ + Options: append([]string(nil), c.Template.Options...), + } + commitMessageTmpl, err := chezmoi.ParseTemplate("commit_message", commitMessageTemplate, funcMap, templateOptions) if err != nil { return err } diff --git a/pkg/cmd/templatefuncs.go b/pkg/cmd/templatefuncs.go index e99ba7f7b47..b8868071dcc 100644 --- a/pkg/cmd/templatefuncs.go +++ b/pkg/cmd/templatefuncs.go @@ -157,7 +157,10 @@ func (c *Config) includeTemplateTemplateFunc(filename string, args ...any) strin panic(err) } - tmpl, err := chezmoi.NewConfiguredTemplate(filename, contents, c.templateFuncs) + templateOptions := chezmoi.TemplateOptions{ + Options: append([]string(nil), c.Template.Options...), + } + tmpl, err := chezmoi.ParseTemplate(filename, contents, c.templateFuncs, templateOptions) if err != nil { panic(err) }
chore
Tidy up template directives
787b1d608f667024d5305d9dd421e254b481225b
2022-05-10 00:16:24
Tom Payne
chore: Update dependencies
false
diff --git a/go.mod b/go.mod index 990e386b118..9b30b36ec09 100644 --- a/go.mod +++ b/go.mod @@ -11,12 +11,12 @@ require ( github.com/coreos/go-semver v0.3.0 github.com/go-git/go-git/v5 v5.4.2 github.com/google/go-github/v44 v44.0.0 - github.com/google/gops v0.3.22 + github.com/google/gops v0.3.23 github.com/google/renameio/v2 v2.0.0 github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 github.com/mitchellh/mapstructure v1.5.0 github.com/muesli/combinator v0.3.0 - github.com/pelletier/go-toml v1.9.5 + github.com/pelletier/go-toml/v2 v2.0.0 github.com/rogpeppe/go-internal v1.8.1 github.com/rs/zerolog v1.26.1 github.com/sergi/go-diff v1.1.0 @@ -34,7 +34,7 @@ require ( go.uber.org/multierr v1.8.0 golang.org/x/oauth2 v0.0.0-20220411215720-9780585627b5 golang.org/x/sync v0.0.0-20210220032951-036812b2e83c - golang.org/x/sys v0.0.0-20220429233432-b5fbb4746d32 + golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6 golang.org/x/term v0.0.0-20220411215600-e5f449aeb171 gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b howett.net/plist v1.0.0 @@ -80,7 +80,7 @@ require ( github.com/muesli/reflow v0.3.0 // indirect github.com/muesli/termenv v0.11.0 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect - github.com/pelletier/go-toml/v2 v2.0.0 // indirect + github.com/pelletier/go-toml v1.9.5 // indirect github.com/peterbourgon/diskv v2.0.1+incompatible // indirect github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e // indirect github.com/pkg/errors v0.9.1 // indirect @@ -96,7 +96,7 @@ require ( github.com/yuin/goldmark v1.4.12 // indirect github.com/yuin/goldmark-emoji v1.0.1 // indirect go.uber.org/atomic v1.9.0 // indirect - golang.org/x/crypto v0.0.0-20220427172511-eb4f295cb31f // indirect + golang.org/x/crypto v0.0.0-20220507011949-2cf3adece122 // indirect golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4 // indirect golang.org/x/text v0.3.7 // indirect google.golang.org/appengine v1.6.7 // indirect diff --git a/go.sum b/go.sum index 5d8c7a2e0c7..57bcdc82e67 100644 --- a/go.sum +++ b/go.sum @@ -273,8 +273,8 @@ github.com/google/go-github/v44 v44.0.0/go.mod h1:CqZYQRxOcb81M+ufZB7duWNS0lFfas github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8= github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/gops v0.3.22 h1:lyvhDxfPLHAOR2xIYwjPhN387qHxyU21Sk9sz/GhmhQ= -github.com/google/gops v0.3.22/go.mod h1:7diIdLsqpCihPSX3fQagksT/Ku/y4RL9LHTlKyEUDl8= +github.com/google/gops v0.3.23 h1:OjsHRINl5FiIyTc8jivIg4UN0GY6Nh32SL8KRbl8GQo= +github.com/google/gops v0.3.23/go.mod h1:7diIdLsqpCihPSX3fQagksT/Ku/y4RL9LHTlKyEUDl8= github.com/google/martian v2.1.0+incompatible h1:/CP5g8u/VJHijgedC/Legn3BAbAaWPgecwXBIDzw5no= github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= @@ -635,8 +635,8 @@ golang.org/x/crypto v0.0.0-20210817164053-32db794688a5/go.mod h1:GvvjBRRGRdwPK5y golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20211215165025-cf75a172585e/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8= golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/crypto v0.0.0-20220427172511-eb4f295cb31f h1:OeJjE6G4dgCY4PIXvIRQbE8+RX+uXZyGhUy/ksMGJoc= -golang.org/x/crypto v0.0.0-20220427172511-eb4f295cb31f/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.0.0-20220507011949-2cf3adece122 h1:NvGWuYG8dkDHFSKksI1P9faiVJ9rayE6l0+ouWVIDs8= +golang.org/x/crypto v0.0.0-20220507011949-2cf3adece122/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -842,8 +842,8 @@ golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220227234510-4e6760a101f9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220328115105-d36c6a25d886/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220429233432-b5fbb4746d32 h1:Js08h5hqB5xyWR789+QqueR6sDE8mk+YvpETZ+F6X9Y= -golang.org/x/sys v0.0.0-20220429233432-b5fbb4746d32/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6 h1:nonptSpoQ4vQjyraW20DXPAglgQfVnM9ZC6MmNLMR60= +golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= diff --git a/pkg/chezmoi/duration.go b/pkg/chezmoi/duration.go new file mode 100644 index 00000000000..016917d9716 --- /dev/null +++ b/pkg/chezmoi/duration.go @@ -0,0 +1,15 @@ +package chezmoi + +import "time" + +// A Duration is a time.Duration that implements encoding.TextUnmarshaler. +type Duration time.Duration + +func (d *Duration) UnmarshalText(data []byte) error { + timeDuration, err := time.ParseDuration(string(data)) + if err != nil { + return err + } + *d = Duration(timeDuration) + return nil +} diff --git a/pkg/chezmoi/format.go b/pkg/chezmoi/format.go index d1359a3ab97..5dafae4c14b 100644 --- a/pkg/chezmoi/format.go +++ b/pkg/chezmoi/format.go @@ -7,7 +7,7 @@ import ( "io" "strings" - "github.com/pelletier/go-toml" // FIXME upgrade to v2 when https://github.com/pelletier/go-toml/issues/767 is fixed + "github.com/pelletier/go-toml/v2" "go.uber.org/multierr" "gopkg.in/yaml.v3" ) diff --git a/pkg/chezmoi/sourcestate.go b/pkg/chezmoi/sourcestate.go index 0c7e3439c42..fb92b7f8d88 100644 --- a/pkg/chezmoi/sourcestate.go +++ b/pkg/chezmoi/sourcestate.go @@ -62,9 +62,9 @@ type External struct { Pull struct { Args []string `json:"args" toml:"args" yaml:"args"` } `json:"pull" toml:"pull" yaml:"pull"` - RefreshPeriod time.Duration `json:"refreshPeriod" toml:"refreshPeriod" yaml:"refreshPeriod"` - StripComponents int `json:"stripComponents" toml:"stripComponents" yaml:"stripComponents"` - URL string `json:"url" toml:"url" yaml:"url"` + RefreshPeriod Duration `json:"refreshPeriod" toml:"refreshPeriod" yaml:"refreshPeriod"` + StripComponents int `json:"stripComponents" toml:"stripComponents" yaml:"stripComponents"` + URL string `json:"url" toml:"url" yaml:"url"` origin string } @@ -1329,7 +1329,7 @@ func (s *SourceState) getExternalDataRaw( var externalCacheEntry externalCacheEntry if err := externalCacheFormat.Unmarshal(data, &externalCacheEntry); err == nil { if externalCacheEntry.URL == external.URL { - if external.RefreshPeriod == 0 || externalCacheEntry.Time.Add(external.RefreshPeriod).After(now) { + if external.RefreshPeriod == 0 || externalCacheEntry.Time.Add(time.Duration(external.RefreshPeriod)).After(now) { return externalCacheEntry.Data, nil } } diff --git a/pkg/chezmoi/sourcestate_test.go b/pkg/chezmoi/sourcestate_test.go index 85f32ff3daa..84fea56a6e6 100644 --- a/pkg/chezmoi/sourcestate_test.go +++ b/pkg/chezmoi/sourcestate_test.go @@ -1528,7 +1528,7 @@ func TestSourceStateReadExternalCache(t *testing.T) { NewRelPath(".dir"): { Type: "archive", URL: httpServer.URL + "/archive.tar", - RefreshPeriod: 1 * time.Minute, + RefreshPeriod: Duration(1 * time.Minute), origin: "/home/user/.local/share/chezmoi/.chezmoiexternal.yaml", }, }, s.externals) diff --git a/pkg/chezmoi/sourcestateentry.go b/pkg/chezmoi/sourcestateentry.go index 89056dd174b..63614bbc514 100644 --- a/pkg/chezmoi/sourcestateentry.go +++ b/pkg/chezmoi/sourcestateentry.go @@ -3,7 +3,6 @@ package chezmoi import ( "encoding/hex" "os/exec" - "time" "github.com/rs/zerolog" @@ -27,7 +26,7 @@ type SourceStateCommand struct { external bool origin string forceRefresh bool - refreshPeriod time.Duration + refreshPeriod Duration } // A SourceStateDir represents the state of a directory in the source state. diff --git a/pkg/chezmoi/targetstateentry.go b/pkg/chezmoi/targetstateentry.go index d6a3e1257f2..2cd74d9cf2a 100644 --- a/pkg/chezmoi/targetstateentry.go +++ b/pkg/chezmoi/targetstateentry.go @@ -22,7 +22,7 @@ type TargetStateEntry interface { type TargetStateModifyDirWithCmd struct { cmd *exec.Cmd forceRefresh bool - refreshPeriod time.Duration + refreshPeriod Duration } // A TargetStateDir represents the state of a directory in the target state. @@ -126,7 +126,7 @@ func (t *TargetStateModifyDirWithCmd) SkipApply(persistentState PersistentState, if t.refreshPeriod == 0 { return true, nil } - return time.Since(modifyDirWithCmdState.RunAt) < t.refreshPeriod, nil + return time.Since(modifyDirWithCmdState.RunAt) < time.Duration(t.refreshPeriod), nil } }
chore
Update dependencies
08373052be27b30550ee2bba146fef9da928886c
2024-11-08 13:52:35
Tom Payne
docs: Add link to article
false
diff --git a/assets/chezmoi.io/docs/links/articles.md.yaml b/assets/chezmoi.io/docs/links/articles.md.yaml index 285686ce5c3..2a9c7cbc205 100644 --- a/assets/chezmoi.io/docs/links/articles.md.yaml +++ b/assets/chezmoi.io/docs/links/articles.md.yaml @@ -458,3 +458,7 @@ articles: version: 2.52.3 title: How I manage Neovim configuration with Chezmoi url: https://www.lorenzobettini.it/2024/10/how-i-manage-neovim-configuration-with-chezmoi/ +- date: '2024-11-07' + version: 2.53.1 + title: 'dotfiles management: chezmoi' + url: https://blg.gkr.one/20241107-chezmoi/
docs
Add link to article
77ab1c9d472c23373e2d64d21d9f7bd14be823a7
2022-01-29 23:06:47
Tom Payne
chore: Improve function name
false
diff --git a/pkg/cmd/bitwardentemplatefuncs.go b/pkg/cmd/bitwardentemplatefuncs.go index bd5e75c4abe..149f2eb3e30 100644 --- a/pkg/cmd/bitwardentemplatefuncs.go +++ b/pkg/cmd/bitwardentemplatefuncs.go @@ -15,7 +15,7 @@ type bitwardenConfig struct { func (c *Config) bitwardenAttachmentTemplateFunc(name, itemid string) string { output, err := c.bitwardenOutput([]string{"attachment", name, "--itemid", itemid, "--raw"}) if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return "" } return string(output) @@ -24,14 +24,14 @@ func (c *Config) bitwardenAttachmentTemplateFunc(name, itemid string) string { func (c *Config) bitwardenFieldsTemplateFunc(args ...string) map[string]interface{} { output, err := c.bitwardenOutput(args) if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return nil } var data struct { Fields []map[string]interface{} `json:"fields"` } if err := json.Unmarshal(output, &data); err != nil { - returnTemplateError(fmt.Errorf("%s: %w\n%s", shellQuoteCommand(c.Bitwarden.Command, args), err, output)) + raiseTemplateError(fmt.Errorf("%s: %w\n%s", shellQuoteCommand(c.Bitwarden.Command, args), err, output)) return nil } result := make(map[string]interface{}) @@ -46,12 +46,12 @@ func (c *Config) bitwardenFieldsTemplateFunc(args ...string) map[string]interfac func (c *Config) bitwardenTemplateFunc(args ...string) map[string]interface{} { output, err := c.bitwardenOutput(args) if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return nil } var data map[string]interface{} if err := json.Unmarshal(output, &data); err != nil { - returnTemplateError(fmt.Errorf("%s: %w\n%s", shellQuoteCommand(c.Bitwarden.Command, args), err, output)) + raiseTemplateError(fmt.Errorf("%s: %w\n%s", shellQuoteCommand(c.Bitwarden.Command, args), err, output)) return nil } return data diff --git a/pkg/cmd/encryptiontemplatefuncs.go b/pkg/cmd/encryptiontemplatefuncs.go index 655bac43223..77e205b89bb 100644 --- a/pkg/cmd/encryptiontemplatefuncs.go +++ b/pkg/cmd/encryptiontemplatefuncs.go @@ -3,7 +3,7 @@ package cmd func (c *Config) decryptTemplateFunc(ciphertext string) string { plaintextBytes, err := c.encryption.Decrypt([]byte(ciphertext)) if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return "" } return string(plaintextBytes) @@ -12,7 +12,7 @@ func (c *Config) decryptTemplateFunc(ciphertext string) string { func (c *Config) encryptTemplateFunc(plaintext string) string { ciphertextBytes, err := c.encryption.Encrypt([]byte(plaintext)) if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return "" } return string(ciphertextBytes) diff --git a/pkg/cmd/executetemplatecmd.go b/pkg/cmd/executetemplatecmd.go index 63370d2c4f8..fd7848b6429 100644 --- a/pkg/cmd/executetemplatecmd.go +++ b/pkg/cmd/executetemplatecmd.go @@ -72,7 +72,7 @@ func (c *Config) runExecuteTemplateCmd(cmd *cobra.Command, args []string) error return args[0] default: err := fmt.Errorf("want 1 or 2 arguments, got %d", len(args)+1) - returnTemplateError(err) + raiseTemplateError(err) return false } }, @@ -87,7 +87,7 @@ func (c *Config) runExecuteTemplateCmd(cmd *cobra.Command, args []string) error return args[0] default: err := fmt.Errorf("want 1 or 2 arguments, got %d", len(args)+1) - returnTemplateError(err) + raiseTemplateError(err) return 0 } }, @@ -105,7 +105,7 @@ func (c *Config) runExecuteTemplateCmd(cmd *cobra.Command, args []string) error return args[0] default: err := fmt.Errorf("want 1 or 2 arguments, got %d", len(args)+1) - returnTemplateError(err) + raiseTemplateError(err) return "" } }, diff --git a/pkg/cmd/githubtemplatefuncs.go b/pkg/cmd/githubtemplatefuncs.go index 3ca1867a9e4..7f9f7e60fce 100644 --- a/pkg/cmd/githubtemplatefuncs.go +++ b/pkg/cmd/githubtemplatefuncs.go @@ -24,7 +24,7 @@ func (c *Config) gitHubKeysTemplateFunc(user string) []*github.Key { httpClient, err := c.getHTTPClient() if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return nil } gitHubClient := newGitHubClient(ctx, httpClient) @@ -36,7 +36,7 @@ func (c *Config) gitHubKeysTemplateFunc(user string) []*github.Key { for { keys, resp, err := gitHubClient.Users.ListKeys(ctx, user, opts) if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return nil } allKeys = append(allKeys, keys...) @@ -56,7 +56,7 @@ func (c *Config) gitHubKeysTemplateFunc(user string) []*github.Key { func (c *Config) gitHubLatestReleaseTemplateFunc(userRepo string) *github.RepositoryRelease { user, repo, ok := chezmoi.CutString(userRepo, "/") if !ok { - returnTemplateError(fmt.Errorf("%s: not a user/repo", userRepo)) + raiseTemplateError(fmt.Errorf("%s: not a user/repo", userRepo)) return nil } @@ -69,14 +69,14 @@ func (c *Config) gitHubLatestReleaseTemplateFunc(userRepo string) *github.Reposi httpClient, err := c.getHTTPClient() if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return nil } gitHubClient := newGitHubClient(ctx, httpClient) release, _, err := gitHubClient.Repositories.GetLatestRelease(ctx, user, repo) if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return nil } diff --git a/pkg/cmd/gopasstemplatefuncs.go b/pkg/cmd/gopasstemplatefuncs.go index f3def98c7c9..6d166b9d2f0 100644 --- a/pkg/cmd/gopasstemplatefuncs.go +++ b/pkg/cmd/gopasstemplatefuncs.go @@ -29,7 +29,7 @@ type gopassConfig struct { func (c *Config) gopassTemplateFunc(id string) string { if !c.Gopass.versionOK { if err := c.gopassVersionCheck(); err != nil { - returnTemplateError(err) + raiseTemplateError(err) return "" } c.Gopass.versionOK = true @@ -42,7 +42,7 @@ func (c *Config) gopassTemplateFunc(id string) string { args := []string{"show", "--password", id} output, err := c.gopassOutput(args...) if err != nil { - returnTemplateError(fmt.Errorf("%s: %w", shellQuoteCommand(c.Gopass.Command, args), err)) + raiseTemplateError(fmt.Errorf("%s: %w", shellQuoteCommand(c.Gopass.Command, args), err)) return "" } @@ -60,7 +60,7 @@ func (c *Config) gopassTemplateFunc(id string) string { func (c *Config) gopassRawTemplateFunc(id string) string { if !c.Gopass.versionOK { if err := c.gopassVersionCheck(); err != nil { - returnTemplateError(err) + raiseTemplateError(err) return "" } c.Gopass.versionOK = true @@ -73,7 +73,7 @@ func (c *Config) gopassRawTemplateFunc(id string) string { args := []string{"show", "--noparsing", id} output, err := c.gopassOutput(args...) if err != nil { - returnTemplateError(fmt.Errorf("%s: %w", shellQuoteCommand(c.Gopass.Command, args), err)) + raiseTemplateError(fmt.Errorf("%s: %w", shellQuoteCommand(c.Gopass.Command, args), err)) return "" } diff --git a/pkg/cmd/inittemplatefuncs.go b/pkg/cmd/inittemplatefuncs.go index 7193c99b94a..a3715037bdf 100644 --- a/pkg/cmd/inittemplatefuncs.go +++ b/pkg/cmd/inittemplatefuncs.go @@ -12,7 +12,7 @@ import ( ) func (c *Config) exitInitTemplateFunc(code int) string { - returnTemplateError(chezmoi.ExitCodeError(code)) + raiseTemplateError(chezmoi.ExitCodeError(code)) return "" } @@ -21,7 +21,7 @@ func (c *Config) promptBoolInitTemplateFunc(field string, args ...bool) bool { case 0: value, err := parseBool(c.promptStringInitTemplateFunc(field)) if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return false } return value @@ -33,13 +33,13 @@ func (c *Config) promptBoolInitTemplateFunc(field string, args ...bool) bool { } value, err := parseBool(valueStr) if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return false } return value default: err := fmt.Errorf("want 1 or 2 arguments, got %d", len(args)+1) - returnTemplateError(err) + raiseTemplateError(err) return false } } @@ -49,7 +49,7 @@ func (c *Config) promptIntInitTemplateFunc(field string, args ...int64) int64 { case 0: value, err := strconv.ParseInt(c.promptStringInitTemplateFunc(field), 10, 64) if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return 0 } return value @@ -61,13 +61,13 @@ func (c *Config) promptIntInitTemplateFunc(field string, args ...int64) int64 { } value, err := strconv.ParseInt(valueStr, 10, 64) if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return 0 } return value default: err := fmt.Errorf("want 1 or 2 arguments, got %d", len(args)+1) - returnTemplateError(err) + raiseTemplateError(err) return 0 } } @@ -77,7 +77,7 @@ func (c *Config) promptStringInitTemplateFunc(prompt string, args ...string) str case 0: value, err := c.readLine(prompt + "? ") if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return "" } return strings.TrimSpace(value) @@ -86,7 +86,7 @@ func (c *Config) promptStringInitTemplateFunc(prompt string, args ...string) str promptStr := prompt + " (default " + strconv.Quote(defaultStr) + ")? " switch value, err := c.readLine(promptStr); { case err != nil: - returnTemplateError(err) + raiseTemplateError(err) return "" case value == "": return defaultStr @@ -95,7 +95,7 @@ func (c *Config) promptStringInitTemplateFunc(prompt string, args ...string) str } default: err := fmt.Errorf("want 1 or 2 arguments, got %d", len(args)+1) - returnTemplateError(err) + raiseTemplateError(err) return "" } } @@ -111,7 +111,7 @@ func (c *Config) stdinIsATTYInitTemplateFunc() bool { func (c *Config) writeToStdout(args ...string) string { for _, arg := range args { if _, err := c.stdout.Write([]byte(arg)); err != nil { - returnTemplateError(err) + raiseTemplateError(err) return "" } } diff --git a/pkg/cmd/keepassxctemplatefuncs.go b/pkg/cmd/keepassxctemplatefuncs.go index da91f3c01cf..09794bed78b 100644 --- a/pkg/cmd/keepassxctemplatefuncs.go +++ b/pkg/cmd/keepassxctemplatefuncs.go @@ -39,7 +39,7 @@ func (c *Config) keepassxcTemplateFunc(entry string) map[string]string { } if c.Keepassxc.Database.Empty() { - returnTemplateError(errors.New("keepassxc.database not set")) + raiseTemplateError(errors.New("keepassxc.database not set")) return nil } @@ -47,7 +47,7 @@ func (c *Config) keepassxcTemplateFunc(entry string) map[string]string { args := []string{"show"} version, err := c.keepassxcVersion() if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return nil } if version.Compare(keepassxcNeedShowProtectedArgVersion) >= 0 { @@ -57,13 +57,13 @@ func (c *Config) keepassxcTemplateFunc(entry string) map[string]string { args = append(args, c.Keepassxc.Database.String(), entry) output, err := c.keepassxcOutput(name, args) if err != nil { - returnTemplateError(fmt.Errorf("%s: %w", shellQuoteCommand(name, args), err)) + raiseTemplateError(fmt.Errorf("%s: %w", shellQuoteCommand(name, args), err)) return nil } data, err := keypassxcParseOutput(output) if err != nil { - returnTemplateError(fmt.Errorf("%s: %w", shellQuoteCommand(name, args), err)) + raiseTemplateError(fmt.Errorf("%s: %w", shellQuoteCommand(name, args), err)) return nil } @@ -85,7 +85,7 @@ func (c *Config) keepassxcAttributeTemplateFunc(entry, attribute string) string } if c.Keepassxc.Database.Empty() { - returnTemplateError(errors.New("keepassxc.database not set")) + raiseTemplateError(errors.New("keepassxc.database not set")) return "" } @@ -93,7 +93,7 @@ func (c *Config) keepassxcAttributeTemplateFunc(entry, attribute string) string args := []string{"show", "--attributes", attribute, "--quiet"} version, err := c.keepassxcVersion() if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return "" } if version.Compare(keepassxcNeedShowProtectedArgVersion) >= 0 { @@ -103,7 +103,7 @@ func (c *Config) keepassxcAttributeTemplateFunc(entry, attribute string) string args = append(args, c.Keepassxc.Database.String(), entry) output, err := c.keepassxcOutput(name, args) if err != nil { - returnTemplateError(fmt.Errorf("%s: %w", shellQuoteCommand(name, args), err)) + raiseTemplateError(fmt.Errorf("%s: %w", shellQuoteCommand(name, args), err)) return "" } @@ -153,6 +153,7 @@ func (c *Config) keepassxcVersion() (*semver.Version, error) { if c.Keepassxc.version != nil { return c.Keepassxc.version, nil } + name := c.Keepassxc.Command args := []string{"--version"} cmd := exec.Command(name, args...) @@ -160,6 +161,7 @@ func (c *Config) keepassxcVersion() (*semver.Version, error) { if err != nil { return nil, fmt.Errorf("%s: %w", shellQuoteCommand(name, args), err) } + c.Keepassxc.version, err = semver.NewVersion(string(bytes.TrimSpace(output))) if err != nil { return nil, fmt.Errorf("cannot parse version %s: %w", output, err) diff --git a/pkg/cmd/keyringtemplatefuncs.go b/pkg/cmd/keyringtemplatefuncs.go index 0d030a36d13..95d6f4b276d 100644 --- a/pkg/cmd/keyringtemplatefuncs.go +++ b/pkg/cmd/keyringtemplatefuncs.go @@ -25,7 +25,7 @@ func (c *Config) keyringTemplateFunc(service, user string) string { } password, err := keyring.Get(service, user) if err != nil { - returnTemplateError(fmt.Errorf("%s %s: %w", service, user, err)) + raiseTemplateError(fmt.Errorf("%s %s: %w", service, user, err)) return "" } diff --git a/pkg/cmd/lastpasstemplatefuncs.go b/pkg/cmd/lastpasstemplatefuncs.go index 4caf5592f8e..06e6128c8f8 100644 --- a/pkg/cmd/lastpasstemplatefuncs.go +++ b/pkg/cmd/lastpasstemplatefuncs.go @@ -32,14 +32,14 @@ type lastpassConfig struct { func (c *Config) lastpassTemplateFunc(id string) []map[string]interface{} { data, err := c.lastpassData(id) if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return nil } for _, d := range data { if note, ok := d["note"].(string); ok { d["note"], err = lastpassParseNote(note) if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return nil } } @@ -50,7 +50,7 @@ func (c *Config) lastpassTemplateFunc(id string) []map[string]interface{} { func (c *Config) lastpassRawTemplateFunc(id string) []map[string]interface{} { data, err := c.lastpassData(id) if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return nil } return data diff --git a/pkg/cmd/onepasswordtemplatefuncs.go b/pkg/cmd/onepasswordtemplatefuncs.go index 1720f2312d0..925c9bddbde 100644 --- a/pkg/cmd/onepasswordtemplatefuncs.go +++ b/pkg/cmd/onepasswordtemplatefuncs.go @@ -30,25 +30,25 @@ type onePasswordItem struct { func (c *Config) onepasswordTemplateFunc(args ...string) map[string]interface{} { sessionToken, err := c.onepasswordGetOrRefreshSessionToken(args) if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return nil } onepasswordArgs, err := onepasswordArgs([]string{"get", "item"}, args) if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return nil } output, err := c.onepasswordOutput(onepasswordArgs, sessionToken) if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return nil } var data map[string]interface{} if err := json.Unmarshal(output, &data); err != nil { - returnTemplateError(fmt.Errorf("%s: %w\n%s", shellQuoteCommand(c.Onepassword.Command, onepasswordArgs), err, output)) + raiseTemplateError(fmt.Errorf("%s: %w\n%s", shellQuoteCommand(c.Onepassword.Command, onepasswordArgs), err, output)) return nil } return data @@ -57,7 +57,7 @@ func (c *Config) onepasswordTemplateFunc(args ...string) map[string]interface{} func (c *Config) onepasswordDetailsFieldsTemplateFunc(args ...string) map[string]interface{} { onepasswordItem, err := c.onepasswordItem(args...) if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return nil } @@ -73,19 +73,19 @@ func (c *Config) onepasswordDetailsFieldsTemplateFunc(args ...string) map[string func (c *Config) onepasswordDocumentTemplateFunc(args ...string) string { sessionToken, err := c.onepasswordGetOrRefreshSessionToken(args) if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return "" } onepasswordArgs, err := onepasswordArgs([]string{"get", "document"}, args) if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return "" } output, err := c.onepasswordOutput(onepasswordArgs, sessionToken) if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return "" } return string(output) @@ -94,7 +94,7 @@ func (c *Config) onepasswordDocumentTemplateFunc(args ...string) string { func (c *Config) onepasswordItemFieldsTemplateFunc(args ...string) map[string]interface{} { onepasswordItem, err := c.onepasswordItem(args...) if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return nil } diff --git a/pkg/cmd/passtemplatefuncs.go b/pkg/cmd/passtemplatefuncs.go index 9d85f41a664..cbdc4a8778d 100644 --- a/pkg/cmd/passtemplatefuncs.go +++ b/pkg/cmd/passtemplatefuncs.go @@ -16,7 +16,7 @@ type passConfig struct { func (c *Config) passTemplateFunc(id string) string { output, err := c.passOutput(id) if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return "" } firstLine, _, _ := chezmoi.CutBytes(output, []byte{'\n'}) @@ -26,7 +26,7 @@ func (c *Config) passTemplateFunc(id string) string { func (c *Config) passFieldsTemplateFunc(id string) map[string]string { output, err := c.passOutput(id) if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return nil } @@ -42,7 +42,7 @@ func (c *Config) passFieldsTemplateFunc(id string) map[string]string { func (c *Config) passRawTemplateFunc(id string) string { output, err := c.passOutput(id) if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return "" } return string(output) diff --git a/pkg/cmd/secrettemplatefuncs.go b/pkg/cmd/secrettemplatefuncs.go index d5e84593b36..c48e62f5c0a 100644 --- a/pkg/cmd/secrettemplatefuncs.go +++ b/pkg/cmd/secrettemplatefuncs.go @@ -26,7 +26,7 @@ func (c *Config) secretTemplateFunc(args ...string) string { cmd.Stderr = c.stderr output, err := c.baseSystem.IdempotentCmdOutput(cmd) if err != nil { - returnTemplateError(fmt.Errorf("%s: %w\n%s", shellQuoteCommand(name, args), err, output)) + raiseTemplateError(fmt.Errorf("%s: %w\n%s", shellQuoteCommand(name, args), err, output)) return "" } @@ -51,13 +51,13 @@ func (c *Config) secretJSONTemplateFunc(args ...string) interface{} { cmd.Stderr = c.stderr output, err := c.baseSystem.IdempotentCmdOutput(cmd) if err != nil { - returnTemplateError(fmt.Errorf("%s: %w\n%s", shellQuoteCommand(name, args), err, output)) + raiseTemplateError(fmt.Errorf("%s: %w\n%s", shellQuoteCommand(name, args), err, output)) return nil } var value interface{} if err := json.Unmarshal(output, &value); err != nil { - returnTemplateError(fmt.Errorf("%s: %w\n%s", shellQuoteCommand(name, args), err, output)) + raiseTemplateError(fmt.Errorf("%s: %w\n%s", shellQuoteCommand(name, args), err, output)) return nil } diff --git a/pkg/cmd/templatefuncs.go b/pkg/cmd/templatefuncs.go index 36ce561e169..5d938df1530 100644 --- a/pkg/cmd/templatefuncs.go +++ b/pkg/cmd/templatefuncs.go @@ -21,7 +21,7 @@ type ioregData struct { func (c *Config) fromYamlTemplateFunc(s string) interface{} { var data interface{} if err := chezmoi.FormatYAML.Unmarshal([]byte(s), &data); err != nil { - returnTemplateError(err) + raiseTemplateError(err) return nil } return data @@ -33,14 +33,14 @@ func (c *Config) includeTemplateFunc(filename string) string { var err error absPath, err = chezmoi.NewAbsPathFromExtPath(filename, c.homeDirAbsPath) if err != nil { - returnTemplateError(err) + raiseTemplateError(err) } } else { absPath = c.SourceDirAbsPath.JoinString(filename) } contents, err := c.fileSystem.ReadFile(absPath.String()) if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return "" } return string(contents) @@ -58,13 +58,13 @@ func (c *Config) ioregTemplateFunc() map[string]interface{} { cmd := exec.Command("ioreg", "-a", "-l") output, err := c.baseSystem.IdempotentCmdOutput(cmd) if err != nil { - returnTemplateError(fmt.Errorf("ioreg: %w", err)) + raiseTemplateError(fmt.Errorf("ioreg: %w", err)) return nil } var value map[string]interface{} if _, err := plist.Unmarshal(output, &value); err != nil { - returnTemplateError(fmt.Errorf("ioreg: %w", err)) + raiseTemplateError(fmt.Errorf("ioreg: %w", err)) return nil } c.ioregData.value = value @@ -84,7 +84,7 @@ func (c *Config) lookPathTemplateFunc(file string) string { case errors.Is(err, fs.ErrNotExist): return "" default: - returnTemplateError(err) + raiseTemplateError(err) return "" } } @@ -92,7 +92,7 @@ func (c *Config) lookPathTemplateFunc(file string) string { func (c *Config) mozillaInstallHashTemplateFunc(path string) string { mozillaInstallHash, err := mozillainstallhash.MozillaInstallHash(path) if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return "" } return mozillaInstallHash @@ -101,7 +101,7 @@ func (c *Config) mozillaInstallHashTemplateFunc(path string) string { func (c *Config) outputTemplateFunc(name string, args ...string) string { output, err := c.baseSystem.IdempotentCmdOutput(exec.Command(name, args...)) if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return "" } // FIXME we should be able to return output directly, but @@ -123,7 +123,7 @@ func (c *Config) statTemplateFunc(name string) interface{} { case errors.Is(err, fs.ErrNotExist): return nil default: - returnTemplateError(err) + raiseTemplateError(err) return nil } } @@ -131,12 +131,12 @@ func (c *Config) statTemplateFunc(name string) interface{} { func (c *Config) toYamlTemplateFunc(data interface{}) string { yaml, err := chezmoi.FormatYAML.Marshal(data) if err != nil { - returnTemplateError(err) + raiseTemplateError(err) return "" } return string(yaml) } -func returnTemplateError(err error) { +func raiseTemplateError(err error) { panic(err) } diff --git a/pkg/cmd/vaulttemplatefuncs.go b/pkg/cmd/vaulttemplatefuncs.go index 023c32280e0..9a00a5fc0c9 100644 --- a/pkg/cmd/vaulttemplatefuncs.go +++ b/pkg/cmd/vaulttemplatefuncs.go @@ -23,13 +23,13 @@ func (c *Config) vaultTemplateFunc(key string) interface{} { cmd.Stderr = c.stderr output, err := c.baseSystem.IdempotentCmdOutput(cmd) if err != nil { - returnTemplateError(fmt.Errorf("%s: %w\n%s", shellQuoteCommand(name, args), err, output)) + raiseTemplateError(fmt.Errorf("%s: %w\n%s", shellQuoteCommand(name, args), err, output)) return nil } var data interface{} if err := json.Unmarshal(output, &data); err != nil { - returnTemplateError(fmt.Errorf("%s: %w\n%s", shellQuoteCommand(name, args), err, output)) + raiseTemplateError(fmt.Errorf("%s: %w\n%s", shellQuoteCommand(name, args), err, output)) return nil }
chore
Improve function name
e2d8c82ff03d1eda0727efe8951e75c0a63d2856
2023-07-12 14:15:09
Tom Payne
chore: Build with Go 1.20.6
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 5d98424bd7a..935ef6d0eee 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -11,7 +11,7 @@ on: env: ACTIONLINT_VERSION: 1.6.25 AGE_VERSION: 1.1.1 - GO_VERSION: 1.20.5 + GO_VERSION: 1.20.6 GOFUMPT_VERSION: 0.4.0 GOLANGCI_LINT_VERSION: 1.53.3 GOLINES_VERSION: 0.11.0
chore
Build with Go 1.20.6
590cbeac8616f54fd7df1e4879550de2b03ac1f1
2021-12-03 20:34:59
Tom Payne
chore: Build with Go 1.17.4
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 15264013cba..846f0d0daa4 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -10,7 +10,7 @@ on: - v* env: AGE_VERSION: 1.0.0 - GO_VERSION: 1.17.3 + GO_VERSION: 1.17.4 GOLANGCI_LINT_VERSION: 1.43.0 jobs: changes:
chore
Build with Go 1.17.4
0fb4392222092155e0d830f15d8a353abcd6983e
2024-10-22 21:50:17
Ruslan Sayfutdinov
docs: Split "Special file and directories"
false
diff --git a/assets/chezmoi.io/docs/reference/special-directories/chezmoidata.md b/assets/chezmoi.io/docs/reference/special-directories/chezmoidata.md new file mode 100644 index 00000000000..4ff3a72eaf5 --- /dev/null +++ b/assets/chezmoi.io/docs/reference/special-directories/chezmoidata.md @@ -0,0 +1,3 @@ +# `.chezmoidata` + +--8<-- "special-files-and-directories/chezmoidata.md" diff --git a/assets/chezmoi.io/docs/reference/special-directories/chezmoiexternals.md b/assets/chezmoi.io/docs/reference/special-directories/chezmoiexternals.md new file mode 100644 index 00000000000..448f275519d --- /dev/null +++ b/assets/chezmoi.io/docs/reference/special-directories/chezmoiexternals.md @@ -0,0 +1,4 @@ +# `.chezmoiexternals` + +If a directory called `.chezmoiexternals` exists, then all files in this +directory are treated as [`.chezmoiexternal.<format>`](../special-files/chezmoiexternal-format.md) files. diff --git a/assets/chezmoi.io/docs/reference/special-files-and-directories/chezmoiscripts.md b/assets/chezmoi.io/docs/reference/special-directories/chezmoiscripts.md similarity index 100% rename from assets/chezmoi.io/docs/reference/special-files-and-directories/chezmoiscripts.md rename to assets/chezmoi.io/docs/reference/special-directories/chezmoiscripts.md diff --git a/assets/chezmoi.io/docs/reference/special-files-and-directories/chezmoitemplates.md b/assets/chezmoi.io/docs/reference/special-directories/chezmoitemplates.md similarity index 100% rename from assets/chezmoi.io/docs/reference/special-files-and-directories/chezmoitemplates.md rename to assets/chezmoi.io/docs/reference/special-directories/chezmoitemplates.md diff --git a/assets/chezmoi.io/docs/reference/special-directories/index.md b/assets/chezmoi.io/docs/reference/special-directories/index.md new file mode 100644 index 00000000000..85de142c6fd --- /dev/null +++ b/assets/chezmoi.io/docs/reference/special-directories/index.md @@ -0,0 +1,3 @@ +# Special directories + +--8<-- "special-files-and-directories/index.md" diff --git a/assets/chezmoi.io/docs/reference/special-files-and-directories/chezmoiexternals.md b/assets/chezmoi.io/docs/reference/special-files-and-directories/chezmoiexternals.md deleted file mode 100644 index d3cef028856..00000000000 --- a/assets/chezmoi.io/docs/reference/special-files-and-directories/chezmoiexternals.md +++ /dev/null @@ -1,4 +0,0 @@ -# `.chezmoiexternals` - -If a directory called `.chezmoiexternals` exists, then all files in this -directory are treated as `.chezmoiexternal.<format>` files. diff --git a/assets/chezmoi.io/docs/reference/special-files-and-directories/chezmoi-format-tmpl.md b/assets/chezmoi.io/docs/reference/special-files/chezmoi-format-tmpl.md similarity index 100% rename from assets/chezmoi.io/docs/reference/special-files-and-directories/chezmoi-format-tmpl.md rename to assets/chezmoi.io/docs/reference/special-files/chezmoi-format-tmpl.md diff --git a/assets/chezmoi.io/docs/reference/special-files/chezmoidata-format.md b/assets/chezmoi.io/docs/reference/special-files/chezmoidata-format.md new file mode 100644 index 00000000000..5098a2e4478 --- /dev/null +++ b/assets/chezmoi.io/docs/reference/special-files/chezmoidata-format.md @@ -0,0 +1,3 @@ +# `.chezmoidata.$FORMAT` + +--8<-- "special-files-and-directories/chezmoidata.md" diff --git a/assets/chezmoi.io/docs/reference/special-files-and-directories/chezmoiexternal-format.md b/assets/chezmoi.io/docs/reference/special-files/chezmoiexternal-format.md similarity index 98% rename from assets/chezmoi.io/docs/reference/special-files-and-directories/chezmoiexternal-format.md rename to assets/chezmoi.io/docs/reference/special-files/chezmoiexternal-format.md index 16d389ae2ae..0ea5e83af03 100644 --- a/assets/chezmoi.io/docs/reference/special-files-and-directories/chezmoiexternal-format.md +++ b/assets/chezmoi.io/docs/reference/special-files/chezmoiexternal-format.md @@ -1,8 +1,8 @@ # `.chezmoiexternal.$FORMAT{,.tmpl}` If a file called `.chezmoiexternal.$FORMAT` (with an optional `.tmpl` extension) -exists in the source state (either `~/.local/share/chezmoi` or directory defined -inside `.chezmoiroot`), it is interpreted as a list of external files and +exists anywhere in the source state (either `~/.local/share/chezmoi` or directory +defined inside `.chezmoiroot`), it is interpreted as a list of external files and archives to be included as if they were in the source state. `$FORMAT` must be one of chezmoi's supported configuration file formats, e.g. diff --git a/assets/chezmoi.io/docs/reference/special-files-and-directories/chezmoiignore.md b/assets/chezmoi.io/docs/reference/special-files/chezmoiignore.md similarity index 100% rename from assets/chezmoi.io/docs/reference/special-files-and-directories/chezmoiignore.md rename to assets/chezmoi.io/docs/reference/special-files/chezmoiignore.md diff --git a/assets/chezmoi.io/docs/reference/special-files-and-directories/chezmoiremove.md b/assets/chezmoi.io/docs/reference/special-files/chezmoiremove.md similarity index 100% rename from assets/chezmoi.io/docs/reference/special-files-and-directories/chezmoiremove.md rename to assets/chezmoi.io/docs/reference/special-files/chezmoiremove.md diff --git a/assets/chezmoi.io/docs/reference/special-files-and-directories/chezmoiroot.md b/assets/chezmoi.io/docs/reference/special-files/chezmoiroot.md similarity index 100% rename from assets/chezmoi.io/docs/reference/special-files-and-directories/chezmoiroot.md rename to assets/chezmoi.io/docs/reference/special-files/chezmoiroot.md diff --git a/assets/chezmoi.io/docs/reference/special-files-and-directories/chezmoiversion.md b/assets/chezmoi.io/docs/reference/special-files/chezmoiversion.md similarity index 100% rename from assets/chezmoi.io/docs/reference/special-files-and-directories/chezmoiversion.md rename to assets/chezmoi.io/docs/reference/special-files/chezmoiversion.md diff --git a/assets/chezmoi.io/docs/reference/special-files/index.md b/assets/chezmoi.io/docs/reference/special-files/index.md new file mode 100644 index 00000000000..0439b834c13 --- /dev/null +++ b/assets/chezmoi.io/docs/reference/special-files/index.md @@ -0,0 +1,3 @@ +# Special files + +--8<-- "special-files-and-directories/index.md" diff --git a/assets/chezmoi.io/mkdocs.yml b/assets/chezmoi.io/mkdocs.yml index bb0ac333552..26f6e4d2803 100644 --- a/assets/chezmoi.io/mkdocs.yml +++ b/assets/chezmoi.io/mkdocs.yml @@ -119,18 +119,21 @@ nav: - textconv: reference/configuration-file/textconv.md - umask: reference/configuration-file/umask.md - Warnings: reference/configuration-file/warnings.md - - Special files and directories: - - reference/special-files-and-directories/index.md - - .chezmoi.&lt;format&gt;.tmpl: reference/special-files-and-directories/chezmoi-format-tmpl.md - - .chezmoidata.&lt;format&gt;: reference/special-files-and-directories/chezmoidata-format.md - - .chezmoiexternal.&lt;format&gt;: reference/special-files-and-directories/chezmoiexternal-format.md - - .chezmoiexternals: reference/special-files-and-directories/chezmoiexternals.md - - .chezmoiignore: reference/special-files-and-directories/chezmoiignore.md - - .chezmoiremove: reference/special-files-and-directories/chezmoiremove.md - - .chezmoiroot: reference/special-files-and-directories/chezmoiroot.md - - .chezmoiscripts: reference/special-files-and-directories/chezmoiscripts.md - - .chezmoitemplates: reference/special-files-and-directories/chezmoitemplates.md - - .chezmoiversion: reference/special-files-and-directories/chezmoiversion.md + - Special files: + - reference/special-files/index.md + - .chezmoi.&lt;format&gt;.tmpl: reference/special-files/chezmoi-format-tmpl.md + - .chezmoidata.&lt;format&gt;: reference/special-files/chezmoidata-format.md + - .chezmoiexternal.&lt;format&gt;: reference/special-files/chezmoiexternal-format.md + - .chezmoiignore: reference/special-files/chezmoiignore.md + - .chezmoiremove: reference/special-files/chezmoiremove.md + - .chezmoiroot: reference/special-files/chezmoiroot.md + - .chezmoiversion: reference/special-files/chezmoiversion.md + - Special directories: + - reference/special-directories/index.md + - .chezmoidata: reference/special-directories/chezmoidata.md + - .chezmoiexternals: reference/special-directories/chezmoiexternals.md + - .chezmoiscripts: reference/special-directories/chezmoiscripts.md + - .chezmoitemplates: reference/special-directories/chezmoitemplates.md - Commands: - add: reference/commands/add.md - age: reference/commands/age.md @@ -347,6 +350,11 @@ markdown_extensions: - admonition - meta - pymdownx.details +- pymdownx.snippets: + base_path: + - assets/chezmoi.io/snippets + - snippets + check_paths: true - pymdownx.superfences: custom_fences: - name: mermaid @@ -368,3 +376,6 @@ plugins: extra_javascript: - extra/refresh_on_toggle_dark_light.js + +watch: + - snippets diff --git a/assets/chezmoi.io/docs/reference/special-files-and-directories/chezmoidata-format.md b/assets/chezmoi.io/snippets/special-files-and-directories/chezmoidata.md similarity index 93% rename from assets/chezmoi.io/docs/reference/special-files-and-directories/chezmoidata-format.md rename to assets/chezmoi.io/snippets/special-files-and-directories/chezmoidata.md index b685fd03c63..310f0a2ab30 100644 --- a/assets/chezmoi.io/docs/reference/special-files-and-directories/chezmoidata-format.md +++ b/assets/chezmoi.io/snippets/special-files-and-directories/chezmoidata.md @@ -1,5 +1,3 @@ -# `.chezmoidata` and `.chezmoidata.$FORMAT` - If a file called `.chezmoidata.$FORMAT` exists in the source state, it is interpreted as template data in the given format. diff --git a/assets/chezmoi.io/docs/reference/special-files-and-directories/index.md b/assets/chezmoi.io/snippets/special-files-and-directories/index.md similarity index 89% rename from assets/chezmoi.io/docs/reference/special-files-and-directories/index.md rename to assets/chezmoi.io/snippets/special-files-and-directories/index.md index e671ffe6c07..c286e440de9 100644 --- a/assets/chezmoi.io/docs/reference/special-files-and-directories/index.md +++ b/assets/chezmoi.io/snippets/special-files-and-directories/index.md @@ -1,5 +1,3 @@ -# Special files and directories - All files and directories in the source state whose name begins with `.` are ignored by default, unless they are one of the special files listed here. `.chezmoidata.$FORMAT` and `.chezmoitemplates` are read before all other files
docs
Split "Special file and directories"
ff2568ba45cf981155efe013cf8c544e2ce429b5
2021-09-29 22:48:11
Tom Payne
chore: Remove conventional commits check on PR name and body
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 63e1a97a39b..c95dda7a1c1 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -258,11 +258,6 @@ jobs: run: | go install github.com/twpayne/findtypos@latest findtypos chezmoi . - - name: Conventional commits - if: github.event_name == 'pull_request' && github.event.pull_request.number - uses: agenthunt/[email protected] - with: - pr-body-regex: ".*" release: # FIXME this should be merged into test-ubuntu above if: startsWith(github.ref, 'refs/tags/') needs:
chore
Remove conventional commits check on PR name and body
f55d12f864d0ba96d27c17e6217ee9f80283f5dc
2022-11-01 01:04:17
Tom Payne
chore: Install Go in test-website and deploy-website jobs
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 61723593f03..5a173bbc198 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -291,6 +291,10 @@ jobs: runs-on: ubuntu-20.04 steps: - uses: actions/checkout@93ea575cb5d8a053eaa0ac8fa3b40d7e05a33cc8 + - uses: actions/setup-go@c4a742cab115ed795e34d4513e2cf7d472deb55f + with: + cache: true + go-version: ${{ env.GO_VERSION }} - name: install-website-dependencies run: pip3 install mkdocs-material mkdocs-mermaid2-plugin mkdocs-redirects mkdocs-simple-hooks - name: build-website @@ -443,6 +447,10 @@ jobs: - uses: actions/checkout@93ea575cb5d8a053eaa0ac8fa3b40d7e05a33cc8 with: fetch-depth: 0 + - uses: actions/setup-go@c4a742cab115ed795e34d4513e2cf7d472deb55f + with: + cache: true + go-version: ${{ env.GO_VERSION }} - name: prepare-chezmoi.io run: | pip3 install mkdocs-material mkdocs-mermaid2-plugin mkdocs-redirects mkdocs-simple-hooks
chore
Install Go in test-website and deploy-website jobs
5585ddd9ccd797e366e3d973e306c6abe1f128fe
2023-06-17 05:04:01
dependabot[bot]
chore(deps): bump dessant/lock-threads from 4.0.0 to 4.0.1
false
diff --git a/.github/workflows/lock.yml b/.github/workflows/lock.yml index 2fd2c63de68..60f31686328 100644 --- a/.github/workflows/lock.yml +++ b/.github/workflows/lock.yml @@ -15,7 +15,7 @@ jobs: action: runs-on: ubuntu-22.04 steps: - - uses: dessant/lock-threads@c1b35aecc5cdb1a34539d14196df55838bb2f836 + - uses: dessant/lock-threads@be8aa5be94131386884a6da4189effda9b14aa21 with: issue-lock-reason: resolved issue-inactive-days: 7
chore
bump dessant/lock-threads from 4.0.0 to 4.0.1
431ec39b1b9bbe6e6f80cb9aef360c4c7dd1cde7
2024-01-28 06:58:02
Tom Payne
feat: Set CHEZMOI_SOURCE_FILE env var for scripts
false
diff --git a/internal/chezmoi/realsystem.go b/internal/chezmoi/realsystem.go index aa9d599a786..51cdcd0726b 100644 --- a/internal/chezmoi/realsystem.go +++ b/internal/chezmoi/realsystem.go @@ -123,6 +123,9 @@ func (s *RealSystem) RunScript(scriptname RelPath, dir AbsPath, data []byte, opt if err != nil { return err } + cmd.Env = append(os.Environ(), + "CHEZMOI_SOURCE_FILE="+options.SourceRelPath.String(), + ) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr diff --git a/internal/chezmoi/sourcestate.go b/internal/chezmoi/sourcestate.go index 2ee3501c807..a0c5147b6a4 100644 --- a/internal/chezmoi/sourcestate.go +++ b/internal/chezmoi/sourcestate.go @@ -1855,6 +1855,9 @@ func (s *SourceState) newModifyTargetStateEntryFunc( // Run the modifier on the current contents. cmd := interpreter.ExecCommand(tempFile.Name()) + cmd.Env = append(os.Environ(), + "CHEZMOI_SOURCE_FILE="+sourceRelPath.String(), + ) cmd.Stdin = bytes.NewReader(currentContents) cmd.Stderr = os.Stderr contents, err = chezmoilog.LogCmdOutput(cmd) @@ -1911,6 +1914,7 @@ func (s *SourceState) newScriptTargetStateEntryFunc( sourceAttr: SourceAttr{ Condition: fileAttr.Condition, }, + sourceRelPath: sourceRelPath, }, nil } } diff --git a/internal/chezmoi/sourcestate_test.go b/internal/chezmoi/sourcestate_test.go index 840c578c7ac..8e7ee901993 100644 --- a/internal/chezmoi/sourcestate_test.go +++ b/internal/chezmoi/sourcestate_test.go @@ -1016,6 +1016,7 @@ func TestSourceStateRead(t *testing.T) { sourceAttr: SourceAttr{ Condition: ScriptConditionAlways, }, + sourceRelPath: NewSourceRelPath("run_script"), }, }, }), @@ -1046,6 +1047,7 @@ func TestSourceStateRead(t *testing.T) { sourceAttr: SourceAttr{ Condition: ScriptConditionAlways, }, + sourceRelPath: NewSourceRelPath("run_script"), }, }, }), diff --git a/internal/chezmoi/system.go b/internal/chezmoi/system.go index 0a9e7c1160c..31547db8ced 100644 --- a/internal/chezmoi/system.go +++ b/internal/chezmoi/system.go @@ -14,8 +14,9 @@ import ( ) type RunScriptOptions struct { - Interpreter *Interpreter - Condition ScriptCondition + Interpreter *Interpreter + Condition ScriptCondition + SourceRelPath SourceRelPath } // A System reads from and writes to a filesystem, runs scripts, and persists diff --git a/internal/chezmoi/targetstateentry.go b/internal/chezmoi/targetstateentry.go index 65a3897e2cd..27779bec00b 100644 --- a/internal/chezmoi/targetstateentry.go +++ b/internal/chezmoi/targetstateentry.go @@ -52,10 +52,11 @@ type TargetStateRemove struct{} // A TargetStateScript represents the state of a script. type TargetStateScript struct { *lazyContents - name RelPath - interpreter *Interpreter - condition ScriptCondition - sourceAttr SourceAttr + name RelPath + interpreter *Interpreter + condition ScriptCondition + sourceAttr SourceAttr + sourceRelPath SourceRelPath } // A TargetStateSymlink represents the state of a symlink in the target state. @@ -333,8 +334,9 @@ func (t *TargetStateScript) Apply( runAt := time.Now().UTC() if !isEmpty(contents) { if err := system.RunScript(t.name, actualStateEntry.Path().Dir(), contents, RunScriptOptions{ - Condition: t.condition, - Interpreter: t.interpreter, + Condition: t.condition, + Interpreter: t.interpreter, + SourceRelPath: t.sourceRelPath, }); err != nil { return false, err } diff --git a/internal/cmd/testdata/scripts/issue2934.txtar b/internal/cmd/testdata/scripts/issue2934.txtar index 973d72be04f..c5b6a77737b 100644 --- a/internal/cmd/testdata/scripts/issue2934.txtar +++ b/internal/cmd/testdata/scripts/issue2934.txtar @@ -1,10 +1,24 @@ -[windows] skip +[windows] skip 'UNIX only' # test that chezmoi sets environment variables for modify_ scripts -exec chezmoi apply -grep ^${CHEZMOISOURCEDIR@R}$ $HOME/.modify +exec chezmoi apply $HOME${/}.modify +grep ^CHEZMOI_SOURCE_DIR=${CHEZMOISOURCEDIR@R}$ $HOME/.modify +grep ^CHEZMOI_SOURCE_FILE=modify_dot_modify$ $HOME/.modify + +chhome home2/user + +# test that CHEZMOI_SOURCE_FILE environment variable is set when running scripts +exec chezmoi apply $HOME${/}script.sh +stdout ^CHEZMOI_SOURCE_DIR=${CHEZMOISOURCEDIR@R}$ +stdout ^CHEZMOI_SOURCE_FILE=run_script.sh$ -- home/user/.local/share/chezmoi/modify_dot_modify -- #!/bin/sh -echo ${CHEZMOI_SOURCE_DIR} +echo CHEZMOI_SOURCE_DIR=${CHEZMOI_SOURCE_DIR} +echo CHEZMOI_SOURCE_FILE=${CHEZMOI_SOURCE_FILE} +-- home2/user/.local/share/chezmoi/run_script.sh -- +#!/bin/sh + +echo CHEZMOI_SOURCE_DIR=${CHEZMOI_SOURCE_DIR} +echo CHEZMOI_SOURCE_FILE=${CHEZMOI_SOURCE_FILE}
feat
Set CHEZMOI_SOURCE_FILE env var for scripts
326b5788ae07e7e5c64e70c0a1ec9e96d4adadc8
2021-12-30 18:11:51
Kamil Domański
feat: Prompt for 1password password if no session token is set
false
diff --git a/docs/HOWTO.md b/docs/HOWTO.md index 377190da9d7..dd7b5bff607 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -944,6 +944,26 @@ instructs the template language to remove any whitespace before and after the substitution. This removes any trailing newline added by your editor when saving the template. +#### 1Password sign-in prompt + +chezmoi will verify the availability and validity of a session token in the +current environment. If it is missing or expired, you will be interactively +prompted to sign-in again. + +In the past chezmoi used to simply exit with an error when no valid session was +available. If you'd like to restore that behavior, set the following option in +your configuration file (`chezmoi.toml`): + +```toml +[onepassword] + prompt = false +``` + +**A session token verified or acquired interactively will be passed to the +1Password CLI through a command-line parameter, which could be visible to other +users of the same system. You should disable the prompt on shared machines for +improved security.** + --- ### Use Bitwarden diff --git a/docs/REFERENCE.md b/docs/REFERENCE.md index f13fcc7b06f..a0209a1412d 100644 --- a/docs/REFERENCE.md +++ b/docs/REFERENCE.md @@ -412,6 +412,7 @@ The following configuration variables are available: | | `command` | string | `vimdiff` | 3-way merge command | | `onepassword` | `cache` | bool | `true` | Enable optional caching provided by `op` | | | `command` | string | `op` | 1Password CLI command | +| | `prompt` | bool | `true` | Prompt for sign-in when no valid session is available | | `pass` | `command` | string | `pass` | Pass CLI command | | `pinentry` | `args` | []string | *none* | Extra args to the pinentry command | | | `command` | string | *none* | pinentry command | @@ -2340,7 +2341,9 @@ same *uuid* will only invoke `op` once. If the optional *vault-uuid* is supplied, it will be passed along to the `op get` call, which can significantly improve performance. If the optional *account-name* is supplied, it will be passed along to the `op get` call, which will help it look in the right account, -in case you have multiple accounts (eg. personal and work accounts). +in case you have multiple accounts (eg. personal and work accounts). If there is +no valid session in the environment, by default you will be interactively +prompted to sign in. #### `onepassword` examples @@ -2364,7 +2367,8 @@ multiple times with the same *uuid* will only invoke `op` once. If the optional can significantly improve performance. If the optional *account-name* is supplied, it will be passed along to the `op get` call, which will help it look in the right account, in case you have multiple accounts (eg. personal and work -accounts). +accounts). If there is no valid session in the environment, by default you will +be interactively prompted to sign in. #### `onepasswordDocument` examples @@ -2384,7 +2388,9 @@ accounts). CLI](https://support.1password.com/command-line-getting-started/) (`op`). *uuid* is passed to `op get item <uuid>`, the output from `op` is parsed as JSON, and elements of `details.fields` are returned as a map indexed by each field's -`designation`. For example, give the output from `op`: +`designation`. If there is no valid session in the environment, by default you +will be interactively prompted to sign in. For example, give the output from +`op`: ```json { @@ -2453,8 +2459,9 @@ accounts). CLI](https://support.1password.com/command-line-getting-started/) (`op`). *uuid* is passed to `op get item <uuid>`, the output from `op` is parsed as JSON, and each element of `details.sections` are iterated over and any `fields` are -returned as a map indexed by each field's `n`. For example, give the output from -`op`: +returned as a map indexed by each field's `n`. If there is no valid session in +the environment, by default you will be interactively prompted to sign in. For +example, give the output from `op`: ```json { diff --git a/internal/cmd/config.go b/internal/cmd/config.go index 491bc87bd95..c931ed02ba0 100644 --- a/internal/cmd/config.go +++ b/internal/cmd/config.go @@ -279,6 +279,7 @@ func newConfig(options ...configOption) (*Config, error) { }, Onepassword: onepasswordConfig{ Command: "op", + Prompt: true, }, Pass: passConfig{ Command: "pass", diff --git a/internal/cmd/onepasswordtemplatefuncs.go b/internal/cmd/onepasswordtemplatefuncs.go index f7f6401e9bb..7c70900102c 100644 --- a/internal/cmd/onepasswordtemplatefuncs.go +++ b/internal/cmd/onepasswordtemplatefuncs.go @@ -4,13 +4,18 @@ import ( "bytes" "encoding/json" "fmt" + "os" "os/exec" "strings" + + "github.com/twpayne/chezmoi/v2/internal/chezmoi" ) type onepasswordConfig struct { - Command string - outputCache map[string][]byte + Command string + Prompt bool + outputCache map[string][]byte + sessionTokens map[string]string } type onePasswordItem struct { @@ -23,8 +28,9 @@ type onePasswordItem struct { } func (c *Config) onepasswordItem(args ...string) *onePasswordItem { + sessionToken := c.onepasswordGetOrRefreshSession(args) onepasswordArgs := getOnepasswordArgs([]string{"get", "item"}, args) - output := c.onepasswordOutput(onepasswordArgs) + output := c.onepasswordOutput(onepasswordArgs, sessionToken) var onepasswordItem onePasswordItem if err := json.Unmarshal(output, &onepasswordItem); err != nil { returnTemplateError(fmt.Errorf("%s: %w\n%s", shellQuoteCommand(c.Onepassword.Command, onepasswordArgs), err, output)) @@ -58,19 +64,26 @@ func (c *Config) onepasswordItemFieldsTemplateFunc(args ...string) map[string]in } func (c *Config) onepasswordDocumentTemplateFunc(args ...string) string { + sessionToken := c.onepasswordGetOrRefreshSession(args) onepasswordArgs := getOnepasswordArgs([]string{"get", "document"}, args) - output := c.onepasswordOutput(onepasswordArgs) + output := c.onepasswordOutput(onepasswordArgs, sessionToken) return string(output) } -func (c *Config) onepasswordOutput(args []string) []byte { +func (c *Config) onepasswordOutput(args []string, sessionToken string) []byte { key := strings.Join(args, "\x00") if output, ok := c.Onepassword.outputCache[key]; ok { return output } + var secretArgs []string + if sessionToken != "" { + secretArgs = []string{"--session", sessionToken} + } + name := c.Onepassword.Command - cmd := exec.Command(name, args...) + // Append the session token here, so it is not logged by accident. + cmd := exec.Command(name, append(secretArgs, args...)...) cmd.Stdin = c.stdin stderr := &bytes.Buffer{} cmd.Stderr = stderr @@ -88,8 +101,9 @@ func (c *Config) onepasswordOutput(args []string) []byte { } func (c *Config) onepasswordTemplateFunc(args ...string) map[string]interface{} { + sessionToken := c.onepasswordGetOrRefreshSession(args) onepasswordArgs := getOnepasswordArgs([]string{"get", "item"}, args) - output := c.onepasswordOutput(onepasswordArgs) + output := c.onepasswordOutput(onepasswordArgs, sessionToken) var data map[string]interface{} if err := json.Unmarshal(output, &data); err != nil { returnTemplateError(fmt.Errorf("%s: %w\n%s", shellQuoteCommand(c.Onepassword.Command, onepasswordArgs), err, output)) @@ -110,5 +124,84 @@ func getOnepasswordArgs(baseArgs, args []string) []string { if len(args) > 2 { baseArgs = append(baseArgs, "--account", args[2]) } + return baseArgs } + +// refreshSession will return the current session token if the token within the +// environment is still valid. Otherwise it will ask the user to sign in and get +// the new token. If `sessioncheck` is disabled, it returns an empty string. +func (c *Config) onepasswordGetOrRefreshSession(callerArgs []string) string { + if !c.Onepassword.Prompt { + return "" + } + + var account string + if len(callerArgs) > 2 { + account = callerArgs[2] + } + + // Check if there's already a valid token cached in this run for this + // account. + token, ok := c.Onepassword.sessionTokens[account] + if ok { + return token + } + + var args []string + if account == "" { + // If no account has been given then look for any session tokens in the + // environment. + token = onepasswordInferSessionToken() + args = []string{"signin", "--raw"} + } else { + token = os.Getenv("OP_SESSION_" + account) + args = []string{"signin", account, "--raw"} + } + + // Do not specify an empty session string if no session tokens were found. + var secretArgs []string + if token != "" { + secretArgs = []string{"--session", token} + } + + name := c.Onepassword.Command + // Append the session token here, so it is not logged by accident. + cmd := exec.Command(name, append(secretArgs, args...)...) + cmd.Stdin = c.stdin + stderr := &bytes.Buffer{} + cmd.Stderr = stderr + output, err := cmd.Output() + if err != nil { + returnTemplateError(fmt.Errorf("%s: %w: %s", + shellQuoteCommand(c.Onepassword.Command, args), err, bytes.TrimSpace(stderr.Bytes()))) + return "" + } + token = strings.TrimSpace(string(output)) + + // Cache the session token in memory, so we don't try to refresh it again + // for this run for this account. + if c.Onepassword.sessionTokens == nil { + c.Onepassword.sessionTokens = make(map[string]string) + } + c.Onepassword.sessionTokens[account] = token + + return token +} + +// onepasswordInferSessionToken will look for any session tokens in the +// environment and if it finds exactly one then it will return it. +func onepasswordInferSessionToken() string { + var token string + for _, env := range os.Environ() { + key, value, found := chezmoi.CutString(env, "=") + if found && strings.HasPrefix(key, "OP_SESSION_") { + if token != "" { + // This is the second session we find. Let's bail. + return "" + } + token = value + } + } + return token +} diff --git a/internal/cmd/testdata/scripts/onepassword.txt b/internal/cmd/testdata/scripts/onepassword.txt index 20f31bc795c..8dea39c3b2b 100644 --- a/internal/cmd/testdata/scripts/onepassword.txt +++ b/internal/cmd/testdata/scripts/onepassword.txt @@ -20,11 +20,14 @@ case "$*" in "--version") echo 1.3.0 ;; -"get item ExampleLogin") +"get item ExampleLogin" | "--session thisIsAFakeSessionToken get item ExampleLogin") echo '{"uuid":"wxcplh5udshnonkzg2n4qx262y","templateUuid":"001","trashed":"N","createdAt":"2020-07-28T13:44:57Z","updatedAt":"2020-07-28T14:27:46Z","changerUuid":"VBDXOA4MPVHONK5IIJVKUQGLXM","itemVersion":2,"vaultUuid":"tscpxgi6s7c662jtqn3vmw4n5a","details":{"fields":[{"designation":"username","name":"username","type":"T","value":"exampleuser"},{"designation":"password","name":"password","type":"P","value":"L8rm1JXJIE1b8YUDWq7h"}],"notesPlain":"","passwordHistory":[],"sections":[{"name":"linked items","title":"Related Items"},{"fields":[{"k":"string","n":"D4328E0846D2461E8E455D7A07B93397","t":"exampleLabel","v":"exampleValue"}],"name":"Section_20E0BD380789477D8904F830BFE8A121","title":""}]},"overview":{"URLs":[{"l":"website","u":"https://www.example.com/"}],"ainfo":"exampleuser","pbe":119.083926,"pgrng":true,"ps":100,"tags":[],"title":"ExampleLogin","url":"https://www.example.com/"}}' ;; +"signin --raw") + echo 'thisIsAFakeSessionToken' + ;; *) - echo [ERROR] 2020/01/01 00:00:00 unknown command \"$*\" for \"op\" + echo [ERROR] 2020/01/01 00:00:00 unknown command \"$*\" for \"op\" 1>&2 exit 1 esac -- bin/op.cmd -- @@ -33,7 +36,11 @@ IF "%*" == "--version" ( echo 1.3.0 ) ELSE IF "%*" == "get item ExampleLogin" ( echo.{"uuid":"wxcplh5udshnonkzg2n4qx262y","templateUuid":"001","trashed":"N","createdAt":"2020-07-28T13:44:57Z","updatedAt":"2020-07-28T14:27:46Z","changerUuid":"VBDXOA4MPVHONK5IIJVKUQGLXM","itemVersion":2,"vaultUuid":"tscpxgi6s7c662jtqn3vmw4n5a","details":{"fields":[{"designation":"username","name":"username","type":"T","value":"exampleuser"},{"designation":"password","name":"password","type":"P","value":"L8rm1JXJIE1b8YUDWq7h"}],"notesPlain":"","passwordHistory":[],"sections":[{"name":"linked items","title":"Related Items"},{"fields":[{"k":"string","n":"D4328E0846D2461E8E455D7A07B93397","t":"exampleLabel","v":"exampleValue"}],"name":"Section_20E0BD380789477D8904F830BFE8A121","title":""}]},"overview":{"URLs":[{"l":"website","u":"https://www.example.com/"}],"ainfo":"exampleuser","pbe":119.083926,"pgrng":true,"ps":100,"tags":[],"title":"ExampleLogin","url":"https://www.example.com/"}} +) ELSE IF "%*" == "--session thisIsAFakeSessionToken get item ExampleLogin" ( + echo.{"uuid":"wxcplh5udshnonkzg2n4qx262y","templateUuid":"001","trashed":"N","createdAt":"2020-07-28T13:44:57Z","updatedAt":"2020-07-28T14:27:46Z","changerUuid":"VBDXOA4MPVHONK5IIJVKUQGLXM","itemVersion":2,"vaultUuid":"tscpxgi6s7c662jtqn3vmw4n5a","details":{"fields":[{"designation":"username","name":"username","type":"T","value":"exampleuser"},{"designation":"password","name":"password","type":"P","value":"L8rm1JXJIE1b8YUDWq7h"}],"notesPlain":"","passwordHistory":[],"sections":[{"name":"linked items","title":"Related Items"},{"fields":[{"k":"string","n":"D4328E0846D2461E8E455D7A07B93397","t":"exampleLabel","v":"exampleValue"}],"name":"Section_20E0BD380789477D8904F830BFE8A121","title":""}]},"overview":{"URLs":[{"l":"website","u":"https://www.example.com/"}],"ainfo":"exampleuser","pbe":119.083926,"pgrng":true,"ps":100,"tags":[],"title":"ExampleLogin","url":"https://www.example.com/"}} +) ELSE IF "%*" == "signin --raw" ( + echo thisIsAFakeSessionToken ) ELSE ( - echo.[ERROR] 2020/01/01 00:00:00 unknown command "%*" for "op" + echo.[ERROR] 2020/01/01 00:00:00 unknown command "%*" for "op" 1>&2 exit /b 1 )
feat
Prompt for 1password password if no session token is set
f67e048b73e2c2c24cbae300e7799675f7604d49
2024-09-10 04:04:21
Tom Payne
docs: Add home page section on getting help
false
diff --git a/assets/chezmoi.io/docs/index.md.tmpl b/assets/chezmoi.io/docs/index.md.tmpl index e3517e798ee..a4f928a2b75 100644 --- a/assets/chezmoi.io/docs/index.md.tmpl +++ b/assets/chezmoi.io/docs/index.md.tmpl @@ -55,6 +55,19 @@ watching [videos](links/videos.md) about chezmoi. Read how [chezmoi compares to other dotfile managers](comparison-table.md). Explore other people's [dotfile repos that use chezmoi](links/dotfile-repos.md). +## How do I get help using chezmoi? + +chezmoi has extensive documentation. First, use the search bar at the top of +this page using a few, short, and specific keywords related to your problem. + +chezmoi is an open source project with tens of thousands of users, so it is very +likely that someone else has already encountered and solved your problem. Search +[chezmoi's GitHub repo](https://github.com/twpayne/chezmoi) for issues and +discussions with keywords related to your problem. + +If your question is still unanswered, please [open a GitHub issue for +support](https://github.com/twpayne/chezmoi/issues/new?assignees=&labels=support&projects=&template=01_support_request.md&title=). + ## I like chezmoi. How do I say thanks? Please [give chezmoi a star on
docs
Add home page section on getting help
f9eeeeb6e7d7b15a1feb0fa275528cd600776b6c
2024-03-16 08:00:11
Tom Payne
chore: Add missing go.sum entries
false
diff --git a/go.sum b/go.sum index beb13cb85f8..1da5476a3ea 100644 --- a/go.sum +++ b/go.sum @@ -1,7 +1,23 @@ +cloud.google.com/go v0.110.10 h1:LXy9GEO+timppncPIAZoOj3l58LIU9k+kn48AN7IO3Y= +cloud.google.com/go v0.110.10/go.mod h1:v1OoFqYxiBkUrruItNM3eT4lLByNjxmJSV/xDKJNnic= +cloud.google.com/go/compute v1.23.3 h1:6sVlXXBmbd7jNX0Ipq0trII3e4n1/MsADLK6a+aiVlk= +cloud.google.com/go/compute v1.23.3/go.mod h1:VCgBUoMnIVIR0CscqQiPJLAG25E3ZRZMzcFZeQ+h8CI= +cloud.google.com/go/compute/metadata v0.2.3 h1:mg4jlk7mCAj6xXp9UJ4fjI9VUI5rubuGBW5aJ7UnBMY= +cloud.google.com/go/compute/metadata v0.2.3/go.mod h1:VAV5nSsACxMJvgaAuX6Pk2AawlZn8kiOGuCv6gTkwuA= +cloud.google.com/go/firestore v1.14.0 h1:8aLcKnMPoldYU3YHgu4t2exrKhLQkqaXAGqT0ljrFVw= +cloud.google.com/go/firestore v1.14.0/go.mod h1:96MVaHLsEhbvkBEdZgfN+AS/GIkco1LRpH9Xp9YZfzQ= +cloud.google.com/go/iam v1.1.5 h1:1jTsCu4bcsNsE4iiqNT5SHwrDRCfRmIaaaVFhRveTJI= +cloud.google.com/go/iam v1.1.5/go.mod h1:rB6P/Ic3mykPbFio+vo7403drjlgvoWfYpJhMXEbzv8= +cloud.google.com/go/longrunning v0.5.4 h1:w8xEcbZodnA2BbW6sVirkkoC+1gP8wS57EUUgGS0GVg= +cloud.google.com/go/longrunning v0.5.4/go.mod h1:zqNVncI0BOP8ST6XQD1+VcvuShMmq7+xFSzOL++V0dI= +cloud.google.com/go/storage v1.35.1 h1:B59ahL//eDfx2IIKFBeT5Atm9wnNmj3+8xG/W4WB//w= +cloud.google.com/go/storage v1.35.1/go.mod h1:M6M/3V/D3KpzMTJyPOR/HU6n2Si5QdaXYEsng2xgOs8= dario.cat/mergo v1.0.0 h1:AGCNq9Evsj31mOgNPcLyXc+4PNABt905YmuqPYYpBWk= dario.cat/mergo v1.0.0/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk= filippo.io/age v1.1.1 h1:pIpO7l151hCnQ4BdyBujnGP2YlUo0uj6sAVNHGBvXHg= filippo.io/age v1.1.1/go.mod h1:l03SrzDUrBkdBx8+IILdnn2KZysqQdbEBUQ4p3sqEQE= +filippo.io/edwards25519 v1.0.0 h1:0wAIcmJUqRdI8IJ/3eGi5/HwXZWPujYXXlkrQogz0Ek= +filippo.io/edwards25519 v1.0.0/go.mod h1:N1IkdkCkiLB6tki+MYJoSx2JTY9NUlxZE7eHn5EwJns= github.com/Azure/azure-sdk-for-go/sdk/azcore v1.10.0 h1:n1DH8TPV4qqPTje2RcUBYwtrTWlabVp4n46+74X2pn4= github.com/Azure/azure-sdk-for-go/sdk/azcore v1.10.0/go.mod h1:HDcZnuGbiyppErN6lB+idp4CKhjbc8gwjto6OPpyggM= github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.5.1 h1:sO0/P7g68FrryJzljemN+6GTssUXdANk6aJ7T1ZxnsQ= @@ -30,6 +46,8 @@ github.com/ProtonMail/go-crypto v1.0.0 h1:LRuvITjQWX+WIfr930YHG2HNfjR1uOfyf5vE0k github.com/ProtonMail/go-crypto v1.0.0/go.mod h1:EjAoLdwvbIOoOQr3ihjnSoLZRtE8azugULFRteWMNc0= github.com/Shopify/ejson v1.5.0 h1:SDV5HmQlpn3hSUiw9HV0nOj9tpzup5i0OV71ioLYkpw= github.com/Shopify/ejson v1.5.0/go.mod h1:a4+JLWuTe9+tTofPBGWZoqzf0af6eQKGmFqbxoMSARc= +github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d h1:licZJFw2RwpHMqeKTCYkitsPqHNxTmd4SNR5r94FGM8= +github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d/go.mod h1:asat636LX7Bqt5lYEZ27JNDcqxfjdBQuJ/MM4CN/Lzo= github.com/alecthomas/assert/v2 v2.6.0 h1:o3WJwILtexrEUk3cUVal3oiQY2tfgr/FHWiz/v2n4FU= github.com/alecthomas/assert/v2 v2.6.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k= github.com/alecthomas/chroma v0.10.0 h1:7XDcGkCQopCNKjZHfYrNLraA+M7e0fMiJ/Mfikbfjek= @@ -40,6 +58,8 @@ github.com/alessio/shellescape v1.4.2 h1:MHPfaU+ddJ0/bYWpgIeUnQUqKrlJ1S7BfEYPM4u github.com/alessio/shellescape v1.4.2/go.mod h1:PZAiSCk0LJaZkiCSkPv8qIobYglO3FPpyFjDCtHLS30= github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8= github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be/go.mod h1:ySMOLuWl6zY27l47sB3qLNK6tF2fkHG55UZxx8oIVo4= +github.com/armon/go-metrics v0.4.1 h1:hR91U9KYmb6bLBYLQjyM+3j+rcd/UhE+G78SFnF8gJA= +github.com/armon/go-metrics v0.4.1/go.mod h1:E6amYzXo6aW1tqzoZGT755KkbgrJsSdpwZ+3JqfkOG4= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= @@ -72,6 +92,7 @@ github.com/aws/aws-sdk-go-v2/service/sts v1.28.4 h1:Ppup1nVNAOWbBOrcoOxaxPeEnSFB github.com/aws/aws-sdk-go-v2/service/sts v1.28.4/go.mod h1:+K1rNPVyGxkRuv9NNiaZ4YhBFuyw2MMA9SlIJ1Zlpz8= github.com/aws/smithy-go v1.20.1 h1:4SZlSlMr36UEqC7XOyRVb27XMeZubNcBNN+9IgEPIQw= github.com/aws/smithy-go v1.20.1/go.mod h1:krry+ya/rV9RDcV/Q16kpu6ypI4K2czasz0NC3qS14E= +github.com/aymanbagabas/go-osc52 v1.0.3 h1:DTwqENW7X9arYimJrPeGZcV0ln14sGMt3pHZspWD+Mg= github.com/aymanbagabas/go-osc52 v1.0.3/go.mod h1:zT8H+Rk4VSabYN90pWyugflM3ZhpTZNC7cASDfUCdT4= github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= @@ -83,6 +104,7 @@ github.com/bradenhilton/cityhash v1.0.0 h1:1QauDCwfxwIGwO2jBTJdEBqXgfCusAgQOSgdl github.com/bradenhilton/cityhash v1.0.0/go.mod h1:Wmb8yW1egA9ulrsRX4mxfYx5zq4nBWOCZ+j63oK6uz8= github.com/bradenhilton/mozillainstallhash v1.0.1 h1:JVAVsItiWlLoudJX4L+tIuml+hoxjlzCwkhlENi9yS4= github.com/bradenhilton/mozillainstallhash v1.0.1/go.mod h1:J6cA36kUZrgaTkDl2bHRqI+4i2UKO1ImDB1P1x1PyOA= +github.com/bwesterb/go-ristretto v1.2.3 h1:1w53tCkGhCQ5djbat3+MH0BAQ5Kfgbt56UZQ/JMzngw= github.com/bwesterb/go-ristretto v1.2.3/go.mod h1:fUIoIZaG73pV5biE2Blr2xEzDoMj7NFEuV9ekS419A0= github.com/charmbracelet/bubbles v0.18.0 h1:PYv1A036luoBGroX6VWjQIE9Syf2Wby2oOl/39KLfy0= github.com/charmbracelet/bubbles v0.18.0/go.mod h1:08qhZhtIwzgrtBjAcJnij1t1H0ZRjwHyGsy6AL11PSw= @@ -101,8 +123,12 @@ github.com/containerd/console v1.0.4 h1:F2g4+oChYvBTsASRTz8NP6iIAi97J3TtSAsLbIFn github.com/containerd/console v1.0.4/go.mod h1:YynlIjWYF8myEu6sdkwKIvGQq+cOckRm6So2avqoYAk= github.com/coreos/go-semver v0.3.1 h1:yi21YpKnrx1gt5R+la8n5WgS0kCrsPp33dmEyHReZr4= github.com/coreos/go-semver v0.3.1/go.mod h1:irMmmIw/7yzSRPWryHsK7EYSg09caPQL03VsM8rvUec= +github.com/coreos/go-systemd/v22 v22.5.0 h1:RrqgGjYQKalulkV8NGVIfkXQf6YYmOyiJKk8iXXhfZs= github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/cpuguy83/go-md2man/v2 v2.0.3 h1:qMCsGGgs+MAzDFyp9LpAe1Lqy/fY/qCovCm0qnXZOBM= github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/creack/pty v1.1.21 h1:1/QdRyBaHHJP61QkWMXlOIBfsgdDeeKfK8SYVUWJKf0= +github.com/creack/pty v1.1.21/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4= github.com/creack/pty/v2 v2.0.0-20231209135443-03db72c7b76c h1:5l8y/PgjeX1aUyZxXabtAf2ahCYQaqWzlFzQgU16o0U= github.com/creack/pty/v2 v2.0.0-20231209135443-03db72c7b76c/go.mod h1:1gZ4PfMDNcYx8FxDdnF/6HYP327cTeB/ru6UdoWVQvw= github.com/cyphar/filepath-securejoin v0.2.4 h1:Ugdm7cg7i6ZK6x3xDF1oEu1nfkyfH53EtKeQYTC3kyg= @@ -118,12 +144,16 @@ github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxK github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= github.com/dnaeon/go-vcr v1.2.0 h1:zHCHvJYTMh1N7xnV7zf1m1GPBF9Ad0Jk/whtQ1663qI= github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/dustin/gojson v0.0.0-20160307161227-2e71ec9dd5ad h1:Qk76DOWdOp+GlyDKBAG3Klr9cn7N+LcYc82AZ2S7+cA= github.com/dustin/gojson v0.0.0-20160307161227-2e71ec9dd5ad/go.mod h1:mPKfmRa823oBIgl2r20LeMSpTAteW5j7FLkc0vjmzyQ= github.com/elazarl/goproxy v0.0.0-20230808193330-2592e75ae04a h1:mATvB/9r/3gvcejNsXKSkQ6lcIaNec2nyfOdlTBR2lU= github.com/elazarl/goproxy v0.0.0-20230808193330-2592e75ae04a/go.mod h1:Ro8st/ElPeALwNFlcTpWmkr6IoMFfkjXAvTHpevnDsM= github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc= github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ= +github.com/fatih/color v1.14.1 h1:qfhVLaG5s+nCROl1zJsZRxFeYrHLqWroPOQ8BWiNb4w= +github.com/fatih/color v1.14.1/go.mod h1:2oHN61fhTpgcxD3TSWCgKDiH1+x4OiDVVGH8WlgGZGg= github.com/fatih/semgroup v1.2.0 h1:h/OLXwEM+3NNyAdZEpMiH1OzfplU09i2qXPVThGZvyg= github.com/fatih/semgroup v1.2.0/go.mod h1:1KAD4iIYfXjE4U13B48VM4z9QUwV5Tt8O4rS879kgm8= github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= @@ -145,6 +175,8 @@ github.com/go-git/go-git/v5 v5.11.0/go.mod h1:6GFcX2P3NM7FPBfpePbpLd21XxsgdAt+lK github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk= github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk= github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE= @@ -167,9 +199,17 @@ github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU= github.com/google/renameio/v2 v2.0.0 h1:UifI23ZTGY8Tt29JbYFiuyIU3eX+RNFtUwefq9qAhxg= github.com/google/renameio/v2 v2.0.0/go.mod h1:BtmJXm5YlszgC+TD4HOEEUFgkJP3nLxehU6hfe7jRt4= +github.com/google/s2a-go v0.1.7 h1:60BLSyTrOV4/haCDW4zb1guZItoSq8foHCXrAnjBo/o= +github.com/google/s2a-go v0.1.7/go.mod h1:50CgR4k1jNlWBu4UfS4AcfhVe1r6pdZPygJ3R8F0Qdw= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/googleapis/enterprise-certificate-proxy v0.3.2 h1:Vie5ybvEvT75RniqhfFxPRy3Bf7vr3h0cechB90XaQs= +github.com/googleapis/enterprise-certificate-proxy v0.3.2/go.mod h1:VLSiSSBs/ksPL8kq3OBOQ6WRI2QnaFynd1DCjZ62+V0= +github.com/googleapis/gax-go/v2 v2.12.0 h1:A+gCJKdRfqXkr+BIRGtZLibNXf0m1f9E4HG56etFpas= +github.com/googleapis/gax-go/v2 v2.12.0/go.mod h1:y+aIqrI5eb1YGMVJfuV3185Ts/D7qKpsEkdD5+I6QGU= +github.com/googleapis/google-cloud-go-testing v0.0.0-20210719221736-1c9a4c676720 h1:zC34cGQu69FG7qzJ3WiKW244WfhDC3xxYMeNOX2gtUQ= +github.com/googleapis/google-cloud-go-testing v0.0.0-20210719221736-1c9a4c676720/go.mod h1:dvDLG8qkwmyD9a/MJJN3XJcT3xFxOKAvTZGvuZmac9g= github.com/gopherjs/gopherjs v1.17.2 h1:fQnZVsXk8uxXIStYb0N4bGk7jeyTalG/wsZjQ25dO0g= github.com/gopherjs/gopherjs v1.17.2/go.mod h1:pRRIvn/QzFLrKfvEz3qUuEhtE/zLCWfreZ6J5gM2i+k= github.com/gorilla/css v1.0.0/go.mod h1:Dn721qIggHpt4+EFCcTLTU/vk5ySda2ReITrtgBl60c= @@ -179,8 +219,22 @@ github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 h1:+ngKgrYPPJr github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= github.com/h2non/filetype v1.1.3 h1:FKkx9QbD7HR/zjK1Ia5XiBsq9zdLi5Kf3zGyFTAFkGg= github.com/h2non/filetype v1.1.3/go.mod h1:319b3zT68BvV+WRj7cwy856M2ehB3HqNOt6sy1HndBY= +github.com/hashicorp/consul/api v1.25.1 h1:CqrdhYzc8XZuPnhIYZWH45toM0LB9ZeYr/gvpLVI3PE= +github.com/hashicorp/consul/api v1.25.1/go.mod h1:iiLVwR/htV7mas/sy0O+XSuEnrdBUUydemjxcUrAt4g= +github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ= +github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48= +github.com/hashicorp/go-hclog v1.5.0 h1:bI2ocEMgcVlz55Oj1xZNBsVi900c7II+fWDyV9o+13c= +github.com/hashicorp/go-hclog v1.5.0/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M= +github.com/hashicorp/go-immutable-radix v1.3.1 h1:DKHmCUm2hRBK510BaiZlwvpD40f8bJFeZnpfm2KLowc= +github.com/hashicorp/go-immutable-radix v1.3.1/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= +github.com/hashicorp/go-rootcerts v1.0.2 h1:jzhAVGtqPKbwpyCPELlgNWhE1znq+qwJtW5Oi2viEzc= +github.com/hashicorp/go-rootcerts v1.0.2/go.mod h1:pqUvnprVnM5bf7AOirdbb01K4ccR319Vf4pU3K5EGc8= +github.com/hashicorp/golang-lru v0.5.4 h1:YDjusn29QI/Das2iO9M0BHnIbxPeyuCHsjMW+lJfyTc= +github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= +github.com/hashicorp/serf v0.10.1 h1:Z1H2J60yRKvfDYAOZLd2MU0ND4AH/WDz7xYHDWQsIPY= +github.com/hashicorp/serf v0.10.1/go.mod h1:yL2t6BqATOLGc5HF7qbFkTfXoPIY0WZdWHfEvMqbG+4= github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= github.com/huandu/xstrings v1.3.3/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= @@ -197,16 +251,24 @@ github.com/itchyny/timefmt-go v0.1.5 h1:G0INE2la8S6ru/ZI5JecgyzbbJNs5lG1RcBqa7Jm github.com/itchyny/timefmt-go v0.1.5/go.mod h1:nEP7L+2YmAbT2kZ2HfSs1d8Xtw9LY8D2stDBckWakZ8= github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 h1:BQSFePA1RWJOlocH6Fxy8MmwDt+yVQYULKfN0RoTN8A= github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99/go.mod h1:1lJo3i6rXxKeerYnT8Nvf0QmHCRC1n8sfWVwXF2Frvo= +github.com/jessevdk/go-flags v1.4.0 h1:4IU2WS7AumrZ/40jfhf4QVDMsQwqA7VEHozFRrGARJA= github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= +github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= +github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/kevinburke/ssh_config v1.2.0 h1:x584FjTGwHzMwvHx18PXxbBVzfnxogHaAReU4gf13a4= github.com/kevinburke/ssh_config v1.2.0/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM= github.com/klauspost/compress v1.17.7 h1:ehO88t2UGzQK66LMdE8tibEd1ErmzZjNEqWkjLAKQQg= github.com/klauspost/compress v1.17.7/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw= +github.com/kr/fs v0.1.0 h1:Jskdu9ieNAYnjxsi0LbQp1ulIKZV1LAFgK1tWhpZgl8= +github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/pty v1.1.1 h1:VkoXIwSboBpnk99O/KFauAEILuNHv5DVFKZMBN/gUgw= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= @@ -215,6 +277,8 @@ github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0 github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= +github.com/lucasjones/reggen v0.0.0-20200904144131-37ba4fa293bb h1:w1g9wNDIE/pHSTmAaUhv4TZQuPBS6GV3mMz5hkgziIU= +github.com/lucasjones/reggen v0.0.0-20200904144131-37ba4fa293bb/go.mod h1:5ELEyG+X8f+meRWHuqUOewBOhvHkl7M76pdGEansxW4= github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= @@ -236,11 +300,21 @@ github.com/microcosm-cc/bluemonday v1.0.25/go.mod h1:ZIOjCQp1OrzBBPIJmfX4qDYFuhU github.com/mitchellh/copystructure v1.0.0/go.mod h1:SNtv71yrdKgLRyLFxmLdkAbkKEFWgYaq1OVrnRcwhnw= github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= +github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= +github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= +github.com/mmcloughlin/avo v0.5.0 h1:nAco9/aI9Lg2kiuROBY6BhCI/z0t5jEvJfjWbL8qXLU= +github.com/mmcloughlin/avo v0.5.0/go.mod h1:ChHFdoV7ql95Wi7vuq2YT1bwCJqiWdZrQ1im3VujLYM= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/montanaflynn/stats v0.7.0 h1:r3y12KyNxj/Sb/iOE46ws+3mS1+MZca1wlHQFPsY/JU= +github.com/montanaflynn/stats v0.7.0/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow= github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI= github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo= github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= @@ -252,10 +326,18 @@ github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKt github.com/muesli/termenv v0.13.0/go.mod h1:sP1+uffeLaEYpyOTb8pLCUctGcGLnoFjSn4YJK5e2bc= github.com/muesli/termenv v0.15.2 h1:GohcuySI0QmI3wN8Ok9PtKGkgkFIk7y6Vpb5PvrY+Wo= github.com/muesli/termenv v0.15.2/go.mod h1:Epx+iuz8sNs7mNKhxzH4fWXGNpZwUaJKRS1noLXviQ8= +github.com/nats-io/nats.go v1.31.0 h1:/WFBHEc/dOKBF6qf1TZhrdEfTmOZ5JzdJ+Y3m6Y/p7E= +github.com/nats-io/nats.go v1.31.0/go.mod h1:di3Bm5MLsoB4Bx61CBTsxuarI36WbhAwOm8QrW39+i8= +github.com/nats-io/nkeys v0.4.6 h1:IzVe95ru2CT6ta874rt9saQRkWfe2nFj1NtvYSLqMzY= +github.com/nats-io/nkeys v0.4.6/go.mod h1:4DxZNzenSVd1cYQoAa8948QY3QDjrHfcfVADymtkpts= +github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw= +github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= github.com/onsi/gomega v1.27.10 h1:naR28SdDFlqrG6kScpT8VWpu1xWY5nJRCF3XaYyBjhI= github.com/onsi/gomega v1.27.10/go.mod h1:RsS8tutOdbdgzbPtzzATp12yT7kM5I5aElG3evPbQ0M= +github.com/pelletier/go-toml v1.9.3 h1:zeC5b1GviRUyKYd6OJPvBU/mcVDVoL1OhT17FCt5dSQ= +github.com/pelletier/go-toml v1.9.3/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= github.com/pelletier/go-toml/v2 v2.1.1 h1:LWAJwfNvjQZCFIDKWYQaM62NcYeYViCmWIwmOStowAI= github.com/pelletier/go-toml/v2 v2.1.1/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc= github.com/peterbourgon/diskv v2.0.1+incompatible h1:UBdAOUP5p4RWqPBg048CAvpKN+vxiaj6gdUUzhl4XmI= @@ -264,8 +346,12 @@ github.com/pjbgf/sha1cd v0.3.0 h1:4D5XXmUUBUl/xQ6IjCkEAbqXskkq/4O7LmGn0AqMDs4= github.com/pjbgf/sha1cd v0.3.0/go.mod h1:nZ1rrWOcGJ5uZgEEVL1VUM9iRQiZvWdbZjkKyFzPPsI= github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= +github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e h1:aoZm08cpOy4WuID//EZDgcC4zIxODThtZNPirFr42+A= +github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/sftp v1.13.6 h1:JFZT4XbOU7l77xGSpOdW+pwIMqP044IyjXX6FGyEKFo= +github.com/pkg/sftp v1.13.6/go.mod h1:tz1ryNURKu77RL+GuCzmoJYxQczL3wLNNpPWagdg4Qk= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= @@ -275,20 +361,28 @@ github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/rs/xid v1.5.0 h1:mKX4bl4iPYJtEIxp6CYiUuLQ/8DYMoz0PUdtGgMFRVc= github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= github.com/rs/zerolog v1.32.0 h1:keLypqrlIjaFsbmJOBdB/qvyF8KEtCWHwobLp5l/mQ0= github.com/rs/zerolog v1.32.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss= +github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/sagikazarmark/crypt v0.17.0 h1:ZA/7pXyjkHoK4bW4mIdnCLvL8hd+Nrbiw7Dqk7D4qUk= +github.com/sagikazarmark/crypt v0.17.0/go.mod h1:SMtHTvdmsZMuY/bpZoqokSoChIrcJ/epOxZN58PbZDg= github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ= github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4= github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE= github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ= +github.com/sahilm/fuzzy v0.1.1-0.20230530133925-c48e322e2a8f h1:MvTmaQdww/z0Q4wrYjDSCcZ78NoftLQyHBSLW/Cx79Y= +github.com/sahilm/fuzzy v0.1.1-0.20230530133925-c48e322e2a8f/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y= github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0= github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= github.com/shopspring/decimal v1.3.1 h1:2Usl1nmF/WZucqkFZhnfFYxxxu8LG21F6nPQBE5gKV8= github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= +github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0= +github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/skeema/knownhosts v1.2.1 h1:SHWdIUa82uGZz+F+47k8SY4QhhI291cXCpopT1lK2AQ= github.com/skeema/knownhosts v1.2.1/go.mod h1:xYbVRSPxqBZFrdmDyMmsOs+uX1UZC3nTN3ThzgDxUwo= github.com/smarty/assertions v1.15.0 h1:cR//PqUBUiQRakZWqBiFFQ9wb8emQGDb0HeGdqGByCY= @@ -304,6 +398,8 @@ github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0= github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0= github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho= +github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= +github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.18.2 h1:LUXCnvUvSM6FXAsj6nnfc8Q2tp1dIgUfY9Kc8GsSOiQ= @@ -339,6 +435,8 @@ github.com/twpayne/go-xdg/v6 v6.1.2 h1:KbfCsAP4bBR5+dzfTIh/M9onOPCSqlYsIER79IKwt github.com/twpayne/go-xdg/v6 v6.1.2/go.mod h1:BFHclQaEPLq3jRRYjf1PdFzUEvAfPeLjNymIO/7/7o4= github.com/ulikunitz/xz v0.5.11 h1:kpFauv27b6ynzBNT/Xy+1k+fK4WswhN/6PN5WhFAGw8= github.com/ulikunitz/xz v0.5.11/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14= +github.com/urfave/cli v1.22.14 h1:ebbhrRiGK2i4naQJr+1Xj92HXZCrK7MsyTS/ob3HnAk= +github.com/urfave/cli v1.22.14/go.mod h1:X0eDS6pD6Exaclxm99NJ3FiCDRED7vIHpx2mDOHLvkA= github.com/xanzy/ssh-agent v0.3.3 h1:+/15pJfg/RsTxqYcX6fHqOXZwwMP+2VyYWJeWM2qQFM= github.com/xanzy/ssh-agent v0.3.3/go.mod h1:6dzNDKs0J9rVPHPhaGCukekBHKqfl+L3KghI1Bc68Uw= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= @@ -356,8 +454,24 @@ github.com/zricethezav/gitleaks/v8 v8.18.2 h1:slo/sMmgs3qA+6Vv6iqVhsCv+gsl3RekQX github.com/zricethezav/gitleaks/v8 v8.18.2/go.mod h1:8F5GrdCpEtyN5R+0MKPubbOPqIHptNckH3F7bYrhT+Y= go.etcd.io/bbolt v1.3.9 h1:8x7aARPEXiXbHmtUwAIv7eV2fQFHrLLavdiJ3uzJXoI= go.etcd.io/bbolt v1.3.9/go.mod h1:zaO32+Ti0PK1ivdPtgMESzuzL2VPoIG1PCQNvOdo/dE= +go.etcd.io/etcd/api/v3 v3.5.10 h1:szRajuUUbLyppkhs9K6BRtjY37l66XQQmw7oZRANE4k= +go.etcd.io/etcd/api/v3 v3.5.10/go.mod h1:TidfmT4Uycad3NM/o25fG3J07odo4GBB9hoxaodFCtI= +go.etcd.io/etcd/client/pkg/v3 v3.5.10 h1:kfYIdQftBnbAq8pUWFXfpuuxFSKzlmM5cSn76JByiT0= +go.etcd.io/etcd/client/pkg/v3 v3.5.10/go.mod h1:DYivfIviIuQ8+/lCq4vcxuseg2P2XbHygkKwFo9fc8U= +go.etcd.io/etcd/client/v2 v2.305.10 h1:MrmRktzv/XF8CvtQt+P6wLUlURaNpSDJHFZhe//2QE4= +go.etcd.io/etcd/client/v2 v2.305.10/go.mod h1:m3CKZi69HzilhVqtPDcjhSGp+kA1OmbNn0qamH80xjA= +go.etcd.io/etcd/client/v3 v3.5.10 h1:W9TXNZ+oB3MCd/8UjxHTWK5J9Nquw9fQBLJd5ne5/Ao= +go.etcd.io/etcd/client/v3 v3.5.10/go.mod h1:RVeBnDz2PUEZqTpgqwAtUd8nAPf5kjyFyND7P1VkOKc= +go.etcd.io/gofail v0.1.0 h1:XItAMIhOojXFQMgrxjnd2EIIHun/d5qL0Pf7FzVTkFg= +go.etcd.io/gofail v0.1.0/go.mod h1:VZBCXYGZhHAinaBiiqYvuDynvahNsAyLFwB3kEHKz1M= +go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= +go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= +go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= +go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/zap v1.21.0 h1:WefMeulhovoZ2sYXz7st6K0sLj7bBhpiFaud4r4zST8= +go.uber.org/zap v1.21.0/go.mod h1:wjWOCqI0f2ZZrJF/UufIOkiC8ii6tm1iqIsLo76RfJw= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= @@ -410,6 +524,8 @@ golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4= golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2 h1:IRJeR9r1pYWsHKTRe/IInb7lYvbBVIqOgsX/u0mbOWY= +golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc= @@ -427,6 +543,8 @@ golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk= +golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= @@ -435,8 +553,20 @@ golang.org/x/tools v0.19.0 h1:tfGCXNR1OsFG+sVdLAitlpjAvD/I6dHDKnYrpEZUHkw= golang.org/x/tools v0.19.0/go.mod h1:qoJWxmGSIBmAeriMx19ogtrEPrGtDbPK634QFIcLAhc= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 h1:H2TDz8ibqkAF6YGhCdN3jS9O0/s90v0rJh3X/OLHEUk= +golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= +google.golang.org/api v0.153.0 h1:N1AwGhielyKFaUqH07/ZSIQR3uNPcV7NVw0vj+j4iR4= +google.golang.org/api v0.153.0/go.mod h1:3qNJX5eOmhiWYc67jRA/3GsDw97UFb5ivv7Y2PrriAY= google.golang.org/appengine v1.6.8 h1:IhEN5q69dyKagZPYMSdIjS2HqprW324FRQZJcGqPAsM= google.golang.org/appengine v1.6.8/go.mod h1:1jJ3jBArFh5pcgW8gCtRJnepW8FzD1V44FJffLiz/Ds= +google.golang.org/genproto v0.0.0-20231106174013-bbf56f31fb17 h1:wpZ8pe2x1Q3f2KyT5f8oP/fa9rHAKgFPr/HZdNuS+PQ= +google.golang.org/genproto v0.0.0-20231106174013-bbf56f31fb17/go.mod h1:J7XzRzVy1+IPwWHZUzoD0IccYZIrXILAQpc+Qy9CMhY= +google.golang.org/genproto/googleapis/api v0.0.0-20231106174013-bbf56f31fb17 h1:JpwMPBpFN3uKhdaekDpiNlImDdkUAyiJ6ez/uxGaUSo= +google.golang.org/genproto/googleapis/api v0.0.0-20231106174013-bbf56f31fb17/go.mod h1:0xJLfVdJqpAPl8tDg1ujOCGzx6LFLttXT5NhllGOXY4= +google.golang.org/genproto/googleapis/rpc v0.0.0-20231120223509-83a465c0220f h1:ultW7fxlIvee4HYrtnaRPon9HpEgFk5zYpmfMgtKB5I= +google.golang.org/genproto/googleapis/rpc v0.0.0-20231120223509-83a465c0220f/go.mod h1:L9KNLi232K1/xB6f7AlSX692koaRnKaWSR0stBki0Yc= +google.golang.org/grpc v1.59.0 h1:Z5Iec2pjwb+LEOqzpB2MR12/eKFhDPhuqW91O+4bwUk= +google.golang.org/grpc v1.59.0/go.mod h1:aUPDwccQo6OTjy7Hct4AfBPD1GptF4fyUjIkQ9YtF98= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI= @@ -449,6 +579,7 @@ gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/warnings.v0 v0.1.2 h1:wFXVbFY8DY5/xOe1ECiWdKCzZlxgshcYVNkBHstARME= gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI= +gopkg.in/yaml.v1 v1.0.0-20140924161607-9f9df34309c0 h1:POO/ycCATvegFmVuPpQzZFJ+pGZeX22Ufu6fibxDVjU= gopkg.in/yaml.v1 v1.0.0-20140924161607-9f9df34309c0/go.mod h1:WDnlLJ4WF5VGsH/HVa3CI79GS0ol3YnhVnKP89i0kNg= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= @@ -460,5 +591,7 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= howett.net/plist v1.0.1 h1:37GdZ8tP09Q35o9ych3ehygcsL+HqKSwzctveSlarvM= howett.net/plist v1.0.1/go.mod h1:lqaXoTrLY4hg8tnEzNru53gicrbv7rrk+2xJA/7hw9g= +mvdan.cc/editorconfig v0.2.1-0.20231228180347-1925077f8eb2 h1:8nmqQGVnHUtHuT+yvuA49lQK0y5il5IOr2PtCBkDI2M= +mvdan.cc/editorconfig v0.2.1-0.20231228180347-1925077f8eb2/go.mod h1:r8RiQJRtzrPrZdcdEs5VCMqvRxAzYDUu9a4S9z7fKh8= mvdan.cc/sh/v3 v3.8.0 h1:ZxuJipLZwr/HLbASonmXtcvvC9HXY9d2lXZHnKGjFc8= mvdan.cc/sh/v3 v3.8.0/go.mod h1:w04623xkgBVo7/IUK89E0g8hBykgEpN0vgOj3RJr6MY=
chore
Add missing go.sum entries
4120b2e73579ddc2fbce0af8991339345929d88a
2022-02-03 02:06:01
Tom Payne
docs: Add link to article
false
diff --git a/assets/chezmoi.io/docs/links/articles-podcasts-and-videos.md b/assets/chezmoi.io/docs/links/articles-podcasts-and-videos.md index a24a65a9aa8..bf497f70c80 100644 --- a/assets/chezmoi.io/docs/links/articles-podcasts-and-videos.md +++ b/assets/chezmoi.io/docs/links/articles-podcasts-and-videos.md @@ -14,6 +14,7 @@ | Date | Version | Format | Link | | ---------- | ------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 2022-02-02 | 2.11.0 | Text (FR) | [Controler ses dotfiles en environnement éphémère](https://blog.wescale.fr/2022/02/02/controler-ses-dotfiles-en-environnement-ephemere-2/) | | 2022-02-01 | 2.10.1 | Text (JP) | [chezmoi で dotfiles を手軽に柔軟にセキュアに管理する](https://zenn.dev/ryo_kawamata/articles/introduce-chezmoi) | | 2022-01-26 | 2.10.1 | Text (JP) | [chezmoi で dotfiles を管理する](https://blog.zoncoen.net/2022/01/26/chezmoi/) | | 2022-01-12 | 2.9.5 | Text (IT) | [Come funzionano i miei Mac](https://correntedebole.com/come-funzionano-i-miei-mac/) |
docs
Add link to article
5c0140d5dd05a24c90200fa9386d620865afdc82
2023-10-07 12:03:19
Braden Hilton
fix: Don't use `replace-executable` for WinGet installations
false
diff --git a/internal/cmd/upgradecmd.go b/internal/cmd/upgradecmd.go index 31782a34d7b..0f15a35e875 100644 --- a/internal/cmd/upgradecmd.go +++ b/internal/cmd/upgradecmd.go @@ -1,4 +1,4 @@ -//go:build !noupgrade +//go:build !noupgrade && !windows package cmd @@ -331,15 +331,6 @@ func (c *Config) replaceExecutable( var archiveFormat chezmoi.ArchiveFormat var archiveName string switch { - case runtime.GOOS == "windows": - archiveFormat = chezmoi.ArchiveFormatZip - archiveName = fmt.Sprintf( - "%s_%s_%s_%s.zip", - c.upgrade.repo, - releaseVersion, - runtime.GOOS, - runtime.GOARCH, - ) case runtime.GOOS == "linux" && runtime.GOARCH == "amd64": archiveFormat = chezmoi.ArchiveFormatTarGz var libc string @@ -389,19 +380,15 @@ func (c *Config) replaceExecutable( // Extract the executable from the archive. var executableData []byte walkArchiveFunc := func(name string, info fs.FileInfo, r io.Reader, linkname string) error { - switch { - case runtime.GOOS != "windows" && name == c.upgrade.repo: - fallthrough - case runtime.GOOS == "windows" && name == c.upgrade.repo+".exe": + if name == c.upgrade.repo { var err error executableData, err = io.ReadAll(r) if err != nil { return err } return fs.SkipAll - default: - return nil } + return nil } if err = chezmoi.WalkArchive(archiveData, archiveFormat, walkArchiveFunc); err != nil { return @@ -411,12 +398,6 @@ func (c *Config) replaceExecutable( return } - // Replace the executable. - if runtime.GOOS == "windows" { - if err = c.baseSystem.Rename(executableFilenameAbsPath, executableFilenameAbsPath.Append(".old")); err != nil { - return - } - } err = c.baseSystem.WriteFile(executableFilenameAbsPath, executableData, 0o755) return diff --git a/internal/cmd/upgradecmd_windows.go b/internal/cmd/upgradecmd_windows.go new file mode 100644 index 00000000000..65b4b01fc3a --- /dev/null +++ b/internal/cmd/upgradecmd_windows.go @@ -0,0 +1,425 @@ +//go:build !noupgrade + +package cmd + +import ( + "bufio" + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "io" + "io/fs" + "net/http" + "os" + "os/exec" + "path/filepath" + "regexp" + "runtime" + "strings" + + "github.com/coreos/go-semver/semver" + "github.com/google/go-github/v55/github" + "github.com/spf13/cobra" + vfs "github.com/twpayne/go-vfs/v4" + + "github.com/twpayne/chezmoi/v2/internal/chezmoi" + "github.com/twpayne/chezmoi/v2/internal/chezmoilog" +) + +const ( + upgradeMethodReplaceExecutable = "replace-executable" + upgradeMethodWinGetUpgrade = "winget-upgrade" +) + +var checksumRx = regexp.MustCompile(`\A([0-9a-f]{64})\s+(\S+)\z`) + +type upgradeCmdConfig struct { + executable string + method string + owner string + repo string +} + +type InstallBehavior struct { + PortablePackageUserRoot string `json:"portablePackageUserRoot"` + PortablePackageMachineRoot string `json:"portablePackageMachineRoot"` +} + +func (ib *InstallBehavior) Values() []string { + return []string{ + ib.PortablePackageUserRoot, + ib.PortablePackageMachineRoot, + } +} + +type WinGetSettings struct { + InstallBehavior InstallBehavior `json:"installBehavior"` +} + +func (c *Config) newUpgradeCmd() *cobra.Command { + upgradeCmd := &cobra.Command{ + Use: "upgrade", + Short: "Upgrade chezmoi to the latest released version", + Long: mustLongHelp("upgrade"), + Example: example("upgrade"), + Args: cobra.NoArgs, + RunE: c.runUpgradeCmd, + Annotations: newAnnotations( + runsCommands, + ), + } + + flags := upgradeCmd.Flags() + flags.StringVar( + &c.upgrade.executable, + "executable", + c.upgrade.method, + "Set executable to replace", + ) + flags.StringVar(&c.upgrade.method, "method", c.upgrade.method, "Set upgrade method") + flags.StringVar(&c.upgrade.owner, "owner", c.upgrade.owner, "Set owner") + flags.StringVar(&c.upgrade.repo, "repo", c.upgrade.repo, "Set repo") + + return upgradeCmd +} + +func (c *Config) runUpgradeCmd(cmd *cobra.Command, args []string) error { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + var zeroVersion semver.Version + if c.version == zeroVersion && !c.force { + return errors.New( + "cannot upgrade dev version to latest released version unless --force is set", + ) + } + + httpClient, err := c.getHTTPClient() + if err != nil { + return err + } + client := chezmoi.NewGitHubClient(ctx, httpClient) + + // Get the latest release. + rr, _, err := client.Repositories.GetLatestRelease(ctx, c.upgrade.owner, c.upgrade.repo) + if err != nil { + return err + } + version, err := semver.NewVersion(strings.TrimPrefix(rr.GetName(), "v")) + if err != nil { + return err + } + + // If the upgrade is not forced, stop if we're already the latest version. + // Print a message and return no error so the command exits with success. + if !c.force && !c.version.LessThan(*version) { + fmt.Fprintf(c.stdout, "chezmoi: already at the latest version (%s)\n", c.version) + return nil + } + + // Determine the upgrade method to use. + if c.upgrade.executable == "" { + executable, err := os.Executable() + if err != nil { + return err + } + c.upgrade.executable = executable + } + + executableAbsPath := chezmoi.NewAbsPath(c.upgrade.executable) + method := c.upgrade.method + if method == "" { + switch method, err = getUpgradeMethod(c.fileSystem, executableAbsPath); { + case err != nil: + return err + case method == "": + return fmt.Errorf( + "%s/%s: cannot determine upgrade method for %s", + runtime.GOOS, + runtime.GOARCH, + executableAbsPath, + ) + } + } + c.logger.Info(). + Str("executable", c.upgrade.executable). + Str("method", method). + Msg("upgradeMethod") + + // Replace the executable with the updated version. + switch method { + case upgradeMethodReplaceExecutable: + if err := c.replaceExecutable(ctx, executableAbsPath, version, rr); err != nil { + return err + } + case upgradeMethodWinGetUpgrade: + if err := c.winGetUpgrade(); err != nil { + return err + } + default: + return fmt.Errorf("%s: invalid method", method) + } + + // Find the executable. If we replaced the executable directly, then use + // that, otherwise look in $PATH. + path := c.upgrade.executable + if method != upgradeMethodReplaceExecutable { + path, err = chezmoi.LookPath(c.upgrade.repo) + if err != nil { + return err + } + } + + // Execute the new version. + chezmoiVersionCmd := exec.Command(path, "--version") + chezmoiVersionCmd.Stdin = os.Stdin + chezmoiVersionCmd.Stdout = os.Stdout + chezmoiVersionCmd.Stderr = os.Stderr + return chezmoilog.LogCmdRun(chezmoiVersionCmd) +} + +func (c *Config) getChecksums( + ctx context.Context, + rr *github.RepositoryRelease, +) (map[string][]byte, error) { + name := fmt.Sprintf( + "%s_%s_checksums.txt", + c.upgrade.repo, + strings.TrimPrefix(rr.GetTagName(), "v"), + ) + releaseAsset := getReleaseAssetByName(rr, name) + if releaseAsset == nil { + return nil, fmt.Errorf("%s: cannot find release asset", name) + } + + data, err := c.downloadURL(ctx, releaseAsset.GetBrowserDownloadURL()) + if err != nil { + return nil, err + } + + checksums := make(map[string][]byte) + s := bufio.NewScanner(bytes.NewReader(data)) + for s.Scan() { + m := checksumRx.FindStringSubmatch(s.Text()) + if m == nil { + return nil, fmt.Errorf("%q: cannot parse checksum", s.Text()) + } + checksums[m[2]], _ = hex.DecodeString(m[1]) + } + return checksums, s.Err() +} + +func (c *Config) downloadURL(ctx context.Context, url string) ([]byte, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, http.NoBody) + if err != nil { + return nil, err + } + httpClient, err := c.getHTTPClient() + if err != nil { + return nil, err + } + resp, err := chezmoilog.LogHTTPRequest(c.logger, httpClient, req) + if err != nil { + return nil, err + } + if resp.StatusCode != http.StatusOK { + _ = resp.Body.Close() + return nil, fmt.Errorf("%s: %s", url, resp.Status) + } + data, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + if err := resp.Body.Close(); err != nil { + return nil, err + } + return data, nil +} + +func (c *Config) replaceExecutable( + ctx context.Context, executableFilenameAbsPath chezmoi.AbsPath, releaseVersion *semver.Version, + rr *github.RepositoryRelease, +) (err error) { + var archiveFormat chezmoi.ArchiveFormat + var archiveName string + archiveFormat = chezmoi.ArchiveFormatZip + archiveName = fmt.Sprintf( + "%s_%s_%s_%s.zip", + c.upgrade.repo, + releaseVersion, + runtime.GOOS, + runtime.GOARCH, + ) + releaseAsset := getReleaseAssetByName(rr, archiveName) + if releaseAsset == nil { + err = fmt.Errorf("%s: cannot find release asset", archiveName) + return + } + + var archiveData []byte + if archiveData, err = c.downloadURL(ctx, releaseAsset.GetBrowserDownloadURL()); err != nil { + return + } + if err = c.verifyChecksum(ctx, rr, releaseAsset.GetName(), archiveData); err != nil { + return + } + + // Extract the executable from the archive. + var executableData []byte + walkArchiveFunc := func(name string, info fs.FileInfo, r io.Reader, linkname string) error { + if name == c.upgrade.repo+".exe" { + var err error + executableData, err = io.ReadAll(r) + if err != nil { + return err + } + return fs.SkipAll + } + return nil + } + if err = chezmoi.WalkArchive(archiveData, archiveFormat, walkArchiveFunc); err != nil { + return + } + if executableData == nil { + err = fmt.Errorf("%s: cannot find executable in archive", archiveName) + return + } + + // Replace the executable. + if err = c.baseSystem.Rename(executableFilenameAbsPath, executableFilenameAbsPath.Append(".old")); err != nil { + return + } + err = c.baseSystem.WriteFile(executableFilenameAbsPath, executableData, 0o755) + + return +} + +func (c *Config) verifyChecksum( + ctx context.Context, + rr *github.RepositoryRelease, + name string, + data []byte, +) error { + checksums, err := c.getChecksums(ctx, rr) + if err != nil { + return err + } + expectedChecksum, ok := checksums[name] + if !ok { + return fmt.Errorf("%s: checksum not found", name) + } + checksum := sha256.Sum256(data) + if !bytes.Equal(checksum[:], expectedChecksum) { + return fmt.Errorf( + "%s: checksum failed (want %s, got %s)", + name, + hex.EncodeToString(expectedChecksum), + hex.EncodeToString(checksum[:]), + ) + } + return nil +} + +// isWinGetInstall determines if executableAbsPath contains a WinGet installation path. +func isWinGetInstall(fileSystem vfs.Stater, executableAbsPath string) (bool, error) { + realExecutableAbsPath := executableAbsPath + fi, err := os.Lstat(executableAbsPath) + if err != nil { + return false, err + } + if fi.Mode().Type() == fs.ModeSymlink { + realExecutableAbsPath, err = os.Readlink(executableAbsPath) + if err != nil { + return false, err + } + } + winGetSettings := WinGetSettings{ + InstallBehavior: InstallBehavior{ + PortablePackageUserRoot: os.ExpandEnv(`${LOCALAPPDATA}\Microsoft\WinGet\Packages\`), + PortablePackageMachineRoot: os.ExpandEnv(`${PROGRAMFILES}\WinGet\Packages\`), + }, + } + settingsPaths := []string{ + os.ExpandEnv( + `${LOCALAPPDATA}\Packages\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe\LocalState\settings.json`, + ), + os.ExpandEnv(`${LOCALAPPDATA}\Microsoft\WinGet\Settings\settings.json`), + } + for _, settingsPath := range settingsPaths { + if _, err := os.Stat(settingsPath); err == nil { + winGetSettingsContents, err := os.ReadFile(settingsPath) + if err == nil { + if err := chezmoi.FormatJSONC.Unmarshal(winGetSettingsContents, &winGetSettings); err != nil { + return false, err + } + } + } + } + for _, path := range winGetSettings.InstallBehavior.Values() { + path = filepath.Clean(path) + if path == "." { + continue + } + if ok, _ := vfs.Contains(fileSystem, realExecutableAbsPath, path); ok { + return true, nil + } + } + return false, nil +} + +func (c *Config) winGetUpgrade() error { + return fmt.Errorf( + "upgrade command is not currently supported for WinGet installations. chezmoi can still be upgraded via WinGet by running `winget upgrade --id %s.%s --source winget`", + c.upgrade.owner, + c.upgrade.repo, + ) +} + +// getUpgradeMethod attempts to determine the method by which chezmoi can be +// upgraded by looking at how it was installed. +func getUpgradeMethod(fileSystem vfs.Stater, executableAbsPath chezmoi.AbsPath) (string, error) { + if ok, err := isWinGetInstall(fileSystem, executableAbsPath.String()); err != nil { + return "", err + } else if ok { + return upgradeMethodWinGetUpgrade, nil + } + + // If the executable is in the user's home directory, then always use + // replace-executable. + switch userHomeDir, err := os.UserHomeDir(); { + case errors.Is(err, fs.ErrNotExist): + case err != nil: + return "", err + default: + switch executableInUserHomeDir, err := vfs.Contains(fileSystem, executableAbsPath.String(), userHomeDir); { + case errors.Is(err, fs.ErrNotExist): + case err != nil: + return "", err + case executableInUserHomeDir: + return upgradeMethodReplaceExecutable, nil + } + } + + // If the executable is in the system's temporary directory, then always use + // replace-executable. + if executableIsInTempDir, err := vfs.Contains(fileSystem, executableAbsPath.String(), os.TempDir()); err != nil { + return "", err + } else if executableIsInTempDir { + return upgradeMethodReplaceExecutable, nil + } + + return "", nil +} + +// getReleaseAssetByName returns the release asset from rr with the given name. +func getReleaseAssetByName(rr *github.RepositoryRelease, name string) *github.ReleaseAsset { + for i, ra := range rr.Assets { + if ra.GetName() == name { + return rr.Assets[i] + } + } + return nil +} diff --git a/internal/cmd/util_windows.go b/internal/cmd/util_windows.go index 3fe38bca0c0..73a417dd4a2 100644 --- a/internal/cmd/util_windows.go +++ b/internal/cmd/util_windows.go @@ -2,7 +2,6 @@ package cmd import ( "fmt" - "io/fs" "strings" "golang.org/x/sys/windows/registry" @@ -35,10 +34,6 @@ var defaultInterpreters = map[string]*chezmoi.Interpreter{ }, } -func fileInfoUID(fs.FileInfo) int { - return 0 -} - func windowsVersion() (map[string]any, error) { registryKey, err := registry.OpenKey( registry.LOCAL_MACHINE,
fix
Don't use `replace-executable` for WinGet installations
4d4839442ec884c4fce85cac99ef3d3ade409788
2023-06-10 18:02:22
Tom Payne
chore: Tidy up use of embed package
false
diff --git a/assets/templates/templates.go b/assets/templates/templates.go index 3eef10299ee..4055a33eb7c 100644 --- a/assets/templates/templates.go +++ b/assets/templates/templates.go @@ -1,10 +1,13 @@ // Package templates contains chezmoi's templates. package templates -import "embed" +import _ "embed" -// FS contains all templates. -// -//go:embed *.sh -//go:embed *.tmpl -var FS embed.FS +//go:embed COMMIT_MESSAGE.tmpl +var CommitMessageTmpl []byte + +//go:embed install.sh +var InstallSH []byte + +//go:embed versioninfo.json.tmpl +var VersionInfoJSON []byte diff --git a/assets/templates/templates_test.go b/assets/templates/templates_test.go deleted file mode 100644 index fd6320a51b3..00000000000 --- a/assets/templates/templates_test.go +++ /dev/null @@ -1,12 +0,0 @@ -package templates - -import ( - "testing" - - "github.com/alecthomas/assert/v2" -) - -func TestFS(t *testing.T) { - _, err := FS.ReadFile("COMMIT_MESSAGE.tmpl") - assert.NoError(t, err) -} diff --git a/pkg/cmd/config.go b/pkg/cmd/config.go index 4787e82ca86..fb83cd6273a 100644 --- a/pkg/cmd/config.go +++ b/pkg/cmd/config.go @@ -1332,10 +1332,6 @@ func (c *Config) gitAutoCommit(status *git.Status) error { if status.Empty() { return nil } - commitMessageTemplate, err := templates.FS.ReadFile("COMMIT_MESSAGE.tmpl") - if err != nil { - return err - } funcMap := maps.Clone(sprig.TxtFuncMap()) funcMap["targetRelPath"] = func(source string) string { return chezmoi.NewSourceRelPath(source).TargetRelPath(c.encryption.EncryptedSuffix()).String() @@ -1343,7 +1339,7 @@ func (c *Config) gitAutoCommit(status *git.Status) error { templateOptions := chezmoi.TemplateOptions{ Options: append([]string(nil), c.Template.Options...), } - commitMessageTmpl, err := chezmoi.ParseTemplate("commit_message", commitMessageTemplate, funcMap, templateOptions) + commitMessageTmpl, err := chezmoi.ParseTemplate("commit_message", templates.CommitMessageTmpl, funcMap, templateOptions) //nolint:lll if err != nil { return err } diff --git a/pkg/cmd/generatecmd.go b/pkg/cmd/generatecmd.go index c6d931797fe..c2cc9fd953e 100644 --- a/pkg/cmd/generatecmd.go +++ b/pkg/cmd/generatecmd.go @@ -31,11 +31,7 @@ func (c *Config) runGenerateCmd(cmd *cobra.Command, args []string) error { builder.Grow(16384) switch args[0] { case "install.sh": - data, err := templates.FS.ReadFile("install.sh") - if err != nil { - return err - } - if _, err := builder.Write(data); err != nil { + if _, err := builder.Write(templates.InstallSH); err != nil { return err } default:
chore
Tidy up use of embed package
0d72f50d0f60b9476c1503fa87e09e9e6a3e6588
2021-10-22 01:43:17
Tom Payne
chore: Sort build artifacts
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index e8f96cf7bc7..d0ba536c082 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -159,16 +159,6 @@ jobs: ./dist/chezmoi-cgo-glibc_linux_amd64/chezmoi --version | tee /dev/stderr | grep -q "chezmoi version v2" ./dist/chezmoi-cgo-musl_linux_amd64/chezmoi --version | tee /dev/stderr | grep -q "chezmoi version v2" ./dist/chezmoi-nocgo_linux_386/chezmoi --version | tee /dev/stderr | grep -q "chezmoi version v2" - - name: Upload artifact chezmoi-linux-amd64 - uses: actions/upload-artifact@v2 - with: - name: chezmoi-linux-amd64 - path: dist/chezmoi-cgo-glibc_linux_amd64/chezmoi - - name: Upload artifact chezmoi-linux-musl-amd64 - uses: actions/upload-artifact@v2 - with: - name: chezmoi-linux-musl-amd64 - path: dist/chezmoi-cgo-musl_linux_amd64/chezmoi - name: Upload artifact chezmoi-darwin-amd64 uses: actions/upload-artifact@v2 with: @@ -179,6 +169,16 @@ jobs: with: name: chezmoi-darwin-arm64 path: dist/chezmoi-nocgo_darwin_arm64/chezmoi + - name: Upload artifact chezmoi-linux-amd64 + uses: actions/upload-artifact@v2 + with: + name: chezmoi-linux-amd64 + path: dist/chezmoi-cgo-glibc_linux_amd64/chezmoi + - name: Upload artifact chezmoi-linux-musl-amd64 + uses: actions/upload-artifact@v2 + with: + name: chezmoi-linux-musl-amd64 + path: dist/chezmoi-cgo-musl_linux_amd64/chezmoi - name: Upload artifact chezmoi-windows-amd64.exe uses: actions/upload-artifact@v2 with:
chore
Sort build artifacts
7203d6bfce13edea2dd5d7e24face022ef0bf461
2023-10-11 00:58:54
Tom Payne
feat: Set CHEZMOI_ and scriptEnv env vars for all invoked commands
false
diff --git a/assets/chezmoi.io/docs/reference/configuration-file/variables.md.yaml b/assets/chezmoi.io/docs/reference/configuration-file/variables.md.yaml index 5e3875ad4ce..3ad788ae3f0 100644 --- a/assets/chezmoi.io/docs/reference/configuration-file/variables.md.yaml +++ b/assets/chezmoi.io/docs/reference/configuration-file/variables.md.yaml @@ -39,7 +39,7 @@ sections: description: Display progress bars scriptEnv: type: object - description: Extra environment variables for scripts + description: Extra environment variables for scripts and commands scriptTempDir: description: Temporary directory for scripts sourceDir: diff --git a/internal/chezmoi/archivereadersystem.go b/internal/chezmoi/archivereadersystem.go index 5b11e6834ab..c4ffe604872 100644 --- a/internal/chezmoi/archivereadersystem.go +++ b/internal/chezmoi/archivereadersystem.go @@ -109,8 +109,3 @@ func (s *ArchiveReaderSystem) Readlink(name AbsPath) (string, error) { } return "", fs.ErrNotExist } - -// UnderlyingSystem implements System.UnderlyingSystem. -func (s *ArchiveReaderSystem) UnderlyingSystem() System { - return s -} diff --git a/internal/chezmoi/debugsystem.go b/internal/chezmoi/debugsystem.go index 2e2f3eefb5e..beb03b80cfd 100644 --- a/internal/chezmoi/debugsystem.go +++ b/internal/chezmoi/debugsystem.go @@ -191,11 +191,6 @@ func (s *DebugSystem) UnderlyingFS() vfs.FS { return s.system.UnderlyingFS() } -// UnderlyingSystem implements System.UnderlyingSystem. -func (s *DebugSystem) UnderlyingSystem() System { - return s.system -} - // WriteFile implements System.WriteFile. func (s *DebugSystem) WriteFile(name AbsPath, data []byte, perm fs.FileMode) error { err := s.system.WriteFile(name, data, perm) diff --git a/internal/chezmoi/dryrunsystem.go b/internal/chezmoi/dryrunsystem.go index fd0aac4d922..f8abfbc6931 100644 --- a/internal/chezmoi/dryrunsystem.go +++ b/internal/chezmoi/dryrunsystem.go @@ -127,11 +127,6 @@ func (s *DryRunSystem) UnderlyingFS() vfs.FS { return s.system.UnderlyingFS() } -// UnderlyingSystem implements System.UnderlyingSystem. -func (s *DryRunSystem) UnderlyingSystem() System { - return s.system -} - // WriteFile implements System.WriteFile. func (s *DryRunSystem) WriteFile(AbsPath, []byte, fs.FileMode) error { s.setModified() diff --git a/internal/chezmoi/dumpsystem.go b/internal/chezmoi/dumpsystem.go index 44d31491f95..e44d5d5cb48 100644 --- a/internal/chezmoi/dumpsystem.go +++ b/internal/chezmoi/dumpsystem.go @@ -124,11 +124,6 @@ func (s *DumpSystem) UnderlyingFS() vfs.FS { return nil } -// UnderlyingSystem implements System.UnderlyingSystem. -func (s *DumpSystem) UnderlyingSystem() System { - return s -} - // WriteFile implements System.WriteFile. func (s *DumpSystem) WriteFile(filename AbsPath, data []byte, perm fs.FileMode) error { return s.setData(filename.String(), &fileData{ diff --git a/internal/chezmoi/erroronwritesystem.go b/internal/chezmoi/erroronwritesystem.go index 94dc3f04271..0df465b38cf 100644 --- a/internal/chezmoi/erroronwritesystem.go +++ b/internal/chezmoi/erroronwritesystem.go @@ -114,11 +114,6 @@ func (s *ErrorOnWriteSystem) UnderlyingFS() vfs.FS { return s.system.UnderlyingFS() } -// UnderlyingSystem implements System.UnderlyingSystem. -func (s *ErrorOnWriteSystem) UnderlyingSystem() System { - return s.system -} - // WriteFile implements System.WriteFile. func (s *ErrorOnWriteSystem) WriteFile(AbsPath, []byte, fs.FileMode) error { return s.err diff --git a/internal/chezmoi/externaldiffsystem.go b/internal/chezmoi/externaldiffsystem.go index 14d4178320d..6b63a4e5d4c 100644 --- a/internal/chezmoi/externaldiffsystem.go +++ b/internal/chezmoi/externaldiffsystem.go @@ -224,11 +224,6 @@ func (s *ExternalDiffSystem) UnderlyingFS() vfs.FS { return s.system.UnderlyingFS() } -// UnderlyingSystem implements System.UnderlyingSystem. -func (s *ExternalDiffSystem) UnderlyingSystem() System { - return s.system -} - // WriteFile implements System.WriteFile. func (s *ExternalDiffSystem) WriteFile(filename AbsPath, data []byte, perm fs.FileMode) error { if s.filter.IncludeEntryTypeBits(EntryTypeFiles) { diff --git a/internal/chezmoi/gitdiffsystem.go b/internal/chezmoi/gitdiffsystem.go index 6e6bfc7468c..f0e7a39152c 100644 --- a/internal/chezmoi/gitdiffsystem.go +++ b/internal/chezmoi/gitdiffsystem.go @@ -247,11 +247,6 @@ func (s *GitDiffSystem) UnderlyingFS() vfs.FS { return s.system.UnderlyingFS() } -// UnderlyingSystem implements System.UnderlyingSystem. -func (s *GitDiffSystem) UnderlyingSystem() System { - return s.system -} - // WriteFile implements System.WriteFile. func (s *GitDiffSystem) WriteFile(filename AbsPath, data []byte, perm fs.FileMode) error { if s.filter.IncludeEntryTypeBits(EntryTypeFiles) { diff --git a/internal/chezmoi/nullsystem.go b/internal/chezmoi/nullsystem.go index 3197f6ab0bc..ddb7033b370 100644 --- a/internal/chezmoi/nullsystem.go +++ b/internal/chezmoi/nullsystem.go @@ -4,8 +4,3 @@ type NullSystem struct { emptySystemMixin noUpdateSystemMixin } - -// UnderlyingSystem implements System.UnderlyingSystem. -func (s *NullSystem) UnderlyingSystem() System { - return s -} diff --git a/internal/chezmoi/readonlysystem.go b/internal/chezmoi/readonlysystem.go index 6a57482c2f0..46e8c42f898 100644 --- a/internal/chezmoi/readonlysystem.go +++ b/internal/chezmoi/readonlysystem.go @@ -58,8 +58,3 @@ func (s *ReadOnlySystem) Stat(name AbsPath) (fs.FileInfo, error) { func (s *ReadOnlySystem) UnderlyingFS() vfs.FS { return s.system.UnderlyingFS() } - -// UnderlyingSystem implements System.UnderlyingSystem. -func (s *ReadOnlySystem) UnderlyingSystem() System { - return s.system -} diff --git a/internal/chezmoi/realsystem.go b/internal/chezmoi/realsystem.go index f4df6f08e4c..a93330983e0 100644 --- a/internal/chezmoi/realsystem.go +++ b/internal/chezmoi/realsystem.go @@ -128,7 +128,6 @@ func (s *RealSystem) RunScript( if err != nil { return err } - cmd.Env = s.scriptEnv cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr @@ -136,11 +135,6 @@ func (s *RealSystem) RunScript( return s.RunCmd(cmd) } -// SetScriptEnv sets the environment variables for scripts. -func (s *RealSystem) SetScriptEnv(scriptEnv []string) { - s.scriptEnv = scriptEnv -} - // Stat implements System.Stat. func (s *RealSystem) Stat(name AbsPath) (fs.FileInfo, error) { return s.fileSystem.Stat(name.String()) @@ -151,11 +145,6 @@ func (s *RealSystem) UnderlyingFS() vfs.FS { return s.fileSystem } -// UnderlyingSystem implements System.UnderlyingSystem. -func (s *RealSystem) UnderlyingSystem() System { - return s -} - // getScriptWorkingDir returns the script's working directory. // // If this is a before_ script then the requested working directory may not diff --git a/internal/chezmoi/realsystem_unix.go b/internal/chezmoi/realsystem_unix.go index e291f20cdcc..b837824d5a7 100644 --- a/internal/chezmoi/realsystem_unix.go +++ b/internal/chezmoi/realsystem_unix.go @@ -21,7 +21,6 @@ type RealSystem struct { safe bool createScriptTempDirOnce sync.Once scriptTempDir AbsPath - scriptEnv []string devCache map[AbsPath]uint // devCache maps directories to device numbers. tempDirCache map[uint]string // tempDirCache maps device numbers to renameio temporary directories. } diff --git a/internal/chezmoi/sourcestate.go b/internal/chezmoi/sourcestate.go index 735e2ce3dd1..ca20dfec902 100644 --- a/internal/chezmoi/sourcestate.go +++ b/internal/chezmoi/sourcestate.go @@ -124,7 +124,6 @@ type SourceState struct { defaultTemplateData map[string]any userTemplateData map[string]any priorityTemplateData map[string]any - scriptEnv []string templateData map[string]any templateFuncs template.FuncMap templateOptions []string @@ -213,13 +212,6 @@ func WithReadTemplateData(readTemplateData bool) SourceStateOption { } } -// WithScriptEnv sets the script environment variables. -func WithScriptEnv(scriptEnv []string) SourceStateOption { - return func(s *SourceState) { - s.scriptEnv = scriptEnv - } -} - // WithSourceDir sets the source directory. func WithSourceDir(sourceDirAbsPath AbsPath) SourceStateOption { return func(s *SourceState) { @@ -1911,7 +1903,6 @@ func (s *SourceState) newModifyTargetStateEntryFunc( // Run the modifier on the current contents. cmd := interpreter.ExecCommand(tempFile.Name()) - cmd.Env = s.scriptEnv cmd.Stdin = bytes.NewReader(currentContents) cmd.Stderr = os.Stderr contents, err = chezmoilog.LogCmdOutput(cmd) diff --git a/internal/chezmoi/system.go b/internal/chezmoi/system.go index 2e69713b097..7302b3437f4 100644 --- a/internal/chezmoi/system.go +++ b/internal/chezmoi/system.go @@ -38,7 +38,6 @@ type System interface { //nolint:interfacebloat RunScript(scriptname RelPath, dir AbsPath, data []byte, options RunScriptOptions) error Stat(name AbsPath) (fs.FileInfo, error) UnderlyingFS() vfs.FS - UnderlyingSystem() System WriteFile(filename AbsPath, data []byte, perm fs.FileMode) error WriteSymlink(oldname string, newname AbsPath) error } diff --git a/internal/chezmoi/tarwritersystem.go b/internal/chezmoi/tarwritersystem.go index 97fcfd81f74..d66957783e5 100644 --- a/internal/chezmoi/tarwritersystem.go +++ b/internal/chezmoi/tarwritersystem.go @@ -52,11 +52,6 @@ func (s *TarWriterSystem) RunScript( return s.WriteFile(NewAbsPath(scriptname.String()), data, 0o700) } -// UnderlyingSystem implements System.UnderlyingSystem. -func (s *TarWriterSystem) UnderlyingSystem() System { - return s -} - // WriteFile implements System.WriteFile. func (s *TarWriterSystem) WriteFile(filename AbsPath, data []byte, perm fs.FileMode) error { header := s.headerTemplate diff --git a/internal/chezmoi/zipwritersystem.go b/internal/chezmoi/zipwritersystem.go index 766819460b3..c438413c138 100644 --- a/internal/chezmoi/zipwritersystem.go +++ b/internal/chezmoi/zipwritersystem.go @@ -57,11 +57,6 @@ func (s *ZIPWriterSystem) RunScript( return s.WriteFile(NewAbsPath(scriptname.String()), data, 0o700) } -// UnderlyingSystem implements System.UnderlyingSystem. -func (s *ZIPWriterSystem) UnderlyingSystem() System { - return s -} - // WriteFile implements System.WriteFile. func (s *ZIPWriterSystem) WriteFile(filename AbsPath, data []byte, perm fs.FileMode) error { fileHeader := zip.FileHeader{ diff --git a/internal/cmd/cdcmd.go b/internal/cmd/cdcmd.go index 74dd504b3cb..a9e88678f92 100644 --- a/internal/cmd/cdcmd.go +++ b/internal/cmd/cdcmd.go @@ -36,9 +36,10 @@ func (c *Config) newCDCmd() *cobra.Command { } func (c *Config) runCDCmd(cmd *cobra.Command, args []string) error { - if _, ok := os.LookupEnv("CHEZMOI"); ok { + if _, ok := os.LookupEnv("CHEZMOI_SUBSHELL"); ok { return errors.New("already in a chezmoi subshell") } + os.Setenv("CHEZMOI_SUBSHELL", "1") cdCommand, cdArgs, err := c.cdCommand() if err != nil { diff --git a/internal/cmd/config.go b/internal/cmd/config.go index ba5287994b7..67cc3c0d00d 100644 --- a/internal/cmd/config.go +++ b/internal/cmd/config.go @@ -232,7 +232,6 @@ type Config struct { sourceState *chezmoi.SourceState sourceStateErr error templateData *templateData - runEnv []string stdin io.Reader stdout io.Writer @@ -710,9 +709,7 @@ func (c *Config) createAndReloadConfigFile(cmd *cobra.Command) error { return err } c.templateData.sourceDir = sourceDirAbsPath - c.runEnv = append(c.runEnv, "CHEZMOI_SOURCE_DIR="+sourceDirAbsPath.String()) - realSystem := c.baseSystem.UnderlyingSystem().(*chezmoi.RealSystem) //nolint:forcetypeassert - realSystem.SetScriptEnv(c.runEnv) + os.Setenv("CHEZMOI_SOURCE_DIR", sourceDirAbsPath.String()) // Find config template, execute it, and create config file. configTemplate, err := c.findConfigTemplate() @@ -1705,7 +1702,6 @@ func (c *Config) newSourceState( chezmoi.WithLogger(&sourceStateLogger), chezmoi.WithMode(c.Mode), chezmoi.WithPriorityTemplateData(c.Data), - chezmoi.WithScriptEnv(c.runEnv), chezmoi.WithSourceDir(c.SourceDirAbsPath), chezmoi.WithSystem(c.sourceSystem), chezmoi.WithTemplateFuncs(c.templateFuncs), @@ -2091,9 +2087,8 @@ func (c *Config) persistentPreRunRootE(cmd *cobra.Command, args []string) error } } - scriptEnv := os.Environ() templateData := c.getTemplateData(cmd) - scriptEnv = append(scriptEnv, "CHEZMOI=1") + os.Setenv("CHEZMOI", "1") for key, value := range map[string]string{ "ARCH": templateData.arch, "ARGS": strings.Join(templateData.args, " "), @@ -2112,10 +2107,10 @@ func (c *Config) persistentPreRunRootE(cmd *cobra.Command, args []string) error "USERNAME": templateData.username, "WORKING_TREE": templateData.workingTree.String(), } { - scriptEnv = append(scriptEnv, "CHEZMOI_"+key+"="+value) + os.Setenv("CHEZMOI_"+key, value) } if c.Verbose { - scriptEnv = append(scriptEnv, "CHEZMOI_VERBOSE=1") + os.Setenv("CHEZMOI_VERBOSE", "1") } for groupKey, group := range map[string]map[string]any{ "KERNEL": templateData.kernel, @@ -2124,16 +2119,14 @@ func (c *Config) persistentPreRunRootE(cmd *cobra.Command, args []string) error "WINDOWS_VERSION": templateData.windowsVersion, } { for key, value := range group { - upperSnakeCaseKey := camelCaseToUpperSnakeCase(key) + key := "CHEZMOI_" + groupKey + "_" + camelCaseToUpperSnakeCase(key) valueStr := fmt.Sprintf("%s", value) - scriptEnv = append(scriptEnv, "CHEZMOI_"+groupKey+"_"+upperSnakeCaseKey+"="+valueStr) + os.Setenv(key, valueStr) } } for key, value := range c.ScriptEnv { - scriptEnv = append(scriptEnv, key+"="+value) + os.Setenv(key, value) } - c.runEnv = scriptEnv - realSystem.SetScriptEnv(scriptEnv) if command := c.Hooks[cmd.Name()].Pre; command.Command != "" { if err := c.run(c.homeDirAbsPath, command.Command, command.Args); err != nil { @@ -2326,7 +2319,6 @@ func (c *Config) run(dir chezmoi.AbsPath, name string, args []string) error { } cmd.Dir = dirRawAbsPath.String() } - cmd.Env = c.runEnv cmd.Stdin = c.stdin cmd.Stdout = c.stdout cmd.Stderr = c.stderr diff --git a/internal/cmd/testdata/scripts/issue3268.txtar b/internal/cmd/testdata/scripts/issue3268.txtar new file mode 100644 index 00000000000..b33956e7f21 --- /dev/null +++ b/internal/cmd/testdata/scripts/issue3268.txtar @@ -0,0 +1,12 @@ +[unix] chmod 755 bin/chezmoi-test-command + +# test that chezmoi sets CHEZMOI_ environment variables +exec chezmoi execute-template '{{ output "chezmoi-test-command" }}' +stdout 'CHEZMOI_SOURCE_DIR=.*/\.local/share/chezmoi\s?$' + +-- bin/chezmoi-test-command -- +#!/bin/sh + +echo CHEZMOI_SOURCE_DIR=${CHEZMOI_SOURCE_DIR} +-- bin/chezmoi-test-command.cmd -- +@echo CHEZMOI_SOURCE_DIR=%CHEZMOI_SOURCE_DIR%
feat
Set CHEZMOI_ and scriptEnv env vars for all invoked commands
5b48fccda9e8962a92621edfc2395bb2bc3b298a
2023-11-19 19:03:04
Yuto Tanaka
chore: Fix typo
false
diff --git a/assets/chezmoi.io/docs/developer/building-on-top-of-chezmoi.md b/assets/chezmoi.io/docs/developer/building-on-top-of-chezmoi.md index 5ffaf0d38c5..13804c27813 100644 --- a/assets/chezmoi.io/docs/developer/building-on-top-of-chezmoi.md +++ b/assets/chezmoi.io/docs/developer/building-on-top-of-chezmoi.md @@ -1,6 +1,6 @@ # Building on top of chezmoi -chezmoi is designed with UNIX-style composibility in mind, and the command line +chezmoi is designed with UNIX-style composability in mind, and the command line tool is semantically versioned. Building on top of chezmoi should primarily be done by executing the binary with arguments and the standard input and output configured appropriately. The `chezmoi dump` and `chezmoi state` commands diff --git a/assets/chezmoi.io/docs/developer/website.md b/assets/chezmoi.io/docs/developer/website.md index e73f71d7905..abdd59e4a70 100644 --- a/assets/chezmoi.io/docs/developer/website.md +++ b/assets/chezmoi.io/docs/developer/website.md @@ -21,7 +21,7 @@ $ cd assets/chezmoi.io $ pip3 install --user -r requirements.txt ``` - === "virutalenv (Recommended)" + === "virtualenv (Recommended)" Create a virtualenv with: diff --git a/assets/chezmoi.io/docs/reference/templates/variables.md b/assets/chezmoi.io/docs/reference/templates/variables.md index 06f84e839f9..ca5339824a1 100644 --- a/assets/chezmoi.io/docs/reference/templates/variables.md +++ b/assets/chezmoi.io/docs/reference/templates/variables.md @@ -18,7 +18,7 @@ chezmoi provides the following automatically-populated variables: | `.chezmoi.kernel` | string | Contains information from `/proc/sys/kernel`. Linux only, useful for detecting specific kernels (e.g. Microsoft's WSL kernel) | | `.chezmoi.os` | string | Operating system, e.g. `darwin`, `linux`, etc. as returned by [runtime.GOOS](https://pkg.go.dev/runtime?tab=doc#pkg-constants) | | `.chezmoi.osRelease` | string | The information from `/etc/os-release`, Linux only, run `chezmoi data` to see its output | -| `.chezmoi.pathListSeparator` | string | The path list separator, typically `;` on Windows and `:` on other systems. Used to separate paths in environment varialbes. ie `/bin:/sbin:/usr/bin` | +| `.chezmoi.pathListSeparator` | string | The path list separator, typically `;` on Windows and `:` on other systems. Used to separate paths in environment variables. ie `/bin:/sbin:/usr/bin` | | `.chezmoi.pathSeparator` | string | The path separator, typically `\` on windows and `/` on unix. Used to separate files and directories in a path. ie `c:\see\dos\run` | | `.chezmoi.sourceDir` | string | The source directory | | `.chezmoi.sourceFile` | string | The path of the template relative to the source directory | diff --git a/assets/chezmoi.io/docs/user-guide/password-managers/bitwarden.md b/assets/chezmoi.io/docs/user-guide/password-managers/bitwarden.md index 7ff0aab349f..b14a9b32bb9 100644 --- a/assets/chezmoi.io/docs/user-guide/password-managers/bitwarden.md +++ b/assets/chezmoi.io/docs/user-guide/password-managers/bitwarden.md @@ -83,7 +83,7 @@ in a template variable, e.g. accessToken = "0.48c78342-1635-48a6-accd-afbe01336365.C0tMmQqHnAp1h0gL8bngprlPOYutt0:B3h5D+YgLvFiQhWkIq6Bow==" ``` -You can then retrive secrets using the `bitwardenSecrets` template function, for +You can then retrieve secrets using the `bitwardenSecrets` template function, for example: ``` diff --git a/assets/scripts/install.ps1 b/assets/scripts/install.ps1 index 273b3b04915..6676cb5296d 100644 --- a/assets/scripts/install.ps1 +++ b/assets/scripts/install.ps1 @@ -70,7 +70,7 @@ function log { [string] $Message ) - if ([int]$LogLevel -ge [int]$MesageLevel) { + if ([int]$LogLevel -ge [int]$MessageLevel) { Write-Host $Message } }
chore
Fix typo
d1790d45584829fc573d50568fa86d7121f6f30e
2023-04-01 15:23:14
dependabot[bot]
chore(deps): bump sigstore/cosign-installer from 2.8.1 to 3.0.1
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 49486bcd30b..e44eba87d8e 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -403,7 +403,7 @@ jobs: - uses: actions/setup-go@4d34df0c2316fe8122ab82dc22947d607c0c91f9 with: go-version: ${{ env.GO_VERSION }} - - uses: sigstore/cosign-installer@9becc617647dfa20ae7b1151972e9b3a2c338a2b + - uses: sigstore/cosign-installer@c3667d99424e7e6047999fb6246c0da843953c65 - name: create-syso run: | make create-syso
chore
bump sigstore/cosign-installer from 2.8.1 to 3.0.1
f8eabef8fcd2feccf41b60e9ae06ea983d59f30b
2022-07-28 04:16:45
Ruijie Yu
feat: Make unmanaged command accept destination directory args
false
diff --git a/assets/chezmoi.io/docs/reference/commands/unmanaged.md b/assets/chezmoi.io/docs/reference/commands/unmanaged.md index 719a8b289d0..511bfe7e336 100644 --- a/assets/chezmoi.io/docs/reference/commands/unmanaged.md +++ b/assets/chezmoi.io/docs/reference/commands/unmanaged.md @@ -1,9 +1,13 @@ -# `unmanaged` +# `unmanaged` [*target*...] -List all unmanaged files in the destination directory. +List all unmanaged files in *target*s. When no *target*s are supplied, list all +unmanaged files in the destination directory. + +It is an error to supply *target*s that are not found on the filesystem. !!! example ```console $ chezmoi unmanaged + $ chezmoi unmanaged ~/.config/chezmoi ~/.ssh ``` diff --git a/pkg/cmd/testdata/scripts/unmanaged.txt b/pkg/cmd/testdata/scripts/unmanaged.txt index dde48b07f1f..220b348037c 100644 --- a/pkg/cmd/testdata/scripts/unmanaged.txt +++ b/pkg/cmd/testdata/scripts/unmanaged.txt @@ -12,6 +12,21 @@ rm $CHEZMOISOURCEDIR/dot_file chezmoi unmanaged cmp stdout golden/unmanaged-dir-file +# test chezmoi unmanaged with arguments +chezmoi unmanaged $HOME${/}.dir $HOME${/}.file +cmp stdout golden/unmanaged-with-args + +# test chezmoi unmanaged, with child of unmanaged dir as argument +chezmoi unmanaged $HOME${/}.dir/subdir +cmp stdout golden/unmanaged-inside-unmanaged + +# test chezmoi unmanaged with managed arguments +chezmoi unmanaged $HOME${/}.create $HOME${/}.file +cmp stdout golden/unmanaged-with-some-managed + +# test that chezmoi unmanaged with absent paths should fail +! chezmoi unmanaged $HOME${/}absent-path + -- golden/unmanaged -- .local -- golden/unmanaged-dir -- @@ -21,3 +36,10 @@ cmp stdout golden/unmanaged-dir-file .dir .file .local +-- golden/unmanaged-with-args -- +.dir +.file +-- golden/unmanaged-inside-unmanaged -- +.dir/subdir +-- golden/unmanaged-with-some-managed -- +.file diff --git a/pkg/cmd/unmanagedcmd.go b/pkg/cmd/unmanagedcmd.go index 37e1f2c3529..94e7bc3d35b 100644 --- a/pkg/cmd/unmanagedcmd.go +++ b/pkg/cmd/unmanagedcmd.go @@ -2,6 +2,7 @@ package cmd import ( "io/fs" + "sort" "strings" "github.com/spf13/cobra" @@ -12,11 +13,11 @@ import ( func (c *Config) newUnmanagedCmd() *cobra.Command { unmanagedCmd := &cobra.Command{ - Use: "unmanaged", + Use: "unmanaged [paths]...", Short: "List the unmanaged files in the destination directory", Long: mustLongHelp("unmanaged"), Example: example("unmanaged"), - Args: cobra.NoArgs, + Args: cobra.ArbitraryArgs, RunE: c.makeRunEWithSourceState(c.runUnmanagedCmd), } @@ -24,7 +25,8 @@ func (c *Config) newUnmanagedCmd() *cobra.Command { } func (c *Config) runUnmanagedCmd(cmd *cobra.Command, args []string, sourceState *chezmoi.SourceState) error { - builder := strings.Builder{} + // the set of discovered, unmanaged items + unmanaged := map[string]bool{} walkFunc := func(destAbsPath chezmoi.AbsPath, fileInfo fs.FileInfo, err error) error { if err != nil { return err @@ -32,20 +34,59 @@ func (c *Config) runUnmanagedCmd(cmd *cobra.Command, args []string, sourceState if destAbsPath == c.DestDirAbsPath { return nil } - targeRelPath := destAbsPath.MustTrimDirPrefix(c.DestDirAbsPath) - managed := sourceState.Contains(targeRelPath) - ignored := sourceState.Ignore(targeRelPath) + targetRelPath, err := destAbsPath.TrimDirPrefix(c.DestDirAbsPath) + if err != nil { + return err + } + managed := sourceState.Contains(targetRelPath) + ignored := sourceState.Ignore(targetRelPath) if !managed && !ignored { - builder.WriteString(targeRelPath.String()) - builder.WriteByte('\n') + unmanaged[targetRelPath.String()] = true } if fileInfo.IsDir() && (!managed || ignored) { return vfs.SkipDir } return nil } - if err := chezmoi.Walk(c.destSystem, c.DestDirAbsPath, walkFunc); err != nil { - return err + + // Build queued paths. When no arguments, start from root; otherwise start + // from arguments. The paths are deduplicated and sorted. + paths := make([]chezmoi.AbsPath, 0, len(args)) // (lsttype, size, capacity) + if len(args) == 0 { + paths = append(paths, c.DestDirAbsPath) + } else { + qPaths := make(map[chezmoi.AbsPath]bool, len(args)) // (map, capacity) + for _, arg := range args { + p, err := chezmoi.NormalizePath(arg) + if err != nil { + return err + } + qPaths[p] = true + } + for path := range qPaths { + paths = append(paths, path) + } + sort.Slice(paths, + func(i, j int) bool { return paths[i].Less(paths[j]) }) + } + + for _, path := range paths { + if err := chezmoi.Walk(c.destSystem, path, walkFunc); err != nil { + return err + } + } + + // collect the keys and sort + builder := strings.Builder{} + unmPaths := make([]string, 0, len(unmanaged)) + for path := range unmanaged { + unmPaths = append(unmPaths, path) + } + sort.Strings(unmPaths) + + for _, path := range unmPaths { + builder.WriteString(path) + builder.WriteByte('\n') } return c.writeOutputString(builder.String()) }
feat
Make unmanaged command accept destination directory args
533eeaab0ee1230ac7c3a51e42675d5142c64ca7
2023-05-11 18:37:15
Tom Payne
chore: Update goreleaser config for version 1.18
false
diff --git a/.goreleaser.yaml b/.goreleaser.yaml index ee4a32d36d4..fb5efb3a91a 100644 --- a/.goreleaser.yaml +++ b/.goreleaser.yaml @@ -206,8 +206,8 @@ release: - glob: ./dist/chezmoi-nocgo_windows_amd64_v1/chezmoi.exe name_template: chezmoi-windows-amd64.exe -scoop: - bucket: +scoops: +- bucket: owner: twpayne name: scoop-bucket token: '{{ .Env.SCOOP_GITHUB_TOKEN }}'
chore
Update goreleaser config for version 1.18