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
f7b73d00019f36e29ba3965d51d4151318ceb3d5
2022-04-02 16:05:42
Tom Payne
chore: Tidy up re-add help and flags
false
diff --git a/pkg/cmd/config.go b/pkg/cmd/config.go index d6d1211ecdc..8d087fc2e90 100644 --- a/pkg/cmd/config.go +++ b/pkg/cmd/config.go @@ -380,9 +380,8 @@ func newConfig(options ...configOption) (*Config, error) { recursive: true, }, reAdd: reAddCmdConfig{ - exclude: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesNone), - include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll), - recursive: true, + exclude: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesNone), + include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll), }, state: stateCmdConfig{ data: stateDataCmdConfig{ diff --git a/pkg/cmd/readdcmd.go b/pkg/cmd/readdcmd.go index d1e31a83810..d7ac2daafab 100644 --- a/pkg/cmd/readdcmd.go +++ b/pkg/cmd/readdcmd.go @@ -11,19 +11,18 @@ import ( ) type reAddCmdConfig struct { - exclude *chezmoi.EntryTypeSet - include *chezmoi.EntryTypeSet - recursive bool + exclude *chezmoi.EntryTypeSet + include *chezmoi.EntryTypeSet } func (c *Config) newReAddCmd() *cobra.Command { reAddCmd := &cobra.Command{ - Use: "re-add [targets...]", + Use: "re-add", Short: "Re-add modified files", Long: mustLongHelp("re-add"), Example: example("re-add"), ValidArgsFunction: c.targetValidArgs, - Args: cobra.ArbitraryArgs, + Args: cobra.NoArgs, RunE: c.makeRunEWithSourceState(c.runReAddCmd), Annotations: map[string]string{ modifiesSourceDirectory: "true", @@ -35,7 +34,6 @@ func (c *Config) newReAddCmd() *cobra.Command { flags := reAddCmd.Flags() flags.VarP(c.reAdd.exclude, "exclude", "x", "Exclude entry types") flags.VarP(c.reAdd.include, "include", "i", "Include entry types") - flags.BoolVarP(&c.reAdd.recursive, "recursive", "r", c.reAdd.recursive, "Recurse into subdirectories") return reAddCmd }
chore
Tidy up re-add help and flags
e68328eecd27255aac0a44ca33055f9c02813238
2023-12-01 19:29:22
Tom Payne
chore: Tighten up types in fromToml template function
false
diff --git a/internal/cmd/templatefuncs.go b/internal/cmd/templatefuncs.go index d85be2797df..71c155140c5 100644 --- a/internal/cmd/templatefuncs.go +++ b/internal/cmd/templatefuncs.go @@ -198,7 +198,7 @@ func (c *Config) fromJsoncTemplateFunc(s string) any { } func (c *Config) fromTomlTemplateFunc(s string) any { - var value any + var value map[string]any if err := chezmoi.FormatTOML.Unmarshal([]byte(s), &value); err != nil { panic(err) }
chore
Tighten up types in fromToml template function
17c480b2ebc3b1152f7c8b3d7a0f709f1c6f46f4
2022-05-16 23:55:33
Tom Payne
feat: Build for riscv64
false
diff --git a/.goreleaser.yaml b/.goreleaser.yaml index b6b9e67ad72..dace2e7fa67 100644 --- a/.goreleaser.yaml +++ b/.goreleaser.yaml @@ -56,6 +56,7 @@ builds: - mips64le - ppc64 - ppc64le + - riscv64 - s390x goarm: - "" diff --git a/assets/chezmoi.io/docs/install.md.tmpl b/assets/chezmoi.io/docs/install.md.tmpl index a45d6a0d5e6..eb63639c3e6 100644 --- a/assets/chezmoi.io/docs/install.md.tmpl +++ b/assets/chezmoi.io/docs/install.md.tmpl @@ -148,19 +148,19 @@ Download a package for your distribution and architecture. === "deb" -{{ range $arch := list "amd64" "arm64" "armel" "i386" "mips64" "mips64le" "ppc64" "ppc64le" "s390x" }} +{{ range $arch := list "amd64" "arm64" "armel" "i386" "mips64" "mips64le" "ppc64" "ppc64le" "riscv64" "s390x" }} [`{{ $arch }}`](https://github.com/twpayne/chezmoi/releases/download/v{{ $version }}/chezmoi_{{ $version }}_linux_{{ $arch }}.deb) {{- end }} === "rpm" -{{ range $arch := list "aarch64" "armhfp" "i686" "mips64" "mips64le" "ppc64" "ppc64le" "s390x" "x86_64" }} +{{ range $arch := list "aarch64" "armhfp" "i686" "mips64" "mips64le" "ppc64" "ppc64le" "s390x" "riscv64" "x86_64" }} [`{{ $arch }}`](https://github.com/twpayne/chezmoi/releases/download/v{{ $version }}/chezmoi-{{ $version }}-{{ $arch }}.rpm) {{- end }} === "apk" -{{ range $arch := list "386" "amd64" "arm" "arm64" "mips64" "mips64le" "ppc64" "ppc64le" "s390x" }} +{{ range $arch := list "386" "amd64" "arm" "arm64" "mips64" "mips64le" "ppc64" "ppc64le" "riscv64" "s390x" }} [`{{ $arch }}`](https://github.com/twpayne/chezmoi/releases/download/v{{ $version }}/chezmoi_{{ $version }}_linux_{{ $arch }}.apk) {{- end }} @@ -171,7 +171,7 @@ pre-built binary and shell completions. === "Linux" -{{ range $arch := list "amd64" "arm" "arm64" "i386" "mips64" "mips64le" "ppc64" "ppc64le" "s390x" }} +{{ range $arch := list "amd64" "arm" "arm64" "i386" "mips64" "mips64le" "ppc64" "ppc64le" "riscv64" "s390x" }} [`{{ $arch }}`](https://github.com/twpayne/chezmoi/releases/download/v{{ $version }}/chezmoi_{{ $version }}_linux_{{ $arch }}.tar.gz) {{- end }} [`amd64` (glibc)](https://github.com/twpayne/chezmoi/releases/download/v{{ $version }}/chezmoi_{{ $version }}_linux-glibc_amd64.tar.gz) diff --git a/assets/scripts/install.sh b/assets/scripts/install.sh index 5be59e10774..1b5f5673755 100644 --- a/assets/scripts/install.sh +++ b/assets/scripts/install.sh @@ -166,6 +166,7 @@ check_goos_goarch() { 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 ;;
feat
Build for riscv64
632c3af17023cc9c01ef2ea1e7823111c5ef9599
2022-10-30 01:21:31
Tom Payne
feat: Add --recurse-submodules flag to init command
false
diff --git a/assets/chezmoi.io/docs/reference/commands/init.md b/assets/chezmoi.io/docs/reference/commands/init.md index 44d4723997d..6227e394002 100644 --- a/assets/chezmoi.io/docs/reference/commands/init.md +++ b/assets/chezmoi.io/docs/reference/commands/init.md @@ -99,6 +99,10 @@ Remove the source and config directories after applying. Attempt to remove the chezmoi binary after applying. +## `--recurse-submodules` *bool* + +Recursively clone submodules. This defaults to `true`. + ## `--ssh` Guess an SSH repo URL instead of an HTTPS repo. diff --git a/pkg/cmd/config.go b/pkg/cmd/config.go index f624e99686c..0fb71b29d9b 100644 --- a/pkg/cmd/config.go +++ b/pkg/cmd/config.go @@ -301,9 +301,10 @@ func newConfig(options ...configOption) (*Config, error) { filter: chezmoi.NewEntryTypeFilter(chezmoi.EntryTypesAll, chezmoi.EntryTypesNone), }, init: initCmdConfig{ - data: true, - filter: chezmoi.NewEntryTypeFilter(chezmoi.EntryTypesAll, chezmoi.EntryTypesNone), - guessRepoURL: true, + data: true, + filter: chezmoi.NewEntryTypeFilter(chezmoi.EntryTypesAll, chezmoi.EntryTypesNone), + guessRepoURL: true, + recurseSubmodules: true, }, managed: managedCmdConfig{ filter: chezmoi.NewEntryTypeFilter(chezmoi.EntryTypesAll, chezmoi.EntryTypesNone), diff --git a/pkg/cmd/initcmd.go b/pkg/cmd/initcmd.go index 8f228543f1e..205a98ffdb4 100644 --- a/pkg/cmd/initcmd.go +++ b/pkg/cmd/initcmd.go @@ -19,21 +19,22 @@ import ( ) type initCmdConfig struct { - apply bool - branch string - configPath chezmoi.AbsPath - data bool - depth int - filter *chezmoi.EntryTypeFilter - guessRepoURL bool - oneShot bool - forcePromptOnce bool - promptBool map[string]string - promptInt map[string]int - promptString map[string]string - purge bool - purgeBinary bool - ssh bool + apply bool + branch string + configPath chezmoi.AbsPath + data bool + depth int + filter *chezmoi.EntryTypeFilter + guessRepoURL bool + oneShot bool + forcePromptOnce bool + promptBool map[string]string + promptInt map[string]int + promptString map[string]string + purge bool + purgeBinary bool + recurseSubmodules bool + ssh bool } var dotfilesRepoGuesses = []struct { @@ -129,7 +130,8 @@ func (c *Config) newInitCmd() *cobra.Command { flags.StringToStringVar(&c.init.promptString, "promptString", c.init.promptString, "Populate promptString") flags.BoolVarP(&c.init.purge, "purge", "p", c.init.purge, "Purge config and source directories after running") flags.BoolVarP(&c.init.purgeBinary, "purge-binary", "P", c.init.purgeBinary, "Purge chezmoi binary after running") - flags.BoolVar(&c.init.ssh, "ssh", false, "Use ssh instead of https when guessing dotfile repo URL") + flags.BoolVar(&c.init.recurseSubmodules, "recurse-submodules", c.init.recurseSubmodules, "Checkout submodules recursively") //nolint:lll + flags.BoolVar(&c.init.ssh, "ssh", c.init.ssh, "Use ssh instead of https when guessing dotfile repo URL") return initCmd } @@ -179,7 +181,11 @@ func (c *Config) runInitCmd(cmd *cobra.Command, args []string) error { } else { args := []string{ "clone", - "--recurse-submodules", + } + if c.init.recurseSubmodules { + args = append(args, + "--recurse-submodules", + ) } if c.init.branch != "" { args = append(args,
feat
Add --recurse-submodules flag to init command
046e39b47b88a7c388589eaf3a797498e6912ef7
2022-02-08 07:21:09
Tom Payne
chore: Factor out common errors
false
diff --git a/pkg/chezmoi/chezmoi.go b/pkg/chezmoi/chezmoi.go index a47eb1de1e1..f42aa15e67b 100644 --- a/pkg/chezmoi/chezmoi.go +++ b/pkg/chezmoi/chezmoi.go @@ -10,8 +10,6 @@ import ( "path/filepath" "regexp" "strings" - - "github.com/coreos/go-semver/semver" ) var ( @@ -107,61 +105,6 @@ var modeTypeNames = map[fs.FileMode]string{ fs.ModeCharDevice: "char device", } -// An ExitCodeError indicates the the main program should exit with the given -// code. -type ExitCodeError int - -func (e ExitCodeError) Error() string { - return fmt.Sprintf("exit status %d", int(e)) -} - -// A TooOldErrror is returned when the source state requires a newer version of -// chezmoi. -type TooOldError struct { - Have semver.Version - Need semver.Version -} - -func (e *TooOldError) Error() string { - return fmt.Sprintf("source state requires version %s or later, chezmoi is version %s", e.Need, e.Have) -} - -type inconsistentStateError struct { - targetRelPath RelPath - origins []string -} - -func (e *inconsistentStateError) Error() string { - return fmt.Sprintf("%s: inconsistent state (%s)", e.targetRelPath, strings.Join(e.origins, ", ")) -} - -type notInAbsDirError struct { - pathAbsPath AbsPath - dirAbsPath AbsPath -} - -func (e *notInAbsDirError) Error() string { - return fmt.Sprintf("%s: not in %s", e.pathAbsPath, e.dirAbsPath) -} - -type notInRelDirError struct { - pathRelPath RelPath - dirRelPath RelPath -} - -func (e *notInRelDirError) Error() string { - return fmt.Sprintf("%s: not in %s", e.pathRelPath, e.dirRelPath) -} - -type unsupportedFileTypeError struct { - absPath AbsPath - mode fs.FileMode -} - -func (e *unsupportedFileTypeError) 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) diff --git a/pkg/chezmoi/errors.go b/pkg/chezmoi/errors.go new file mode 100644 index 00000000000..47a4bcacec7 --- /dev/null +++ b/pkg/chezmoi/errors.go @@ -0,0 +1,64 @@ +package chezmoi + +import ( + "fmt" + "io/fs" + "strings" + + "github.com/coreos/go-semver/semver" +) + +// An ExitCodeError indicates the the main program should exit with the given +// code. +type ExitCodeError int + +func (e ExitCodeError) Error() string { + return fmt.Sprintf("exit status %d", int(e)) +} + +// A TooOldErrror is returned when the source state requires a newer version of +// chezmoi. +type TooOldError struct { + Have semver.Version + Need semver.Version +} + +func (e *TooOldError) Error() string { + return fmt.Sprintf("source state requires chezmoi version %s or later, chezmoi is version %s", e.Need, e.Have) +} + +type inconsistentStateError struct { + targetRelPath RelPath + origins []string +} + +func (e *inconsistentStateError) Error() string { + return fmt.Sprintf("%s: inconsistent state (%s)", e.targetRelPath, strings.Join(e.origins, ", ")) +} + +type notInAbsDirError struct { + pathAbsPath AbsPath + dirAbsPath AbsPath +} + +func (e *notInAbsDirError) Error() string { + return fmt.Sprintf("%s: not in %s", e.pathAbsPath, e.dirAbsPath) +} + +type notInRelDirError struct { + pathRelPath RelPath + dirRelPath RelPath +} + +func (e *notInRelDirError) Error() string { + return fmt.Sprintf("%s: not in %s", e.pathRelPath, e.dirRelPath) +} + +type unsupportedFileTypeError struct { + absPath AbsPath + mode fs.FileMode +} + +func (e *unsupportedFileTypeError) Error() string { + return fmt.Sprintf("%s: unsupported file type %s", e.absPath, modeTypeName(e.mode)) +} diff --git a/pkg/chezmoi/sourcestate_test.go b/pkg/chezmoi/sourcestate_test.go index 2c09fd1bbd0..e209b7dbdf8 100644 --- a/pkg/chezmoi/sourcestate_test.go +++ b/pkg/chezmoi/sourcestate_test.go @@ -1284,7 +1284,7 @@ func TestSourceStateRead(t *testing.T) { }, }, }, - expectedError: "source state requires version 2.3.4 or later, chezmoi is version 1.2.3", + expectedError: "source state requires chezmoi version 2.3.4 or later, chezmoi is version 1.2.3", }, { name: "ignore_dir", diff --git a/pkg/cmd/errors.go b/pkg/cmd/errors.go index 4806d64e97a..d1a3329244a 100644 --- a/pkg/cmd/errors.go +++ b/pkg/cmd/errors.go @@ -3,6 +3,8 @@ package cmd import ( "fmt" "os/exec" + + "github.com/coreos/go-semver/semver" ) type cmdOutputError struct { @@ -32,6 +34,14 @@ func (e *cmdOutputError) Unrwap() error { return e.err } +type extractVersionError struct { + output []byte +} + +func (e *extractVersionError) Error() string { + return fmt.Sprintf("%s: cannot extract version", e.output) +} + type parseCmdOutputError struct { command string args []string @@ -55,3 +65,33 @@ func (e *parseCmdOutputError) Error() string { func (e *parseCmdOutputError) Unwrap() error { return e.err } + +type parseVersionError struct { + output []byte + err error +} + +func (e *parseVersionError) Error() string { + return fmt.Sprintf("%s: cannot parse version: %v", e.output, e.err) +} + +func (e *parseVersionError) Unwrap() error { + return e.err +} + +type unsupportedVersionError struct { + version *semver.Version +} + +func (e *unsupportedVersionError) Error() string { + return fmt.Sprintf("%s: unsupported version", e.version) +} + +type versionTooOldError struct { + have *semver.Version + need *semver.Version +} + +func (e *versionTooOldError) Error() string { + return fmt.Sprintf("found version %s, need version %s or later", e.have, e.need) +} diff --git a/pkg/cmd/gopasstemplatefuncs.go b/pkg/cmd/gopasstemplatefuncs.go index 62ef952bf8f..9cc4d4b3d63 100644 --- a/pkg/cmd/gopasstemplatefuncs.go +++ b/pkg/cmd/gopasstemplatefuncs.go @@ -1,7 +1,6 @@ package cmd import ( - "fmt" "os/exec" "regexp" @@ -100,14 +99,19 @@ func (c *Config) gopassVersionCheck() error { } m := gopassVersionRx.FindSubmatch(output) if m == nil { - return fmt.Errorf("%s: could not extract version", output) + return &extractVersionError{ + output: 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 &versionTooOldError{ + have: version, + need: &gopassMinVersion, + } } return nil } diff --git a/pkg/cmd/keepassxctemplatefuncs.go b/pkg/cmd/keepassxctemplatefuncs.go index 5921872c523..c246a69743f 100644 --- a/pkg/cmd/keepassxctemplatefuncs.go +++ b/pkg/cmd/keepassxctemplatefuncs.go @@ -159,7 +159,10 @@ func (c *Config) keepassxcVersion() (*semver.Version, error) { c.Keepassxc.version, err = semver.NewVersion(string(bytes.TrimSpace(output))) if err != nil { - return nil, fmt.Errorf("cannot parse version %s: %w", output, err) + return nil, &parseVersionError{ + output: output, + err: err, + } } return c.Keepassxc.version, nil } diff --git a/pkg/cmd/lastpasstemplatefuncs.go b/pkg/cmd/lastpasstemplatefuncs.go index 9efa669e3f7..d0c7dc777d4 100644 --- a/pkg/cmd/lastpasstemplatefuncs.go +++ b/pkg/cmd/lastpasstemplatefuncs.go @@ -101,14 +101,19 @@ func (c *Config) lastpassVersionCheck() error { } m := lastpassVersionRx.FindSubmatch(output) if m == nil { - return fmt.Errorf("%s: could not extract version", output) + return &extractVersionError{ + output: 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 &versionTooOldError{ + have: version, + need: &lastpassMinVersion, + } } return nil } diff --git a/pkg/cmd/onepasswordtemplatefuncs.go b/pkg/cmd/onepasswordtemplatefuncs.go index 2e849007ed3..127e9ff05a8 100644 --- a/pkg/cmd/onepasswordtemplatefuncs.go +++ b/pkg/cmd/onepasswordtemplatefuncs.go @@ -21,14 +21,6 @@ const ( withoutSessionToken withSessionTokenType = false ) -type unsupportedVersionError struct { - version *semver.Version -} - -func (e unsupportedVersionError) Error() string { - return fmt.Sprintf("%s: unsupported version", e.version) -} - var onepasswordVersionRx = regexp.MustCompile(`^(\d+\.\d+\.\d+\S*)`) type onepasswordConfig struct { @@ -74,7 +66,7 @@ func (c *Config) onepasswordTemplateFunc(userArgs ...string) map[string]interfac case version.Major >= 2: baseArgs = []string{"item", "get", "--format", "json"} default: - panic(unsupportedVersionError{ + panic(&unsupportedVersionError{ version: version, }) } @@ -135,7 +127,7 @@ func (c *Config) onepasswordDetailsFieldsTemplateFunc(userArgs ...string) map[st return result default: - panic(unsupportedVersionError{ + panic(&unsupportedVersionError{ version: version, }) } @@ -154,7 +146,7 @@ func (c *Config) onepasswordDocumentTemplateFunc(userArgs ...string) string { case version.Major >= 2: baseArgs = []string{"document", "get"} default: - panic(unsupportedVersionError{ + panic(&unsupportedVersionError{ version: version, }) } @@ -212,7 +204,7 @@ func (c *Config) onepasswordItemFieldsTemplateFunc(userArgs ...string) map[strin return result default: - panic(unsupportedVersionError{ + panic(&unsupportedVersionError{ version: version, }) } @@ -367,13 +359,18 @@ func (c *Config) onepasswordVersion() (*semver.Version, error) { m := onepasswordVersionRx.FindSubmatch(output) if m == nil { - c.Onepassword.versionErr = fmt.Errorf("%q: cannot extract version", bytes.TrimSpace(output)) + c.Onepassword.versionErr = &extractVersionError{ + output: output, + } return nil, c.Onepassword.versionErr } version, err := semver.NewVersion(string(m[1])) if err != nil { - c.Onepassword.versionErr = fmt.Errorf("%q: cannot parse version: %w", m[1], err) + c.Onepassword.versionErr = &parseVersionError{ + output: m[1], + err: err, + } return nil, c.Onepassword.versionErr } diff --git a/pkg/cmd/testdata/scripts/errors.txt b/pkg/cmd/testdata/scripts/errors.txt index 0085192dd85..aa6867a8539 100644 --- a/pkg/cmd/testdata/scripts/errors.txt +++ b/pkg/cmd/testdata/scripts/errors.txt @@ -21,12 +21,12 @@ chhome home4/user # test that chezmoi checks .chezmoiversion ! chezmoi verify -stderr 'source state requires version' +stderr 'source state requires chezmoi version' chhome home5/user # test that chezmoi checks .chezmoiversion when .chezmoiroot is used ! chezmoi verify -stderr 'source state requires version' +stderr 'source state requires chezmoi version' chhome home6/user
chore
Factor out common errors
7eb8d38a1bd424d06613393942f6ab129f83637f
2023-05-15 00:05:15
Tom Payne
chore: Refactor internal handling of remove_ directories
false
diff --git a/pkg/chezmoi/attr.go b/pkg/chezmoi/attr.go index ef72486b387..37acac378b3 100644 --- a/pkg/chezmoi/attr.go +++ b/pkg/chezmoi/attr.go @@ -7,6 +7,21 @@ import ( "github.com/rs/zerolog" ) +// A SourceDirTargetType is the type of a target represented by a directory in +// the source state. +type SourceDirTargetType int + +// Source dir types. +const ( + SourceDirTypeDir SourceDirTargetType = iota + SourceDirTypeRemove +) + +var sourceDirTypeStrs = map[SourceDirTargetType]string{ + SourceDirTypeDir: "dir", + SourceDirTypeRemove: "remove", +} + // A SourceFileTargetType is a the type of a target represented by a file in the // source state. A file in the source state can represent a file, script, or // symlink in the target state. @@ -55,11 +70,11 @@ const ( // DirAttr holds attributes parsed from a source directory name. type DirAttr struct { TargetName string + Type SourceDirTargetType Exact bool External bool Private bool ReadOnly bool - Remove bool } // A FileAttr holds attributes parsed from a source file name. @@ -78,12 +93,24 @@ type FileAttr struct { // parseDirAttr parses a single directory name in the source state. func parseDirAttr(sourceName string) DirAttr { - name := sourceName - name, external := CutPrefix(name, externalPrefix) - name, remove := CutPrefix(name, removePrefix) - name, exact := CutPrefix(name, exactPrefix) - name, private := CutPrefix(name, privatePrefix) - name, readOnly := CutPrefix(name, readOnlyPrefix) + var ( + sourceDirType = SourceDirTypeDir + name = sourceName + external = false + exact = false + private = false + readOnly = false + ) + switch { + case strings.HasPrefix(name, removePrefix): + sourceDirType = SourceDirTypeRemove + name = name[len(removePrefix):] + default: + name, external = CutPrefix(name, externalPrefix) + name, exact = CutPrefix(name, exactPrefix) + name, private = CutPrefix(name, privatePrefix) + name, readOnly = CutPrefix(name, readOnlyPrefix) + } switch { case strings.HasPrefix(name, dotPrefix): name = "." + name[len(dotPrefix):] @@ -92,43 +119,45 @@ func parseDirAttr(sourceName string) DirAttr { } return DirAttr{ TargetName: name, + Type: sourceDirType, Exact: exact, External: external, Private: private, ReadOnly: readOnly, - Remove: remove, } } // MarshalZerologObject implements // github.com/rs/zerolog.ObjectMarshaler.MarshalZerologObject. func (da DirAttr) MarshalZerologObject(e *zerolog.Event) { - e.Str("targetName", da.TargetName) - e.Bool("exact", da.Exact) - e.Bool("external", da.External) - e.Bool("private", da.Private) - e.Bool("readOnly", da.ReadOnly) - e.Bool("remove", da.Remove) + e.Str("TargetName", da.TargetName) + e.Str("Type", sourceDirTypeStrs[da.Type]) + e.Bool("Exact", da.Exact) + e.Bool("External", da.External) + e.Bool("Private", da.Private) + e.Bool("ReadOnly", da.ReadOnly) } // SourceName returns da's source name. func (da DirAttr) SourceName() string { sourceName := "" - if da.External { - sourceName += externalPrefix - } - if da.Remove { + switch da.Type { + case SourceDirTypeDir: + if da.External { + sourceName += externalPrefix + } + if da.Exact { + sourceName += exactPrefix + } + if da.Private { + sourceName += privatePrefix + } + if da.ReadOnly { + sourceName += readOnlyPrefix + } + case SourceDirTypeRemove: sourceName += removePrefix } - if da.Exact { - sourceName += exactPrefix - } - if da.Private { - sourceName += privatePrefix - } - if da.ReadOnly { - sourceName += readOnlyPrefix - } switch { case strings.HasPrefix(da.TargetName, "."): sourceName += dotPrefix + da.TargetName[len("."):] diff --git a/pkg/chezmoi/attr_test.go b/pkg/chezmoi/attr_test.go index 54415d974b8..de56aad8240 100644 --- a/pkg/chezmoi/attr_test.go +++ b/pkg/chezmoi/attr_test.go @@ -9,35 +9,42 @@ import ( ) func TestDirAttr(t *testing.T) { - testData := struct { + var dirAttrs []DirAttr + targetNames := []string{ + ".dir", + "dir.tmpl", + "dir", + "exact_dir", + "empty_dir", + "encrypted_dir", + "executable_dir", + "once_dir", + "run_dir", + "run_once_dir", + "symlink_dir", + } + assert.NoError(t, combinator.Generate(&dirAttrs, struct { + Type SourceDirTargetType TargetName []string Exact []bool External []bool Private []bool ReadOnly []bool - Remove []bool }{ - TargetName: []string{ - ".dir", - "dir.tmpl", - "dir", - "exact_dir", - "empty_dir", - "encrypted_dir", - "executable_dir", - "once_dir", - "run_dir", - "run_once_dir", - "symlink_dir", - }, - Exact: []bool{false, true}, - External: []bool{false, true}, - Private: []bool{false, true}, - ReadOnly: []bool{false, true}, - Remove: []bool{false, true}, - } - var dirAttrs []DirAttr - assert.NoError(t, combinator.Generate(&dirAttrs, testData)) + Type: SourceDirTypeDir, + TargetName: targetNames, + Exact: []bool{false, true}, + External: []bool{false, true}, + Private: []bool{false, true}, + ReadOnly: []bool{false, true}, + })) + assert.NoError(t, combinator.Generate(&dirAttrs, struct { + Type SourceDirTargetType + TargetName []string + }{ + Type: SourceDirTypeRemove, + TargetName: targetNames, + })) for _, dirAttr := range dirAttrs { actualSourceName := dirAttr.SourceName() actualDirAttr := parseDirAttr(actualSourceName) @@ -90,6 +97,7 @@ func TestFileAttr(t *testing.T) { "modify_name", "name.literal", "name", + "remove_", "run_name", "symlink_name", "template.tmpl", diff --git a/pkg/chezmoi/sourcestate.go b/pkg/chezmoi/sourcestate.go index 52f86e15403..3ef30c5ea8c 100644 --- a/pkg/chezmoi/sourcestate.go +++ b/pkg/chezmoi/sourcestate.go @@ -911,7 +911,7 @@ func (s *SourceState) Read(ctx context.Context, options *ReadOptions) error { allSourceStateEntriesMu.Unlock() return fs.SkipDir } - if sourceStateDir.Attr.Remove { + if sourceStateDir.Attr.Type == SourceDirTypeRemove { s.Lock() s.removeDirs[targetRelPath] = struct{}{} s.Unlock() diff --git a/pkg/cmd/chattrcmd.go b/pkg/cmd/chattrcmd.go index 5f0dd1722ec..b72da2fe7ef 100644 --- a/pkg/cmd/chattrcmd.go +++ b/pkg/cmd/chattrcmd.go @@ -42,6 +42,14 @@ const ( orderModifierSetAfter orderModifier = 2 ) +type sourceDirTypeModifier int + +const ( + sourceDirTypeModifierLeaveUnchanged sourceDirTypeModifier = iota + sourceDirTypeModifierSetRemove + sourceDirTypeModifierClearRemove +) + type sourceFileTypeModifier int const ( @@ -50,6 +58,8 @@ const ( sourceFileTypeModifierClearCreate sourceFileTypeModifierSetModify sourceFileTypeModifierClearModify + sourceFileTypeModifierSetRemove + sourceFileTypeModifierClearRemove sourceFileTypeModifierSetScript sourceFileTypeModifierClearScript sourceFileTypeModifierSetSymlink @@ -57,6 +67,7 @@ const ( ) type modifier struct { + sourceDirType sourceDirTypeModifier sourceFileType sourceFileTypeModifier condition conditionModifier empty boolModifier @@ -67,7 +78,6 @@ type modifier struct { order orderModifier private boolModifier readOnly boolModifier - remove boolModifier template boolModifier } @@ -288,6 +298,23 @@ func (m orderModifier) modify(order chezmoi.ScriptOrder) chezmoi.ScriptOrder { } } +// modify returns the modified value of type. +func (m sourceDirTypeModifier) modify(sourceDirType chezmoi.SourceDirTargetType) chezmoi.SourceDirTargetType { + switch m { + case sourceDirTypeModifierLeaveUnchanged: + return sourceDirType + case sourceDirTypeModifierSetRemove: + return chezmoi.SourceDirTypeRemove + case sourceDirTypeModifierClearRemove: + if sourceDirType == chezmoi.SourceDirTypeRemove { + return chezmoi.SourceDirTypeDir + } + return sourceDirType + default: + panic(fmt.Sprintf("%d: unknown type modifier", m)) + } +} + // modify returns the modified value of type. func (m sourceFileTypeModifier) modify(sourceFileType chezmoi.SourceFileTargetType) chezmoi.SourceFileTargetType { switch m { @@ -300,6 +327,13 @@ func (m sourceFileTypeModifier) modify(sourceFileType chezmoi.SourceFileTargetTy return chezmoi.SourceFileTypeFile } return sourceFileType + case sourceFileTypeModifierSetRemove: + return chezmoi.SourceFileTypeRemove + case sourceFileTypeModifierClearRemove: + if sourceFileType == chezmoi.SourceFileTypeRemove { + return chezmoi.SourceFileTypeFile + } + return sourceFileType case sourceFileTypeModifierSetModify: return chezmoi.SourceFileTypeModify case sourceFileTypeModifierClearModify: @@ -412,7 +446,14 @@ func parseModifier(s string) (*modifier, error) { case "readonly", "r": m.readOnly = bm case "remove": - m.remove = bm + switch bm { + case boolModifierClear: + m.sourceDirType = sourceDirTypeModifierClearRemove + m.sourceFileType = sourceFileTypeModifierClearRemove + case boolModifierSet: + m.sourceDirType = sourceDirTypeModifierSetRemove + m.sourceFileType = sourceFileTypeModifierSetRemove + } case "script": switch bm { case boolModifierClear: @@ -438,13 +479,23 @@ func parseModifier(s string) (*modifier, error) { // modifyDirAttr returns the modified value of dirAttr. func (m *modifier) modifyDirAttr(dirAttr chezmoi.DirAttr) chezmoi.DirAttr { - return chezmoi.DirAttr{ - TargetName: dirAttr.TargetName, - Exact: m.exact.modify(dirAttr.Exact), - External: m.external.modify(dirAttr.External), - Private: m.private.modify(dirAttr.Private), - ReadOnly: m.readOnly.modify(dirAttr.ReadOnly), - Remove: m.remove.modify(dirAttr.Remove), + switch m.sourceDirType.modify(dirAttr.Type) { + case chezmoi.SourceDirTypeDir: + return chezmoi.DirAttr{ + TargetName: dirAttr.TargetName, + Type: chezmoi.SourceDirTypeDir, + Exact: m.exact.modify(dirAttr.Exact), + External: m.external.modify(dirAttr.External), + Private: m.private.modify(dirAttr.Private), + ReadOnly: m.readOnly.modify(dirAttr.ReadOnly), + } + case chezmoi.SourceDirTypeRemove: + return chezmoi.DirAttr{ + TargetName: dirAttr.TargetName, + Type: chezmoi.SourceDirTypeRemove, + } + default: + panic(fmt.Sprintf("%d: unknown source dir type", dirAttr.Type)) } } diff --git a/pkg/cmd/testdata/scripts/chattr.txtar b/pkg/cmd/testdata/scripts/chattr.txtar index 48fa9840388..fb1bdf8dd4b 100644 --- a/pkg/cmd/testdata/scripts/chattr.txtar +++ b/pkg/cmd/testdata/scripts/chattr.txtar @@ -78,6 +78,21 @@ exec chezmoi chattr readonly $HOME${/}.dir ! exists $CHEZMOISOURCEDIR/exact_dot_dir exists $CHEZMOISOURCEDIR/exact_readonly_dot_dir +# test that chezmoi chattr remove sets the remove attribute on a directory +exec chezmoi chattr remove $HOME${/}.dir +! exists $CHEZMOISOURCEDIR/exact_readonly_dot_dir +exists $CHEZMOISOURCEDIR/remove_dot_dir + +# test that chezmoi chattr noremove removes the remove attribute on a directory +exec chezmoi chattr noremove $HOME${/}.dir +! exists $CHEZMOISOURCEDIR/remove_dot_dir +exists $CHEZMOISOURCEDIR/dot_dir + +# test that chezmoi chattr exact,readonly sets the exact and readonly attributes on a directory +exec chezmoi chattr exact,readonly $HOME${/}.dir +! exists $CHEZMOISOURCEDIR/dot_dir +exists $CHEZMOISOURCEDIR/exact_readonly_dot_dir + # test that chezmoi chattr +t sets the template attribute on a symlink exists $CHEZMOISOURCEDIR/symlink_dot_symlink exec chezmoi chattr +t $HOME${/}.symlink
chore
Refactor internal handling of remove_ directories
dbc474be6282090e717207be65011d1c193652f0
2022-01-29 23:06:47
Tom Payne
chore: Tidy up pass template functions
false
diff --git a/pkg/cmd/passtemplatefuncs.go b/pkg/cmd/passtemplatefuncs.go index 5e3233e131c..9d85f41a664 100644 --- a/pkg/cmd/passtemplatefuncs.go +++ b/pkg/cmd/passtemplatefuncs.go @@ -13,9 +13,44 @@ type passConfig struct { cache map[string][]byte } -func (c *Config) passOutput(id string) []byte { +func (c *Config) passTemplateFunc(id string) string { + output, err := c.passOutput(id) + if err != nil { + returnTemplateError(err) + return "" + } + firstLine, _, _ := chezmoi.CutBytes(output, []byte{'\n'}) + return string(bytes.TrimSpace(firstLine)) +} + +func (c *Config) passFieldsTemplateFunc(id string) map[string]string { + output, err := c.passOutput(id) + if err != nil { + returnTemplateError(err) + return nil + } + + result := make(map[string]string) + for _, line := range bytes.Split(output, []byte{'\n'}) { + if key, value, ok := chezmoi.CutBytes(line, []byte{':'}); ok { + result[string(bytes.TrimSpace(key))] = string(bytes.TrimSpace(value)) + } + } + return result +} + +func (c *Config) passRawTemplateFunc(id string) string { + output, err := c.passOutput(id) + if err != nil { + returnTemplateError(err) + return "" + } + return string(output) +} + +func (c *Config) passOutput(id string) ([]byte, error) { if output, ok := c.Pass.cache[id]; ok { - return output + return output, nil } name := c.Pass.Command @@ -25,8 +60,7 @@ func (c *Config) passOutput(id string) []byte { cmd.Stderr = c.stderr output, err := c.baseSystem.IdempotentCmdOutput(cmd) if err != nil { - returnTemplateError(fmt.Errorf("%s: %w", shellQuoteCommand(name, args), err)) - return nil + return nil, fmt.Errorf("%s: %w", shellQuoteCommand(name, args), err) } if c.Pass.cache == nil { @@ -34,25 +68,5 @@ func (c *Config) passOutput(id string) []byte { } c.Pass.cache[id] = output - return output -} - -func (c *Config) passTemplateFunc(id string) string { - output, _, _ := chezmoi.CutBytes(c.passOutput(id), []byte{'\n'}) - return string(bytes.TrimSpace(output)) -} - -func (c *Config) passFieldsTemplateFunc(id string) map[string]string { - output := c.passOutput(id) - result := make(map[string]string) - for _, line := range bytes.Split(output, []byte{'\n'}) { - if key, value, ok := chezmoi.CutBytes(line, []byte{':'}); ok { - result[string(bytes.TrimSpace(key))] = string(bytes.TrimSpace(value)) - } - } - return result -} - -func (c *Config) passRawTemplateFunc(id string) string { - return string(c.passOutput(id)) + return output, nil }
chore
Tidy up pass template functions
38ac09fa68fcefb5c5c3f8540f73a5442ef84ad3
2022-08-24 20:50:11
Tom Payne
chore: Bump golangci-lint to v1.49.0
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 875bd688983..750cd47527d 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -12,7 +12,7 @@ env: AGE_VERSION: 1.0.0 GO_VERSION: 1.19 GOFUMPT_VERSION: 0.3.1 - GOLANGCI_LINT_VERSION: 1.48.0 + GOLANGCI_LINT_VERSION: 1.49.0 TPARSE_VERSION: 0.11.1 jobs: changes: diff --git a/.golangci.yml b/.golangci.yml index 9109807775b..389516913af 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -3,7 +3,7 @@ linters: - asciicheck - bidichk - bodyclose - - deadcode + - contextcheck - decorder - depguard - dogsled @@ -31,8 +31,10 @@ linters: - govet - importas - ineffassign + - interfacebloat - ireturn - lll + - logrlint - makezero - misspell - nilerr @@ -42,6 +44,7 @@ linters: - prealloc - predeclared - promlinter + - reassign - revive - staticcheck - stylecheck @@ -52,11 +55,9 @@ linters: - unconvert - unparam - unused - - varcheck - whitespace disable: - asasalint - - contextcheck # https://github.com/golangci/golangci-lint/issues/2649 - cyclop - exhaustive - exhaustivestruct diff --git a/pkg/chezmoi/chezmoi_test.go b/pkg/chezmoi/chezmoi_test.go index fa22ea0bdac..6241ad42f0e 100644 --- a/pkg/chezmoi/chezmoi_test.go +++ b/pkg/chezmoi/chezmoi_test.go @@ -21,7 +21,7 @@ func init() { Out: os.Stderr, NoColor: true, }) - zerolog.ErrorStackMarshaler = pkgerrors.MarshalStack + zerolog.ErrorStackMarshaler = pkgerrors.MarshalStack //nolint:reassign } func TestEtcHostsFQDNHostname(t *testing.T) { diff --git a/pkg/chezmoi/system.go b/pkg/chezmoi/system.go index 6b10bd93086..2fc2562b78f 100644 --- a/pkg/chezmoi/system.go +++ b/pkg/chezmoi/system.go @@ -14,6 +14,8 @@ import ( // A System reads from and writes to a filesystem, runs scripts, and persists // state. +// +//nolint:interfacebloat type System interface { Chmod(name AbsPath, mode fs.FileMode) error Glob(pattern string) ([]string, error)
chore
Bump golangci-lint to v1.49.0
3b7b84200ad2d5b1dfa5fb58e25c4d8f3ea1aa5a
2022-12-30 00:15:13
Tom Payne
fix: Don't request authentication when cloning public repo with builtin git
false
diff --git a/pkg/cmd/initcmd.go b/pkg/cmd/initcmd.go index cfebf1c92a9..aa6c99041a8 100644 --- a/pkg/cmd/initcmd.go +++ b/pkg/cmd/initcmd.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "io/fs" + "net/url" "regexp" "runtime" "strconv" @@ -45,49 +46,49 @@ var dotfilesRepoGuesses = []struct { }{ { rx: regexp.MustCompile(`\A([-0-9A-Za-z]+)\z`), - httpRepoGuessRepl: "https://[email protected]/$1/dotfiles.git", + httpRepoGuessRepl: "https://github.com/$1/dotfiles.git", httpUsernameGuessRepl: "$1", sshRepoGuessRepl: "[email protected]:$1/dotfiles.git", }, { rx: regexp.MustCompile(`\A([-0-9A-Za-z]+)/([-0-9A-Za-z]+)(\.git)?\z`), - httpRepoGuessRepl: "https://[email protected]/$1/$2.git", + httpRepoGuessRepl: "https://github.com/$1/$2.git", httpUsernameGuessRepl: "$1", sshRepoGuessRepl: "[email protected]:$1/$2.git", }, { rx: regexp.MustCompile(`\A([-.0-9A-Za-z]+)/([-0-9A-Za-z]+)\z`), - httpRepoGuessRepl: "https://$2@$1/$2/dotfiles.git", + httpRepoGuessRepl: "https://$1/$2/dotfiles.git", httpUsernameGuessRepl: "$2", sshRepoGuessRepl: "git@$1:$2/dotfiles.git", }, { rx: regexp.MustCompile(`\A([-0-9A-Za-z]+)/([-0-9A-Za-z]+)/([-.0-9A-Za-z]+)\z`), - httpRepoGuessRepl: "https://$2@$1/$2/$3.git", + httpRepoGuessRepl: "https://$1/$2/$3.git", httpUsernameGuessRepl: "$2", sshRepoGuessRepl: "git@$1:$2/$3.git", }, { rx: regexp.MustCompile(`\A([-.0-9A-Za-z]+)/([-0-9A-Za-z]+)/([-0-9A-Za-z]+)(\.git)?\z`), - httpRepoGuessRepl: "https://$2@$1/$2/$3.git", + httpRepoGuessRepl: "https://$1/$2/$3.git", httpUsernameGuessRepl: "$2", sshRepoGuessRepl: "git@$1:$2/$3.git", }, { rx: regexp.MustCompile(`\A(https?://)([-.0-9A-Za-z]+)/([-0-9A-Za-z]+)/([-0-9A-Za-z]+)(\.git)?\z`), - httpRepoGuessRepl: "$1$3@$2/$3/$4.git", + httpRepoGuessRepl: "$1$2/$3/$4.git", httpUsernameGuessRepl: "$3", sshRepoGuessRepl: "git@$2:$3/$4.git", }, { rx: regexp.MustCompile(`\Asr\.ht/~([a-z_][a-z0-9_-]+)\z`), - httpRepoGuessRepl: "https://[email protected]/~$1/dotfiles", + httpRepoGuessRepl: "https://git.sr.ht/~$1/dotfiles", httpUsernameGuessRepl: "$1", sshRepoGuessRepl: "[email protected]:~$1/dotfiles", }, { rx: regexp.MustCompile(`\Asr\.ht/~([a-z_][a-z0-9_-]+)/([-0-9A-Za-z]+)\z`), - httpRepoGuessRepl: "https://[email protected]/~$1/$2", + httpRepoGuessRepl: "https://git.sr.ht/~$1/$2", httpUsernameGuessRepl: "$1", sshRepoGuessRepl: "[email protected]:~$1/$2", }, @@ -197,8 +198,15 @@ func (c *Config) runInitCmd(cmd *cobra.Command, args []string) error { "--depth", strconv.Itoa(c.init.depth), ) } + dotfilesRepoURL, err := url.Parse(dotfilesRepoURL) + if err != nil { + return err + } + if dotfilesRepoURL.User == nil { + dotfilesRepoURL.User = url.User(username) + } args = append(args, - dotfilesRepoURL, + dotfilesRepoURL.String(), workingTreeRawPath.String(), ) if err := c.run(chezmoi.EmptyAbsPath, c.Git.Command, args); err != nil { diff --git a/pkg/cmd/initcmd_test.go b/pkg/cmd/initcmd_test.go index fecbd22e10f..1730c960347 100644 --- a/pkg/cmd/initcmd_test.go +++ b/pkg/cmd/initcmd_test.go @@ -26,73 +26,73 @@ func TestGuessDotfilesRepoURL(t *testing.T) { }, { arg: "codeberg.org/user", - expectedHTTPRepoURL: "https://[email protected]/user/dotfiles.git", + expectedHTTPRepoURL: "https://codeberg.org/user/dotfiles.git", expectedHTTPUsername: "user", expectedSSHRepoURL: "[email protected]:user/dotfiles.git", }, { arg: "codeberg.org/user/dots", - expectedHTTPRepoURL: "https://[email protected]/user/dots.git", + expectedHTTPRepoURL: "https://codeberg.org/user/dots.git", expectedHTTPUsername: "user", expectedSSHRepoURL: "[email protected]:user/dots.git", }, { arg: "gitlab.com/user", - expectedHTTPRepoURL: "https://[email protected]/user/dotfiles.git", + expectedHTTPRepoURL: "https://gitlab.com/user/dotfiles.git", expectedHTTPUsername: "user", expectedSSHRepoURL: "[email protected]:user/dotfiles.git", }, { arg: "gitlab.com/user/dots", - expectedHTTPRepoURL: "https://[email protected]/user/dots.git", + expectedHTTPRepoURL: "https://gitlab.com/user/dots.git", expectedHTTPUsername: "user", expectedSSHRepoURL: "[email protected]:user/dots.git", }, { arg: "gitlab.com/user/dots.git", - expectedHTTPRepoURL: "https://[email protected]/user/dots.git", + expectedHTTPRepoURL: "https://gitlab.com/user/dots.git", expectedHTTPUsername: "user", expectedSSHRepoURL: "[email protected]:user/dots.git", }, { arg: "http://gitlab.com/user/dots.git", - expectedHTTPRepoURL: "http://[email protected]/user/dots.git", + expectedHTTPRepoURL: "http://gitlab.com/user/dots.git", expectedHTTPUsername: "user", expectedSSHRepoURL: "[email protected]:user/dots.git", }, { arg: "https://gitlab.com/user/dots.git", - expectedHTTPRepoURL: "https://[email protected]/user/dots.git", + expectedHTTPRepoURL: "https://gitlab.com/user/dots.git", expectedHTTPUsername: "user", expectedSSHRepoURL: "[email protected]:user/dots.git", }, { arg: "sr.ht/~user_name", - expectedHTTPRepoURL: "https://[email protected]/~user_name/dotfiles", + expectedHTTPRepoURL: "https://git.sr.ht/~user_name/dotfiles", expectedHTTPUsername: "user_name", expectedSSHRepoURL: "[email protected]:~user_name/dotfiles", }, { arg: "sr.ht/~user_name/dots", - expectedHTTPRepoURL: "https://[email protected]/~user_name/dots", + expectedHTTPRepoURL: "https://git.sr.ht/~user_name/dots", expectedHTTPUsername: "user_name", expectedSSHRepoURL: "[email protected]:~user_name/dots", }, { arg: "user", - expectedHTTPRepoURL: "https://[email protected]/user/dotfiles.git", + expectedHTTPRepoURL: "https://github.com/user/dotfiles.git", expectedHTTPUsername: "user", expectedSSHRepoURL: "[email protected]:user/dotfiles.git", }, { arg: "user/dots", - expectedHTTPRepoURL: "https://[email protected]/user/dots.git", + expectedHTTPRepoURL: "https://github.com/user/dots.git", expectedHTTPUsername: "user", expectedSSHRepoURL: "[email protected]:user/dots.git", }, { arg: "user/dots.git", - expectedHTTPRepoURL: "https://[email protected]/user/dots.git", + expectedHTTPRepoURL: "https://github.com/user/dots.git", expectedHTTPUsername: "user", expectedSSHRepoURL: "[email protected]:user/dots.git", }, diff --git a/pkg/cmd/testdata/scripts/issue-2649.txtar b/pkg/cmd/testdata/scripts/issue-2649.txtar new file mode 100644 index 00000000000..2f7b5b0c675 --- /dev/null +++ b/pkg/cmd/testdata/scripts/issue-2649.txtar @@ -0,0 +1,9 @@ +# test that chezmoi init clones a public dotfiles repo if git is installed +[exec:git] exec chezmoi init --use-builtin-git=false chezmoi +[exec:git] exists ${CHEZMOISOURCEDIR}/README.md + +chhome home2/user + +# test that chezmoi init clones a public dotfiles repo using builtin git +exec chezmoi init --use-builtin-git=true chezmoi +exists ${CHEZMOISOURCEDIR}/README.md
fix
Don't request authentication when cloning public repo with builtin git
29dab4dd633fef0345e5ec67ccec2d9d42326c16
2023-01-29 19:26:58
Tom Payne
feat: Add external_ attribute for directories
false
diff --git a/assets/chezmoi.io/docs/reference/commands/chattr.md b/assets/chezmoi.io/docs/reference/commands/chattr.md index 4370db09183..3124522a17f 100644 --- a/assets/chezmoi.io/docs/reference/commands/chattr.md +++ b/assets/chezmoi.io/docs/reference/commands/chattr.md @@ -16,6 +16,7 @@ modifiers and their abbreviations are: | `encrypted` | *none* | | `exact` | *none* | | `executable` | `x` | +| `external` | *none* | | `once` | `o` | | `private` | `p` | | `readonly` | `r` | diff --git a/assets/chezmoi.io/docs/reference/source-state-attributes.md b/assets/chezmoi.io/docs/reference/source-state-attributes.md index 2ac5e66c6a9..0000251ad21 100644 --- a/assets/chezmoi.io/docs/reference/source-state-attributes.md +++ b/assets/chezmoi.io/docs/reference/source-state-attributes.md @@ -19,6 +19,7 @@ to as "attributes": | `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 | +| `external_` | Ignore attributes in child entries | | `exact_` | Remove anything not managed by chezmoi | | `executable_` | Add executable permissions to the target file | | `literal_` | Stop parsing prefix attributes | @@ -41,7 +42,7 @@ prefixes is important. | Target type | Source type | Allowed prefixes in order | Allowed suffixes | | ------------- | ----------- | ----------------------------------------------------------------------- | ---------------- | -| Directory | Directory | `remove_`, `exact_`, `private_`, `readonly_`, `dot_` | *none* | +| Directory | Directory | `external_` or `remove_`, `exact_`, `private_`, `readonly_`, `dot_` | *none* | | Regular file | File | `encrypted_`, `private_`, `executable_`, `dot_` | `.tmpl` | | Create file | File | `create_`, `encrypted_`, `private_`, `readonly_`, `executable_`, `dot_` | `.tmpl` | | Modify file | File | `modify_`, `encrypted_`, `private_`, `readonly_`, `executable_`, `dot_` | `.tmpl` | diff --git a/pkg/chezmoi/attr.go b/pkg/chezmoi/attr.go index 5d5a63b5b17..c5389d61fd1 100644 --- a/pkg/chezmoi/attr.go +++ b/pkg/chezmoi/attr.go @@ -56,6 +56,7 @@ const ( type DirAttr struct { TargetName string Exact bool + External bool Private bool ReadOnly bool Remove bool @@ -80,10 +81,15 @@ func parseDirAttr(sourceName string) DirAttr { var ( name = sourceName exact = false + external = false private = false readOnly = false remove = false ) + if strings.HasPrefix(name, externalPrefix) { + name = mustTrimPrefix(name, externalPrefix) + external = true + } if strings.HasPrefix(name, removePrefix) { name = mustTrimPrefix(name, removePrefix) remove = true @@ -109,6 +115,7 @@ func parseDirAttr(sourceName string) DirAttr { return DirAttr{ TargetName: name, Exact: exact, + External: external, Private: private, ReadOnly: readOnly, Remove: remove, @@ -120,6 +127,7 @@ func parseDirAttr(sourceName string) DirAttr { func (da DirAttr) MarshalZerologObject(e *zerolog.Event) { e.Str("targetName", da.TargetName) e.Bool("exact", da.Exact) + e.Bool("external", da.External) e.Bool("private", da.Private) e.Bool("readOnly", da.ReadOnly) e.Bool("remove", da.Remove) @@ -128,6 +136,9 @@ func (da DirAttr) MarshalZerologObject(e *zerolog.Event) { // SourceName returns da's source name. func (da DirAttr) SourceName() string { sourceName := "" + if da.External { + sourceName += externalPrefix + } if da.Remove { sourceName += removePrefix } diff --git a/pkg/chezmoi/attr_test.go b/pkg/chezmoi/attr_test.go index e50d050b731..a85f05c5bdb 100644 --- a/pkg/chezmoi/attr_test.go +++ b/pkg/chezmoi/attr_test.go @@ -13,6 +13,7 @@ func TestDirAttr(t *testing.T) { testData := struct { TargetName []string Exact []bool + External []bool Private []bool ReadOnly []bool Remove []bool @@ -31,6 +32,7 @@ func TestDirAttr(t *testing.T) { "symlink_dir", }, Exact: []bool{false, true}, + External: []bool{false, true}, Private: []bool{false, true}, ReadOnly: []bool{false, true}, Remove: []bool{false, true}, diff --git a/pkg/chezmoi/chezmoi.go b/pkg/chezmoi/chezmoi.go index 50dd4e13960..19e2be96b75 100644 --- a/pkg/chezmoi/chezmoi.go +++ b/pkg/chezmoi/chezmoi.go @@ -51,6 +51,7 @@ const ( encryptedPrefix = "encrypted_" exactPrefix = "exact_" executablePrefix = "executable_" + externalPrefix = "external_" literalPrefix = "literal_" modifyPrefix = "modify_" oncePrefix = "once_" diff --git a/pkg/chezmoi/relpath.go b/pkg/chezmoi/relpath.go index abb0a632a9b..816b4c2ee04 100644 --- a/pkg/chezmoi/relpath.go +++ b/pkg/chezmoi/relpath.go @@ -100,6 +100,16 @@ func (p RelPath) Slice(begin, end int) RelPath { return NewRelPath(p.relPath[begin:end]) } +// SourceRelPath returns p as a SourceRelPath. +func (p RelPath) SourceRelPath() SourceRelPath { + return NewSourceRelPath(p.relPath) +} + +// SourceRelDirPath returns p as a directory SourceRelPath. +func (p RelPath) SourceRelDirPath() SourceRelPath { + return NewSourceRelDirPath(p.relPath) +} + // Split returns p's directory and path. func (p RelPath) Split() (RelPath, RelPath) { dir, file := path.Split(p.relPath) diff --git a/pkg/chezmoi/sourcestate.go b/pkg/chezmoi/sourcestate.go index f10a9c30f83..cdaad1bd8d6 100644 --- a/pkg/chezmoi/sourcestate.go +++ b/pkg/chezmoi/sourcestate.go @@ -876,6 +876,18 @@ func (s *SourceState) Read(ctx context.Context, options *ReadOptions) error { } sourceStateDir := s.newSourceStateDir(sourceAbsPath, sourceRelPath, da) addSourceStateEntries(targetRelPath, sourceStateDir) + if da.External { + sourceStateEntries, err := s.readExternalDir(sourceAbsPath, sourceRelPath, targetRelPath) + if err != nil { + return err + } + allSourceStateEntriesMu.Lock() + for relPath, entries := range sourceStateEntries { + allSourceStateEntries[relPath] = append(allSourceStateEntries[relPath], entries...) + } + allSourceStateEntriesMu.Unlock() + return fs.SkipDir + } if sourceStateDir.Attr.Remove { s.Lock() s.removeDirs[targetRelPath] = struct{}{} @@ -2108,6 +2120,98 @@ func (s *SourceState) readExternalArchive( return sourceStateEntries, nil } +// ReadExternalDir returns all source state entries in an external_ dir. +func (s *SourceState) readExternalDir( + rootSourceAbsPath AbsPath, rootSourceRelPath SourceRelPath, rootTargetRelPath RelPath, +) (map[RelPath][]SourceStateEntry, error) { + sourceStateEntries := make(map[RelPath][]SourceStateEntry) + walkFunc := func(absPath AbsPath, fileInfo fs.FileInfo, err error) error { + switch { + case err != nil: + return err + case absPath == rootSourceAbsPath: + return nil + } + relPath := absPath.MustTrimDirPrefix(rootSourceAbsPath) + targetRelPath := rootTargetRelPath.Join(relPath) + if s.Ignore(targetRelPath) { + if fileInfo.IsDir() { + return fs.SkipDir + } + return nil + } + var sourceStateEntry SourceStateEntry + switch fileInfo.Mode().Type() { + case 0: + fileAttr := FileAttr{ + TargetName: fileInfo.Name(), + Type: SourceFileTypeFile, + Empty: true, + Private: isPrivate(fileInfo), + ReadOnly: isReadOnly(fileInfo), + } + lazyContents := newLazyContentsFunc(func() ([]byte, error) { + return s.system.ReadFile(absPath) + }) + sourceStateEntry = &SourceStateFile{ + lazyContents: lazyContents, + origin: SourceStateOriginAbsPath(absPath), + Attr: fileAttr, + sourceRelPath: rootSourceRelPath.Join(relPath.SourceRelPath()), + targetStateEntry: &TargetStateFile{ + lazyContents: lazyContents, + empty: true, + perm: fileAttr.perm() &^ s.umask, + }, + } + case fs.ModeDir: + dirAttr := DirAttr{ + TargetName: fileInfo.Name(), + Exact: true, + Private: isPrivate(fileInfo), + ReadOnly: isReadOnly(fileInfo), + } + sourceStateEntry = &SourceStateDir{ + origin: SourceStateOriginAbsPath(absPath), + sourceRelPath: rootSourceRelPath.Join(relPath.SourceRelDirPath()), + Attr: dirAttr, + targetStateEntry: &TargetStateDir{ + perm: dirAttr.perm() &^ s.umask, + }, + } + case fs.ModeSymlink: + fileAttr := FileAttr{ + TargetName: fileInfo.Name(), + Type: SourceFileTypeFile, + } + lazyLinkname := newLazyLinknameFunc(func() (string, error) { + return s.system.Readlink(absPath) + }) + sourceStateEntry = &SourceStateFile{ + lazyContents: newLazyContentsFunc(func() ([]byte, error) { + linkname, err := lazyLinkname.Linkname() + if err != nil { + return nil, err + } + return []byte(linkname), nil + }), + origin: SourceStateOriginAbsPath(absPath), + Attr: fileAttr, + sourceRelPath: rootSourceRelPath.Join(relPath.SourceRelPath()), + targetStateEntry: &TargetStateSymlink{ + lazyLinkname: lazyLinkname, + }, + } + } + sourceStateEntries[targetRelPath] = append(sourceStateEntries[targetRelPath], sourceStateEntry) + return nil + } + if err := Walk(s.system, rootSourceAbsPath, walkFunc); err != nil { + return nil, err + } + return sourceStateEntries, nil +} + // readExternalFile reads an external file and returns its SourceStateEntries. func (s *SourceState) readExternalFile( ctx context.Context, externalRelPath RelPath, parentSourceRelPath SourceRelPath, external *External, diff --git a/pkg/chezmoi/sourcestate_test.go b/pkg/chezmoi/sourcestate_test.go index e414dfdd08b..a6597bfd707 100644 --- a/pkg/chezmoi/sourcestate_test.go +++ b/pkg/chezmoi/sourcestate_test.go @@ -1308,6 +1308,88 @@ func TestSourceStateRead(t *testing.T) { ), ), }, + { + name: "external", + root: map[string]any{ + "/home/user/.local/share/chezmoi": map[string]any{ + "external_dir": map[string]any{ + "dot_file": "# contents of dir/dot_file\n", + "subdir": map[string]any{ + "empty_file": "", + }, + "symlink": &vfst.Symlink{Target: "dot_file"}, + }, + }, + }, + expectedSourceState: NewSourceState( + withEntries(map[RelPath]SourceStateEntry{ + NewRelPath("dir"): &SourceStateDir{ + origin: SourceStateOriginAbsPath(NewAbsPath("/home/user/.local/share/chezmoi/external_dir")), + sourceRelPath: NewSourceRelDirPath("external_dir"), + Attr: DirAttr{ + TargetName: "dir", + External: true, + }, + targetStateEntry: &TargetStateDir{ + perm: fs.ModePerm &^ chezmoitest.Umask, + }, + }, + NewRelPath("dir/dot_file"): &SourceStateFile{ + origin: SourceStateOriginAbsPath(NewAbsPath("/home/user/.local/share/chezmoi/external_dir/dot_file")), + sourceRelPath: NewSourceRelPath("external_dir/dot_file"), + Attr: FileAttr{ + TargetName: "dot_file", + Type: SourceFileTypeFile, + Empty: true, + }, + lazyContents: newLazyContents([]byte("# contents of dir/dot_file\n")), + targetStateEntry: &TargetStateFile{ + empty: true, + perm: 0o666 &^ chezmoitest.Umask, + lazyContents: newLazyContents([]byte("# contents of dir/dot_file\n")), + }, + }, + NewRelPath("dir/subdir"): &SourceStateDir{ + origin: SourceStateOriginAbsPath(NewAbsPath("/home/user/.local/share/chezmoi/external_dir/subdir")), + sourceRelPath: NewSourceRelDirPath("external_dir/subdir"), + Attr: DirAttr{ + TargetName: "subdir", + Exact: true, + }, + targetStateEntry: &TargetStateDir{ + perm: fs.ModePerm &^ chezmoitest.Umask, + }, + }, + NewRelPath("dir/subdir/empty_file"): &SourceStateFile{ + origin: SourceStateOriginAbsPath(NewAbsPath("/home/user/.local/share/chezmoi/external_dir/subdir/empty_file")), + sourceRelPath: NewSourceRelPath("external_dir/subdir/empty_file"), + Attr: FileAttr{ + TargetName: "empty_file", + Type: SourceFileTypeFile, + Empty: true, + }, + lazyContents: newLazyContents([]byte{}), + targetStateEntry: &TargetStateFile{ + empty: true, + perm: 0o666 &^ chezmoitest.Umask, + lazyContents: newLazyContents([]byte{}), + }, + }, + NewRelPath("dir/symlink"): &SourceStateFile{ + origin: SourceStateOriginAbsPath(NewAbsPath("/home/user/.local/share/chezmoi/external_dir/symlink")), + sourceRelPath: NewSourceRelPath("external_dir/symlink"), + Attr: FileAttr{ + TargetName: "symlink", + Type: SourceFileTypeFile, + }, + lazyContents: newLazyContents([]byte("dot_file")), + targetStateEntry: &TargetStateSymlink{ + lazyLinkname: newLazyLinkname("dot_file"), + }, + }, + }), + ), + }, { name: "chezmoitemplates", root: map[string]any{ diff --git a/pkg/cmd/chattrcmd.go b/pkg/cmd/chattrcmd.go index 15330774401..4023c6567fb 100644 --- a/pkg/cmd/chattrcmd.go +++ b/pkg/cmd/chattrcmd.go @@ -63,6 +63,7 @@ type modifier struct { encrypted boolModifier exact boolModifier executable boolModifier + external boolModifier order orderModifier private boolModifier readOnly boolModifier @@ -106,6 +107,7 @@ func (c *Config) chattrCmdValidArgs( "encrypted", "exact", "executable", + "external", "modify", "once", "onchange", @@ -382,6 +384,8 @@ func parseModifier(s string) (*modifier, error) { m.exact = bm case "executable", "x": m.executable = bm + case "external": + m.external = bm case "modify": switch bm { case boolModifierClear: @@ -437,6 +441,7 @@ func (m *modifier) modifyDirAttr(dirAttr chezmoi.DirAttr) chezmoi.DirAttr { return chezmoi.DirAttr{ TargetName: dirAttr.TargetName, Exact: m.exact.modify(dirAttr.Exact), + External: m.external.modify(dirAttr.External), Private: m.private.modify(dirAttr.Private), ReadOnly: m.readOnly.modify(dirAttr.ReadOnly), Remove: m.remove.modify(dirAttr.Remove), diff --git a/pkg/cmd/chattrcmd_test.go b/pkg/cmd/chattrcmd_test.go index bad744ae446..3e460c23ebf 100644 --- a/pkg/cmd/chattrcmd_test.go +++ b/pkg/cmd/chattrcmd_test.go @@ -23,7 +23,7 @@ func TestChattrCmdValidArgs(t *testing.T) { }, { toComplete: "e", - expectedCompletions: []string{"empty", "encrypted", "exact", "executable"}, + expectedCompletions: []string{"empty", "encrypted", "exact", "executable", "external"}, expectedShellCompDirective: cobra.ShellCompDirectiveNoFileComp, }, { diff --git a/pkg/cmd/testdata/scripts/externaldir.txtar b/pkg/cmd/testdata/scripts/externaldir.txtar new file mode 100644 index 00000000000..0ea47108379 --- /dev/null +++ b/pkg/cmd/testdata/scripts/externaldir.txtar @@ -0,0 +1,35 @@ +symlink $CHEZMOISOURCEDIR/dot_vim/external_bundle/symlink -> executable_file + +# test that chezmoi ignores attributes in external_ dirs +exec chezmoi apply + +# test that executable_ attributes are ignored and empty files are created +cmp $HOME/.vim/bundle/executable_file $CHEZMOISOURCEDIR/dot_vim/external_bundle/executable_file + +# test that scripts are not run +cmp $HOME/.vim/bundle/run_script.sh $CHEZMOISOURCEDIR/dot_vim/external_bundle/run_script.sh +! stdout evil + +# test that private_ attributes are ignored and subdirectories are created +isdir $HOME/.vim/bundle/private_subdir + +# test that files can be ignored +! exists $HOME/.vim/bundle/private_subdir/.keep + +# test that symlinks are created +issymlink $HOME/.vim/bundle/symlink + +# test that symlink_ attributes are ignored +cmp $HOME/.vim/bundle/symlink_example $CHEZMOISOURCEDIR/dot_vim/external_bundle/symlink_example +! issymlink $HOME/.vim/bundle/symlink_example + +-- home/user/.local/share/chezmoi/.chezmoiignore -- +**/.keep +-- home/user/.local/share/chezmoi/dot_vim/external_bundle/executable_file -- +-- home/user/.local/share/chezmoi/dot_vim/external_bundle/private_subdir/.keep -- +-- home/user/.local/share/chezmoi/dot_vim/external_bundle/run_script.sh -- +#!/bin/sh + +echo evil +-- home/user/.local/share/chezmoi/dot_vim/external_bundle/symlink_example -- +# contents of .vim/bundle/symlink_example
feat
Add external_ attribute for directories
565cbbe117746aa6bfec5f2cee20ae4cbbb5e645
2022-05-30 13:36:04
Tom Payne
chore: Tidy up DumpSystem logic
false
diff --git a/pkg/chezmoi/dumpsystem.go b/pkg/chezmoi/dumpsystem.go index 9e999795e1e..0b959f78fd7 100644 --- a/pkg/chezmoi/dumpsystem.go +++ b/pkg/chezmoi/dumpsystem.go @@ -77,15 +77,11 @@ func (s *DumpSystem) Data() interface{} { // Mkdir implements System.Mkdir. func (s *DumpSystem) Mkdir(dirname AbsPath, perm fs.FileMode) error { - if _, exists := s.data[dirname.String()]; exists { - return fs.ErrExist - } - s.data[dirname.String()] = &dirData{ + return s.setData(dirname.String(), &dirData{ Type: dataTypeDir, Name: dirname, Perm: perm, - } - return nil + }) } // RunCmd implements System.RunCmd. @@ -93,20 +89,16 @@ func (s *DumpSystem) RunCmd(cmd *exec.Cmd) error { if cmd.Dir == "" { return nil } - s.data[cmd.Dir] = &commandData{ + return s.setData(cmd.Dir, &commandData{ Type: dataTypeCommand, Path: cmd.Path, Args: cmd.Args, - } - return nil + }) } // RunScript implements System.RunScript. func (s *DumpSystem) RunScript(scriptname RelPath, dir AbsPath, data []byte, interpreter *Interpreter) error { scriptnameStr := scriptname.String() - if _, exists := s.data[scriptnameStr]; exists { - return fs.ErrExist - } scriptData := &scriptData{ Type: dataTypeScript, Name: NewAbsPath(scriptnameStr), @@ -115,8 +107,7 @@ func (s *DumpSystem) RunScript(scriptname RelPath, dir AbsPath, data []byte, int if !interpreter.None() { scriptData.Interpreter = interpreter } - s.data[scriptnameStr] = scriptData - return nil + return s.setData(scriptnameStr, scriptData) } // UnderlyingFS implements System.UnderlyingFS. @@ -126,29 +117,27 @@ func (s *DumpSystem) UnderlyingFS() vfs.FS { // WriteFile implements System.WriteFile. func (s *DumpSystem) WriteFile(filename AbsPath, data []byte, perm fs.FileMode) error { - filenameStr := filename.String() - if _, exists := s.data[filenameStr]; exists { - return fs.ErrExist - } - s.data[filenameStr] = &fileData{ + return s.setData(filename.String(), &fileData{ Type: dataTypeFile, Name: filename, Contents: string(data), Perm: perm, - } - return nil + }) } // WriteSymlink implements System.WriteSymlink. func (s *DumpSystem) WriteSymlink(oldname string, newname AbsPath) error { - newnameStr := newname.String() - if _, exists := s.data[newnameStr]; exists { - return fs.ErrExist - } - s.data[newnameStr] = &symlinkData{ + return s.setData(newname.String(), &symlinkData{ Type: dataTypeSymlink, Name: newname, Linkname: oldname, + }) +} + +func (s *DumpSystem) setData(key string, value interface{}) error { + if _, ok := s.data[key]; ok { + return fs.ErrExist } + s.data[key] = value return nil }
chore
Tidy up DumpSystem logic
05e94c66dd830063af221c3f942502b679be5c99
2021-12-14 21:41:23
Tom Payne
fix: Add missing --value flag to secret keyring set command
false
diff --git a/internal/cmd/secretkeyringcmd.go b/internal/cmd/secretkeyringcmd.go index 0cc30f5e122..9d5b5e3ec92 100644 --- a/internal/cmd/secretkeyringcmd.go +++ b/internal/cmd/secretkeyringcmd.go @@ -6,6 +6,16 @@ import ( ) type secretKeyringCmdConfig struct { + get secretKeyringGetCmdConfig + set secretKeyringSetCmdConfig +} + +type secretKeyringGetCmdConfig struct { + service string + user string +} + +type secretKeyringSetCmdConfig struct { service string user string value string @@ -18,17 +28,16 @@ func (c *Config) newSecretKeyringCmd() *cobra.Command { Short: "Interact with keyring", } - persistentFlags := keyringCmd.PersistentFlags() - persistentFlags.StringVar(&c.secretKeyring.service, "service", "", "service") - persistentFlags.StringVar(&c.secretKeyring.user, "user", "", "user") - markPersistentFlagsRequired(keyringCmd, "service", "user") - keyringGetCmd := &cobra.Command{ Use: "get", Args: cobra.NoArgs, Short: "Get a value from keyring", RunE: c.runKeyringGetCmdE, } + secretKeyringGetPersistentFlags := keyringGetCmd.PersistentFlags() + secretKeyringGetPersistentFlags.StringVar(&c.secretKeyring.get.service, "service", "", "service") + secretKeyringGetPersistentFlags.StringVar(&c.secretKeyring.get.user, "user", "", "user") + markPersistentFlagsRequired(keyringGetCmd, "service", "user") keyringCmd.AddCommand(keyringGetCmd) keyringSetCmd := &cobra.Command{ @@ -37,13 +46,18 @@ func (c *Config) newSecretKeyringCmd() *cobra.Command { Short: "Set a value in keyring", RunE: c.runKeyringSetCmdE, } + secretKeyringSetPersistentFlags := keyringSetCmd.PersistentFlags() + secretKeyringSetPersistentFlags.StringVar(&c.secretKeyring.set.service, "service", "", "service") + secretKeyringSetPersistentFlags.StringVar(&c.secretKeyring.set.user, "user", "", "user") + secretKeyringSetPersistentFlags.StringVar(&c.secretKeyring.set.value, "value", "", "value") + markPersistentFlagsRequired(keyringSetCmd, "service", "user") keyringCmd.AddCommand(keyringSetCmd) return keyringCmd } func (c *Config) runKeyringGetCmdE(cmd *cobra.Command, args []string) error { - value, err := keyring.Get(c.secretKeyring.service, c.secretKeyring.user) + value, err := keyring.Get(c.secretKeyring.get.service, c.secretKeyring.get.user) if err != nil { return err } @@ -51,7 +65,7 @@ func (c *Config) runKeyringGetCmdE(cmd *cobra.Command, args []string) error { } func (c *Config) runKeyringSetCmdE(cmd *cobra.Command, args []string) error { - value := c.secretKeyring.value + value := c.secretKeyring.set.value if value == "" { var err error value, err = c.readPassword("Value: ") @@ -59,5 +73,5 @@ func (c *Config) runKeyringSetCmdE(cmd *cobra.Command, args []string) error { return err } } - return keyring.Set(c.secretKeyring.service, c.secretKeyring.user, value) + return keyring.Set(c.secretKeyring.set.service, c.secretKeyring.set.user, value) }
fix
Add missing --value flag to secret keyring set command
2c895411dfcda5ce96098fa9d255fd8906e1db7a
2022-06-17 16:49:21
Ryan Kavanagh
feat: Support determining FQDN via /etc/myname
false
diff --git a/pkg/chezmoi/chezmoi_unix.go b/pkg/chezmoi/chezmoi_unix.go index 663e5126c97..b2254aefc34 100644 --- a/pkg/chezmoi/chezmoi_unix.go +++ b/pkg/chezmoi/chezmoi_unix.go @@ -8,6 +8,7 @@ import ( "bytes" "io/fs" "regexp" + "runtime" "strings" vfs "github.com/twpayne/go-vfs/v4" @@ -26,6 +27,11 @@ func FQDNHostname(fileSystem vfs.FS) string { if fqdnHostname, err := etcHostsFQDNHostname(fileSystem); err == nil && fqdnHostname != "" { return fqdnHostname } + if runtime.GOOS == "openbsd" { + if fqdnHostname, err := etcMynameFQDNHostname(fileSystem); err == nil && fqdnHostname != "" { + return fqdnHostname + } + } if fqdnHostname, err := etcHostnameFQDNHostname(fileSystem); err == nil && fqdnHostname != "" { return fqdnHostname } @@ -49,6 +55,24 @@ func etcHostnameFQDNHostname(fileSystem vfs.FS) (string, error) { return "", s.Err() } +// etcMynameFQDNHostname returns the FQDN hostname from parsing /etc/myname. +// See OpenBSD's myname(5) for details on this file. +func etcMynameFQDNHostname(fileSystem vfs.FS) (string, error) { + contents, err := fileSystem.ReadFile("/etc/myname") + if err != nil { + return "", err + } + s := bufio.NewScanner(bytes.NewReader(contents)) + for s.Scan() { + text := s.Text() + text, _, _ = CutString(text, "#") + if hostname := strings.TrimSpace(text); hostname != "" { + return hostname, nil + } + } + return "", s.Err() +} + // etcHostsFQDNHostname returns the FQDN hostname from parsing /etc/hosts. func etcHostsFQDNHostname(fileSystem vfs.FS) (string, error) { contents, err := fileSystem.ReadFile("/etc/hosts")
feat
Support determining FQDN via /etc/myname
64f40d93ea1f1456a6788798b9e9c4813156d86e
2024-08-08 01:41:15
Tom Payne
chore: Limit commit hash length to seven characters in website
false
diff --git a/assets/chezmoi.io/docs/reference/release-history.md.tmpl b/assets/chezmoi.io/docs/reference/release-history.md.tmpl index 235e6cd487d..e3fd0639f5d 100644 --- a/assets/chezmoi.io/docs/reference/release-history.md.tmpl +++ b/assets/chezmoi.io/docs/reference/release-history.md.tmpl @@ -20,7 +20,7 @@ | replaceAllRegex "\\(#(\\d+)[)]" "(https://github.com/twpayne/chezmoi/pull/$1)" | replaceAllRegex "(https://github\\.com/twpayne/chezmoi/pull/(\\d+))" "[#$2]($1)" | replaceAllRegex "(?m)^([0-9a-f]{7,})" "* $1" - | replaceAllRegex "(?m)^\\* ([0-9a-f]{7,})" "* [`$1`](https://github.com/twpayne/chezmoi/commit/$1)" + | replaceAllRegex "(?m)^\\* (([0-9a-f]{7})[0-9a-f]*)" "* [`$2`](https://github.com/twpayne/chezmoi/commit/$1)" | replaceAllRegex "\\r\\n" "\\n" | trim | default "Internal changes only"
chore
Limit commit hash length to seven characters in website
48f873beffa5e9d687afae66a56039a5fe7dcec7
2024-08-06 04:19:51
Camille Moncelier
feat: Add gitHubRelease and gitHubReleaseAssetURL template functions
false
diff --git a/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubRelease.md b/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubRelease.md new file mode 100644 index 00000000000..b522999c412 --- /dev/null +++ b/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubRelease.md @@ -0,0 +1,17 @@ +# `gitHubRelease` *owner-repo* *version* + +`gitHubRelease` calls the GitHub API to retrieve the latest releases about +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). + +Calls to `gitHubRelease` are cached so calling `gitHubRelease` with +the same *owner-repo* *version* will only result in one call to the GitHub API. + +!!! example + + ``` + {{ (gitHubRelease "docker/compose" "v2.29.1").TagName }} + ``` diff --git a/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubReleaseAssetURL.md b/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubReleaseAssetURL.md new file mode 100644 index 00000000000..ed91b917a72 --- /dev/null +++ b/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubReleaseAssetURL.md @@ -0,0 +1,21 @@ +# `gitHubReleaseAssetURL` *owner-repo* *version* *pattern* + +`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). +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 +`path.Match`](https://pkg.go.dev/path#Match). + +Calls to `gitHubReleaseAssetURL` are cached so calling +`gitHubReleaseAssetURL` with the same *owner-repo* will only result in one +call to the GitHub API. + +!!! example + + ``` + {{ gitHubReleaseAssetURL "FiloSottile/age" "age v1.2.0" (printf "age-*-%s-%s.tar.gz" .chezmoi.os .chezmoi.arch) }} + {{ gitHubReleaseAssetURL "twpayne/chezmoi" "v2.50.0" (printf "chezmoi-%s-%s" .chezmoi.os .chezmoi.arch) }} + ``` diff --git a/assets/chezmoi.io/mkdocs.yml b/assets/chezmoi.io/mkdocs.yml index 31a9df256d9..e0ec98ebca4 100644 --- a/assets/chezmoi.io/mkdocs.yml +++ b/assets/chezmoi.io/mkdocs.yml @@ -225,7 +225,9 @@ nav: - reference/templates/github-functions/index.md - gitHubKeys: reference/templates/github-functions/gitHubKeys.md - gitHubLatestRelease: reference/templates/github-functions/gitHubLatestRelease.md + - gitHubRelease: reference/templates/github-functions/gitHubRelease.md - gitHubLatestReleaseAssetURL: reference/templates/github-functions/gitHubLatestReleaseAssetURL.md + - gitHubReleaseAssetURL: reference/templates/github-functions/gitHubReleaseAssetURL.md - gitHubLatestTag: reference/templates/github-functions/gitHubLatestTag.md - gitHubReleases: reference/templates/github-functions/gitHubReleases.md - gitHubTags: reference/templates/github-functions/gitHubTags.md diff --git a/internal/cmd/config.go b/internal/cmd/config.go index b1a512a9493..5d9fcf63f02 100644 --- a/internal/cmd/config.go +++ b/internal/cmd/config.go @@ -436,7 +436,9 @@ func newConfig(options ...configOption) (*Config, error) { "fromYaml": c.fromYamlTemplateFunc, "gitHubKeys": c.gitHubKeysTemplateFunc, "gitHubLatestRelease": c.gitHubLatestReleaseTemplateFunc, + "gitHubRelease": c.gitHubReleaseTemplateFunc, "gitHubLatestReleaseAssetURL": c.gitHubLatestReleaseAssetURLTemplateFunc, + "gitHubReleaseAssetURL": c.gitHubReleaseAssetURLTemplateFunc, "gitHubLatestTag": c.gitHubLatestTagTemplateFunc, "gitHubReleases": c.gitHubReleasesTemplateFunc, "gitHubTags": c.gitHubTagsTemplateFunc, diff --git a/internal/cmd/githubtemplatefuncs.go b/internal/cmd/githubtemplatefuncs.go index 6f918987282..0b022d349fe 100644 --- a/internal/cmd/githubtemplatefuncs.go +++ b/internal/cmd/githubtemplatefuncs.go @@ -37,19 +37,21 @@ type gitHubTagsState struct { } var ( - gitHubKeysStateBucket = []byte("gitHubLatestKeysState") - gitHubLatestReleaseStateBucket = []byte("gitHubLatestReleaseState") - gitHubReleasesStateBucket = []byte("gitHubReleasesState") - gitHubTagsStateBucket = []byte("gitHubTagsState") + gitHubKeysStateBucket = []byte("gitHubLatestKeysState") + gitHubVersionReleaseStateBucket = []byte("gitHubVersionReleaseState") + gitHubLatestReleaseStateBucket = []byte("gitHubLatestReleaseState") + gitHubReleasesStateBucket = []byte("gitHubReleasesState") + gitHubTagsStateBucket = []byte("gitHubTagsState") ) type gitHubData struct { - client *github.Client - clientErr error - keysCache map[string][]*github.Key - latestReleaseCache map[string]map[string]*github.RepositoryRelease - releasesCache map[string]map[string][]*github.RepositoryRelease - tagsCache map[string]map[string][]*github.RepositoryTag + client *github.Client + clientErr error + keysCache map[string][]*github.Key + versionReleaseCache map[string]map[string]map[string]*github.RepositoryRelease + latestReleaseCache map[string]map[string]*github.RepositoryRelease + releasesCache map[string]map[string][]*github.RepositoryRelease + tagsCache map[string]map[string][]*github.RepositoryTag } func (c *Config) gitHubKeysTemplateFunc(user string) []*github.Key { @@ -108,11 +110,7 @@ func (c *Config) gitHubKeysTemplateFunc(user string) []*github.Key { return allKeys } -func (c *Config) gitHubLatestReleaseAssetURLTemplateFunc(ownerRepo, pattern string) string { - release, err := c.gitHubLatestRelease(ownerRepo) - if err != nil { - panic(err) - } +func (c *Config) githubMatchingReleaseAssetURL(release *github.RepositoryRelease, pattern string) string { for _, asset := range release.Assets { if asset.Name == nil { continue @@ -127,6 +125,79 @@ func (c *Config) gitHubLatestReleaseAssetURLTemplateFunc(ownerRepo, pattern stri return "" } +func (c *Config) gitHubLatestReleaseAssetURLTemplateFunc(ownerRepo, pattern string) string { + release, err := c.gitHubLatestRelease(ownerRepo) + if err != nil { + panic(err) + } + return c.githubMatchingReleaseAssetURL(release, pattern) +} + +func (c *Config) gitHubReleaseAssetURLTemplateFunc(ownerRepo, version, pattern string) string { + release, err := c.gitHubRelease(ownerRepo, version) + if err != nil { + panic(err) + } + return c.githubMatchingReleaseAssetURL(release, pattern) +} + +func (c *Config) gitHubRelease(ownerRepo, version string) (*github.RepositoryRelease, error) { + owner, repo, err := gitHubSplitOwnerRepo(ownerRepo) + if err != nil { + return nil, err + } + + if c.gitHub.versionReleaseCache == nil { + c.gitHub.versionReleaseCache = make(map[string]map[string]map[string]*github.RepositoryRelease) + } + if c.gitHub.versionReleaseCache[owner] == nil { + c.gitHub.versionReleaseCache[owner] = make(map[string]map[string]*github.RepositoryRelease) + } + if c.gitHub.versionReleaseCache[owner][repo] == nil { + c.gitHub.versionReleaseCache[owner][repo] = make(map[string]*github.RepositoryRelease) + } + + if release := c.gitHub.versionReleaseCache[owner][repo][version]; release != nil { + return release, nil + } + + now := time.Now() + gitHubVersionReleaseKey := []byte(owner + "/" + repo + "/" + version) + if c.GitHub.RefreshPeriod != 0 { + var gitHubVersionReleaseStateValue gitHubLatestReleaseState + switch ok, err := chezmoi.PersistentStateGet(c.persistentState, gitHubVersionReleaseStateBucket, gitHubVersionReleaseKey, &gitHubVersionReleaseStateValue); { + case err != nil: + return nil, err + case ok && now.Before(gitHubVersionReleaseStateValue.RequestedAt.Add(c.GitHub.RefreshPeriod)): + return gitHubVersionReleaseStateValue.Release, nil + } + } + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + gitHubClient, err := c.getGitHubClient(ctx) + if err != nil { + return nil, err + } + + release, _, err := gitHubClient.Repositories.GetReleaseByTag(ctx, owner, repo, version) + if err != nil { + return nil, err + } + + if err := chezmoi.PersistentStateSet(c.persistentState, gitHubVersionReleaseStateBucket, gitHubVersionReleaseKey, &gitHubLatestReleaseState{ + RequestedAt: now, + Release: release, + }); err != nil { + return nil, err + } + + c.gitHub.versionReleaseCache[owner][repo][version] = release + + return release, nil +} + func (c *Config) gitHubLatestRelease(ownerRepo string) (*github.RepositoryRelease, error) { owner, repo, err := gitHubSplitOwnerRepo(ownerRepo) if err != nil { @@ -188,6 +259,14 @@ func (c *Config) gitHubLatestReleaseTemplateFunc(ownerRepo string) *github.Repos return release } +func (c *Config) gitHubReleaseTemplateFunc(ownerRepo, version string) *github.RepositoryRelease { + release, err := c.gitHubRelease(ownerRepo, version) + if err != nil { + panic(err) + } + return release +} + func (c *Config) gitHubLatestTagTemplateFunc(ownerRepo string) *github.RepositoryTag { tags, err := c.getGitHubTags(ownerRepo) if err != nil { diff --git a/internal/cmd/statecmd.go b/internal/cmd/statecmd.go index 6f2034d0cec..102a7981e65 100644 --- a/internal/cmd/statecmd.go +++ b/internal/cmd/statecmd.go @@ -171,14 +171,15 @@ func (c *Config) runStateDeleteBucketCmd(cmd *cobra.Command, args []string) erro func (c *Config) runStateDumpCmd(cmd *cobra.Command, args []string) error { data, err := chezmoi.PersistentStateData(c.persistentState, map[string][]byte{ - "configState": chezmoi.ConfigStateBucket, - "entryState": chezmoi.EntryStateBucket, - "gitHubKeysState": gitHubKeysStateBucket, - "gitHubLatestReleaseState": gitHubLatestReleaseStateBucket, - "gitHubReleasesState": gitHubReleasesStateBucket, - "gitHubTagsState": gitHubTagsStateBucket, - "gitRepoExternalState": chezmoi.GitRepoExternalStateBucket, - "scriptState": chezmoi.ScriptStateBucket, + "configState": chezmoi.ConfigStateBucket, + "entryState": chezmoi.EntryStateBucket, + "gitHubKeysState": gitHubKeysStateBucket, + "gitHubLatestReleaseState": gitHubLatestReleaseStateBucket, + "gitHubVersionReleaseState": gitHubVersionReleaseStateBucket, + "gitHubReleasesState": gitHubReleasesStateBucket, + "gitHubTagsState": gitHubTagsStateBucket, + "gitRepoExternalState": chezmoi.GitRepoExternalStateBucket, + "scriptState": chezmoi.ScriptStateBucket, }) if err != nil { return err diff --git a/internal/cmd/testdata/scripts/configstate.txtar b/internal/cmd/testdata/scripts/configstate.txtar index 1cc08c5e65b..77b43adf708 100644 --- a/internal/cmd/testdata/scripts/configstate.txtar +++ b/internal/cmd/testdata/scripts/configstate.txtar @@ -71,6 +71,7 @@ gitHubKeysState: {} gitHubLatestReleaseState: {} gitHubReleasesState: {} gitHubTagsState: {} +gitHubVersionReleaseState: {} gitRepoExternalState: {} scriptState: {} -- home/user/.local/share/chezmoi/.chezmoi.toml.tmpl -- diff --git a/internal/cmd/testdata/scripts/githubtemplatefuncs.txtar b/internal/cmd/testdata/scripts/githubtemplatefuncs.txtar index 933a15f7343..79a3c93da00 100644 --- a/internal/cmd/testdata/scripts/githubtemplatefuncs.txtar +++ b/internal/cmd/testdata/scripts/githubtemplatefuncs.txtar @@ -8,6 +8,14 @@ stdout ^ssh-rsa exec chezmoi execute-template '{{ (gitHubLatestRelease "twpayne/chezmoi").TagName }}' stdout ^v2\. +# test gitHubLatestRelease template function +exec chezmoi execute-template '{{ (gitHubLatestRelease "2.51.0" "twpayne/chezmoi").TagName }}' +stdout ^v2.51.0 + +# test gitHubLatestRelease template function +exec chezmoi execute-template '{{ (gitHubLatestRelease "2.49.0" "twpayne/chezmoi").TagName }}' +stdout ^v2.49.0 + # test gitHubLatestTag template function exec chezmoi execute-template '{{ (gitHubLatestTag "twpayne/chezmoi").Name }}' stdout ^v2\. diff --git a/internal/cmd/testdata/scripts/state_unix.txtar b/internal/cmd/testdata/scripts/state_unix.txtar index b7130f4500a..93d1ab7484b 100644 --- a/internal/cmd/testdata/scripts/state_unix.txtar +++ b/internal/cmd/testdata/scripts/state_unix.txtar @@ -44,6 +44,7 @@ gitHubKeysState: {} gitHubLatestReleaseState: {} gitHubReleasesState: {} gitHubTagsState: {} +gitHubVersionReleaseState: {} gitRepoExternalState: {} scriptState: {} -- home/user/.local/share/chezmoi/run_once_script.sh -- diff --git a/internal/cmd/testdata/scripts/state_windows.txtar b/internal/cmd/testdata/scripts/state_windows.txtar index 0f936cee10c..b3e64cc8a04 100644 --- a/internal/cmd/testdata/scripts/state_windows.txtar +++ b/internal/cmd/testdata/scripts/state_windows.txtar @@ -25,6 +25,7 @@ gitHubKeysState: {} gitHubLatestReleaseState: {} gitHubReleasesState: {} gitHubTagsState: {} +gitHubVersionReleaseState: {} gitRepoExternalState: {} scriptState: {} -- home/user/.local/share/chezmoi/run_once_script.cmd --
feat
Add gitHubRelease and gitHubReleaseAssetURL template functions
3077a1a0d575e58b85096e1d800061b0876d42c0
2021-11-23 07:25:35
Tom Payne
chore: Fix HTTP cache path in tests
false
diff --git a/internal/cmd/config.go b/internal/cmd/config.go index e1cd8797657..48f165cc307 100644 --- a/internal/cmd/config.go +++ b/internal/cmd/config.go @@ -30,6 +30,8 @@ import ( gogit "github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5/plumbing/format/diff" "github.com/google/gops/agent" + "github.com/gregjones/httpcache" + "github.com/gregjones/httpcache/diskcache" "github.com/mitchellh/mapstructure" "github.com/rs/zerolog" "github.com/rs/zerolog/log" @@ -395,7 +397,6 @@ func newConfig(options ...configOption) (*Config, error) { // Configuration. fileSystem: vfs.OSFS, bds: bds, - httpClient: newCacheHTTPClient(cacheDirAbsPath.Join(httpCacheDirRelPath)), // Computed configuration. homeDirAbsPath: homeDirAbsPath, @@ -1129,6 +1130,22 @@ func (c *Config) findFirstConfigTemplate() (chezmoi.RelPath, string, []byte, err return chezmoi.EmptyRelPath, "", nil, nil } +func (c *Config) getHTTPClient() (*http.Client, error) { + if c.httpClient != nil { + return c.httpClient, nil + } + + httpCacheBasePath, err := c.baseSystem.RawPath(c.CacheDirAbsPath.Join(httpCacheDirRelPath)) + if err != nil { + return nil, err + } + httpCache := diskcache.New(httpCacheBasePath.String()) + httpTransport := httpcache.NewTransport(httpCache) + c.httpClient = httpTransport.Client() + + return c.httpClient, nil +} + // gitAutoAdd adds all changes to the git index and returns the new git status. func (c *Config) gitAutoAdd() (*git.Status, error) { if err := c.run(c.WorkingTreeAbsPath, c.Git.Command, []string{"add", "."}); err != nil { @@ -1324,6 +1341,11 @@ func (c *Config) newRootCmd() (*cobra.Command, error) { func (c *Config) newSourceState( ctx context.Context, options ...chezmoi.SourceStateOption, ) (*chezmoi.SourceState, error) { + httpClient, err := c.getHTTPClient() + if err != nil { + return nil, err + } + sourceStateLogger := c.logger.With().Str(logComponentKey, logComponentValueSourceState).Logger() sourceDirAbsPath := c.SourceDirAbsPath @@ -1341,7 +1363,7 @@ func (c *Config) newSourceState( chezmoi.WithDefaultTemplateDataFunc(c.defaultTemplateData), chezmoi.WithDestDir(c.DestDirAbsPath), chezmoi.WithEncryption(c.encryption), - chezmoi.WithHTTPClient(c.httpClient), + chezmoi.WithHTTPClient(httpClient), chezmoi.WithInterpreters(c.Interpreters), chezmoi.WithLogger(&sourceStateLogger), chezmoi.WithMode(c.Mode), diff --git a/internal/cmd/githubtemplatefuncs.go b/internal/cmd/githubtemplatefuncs.go index d8f791c6a31..36c31541404 100644 --- a/internal/cmd/githubtemplatefuncs.go +++ b/internal/cmd/githubtemplatefuncs.go @@ -21,7 +21,12 @@ func (c *Config) gitHubKeysTemplateFunc(user string) []*github.Key { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - gitHubClient := newGitHubClient(ctx, c.httpClient) + httpClient, err := c.getHTTPClient() + if err != nil { + returnTemplateError(err) + return nil + } + gitHubClient := newGitHubClient(ctx, httpClient) var allKeys []*github.Key opts := &github.ListOptions{ @@ -57,7 +62,12 @@ func (c *Config) gitHubLatestReleaseTemplateFunc(userRepo string) *github.Reposi ctx, cancel := context.WithCancel(context.Background()) defer cancel() - gitHubClient := newGitHubClient(ctx, c.httpClient) + httpClient, err := c.getHTTPClient() + if err != nil { + returnTemplateError(err) + return nil + } + gitHubClient := newGitHubClient(ctx, httpClient) release, _, err := gitHubClient.Repositories.GetLatestRelease(ctx, user, repo) if err != nil { diff --git a/internal/cmd/upgradecmd.go b/internal/cmd/upgradecmd.go index 31f58a6480e..ffb67740268 100644 --- a/internal/cmd/upgradecmd.go +++ b/internal/cmd/upgradecmd.go @@ -116,7 +116,11 @@ func (c *Config) runUpgradeCmd(cmd *cobra.Command, args []string) error { return errors.New("cannot upgrade dev version to latest released version unless --force is set") } - client := newGitHubClient(ctx, c.httpClient) + httpClient, err := c.getHTTPClient() + if err != nil { + return err + } + client := newGitHubClient(ctx, httpClient) // Get the latest release. rr, _, err := client.Repositories.GetLatestRelease(ctx, c.upgrade.owner, c.upgrade.repo) @@ -240,7 +244,11 @@ func (c *Config) downloadURL(ctx context.Context, url string) ([]byte, error) { if err != nil { return nil, err } - resp, err := c.httpClient.Do(req) + httpClient, err := c.getHTTPClient() + if err != nil { + return nil, err + } + resp, err := httpClient.Do(req) if resp != nil { c.logger.Err(err). Str("method", req.Method). diff --git a/internal/cmd/util.go b/internal/cmd/util.go index 5ab54b699d2..3a74b8e1dc2 100644 --- a/internal/cmd/util.go +++ b/internal/cmd/util.go @@ -11,11 +11,7 @@ import ( "unicode" "github.com/google/go-github/v40/github" - "github.com/gregjones/httpcache" - "github.com/gregjones/httpcache/diskcache" "golang.org/x/oauth2" - - "github.com/twpayne/chezmoi/v2/internal/chezmoi" ) var ( @@ -76,12 +72,6 @@ func firstNonEmptyString(ss ...string) string { return "" } -// newCacheHTTPClient returns a new http.Client that will cache responses -// according to the HTTP RFC. -func newCacheHTTPClient(cacheDirAbsPath chezmoi.AbsPath) *http.Client { - return httpcache.NewTransport(diskcache.New(cacheDirAbsPath.String())).Client() -} - // newGitHubClient returns a new github.Client configured with an access token // and a http client, if available. func newGitHubClient(ctx context.Context, httpClient *http.Client) *github.Client {
chore
Fix HTTP cache path in tests
e1e9a1d0aad2b0db453e684e6a20794eaa1d8971
2021-11-01 02:23:49
Tom Payne
docs: Fix link to list of template functions
false
diff --git a/docs/TEMPLATING.md b/docs/TEMPLATING.md index 8127651e894..e24748a7260 100644 --- a/docs/TEMPLATING.md +++ b/docs/TEMPLATING.md @@ -322,7 +322,8 @@ the `text/template` format that contains many helper functions. Take a look at their documentation for a list. chezmoi adds a few functions of its own as well. Take a look at the -[`reference`](REFERENCE.md#template-functions) for complete list. +[reference](https://github.com/twpayne/chezmoi/blob/master/docs/REFERENCE.md#template-functions) +for complete list. ---
docs
Fix link to list of template functions
a94d8762b394beb4fb87e7f12bb3f57660f2be16
2023-04-07 20:12:05
James Morris
fix: Change where fish completions are installed
false
diff --git a/.goreleaser.yaml b/.goreleaser.yaml index 9e446a3529e..91a65dafb40 100644 --- a/.goreleaser.yaml +++ b/.goreleaser.yaml @@ -159,7 +159,7 @@ nfpms: - src: completions/chezmoi-completion.bash dst: /usr/share/bash-completion/completions/chezmoi - src: completions/chezmoi.fish - dst: /usr/share/fish/completions/chezmoi.fish + dst: /usr/share/fish/vendor_completions.d/chezmoi.fish - src: completions/chezmoi.zsh dst: /usr/share/zsh/vendor-completions/_chezmoi rpm: @@ -175,7 +175,7 @@ nfpms: - src: completions/chezmoi-completion.bash dst: /usr/share/bash-completion/completions/chezmoi - src: completions/chezmoi.fish - dst: /usr/share/fish/completions/chezmoi.fish + dst: /usr/share/fish/vendor_completions.d/chezmoi.fish - src: completions/chezmoi.zsh dst: /usr/share/zsh/site-functions/_chezmoi - id: apks
fix
Change where fish completions are installed
012b02d8ab34192d73e7da149fa3faa90775bc39
2022-12-01 13:33:08
dependabot[bot]
chore(deps): bump golangci/golangci-lint-action from 3.3.0 to 3.3.1
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 1c4c6eae9cb..07a5cdd3c57 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -380,7 +380,7 @@ jobs: with: cache: true go-version: ${{ env.GO_VERSION }} - - uses: golangci/golangci-lint-action@07db5389c99593f11ad7b44463c2d4233066a9b1 + - uses: golangci/golangci-lint-action@0ad9a0988b3973e851ab0a07adf248ec2e100376 with: version: v${{ env.GOLANGCI_LINT_VERSION }} args: --timeout=5m
chore
bump golangci/golangci-lint-action from 3.3.0 to 3.3.1
5c003ae81bedf169a59a50a1b92f6bac1b8ebd3a
2025-02-22 07:40:39
Austin Ziegler
feat: Add promptMultiChoice{,Once}
false
diff --git a/assets/chezmoi.io/docs/reference/commands/execute-template.md b/assets/chezmoi.io/docs/reference/commands/execute-template.md index 37a178a6a0f..d6caa4c44e2 100644 --- a/assets/chezmoi.io/docs/reference/commands/execute-template.md +++ b/assets/chezmoi.io/docs/reference/commands/execute-template.md @@ -27,7 +27,7 @@ it returns false. Simulate the `promptChoice` template function with a function that returns values from *pairs*. *pairs* is a comma-separated list of *prompt*`=`*value* pairs. If `promptChoice` is called with a *prompt* that does not match any of -*pairs*, then it returns false. +*pairs*, then it returns *prompt* unchanged. ### `--promptInt` *pairs* @@ -36,6 +36,13 @@ 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. +### `--promptMultichoice` *pairs* + +Simulate the `promptMultichoice` template function with a function that returns +values from *pairs*. *pairs* is a comma-separated list of *prompt*`=`*value* +pairs. If `promptMultichoice` is called with a *prompt* that does not match any +of *pairs*, then it returns *prompt* as an array. + ### `-p`, `--promptString` *pairs* Simulate the `promptString` template function with a function that returns diff --git a/assets/chezmoi.io/docs/reference/commands/init.md b/assets/chezmoi.io/docs/reference/commands/init.md index f2f4efc930d..f610047ca55 100644 --- a/assets/chezmoi.io/docs/reference/commands/init.md +++ b/assets/chezmoi.io/docs/reference/commands/init.md @@ -20,7 +20,6 @@ order: 5. If the `--purge-binary` is passed, chezmoi will attempt to remove its own binary. - By default, if *repo* is given, chezmoi will guess the full git repo URL, using HTTPS by default, or SSH if the `--ssh` option is specified, according to the following patterns: @@ -113,16 +112,23 @@ default value instead of prompting. ### `--promptInt` *pairs* Populate the `promptInt` template function with values from *pairs*. *pairs* is -a comma-separated list of *prompt*`=`*value* pairs. If `prompInt` is called +a comma-separated list of *prompt*`=`*value* pairs. If `promptInt` is called with a *prompt* that does not match any of *pairs*, then it prompts the user for a value. +### `--promptMultichoice` *pairs* + +Populate the `promptMultichoice` template function with values from *pairs*. +*pairs* is a comma-separated list of *prompt*`=`*value*[`/`*value*] pairs. If +`promptMultichoice` is called with a *prompt* that does not match any of +*pairs*, then it prompts the user for values. + ### `--promptString` *pairs* -Populate the `promptString` template function with 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 prompts the user for -a value. +Populate the `promptString` template function with 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 prompts the +user for a value. ### `-p`, `--purge` diff --git a/assets/chezmoi.io/docs/reference/templates/init-functions/promptChoiceOnce.md b/assets/chezmoi.io/docs/reference/templates/init-functions/promptChoiceOnce.md index fd5aacde936..fa4df94cc93 100644 --- a/assets/chezmoi.io/docs/reference/templates/init-functions/promptChoiceOnce.md +++ b/assets/chezmoi.io/docs/reference/templates/init-functions/promptChoiceOnce.md @@ -2,7 +2,7 @@ `promptChoiceOnce` returns the value of *map* at *path* if it exists and is a string, otherwise it prompts the user for one of *choices* with *prompt* and an -optional *default* using `promptChoice`. +optional *default* using [`promptChoice`][pc]. !!! example @@ -12,3 +12,5 @@ optional *default* using `promptChoice`. [data] hosttype = {{- $hosttype | quote -}} ``` + +[pc]: /reference/templates/init-functions/promptChoice.md diff --git a/assets/chezmoi.io/docs/reference/templates/init-functions/promptMultichoice.md b/assets/chezmoi.io/docs/reference/templates/init-functions/promptMultichoice.md new file mode 100644 index 00000000000..fa4a42a2ca5 --- /dev/null +++ b/assets/chezmoi.io/docs/reference/templates/init-functions/promptMultichoice.md @@ -0,0 +1,16 @@ +# `promptMultichoice` *prompt* *choices* [*default*] + +`promptMultichoice` prompts the user with *prompt* and *choices* and returns the +user's response. *choices* must be a list of strings. If a *default* list is +passed and the user's response is empty then it returns *default*. + +!!! example + + ``` + {{- $choices := list "chocolate" "strawberry" "vanilla" "pistachio" -}} + {{- $icecream := promptMultichoice "What type of ice cream do you like" + $choices (list "pistachio" "chocolate") + -}} + [data] + icecream = {{- $icecream | toToml -}} + ``` diff --git a/assets/chezmoi.io/docs/reference/templates/init-functions/promptMultichoiceOnce.md b/assets/chezmoi.io/docs/reference/templates/init-functions/promptMultichoiceOnce.md new file mode 100644 index 00000000000..21f7b33b568 --- /dev/null +++ b/assets/chezmoi.io/docs/reference/templates/init-functions/promptMultichoiceOnce.md @@ -0,0 +1,21 @@ +# `promptMultichoiceOnce` *map* *path* *prompt* *choices* [*default*] + +`promptMultichoiceOnce` returns the value of *map* at *path* if it exists and is +a string, otherwise it prompts the user for one of *choices* with *prompt* and +an optional list *default* using [`promptMultichoice`][pm]. + +!!! example + + ``` + {{- $choices := list "chocolate" "strawberry" "vanilla" "pistachio" -}} + {{- $icecream := promptMultichoiceOnce + . "icecream" + "What type of ice cream do you like" + $choices + (list "pistachio" "chocolate") + -}} + [data] + icecream = {{- $icecream | toToml -}} + ``` + +[pm]: /reference/templates/init-functions/promptMultichoice.md diff --git a/assets/chezmoi.io/mkdocs.yml b/assets/chezmoi.io/mkdocs.yml index 0a0e01a86b0..5c79480b4ed 100644 --- a/assets/chezmoi.io/mkdocs.yml +++ b/assets/chezmoi.io/mkdocs.yml @@ -254,6 +254,8 @@ nav: - promptChoiceOnce: reference/templates/init-functions/promptChoiceOnce.md - promptInt: reference/templates/init-functions/promptInt.md - promptIntOnce: reference/templates/init-functions/promptIntOnce.md + - promptMultichoice: reference/templates/init-functions/promptMultichoice.md + - promptMultichoiceOnce: reference/templates/init-functions/promptMultichoiceOnce.md - promptString: reference/templates/init-functions/promptString.md - promptStringOnce: reference/templates/init-functions/promptStringOnce.md - stdinIsATTY: reference/templates/init-functions/stdinIsATTY.md diff --git a/internal/chezmoibubbles/multichoiceinputmodel.go b/internal/chezmoibubbles/multichoiceinputmodel.go new file mode 100644 index 00000000000..ab939961b3c --- /dev/null +++ b/internal/chezmoibubbles/multichoiceinputmodel.go @@ -0,0 +1,340 @@ +package chezmoibubbles + +import ( + "slices" + "strings" + + "github.com/charmbracelet/bubbles/help" + "github.com/charmbracelet/bubbles/key" + "github.com/charmbracelet/bubbles/paginator" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" +) + +// This is adapted from github.com/charmbracelet/gum/blob/main/choose/... for +// chezmoi, as of gum 0.15.2. Many things which are configurable in gum are not +// configurable in this module. +// +// Specific configuration options: +// - Provided options (`choices`) are also the labels. +// - No support for automatic select with one entry in the choice list. +// - Any number of options may be selected. +// - Default values are pre-selected. There is no support for wildcard +// selection. +// - Options are shown in the order provided, selections are preserved in the +// order selected. + +type item struct { + text string + selected bool +} + +type keymap struct { + Down, + Up, + Right, + Left, + Home, + End, + ToggleAll, + Toggle, + Abort, + Quit, + Submit key.Binding +} + +type MultichoiceInputModel struct { + items []item + defaultValue *[]string + + header string + quitting bool + submitted bool + index int + numSelected int + + paginator paginator.Model + help help.Model + keymap keymap +} + +const ( + height = 10 + cursor = "> " + selectedPrefix = "✓ " + unselectedPrefix = "• " + cursorPrefix = "• " +) + +var ( + cursorStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("212")) + headerStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("99")) + itemStyle = lipgloss.NewStyle() + selectedItemStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("212")) +) + +func NewMultichoiceInputModel(prompt string, choices []string, defaultValue *[]string) MultichoiceInputModel { + var ( + subduedStyle = lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "#847A85", Dark: "#979797"}) + verySubduedStyle = lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "#DDDADA", Dark: "#3C3C3C"}) + ) + + currentSelected := 0 + hasSelectedItems := defaultValue != nil && len(*defaultValue) > 0 + startingIndex := 0 + + items := make([]item, len(choices)) + for i, option := range choices { + // Check if the option should be selected + isSelected := hasSelectedItems && slices.Contains(*defaultValue, option) + if isSelected { + currentSelected++ + } + items[i] = item{text: option, selected: isSelected} + } + + // Use the pagination model to display the current and total number of + // pages. + pager := paginator.New() + pager.SetTotalPages((len(items) + height - 1) / height) + pager.PerPage = height + pager.Type = paginator.Dots + pager.ActiveDot = subduedStyle.Render("•") + pager.InactiveDot = verySubduedStyle.Render("•") + pager.KeyMap = paginator.KeyMap{} + pager.Page = startingIndex / height + + km := keymap{ + Down: key.NewBinding(key.WithKeys("down", "j", "ctrl+j", "ctrl+n")), + Up: key.NewBinding(key.WithKeys("up", "k", "ctrl+k", "ctrl+p")), + Right: key.NewBinding(key.WithKeys("right", "l", "ctrl+f")), + Left: key.NewBinding(key.WithKeys("left", "h", "ctrl+b")), + Home: key.NewBinding(key.WithKeys("g", "home")), + End: key.NewBinding(key.WithKeys("G", "end")), + ToggleAll: key.NewBinding( + key.WithKeys("a", "A", "ctrl+a"), + key.WithHelp("ctrl+a", "select all"), + ), + Toggle: key.NewBinding( + key.WithKeys(" ", "tab", "x", "ctrl+@"), + key.WithHelp("x", "toggle"), + ), + Abort: key.NewBinding( + key.WithKeys("ctrl+c"), + key.WithHelp("ctrl+c", "abort"), + ), + Quit: key.NewBinding( + key.WithKeys("esc"), + key.WithHelp("esc", "quit"), + ), + Submit: key.NewBinding( + key.WithKeys("enter", "ctrl+q"), + key.WithHelp("enter", "submit"), + ), + } + + m := MultichoiceInputModel{ + items: items, + defaultValue: defaultValue, + + header: prompt, + index: startingIndex, + + paginator: pager, + numSelected: currentSelected, + help: help.New(), + keymap: km, + } + + return m +} + +func (m MultichoiceInputModel) Init() tea.Cmd { + return nil +} + +func (m MultichoiceInputModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + switch msg := msg.(type) { + case tea.WindowSizeMsg: + return m, nil + + case tea.KeyMsg: + start, end := m.paginator.GetSliceBounds(len(m.items)) + km := m.keymap + switch { + case key.Matches(msg, km.Down): + m.index++ + if m.index >= len(m.items) { + m.index = 0 + m.paginator.Page = 0 + } + if m.index >= end { + m.paginator.NextPage() + } + case key.Matches(msg, km.Up): + m.index-- + if m.index < 0 { + m.index = len(m.items) - 1 + m.paginator.Page = m.paginator.TotalPages - 1 + } + if m.index < start { + m.paginator.PrevPage() + } + case key.Matches(msg, km.Right): + m.index = clamp(m.index+height, 0, len(m.items)-1) + m.paginator.NextPage() + case key.Matches(msg, km.Left): + m.index = clamp(m.index-height, 0, len(m.items)-1) + m.paginator.PrevPage() + case key.Matches(msg, km.End): + m.index = len(m.items) - 1 + m.paginator.Page = m.paginator.TotalPages - 1 + case key.Matches(msg, km.Home): + m.index = 0 + m.paginator.Page = 0 + case key.Matches(msg, km.ToggleAll): + if m.numSelected < len(m.items) { + m = m.selectAll() + } else { + m = m.deselectAll() + } + case key.Matches(msg, km.Quit): + if m.numSelected < 1 && m.defaultValue != nil { + for i := range m.items { + if slices.Contains(*m.defaultValue, m.items[i].text) { + m.items[i].selected = true + m.numSelected++ + } + } + } + m.quitting = true + return m, tea.Quit + case key.Matches(msg, km.Abort): + m.quitting = true + return m, tea.Interrupt + case key.Matches(msg, km.Toggle): + if m.items[m.index].selected { + m.items[m.index].selected = false + m.numSelected-- + } else { + m.items[m.index].selected = true + m.numSelected++ + } + case key.Matches(msg, km.Submit): + m.quitting = true + if m.numSelected < 1 { + m.items[m.index].selected = true + } + m.submitted = true + return m, tea.Quit + } + } + + var cmd tea.Cmd + m.paginator, cmd = m.paginator.Update(msg) + return m, cmd +} + +func (m MultichoiceInputModel) selectAll() MultichoiceInputModel { + for i := range m.items { + if m.items[i].selected { + continue + } + m.items[i].selected = true + m.numSelected++ + } + return m +} + +func (m MultichoiceInputModel) deselectAll() MultichoiceInputModel { + for i := range m.items { + m.items[i].selected = false + } + m.numSelected = 0 + return m +} + +func (m MultichoiceInputModel) View() string { + if m.quitting { + return "" + } + + var s strings.Builder + + start, end := m.paginator.GetSliceBounds(len(m.items)) + for i, item := range m.items[start:end] { + if i == m.index%height { + s.WriteString(cursorStyle.Render(cursor)) + } else { + s.WriteString(strings.Repeat(" ", lipgloss.Width(cursor))) + } + + switch { + case item.selected: + s.WriteString(selectedItemStyle.Render(selectedPrefix + item.text)) + case i == m.index%height: + s.WriteString(cursorStyle.Render(cursorPrefix + item.text)) + default: + s.WriteString(itemStyle.Render(unselectedPrefix + item.text)) + } + if i != height { + s.WriteRune('\n') + } + } + + if m.paginator.TotalPages > 1 { + s.WriteString(strings.Repeat("\n", height-m.paginator.ItemsOnPage(len(m.items))+1)) + s.WriteString(" " + m.paginator.View()) + } + + var parts []string + + if m.header != "" { + parts = append(parts, headerStyle.Render(m.header)) + } + parts = append(parts, s.String(), m.help.View(m.keymap)) + + return lipgloss.JoinVertical(lipgloss.Left, parts...) +} + +func (m MultichoiceInputModel) Value() []string { + if (m.numSelected == 0 || !m.submitted) && m.defaultValue != nil { + return *m.defaultValue + } + + var out []string + + for _, item := range m.items { + if item.selected { + out = append(out, item.text) + } + } + + return out +} + +func clamp(x, low, high int) int { + if x < low { + return low + } + if x > high { + return high + } + return x +} + +// FullHelp implements help.KeyMap. +func (k keymap) FullHelp() [][]key.Binding { return nil } + +// ShortHelp implements help.KeyMap. +func (k keymap) ShortHelp() []key.Binding { + return []key.Binding{ + k.Toggle, + key.NewBinding( + key.WithKeys("up", "down", "right", "left"), + key.WithHelp("←↓↑→", "navigate"), + ), + k.Submit, + k.ToggleAll, + } +} diff --git a/internal/cmd/config.go b/internal/cmd/config.go index f453a8080ed..76f26818b17 100644 --- a/internal/cmd/config.go +++ b/internal/cmd/config.go @@ -861,17 +861,19 @@ func (c *Config) createConfigFile(filename chezmoi.RelPath, data []byte, cmd *co }() initTemplateFuncs := map[string]any{ - "exit": c.exitInitTemplateFunc, - "promptBool": c.promptBoolInteractiveTemplateFunc, - "promptBoolOnce": c.promptBoolOnceInteractiveTemplateFunc, - "promptChoice": c.promptChoiceInteractiveTemplateFunc, - "promptChoiceOnce": c.promptChoiceOnceInteractiveTemplateFunc, - "promptInt": c.promptIntInteractiveTemplateFunc, - "promptIntOnce": c.promptIntOnceInteractiveTemplateFunc, - "promptString": c.promptStringInteractiveTemplateFunc, - "promptStringOnce": c.promptStringOnceInteractiveTemplateFunc, - "stdinIsATTY": c.stdinIsATTYInitTemplateFunc, - "writeToStdout": c.writeToStdout, + "exit": c.exitInitTemplateFunc, + "promptBool": c.promptBoolInteractiveTemplateFunc, + "promptBoolOnce": c.promptBoolOnceInteractiveTemplateFunc, + "promptChoice": c.promptChoiceInteractiveTemplateFunc, + "promptChoiceOnce": c.promptChoiceOnceInteractiveTemplateFunc, + "promptInt": c.promptIntInteractiveTemplateFunc, + "promptIntOnce": c.promptIntOnceInteractiveTemplateFunc, + "promptMultichoice": c.promptMultichoiceInteractiveTemplateFunc, + "promptMultichoiceOnce": c.promptMultichoiceOnceInteractiveTemplateFunc, + "promptString": c.promptStringInteractiveTemplateFunc, + "promptStringOnce": c.promptStringOnceInteractiveTemplateFunc, + "stdinIsATTY": c.stdinIsATTYInitTemplateFunc, + "writeToStdout": c.writeToStdout, } chezmoi.RecursiveMerge(c.templateFuncs, initTemplateFuncs) @@ -1617,10 +1619,11 @@ func (c *Config) gitAutoPush(status *chezmoigit.Status) error { func (c *Config) gitCommitMessage(cmd *cobra.Command, status *chezmoigit.Status) ([]byte, error) { templateFuncs := maps.Clone(c.templateFuncs) maps.Copy(templateFuncs, map[string]any{ - "promptBool": c.promptBoolInteractiveTemplateFunc, - "promptChoice": c.promptChoiceInteractiveTemplateFunc, - "promptInt": c.promptIntInteractiveTemplateFunc, - "promptString": c.promptStringInteractiveTemplateFunc, + "promptBool": c.promptBoolInteractiveTemplateFunc, + "promptChoice": c.promptChoiceInteractiveTemplateFunc, + "promptInt": c.promptIntInteractiveTemplateFunc, + "promptMultichoice": c.promptMultichoiceInteractiveTemplateFunc, + "promptString": c.promptStringInteractiveTemplateFunc, "targetRelPath": func(source string) string { return chezmoi.NewSourceRelPath(source).TargetRelPath(c.encryption.EncryptedSuffix()).String() }, diff --git a/internal/cmd/executetemplatecmd.go b/internal/cmd/executetemplatecmd.go index 8d155145437..d6108a8f27e 100644 --- a/internal/cmd/executetemplatecmd.go +++ b/internal/cmd/executetemplatecmd.go @@ -13,14 +13,15 @@ import ( ) type executeTemplateCmdConfig struct { - init bool - promptBool map[string]string - promptChoice map[string]string - promptInt map[string]int - promptString map[string]string - stdinIsATTY bool - templateOptions chezmoi.TemplateOptions - withStdin bool + init bool + promptBool map[string]string + promptChoice map[string]string + promptInt map[string]int + promptMultichoice map[string]string + promptString map[string]string + stdinIsATTY bool + templateOptions chezmoi.TemplateOptions + withStdin bool } func (c *Config) newExecuteTemplateCmd() *cobra.Command { @@ -42,6 +43,8 @@ func (c *Config) newExecuteTemplateCmd() *cobra.Command { StringToStringVar(&c.executeTemplate.promptChoice, "promptChoice", c.executeTemplate.promptChoice, "Simulate promptChoice") executeTemplateCmd.Flags(). StringToIntVar(&c.executeTemplate.promptInt, "promptInt", c.executeTemplate.promptInt, "Simulate promptInt") + executeTemplateCmd.Flags(). + StringToStringVar(&c.executeTemplate.promptMultichoice, "promptMultichoice", c.executeTemplate.promptMultichoice, "Simulate promptMultichoice") executeTemplateCmd.Flags(). StringToStringVarP(&c.executeTemplate.promptString, "promptString", "p", c.executeTemplate.promptString, "Simulate promptString") executeTemplateCmd.Flags(). @@ -147,6 +150,37 @@ func (c *Config) runExecuteTemplateCmd(cmd *cobra.Command, args []string) error return promptChoiceInitTemplateFunc(prompt, choices, args...) } + promptMultichoiceInitTemplateFunc := func(prompt string, choices any, args ...any) []string { + choiceStrs := mustValue(anyToStringSlice(choices)) + if value, ok := c.executeTemplate.promptMultichoice[prompt]; ok { + values := strings.Split(value, "/") + + for _, v := range values { + if !slices.Contains(choiceStrs, v) { + panic(fmt.Errorf("%s: invalid choice", value)) + } + } + + return values + } + + if len(args) == 0 { + return []string{prompt} + } + + return mustValue(anyToStringSlice(args[0])) + } + + promptMultichoiceOnceInitTemplateFunc := func(m map[string]any, path any, prompt string, choices []any, args ...any) []string { + nestedMap, lastKey := mustValues(nestedMapAtPath(m, path)) + if value, ok := nestedMap[lastKey]; ok { + if stringValue, ok := value.(string); ok { + return strings.Split(stringValue, ",") + } + } + return promptMultichoiceInitTemplateFunc(prompt, choices, args...) + } + promptIntInitTemplateFunc := func(prompt string, args ...int64) int64 { switch len(args) { case 0: @@ -203,17 +237,19 @@ func (c *Config) runExecuteTemplateCmd(cmd *cobra.Command, args []string) error } initTemplateFuncs := map[string]any{ - "exit": c.exitInitTemplateFunc, - "promptBool": promptBoolInitTemplateFunc, - "promptBoolOnce": promptBoolOnceInitTemplateFunc, - "promptChoice": promptChoiceInitTemplateFunc, - "promptChoiceOnce": promptChoiceOnceInitTemplateFunc, - "promptInt": promptIntInitTemplateFunc, - "promptIntOnce": promptIntOnceInitTemplateFunc, - "promptString": promptStringInitTemplateFunc, - "promptStringOnce": promptStringOnceInitTemplateFunc, - "stdinIsATTY": stdinIsATTYInitTemplateFunc, - "writeToStdout": c.writeToStdout, + "exit": c.exitInitTemplateFunc, + "promptBool": promptBoolInitTemplateFunc, + "promptBoolOnce": promptBoolOnceInitTemplateFunc, + "promptChoice": promptChoiceInitTemplateFunc, + "promptChoiceOnce": promptChoiceOnceInitTemplateFunc, + "promptInt": promptIntInitTemplateFunc, + "promptIntOnce": promptIntOnceInitTemplateFunc, + "promptMultichoice": promptMultichoiceInitTemplateFunc, + "promptMultichoiceOnce": promptMultichoiceOnceInitTemplateFunc, + "promptString": promptStringInitTemplateFunc, + "promptStringOnce": promptStringOnceInitTemplateFunc, + "stdinIsATTY": stdinIsATTYInitTemplateFunc, + "writeToStdout": c.writeToStdout, } chezmoi.RecursiveMerge(c.templateFuncs, initTemplateFuncs) diff --git a/internal/cmd/helps.gen.go b/internal/cmd/helps.gen.go index f6c3b1959be..5ae53c54534 100644 --- a/internal/cmd/helps.gen.go +++ b/internal/cmd/helps.gen.go @@ -399,6 +399,7 @@ var helps = map[string]*help{ "promptBool", "promptChoice", "promptInt", + "promptMultichoice", "promptString", "right-delimiter", "stdinisatty", @@ -545,6 +546,7 @@ var helps = map[string]*help{ "promptChoice", "promptDefaults", "promptInt", + "promptMultichoice", "promptString", "purge", "purge-binary", diff --git a/internal/cmd/inittemplatefuncs_test.go b/internal/cmd/inittemplatefuncs_test.go index 3454d185217..e81a8934389 100644 --- a/internal/cmd/inittemplatefuncs_test.go +++ b/internal/cmd/inittemplatefuncs_test.go @@ -243,6 +243,106 @@ func TestPromptIntInteractiveTemplateFunc(t *testing.T) { } } +func TestPromptMultichoiceInteractiveTemplateFunc(t *testing.T) { + for _, tc := range []struct { + name string + prompt string + multichoices []any + args []any + stdinStr string + expectedStdoutStr string + expected []string + expectedErr bool + }{ + { + name: "response_without_default", + prompt: "multichoice", + multichoices: []any{"one", "two", "three"}, + stdinStr: "one\n\n", + expectedStdoutStr: "multichoice?\nChoices (one/two/three)\nChoice (ENTER to stop)> Choice (ENTER to stop)> ", + expected: []string{"one"}, + }, + { + name: "response_with_default", + prompt: "multichoice", + multichoices: []any{"one", "two", "three"}, + args: []any{[]string{"one"}}, + stdinStr: "two\n\n", + expectedStdoutStr: "multichoice?\nChoices (one/two/three)\nDefault [one]\nChoice (ENTER to stop)> Choice (ENTER to stop)> ", + expected: []string{"two"}, + }, + { + name: "no_response_with_default", + prompt: "multichoice", + multichoices: []any{"one", "two", "three"}, + args: []any{[]string{"three", "two"}}, + stdinStr: "\n", + expectedStdoutStr: "multichoice?\nChoices (one/two/three)\nDefault [three, two]\nChoice (ENTER to stop)> ", + expected: []string{"three", "two"}, + }, + { + name: "empty_response_without_default", + prompt: "multichoice", + multichoices: []any{"one", "two", "three"}, + stdinStr: "[]\n", + expectedStdoutStr: "multichoice?\nChoices (one/two/three)\nChoice (ENTER to stop)> ", + expected: []string{}, + }, + { + name: "empty_response_without_default", + prompt: "multichoice", + multichoices: []any{"one", "two", "three"}, + args: []any{[]string{"three", "two"}}, + stdinStr: "[]\n", + expectedStdoutStr: "multichoice?\nChoices (one/two/three)\nDefault [three, two]\nChoice (ENTER to stop)> ", + expected: []string{}, + }, + { + name: "invalid_response", + prompt: "multichoice", + multichoices: []any{"one", "two", "three"}, + stdinStr: "invalid\n", + expectedErr: true, + }, + { + name: "invalid_response_with_default", + prompt: "multichoice", + multichoices: []any{"one", "two", "three"}, + args: []any{[]string{"one"}}, + stdinStr: "invalid\n", + expectedErr: true, + }, + { + name: "invalid_default", + prompt: "multichoice", + multichoices: []any{"one", "two", "three"}, + args: []any{[]string{"four"}}, + stdinStr: "\n", + expectedErr: true, + }, + } { + t.Run(tc.name, func(t *testing.T) { + stdin := strings.NewReader(tc.stdinStr) + stdout := &strings.Builder{} + config, err := newConfig( + withNoTTY(true), + withStdin(stdin), + withStdout(stdout), + ) + assert.NoError(t, err) + if tc.expectedErr { + assert.Panics(t, func() { + config.promptMultichoiceInteractiveTemplateFunc(tc.prompt, tc.multichoices, tc.args...) + }) + } else { + assert.Equal(t, tc.expected, config.promptMultichoiceInteractiveTemplateFunc(tc.prompt, tc.multichoices, tc.args...)) + + assert.Equal(t, tc.expectedStdoutStr, stdout.String()) + } + }) + } +} + func TestPromptStringInteractiveTemplateFunc(t *testing.T) { for _, tc := range []struct { name string diff --git a/internal/cmd/interactivetemplatefuncs.go b/internal/cmd/interactivetemplatefuncs.go index 9a3a4ac71c3..237bd20e47c 100644 --- a/internal/cmd/interactivetemplatefuncs.go +++ b/internal/cmd/interactivetemplatefuncs.go @@ -2,6 +2,7 @@ package cmd import ( "fmt" + "strings" "github.com/spf13/pflag" @@ -9,12 +10,13 @@ import ( ) type interactiveTemplateFuncsConfig struct { - forcePromptOnce bool - promptBool map[string]string - promptChoice map[string]string - promptDefaults bool - promptInt map[string]int - promptString map[string]string + forcePromptOnce bool + promptBool map[string]string + promptChoice map[string]string + promptDefaults bool + promptInt map[string]int + promptMultichoice map[string]string + promptString map[string]string } func (c *Config) addInteractiveTemplateFuncFlags(flags *pflag.FlagSet) { @@ -42,6 +44,12 @@ func (c *Config) addInteractiveTemplateFuncFlags(flags *pflag.FlagSet) { c.interactiveTemplateFuncs.promptChoice, "Populate promptChoice", ) + flags.StringToStringVar( + &c.interactiveTemplateFuncs.promptMultichoice, + "promptMultichoice", + c.interactiveTemplateFuncs.promptMultichoice, + "Populate promptMultichoice", + ) flags.StringToIntVar( &c.interactiveTemplateFuncs.promptInt, "promptInt", @@ -126,6 +134,48 @@ func (c *Config) promptChoiceOnceInteractiveTemplateFunc( return c.promptChoiceInteractiveTemplateFunc(prompt, choices, args...) } +func (c *Config) promptMultichoiceInteractiveTemplateFunc(prompt string, choices any, args ...any) []string { + if len(args) > 1 { + panic(fmt.Errorf("want 2 or 3 arguments, got %d", len(args)+2)) + } + + if valueStr, ok := c.interactiveTemplateFuncs.promptMultichoice[prompt]; ok { + return strings.Split(valueStr, "/") + } + + choiceStrs := mustValue(anyToStringSlice(choices)) + + var defaultValue *[]string + + if len(args) == 1 && args[0] != nil { + values := mustValue(anyToStringSlice(args[0])) + defaultValue = &values + } + + return mustValue(c.promptMultichoice(prompt, choiceStrs, defaultValue)) +} + +func (c *Config) promptMultichoiceOnceInteractiveTemplateFunc( + m map[string]any, + path any, + prompt string, + choices any, + args ...any, +) []string { + if len(args) > 1 { + panic(fmt.Errorf("want 4 or 5 arguments, got %d", len(args)+4)) + } + + nestedMap, lastKey := mustValues(nestedMapAtPath(m, path)) + if !c.interactiveTemplateFuncs.forcePromptOnce { + if value, ok := nestedMap[lastKey]; ok { + return mustValue(anyToStringSlice(value)) + } + } + + return c.promptMultichoiceInteractiveTemplateFunc(prompt, choices, args...) +} + func (c *Config) promptIntInteractiveTemplateFunc(prompt string, args ...int64) int64 { if len(args) > 1 { panic(fmt.Errorf("want 1 or 2 arguments, got %d", len(args)+1)) diff --git a/internal/cmd/internaltestcmd.go b/internal/cmd/internaltestcmd.go index cdde2075488..2bcaa324c3d 100644 --- a/internal/cmd/internaltestcmd.go +++ b/internal/cmd/internaltestcmd.go @@ -42,7 +42,6 @@ func (c *Config) newInternalTestCmd() *cobra.Command { ), } internalTestCmd.AddCommand(internalTestPromptChoiceCmd) - internalTestPromptIntCmd := &cobra.Command{ Use: "prompt-int", Args: cobra.MinimumNArgs(1), @@ -55,6 +54,18 @@ func (c *Config) newInternalTestCmd() *cobra.Command { } internalTestCmd.AddCommand(internalTestPromptIntCmd) + internalTestPromptMultichoiceCmd := &cobra.Command{ + Use: "prompt-multichoice", + Args: cobra.MinimumNArgs(2), + Short: "Run promptMultichoice", + RunE: c.runInternalTestPromptMultichoiceCmd, + Annotations: newAnnotations( + doesNotRequireValidConfig, + persistentStateModeNone, + ), + } + internalTestCmd.AddCommand(internalTestPromptMultichoiceCmd) + internalTestPromptStringCmd := &cobra.Command{ Use: "prompt-string", Args: cobra.MinimumNArgs(1), @@ -106,6 +117,28 @@ func (c *Config) runInternalTestPromptChoiceCmd(cmd *cobra.Command, args []strin return c.writeOutputString(value + "\n") } +func (c *Config) runInternalTestPromptMultichoiceCmd(cmd *cobra.Command, args []string) error { + var defaults *[]string + + if len(args) > 2 { + values := strings.Split(args[2], ",") + defaults = &values + } + + value, err := c.promptMultichoice(args[0], strings.Split(args[1], ","), defaults) + if err != nil { + return err + } + + for _, entry := range value { + if err := c.writeOutputString(entry + "\n"); err != nil { + return err + } + } + + return nil +} + func (c *Config) runInternalTestPromptIntCmd(cmd *cobra.Command, args []string) error { int64Args := make([]int64, 0, len(args)-1) for _, arg := range args[1:] { diff --git a/internal/cmd/prompt.go b/internal/cmd/prompt.go index 333252b6c5d..7ea440b5771 100644 --- a/internal/cmd/prompt.go +++ b/internal/cmd/prompt.go @@ -3,6 +3,7 @@ package cmd import ( "bufio" "fmt" + "os" "slices" "strconv" "strings" @@ -123,6 +124,73 @@ func (c *Config) readLineRaw(prompt string) (string, error) { return strings.TrimSpace(line), nil } +// readMultichoice reads multiple choices from a list. +func (c *Config) readMultichoice(prompt string, choices []string, defaultValue *[]string) ([]string, error) { + switch { + case c.noTTY: + shortPrompt := "Choice (ENTER to stop)> " + + fullPrompt := prompt + "?\nChoices (" + strings.Join(choices, "/") + ")" + if defaultValue != nil { + fullPrompt += "\nDefault [" + strings.Join(*defaultValue, ", ") + "]" + } + fullPrompt += "\n" + + _, err := c.stdout.Write([]byte(fullPrompt)) + if err != nil { + return []string{}, err + } + + abbreviations := chezmoi.UniqueAbbreviations(choices) + selected := make(map[string]struct{}) + + for { + value, err := c.readLineRaw(shortPrompt) + if err != nil { + return []string{}, err + } + + if value == "" { + if len(selected) == 0 && defaultValue != nil { + return *defaultValue, nil + } + + if len(selected) > 0 { + break + } + } + + if value == "[]" { + return []string{}, nil + } + + if value, ok := abbreviations[value]; ok { + selected[value] = struct{}{} + } + + if len(selected) == len(choices) { + break + } + } + + result := make([]string, 0) + for name := range selected { + result = append(result, name) + } + + return result, nil + + default: + initModel := chezmoibubbles.NewMultichoiceInputModel(prompt, choices, defaultValue) + finalModel, err := tea.NewProgram(initModel, tea.WithOutput(os.Stderr)).Run() + if err != nil { + return []string{}, err + } + + return finalModel.(chezmoibubbles.MultichoiceInputModel).Value(), nil //nolint:forcetypeassert + } +} + // readPassword reads a password. func (c *Config) readPassword(prompt, placeholder string) (string, error) { switch { @@ -190,6 +258,7 @@ func (c *Config) promptChoice(prompt string, choices []string, args ...string) ( case 0: // Do nothing. case 1: + if !slices.Contains(choices, args[0]) { return "", fmt.Errorf("%s: invalid default value", args[0]) } @@ -219,6 +288,23 @@ func (c *Config) promptInt(prompt string, args ...int64) (int64, error) { return c.readInt(prompt, defaultValue) } +// promptMultiChoice prompts the user to select one or more values in a list. +func (c *Config) promptMultichoice(prompt string, choices []string, defaults *[]string) ([]string, error) { + if defaults != nil { + for i, defaultValue := range *defaults { + if !slices.Contains(choices, defaultValue) { + return []string{}, fmt.Errorf("%s: invalid default value (index %d)", defaultValue, i+1) + } + } + } + + if c.interactiveTemplateFuncs.promptDefaults && defaults != nil { + return *defaults, nil + } + + return c.readMultichoice(prompt, choices, defaults) +} + func (c *Config) promptString(prompt string, args ...string) (string, error) { var defaultValue *string switch len(args) { diff --git a/internal/cmd/testdata/scripts/executetemplate.txtar b/internal/cmd/testdata/scripts/executetemplate.txtar index afdff8b95e0..f2d6d1defa5 100644 --- a/internal/cmd/testdata/scripts/executetemplate.txtar +++ b/internal/cmd/testdata/scripts/executetemplate.txtar @@ -72,6 +72,18 @@ stderr 'invalid choice' exec chezmoi execute-template --init '{{ promptChoice "value" (list "one" "two" "three") "three" }}' stdout three +# test --init --promptMultichoice +exec chezmoi execute-template --init --promptMultichoice value=one/two '{{ promptMultichoice "value" (list "one" "two" "three") }}' +stdout '[one two]' + +# test --init --promptMultichoice with an invalid value +! exec chezmoi execute-template --init --promptMultichoice value=four '{{ promptMultichoice "value" (list "one" "two" "three") }}' +stderr 'invalid choice' + +# test --init --promptMultichoice with a default value +exec chezmoi execute-template --init '{{ promptMultichoice "value" (list "one" "two" "three") (list "two" "three") }}' +stdout '[two three]' + # test --init --promptInt exec chezmoi execute-template --init --promptInt value=1 '{{ promptInt "value" }}' stdout 1 diff --git a/internal/cmd/testdata/scripts/init.txtar b/internal/cmd/testdata/scripts/init.txtar index 8fb9237e6fd..c523a579bc3 100644 --- a/internal/cmd/testdata/scripts/init.txtar +++ b/internal/cmd/testdata/scripts/init.txtar @@ -119,7 +119,7 @@ exec chezmoi init chhome home13/user # test chezmoi init --prompt* -exec chezmoi init --promptBool bool=true,boolOncePrompt=true --promptChoice=choice=one,choiceOncePrompt=two --promptInt int=1,intOncePrompt=2 --promptString bool=string,stringOncePrompt=once +exec chezmoi init --promptBool bool=true,boolOncePrompt=true --promptChoice=choice=one,choiceOncePrompt=two --promptInt int=1,intOncePrompt=2 --promptString string=string,stringOncePrompt=once --promptMultichoice multichoice=one/two,multichoiceOncePrompt=two/three cmp $CHEZMOICONFIGDIR/chezmoi.yaml golden/chezmoi.yaml chhome home14/user @@ -146,6 +146,8 @@ data: choiceOnce: two int: 1 intOnce: 2 + multichoice: ["one","two"] + multichoiceOnce: ["two","three"] string: string stringOnce: once -- home13/user/.local/share/chezmoi/.chezmoi.yaml.tmpl -- @@ -156,7 +158,9 @@ data: choiceOnce: {{ promptChoiceOnce . "choiceOnce" "choiceOncePrompt" (list "one" "two" "three") }} int: {{ promptInt "int" }} intOnce: {{ promptIntOnce . "intOnce" "intOncePrompt" }} - string: {{ promptString "bool" }} + multichoice: {{ promptMultichoice "multichoice" (list "one" "two" "three") | toJson}} + multichoiceOnce: {{ promptMultichoiceOnce . "multichoiceOnce" "multichoiceOncePrompt" (list "one" "two" "three") | toJson }} + string: {{ promptString "string" }} stringOnce: {{ promptStringOnce . "stringOnce" "stringOncePrompt" }} -- home14/user/.local/share/chezmoi/.chezmoi.yml.tmpl -- data: diff --git a/internal/cmd/testdata/scripts/inittemplatefuncs.txtar b/internal/cmd/testdata/scripts/inittemplatefuncs.txtar index c1cb4e84b94..f633cd34176 100644 --- a/internal/cmd/testdata/scripts/inittemplatefuncs.txtar +++ b/internal/cmd/testdata/scripts/inittemplatefuncs.txtar @@ -10,6 +10,10 @@ stdout true exec chezmoi execute-template --init --promptChoice choice=one '{{ promptChoiceOnce . "choice" "choice" (list "one" "two" "three") }}' stdout one +# test promptMultichoiceOnce template function with execute-template --init +exec chezmoi execute-template --init --promptMultichoice multichoice=one/two '{{ promptMultichoiceOnce . "multichoice" "multichoice" (list "one" "two" "three") }}' +stdout '[one two]' + # test promptIntOnce template function with execute-template --init exec chezmoi execute-template --init --promptInt int=1 '{{ promptIntOnce . "int" "int" }}' stdout 1
feat
Add promptMultiChoice{,Once}
491ff52c9e2c34cef42092e3bacf15f967201963
2024-12-20 03:58:29
Tom Payne
chore: Remove stale go.mod entry
false
diff --git a/go.mod b/go.mod index 0ee36a5b05f..fd97c3cf123 100644 --- a/go.mod +++ b/go.mod @@ -165,7 +165,4 @@ 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 - github.com/tailscale/hujson v0.0.0-20241010212012-29efb4a0184b // Requires Go 1.23. -) +exclude github.com/tailscale/hujson v0.0.0-20241010212012-29efb4a0184b // Requires Go 1.23.
chore
Remove stale go.mod entry
cc19a4d82ec9394e7d1885af5962a33e86599f2d
2022-10-18 00:47:59
Austin Ziegler
feat: Add per-template configurable delimiters
false
diff --git a/assets/chezmoi.io/docs/reference/commands/execute-template.md b/assets/chezmoi.io/docs/reference/commands/execute-template.md index abb7ac6a46c..ada18a55553 100644 --- a/assets/chezmoi.io/docs/reference/commands/execute-template.md +++ b/assets/chezmoi.io/docs/reference/commands/execute-template.md @@ -9,6 +9,10 @@ specified, the template is read from stdin. Include simulated functions only available during `chezmoi init`. +## `--left-delimiter` *delimiter* + +Set the left template delimiter. + ## `--promptBool` *pairs* Simulate the `promptBool` template function with a function that returns values @@ -30,6 +34,10 @@ 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. +## `--right-delimiter` *delimiter* + +Set the right template delimiter. + ## `--stdinisatty` *bool* Simulate the `stdinIsATTY` function by returning *bool*. diff --git a/assets/chezmoi.io/docs/reference/templates/delimiters.md b/assets/chezmoi.io/docs/reference/templates/delimiters.md new file mode 100644 index 00000000000..39f391f0921 --- /dev/null +++ b/assets/chezmoi.io/docs/reference/templates/delimiters.md @@ -0,0 +1,28 @@ +# Delimiters + +By default, chezmoi uses the standard `text/template` delimiters `{{` and `}}`. +If a template contains the string + + chezmoi:template:left-delimiter=$LEFT right-delimiter=$RIGHT + +Then the delimiters `$LEFT` and `$RIGHT` are used instead. Either or both of +`left-delimiter=$LEFT` and `right-delimiter=$RIGHT` may be omitted. `$LEFT` and +`$RIGHT` must be quoted if they contain spaces. If either `$LEFT` or `$RIGHT` +is empty then the default delimiter (`{{` and `}}` respectively) is set +instead. + +chezmoi will remove the line containing the `chezmoi:template:` directive to +avoid parse errors from the delimiters. Only the first encountered directive is +considered. + +The delimiters are specific to the file in which they appear and are not +inherited by templates called from the file. + +!!! example + + ```sh + #!/bin/sh + # chezmoi:template:left-delimiter="# [[" right-delimiter=]] + + # [[ "true" ]] + ``` diff --git a/assets/chezmoi.io/mkdocs.yml b/assets/chezmoi.io/mkdocs.yml index 9bc35b30aeb..9edfdbd10d7 100644 --- a/assets/chezmoi.io/mkdocs.yml +++ b/assets/chezmoi.io/mkdocs.yml @@ -168,6 +168,7 @@ nav: - Templates: - reference/templates/index.md - Variables: reference/templates/variables.md + - Delimiters: reference/templates/delimiters.md - Functions: - reference/templates/functions/index.md - comment: reference/templates/functions/comment.md diff --git a/pkg/chezmoi/sourcestate.go b/pkg/chezmoi/sourcestate.go index 89ece3e4704..5a6c78d193a 100644 --- a/pkg/chezmoi/sourcestate.go +++ b/pkg/chezmoi/sourcestate.go @@ -17,6 +17,7 @@ import ( "os/exec" "path" "path/filepath" + "regexp" "runtime" "sort" "strings" @@ -45,6 +46,15 @@ const ( ExternalTypeGitRepo ExternalType = "git-repo" ) +var templateDirectiveRx = regexp.MustCompile( + `(?m)^.*?chezmoi:template:(?:left-delimiter=(".*?"|\S*)\s*)?(?:right-delimiter=(".*?"|\S*))?.*(\r?\n)?`, +) + +type TemplateOptions struct { + LeftDelimiter string + RightDelimiter string +} + // An External is an external source. type External struct { Type ExternalType `json:"type" toml:"type" yaml:"type"` @@ -649,11 +659,21 @@ func (s *SourceState) Encryption() Encryption { return s.encryption } +// ExecuteTemplateDataOptions are options to SourceState.ExecuteTemplateData. +type ExecuteTemplateDataOptions struct { + Name string + Data []byte + TemplateOptions TemplateOptions +} + // ExecuteTemplateData returns the result of executing template data. -func (s *SourceState) ExecuteTemplateData(name string, data []byte) ([]byte, error) { - tmpl, err := template.New(name). +func (s *SourceState) ExecuteTemplateData(options ExecuteTemplateDataOptions) ([]byte, error) { + templateOptions := options.TemplateOptions + data := templateOptions.parseDirective(options.Data) + tmpl, err := template.New(options.Name). Option(s.templateOptions...). Funcs(s.templateFuncs). + Delims(templateOptions.LeftDelimiter, templateOptions.RightDelimiter). Parse(string(data)) if err != nil { return nil, err @@ -669,12 +689,12 @@ func (s *SourceState) ExecuteTemplateData(name string, data []byte) ([]byte, err // Temporarily set .chezmoi.sourceFile to the name of the template. templateData := s.TemplateData() if chezmoiTemplateData, ok := templateData["chezmoi"].(map[string]any); ok { - chezmoiTemplateData["sourceFile"] = name + chezmoiTemplateData["sourceFile"] = options.Name defer delete(chezmoiTemplateData, "sourceFile") } builder := strings.Builder{} - if err = tmpl.ExecuteTemplate(&builder, name, templateData); err != nil { + if err = tmpl.ExecuteTemplate(&builder, options.Name, templateData); err != nil { return nil, err } return []byte(builder.String()), nil @@ -1268,7 +1288,10 @@ func (s *SourceState) executeTemplate(templateAbsPath AbsPath) ([]byte, error) { if err != nil { return nil, err } - return s.ExecuteTemplateData(templateAbsPath.String(), data) + return s.ExecuteTemplateData(ExecuteTemplateDataOptions{ + Name: templateAbsPath.String(), + Data: data, + }) } // getExternalDataRaw returns the raw data for external at externalRelPath, @@ -1406,7 +1429,10 @@ func (s *SourceState) newCreateTargetStateEntryFunc( return nil, err } if fileAttr.Template { - contents, err = s.ExecuteTemplateData(sourceRelPath.String(), contents) + contents, err = s.ExecuteTemplateData(ExecuteTemplateDataOptions{ + Name: sourceRelPath.String(), + Data: contents, + }) if err != nil { return nil, err } @@ -1456,7 +1482,10 @@ func (s *SourceState) newFileTargetStateEntryFunc( return nil, err } if fileAttr.Template { - contents, err = s.ExecuteTemplateData(sourceRelPath.String(), contents) + contents, err = s.ExecuteTemplateData(ExecuteTemplateDataOptions{ + Name: sourceRelPath.String(), + Data: contents, + }) if err != nil { return nil, err } @@ -1496,7 +1525,10 @@ func (s *SourceState) newModifyTargetStateEntryFunc( return } if fileAttr.Template { - modifierContents, err = s.ExecuteTemplateData(sourceRelPath.String(), modifierContents) + modifierContents, err = s.ExecuteTemplateData(ExecuteTemplateDataOptions{ + Name: sourceRelPath.String(), + Data: modifierContents, + }) if err != nil { return } @@ -1565,7 +1597,10 @@ func (s *SourceState) newScriptTargetStateEntryFunc( return nil, err } if fileAttr.Template { - contents, err = s.ExecuteTemplateData(sourceRelPath.String(), contents) + contents, err = s.ExecuteTemplateData(ExecuteTemplateDataOptions{ + Name: sourceRelPath.String(), + Data: contents, + }) if err != nil { return nil, err } @@ -1593,7 +1628,10 @@ func (s *SourceState) newSymlinkTargetStateEntryFunc( return "", err } if fileAttr.Template { - linknameBytes, err = s.ExecuteTemplateData(sourceRelPath.String(), linknameBytes) + linknameBytes, err = s.ExecuteTemplateData(ExecuteTemplateDataOptions{ + Name: sourceRelPath.String(), + Data: linknameBytes, + }) if err != nil { return "", err } @@ -2138,6 +2176,25 @@ func (e *External) OriginString() string { return e.URL + " defined in " + e.sourceAbsPath.String() } +// parseDirective updates o by parsing a template directive in data and returns +// data with the line containing the directive removed. The line is removed so +// that the specified delimiters do not break template parsing. +func (o *TemplateOptions) parseDirective(data []byte) []byte { + match := templateDirectiveRx.FindSubmatchIndex(data) + if match == nil { + return data + } + + if match[2] != -1 { + o.LeftDelimiter = maybeUnquote(string(data[match[2]:match[3]])) + } + if match[4] != -1 { + o.RightDelimiter = maybeUnquote(string(data[match[4]:match[5]])) + } + + return bytes.Join([][]byte{data[:match[0]], data[match[1]:]}, nil) +} + // allEquivalentDirs returns if sourceStateEntries are all equivalent // directories. func allEquivalentDirs(sourceStateEntries []SourceStateEntry) bool { diff --git a/pkg/chezmoi/sourcestate_test.go b/pkg/chezmoi/sourcestate_test.go index 3611dbb5450..f3043c97741 100644 --- a/pkg/chezmoi/sourcestate_test.go +++ b/pkg/chezmoi/sourcestate_test.go @@ -1613,6 +1613,115 @@ func TestSourceStateTargetRelPaths(t *testing.T) { } } +func TestTemplateOptionsParseDirective(t *testing.T) { + for _, tc := range []struct { + name string + dataStr string + expected TemplateOptions + expectedDataStr string + }{ + { + name: "empty", + }, + { + name: "unquoted", + dataStr: "chezmoi:template:left-delimiter=[[ right-delimiter=]]", + expected: TemplateOptions{ + LeftDelimiter: "[[", + RightDelimiter: "]]", + }, + }, + { + name: "quoted", + dataStr: `chezmoi:template:left-delimiter="# {{" right-delimiter="}}"`, + expected: TemplateOptions{ + LeftDelimiter: "# {{", + RightDelimiter: "}}", + }, + }, + { + name: "left_only", + dataStr: "chezmoi:template:left-delimiter=[[", + expected: TemplateOptions{ + LeftDelimiter: "[[", + }, + }, + { + name: "left_quoted_only", + dataStr: `chezmoi:template:left-delimiter="# [["`, + expected: TemplateOptions{ + LeftDelimiter: "# [[", + }, + }, + { + name: "right_quoted_only", + dataStr: `chezmoi:template:right-delimiter="]]"`, + expected: TemplateOptions{ + RightDelimiter: "]]", + }, + }, + { + name: "line_with_leading_data", + dataStr: "# chezmoi:template:left-delimiter=[[ right-delimiter=]]", + expected: TemplateOptions{ + LeftDelimiter: "[[", + RightDelimiter: "]]", + }, + }, + { + name: "line_before", + dataStr: chezmoitest.JoinLines( + "# before", + "# chezmoi:template:left-delimiter=[[ right-delimiter=]]", + ), + expected: TemplateOptions{ + LeftDelimiter: "[[", + RightDelimiter: "]]", + }, + expectedDataStr: chezmoitest.JoinLines( + "# before", + ), + }, + { + name: "line_after", + dataStr: chezmoitest.JoinLines( + "# chezmoi:template:left-delimiter=[[ right-delimiter=]]", + "# after", + ), + expected: TemplateOptions{ + LeftDelimiter: "[[", + RightDelimiter: "]]", + }, + expectedDataStr: chezmoitest.JoinLines( + "# after", + ), + }, + { + name: "line_before_and_after", + dataStr: chezmoitest.JoinLines( + "# before", + "# chezmoi:template:left-delimiter=[[ right-delimiter=]]", + "# after", + ), + expected: TemplateOptions{ + LeftDelimiter: "[[", + RightDelimiter: "]]", + }, + expectedDataStr: chezmoitest.JoinLines( + "# before", + "# after", + ), + }, + } { + t.Run(tc.name, func(t *testing.T) { + var actual TemplateOptions + actualData := actual.parseDirective([]byte(tc.dataStr)) + assert.Equal(t, tc.expected, actual) + assert.Equal(t, tc.expectedDataStr, string(actualData)) + }) + } +} + // applyAll updates targetDirAbsPath in targetSystem to match s. func (s *SourceState) applyAll( targetSystem, destSystem System, persistentState PersistentState, targetDirAbsPath AbsPath, options ApplyOptions, diff --git a/pkg/cmd/catcmd_test.go b/pkg/cmd/catcmd_test.go new file mode 100644 index 00000000000..658cd147534 --- /dev/null +++ b/pkg/cmd/catcmd_test.go @@ -0,0 +1,49 @@ +package cmd + +import ( + "runtime" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/twpayne/go-vfs/v4" + + "github.com/twpayne/chezmoi/v2/pkg/chezmoitest" +) + +func TestCatCmd(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("fails due to Windows paths on GitHub Actions") + } + for _, tc := range []struct { + name string + root any + args []string + expectedStr string + }{ + { + name: "template_delimiters", + root: map[string]any{ + "/home/user/.local/share/chezmoi/dot_template.tmpl": chezmoitest.JoinLines( + `# chezmoi:template:left-delimiter=[[ right-delimiter=]]`, + `[[ "ok" ]]`, + ), + }, + args: []string{ + "/home/user/.template", + }, + expectedStr: chezmoitest.JoinLines( + "ok", + ), + }, + } { + t.Run(tc.name, func(t *testing.T) { + chezmoitest.WithTestFS(t, tc.root, func(fileSystem vfs.FS) { + stdout := strings.Builder{} + c := newTestConfig(t, fileSystem, withStdout(&stdout)) + assert.NoError(t, c.execute(append([]string{"cat"}, tc.args...))) + assert.Equal(t, tc.expectedStr, stdout.String()) + }) + }) + } +} diff --git a/pkg/cmd/executetemplatecmd.go b/pkg/cmd/executetemplatecmd.go index 1f9bef52663..df2557a16e8 100644 --- a/pkg/cmd/executetemplatecmd.go +++ b/pkg/cmd/executetemplatecmd.go @@ -12,11 +12,12 @@ import ( ) type executeTemplateCmdConfig struct { - init bool - promptBool map[string]string - promptInt map[string]int - promptString map[string]string - stdinIsATTY bool + init bool + promptBool map[string]string + promptInt map[string]int + promptString map[string]string + stdinIsATTY bool + templateOptions chezmoi.TemplateOptions } func (c *Config) newExecuteTemplateCmd() *cobra.Command { @@ -34,6 +35,8 @@ func (c *Config) newExecuteTemplateCmd() *cobra.Command { flags.StringToIntVar(&c.executeTemplate.promptInt, "promptInt", c.executeTemplate.promptInt, "Simulate promptInt") flags.StringToStringVarP(&c.executeTemplate.promptString, "promptString", "p", c.executeTemplate.promptString, "Simulate promptString") //nolint:lll flags.BoolVar(&c.executeTemplate.stdinIsATTY, "stdinisatty", c.executeTemplate.stdinIsATTY, "Simulate stdinIsATTY") + flags.StringVar(&c.executeTemplate.templateOptions.LeftDelimiter, "left-delimiter", c.executeTemplate.templateOptions.LeftDelimiter, "Set left template delimiter") //nolint:lll + flags.StringVar(&c.executeTemplate.templateOptions.RightDelimiter, "right-delimiter", c.executeTemplate.templateOptions.RightDelimiter, "Set right template delimiter") //nolint:lll return executeTemplateCmd } @@ -158,7 +161,11 @@ func (c *Config) runExecuteTemplateCmd(cmd *cobra.Command, args []string) error if err != nil { return err } - output, err := sourceState.ExecuteTemplateData("stdin", data) + output, err := sourceState.ExecuteTemplateData(chezmoi.ExecuteTemplateDataOptions{ + Name: "stdin", + Data: data, + TemplateOptions: c.executeTemplate.templateOptions, + }) if err != nil { return err } @@ -167,7 +174,11 @@ func (c *Config) runExecuteTemplateCmd(cmd *cobra.Command, args []string) error output := strings.Builder{} for i, arg := range args { - result, err := sourceState.ExecuteTemplateData("arg"+strconv.Itoa(i+1), []byte(arg)) + result, err := sourceState.ExecuteTemplateData(chezmoi.ExecuteTemplateDataOptions{ + Name: "arg" + strconv.Itoa(i+1), + Data: []byte(arg), + TemplateOptions: c.executeTemplate.templateOptions, + }) if err != nil { return err } diff --git a/pkg/cmd/testdata/scripts/templatedelimiters.txtar b/pkg/cmd/testdata/scripts/templatedelimiters.txtar new file mode 100644 index 00000000000..a869d07db0f --- /dev/null +++ b/pkg/cmd/testdata/scripts/templatedelimiters.txtar @@ -0,0 +1,13 @@ +# test --left-delimiter and --right-delimiter flags to chezmoi execute-template +exec chezmoi execute-template --left-delimiter=[[ --right-delimiter=]] '[[ "ok" ]]' +stdout ^ok$ + +# test that template delimiters can be set in files +exec chezmoi cat $HOME${/}template +cmp stdout golden/template + +-- golden/template -- +ok +-- home/user/.local/share/chezmoi/template.tmpl -- +# chezmoi:template:left-delimiter=[[ right-delimiter=]] +[[ "ok" ]]
feat
Add per-template configurable delimiters
9d401ab547c6372d4b79d35228c39811494861ab
2022-10-26 17:29:58
Tom Payne
chore: Rename release artifact
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 51d9897d94b..8c96c593ff4 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -223,7 +223,7 @@ jobs: if: github.event_name == 'push' || needs.changes.outputs.code == 'true' uses: actions/upload-artifact@3cea5372237819ed00197afe530f5a7ea3e805c8 with: - name: chezmoi-windows-amd64.exe + name: chezmoi-windows-amd64 path: dist/chezmoi-nocgo_windows_amd64_v1/chezmoi.exe test-ubuntu: needs: changes
chore
Rename release artifact
cc6844aa172808ca45be3781756ff5114453cffa
2024-01-09 15:23:25
Tom Payne
chore: Reduce use of fmt.Sprintf
false
diff --git a/internal/chezmoi/archive.go b/internal/chezmoi/archive.go index d94a9646a50..e65d72049e8 100644 --- a/internal/chezmoi/archive.go +++ b/internal/chezmoi/archive.go @@ -42,7 +42,7 @@ func (e UnknownArchiveFormatError) Error() string { if e == UnknownArchiveFormatError(ArchiveFormatUnknown) { return "unknown archive format" } - return fmt.Sprintf("%s: unknown archive format", string(e)) + return string(e) + ": unknown archive format" } // An WalkArchiveFunc is called once for each entry in an archive. diff --git a/internal/cmd/addcmd.go b/internal/cmd/addcmd.go index 4e5086b4e88..7a847944be6 100644 --- a/internal/cmd/addcmd.go +++ b/internal/cmd/addcmd.go @@ -96,7 +96,7 @@ func (c *Config) defaultPreAddFunc(targetRelPath chezmoi.RelPath) error { case choice == "yes": return nil default: - panic(fmt.Sprintf("%s: unexpected choice", choice)) + panic(choice + ": unexpected choice") } } } @@ -147,7 +147,7 @@ func (c *Config) defaultReplaceFunc( case choice == "yes": return nil default: - panic(fmt.Sprintf("%s: unexpected choice", choice)) + panic(choice + ": unexpected choice") } } } diff --git a/internal/cmd/azurekeyvaulttemplatefuncs.go b/internal/cmd/azurekeyvaulttemplatefuncs.go index 8ab0f15e42d..57a80fbd7d2 100644 --- a/internal/cmd/azurekeyvaulttemplatefuncs.go +++ b/internal/cmd/azurekeyvaulttemplatefuncs.go @@ -2,6 +2,7 @@ package cmd import ( "context" + "errors" "fmt" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" @@ -72,7 +73,7 @@ func (c *Config) azureKeyVaultTemplateFunc(args ...string) string { switch len(args) { case 1: if c.AzureKeyVault.DefaultVault == "" { - panic(fmt.Errorf("no value set in azureKeyVault.defaultVault")) + panic(errors.New("no value set in azureKeyVault.defaultVault")) } secretName, vaultName = args[0], c.AzureKeyVault.DefaultVault case 2: diff --git a/internal/cmd/cmd.go b/internal/cmd/cmd.go index 4c2b67c6627..2cc41cac450 100644 --- a/internal/cmd/cmd.go +++ b/internal/cmd/cmd.go @@ -252,7 +252,7 @@ func markPersistentFlagsRequired(cmd *cobra.Command, flags ...string) { func mustLongHelp(command string) string { help, ok := helps[command] if !ok { - panic(fmt.Sprintf("missing long help for command %s", command)) + panic(command + ": missing long help") } return help.longHelp } diff --git a/internal/cmd/config.go b/internal/cmd/config.go index 38d7e24dcf8..1e0757fd454 100644 --- a/internal/cmd/config.go +++ b/internal/cmd/config.go @@ -526,7 +526,7 @@ func (c *Config) Close() error { // same key. func (c *Config) addTemplateFunc(key string, value any) { if _, ok := c.templateFuncs[key]; ok { - panic(fmt.Sprintf("%s: already defined", key)) + panic(key + ": already defined") } c.templateFuncs[key] = value } @@ -981,7 +981,7 @@ func (c *Config) defaultPreApplyFunc( case choice == "quit": return chezmoi.ExitCodeError(0) default: - panic(fmt.Sprintf("%s: unexpected choice", choice)) + panic(choice + ": unexpected choice") } } } @@ -1023,7 +1023,7 @@ func (c *Config) defaultPreApplyFunc( case choice == "quit": return chezmoi.ExitCodeError(0) default: - panic(fmt.Sprintf("%s: unexpected choice", choice)) + panic(choice + ": unexpected choice") } } } diff --git a/internal/cmd/doctorcmd.go b/internal/cmd/doctorcmd.go index 3db7ff5b3fe..0e0059e3d3b 100644 --- a/internal/cmd/doctorcmd.go +++ b/internal/cmd/doctorcmd.go @@ -465,7 +465,7 @@ func (c *binaryCheck) Run(system chezmoi.System, homeDirAbsPath chezmoi.AbsPath) var pathAbsPath chezmoi.AbsPath switch path, err := chezmoi.LookPath(c.binaryname); { case errors.Is(err, exec.ErrNotFound): - return c.ifNotExist, fmt.Sprintf("%s not found in $PATH", c.binaryname) + return c.ifNotExist, c.binaryname + " not found in $PATH" case err != nil: return checkResultFailed, err.Error() default: @@ -551,7 +551,7 @@ func (c *configFileCheck) Run(system chezmoi.System, homeDirAbsPath chezmoi.AbsP filenameStrs = append(filenameStrs, filenameAbsPath.String()) } sort.Strings(filenameStrs) - return checkResultWarning, fmt.Sprintf("%s: multiple config files", englishList(filenameStrs)) + return checkResultWarning, englishList(filenameStrs) + ": multiple config files" } } diff --git a/internal/cmd/readdcmd.go b/internal/cmd/readdcmd.go index a893018e9d0..ac285c0d50c 100644 --- a/internal/cmd/readdcmd.go +++ b/internal/cmd/readdcmd.go @@ -140,7 +140,7 @@ TARGET_REL_PATH: case choice == "quit": return chezmoi.ExitCodeError(0) default: - panic(fmt.Sprintf("%s: unexpected choice", choice)) + panic(choice + ": unexpected choice") } } } diff --git a/internal/cmd/statuscmd.go b/internal/cmd/statuscmd.go index d434c98e5f1..a399a57ce27 100644 --- a/internal/cmd/statuscmd.go +++ b/internal/cmd/statuscmd.go @@ -1,6 +1,7 @@ package cmd import ( + "errors" "fmt" "io/fs" "strings" @@ -81,9 +82,9 @@ func (c *Config) runStatusCmd(cmd *cobra.Command, args []string) error { case chezmoi.PathStyleRelative: path = targetRelPath.String() case chezmoi.PathStyleSourceAbsolute: - return fmt.Errorf("source-absolute not supported for status") + return errors.New("source-absolute not supported for status") case chezmoi.PathStyleSourceRelative: - return fmt.Errorf("source-relative not supported for status") + return errors.New("source-relative not supported for status") } fmt.Fprintf(&builder, "%c%c %s\n", x, y, path) diff --git a/internal/cmds/execute-template/main.go b/internal/cmds/execute-template/main.go index d872770962f..ef7a79dde4c 100644 --- a/internal/cmds/execute-template/main.go +++ b/internal/cmds/execute-template/main.go @@ -93,7 +93,7 @@ func run() error { } if flag.NArg() == 0 { - return fmt.Errorf("no arguments") + return errors.New("no arguments") } templateName := path.Base(flag.Arg(0)) diff --git a/internal/git/status.go b/internal/git/status.go index e1ad753fa47..7d8b5e7a165 100644 --- a/internal/git/status.go +++ b/internal/git/status.go @@ -3,7 +3,6 @@ package git import ( "bufio" "bytes" - "fmt" "regexp" "strconv" ) @@ -127,7 +126,7 @@ var ( ) func (e ParseError) Error() string { - return fmt.Sprintf("%s: parse error", string(e)) + return string(e) + ": parse error" } // ParseStatusPorcelainV2 parses the output of
chore
Reduce use of fmt.Sprintf
4141e796f8e86ea07b59f46b03d711d33635a330
2022-02-21 07:53:42
Tom Payne
chore: Make GitHub linguist stats more accurate
false
diff --git a/.gitattributes b/.gitattributes index d9e289a0fe5..df6f3cf6808 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,5 +1,5 @@ * -text # Make GitHub language breakdown more accurate, see https://github.com/github/linguist -*.gen.go linguist-generated +assets/scripts/install.sh linguist-generated completions/* linguist-generated
chore
Make GitHub linguist stats more accurate
eaa27b35da4f776fe114e721fb52efee9ee8af90
2022-04-29 04:07:46
Tom Payne
fix: Don't cache negative results of path lookups
false
diff --git a/pkg/chezmoi/lookpath.go b/pkg/chezmoi/lookpath.go index 74d81218aab..6461e3c0201 100644 --- a/pkg/chezmoi/lookpath.go +++ b/pkg/chezmoi/lookpath.go @@ -5,29 +5,25 @@ import ( "sync" ) -type lookPathCacheValue struct { - path string - err error -} - var ( lookPathCacheMutex sync.Mutex - lookPathCache = make(map[string]lookPathCacheValue) + lookPathCache = make(map[string]string) ) -// LookPath is like os/exec.LookPath except that results are cached. +// LookPath is like os/exec.LookPath except that the first positive result is +// cached. func LookPath(file string) (string, error) { lookPathCacheMutex.Lock() defer lookPathCacheMutex.Unlock() - if result, ok := lookPathCache[file]; ok { - return result.path, result.err + if path, ok := lookPathCache[file]; ok { + return path, nil } path, err := exec.LookPath(file) - lookPathCache[file] = lookPathCacheValue{ - path: path, - err: err, + if err == nil { + lookPathCache[file] = path } + return path, err }
fix
Don't cache negative results of path lookups
a846e2c922fcbaf8b2bf01de857fc5b8c37a1e70
2024-02-07 15:25:08
Tom Payne
chore: Use standard maps and slices packages
false
diff --git a/go.mod b/go.mod index 3256315a526..a3eab448ceb 100644 --- a/go.mod +++ b/go.mod @@ -47,7 +47,6 @@ require ( github.com/zricethezav/gitleaks/v8 v8.18.2 go.etcd.io/bbolt v1.3.8 golang.org/x/crypto v0.18.0 - golang.org/x/exp v0.0.0-20240119083558-1b970713d09a golang.org/x/oauth2 v0.16.0 golang.org/x/sync v0.6.0 golang.org/x/sys v0.16.0 @@ -149,6 +148,7 @@ require ( github.com/yuin/goldmark v1.7.0 // indirect github.com/yuin/goldmark-emoji v1.0.2 // indirect go.uber.org/multierr v1.11.0 // indirect + golang.org/x/exp v0.0.0-20240119083558-1b970713d09a // indirect golang.org/x/mod v0.14.0 // indirect golang.org/x/net v0.20.0 // indirect golang.org/x/text v0.14.0 // indirect diff --git a/internal/chezmoi/autotemplate.go b/internal/chezmoi/autotemplate.go index 42c984e61e6..f6d8c11b1a7 100644 --- a/internal/chezmoi/autotemplate.go +++ b/internal/chezmoi/autotemplate.go @@ -2,10 +2,9 @@ package chezmoi import ( "regexp" + "slices" "sort" "strings" - - "golang.org/x/exp/slices" ) // A templateVariable is a template variable. It is used instead of a diff --git a/internal/chezmoi/boltpersistentstate.go b/internal/chezmoi/boltpersistentstate.go index c2966d269e1..5df90823742 100644 --- a/internal/chezmoi/boltpersistentstate.go +++ b/internal/chezmoi/boltpersistentstate.go @@ -5,11 +5,11 @@ import ( "fmt" "io/fs" "os" + "slices" "syscall" "time" "go.etcd.io/bbolt" - "golang.org/x/exp/slices" ) // A BoltPersistentStateMode is a mode for opening a PersistentState. diff --git a/internal/chezmoi/chezmoi_windows.go b/internal/chezmoi/chezmoi_windows.go index c6fad0afcca..2a36896adad 100644 --- a/internal/chezmoi/chezmoi_windows.go +++ b/internal/chezmoi/chezmoi_windows.go @@ -4,9 +4,8 @@ import ( "io/fs" "os" "path/filepath" + "slices" "strings" - - "golang.org/x/exp/slices" ) const nativeLineEnding = "\r\n" diff --git a/internal/chezmoi/refreshexternals.go b/internal/chezmoi/refreshexternals.go index b23e0393bb6..db0416d5e02 100644 --- a/internal/chezmoi/refreshexternals.go +++ b/internal/chezmoi/refreshexternals.go @@ -4,7 +4,7 @@ import ( "fmt" "strings" - "golang.org/x/exp/maps" + "github.com/twpayne/chezmoi/v2/internal/chezmoimaps" ) type RefreshExternals int @@ -22,7 +22,7 @@ var ( "never": RefreshExternalsNever, } - RefreshExternalsFlagCompletionFunc = FlagCompletionFunc(maps.Keys(refreshExternalsWellKnownStrings)) + RefreshExternalsFlagCompletionFunc = FlagCompletionFunc(chezmoimaps.Keys(refreshExternalsWellKnownStrings)) ) func (re *RefreshExternals) Set(s string) error { diff --git a/internal/chezmoi/sourcestate.go b/internal/chezmoi/sourcestate.go index a0c5147b6a4..b88941f2749 100644 --- a/internal/chezmoi/sourcestate.go +++ b/internal/chezmoi/sourcestate.go @@ -19,6 +19,7 @@ import ( "path/filepath" "regexp" "runtime" + "slices" "sort" "strings" "sync" @@ -30,11 +31,10 @@ import ( "github.com/mitchellh/copystructure" "github.com/rs/zerolog" "github.com/rs/zerolog/log" - "golang.org/x/exp/maps" - "golang.org/x/exp/slices" "github.com/twpayne/chezmoi/v2/internal/chezmoierrors" "github.com/twpayne/chezmoi/v2/internal/chezmoilog" + "github.com/twpayne/chezmoi/v2/internal/chezmoimaps" ) // An ExternalType is a type of external source. @@ -338,7 +338,7 @@ func (s *SourceState) Add( options *AddOptions, ) error { // Filter out excluded and ignored paths. - destAbsPaths := AbsPaths(maps.Keys(destAbsPathInfos)) + destAbsPaths := AbsPaths(chezmoimaps.Keys(destAbsPathInfos)) sort.Sort(destAbsPaths) n := 0 for _, destAbsPath := range destAbsPaths { diff --git a/internal/chezmoi/sourcestatetreenode.go b/internal/chezmoi/sourcestatetreenode.go index f15a86d67bd..c4589f65aa7 100644 --- a/internal/chezmoi/sourcestatetreenode.go +++ b/internal/chezmoi/sourcestatetreenode.go @@ -6,7 +6,7 @@ import ( "io/fs" "sort" - "golang.org/x/exp/maps" + "github.com/twpayne/chezmoi/v2/internal/chezmoimaps" ) // A sourceStateEntryTreeNode is a node in a tree of SourceStateEntries. @@ -65,7 +65,7 @@ func (n *sourceStateEntryTreeNode) ForEachNode(targetRelPath RelPath, f func(Rel return err } - childrenByRelPath := RelPaths(maps.Keys(n.children)) + childrenByRelPath := RelPaths(chezmoimaps.Keys(n.children)) sort.Sort(childrenByRelPath) for _, childRelPath := range childrenByRelPath { child := n.children[childRelPath] diff --git a/internal/chezmoilog/chezmoilog.go b/internal/chezmoilog/chezmoilog.go index 9e93e904f3d..8bdd2bce623 100644 --- a/internal/chezmoilog/chezmoilog.go +++ b/internal/chezmoilog/chezmoilog.go @@ -6,11 +6,11 @@ import ( "net/http" "os" "os/exec" + "slices" "time" "github.com/rs/zerolog" "github.com/rs/zerolog/log" - "golang.org/x/exp/slices" ) const few = 64 diff --git a/internal/chezmoimaps/chezmoimaps.go b/internal/chezmoimaps/chezmoimaps.go index cd2c49aaed9..70eef78f6e3 100644 --- a/internal/chezmoimaps/chezmoimaps.go +++ b/internal/chezmoimaps/chezmoimaps.go @@ -2,14 +2,22 @@ package chezmoimaps import ( - "golang.org/x/exp/constraints" - "golang.org/x/exp/maps" - "golang.org/x/exp/slices" + "cmp" + "slices" ) +// Keys returns the keys of the map m. +func Keys[M ~map[K]V, K comparable, V any](m M) []K { + keys := make([]K, 0, len(m)) + for key := range m { + keys = append(keys, key) + } + return keys +} + // SortedKeys returns the keys of the map m in order. -func SortedKeys[M ~map[K]V, K constraints.Ordered, V any](m M) []K { - keys := maps.Keys(m) +func SortedKeys[M ~map[K]V, K cmp.Ordered, V any](m M) []K { + keys := Keys(m) slices.Sort(keys) return keys } diff --git a/internal/cmd/annotation.go b/internal/cmd/annotation.go index 71ec73b482b..0df9b26ce6e 100644 --- a/internal/cmd/annotation.go +++ b/internal/cmd/annotation.go @@ -2,9 +2,9 @@ package cmd import ( "fmt" + "slices" "github.com/spf13/cobra" - "golang.org/x/exp/slices" ) // Annotations. diff --git a/internal/cmd/config.go b/internal/cmd/config.go index 27492f294ca..7a2374ef3a6 100644 --- a/internal/cmd/config.go +++ b/internal/cmd/config.go @@ -9,6 +9,7 @@ import ( "fmt" "io" "io/fs" + "maps" "net/http" "os" "os/exec" @@ -18,6 +19,7 @@ import ( "regexp" "runtime" "runtime/pprof" + "slices" "sort" "strconv" "strings" @@ -42,8 +44,6 @@ import ( "github.com/twpayne/go-xdg/v6" cobracompletefig "github.com/withfig/autocomplete-tools/integrations/cobra" "github.com/zricethezav/gitleaks/v8/detect" - "golang.org/x/exp/maps" - "golang.org/x/exp/slices" "golang.org/x/term" "mvdan.cc/sh/v3/expand" "mvdan.cc/sh/v3/syntax" diff --git a/internal/cmd/dashlanetemplatefuncs.go b/internal/cmd/dashlanetemplatefuncs.go index fd31596f78b..8358c130365 100644 --- a/internal/cmd/dashlanetemplatefuncs.go +++ b/internal/cmd/dashlanetemplatefuncs.go @@ -4,8 +4,7 @@ import ( "encoding/json" "os" "os/exec" - - "golang.org/x/exp/slices" + "slices" "github.com/twpayne/chezmoi/v2/internal/chezmoilog" ) diff --git a/internal/cmd/dopplertemplatefuncs.go b/internal/cmd/dopplertemplatefuncs.go index 6a1dbb02972..d6108bc8f33 100644 --- a/internal/cmd/dopplertemplatefuncs.go +++ b/internal/cmd/dopplertemplatefuncs.go @@ -5,10 +5,9 @@ import ( "fmt" "os" "os/exec" + "slices" "strings" - "golang.org/x/exp/slices" - "github.com/twpayne/chezmoi/v2/internal/chezmoilog" ) diff --git a/internal/cmd/executetemplatecmd.go b/internal/cmd/executetemplatecmd.go index e507c8ce5be..67b4c036e8c 100644 --- a/internal/cmd/executetemplatecmd.go +++ b/internal/cmd/executetemplatecmd.go @@ -3,11 +3,11 @@ package cmd import ( "fmt" "io" + "slices" "strconv" "strings" "github.com/spf13/cobra" - "golang.org/x/exp/slices" "github.com/twpayne/chezmoi/v2/internal/chezmoi" ) diff --git a/internal/cmd/hcpvaultsecretsttemplatefuncs.go b/internal/cmd/hcpvaultsecretsttemplatefuncs.go index 5dc1005c47d..374071d9ab1 100644 --- a/internal/cmd/hcpvaultsecretsttemplatefuncs.go +++ b/internal/cmd/hcpvaultsecretsttemplatefuncs.go @@ -5,10 +5,10 @@ import ( "fmt" "os" "os/exec" + "slices" "strings" "github.com/coreos/go-semver/semver" - "golang.org/x/exp/slices" "github.com/twpayne/chezmoi/v2/internal/chezmoilog" ) diff --git a/internal/cmd/keepassxctemplatefuncs.go b/internal/cmd/keepassxctemplatefuncs.go index 290b9ee7974..4b5df48994b 100644 --- a/internal/cmd/keepassxctemplatefuncs.go +++ b/internal/cmd/keepassxctemplatefuncs.go @@ -8,13 +8,13 @@ import ( "os" "os/exec" "regexp" + "slices" "strconv" "strings" "time" "github.com/Netflix/go-expect" "github.com/coreos/go-semver/semver" - "golang.org/x/exp/slices" "github.com/twpayne/chezmoi/v2/internal/chezmoi" "github.com/twpayne/chezmoi/v2/internal/chezmoilog" diff --git a/internal/cmd/passholetemplatefuncs.go b/internal/cmd/passholetemplatefuncs.go index 2afb0c95c50..ecd212fbef4 100644 --- a/internal/cmd/passholetemplatefuncs.go +++ b/internal/cmd/passholetemplatefuncs.go @@ -5,9 +5,9 @@ import ( "io" "os" "os/exec" + "slices" "github.com/coreos/go-semver/semver" - "golang.org/x/exp/slices" "github.com/twpayne/chezmoi/v2/internal/chezmoilog" ) diff --git a/internal/cmd/prompt.go b/internal/cmd/prompt.go index 9d9154d27af..c78c5abc307 100644 --- a/internal/cmd/prompt.go +++ b/internal/cmd/prompt.go @@ -3,11 +3,11 @@ package cmd import ( "bufio" "fmt" + "slices" "strconv" "strings" tea "github.com/charmbracelet/bubbletea" - "golang.org/x/exp/slices" "github.com/twpayne/chezmoi/v2/internal/chezmoi" "github.com/twpayne/chezmoi/v2/internal/chezmoibubbles" diff --git a/internal/cmd/secrettemplatefuncs.go b/internal/cmd/secrettemplatefuncs.go index f0dbea21ed8..04aaaa8893b 100644 --- a/internal/cmd/secrettemplatefuncs.go +++ b/internal/cmd/secrettemplatefuncs.go @@ -5,10 +5,9 @@ import ( "encoding/json" "os" "os/exec" + "slices" "strings" - "golang.org/x/exp/slices" - "github.com/twpayne/chezmoi/v2/internal/chezmoilog" ) diff --git a/internal/cmd/templatefuncs.go b/internal/cmd/templatefuncs.go index 4e2ed85dcf5..8a889d0aa6e 100644 --- a/internal/cmd/templatefuncs.go +++ b/internal/cmd/templatefuncs.go @@ -12,12 +12,12 @@ import ( "path/filepath" "regexp" "runtime" + "slices" "strconv" "strings" "github.com/bradenhilton/mozillainstallhash" "github.com/itchyny/gojq" - "golang.org/x/exp/slices" "gopkg.in/ini.v1" "howett.net/plist" diff --git a/internal/cmd/unmanagedcmd.go b/internal/cmd/unmanagedcmd.go index d0127a265a1..e5fb75e4893 100644 --- a/internal/cmd/unmanagedcmd.go +++ b/internal/cmd/unmanagedcmd.go @@ -7,9 +7,9 @@ import ( "strings" "github.com/spf13/cobra" - "golang.org/x/exp/maps" "github.com/twpayne/chezmoi/v2/internal/chezmoi" + "github.com/twpayne/chezmoi/v2/internal/chezmoimaps" ) type unmanagedCmdConfig struct { @@ -97,7 +97,7 @@ func (c *Config) runUnmanagedCmd(cmd *cobra.Command, args []string, sourceState } builder := strings.Builder{} - sortedRelPaths := chezmoi.RelPaths(maps.Keys(unmanagedRelPaths)) + sortedRelPaths := chezmoi.RelPaths(chezmoimaps.Keys(unmanagedRelPaths)) sort.Sort(sortedRelPaths) for _, relPath := range sortedRelPaths { switch c.unmanaged.pathStyle { diff --git a/internal/cmds/lint-txtar/main.go b/internal/cmds/lint-txtar/main.go index f667db540a5..f93fe7383d3 100644 --- a/internal/cmds/lint-txtar/main.go +++ b/internal/cmds/lint-txtar/main.go @@ -5,10 +5,10 @@ import ( "flag" "fmt" "os" + "slices" "strings" "github.com/rogpeppe/go-internal/txtar" - "golang.org/x/exp/slices" "github.com/twpayne/chezmoi/v2/internal/chezmoierrors" )
chore
Use standard maps and slices packages
524cf197fefc069cabd60e16ecb578605f847487
2022-01-05 18:54:56
Tom Payne
chore: Improve error message when parsing .chezmoiversion
false
diff --git a/internal/chezmoi/sourcestate.go b/internal/chezmoi/sourcestate.go index ad787058609..61de70ac3d8 100644 --- a/internal/chezmoi/sourcestate.go +++ b/internal/chezmoi/sourcestate.go @@ -1895,7 +1895,7 @@ func (s *SourceState) readVersionFile(sourceAbsPath AbsPath) error { } version, err := semver.NewVersion(strings.TrimSpace(string(data))) if err != nil { - return err + return fmt.Errorf("%s: %q: %w", sourceAbsPath, data, err) } var zeroVersion semver.Version if s.version != zeroVersion && s.version.LessThan(*version) { diff --git a/internal/cmd/config.go b/internal/cmd/config.go index c931ed02ba0..9edf3a3d5a1 100644 --- a/internal/cmd/config.go +++ b/internal/cmd/config.go @@ -1380,7 +1380,7 @@ func (c *Config) newSourceState( default: minVersion, err := semver.NewVersion(strings.TrimSpace(string(data))) if err != nil { - return nil, fmt.Errorf("%s: %w", versionAbsPath, err) + return nil, fmt.Errorf("%s: %q: %w", versionAbsPath, data, err) } var zeroVersion semver.Version if c.version != zeroVersion && c.version.LessThan(*minVersion) {
chore
Improve error message when parsing .chezmoiversion
74cdf24bb6777a134b21ff8e49a2de49bbfd88f4
2021-01-24 22:25:14
Justin Grote
fix: Add musl-tools for goreleaser
false
diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index 5b3fa2c4d86..2b048cded19 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -4,7 +4,7 @@ FROM mcr.microsoft.com/vscode/devcontainers/go:0-${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 + && apt-get -y install --no-install-recommends acl musl-tools snapcraft # [Optional] Uncomment the next line to use go get to install anything else you need RUN go get -x mvdan.cc/gofumpt
fix
Add musl-tools for goreleaser
18368c2731c122c483e3cac18ce8a640ef041f3d
2023-01-17 05:02:55
Tom Payne
feat: Remove duplication from error messages
false
diff --git a/pkg/cmd/cmd.go b/pkg/cmd/cmd.go index 6ac2a2767a6..924e6677cc6 100644 --- a/pkg/cmd/cmd.go +++ b/pkg/cmd/cmd.go @@ -29,7 +29,8 @@ const ( var ( noArgs = []string(nil) - trailingSpaceRx = regexp.MustCompile(` +\n`) + deDuplicateErrorRx = regexp.MustCompile(`:\s+`) + trailingSpaceRx = regexp.MustCompile(` +\n`) helps = make(map[string]*help) ) @@ -109,12 +110,28 @@ func Main(versionInfo VersionInfo, args []string) int { if errors.As(err, &errExitCode) { return int(errExitCode) } - fmt.Fprintf(os.Stderr, "chezmoi: %v\n", err) + fmt.Fprintf(os.Stderr, "chezmoi: %s\n", deDuplicateError(err)) return 1 } return 0 } +// deDuplicateError returns err's human-readable string with duplicate components +// removed. +func deDuplicateError(err error) string { + components := deDuplicateErrorRx.Split(err.Error(), -1) + seenComponents := make(map[string]struct{}, len(components)) + uniqueComponents := make([]string, 0, len(components)) + for _, component := range components { + if _, ok := seenComponents[component]; ok { + continue + } + uniqueComponents = append(uniqueComponents, component) + seenComponents[component] = struct{}{} + } + return strings.Join(uniqueComponents, ": ") +} + // example returns command's example. func example(command string) string { help, ok := helps[command] diff --git a/pkg/cmd/cmd_test.go b/pkg/cmd/cmd_test.go index 8a83ef4dfea..f27127e6d40 100644 --- a/pkg/cmd/cmd_test.go +++ b/pkg/cmd/cmd_test.go @@ -1,6 +1,8 @@ package cmd import ( + "errors" + "strconv" "testing" "github.com/stretchr/testify/assert" @@ -15,6 +17,51 @@ func init() { chezmoi.Umask = chezmoitest.Umask } +func TestDeDuplicateError(t *testing.T) { + for i, tc := range []struct { + errStr string + expected string + }{ + { + errStr: "", + expected: "", + }, + { + errStr: "a", + expected: "a", + }, + { + errStr: "a: a", + expected: "a", + }, + { + errStr: "a: b", + expected: "a: b", + }, + { + errStr: "a: a: b", //nolint:dupword + expected: "a: b", + }, + { + errStr: "a: b: b", + expected: "a: b", + }, + { + errStr: "a: b: c: b: a: d", + expected: "a: b: c: d", + }, + { + errStr: "a: b: a: b: c", + expected: "a: b: c", + }, + } { + t.Run(strconv.Itoa(i), func(t *testing.T) { + actual := deDuplicateError(errors.New(tc.errStr)) + assert.Equal(t, tc.expected, actual) + }) + } +} + func TestMustGetLongHelpPanics(t *testing.T) { assert.Panics(t, func() { mustLongHelp("non-existent-command") diff --git a/pkg/cmd/testdata/scripts/issue2695.txtar b/pkg/cmd/testdata/scripts/issue2695.txtar index a5b59ba7079..8f5a498d614 100644 --- a/pkg/cmd/testdata/scripts/issue2695.txtar +++ b/pkg/cmd/testdata/scripts/issue2695.txtar @@ -1,6 +1,7 @@ # test that chezmoi status returns an error when the JSON config file is invalid ! exec chezmoi status stderr 'invalid config' +! stderr 'json.*json' # check that chezmoi doctor warns about invalid JSON config files ! exec chezmoi doctor @@ -11,6 +12,7 @@ chhome home2/user # test that chezmoi status returns an error when the TOML config file is invalid ! exec chezmoi status stderr 'invalid config' +! stderr 'chezmoi\.toml.*chezmoi\.toml' # check that chezmoi doctor warns about invalid TOML config files ! exec chezmoi doctor @@ -21,6 +23,7 @@ chhome home3/user # test that chezmoi status returns an error when the YAML config file is invalid ! exec chezmoi status stderr 'invalid config' +! stderr 'chezmoi\.yaml.*chezmoi\.yaml' # check that chezmoi doctor warns about invalid YAML config files ! exec chezmoi doctor
feat
Remove duplication from error messages
060faf6622eb7702b83969abc69c0c417ebae033
2023-03-05 19:54:44
Tom Payne
fix: Allow underscores and dots in GitHub dotfile repo name guesses
false
diff --git a/pkg/cmd/initcmd.go b/pkg/cmd/initcmd.go index c93741a3f48..7df6674da0b 100644 --- a/pkg/cmd/initcmd.go +++ b/pkg/cmd/initcmd.go @@ -47,7 +47,7 @@ var repoGuesses = []struct { sshRepoGuessRepl: "[email protected]:$1/dotfiles.git", }, { - rx: regexp.MustCompile(`\A([-0-9A-Za-z]+)/([-0-9A-Za-z]+)(\.git)?\z`), + rx: regexp.MustCompile(`\A([-0-9A-Za-z]+)/([-\.0-9A-Z_a-z]+?)(\.git)?\z`), httpRepoGuessRepl: "https://github.com/$1/$2.git", sshRepoGuessRepl: "[email protected]:$1/$2.git", }, diff --git a/pkg/cmd/initcmd_test.go b/pkg/cmd/initcmd_test.go index 75619feaee7..4b60f51c83e 100644 --- a/pkg/cmd/initcmd_test.go +++ b/pkg/cmd/initcmd_test.go @@ -73,6 +73,16 @@ func TestGuessRepoURL(t *testing.T) { expectedHTTPRepoURL: "https://github.com/user/dotfiles.git", expectedSSHRepoURL: "[email protected]:user/dotfiles.git", }, + { + arg: "user/chezmoi_dotfiles", + expectedHTTPRepoURL: "https://github.com/user/chezmoi_dotfiles.git", + expectedSSHRepoURL: "[email protected]:user/chezmoi_dotfiles.git", + }, + { + arg: "user/.dotfiles", + expectedHTTPRepoURL: "https://github.com/user/.dotfiles.git", + expectedSSHRepoURL: "[email protected]:user/.dotfiles.git", + }, { arg: "user/dots", expectedHTTPRepoURL: "https://github.com/user/dots.git",
fix
Allow underscores and dots in GitHub dotfile repo name guesses
17105dc1c3d1e3a31ba7ac29fda74d93e05dca42
2022-04-15 00:56:40
Tom Payne
chore: Pin GitHub Actions hashes
false
diff --git a/.github/workflows/lock.yml b/.github/workflows/lock.yml index 54c116d7a71..f6b98d4cca3 100644 --- a/.github/workflows/lock.yml +++ b/.github/workflows/lock.yml @@ -3,7 +3,7 @@ name: lock-threads on: schedule: - cron: '0 0 * * *' - workflow_dispatch: + workflow_dispatch: {} permissions: issues: write @@ -15,7 +15,7 @@ jobs: action: runs-on: ubuntu-latest steps: - - uses: dessant/lock-threads@v3 + - uses: dessant/lock-threads@e460dfeb36e731f3aeb214be6b0c9a9d9a67eda6 # pin@v3 with: issue-lock-reason: resolved issue-inactive-days: 7 diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 11293208f1c..c17fdc6500a 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -2,12 +2,12 @@ name: main on: pull_request: branches: - - master + - master push: branches: - - master + - master tags: - - v* + - v* env: AGE_VERSION: 1.0.0 GO_VERSION: 1.18.1 @@ -17,34 +17,33 @@ jobs: build-website: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 - - name: install-website-dependencies - run: | - pip3 install mkdocs-material mkdocs-mermaid2-plugin mkdocs-redirects mkdocs-simple-hooks - - name: build-website - run: - ( cd assets/chezmoi.io && mkdocs build ) + - uses: actions/checkout@dcd71f646680f2efd8db4afa5ad64fdcba30e748 # pin@v3 + - name: install-website-dependencies + run: | + pip3 install mkdocs-material mkdocs-mermaid2-plugin mkdocs-redirects mkdocs-simple-hooks + - name: build-website + run: ( cd assets/chezmoi.io && mkdocs build ) changes: runs-on: ubuntu-20.04 outputs: code: ${{ steps.filter.outputs.code }} steps: - - uses: actions/checkout@v3 - - id: filter - uses: dorny/paths-filter@v2 - with: - filters: | - code: - - '**/*.go' - - '**/*.ps1' - - '**/*.tmpl' - - '.github/workflows/**' - - 'Makefile' - - 'assets/docker/**' - - 'assets/scripts/**' - - 'assets/vagrant/**' - - 'go.*' - - 'pkg/**' + - uses: actions/checkout@dcd71f646680f2efd8db4afa5ad64fdcba30e748 # pin@v3 + - id: filter + uses: dorny/paths-filter@b2feaf19c27470162a626bd6fa8438ae5b263721 # pin@v2 + with: + filters: | + code: + - '**/*.go' + - '**/*.ps1' + - '**/*.tmpl' + - '.github/workflows/**' + - 'Makefile' + - 'assets/docker/**' + - 'assets/scripts/**' + - 'assets/vagrant/**' + - 'go.*' + - 'pkg/**' codeql: needs: changes if: github.event_name == 'push' || needs.changes.outputs.code == 'true' @@ -52,35 +51,35 @@ jobs: permissions: security-events: write steps: - - uses: actions/checkout@v3 - with: - fetch-depth: 1 - - uses: github/codeql-action/init@v1 - with: - languages: go - - uses: github/codeql-action/analyze@v1 + - uses: actions/checkout@dcd71f646680f2efd8db4afa5ad64fdcba30e748 # pin@v3 + with: + fetch-depth: 1 + - uses: github/codeql-action/init@e2cc7cc006b87d43538b16d71752753e7b85224d # pin@v1 + with: + languages: go + - uses: github/codeql-action/analyze@e2cc7cc006b87d43538b16d71752753e7b85224d # pin@v1 test-alpine: needs: changes if: github.event_name == 'push' || needs.changes.outputs.code == 'true' runs-on: ubuntu-20.04 steps: - - uses: actions/checkout@v3 - - name: test - env: - CHEZMOI_GITHUB_TOKEN: ${{ secrets.CHEZMOI_GITHUB_TOKEN }} - run: | - ( cd assets/docker && ./test.sh alpine ) + - uses: actions/checkout@dcd71f646680f2efd8db4afa5ad64fdcba30e748 # pin@v3 + - name: test + env: + CHEZMOI_GITHUB_TOKEN: ${{ secrets.CHEZMOI_GITHUB_TOKEN }} + run: | + ( cd assets/docker && ./test.sh alpine ) test-archlinux: needs: changes if: github.event_name == 'push' || needs.changes.outputs.code == 'true' runs-on: ubuntu-20.04 steps: - - uses: actions/checkout@v3 - - name: test - env: - CHEZMOI_GITHUB_TOKEN: ${{ secrets.CHEZMOI_GITHUB_TOKEN }} - run: | - ( cd assets/docker && ./test.sh archlinux ) + - uses: actions/checkout@dcd71f646680f2efd8db4afa5ad64fdcba30e748 # pin@v3 + - name: test + env: + CHEZMOI_GITHUB_TOKEN: ${{ secrets.CHEZMOI_GITHUB_TOKEN }} + run: | + ( cd assets/docker && ./test.sh archlinux ) test-debian-i386: needs: changes if: github.event_name == 'push' || needs.changes.outputs.code == 'true' @@ -88,27 +87,28 @@ jobs: env: VAGRANT_BOX: debian11-i386 steps: - - uses: actions/checkout@v3 - - uses: actions/[email protected] - with: - path: ~/.vagrant.d - key: ${{ runner.os }}-vagrant-${{ env.VAGRANT_BOX }}-${{ hashFiles('assets/vagrant/debian11-i386.Vagrantfile') }} - restore-keys: | - ${{ runner.os }}-vagrant-${{ env.VAGRANT_BOX }}- - - name: test - run: | - ( cd assets/vagrant && ./test.sh debian11-i386 ) + - uses: actions/checkout@dcd71f646680f2efd8db4afa5ad64fdcba30e748 # pin@v3 + - uses: actions/cache@136d96b4aee02b1f0de3ba493b1d47135042d9c0 # [email protected] + with: + path: ~/.vagrant.d + key: ${{ runner.os }}-vagrant-${{ env.VAGRANT_BOX }}-${{ + hashFiles('assets/vagrant/debian11-i386.Vagrantfile') }} + restore-keys: | + ${{ runner.os }}-vagrant-${{ env.VAGRANT_BOX }}- + - name: test + run: | + ( cd assets/vagrant && ./test.sh debian11-i386 ) test-fedora: needs: changes if: github.event_name == 'push' || needs.changes.outputs.code == 'true' runs-on: ubuntu-20.04 steps: - - uses: actions/checkout@v3 - - name: test - env: - CHEZMOI_GITHUB_TOKEN: ${{ secrets.CHEZMOI_GITHUB_TOKEN }} - run: | - ( cd assets/docker && ./test.sh fedora ) + - uses: actions/checkout@dcd71f646680f2efd8db4afa5ad64fdcba30e748 # pin@v3 + - name: test + env: + CHEZMOI_GITHUB_TOKEN: ${{ secrets.CHEZMOI_GITHUB_TOKEN }} + run: | + ( cd assets/docker && ./test.sh fedora ) test-freebsd: needs: changes if: github.event_name == 'push' || needs.changes.outputs.code == 'true' @@ -116,332 +116,332 @@ jobs: env: VAGRANT_BOX: freebsd13 steps: - - uses: actions/checkout@v3 - - uses: actions/[email protected] - with: - path: ~/.vagrant.d - key: ${{ runner.os }}-vagrant-${{ env.VAGRANT_BOX }}-${{ hashFiles('assets/vagrant/freebsd13.Vagrantfile') }} - restore-keys: | - ${{ runner.os }}-vagrant-${{ env.VAGRANT_BOX }}- - - name: test - run: | - ( cd assets/vagrant && ./test.sh freebsd13 ) + - uses: actions/checkout@dcd71f646680f2efd8db4afa5ad64fdcba30e748 # pin@v3 + - uses: actions/cache@136d96b4aee02b1f0de3ba493b1d47135042d9c0 # [email protected] + with: + path: ~/.vagrant.d + key: ${{ runner.os }}-vagrant-${{ env.VAGRANT_BOX }}-${{ + hashFiles('assets/vagrant/freebsd13.Vagrantfile') }} + restore-keys: | + ${{ runner.os }}-vagrant-${{ env.VAGRANT_BOX }}- + - name: test + run: | + ( cd assets/vagrant && ./test.sh freebsd13 ) test-macos: needs: changes if: github.event_name == 'push' || needs.changes.outputs.code == 'true' runs-on: macos-11 steps: - - uses: actions/setup-go@v2 - with: - go-version: ${{ env.GO_VERSION }} - - uses: actions/checkout@v3 - - uses: actions/[email protected] - with: - path: ~/go/pkg/mod - key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} - restore-keys: | - ${{ runner.os }}-go- - - name: build - run: | - go build ./... - - name: run - run: | - go run . --version - - name: install-age - run: | - cd $(mktemp -d) - curl -fsSL https://github.com/FiloSottile/age/releases/download/v${AGE_VERSION}/age-v${AGE_VERSION}-darwin-amd64.tar.gz | tar xzf - - sudo install -m 755 age/age /usr/local/bin - sudo install -m 755 age/age-keygen /usr/local/bin - - name: test - env: - CHEZMOI_GITHUB_TOKEN: ${{ secrets.CHEZMOI_GITHUB_TOKEN }} - run: | - go test -race ./... - - name: test-install.sh - run: | - sh assets/scripts/install.sh - bin/chezmoi --version + - uses: actions/setup-go@bfdd3570ce990073878bf10f6b2d79082de49492 # pin@v2 + with: + go-version: ${{ env.GO_VERSION }} + - uses: actions/checkout@dcd71f646680f2efd8db4afa5ad64fdcba30e748 # pin@v3 + - uses: actions/cache@136d96b4aee02b1f0de3ba493b1d47135042d9c0 # [email protected] + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go- + - name: build + run: | + go build ./... + - name: run + run: | + go run . --version + - name: install-age + run: | + cd $(mktemp -d) + curl -fsSL https://github.com/FiloSottile/age/releases/download/v${AGE_VERSION}/age-v${AGE_VERSION}-darwin-amd64.tar.gz | tar xzf - + sudo install -m 755 age/age /usr/local/bin + sudo install -m 755 age/age-keygen /usr/local/bin + - name: test + env: + CHEZMOI_GITHUB_TOKEN: ${{ secrets.CHEZMOI_GITHUB_TOKEN }} + run: | + go test -race ./... + - name: test-install.sh + run: | + sh assets/scripts/install.sh + bin/chezmoi --version test-ubuntu: needs: changes runs-on: ubuntu-18.04 steps: - - uses: actions/setup-go@v2 - with: - go-version: ${{ env.GO_VERSION }} - - name: install-age - if: github.event_name == 'push' || needs.changes.outputs.code == 'true' - run: | - cd $(mktemp -d) - curl -fsSL https://github.com/FiloSottile/age/releases/download/v${AGE_VERSION}/age-v${AGE_VERSION}-linux-amd64.tar.gz | tar xzf - - sudo install -m 755 age/age /usr/local/bin - sudo install -m 755 age/age-keygen /usr/local/bin - - uses: actions/checkout@v3 - with: - fetch-depth: 0 - - uses: actions/[email protected] - with: - path: ~/go/pkg/mod - key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} - restore-keys: | - ${{ runner.os }}-go- - - name: build - run: | - go build ./... - - name: run - run: | - go run . --version - - name: test-umask-022 - if: github.event_name == 'push' || needs.changes.outputs.code == 'true' - env: - CHEZMOI_GITHUB_TOKEN: ${{ secrets.CHEZMOI_GITHUB_TOKEN }} - run: | - go test -ldflags="-X github.com/twpayne/chezmoi/pkg/chezmoitest.umaskStr=0o022" -race ./... - - name: test-umask-002 - if: github.event_name == 'push' || needs.changes.outputs.code == 'true' - env: - CHEZMOI_GITHUB_TOKEN: ${{ secrets.CHEZMOI_GITHUB_TOKEN }} - run: | - go test -ldflags="-X github.com/twpayne/chezmoi/pkg/chezmoitest.umaskStr=0o002" -race ./... - - name: test-install.sh - if: github.event_name == 'push' || needs.changes.outputs.code == 'true' - run: | - rm -f bin/chezmoi - sh assets/scripts/install.sh - bin/chezmoi --version - - name: install-release-dependencies - if: github.event_name == 'push' || needs.changes.outputs.code == 'true' - run: | - sudo apt-get update - sudo apt-get -yq --no-install-suggests --no-install-recommends install musl-tools snapcraft - - name: build-release - if: github.event_name == 'push' || needs.changes.outputs.code == 'true' - uses: goreleaser/goreleaser-action@v2 - with: - version: latest - args: release --skip-publish --snapshot - - name: test-release - if: github.event_name == 'push' || needs.changes.outputs.code == 'true' - run: | - # verify that version information is embedded correctly - file ./dist/chezmoi-cgo-glibc_linux_amd64/chezmoi | tee /dev/stderr | grep -q "dynamically linked" - file ./dist/chezmoi-cgo-musl_linux_amd64/chezmoi | tee /dev/stderr | grep -q "statically linked" - ./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-darwin-amd64 - if: github.event_name == 'push' || needs.changes.outputs.code == 'true' - uses: actions/upload-artifact@v2 - with: - name: chezmoi-darwin-amd64 - path: dist/chezmoi-nocgo_darwin_amd64/chezmoi - - name: upload-artifact-chezmoi-darwin-arm64 - if: github.event_name == 'push' || needs.changes.outputs.code == 'true' - uses: actions/upload-artifact@v2 - 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@v2 - with: - name: chezmoi-linux-amd64 - path: dist/chezmoi-cgo-glibc_linux_amd64/chezmoi - - name: upload-artifact-chezmoi-linux-musl-amd64 - if: github.event_name == 'push' || needs.changes.outputs.code == 'true' - uses: actions/upload-artifact@v2 - with: - name: chezmoi-linux-amd64-musl - path: dist/chezmoi-cgo-musl_linux_amd64/chezmoi - - name: upload-artifact-chezmoi-windows-amd64.exe - if: github.event_name == 'push' || needs.changes.outputs.code == 'true' - uses: actions/upload-artifact@v2 - with: - name: chezmoi-windows-amd64.exe - path: dist/chezmoi-nocgo_windows_amd64/chezmoi.exe + - uses: actions/setup-go@bfdd3570ce990073878bf10f6b2d79082de49492 # pin@v2 + with: + go-version: ${{ env.GO_VERSION }} + - name: install-age + if: github.event_name == 'push' || needs.changes.outputs.code == 'true' + run: | + cd $(mktemp -d) + curl -fsSL https://github.com/FiloSottile/age/releases/download/v${AGE_VERSION}/age-v${AGE_VERSION}-linux-amd64.tar.gz | tar xzf - + sudo install -m 755 age/age /usr/local/bin + sudo install -m 755 age/age-keygen /usr/local/bin + - uses: actions/checkout@dcd71f646680f2efd8db4afa5ad64fdcba30e748 # pin@v3 + with: + fetch-depth: 0 + - uses: actions/cache@136d96b4aee02b1f0de3ba493b1d47135042d9c0 # [email protected] + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go- + - name: build + run: | + go build ./... + - name: run + run: | + go run . --version + - name: test-umask-022 + if: github.event_name == 'push' || needs.changes.outputs.code == 'true' + env: + CHEZMOI_GITHUB_TOKEN: ${{ secrets.CHEZMOI_GITHUB_TOKEN }} + run: | + go test -ldflags="-X github.com/twpayne/chezmoi/pkg/chezmoitest.umaskStr=0o022" -race ./... + - name: test-umask-002 + if: github.event_name == 'push' || needs.changes.outputs.code == 'true' + env: + CHEZMOI_GITHUB_TOKEN: ${{ secrets.CHEZMOI_GITHUB_TOKEN }} + run: | + go test -ldflags="-X github.com/twpayne/chezmoi/pkg/chezmoitest.umaskStr=0o002" -race ./... + - name: test-install.sh + if: github.event_name == 'push' || needs.changes.outputs.code == 'true' + run: | + rm -f bin/chezmoi + sh assets/scripts/install.sh + bin/chezmoi --version + - name: install-release-dependencies + if: github.event_name == 'push' || needs.changes.outputs.code == 'true' + run: | + sudo apt-get update + sudo apt-get -yq --no-install-suggests --no-install-recommends install musl-tools snapcraft + - name: build-release + if: github.event_name == 'push' || needs.changes.outputs.code == 'true' + uses: goreleaser/goreleaser-action@b953231f81b8dfd023c58e0854a721e35037f28b # pin@v2 + with: + version: latest + args: release --skip-publish --snapshot + - name: test-release + if: github.event_name == 'push' || needs.changes.outputs.code == 'true' + run: | + # verify that version information is embedded correctly + file ./dist/chezmoi-cgo-glibc_linux_amd64/chezmoi | tee /dev/stderr | grep -q "dynamically linked" + file ./dist/chezmoi-cgo-musl_linux_amd64/chezmoi | tee /dev/stderr | grep -q "statically linked" + ./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-darwin-amd64 + if: github.event_name == 'push' || needs.changes.outputs.code == 'true' + uses: actions/upload-artifact@82c141cc518b40d92cc801eee768e7aafc9c2fa2 # pin@v2 + with: + name: chezmoi-darwin-amd64 + path: dist/chezmoi-nocgo_darwin_amd64/chezmoi + - name: upload-artifact-chezmoi-darwin-arm64 + if: github.event_name == 'push' || needs.changes.outputs.code == 'true' + uses: actions/upload-artifact@82c141cc518b40d92cc801eee768e7aafc9c2fa2 # pin@v2 + 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@82c141cc518b40d92cc801eee768e7aafc9c2fa2 # pin@v2 + with: + name: chezmoi-linux-amd64 + path: dist/chezmoi-cgo-glibc_linux_amd64/chezmoi + - name: upload-artifact-chezmoi-linux-musl-amd64 + if: github.event_name == 'push' || needs.changes.outputs.code == 'true' + uses: actions/upload-artifact@82c141cc518b40d92cc801eee768e7aafc9c2fa2 # pin@v2 + with: + name: chezmoi-linux-amd64-musl + path: dist/chezmoi-cgo-musl_linux_amd64/chezmoi + - name: upload-artifact-chezmoi-windows-amd64.exe + if: github.event_name == 'push' || needs.changes.outputs.code == 'true' + uses: actions/upload-artifact@82c141cc518b40d92cc801eee768e7aafc9c2fa2 # pin@v2 + with: + name: chezmoi-windows-amd64.exe + path: dist/chezmoi-nocgo_windows_amd64/chezmoi.exe test-ubuntu-go1-17: needs: changes if: github.event_name == 'push' || needs.changes.outputs.code == 'true' runs-on: ubuntu-18.04 steps: - - uses: actions/setup-go@v2 - with: - go-version: 1.17.x - - uses: actions/checkout@v3 - - uses: actions/[email protected] - with: - path: ~/go/pkg/mod - key: ${{ runner.os }}-ubuntu-go-1-17-${{ hashFiles('**/go.sum') }} - restore-keys: | - ${{ runner.os }}-ubuntu-go-1-17- - - name: build - run: | - go build ./... - - name: run - run: | - go run . --version - - name: install-age - run: | - cd $(mktemp -d) - curl -fsSL https://github.com/FiloSottile/age/releases/download/v${AGE_VERSION}/age-v${AGE_VERSION}-linux-amd64.tar.gz | tar xzf - - sudo install -m 755 age/age /usr/local/bin - sudo install -m 755 age/age-keygen /usr/local/bin - - name: test - env: - CHEZMOI_GITHUB_TOKEN: ${{ secrets.CHEZMOI_GITHUB_TOKEN }} - run: | - go test ./... + - uses: actions/setup-go@bfdd3570ce990073878bf10f6b2d79082de49492 # pin@v2 + with: + go-version: 1.17.x + - uses: actions/checkout@dcd71f646680f2efd8db4afa5ad64fdcba30e748 # pin@v3 + - uses: actions/cache@136d96b4aee02b1f0de3ba493b1d47135042d9c0 # [email protected] + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-ubuntu-go-1-17-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-ubuntu-go-1-17- + - name: build + run: | + go build ./... + - name: run + run: | + go run . --version + - name: install-age + run: | + cd $(mktemp -d) + curl -fsSL https://github.com/FiloSottile/age/releases/download/v${AGE_VERSION}/age-v${AGE_VERSION}-linux-amd64.tar.gz | tar xzf - + sudo install -m 755 age/age /usr/local/bin + sudo install -m 755 age/age-keygen /usr/local/bin + - name: test + env: + CHEZMOI_GITHUB_TOKEN: ${{ secrets.CHEZMOI_GITHUB_TOKEN }} + run: | + go test ./... test-windows: needs: changes if: github.event_name == 'push' || needs.changes.outputs.code == 'true' runs-on: windows-2019 steps: - - uses: actions/setup-go@v2 - with: - go-version: ${{ env.GO_VERSION }} - - uses: actions/checkout@v3 - - uses: actions/[email protected] - with: - path: ~/go/pkg/mod - key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} - restore-keys: | - ${{ runner.os }}-go- - - name: build - run: | - go build ./... - - name: run - run: | - go run . --version - - name: test - env: - CHEZMOI_GITHUB_TOKEN: ${{ secrets.CHEZMOI_GITHUB_TOKEN }} - run: | - go test -race ./... - - name: test-install.ps1 - run: | - if (Test-Path -Path bin/chezmoi.exe) { Remove-Item -Force bin/chezmoi.exe } - powershell -c assets/scripts/install.ps1 - bin/chezmoi.exe --version - - name: test-install-irm - run: | - if (Test-Path -Path bin/chezmoi.exe) { Remove-Item -Force bin/chezmoi.exe } - (irm -useb https://chezmoi.io/get.ps1) | powershell -c - - bin/chezmoi.exe --version - - name: test-install-iwr - run: | - 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 + - uses: actions/setup-go@bfdd3570ce990073878bf10f6b2d79082de49492 # pin@v2 + with: + go-version: ${{ env.GO_VERSION }} + - uses: actions/checkout@dcd71f646680f2efd8db4afa5ad64fdcba30e748 # pin@v3 + - uses: actions/cache@136d96b4aee02b1f0de3ba493b1d47135042d9c0 # [email protected] + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go- + - name: build + run: | + go build ./... + - name: run + run: | + go run . --version + - name: test + env: + CHEZMOI_GITHUB_TOKEN: ${{ secrets.CHEZMOI_GITHUB_TOKEN }} + run: | + go test -race ./... + - name: test-install.ps1 + run: | + if (Test-Path -Path bin/chezmoi.exe) { Remove-Item -Force bin/chezmoi.exe } + powershell -c assets/scripts/install.ps1 + bin/chezmoi.exe --version + - name: test-install-irm + run: | + if (Test-Path -Path bin/chezmoi.exe) { Remove-Item -Force bin/chezmoi.exe } + (irm -useb https://chezmoi.io/get.ps1) | powershell -c - + bin/chezmoi.exe --version + - name: test-install-iwr + run: | + 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@v3 - - name: test - env: - CHEZMOI_GITHUB_TOKEN: ${{ secrets.CHEZMOI_GITHUB_TOKEN }} - run: | - ( cd assets/docker && ./test.sh voidlinux ) + - uses: actions/checkout@dcd71f646680f2efd8db4afa5ad64fdcba30e748 # pin@v3 + - name: test + env: + CHEZMOI_GITHUB_TOKEN: ${{ secrets.CHEZMOI_GITHUB_TOKEN }} + run: | + ( cd assets/docker && ./test.sh voidlinux ) check: runs-on: ubuntu-18.04 steps: - - uses: actions/setup-go@v2 - with: - go-version: ${{ env.GO_VERSION }} - - uses: actions/checkout@v3 - - uses: actions/[email protected] - with: - path: ~/go/pkg/mod - key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} - restore-keys: | - ${{ runner.os }}-go- - - name: generate - run: | - go generate - git diff --exit-code - - uses: ludeeus/[email protected] - with: - ignore: completions - - name: lint-whitespace - run: | - go run ./internal/cmds/lint-whitespace - - name: findtypos - run: | - go install github.com/twpayne/[email protected] - findtypos -format=github-actions chezmoi . + - uses: actions/setup-go@bfdd3570ce990073878bf10f6b2d79082de49492 # pin@v2 + with: + go-version: ${{ env.GO_VERSION }} + - uses: actions/checkout@dcd71f646680f2efd8db4afa5ad64fdcba30e748 # pin@v3 + - uses: actions/cache@136d96b4aee02b1f0de3ba493b1d47135042d9c0 # [email protected] + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go- + - name: generate + run: | + go generate + git diff --exit-code + - uses: ludeeus/action-shellcheck@94e0aab03ca135d11a35e5bfc14e6746dc56e7e9 # [email protected] + with: + ignore: completions + - name: lint-whitespace + run: | + go run ./internal/cmds/lint-whitespace + - name: findtypos + run: | + go install github.com/twpayne/[email protected] + findtypos -format=github-actions chezmoi . lint: needs: changes if: github.event_name == 'push' || needs.changes.outputs.code == 'true' runs-on: ubuntu-18.04 steps: - - uses: actions/setup-go@v2 - with: - go-version: ${{ env.GO_VERSION }} - - uses: actions/checkout@v3 - - uses: golangci/[email protected] - with: - version: v${{ env.GOLANGCI_LINT_VERSION }} - args: --timeout=5m + - uses: actions/setup-go@bfdd3570ce990073878bf10f6b2d79082de49492 # pin@v2 + with: + go-version: ${{ env.GO_VERSION }} + - uses: actions/checkout@dcd71f646680f2efd8db4afa5ad64fdcba30e748 # pin@v3 + - uses: golangci/golangci-lint-action@b517f99ae23d86ecc4c0dec08dcf48d2336abc29 # [email protected] + with: + version: v${{ env.GOLANGCI_LINT_VERSION }} + args: --timeout=5m release: # FIXME this should be merged into test-ubuntu above if: startsWith(github.ref, 'refs/tags/') needs: - - build-website - - check - - lint - - test-alpine - - test-archlinux - - test-debian-i386 - - test-fedora - - test-freebsd - - test-macos - - test-ubuntu - - test-ubuntu-go1-17 - - test-voidlinux - - test-windows + - build-website + - check + - lint + - test-alpine + - test-archlinux + - test-debian-i386 + - test-fedora + - test-freebsd + - test-macos + - test-ubuntu + - test-ubuntu-go1-17 + - test-voidlinux + - test-windows runs-on: ubuntu-18.04 steps: - - name: install-build-dependencies - run: | - sudo apt-get update - sudo apt-get -yq --no-install-suggests --no-install-recommends install musl-tools snapcraft - - uses: actions/setup-go@v2 - with: - go-version: ${{ env.GO_VERSION }} - - uses: actions/checkout@v3 - with: - fetch-depth: 0 - - uses: actions/[email protected] - with: - path: ~/go/pkg/mod - key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} - restore-keys: | - ${{ runner.os }}-go- - - name: snapcraft-login - env: - SNAPCRAFT_LOGIN: ${{ secrets.SNAPCRAFT_LOGIN }} - run: | - snapcraft login --with <(echo "$SNAPCRAFT_LOGIN" | base64 -d) - - uses: goreleaser/goreleaser-action@v2 - with: - version: latest - args: release - env: - GITHUB_TOKEN: ${{ secrets.GORELEASER_GITHUB_TOKEN }} - # 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. - - 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 }} - - name: install-website-dependencies - run: | - pip3 install mkdocs-material mkdocs-mermaid2-plugin mkdocs-redirects mkdocs-simple-hooks - - name: deploy-website - run: - ( cd assets/chezmoi.io && mkdocs build && mkdocs gh-deploy ) + - name: install-build-dependencies + run: | + sudo apt-get update + sudo apt-get -yq --no-install-suggests --no-install-recommends install musl-tools snapcraft + - uses: actions/setup-go@bfdd3570ce990073878bf10f6b2d79082de49492 # pin@v2 + with: + go-version: ${{ env.GO_VERSION }} + - uses: actions/checkout@dcd71f646680f2efd8db4afa5ad64fdcba30e748 # pin@v3 + with: + fetch-depth: 0 + - uses: actions/cache@136d96b4aee02b1f0de3ba493b1d47135042d9c0 # [email protected] + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go- + - name: snapcraft-login + env: + SNAPCRAFT_LOGIN: ${{ secrets.SNAPCRAFT_LOGIN }} + run: | + snapcraft login --with <(echo "$SNAPCRAFT_LOGIN" | base64 -d) + - uses: goreleaser/goreleaser-action@b953231f81b8dfd023c58e0854a721e35037f28b # pin@v2 + with: + version: latest + args: release + env: + GITHUB_TOKEN: ${{ secrets.GORELEASER_GITHUB_TOKEN }} + # 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. + - 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 }} + - name: install-website-dependencies + run: | + pip3 install mkdocs-material mkdocs-mermaid2-plugin mkdocs-redirects mkdocs-simple-hooks + - name: deploy-website + run: ( cd assets/chezmoi.io && mkdocs build && mkdocs gh-deploy ) diff --git a/.github/workflows/misspell.yml b/.github/workflows/misspell.yml index add44b44e43..803d0afbd57 100644 --- a/.github/workflows/misspell.yml +++ b/.github/workflows/misspell.yml @@ -3,18 +3,18 @@ name: misspell on: push: branches: - - master + - master tags: - - v* - pull_request: + - v* + pull_request: null jobs: misspell: name: spellcheck runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@dcd71f646680f2efd8db4afa5ad64fdcba30e748 # pin@v3 - name: misspell - uses: reviewdog/action-misspell@v1 + uses: reviewdog/action-misspell@3347037502cd60235723196fe0084fd1c11ff33a # pin@v1 with: locale: US
chore
Pin GitHub Actions hashes
9d37a455c692f2598d52f2e3e54da4706d815712
2022-02-21 08:28:44
Tom Payne
chore: Relax integration tests that rely on GitHub API
false
diff --git a/pkg/cmd/testdata/scripts/doctor_unix.txt b/pkg/cmd/testdata/scripts/doctor_unix.txt index fb259d4f1c9..93153569e4b 100644 --- a/pkg/cmd/testdata/scripts/doctor_unix.txt +++ b/pkg/cmd/testdata/scripts/doctor_unix.txt @@ -21,7 +21,7 @@ mksourcedir # test that chezmoi doctor behaves as expected chezmoi doctor stdout '^ok\s+version\s+' -stdout '^warning\s+latest-version\s+' +stdout '^\w+\s+latest-version\s+' stdout '^ok\s+os-arch\s+' ! stdout '^\S+\s+systeminfo\s+' stdout '^ok\s+uname\s+'
chore
Relax integration tests that rely on GitHub API
23de4476284bb694372eb378d4292a9ad33135f1
2024-12-07 22:47:23
mohamedhany01
fix: YAML parsing error by escaping `|` in `title`
false
diff --git a/assets/chezmoi.io/docs/links/videos.md.yaml b/assets/chezmoi.io/docs/links/videos.md.yaml index 234565d46c6..e5c55707ebf 100644 --- a/assets/chezmoi.io/docs/links/videos.md.yaml +++ b/assets/chezmoi.io/docs/links/videos.md.yaml @@ -60,5 +60,5 @@ videos: - date: '2024-11-18' version: 2.54.0 lang: AR - title: 'Chezmoi, Dotfiles, Workflow, Templates and Encryption | Arabic شرح' + title: 'Chezmoi, Dotfiles, Workflow, Templates and Encryption \| Arabic شرح' url: https://www.youtube.com/watch?v=Jrrd2dHYBmY
fix
YAML parsing error by escaping `|` in `title`
fee27fe1c0a0f9b65a7dae68f5d0d7831c673149
2022-01-26 08:10:10
Tom Payne
chore: Ignore more URLs in htmltest
false
diff --git a/assets/chezmoi.io/htmltest.yml b/assets/chezmoi.io/htmltest.yml index c0f127e7ab9..3f74b49adc3 100644 --- a/assets/chezmoi.io/htmltest.yml +++ b/assets/chezmoi.io/htmltest.yml @@ -14,7 +14,9 @@ IgnoreURLs: - https://johnmathews\.is/ - https://jonathanbartlett\.co\.uk/ - https://lastpass\.com/ +- https://seds\.nl/ - https://www\.jacobbolda\.com/ - https://www\.jx0\.uk/ - https://www\.vaultproject\.io/ - https://zacwe\.st/ +- https://zerokspot\.com/
chore
Ignore more URLs in htmltest
ef9e0ec57ec7590962554d57d2fa9793b2a7a285
2022-09-14 03:19:07
Tom Payne
chore: Sort checks in doctor command
false
diff --git a/pkg/cmd/doctorcmd.go b/pkg/cmd/doctorcmd.go index a41bf127ee2..142d686ddf3 100644 --- a/pkg/cmd/doctorcmd.go +++ b/pkg/cmd/doctorcmd.go @@ -209,17 +209,7 @@ func (c *Config) runDoctorCmd(cmd *cobra.Command, args []string) error { name: "dest-dir", dirname: c.DestDirAbsPath, }, - &binaryCheck{ - name: "shell-command", - binaryname: shellCommand, - ifNotSet: checkResultError, - ifNotExist: checkResultError, - }, - &argsCheck{ - name: "shell-args", - command: shellCommand, - args: shellArgs, - }, + umaskCheck{}, &binaryCheck{ name: "cd-command", binaryname: cdCommand, @@ -231,6 +221,12 @@ func (c *Config) runDoctorCmd(cmd *cobra.Command, args []string) error { command: cdCommand, args: cdArgs, }, + &binaryCheck{ + name: "diff-command", + binaryname: c.Diff.Command, + ifNotSet: checkResultInfo, + ifNotExist: checkResultWarning, + }, &binaryCheck{ name: "edit-command", binaryname: editCommand, @@ -242,13 +238,6 @@ func (c *Config) runDoctorCmd(cmd *cobra.Command, args []string) error { command: editCommand, args: editArgs, }, - &binaryCheck{ - name: "diff-command", - binaryname: c.Diff.Command, - ifNotSet: checkResultInfo, - ifNotExist: checkResultWarning, - }, - umaskCheck{}, &binaryCheck{ name: "git-command", binaryname: c.Git.Command, @@ -263,6 +252,17 @@ func (c *Config) runDoctorCmd(cmd *cobra.Command, args []string) error { ifNotSet: checkResultWarning, ifNotExist: checkResultWarning, }, + &binaryCheck{ + name: "shell-command", + binaryname: shellCommand, + ifNotSet: checkResultError, + ifNotExist: checkResultError, + }, + &argsCheck{ + name: "shell-args", + command: shellCommand, + args: shellArgs, + }, &binaryCheck{ name: "age-command", binaryname: c.Age.Command, @@ -320,6 +320,12 @@ func (c *Config) runDoctorCmd(cmd *cobra.Command, args []string) error { versionArgs: []string{"--version"}, versionRx: regexp.MustCompile(`^(\d+\.\d+\.\d+)`), }, + &fileCheck{ + name: "keepassxc-db", + filename: c.Keepassxc.Database, + ifNotSet: checkResultInfo, + ifNotExist: checkResultInfo, + }, &binaryCheck{ name: "keeper-command", binaryname: c.Keeper.Command, @@ -328,12 +334,6 @@ func (c *Config) runDoctorCmd(cmd *cobra.Command, args []string) error { versionArgs: []string{"version"}, versionRx: regexp.MustCompile(`^Commander\s+Version:\s+(\d+\.\d+\.\d+)`), }, - &fileCheck{ - name: "keepassxc-db", - filename: c.Keepassxc.Database, - ifNotSet: checkResultInfo, - ifNotExist: checkResultInfo, - }, &binaryCheck{ name: "lastpass-command", binaryname: c.Lastpass.Command,
chore
Sort checks in doctor command
543c6d1e0558b4726f67414657c7638230890363
2022-03-05 05:16:26
Tom Payne
chore: Build with Go 1.17.8
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index f2d01f81303..c701fe8a5fa 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.7 + GO_VERSION: 1.17.8 GOFUMPT_VERSION: 0.3.0 GOLANGCI_LINT_VERSION: 1.44.2 jobs:
chore
Build with Go 1.17.8
f16703eab137bf059f61684f5aa3aa0d9e89ae9e
2024-03-03 20:48:32
Tom Payne
chore: Fix permissions for deploy-website step
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 6c7c318f726..512c413abaf 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -440,7 +440,7 @@ jobs: - release runs-on: ubuntu-22.04 permissions: - contents: read + contents: write steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 with:
chore
Fix permissions for deploy-website step
4ebcb0b3ebe4fc75c20285d2db1e3e1661edd95b
2024-07-12 15:20:11
Tom Payne
chore: Update tools
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index fb155d69e7b..cd5b5bd8735 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -14,7 +14,7 @@ env: ACTIONLINT_VERSION: 1.7.1 # https://github.com/rhysd/actionlint/releases AGE_VERSION: 1.2.0 # https://github.com/FiloSottile/age/releases 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 + EDITORCONFIG_CHECKER_VERSION: 3.0.3 # 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.5 # https://go.dev/doc/devel/release GOFUMPT_VERSION: 0.6.0 # https://github.com/mvdan/gofumpt/releases
chore
Update tools
c136cd0324b46d311427eaf8ebff3d4532effbb1
2024-09-30 14:09:47
Tom Payne
chore: Update GitHub Actions
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 2446e938920..2ed7306d32b 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -284,7 +284,7 @@ jobs: - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 with: go-version: ${{ env.GO_VERSION }} - - uses: astral-sh/setup-uv@4cda7d73322c50eac316ad623a716f09a2db2ac7 + - uses: astral-sh/setup-uv@023eb7875fa1caa15814da58d1df7350f8fb1fd9 with: version: ${{ env.UV_VERSION }} - name: install-website-dependencies @@ -456,7 +456,7 @@ jobs: - uses: actions/setup-go@0a12ed9d6a96ab950c8f026ed9f722fe0da7ef32 with: go-version: ${{ env.GO_VERSION }} - - uses: astral-sh/setup-uv@4cda7d73322c50eac316ad623a716f09a2db2ac7 + - uses: astral-sh/setup-uv@023eb7875fa1caa15814da58d1df7350f8fb1fd9 with: version: ${{ env.UV_VERSION }} - name: prepare-chezmoi.io
chore
Update GitHub Actions
51de96fe98420bac769a3a5fedf1b839a3fa7623
2022-10-20 01:18:57
Tom Payne
feat: Make --include and --exclude flags behavior more consistent
false
diff --git a/assets/chezmoi.io/docs/reference/command-line-flags/common.md b/assets/chezmoi.io/docs/reference/command-line-flags/common.md index d097ab2c754..a32954c2fd7 100644 --- a/assets/chezmoi.io/docs/reference/command-line-flags/common.md +++ b/assets/chezmoi.io/docs/reference/command-line-flags/common.md @@ -8,15 +8,29 @@ Set the output format. ## `-i`, `--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/or source attributes (`encrypted`, `externals`, -`templates`) and can be excluded by preceding them with a `no`. +Include target state entries of type *types*. *types* is a comma-separated list +of types: + +| Type | Description | +| ----------- | --------------------- | +| `all` | All entries (default) | +| `none` | No entries | +| `dirs` | Directories | +| `files` | Files | +| `remove` | Removes | +| `scripts` | Scripts | +| `symlinks` | Symbolic links | +| `encrypted` | Encrypted entries | +| `externals` | External entries | +| `templates` | Templates | + +Types can be preceded with `no` to remove them. + +Types can be explicitly excluded with the `--exclude` flag. !!! example - `--include=dirs,files` will cause the command to apply to directories and - files only. + `--include=all,noencrypted` specifies all entries except encrypted files. ## `--init` @@ -33,9 +47,8 @@ Recurse into subdirectories, `true` by default. ## `-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/or source attributes (`encrypted`, `externals`, `templates`). +Exclude target state entries of type *types*. *types* is defined as in the +`--include` flag and defaults to `none`. !!! example diff --git a/pkg/chezmoi/dumpsystem_test.go b/pkg/chezmoi/dumpsystem_test.go index 532873c7a69..75b96f0abac 100644 --- a/pkg/chezmoi/dumpsystem_test.go +++ b/pkg/chezmoi/dumpsystem_test.go @@ -49,7 +49,7 @@ func TestDumpSystem(t *testing.T) { dumpSystem := NewDumpSystem() persistentState := NewMockPersistentState() require.NoError(t, s.applyAll(dumpSystem, system, persistentState, EmptyAbsPath, ApplyOptions{ - Include: NewEntryTypeSet(EntryTypesAll), + Filter: NewEntryTypeFilter(EntryTypesAll, EntryTypesNone), })) expectedData := map[string]any{ ".dir": &dirData{ diff --git a/pkg/chezmoi/entrytypefilter.go b/pkg/chezmoi/entrytypefilter.go new file mode 100644 index 00000000000..d8e85d98140 --- /dev/null +++ b/pkg/chezmoi/entrytypefilter.go @@ -0,0 +1,40 @@ +package chezmoi + +import "io/fs" + +// An EntryTypeFilter filters entries by type and source attributes. Any entry +// in the include set is included, otherwise if the entry is in the exclude set +// then it is excluded, otherwise it is included. +type EntryTypeFilter struct { + Include *EntryTypeSet + Exclude *EntryTypeSet +} + +// NewEntryTypeFilter returns a new EntryTypeFilter with the given entry type +// bits. +func NewEntryTypeFilter(includeEntryTypeBits, excludeEntryTypeBits EntryTypeBits) *EntryTypeFilter { + return &EntryTypeFilter{ + Include: NewEntryTypeSet(includeEntryTypeBits), + Exclude: NewEntryTypeSet(excludeEntryTypeBits), + } +} + +// IncludeEntryTypes returns if entryTypeBits is included. +func (f *EntryTypeFilter) IncludeEntryTypeBits(entryTypeBits EntryTypeBits) bool { + return f.Include.ContainsEntryTypeBits(entryTypeBits) && !f.Exclude.ContainsEntryTypeBits(entryTypeBits) +} + +// IncludeFileInfo returns if fileInfo is included. +func (f *EntryTypeFilter) IncludeFileInfo(fileInfo fs.FileInfo) bool { + return f.Include.ContainsFileInfo(fileInfo) && !f.Exclude.ContainsFileInfo(fileInfo) +} + +// IncludeSourceStateEntry returns if sourceStateEntry is included. +func (f *EntryTypeFilter) IncludeSourceStateEntry(sourceStateEntry SourceStateEntry) bool { + return f.Include.ContainsSourceStateEntry(sourceStateEntry) && !f.Exclude.ContainsSourceStateEntry(sourceStateEntry) +} + +// IncludeTargetStateEntry returns if targetStateEntry is included. +func (f *EntryTypeFilter) IncludeTargetStateEntry(targetStateEntry TargetStateEntry) bool { + return f.Include.ContainsTargetStateEntry(targetStateEntry) && !f.Exclude.ContainsTargetStateEntry(targetStateEntry) +} diff --git a/pkg/chezmoi/entrytypeset.go b/pkg/chezmoi/entrytypeset.go index 6e21064ff1a..b6bead6d3f6 100644 --- a/pkg/chezmoi/entrytypeset.go +++ b/pkg/chezmoi/entrytypeset.go @@ -90,28 +90,18 @@ func NewEntryTypeSet(bits EntryTypeBits) *EntryTypeSet { } } -// Include returns if s includes b. -func (s *EntryTypeSet) Include(b EntryTypeBits) bool { +// ContainsEntryTypeBits returns if s includes b. +func (s *EntryTypeSet) ContainsEntryTypeBits(b EntryTypeBits) bool { return s.bits&b != 0 } -// IncludeEncrypted returns true if s includes encrypted files. -func (s *EntryTypeSet) IncludeEncrypted() bool { - return s.bits&EntryTypeEncrypted != 0 +// Bits returns s's bits. +func (s *EntryTypeSet) Bits() EntryTypeBits { + return s.bits } -// IncludeExternals returns true if s includes externals files. -func (s *EntryTypeSet) IncludeExternals() bool { - return s.bits&EntryTypeExternals != 0 -} - -// IncludeTemplates returns true if s includes templates. -func (s *EntryTypeSet) IncludeTemplates() bool { - return s.bits&EntryTypeTemplates != 0 -} - -// IncludeFileInfo returns true if the type of fileInfo is a member. -func (s *EntryTypeSet) IncludeFileInfo(fileInfo fs.FileInfo) bool { +// ContainsFileInfo returns true if fileInfo is a member. +func (s *EntryTypeSet) ContainsFileInfo(fileInfo fs.FileInfo) bool { switch { case fileInfo.IsDir(): return s.bits&EntryTypeDirs != 0 @@ -124,32 +114,129 @@ func (s *EntryTypeSet) IncludeFileInfo(fileInfo fs.FileInfo) bool { } } -// IncludeTargetStateEntry returns true if type of targetStateEntry is a member. -func (s *EntryTypeSet) IncludeTargetStateEntry(targetStateEntry TargetStateEntry) bool { - switch sourceAttr := targetStateEntry.SourceAttr(); { - case s.IncludeEncrypted() && sourceAttr.Encrypted: - return true - case s.IncludeExternals() && sourceAttr.External: - return true - case s.IncludeTemplates() && sourceAttr.Template: - return true +// ContainsSourceStateEntry returns true if sourceStateEntry is a member. +func (s *EntryTypeSet) ContainsSourceStateEntry(sourceStateEntry SourceStateEntry) bool { + switch sourceStateEntry := sourceStateEntry.(type) { + case *SourceStateCommand: + switch { + case s.bits&EntryTypeDirs != 0: + return true + case s.bits&EntryTypeExternals != 0 && !sourceStateEntry.origin.Path().Empty(): + return true + default: + return false + } + case *SourceStateDir: + switch { + case s.bits&EntryTypeDirs != 0: + return true + case s.bits&EntryTypeExternals != 0 && !sourceStateEntry.origin.Path().Empty(): + return true + default: + return false + } + case *SourceStateFile: + switch sourceAttr := sourceStateEntry.Attr; { + case s.bits&EntryTypeFiles != 0 && sourceAttr.Type == SourceFileTypeCreate: + return true + case s.bits&EntryTypeFiles != 0 && sourceAttr.Type == SourceFileTypeFile: + return true + case s.bits&EntryTypeFiles != 0 && sourceAttr.Type == SourceFileTypeModify: + return true + case s.bits&EntryTypeRemove != 0 && sourceAttr.Type == SourceFileTypeRemove: + return true + case s.bits&EntryTypeScripts != 0 && sourceAttr.Type == SourceFileTypeScript: + return true + case s.bits&EntryTypeSymlinks != 0 && sourceAttr.Type == SourceFileTypeSymlink: + return true + case s.bits&EntryTypeEncrypted != 0 && sourceAttr.Encrypted: + return true + case s.bits&EntryTypeExternals != 0 && !sourceStateEntry.origin.Path().Empty(): + return true + case s.bits&EntryTypeTemplates != 0 && sourceAttr.Template: + return true + default: + return false + } + case *SourceStateRemove: + switch { + case s.bits&EntryTypeRemove != 0: + return true + case s.bits&EntryTypeExternals != 0 && !sourceStateEntry.origin.Path().Empty(): + return true + default: + return false + } + default: + panic(fmt.Sprintf("%T: unsupported type", sourceStateEntry)) } +} +// ContainsTargetStateEntry returns true if targetStateEntry is a member. +func (s *EntryTypeSet) ContainsTargetStateEntry(targetStateEntry TargetStateEntry) bool { + sourceAttr := targetStateEntry.SourceAttr() switch targetStateEntry.(type) { case *TargetStateDir: - return s.bits&EntryTypeDirs != 0 + switch { + case s.bits&EntryTypeDirs != 0: + return true + case s.bits&EntryTypeEncrypted != 0 && sourceAttr.Encrypted: + return true + case s.bits&EntryTypeExternals != 0 && sourceAttr.External: + return true + default: + return false + } case *TargetStateFile: - return s.bits&EntryTypeFiles != 0 + switch { + case s.bits&EntryTypeFiles != 0: + return true + case s.bits&EntryTypeEncrypted != 0 && sourceAttr.Encrypted: + return true + case s.bits&EntryTypeExternals != 0 && sourceAttr.External: + return true + case s.bits&EntryTypeTemplates != 0 && sourceAttr.Template: + return true + default: + return false + } case *TargetStateModifyDirWithCmd: - return s.bits&EntryTypeDirs != 0 + switch { + case s.bits&EntryTypeDirs != 0: + return true + case s.bits&EntryTypeExternals != 0 && sourceAttr.External: + return true + default: + return false + } case *TargetStateRemove: return s.bits&EntryTypeRemove != 0 case *TargetStateScript: - return s.bits&EntryTypeScripts != 0 + switch { + case s.bits&EntryTypeScripts != 0: + return true + case s.bits&EntryTypeEncrypted != 0 && sourceAttr.Encrypted: + return true + case s.bits&EntryTypeTemplates != 0 && sourceAttr.Template: + return true + default: + return false + } case *TargetStateSymlink: - return s.bits&EntryTypeSymlinks != 0 + switch { + case s.bits&EntryTypeSymlinks != 0: + return true + case s.bits&EntryTypeEncrypted != 0 && sourceAttr.Encrypted: + return true + case s.bits&EntryTypeExternals != 0 && sourceAttr.External: + return true + case s.bits&EntryTypeTemplates != 0 && sourceAttr.Template: + return true + default: + return false + } default: - return false + panic(fmt.Sprintf("%T: unsupported type", targetStateEntry)) } } @@ -212,16 +299,6 @@ func (s *EntryTypeSet) String() string { return strings.Join(entryTypeStrs, ",") } -// Sub returns a copy of s with the elements of other removed. -func (s *EntryTypeSet) Sub(other *EntryTypeSet) *EntryTypeSet { - if other == nil { - return s - } - return &EntryTypeSet{ - bits: (s.bits &^ other.bits) & EntryTypesAll, - } -} - // Type implements github.com/spf13/pflag.Value.Type. func (s *EntryTypeSet) Type() string { return "types" diff --git a/pkg/chezmoi/entrytypeset_test.go b/pkg/chezmoi/entrytypeset_test.go index b29c512e50c..53c5330ec7b 100644 --- a/pkg/chezmoi/entrytypeset_test.go +++ b/pkg/chezmoi/entrytypeset_test.go @@ -32,7 +32,7 @@ func TestIncludeMaskSet(t *testing.T) { }, { s: "all,noscripts", - expected: NewEntryTypeSet(EntryTypeDirs | EntryTypeFiles | EntryTypeRemove | EntryTypeSymlinks | EntryTypeEncrypted | EntryTypeExternals | EntryTypeTemplates), + expected: NewEntryTypeSet(EntryTypesAll &^ EntryTypeScripts), }, { s: "noscripts", @@ -134,6 +134,12 @@ func TestEntryTypeSetFlagCompletionFunc(t *testing.T) { "externals", }, }, + { + toComplete: "t", + expectedCompletions: []string{ + "templates", + }, + }, { toComplete: "all,nos", expectedCompletions: []string{ diff --git a/pkg/chezmoi/externaldiffsystem.go b/pkg/chezmoi/externaldiffsystem.go index 5a5d8ab5748..b946c220505 100644 --- a/pkg/chezmoi/externaldiffsystem.go +++ b/pkg/chezmoi/externaldiffsystem.go @@ -24,13 +24,13 @@ type ExternalDiffSystem struct { args []string destDirAbsPath AbsPath tempDirAbsPath AbsPath - include *EntryTypeSet + filter *EntryTypeFilter reverse bool } // ExternalDiffSystemOptions are options for NewExternalDiffSystem. type ExternalDiffSystemOptions struct { - Include *EntryTypeSet + Filter *EntryTypeFilter Reverse bool } @@ -43,7 +43,7 @@ func NewExternalDiffSystem( command: command, args: args, destDirAbsPath: destDirAbsPath, - include: options.Include, + filter: options.Filter, reverse: options.Reverse, } } @@ -88,7 +88,7 @@ func (s *ExternalDiffSystem) Lstat(name AbsPath) (fs.FileInfo, error) { // Mkdir implements System.Mkdir. func (s *ExternalDiffSystem) Mkdir(name AbsPath, perm fs.FileMode) error { - if s.include.Include(EntryTypeDirs) { + if s.filter.IncludeEntryTypeBits(EntryTypeDirs) { targetRelPath, err := name.TrimDirPrefix(s.destDirAbsPath) if err != nil { return err @@ -130,7 +130,7 @@ func (s *ExternalDiffSystem) Readlink(name AbsPath) (string, error) { // Remove implements System.Remove. func (s *ExternalDiffSystem) Remove(name AbsPath) error { - if s.include.Include(EntryTypeRemove) { + if s.filter.IncludeEntryTypeBits(EntryTypeRemove) { if err := s.runDiffCommand(name, devNullAbsPath); err != nil { return err } @@ -140,7 +140,7 @@ func (s *ExternalDiffSystem) Remove(name AbsPath) error { // RemoveAll implements System.RemoveAll. func (s *ExternalDiffSystem) RemoveAll(name AbsPath) error { - if s.include.Include(EntryTypeRemove) { + if s.filter.IncludeEntryTypeBits(EntryTypeRemove) { if err := s.runDiffCommand(name, devNullAbsPath); err != nil { return err } @@ -161,7 +161,7 @@ func (s *ExternalDiffSystem) RunCmd(cmd *exec.Cmd) error { // RunScript implements System.RunScript. func (s *ExternalDiffSystem) RunScript(scriptname RelPath, dir AbsPath, data []byte, interpreter *Interpreter) error { - if s.include.Include(EntryTypeScripts) { + if s.filter.IncludeEntryTypeBits(EntryTypeScripts) { tempDirAbsPath, err := s.tempDir() if err != nil { return err @@ -192,7 +192,7 @@ func (s *ExternalDiffSystem) UnderlyingFS() vfs.FS { // WriteFile implements System.WriteFile. func (s *ExternalDiffSystem) WriteFile(filename AbsPath, data []byte, perm fs.FileMode) error { - if s.include.Include(EntryTypeFiles) { + if s.filter.IncludeEntryTypeBits(EntryTypeFiles) { // If filename does not exist, replace it with /dev/null to avoid // passing the name of a non-existent file to the external diff command. destAbsPath := filename diff --git a/pkg/chezmoi/gitdiffsystem.go b/pkg/chezmoi/gitdiffsystem.go index 38cfcc8cb07..ca9c75163f7 100644 --- a/pkg/chezmoi/gitdiffsystem.go +++ b/pkg/chezmoi/gitdiffsystem.go @@ -22,7 +22,7 @@ type TextConvFunc func(string, []byte) ([]byte, error) type GitDiffSystem struct { system System dirAbsPath AbsPath - include *EntryTypeSet + filter *EntryTypeFilter reverse bool textConvFunc TextConvFunc unifiedEncoder *diff.UnifiedEncoder @@ -31,7 +31,7 @@ type GitDiffSystem struct { // GetDiffSystemOptions are options for NewGitDiffSystem. type GitDiffSystemOptions struct { Color bool - Include *EntryTypeSet + Filter *EntryTypeFilter Reverse bool TextConvFunc TextConvFunc } @@ -47,7 +47,7 @@ func NewGitDiffSystem(system System, w io.Writer, dirAbsPath AbsPath, options *G return &GitDiffSystem{ system: system, dirAbsPath: dirAbsPath, - include: options.Include, + filter: options.Filter, reverse: options.Reverse, textConvFunc: options.TextConvFunc, unifiedEncoder: unifiedEncoder, @@ -60,7 +60,7 @@ func (s *GitDiffSystem) Chmod(name AbsPath, mode fs.FileMode) error { if err != nil { return err } - if s.include.IncludeFileInfo(fromInfo) { + if s.filter.IncludeFileInfo(fromInfo) { toMode := fromInfo.Mode().Type() | mode var toData []byte if fromInfo.Mode().IsRegular() { @@ -99,7 +99,7 @@ func (s *GitDiffSystem) Lstat(name AbsPath) (fs.FileInfo, error) { // Mkdir implements System.Mkdir. func (s *GitDiffSystem) Mkdir(name AbsPath, perm fs.FileMode) error { - if s.include.Include(EntryTypeDirs) { + if s.filter.IncludeEntryTypeBits(EntryTypeDirs) { if err := s.encodeDiff(name, nil, fs.ModeDir|perm); err != nil { return err } @@ -137,7 +137,7 @@ func (s *GitDiffSystem) Remove(name AbsPath) error { // RemoveAll implements System.RemoveAll. func (s *GitDiffSystem) RemoveAll(name AbsPath) error { - if s.include.Include(EntryTypeRemove) { + if s.filter.IncludeEntryTypeBits(EntryTypeRemove) { if err := s.encodeDiff(name, nil, 0); err != nil { return err } @@ -151,7 +151,7 @@ func (s *GitDiffSystem) Rename(oldpath, newpath AbsPath) error { if err != nil { return err } - if s.include.IncludeFileInfo(fromFileInfo) { + if s.filter.IncludeFileInfo(fromFileInfo) { var fileMode filemode.FileMode var hash plumbing.Hash switch { @@ -199,7 +199,7 @@ func (s *GitDiffSystem) RunCmd(cmd *exec.Cmd) error { // RunScript implements System.RunScript. func (s *GitDiffSystem) RunScript(scriptname RelPath, dir AbsPath, data []byte, interpreter *Interpreter) error { - if s.include.Include(EntryTypeScripts) { + if s.filter.IncludeEntryTypeBits(EntryTypeScripts) { mode := fs.FileMode(filemode.Executable) fromData, toData := []byte(nil), data if s.reverse { @@ -228,7 +228,7 @@ func (s *GitDiffSystem) UnderlyingFS() vfs.FS { // WriteFile implements System.WriteFile. func (s *GitDiffSystem) WriteFile(filename AbsPath, data []byte, perm fs.FileMode) error { - if s.include.Include(EntryTypeFiles) { + if s.filter.IncludeEntryTypeBits(EntryTypeFiles) { if err := s.encodeDiff(filename, data, perm); err != nil { return err } @@ -238,7 +238,7 @@ func (s *GitDiffSystem) WriteFile(filename AbsPath, data []byte, perm fs.FileMod // WriteSymlink implements System.WriteSymlink. func (s *GitDiffSystem) WriteSymlink(oldname string, newname AbsPath) error { - if s.include.Include(EntryTypeSymlinks) { + if s.filter.IncludeEntryTypeBits(EntryTypeSymlinks) { toData := append([]byte(normalizeLinkname(oldname)), '\n') toMode := fs.ModeSymlink if runtime.GOOS == "windows" { diff --git a/pkg/chezmoi/sourcestate.go b/pkg/chezmoi/sourcestate.go index a8bfd7bec33..f9518dbd1c6 100644 --- a/pkg/chezmoi/sourcestate.go +++ b/pkg/chezmoi/sourcestate.go @@ -272,17 +272,17 @@ type ReplaceFunc func(targetRelPath RelPath, newSourceStateEntry, oldSourceState // AddOptions are options to SourceState.Add. type AddOptions struct { - AutoTemplate bool // Automatically create templates, if possible. - Create bool // Add create_ entries instead of normal entries. - Encrypt bool // Encrypt files. - EncryptedSuffix string // Suffix for encrypted files. - Exact bool // Add the exact_ attribute to added directories. - Include *EntryTypeSet // Only add types in this set. - PreAddFunc PreAddFunc // Function to be called before a source entry is added. - RemoveDir RelPath // Directory to remove before adding. - ReplaceFunc ReplaceFunc // Function to be called before a source entry is replaced. - Template bool // Add the .tmpl attribute to added files. - TemplateSymlinks bool // Add symlinks with targets in the source or home directories as templates. + AutoTemplate bool // Automatically create templates, if possible. + Create bool // Add create_ entries instead of normal entries. + Encrypt bool // Encrypt files. + EncryptedSuffix string // Suffix for encrypted files. + Exact bool // Add the exact_ attribute to added directories. + Filter *EntryTypeFilter // Entry type filter. + PreAddFunc PreAddFunc // Function to be called before a source entry is added. + RemoveDir RelPath // Directory to remove before adding. + ReplaceFunc ReplaceFunc // Function to be called before a source entry is replaced. + Template bool // Add the .tmpl attribute to added files. + TemplateSymlinks bool // Add symlinks with targets in the source or home directories as templates. } // Add adds destAbsPathInfos to s. @@ -307,7 +307,7 @@ func (s *SourceState) Add( DESTABSPATH: for _, destAbsPath := range destAbsPaths { destAbsPathInfo := destAbsPathInfos[destAbsPath] - if !options.Include.IncludeFileInfo(destAbsPathInfo) { + if !options.Filter.IncludeFileInfo(destAbsPathInfo) { continue } targetRelPath := destAbsPath.MustTrimDirPrefix(s.destDirAbsPath) @@ -472,8 +472,8 @@ DESTABSPATH: err := targetSourceState.Apply( sourceSystem, sourceSystem, NullPersistentState{}, s.sourceDirAbsPath, sourceRelPath.RelPath(), ApplyOptions{ - Include: options.Include, - Umask: s.umask, + Filter: options.Filter, + Umask: s.umask, }, ) if err != nil { @@ -553,7 +553,7 @@ type PreApplyFunc func( // ApplyOptions are options to SourceState.ApplyAll and SourceState.ApplyOne. type ApplyOptions struct { - Include *EntryTypeSet + Filter *EntryTypeFilter PreApplyFunc PreApplyFunc Umask fs.FileMode } @@ -565,16 +565,8 @@ func (s *SourceState) Apply( ) error { sourceStateEntry := s.root.Get(targetRelPath) - if !options.Include.IncludeEncrypted() { - if sourceStateFile, ok := sourceStateEntry.(*SourceStateFile); ok && sourceStateFile.Attr.Encrypted { - return nil - } - } - - if !options.Include.IncludeExternals() { - if _, ok := sourceStateEntry.Origin().(*External); ok { - return nil - } + if !options.Filter.IncludeSourceStateEntry(sourceStateEntry) { + return nil } destAbsPath := s.destDirAbsPath.Join(targetRelPath) @@ -583,7 +575,7 @@ func (s *SourceState) Apply( return err } - if options.Include != nil && !options.Include.IncludeTargetStateEntry(targetStateEntry) { + if !options.Filter.IncludeTargetStateEntry(targetStateEntry) { return nil } diff --git a/pkg/chezmoi/sourcestate_test.go b/pkg/chezmoi/sourcestate_test.go index f9ab8cc078e..f765d83f218 100644 --- a/pkg/chezmoi/sourcestate_test.go +++ b/pkg/chezmoi/sourcestate_test.go @@ -37,7 +37,7 @@ func TestSourceStateAdd(t *testing.T) { NewAbsPath("/home/user/.dir"), }, addOptions: AddOptions{ - Include: NewEntryTypeSet(EntryTypesAll), + Filter: NewEntryTypeFilter(EntryTypesAll, EntryTypesNone), }, tests: []any{ vfst.TestPath("/home/user/.local/share/chezmoi/dot_dir", @@ -58,7 +58,7 @@ func TestSourceStateAdd(t *testing.T) { NewAbsPath("/home/user/.dir"), }, addOptions: AddOptions{ - Include: NewEntryTypeSet(EntryTypesAll), + Filter: NewEntryTypeFilter(EntryTypesAll, EntryTypesNone), }, extraRoot: map[string]any{ "/home/user": map[string]any{ @@ -86,7 +86,7 @@ func TestSourceStateAdd(t *testing.T) { NewAbsPath("/home/user/.dir/file"), }, addOptions: AddOptions{ - Include: NewEntryTypeSet(EntryTypesAll), + Filter: NewEntryTypeFilter(EntryTypesAll, EntryTypesNone), }, tests: []any{ vfst.TestPath("/home/user/.local/share/chezmoi/dot_dir", @@ -106,7 +106,7 @@ func TestSourceStateAdd(t *testing.T) { NewAbsPath("/home/user/.dir/file"), }, addOptions: AddOptions{ - Include: NewEntryTypeSet(EntryTypesAll), + Filter: NewEntryTypeFilter(EntryTypesAll, EntryTypesNone), }, extraRoot: map[string]any{ "/home/user/.local/share/chezmoi/dot_dir": &vfst.Dir{Perm: 0o777}, @@ -124,7 +124,7 @@ func TestSourceStateAdd(t *testing.T) { NewAbsPath("/home/user/.dir/subdir"), }, addOptions: AddOptions{ - Include: NewEntryTypeSet(EntryTypesAll), + Filter: NewEntryTypeFilter(EntryTypesAll, EntryTypesNone), }, tests: []any{ vfst.TestPath("/home/user/.local/share/chezmoi/dot_dir", @@ -146,7 +146,7 @@ func TestSourceStateAdd(t *testing.T) { NewAbsPath("/home/user/.dir/subdir/file"), }, addOptions: AddOptions{ - Include: NewEntryTypeSet(EntryTypesAll), + Filter: NewEntryTypeFilter(EntryTypesAll, EntryTypesNone), }, tests: []any{ vfst.TestPath("/home/user/.local/share/chezmoi/dot_dir", @@ -173,7 +173,7 @@ func TestSourceStateAdd(t *testing.T) { NewAbsPath("/home/user/.dir/subdir/file"), }, addOptions: AddOptions{ - Include: NewEntryTypeSet(EntryTypesAll), + Filter: NewEntryTypeFilter(EntryTypesAll, EntryTypesNone), }, extraRoot: map[string]any{ "/home/user/.local/share/chezmoi/dot_dir/subdir": &vfst.Dir{Perm: 0o777}, @@ -191,7 +191,7 @@ func TestSourceStateAdd(t *testing.T) { NewAbsPath("/home/user/.readonly_dir"), }, addOptions: AddOptions{ - Include: NewEntryTypeSet(EntryTypesAll), + Filter: NewEntryTypeFilter(EntryTypesAll, EntryTypesNone), }, extraRoot: map[string]any{ "/home/user/.readonly_dir": &vfst.Dir{Perm: 0o555}, @@ -209,7 +209,7 @@ func TestSourceStateAdd(t *testing.T) { NewAbsPath("/home/user/.empty"), }, addOptions: AddOptions{ - Include: NewEntryTypeSet(EntryTypesAll), + Filter: NewEntryTypeFilter(EntryTypesAll, EntryTypesNone), }, tests: []any{ vfst.TestPath("/home/user/.local/share/chezmoi/dot_empty", @@ -223,7 +223,7 @@ func TestSourceStateAdd(t *testing.T) { NewAbsPath("/home/user/.empty"), }, addOptions: AddOptions{ - Include: NewEntryTypeSet(EntryTypesAll), + Filter: NewEntryTypeFilter(EntryTypesAll, EntryTypesNone), }, tests: []any{ vfst.TestPath("/home/user/.local/share/chezmoi/empty_dot_empty", @@ -239,7 +239,7 @@ func TestSourceStateAdd(t *testing.T) { NewAbsPath("/home/user/.executable"), }, addOptions: AddOptions{ - Include: NewEntryTypeSet(EntryTypesAll), + Filter: NewEntryTypeFilter(EntryTypesAll, EntryTypesNone), }, tests: []any{ vfst.TestPath("/home/user/.local/share/chezmoi/executable_dot_executable", @@ -255,7 +255,7 @@ func TestSourceStateAdd(t *testing.T) { NewAbsPath("/home/user/.executable"), }, addOptions: AddOptions{ - Include: NewEntryTypeSet(EntryTypesAll), + Filter: NewEntryTypeFilter(EntryTypesAll, EntryTypesNone), }, tests: []any{ vfst.TestPath("/home/user/.local/share/chezmoi/dot_executable", @@ -271,8 +271,8 @@ func TestSourceStateAdd(t *testing.T) { NewAbsPath("/home/user/.create"), }, addOptions: AddOptions{ - Create: true, - Include: NewEntryTypeSet(EntryTypesAll), + Create: true, + Filter: NewEntryTypeFilter(EntryTypesAll, EntryTypesNone), }, tests: []any{ vfst.TestPath("/home/user/.local/share/chezmoi/create_dot_create", @@ -288,7 +288,7 @@ func TestSourceStateAdd(t *testing.T) { NewAbsPath("/home/user/.file"), }, addOptions: AddOptions{ - Include: NewEntryTypeSet(EntryTypesAll), + Filter: NewEntryTypeFilter(EntryTypesAll, EntryTypesNone), }, tests: []any{ vfst.TestPath("/home/user/.local/share/chezmoi/dot_file", @@ -304,7 +304,7 @@ func TestSourceStateAdd(t *testing.T) { NewAbsPath("/home/user/.file"), }, addOptions: AddOptions{ - Include: NewEntryTypeSet(EntryTypesAll), + Filter: NewEntryTypeFilter(EntryTypesAll, EntryTypesNone), }, extraRoot: map[string]any{ "/home/user/.local/share/chezmoi/executable_dot_file": "# contents of .file\n", @@ -326,7 +326,7 @@ func TestSourceStateAdd(t *testing.T) { NewAbsPath("/home/user/.file"), }, addOptions: AddOptions{ - Include: NewEntryTypeSet(EntryTypesAll), + Filter: NewEntryTypeFilter(EntryTypesAll, EntryTypesNone), }, extraRoot: map[string]any{ "/home/user/.local/share/chezmoi/dot_file": "# old contents of .file\n", @@ -345,7 +345,7 @@ func TestSourceStateAdd(t *testing.T) { NewAbsPath("/home/user/.private"), }, addOptions: AddOptions{ - Include: NewEntryTypeSet(EntryTypesAll), + Filter: NewEntryTypeFilter(EntryTypesAll, EntryTypesNone), }, tests: []any{ vfst.TestPath("/home/user/.local/share/chezmoi/private_dot_private", @@ -361,7 +361,7 @@ func TestSourceStateAdd(t *testing.T) { NewAbsPath("/home/user/.private"), }, addOptions: AddOptions{ - Include: NewEntryTypeSet(EntryTypesAll), + Filter: NewEntryTypeFilter(EntryTypesAll, EntryTypesNone), }, tests: []any{ vfst.TestPath("/home/user/.local/share/chezmoi/dot_private", @@ -377,7 +377,7 @@ func TestSourceStateAdd(t *testing.T) { NewAbsPath("/home/user/.readonly"), }, addOptions: AddOptions{ - Include: NewEntryTypeSet(EntryTypesAll), + Filter: NewEntryTypeFilter(EntryTypesAll, EntryTypesNone), }, extraRoot: map[string]any{ "/home/user/.readonly": &vfst.File{ @@ -399,7 +399,7 @@ func TestSourceStateAdd(t *testing.T) { NewAbsPath("/home/user/.symlink"), }, addOptions: AddOptions{ - Include: NewEntryTypeSet(EntryTypesAll), + Filter: NewEntryTypeFilter(EntryTypesAll, EntryTypesNone), }, tests: []any{ vfst.TestPath("/home/user/.local/share/chezmoi/symlink_dot_symlink", @@ -414,7 +414,7 @@ func TestSourceStateAdd(t *testing.T) { NewAbsPath("/home/user/.symlink_windows"), }, addOptions: AddOptions{ - Include: NewEntryTypeSet(EntryTypesAll), + Filter: NewEntryTypeFilter(EntryTypesAll, EntryTypesNone), }, extraRoot: map[string]any{ "/home/user": map[string]any{ @@ -435,7 +435,7 @@ func TestSourceStateAdd(t *testing.T) { }, addOptions: AddOptions{ AutoTemplate: true, - Include: NewEntryTypeSet(EntryTypesAll), + Filter: NewEntryTypeFilter(EntryTypesAll, EntryTypesNone), }, tests: []any{ vfst.TestPath("/home/user/.local/share/chezmoi/dot_template.tmpl", @@ -452,7 +452,7 @@ func TestSourceStateAdd(t *testing.T) { NewAbsPath("/home/user/.dir/file"), }, addOptions: AddOptions{ - Include: NewEntryTypeSet(EntryTypesAll), + Filter: NewEntryTypeFilter(EntryTypesAll, EntryTypesNone), }, tests: []any{ vfst.TestPath("/home/user/.local/share/chezmoi/dot_dir", @@ -472,7 +472,7 @@ func TestSourceStateAdd(t *testing.T) { NewAbsPath("/home/user/.dir/subdir/file"), }, addOptions: AddOptions{ - Include: NewEntryTypeSet(EntryTypesAll), + Filter: NewEntryTypeFilter(EntryTypesAll, EntryTypesNone), }, extraRoot: map[string]any{ "/home/user/.local/share/chezmoi/dot_dir/exact_subdir": &vfst.Dir{Perm: 0o777}, @@ -596,7 +596,7 @@ func TestSourceStateAddInExternal(t *testing.T) { destAbsPath: fileInfo, } require.NoError(t, s.Add(system, persistentState, system, destAbsPathInfos, &AddOptions{ - Include: NewEntryTypeSet(EntryTypesAll), + Filter: NewEntryTypeFilter(EntryTypesAll, EntryTypesNone), })) vfst.RunTests(t, fileSystem, "", @@ -822,8 +822,8 @@ func TestSourceStateApplyAll(t *testing.T) { require.NoError(t, s.Read(ctx, nil)) requireEvaluateAll(t, s, system) require.NoError(t, s.applyAll(system, system, persistentState, NewAbsPath("/home/user"), ApplyOptions{ - Include: NewEntryTypeSet(EntryTypesAll), - Umask: chezmoitest.Umask, + Filter: NewEntryTypeFilter(EntryTypesAll, EntryTypesNone), + Umask: chezmoitest.Umask, })) vfst.RunTests(t, fileSystem, "", tc.tests...) diff --git a/pkg/chezmoi/tarwritersystem_test.go b/pkg/chezmoi/tarwritersystem_test.go index 42d9ab208f0..6656d2ae467 100644 --- a/pkg/chezmoi/tarwritersystem_test.go +++ b/pkg/chezmoi/tarwritersystem_test.go @@ -53,7 +53,7 @@ func TestTarWriterSystem(t *testing.T) { tarWriterSystem := NewTarWriterSystem(b, tar.Header{}) persistentState := NewMockPersistentState() require.NoError(t, s.applyAll(tarWriterSystem, system, persistentState, EmptyAbsPath, ApplyOptions{ - Include: NewEntryTypeSet(EntryTypesAll), + Filter: NewEntryTypeFilter(EntryTypesAll, EntryTypesNone), })) require.NoError(t, tarWriterSystem.Close()) diff --git a/pkg/chezmoi/zipwritersystem_test.go b/pkg/chezmoi/zipwritersystem_test.go index a2e68a67529..ad968ac5f4d 100644 --- a/pkg/chezmoi/zipwritersystem_test.go +++ b/pkg/chezmoi/zipwritersystem_test.go @@ -55,7 +55,7 @@ func TestZIPWriterSystem(t *testing.T) { zipWriterSystem := NewZIPWriterSystem(b, time.Now().UTC()) persistentState := NewMockPersistentState() require.NoError(t, s.applyAll(zipWriterSystem, system, persistentState, EmptyAbsPath, ApplyOptions{ - Include: NewEntryTypeSet(EntryTypesAll), + Filter: NewEntryTypeFilter(EntryTypesAll, EntryTypesNone), })) require.NoError(t, zipWriterSystem.Close()) diff --git a/pkg/cmd/addcmd.go b/pkg/cmd/addcmd.go index d9e4d42f876..94d0ba12371 100644 --- a/pkg/cmd/addcmd.go +++ b/pkg/cmd/addcmd.go @@ -14,9 +14,8 @@ type addCmdConfig struct { create bool encrypt bool exact bool - exclude *chezmoi.EntryTypeSet + filter *chezmoi.EntryTypeFilter follow bool - include *chezmoi.EntryTypeSet prompt bool recursive bool template bool @@ -44,9 +43,9 @@ 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.BoolVar(&c.Add.encrypt, "encrypt", c.Add.encrypt, "Encrypt files") flags.BoolVar(&c.Add.exact, "exact", c.Add.exact, "Add directories exactly") - flags.VarP(c.Add.exclude, "exclude", "x", "Exclude entry types") + flags.VarP(c.Add.filter.Exclude, "exclude", "x", "Exclude entry types") flags.BoolVarP(&c.Add.follow, "follow", "f", c.Add.follow, "Add symlink targets instead of symlinks") - flags.VarP(c.Add.include, "include", "i", "Include entry types") + flags.VarP(c.Add.filter.Include, "include", "i", "Include entry types") flags.BoolVarP(&c.Add.prompt, "prompt", "p", c.Add.prompt, "Prompt before adding each entry") flags.BoolVarP(&c.Add.recursive, "recursive", "r", c.Add.recursive, "Recurse into subdirectories") flags.BoolVarP(&c.Add.template, "template", "T", c.Add.template, "Add files as templates") @@ -147,7 +146,7 @@ func (c *Config) runAddCmd(cmd *cobra.Command, args []string, sourceState *chezm Encrypt: c.Add.encrypt, EncryptedSuffix: c.encryption.EncryptedSuffix(), Exact: c.Add.exact, - Include: c.Add.include.Sub(c.Add.exclude), + Filter: c.Add.filter, PreAddFunc: c.defaultPreAddFunc, ReplaceFunc: c.defaultReplaceFunc, Template: c.Add.template, diff --git a/pkg/cmd/applycmd.go b/pkg/cmd/applycmd.go index 9b734578f46..412febefd56 100644 --- a/pkg/cmd/applycmd.go +++ b/pkg/cmd/applycmd.go @@ -7,9 +7,8 @@ import ( ) type applyCmdConfig struct { - exclude *chezmoi.EntryTypeSet + filter *chezmoi.EntryTypeFilter init bool - include *chezmoi.EntryTypeSet recursive bool } @@ -29,8 +28,8 @@ func (c *Config) newApplyCmd() *cobra.Command { } flags := applyCmd.Flags() - flags.VarP(c.apply.exclude, "exclude", "x", "Exclude entry types") - flags.VarP(c.apply.include, "include", "i", "Include entry types") + flags.VarP(c.apply.filter.Exclude, "exclude", "x", "Exclude entry types") + flags.VarP(c.apply.filter.Include, "include", "i", "Include entry types") flags.BoolVar(&c.apply.init, "init", c.update.init, "Recreate config file from template") flags.BoolVarP(&c.apply.recursive, "recursive", "r", c.apply.recursive, "Recurse into subdirectories") @@ -41,7 +40,7 @@ func (c *Config) newApplyCmd() *cobra.Command { func (c *Config) runApplyCmd(cmd *cobra.Command, args []string) error { return c.applyArgs(cmd.Context(), c.destSystem, c.DestDirAbsPath, args, applyArgsOptions{ - include: c.apply.include.Sub(c.apply.exclude), + filter: c.apply.filter, init: c.apply.init, recursive: c.apply.recursive, umask: c.Umask, diff --git a/pkg/cmd/archivecmd.go b/pkg/cmd/archivecmd.go index 960a59229b6..70f20249b7f 100644 --- a/pkg/cmd/archivecmd.go +++ b/pkg/cmd/archivecmd.go @@ -14,10 +14,9 @@ import ( ) type archiveCmdConfig struct { - exclude *chezmoi.EntryTypeSet + filter *chezmoi.EntryTypeFilter format chezmoi.ArchiveFormat gzip bool - include *chezmoi.EntryTypeSet init bool recursive bool } @@ -37,10 +36,10 @@ func (c *Config) newArchiveCmd() *cobra.Command { } flags := archiveCmd.Flags() - flags.VarP(c.archive.exclude, "exclude", "x", "Exclude entry types") + flags.VarP(c.archive.filter.Exclude, "exclude", "x", "Exclude entry types") flags.VarP(&c.archive.format, "format", "f", "Set archive format") flags.BoolVarP(&c.archive.gzip, "gzip", "z", c.archive.gzip, "Compress output with gzip") - flags.VarP(c.archive.include, "include", "i", "Include entry types") + flags.VarP(c.archive.filter.Exclude, "include", "i", "Include entry types") flags.BoolVar(&c.archive.init, "init", c.update.init, "Recreate config file from template") flags.BoolVarP(&c.archive.recursive, "recursive", "r", c.archive.recursive, "Recurse into subdirectories") @@ -77,7 +76,7 @@ func (c *Config) runArchiveCmd(cmd *cobra.Command, args []string) error { return chezmoi.UnknownArchiveFormatError(format) } if err := c.applyArgs(cmd.Context(), archiveSystem, chezmoi.EmptyAbsPath, args, applyArgsOptions{ - include: c.archive.include.Sub(c.archive.exclude), + filter: c.archive.filter, init: c.archive.init, recursive: c.archive.recursive, }); err != nil { diff --git a/pkg/cmd/config.go b/pkg/cmd/config.go index fdd061c31ff..1abbf2b6ce1 100644 --- a/pkg/cmd/config.go +++ b/pkg/cmd/config.go @@ -282,18 +282,15 @@ func newConfig(options ...configOption) (*Config, error) { // Command configurations. apply: applyCmdConfig{ - exclude: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesNone), - include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll), + filter: chezmoi.NewEntryTypeFilter(chezmoi.EntryTypesAll, chezmoi.EntryTypesNone), recursive: true, }, archive: archiveCmdConfig{ - exclude: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesNone), - include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll), + filter: chezmoi.NewEntryTypeFilter(chezmoi.EntryTypesAll, chezmoi.EntryTypesNone), recursive: true, }, dump: dumpCmdConfig{ - exclude: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesNone), - include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll), + filter: chezmoi.NewEntryTypeFilter(chezmoi.EntryTypesAll, chezmoi.EntryTypesNone), recursive: true, }, executeTemplate: executeTemplateCmdConfig{ @@ -301,29 +298,25 @@ func newConfig(options ...configOption) (*Config, error) { }, _import: importCmdConfig{ destination: homeDirAbsPath, - exclude: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesNone), - include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll), + filter: chezmoi.NewEntryTypeFilter(chezmoi.EntryTypesAll, chezmoi.EntryTypesNone), }, init: initCmdConfig{ data: true, - exclude: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesNone), + filter: chezmoi.NewEntryTypeFilter(chezmoi.EntryTypesAll, chezmoi.EntryTypesNone), guessRepoURL: true, }, managed: managedCmdConfig{ - exclude: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesNone), - include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll &^ (chezmoi.EntryTypeRemove | chezmoi.EntryTypeScripts)), + filter: chezmoi.NewEntryTypeFilter(chezmoi.EntryTypesAll, chezmoi.EntryTypesNone), }, mergeAll: mergeAllCmdConfig{ recursive: true, }, reAdd: reAddCmdConfig{ - exclude: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesNone), - include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll), + filter: chezmoi.NewEntryTypeFilter(chezmoi.EntryTypesAll, chezmoi.EntryTypesNone), }, update: updateCmdConfig{ apply: true, - exclude: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesNone), - include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll), + filter: chezmoi.NewEntryTypeFilter(chezmoi.EntryTypesAll, chezmoi.EntryTypesNone), recursive: true, }, upgrade: upgradeCmdConfig{ @@ -448,9 +441,8 @@ func (c *Config) addTemplateFunc(key string, value any) { } type applyArgsOptions struct { - include *chezmoi.EntryTypeSet + filter *chezmoi.EntryTypeFilter init bool - exclude *chezmoi.EntryTypeSet recursive bool umask fs.FileMode preApplyFunc chezmoi.PreApplyFunc @@ -538,7 +530,7 @@ func (c *Config) applyArgs( } applyOptions := chezmoi.ApplyOptions{ - Include: options.include.Sub(options.exclude), + Filter: options.filter, PreApplyFunc: options.preApplyFunc, Umask: options.umask, } @@ -1444,14 +1436,14 @@ func (c *Config) newDiffSystem(s chezmoi.System, w io.Writer, dirAbsPath chezmoi if c.Diff.useBuiltinDiff || c.Diff.Command == "" { options := &chezmoi.GitDiffSystemOptions{ Color: c.Color.Value(c.colorAutoFunc), - Include: c.Diff.include.Sub(c.Diff.Exclude), + Filter: chezmoi.NewEntryTypeFilter(c.Diff.include.Bits(), c.Diff.Exclude.Bits()), Reverse: c.Diff.Reverse, TextConvFunc: c.TextConv.convert, } return chezmoi.NewGitDiffSystem(s, w, dirAbsPath, options) } options := &chezmoi.ExternalDiffSystemOptions{ - Include: c.Diff.include.Sub(c.Diff.Exclude), + Filter: chezmoi.NewEntryTypeFilter(c.Diff.include.Bits(), c.Diff.Exclude.Bits()), Reverse: c.Diff.Reverse, } return chezmoi.NewExternalDiffSystem(s, c.Diff.Command, c.Diff.Args, c.DestDirAbsPath, options) @@ -2375,8 +2367,7 @@ func newConfigFile(bds *xdg.BaseDirectorySpecification) ConfigFile { // Command configurations. Add: addCmdConfig{ - exclude: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesNone), - include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll), + filter: chezmoi.NewEntryTypeFilter(chezmoi.EntryTypesAll, chezmoi.EntryTypesNone), recursive: true, }, Diff: diffCmdConfig{ @@ -2386,10 +2377,7 @@ func newConfigFile(bds *xdg.BaseDirectorySpecification) ConfigFile { Edit: editCmdConfig{ Hardlink: true, MinDuration: 1 * time.Second, - exclude: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesNone), - include: chezmoi.NewEntryTypeSet( - chezmoi.EntryTypeDirs | chezmoi.EntryTypeFiles | chezmoi.EntryTypeSymlinks | chezmoi.EntryTypeEncrypted, - ), + filter: chezmoi.NewEntryTypeFilter(chezmoi.EntryTypesAll, chezmoi.EntryTypesNone), }, Format: writeDataFormatJSON, Git: gitCmdConfig{ @@ -2405,7 +2393,7 @@ func newConfigFile(bds *xdg.BaseDirectorySpecification) ConfigFile { }, Verify: verifyCmdConfig{ Exclude: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesNone), - include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll &^ chezmoi.EntryTypeScripts), + include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll), recursive: true, }, } diff --git a/pkg/cmd/diffcmd.go b/pkg/cmd/diffcmd.go index e7e8b6b5651..2d0dc933474 100644 --- a/pkg/cmd/diffcmd.go +++ b/pkg/cmd/diffcmd.go @@ -53,7 +53,7 @@ func (c *Config) runDiffCmd(cmd *cobra.Command, args []string) (err error) { dryRunSystem := chezmoi.NewDryRunSystem(c.destSystem) diffSystem := c.newDiffSystem(dryRunSystem, builder, c.DestDirAbsPath) if err = c.applyArgs(cmd.Context(), diffSystem, c.DestDirAbsPath, args, applyArgsOptions{ - include: c.Diff.include.Sub(c.Diff.Exclude), + filter: chezmoi.NewEntryTypeFilter(c.Diff.include.Bits(), c.Diff.Exclude.Bits()), init: c.Diff.init, recursive: c.Diff.recursive, umask: c.Umask, diff --git a/pkg/cmd/dumpcmd.go b/pkg/cmd/dumpcmd.go index dc96be87aa7..b1ab50a7644 100644 --- a/pkg/cmd/dumpcmd.go +++ b/pkg/cmd/dumpcmd.go @@ -7,8 +7,7 @@ import ( ) type dumpCmdConfig struct { - exclude *chezmoi.EntryTypeSet - include *chezmoi.EntryTypeSet + filter *chezmoi.EntryTypeFilter init bool recursive bool } @@ -28,9 +27,9 @@ func (c *Config) newDumpCmd() *cobra.Command { } flags := dumpCmd.Flags() - flags.VarP(c.dump.exclude, "exclude", "x", "Exclude entry types") + flags.VarP(c.dump.filter.Exclude, "exclude", "x", "Exclude entry types") flags.VarP(&c.Format, "format", "f", "Output format") - flags.VarP(c.dump.include, "include", "i", "Include entry types") + flags.VarP(c.dump.filter.Include, "include", "i", "Include entry types") flags.BoolVar(&c.dump.init, "init", c.update.init, "Recreate config file from template") flags.BoolVarP(&c.dump.recursive, "recursive", "r", c.dump.recursive, "Recurse into subdirectories") if err := dumpCmd.RegisterFlagCompletionFunc("format", writeDataFormatFlagCompletionFunc); err != nil { @@ -45,7 +44,7 @@ func (c *Config) newDumpCmd() *cobra.Command { func (c *Config) runDumpCmd(cmd *cobra.Command, args []string) error { dumpSystem := chezmoi.NewDumpSystem() if err := c.applyArgs(cmd.Context(), dumpSystem, chezmoi.EmptyAbsPath, args, applyArgsOptions{ - include: c.dump.include.Sub(c.dump.exclude), + filter: c.dump.filter, init: c.dump.init, recursive: c.dump.recursive, umask: c.Umask, diff --git a/pkg/cmd/editcmd.go b/pkg/cmd/editcmd.go index 592d7ef2a49..d3dc3b946a6 100644 --- a/pkg/cmd/editcmd.go +++ b/pkg/cmd/editcmd.go @@ -18,8 +18,7 @@ type editCmdConfig struct { MinDuration time.Duration `mapstructure:"minDuration"` Watch bool `mapstructure:"watch"` Apply bool `mapstructure:"apply"` - exclude *chezmoi.EntryTypeSet - include *chezmoi.EntryTypeSet + filter *chezmoi.EntryTypeFilter init bool } @@ -42,9 +41,9 @@ func (c *Config) newEditCmd() *cobra.Command { flags := editCmd.Flags() flags.BoolVarP(&c.Edit.Apply, "apply", "a", c.Edit.Apply, "Apply after editing") - flags.VarP(c.Edit.exclude, "exclude", "x", "Exclude entry types") + flags.VarP(c.Edit.filter.Exclude, "exclude", "x", "Exclude entry types") flags.BoolVar(&c.Edit.Hardlink, "hardlink", c.Edit.Hardlink, "Invoke editor with a hardlink to the source file") - flags.VarP(c.Edit.include, "include", "i", "Include entry types") + flags.VarP(c.Edit.filter.Include, "include", "i", "Include entry types") flags.BoolVar(&c.Edit.init, "init", c.Edit.init, "Recreate config file from template") flags.BoolVar(&c.Edit.Watch, "watch", c.Edit.Watch, "Apply on save") @@ -60,7 +59,7 @@ func (c *Config) runEditCmd(cmd *cobra.Command, args []string) error { } if c.Edit.Apply { if err := c.applyArgs(cmd.Context(), c.destSystem, c.DestDirAbsPath, noArgs, applyArgsOptions{ - include: c.Edit.include.Sub(c.Edit.exclude), + filter: c.Edit.filter, init: c.Edit.init, recursive: true, umask: c.Umask, @@ -179,7 +178,7 @@ TARGETRELPATH: if c.Edit.Apply || c.Edit.Watch { if err := c.applyArgs(cmd.Context(), c.destSystem, c.DestDirAbsPath, args, applyArgsOptions{ - include: c.Edit.include, + filter: c.Edit.filter, init: c.Edit.init, recursive: true, umask: c.Umask, diff --git a/pkg/cmd/importcmd.go b/pkg/cmd/importcmd.go index 50876619c9a..92806938b5a 100644 --- a/pkg/cmd/importcmd.go +++ b/pkg/cmd/importcmd.go @@ -9,10 +9,9 @@ import ( ) type importCmdConfig struct { - exclude *chezmoi.EntryTypeSet destination chezmoi.AbsPath exact bool - include *chezmoi.EntryTypeSet + filter *chezmoi.EntryTypeFilter removeDestination bool stripComponents int } @@ -35,8 +34,8 @@ func (c *Config) newImportCmd() *cobra.Command { flags := importCmd.Flags() flags.VarP(&c._import.destination, "destination", "d", "Set destination prefix") flags.BoolVar(&c._import.exact, "exact", c._import.exact, "Set exact_ attribute on imported directories") - flags.VarP(c._import.exclude, "exclude", "x", "Exclude entry types") - flags.VarP(c._import.include, "include", "i", "Include entry types") + flags.VarP(c._import.filter.Exclude, "exclude", "x", "Exclude entry types") + flags.VarP(c._import.filter.Include, "include", "i", "Include entry types") flags.BoolVarP(&c._import.removeDestination, "remove-destination", "r", c._import.removeDestination, "Remove destination before import") //nolint:lll flags.IntVar(&c._import.stripComponents, "strip-components", c._import.stripComponents, "Strip leading path components") //nolint:lll @@ -87,7 +86,7 @@ func (c *Config) runImportCmd(cmd *cobra.Command, args []string, sourceState *ch return sourceState.Add( c.sourceSystem, c.persistentState, archiveReaderSystem, archiveReaderSystem.FileInfos(), &chezmoi.AddOptions{ Exact: c._import.exact, - Include: c._import.include.Sub(c._import.exclude), + Filter: c._import.filter, RemoveDir: removeDir, }, ) diff --git a/pkg/cmd/initcmd.go b/pkg/cmd/initcmd.go index 3935908e131..8f228543f1e 100644 --- a/pkg/cmd/initcmd.go +++ b/pkg/cmd/initcmd.go @@ -24,7 +24,7 @@ type initCmdConfig struct { configPath chezmoi.AbsPath data bool depth int - exclude *chezmoi.EntryTypeSet + filter *chezmoi.EntryTypeFilter guessRepoURL bool oneShot bool forcePromptOnce bool @@ -119,9 +119,10 @@ func (c *Config) newInitCmd() *cobra.Command { flags.VarP(&c.init.configPath, "config-path", "C", "Path to write generated config file") flags.BoolVar(&c.init.data, "data", c.init.data, "Include existing template data") flags.IntVarP(&c.init.depth, "depth", "d", c.init.depth, "Create a shallow clone") - flags.VarP(c.init.exclude, "exclude", "x", "Exclude entry types") + flags.VarP(c.init.filter.Exclude, "exclude", "x", "Exclude entry types") flags.BoolVar(&c.init.forcePromptOnce, "prompt", c.init.forcePromptOnce, "Force prompt*Once template functions to prompt") //nolint:lll flags.BoolVarP(&c.init.guessRepoURL, "guess-repo-url", "g", c.init.guessRepoURL, "Guess the repo URL") + flags.VarP(c.init.filter.Include, "include", "i", "Include entry types") flags.BoolVar(&c.init.oneShot, "one-shot", c.init.oneShot, "Run in one-shot mode") flags.StringToStringVar(&c.init.promptBool, "promptBool", c.init.promptBool, "Populate promptBool") flags.StringToIntVar(&c.init.promptInt, "promptInt", c.init.promptInt, "Populate promptInt") @@ -222,7 +223,7 @@ func (c *Config) runInitCmd(cmd *cobra.Command, args []string) error { // Apply. if c.init.apply { if err := c.applyArgs(cmd.Context(), c.destSystem, c.DestDirAbsPath, noArgs, applyArgsOptions{ - include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll).Sub(c.init.exclude), + filter: c.init.filter, recursive: false, umask: c.Umask, preApplyFunc: c.defaultPreApplyFunc, diff --git a/pkg/cmd/managedcmd.go b/pkg/cmd/managedcmd.go index c2aba1ca0cb..2784fdced23 100644 --- a/pkg/cmd/managedcmd.go +++ b/pkg/cmd/managedcmd.go @@ -11,8 +11,7 @@ import ( ) type managedCmdConfig struct { - exclude *chezmoi.EntryTypeSet - include *chezmoi.EntryTypeSet + filter *chezmoi.EntryTypeFilter } func (c *Config) newManagedCmd() *cobra.Command { @@ -27,8 +26,8 @@ func (c *Config) newManagedCmd() *cobra.Command { } flags := managedCmd.Flags() - flags.VarP(c.managed.exclude, "exclude", "x", "Exclude entry types") - flags.VarP(c.managed.include, "include", "i", "Include entry types") + flags.VarP(c.managed.filter.Exclude, "exclude", "x", "Exclude entry types") + flags.VarP(c.managed.filter.Include, "include", "i", "Include entry types") registerExcludeIncludeFlagCompletionFuncs(managedCmd) @@ -36,8 +35,6 @@ 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.managed.exclude) - // Build queued relPaths. When there are no arguments, start from root, // otherwise start from arguments. var relPaths chezmoi.RelPaths @@ -53,11 +50,15 @@ func (c *Config) runManagedCmd(cmd *cobra.Command, args []string, sourceState *c var targetRelPaths chezmoi.RelPaths _ = sourceState.ForEach(func(targetRelPath chezmoi.RelPath, sourceStateEntry chezmoi.SourceStateEntry) error { + if !c.managed.filter.IncludeSourceStateEntry(sourceStateEntry) { + return nil + } + targetStateEntry, err := sourceStateEntry.TargetStateEntry(c.destSystem, c.DestDirAbsPath.Join(targetRelPath)) if err != nil { return err } - if !include.IncludeTargetStateEntry(targetStateEntry) { + if !c.managed.filter.IncludeTargetStateEntry(targetStateEntry) { return nil } diff --git a/pkg/cmd/managedcmd_test.go b/pkg/cmd/managedcmd_test.go index 8605e88ddc7..7b8b1edfaae 100644 --- a/pkg/cmd/managedcmd_test.go +++ b/pkg/cmd/managedcmd_test.go @@ -75,6 +75,19 @@ func TestManagedCmd(t *testing.T) { ".symlink", ), }, + { + name: "external_git_repo", + root: map[string]any{ + "/home/user/.local/share/chezmoi/.chezmoiexternal.toml": chezmoitest.JoinLines( + `[".dir"]`, + ` type = "git-repo"`, + ` url = "https://github.com/example/example.git"`, + ), + }, + expectedOutput: chezmoitest.JoinLines( + ".dir", + ), + }, } { t.Run(tc.name, func(t *testing.T) { chezmoitest.WithTestFS(t, tc.root, func(fileSystem vfs.FS) { diff --git a/pkg/cmd/mergeallcmd.go b/pkg/cmd/mergeallcmd.go index aa383e7929e..a258bec5cad 100644 --- a/pkg/cmd/mergeallcmd.go +++ b/pkg/cmd/mergeallcmd.go @@ -43,7 +43,7 @@ func (c *Config) runMergeAllCmd(cmd *cobra.Command, args []string) error { return chezmoi.Skip } if err := c.applyArgs(cmd.Context(), dryRunSystem, c.DestDirAbsPath, args, applyArgsOptions{ - include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypeFiles), + filter: chezmoi.NewEntryTypeFilter(chezmoi.EntryTypesAll, chezmoi.EntryTypesNone), init: c.mergeAll.init, recursive: c.mergeAll.recursive, umask: c.Umask, diff --git a/pkg/cmd/readdcmd.go b/pkg/cmd/readdcmd.go index 4966283412a..855af9b9e4f 100644 --- a/pkg/cmd/readdcmd.go +++ b/pkg/cmd/readdcmd.go @@ -11,8 +11,7 @@ import ( ) type reAddCmdConfig struct { - exclude *chezmoi.EntryTypeSet - include *chezmoi.EntryTypeSet + filter *chezmoi.EntryTypeFilter } func (c *Config) newReAddCmd() *cobra.Command { @@ -32,8 +31,8 @@ func (c *Config) newReAddCmd() *cobra.Command { } flags := reAddCmd.Flags() - flags.VarP(c.reAdd.exclude, "exclude", "x", "Exclude entry types") - flags.VarP(c.reAdd.include, "include", "i", "Include entry types") + flags.VarP(c.reAdd.filter.Exclude, "exclude", "x", "Exclude entry types") + flags.VarP(c.reAdd.filter.Include, "include", "i", "Include entry types") registerExcludeIncludeFlagCompletionFuncs(reAddCmd) @@ -100,7 +99,7 @@ func (c *Config) runReAddCmd(cmd *cobra.Command, args []string, sourceState *che if err := sourceState.Add(c.sourceSystem, c.persistentState, c.destSystem, destAbsPathInfos, &chezmoi.AddOptions{ Encrypt: sourceStateFile.Attr.Encrypted, EncryptedSuffix: c.encryption.EncryptedSuffix(), - Include: c.reAdd.include.Sub(c.reAdd.exclude), + Filter: c.reAdd.filter, }); err != nil { return err } diff --git a/pkg/cmd/statuscmd.go b/pkg/cmd/statuscmd.go index f11ec168db6..9ef40051e35 100644 --- a/pkg/cmd/statuscmd.go +++ b/pkg/cmd/statuscmd.go @@ -72,7 +72,7 @@ func (c *Config) runStatusCmd(cmd *cobra.Command, args []string) error { return chezmoi.Skip } if err := c.applyArgs(cmd.Context(), dryRunSystem, c.DestDirAbsPath, args, applyArgsOptions{ - include: c.Status.include.Sub(c.Status.Exclude), + filter: chezmoi.NewEntryTypeFilter(c.Status.include.Bits(), c.Status.Exclude.Bits()), init: c.Status.init, recursive: c.Status.recursive, umask: c.Umask, diff --git a/pkg/cmd/testdata/scripts/managed.txtar b/pkg/cmd/testdata/scripts/managed.txtar index 350dd8dc8fa..39a44f65e6d 100644 --- a/pkg/cmd/testdata/scripts/managed.txtar +++ b/pkg/cmd/testdata/scripts/managed.txtar @@ -89,7 +89,6 @@ cmp stdout golden/managed2 .dir .dir/subdir .symlink -.template -- golden/managed-except-files-and-templates -- .dir .dir/subdir diff --git a/pkg/cmd/updatecmd.go b/pkg/cmd/updatecmd.go index 940cb991179..7acbfc7f286 100644 --- a/pkg/cmd/updatecmd.go +++ b/pkg/cmd/updatecmd.go @@ -11,8 +11,7 @@ import ( type updateCmdConfig struct { apply bool - exclude *chezmoi.EntryTypeSet - include *chezmoi.EntryTypeSet + filter *chezmoi.EntryTypeFilter init bool recursive bool } @@ -36,8 +35,8 @@ func (c *Config) newUpdateCmd() *cobra.Command { flags := updateCmd.Flags() flags.BoolVarP(&c.update.apply, "apply", "a", c.update.apply, "Apply after pulling") - flags.VarP(c.update.exclude, "exclude", "x", "Exclude entry types") - flags.VarP(c.update.include, "include", "i", "Include entry types") + flags.VarP(c.update.filter.Exclude, "exclude", "x", "Exclude entry types") + flags.VarP(c.update.filter.Include, "include", "i", "Include entry types") flags.BoolVar(&c.update.init, "init", c.update.init, "Recreate config file from template") flags.BoolVarP(&c.update.recursive, "recursive", "r", c.update.recursive, "Recurse into subdirectories") @@ -78,7 +77,7 @@ func (c *Config) runUpdateCmd(cmd *cobra.Command, args []string) error { if c.update.apply { if err := c.applyArgs(cmd.Context(), c.destSystem, c.DestDirAbsPath, args, applyArgsOptions{ - include: c.update.include.Sub(c.update.exclude), + filter: c.update.filter, init: c.update.init, recursive: c.update.recursive, umask: c.Umask, diff --git a/pkg/cmd/verifycmd.go b/pkg/cmd/verifycmd.go index d172a91d3d4..20f8e38576b 100644 --- a/pkg/cmd/verifycmd.go +++ b/pkg/cmd/verifycmd.go @@ -41,7 +41,7 @@ func (c *Config) newVerifyCmd() *cobra.Command { func (c *Config) runVerifyCmd(cmd *cobra.Command, args []string) error { errorOnWriteSystem := chezmoi.NewErrorOnWriteSystem(c.destSystem, chezmoi.ExitCodeError(1)) return c.applyArgs(cmd.Context(), errorOnWriteSystem, c.DestDirAbsPath, args, applyArgsOptions{ - include: c.Verify.include.Sub(c.Verify.Exclude), + filter: chezmoi.NewEntryTypeFilter(c.Verify.include.Bits(), c.Verify.Exclude.Bits()), init: c.Verify.init, recursive: c.Verify.recursive, umask: c.Umask,
feat
Make --include and --exclude flags behavior more consistent
a516387c8c0d38e8f8bcc2d152df6701fb716228
2024-11-07 23:26:01
Tom Payne
chore: Use choiceFlag for data formats
false
diff --git a/internal/cmd/config.go b/internal/cmd/config.go index 218602c762c..aa03b0477e0 100644 --- a/internal/cmd/config.go +++ b/internal/cmd/config.go @@ -103,7 +103,7 @@ type ConfigFile struct { Color autoBool `json:"color" mapstructure:"color" yaml:"color"` Data map[string]any `json:"data" mapstructure:"data" yaml:"data"` Env map[string]string `json:"env" mapstructure:"env" yaml:"env"` - Format writeDataFormat `json:"format" mapstructure:"format" yaml:"format"` + Format string `json:"format" mapstructure:"format" yaml:"format"` DestDirAbsPath chezmoi.AbsPath `json:"destDir" mapstructure:"destDir" yaml:"destDir"` GitHub gitHubConfig `json:"gitHub" mapstructure:"gitHub" yaml:"gitHub"` Hooks map[string]hookConfig `json:"hooks" mapstructure:"hooks" yaml:"hooks"` @@ -171,7 +171,7 @@ type Config struct { ConfigFile // Global configuration. - configFormat readDataFormat + configFormat *choiceFlag cpuProfile chezmoi.AbsPath debug bool dryRun bool @@ -196,9 +196,11 @@ type Config struct { apply applyCmdConfig archive archiveCmdConfig chattr chattrCmdConfig + data dataCmdConfig destroy destroyCmdConfig doctor doctorCmdConfig dump dumpCmdConfig + dumpConfig dumpConfigCmdConfig executeTemplate executeTemplateCmdConfig ignored ignoredCmdConfig _import importCmdConfig @@ -313,7 +315,6 @@ var ( commonFlagCompletionFuncs = map[string]func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective){ "exclude": chezmoi.EntryTypeSetFlagCompletionFunc, - "format": writeDataFormatFlagCompletionFunc, "include": chezmoi.EntryTypeSetFlagCompletionFunc, "path-style": chezmoi.PathStyleFlagCompletionFunc, "secrets": severityFlagCompletionFunc, @@ -342,6 +343,7 @@ func newConfig(options ...configOption) (*Config, error) { ConfigFile: newConfigFile(bds), // Global configuration. + configFormat: newChoiceFlag("", []string{"", "json", "toml", "yaml"}), homeDir: userHomeDir, templateFuncs: sprig.TxtFuncMap(), @@ -354,10 +356,17 @@ func newConfig(options ...configOption) (*Config, error) { filter: chezmoi.NewEntryTypeFilter(chezmoi.EntryTypesAll, chezmoi.EntryTypesNone), recursive: true, }, + data: dataCmdConfig{ + format: newChoiceFlag("", []string{"", "json", "yaml"}), + }, dump: dumpCmdConfig{ filter: chezmoi.NewEntryTypeFilter(chezmoi.EntryTypesAll, chezmoi.EntryTypesNone), + format: newChoiceFlag("", []string{"", "json", "yaml"}), recursive: true, }, + dumpConfig: dumpConfigCmdConfig{ + format: newChoiceFlag("", []string{"", "json", "yaml"}), + }, executeTemplate: executeTemplateCmdConfig{ stdinIsATTY: true, }, @@ -382,6 +391,17 @@ func newConfig(options ...configOption) (*Config, error) { filter: chezmoi.NewEntryTypeFilter(chezmoi.EntryTypesAll, chezmoi.EntryTypesNone), recursive: true, }, + state: stateCmdConfig{ + data: stateDataCmdConfig{ + format: newChoiceFlag("json", []string{"", "json", "yaml"}), + }, + dump: stateDumpCmdConfig{ + format: newChoiceFlag("json", []string{"", "json", "yaml"}), + }, + getBucket: stateGetBucketCmdConfig{ + format: newChoiceFlag("json", []string{"", "json", "yaml"}), + }, + }, unmanaged: unmanagedCmdConfig{ pathStyle: chezmoi.PathStyleSimple(chezmoi.PathStyleRelative), }, @@ -933,14 +953,19 @@ func (c *Config) decodeConfigBytes(format chezmoi.Format, data []byte, configFil // configFile. func (c *Config) decodeConfigFile(configFileAbsPath chezmoi.AbsPath, configFile *ConfigFile) error { var format chezmoi.Format - if c.configFormat == "" { + switch c.configFormat.String() { + case "": var err error format, err = chezmoi.FormatFromAbsPath(configFileAbsPath) if err != nil { return err } - } else { - format = c.configFormat.Format() + case "json": + format = chezmoi.FormatJSON + case "toml": + format = chezmoi.FormatTOML + case "yaml": + format = chezmoi.FormatYAML } configFileContents, err := c.fileSystem.ReadFile(configFileAbsPath.String()) @@ -1625,8 +1650,17 @@ func (c *Config) makeRunEWithSourceState( } // marshal formats data in dataFormat and writes it to the standard output. -func (c *Config) marshal(dataFormat writeDataFormat, data any) error { - marshaledData, err := dataFormat.Format().Marshal(data) +func (c *Config) marshal(dataFormat string, data any) error { + var format chezmoi.Format + switch dataFormat { + case "json": + format = chezmoi.FormatJSON + case "yaml": + format = chezmoi.FormatYAML + default: + return fmt.Errorf("%s: invalid format", dataFormat) + } + marshaledData, err := format.Marshal(data) if err != nil { return err } @@ -1661,7 +1695,7 @@ func (c *Config) newRootCmd() (*cobra.Command, error) { persistentFlags.VarP(&c.WorkingTreeAbsPath, "working-tree", "W", "Set working tree directory") persistentFlags.VarP(&c.customConfigFileAbsPath, "config", "c", "Set config file") - persistentFlags.Var(&c.configFormat, "config-format", "Set config file format") + persistentFlags.Var(c.configFormat, "config-format", "Set config file format") persistentFlags.Var(&c.cpuProfile, "cpu-profile", "Write a CPU profile to path") 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") @@ -1685,7 +1719,7 @@ func (c *Config) newRootCmd() (*cobra.Command, error) { persistentFlags.MarkHidden("safe"), rootCmd.MarkPersistentFlagDirname("source"), rootCmd.RegisterFlagCompletionFunc("color", autoBoolFlagCompletionFunc), - rootCmd.RegisterFlagCompletionFunc("config-format", readDataFormatFlagCompletionFunc), + rootCmd.RegisterFlagCompletionFunc("config-format", c.configFormat.FlagCompletionFunc()), rootCmd.RegisterFlagCompletionFunc("mode", chezmoi.ModeFlagCompletionFunc), rootCmd.RegisterFlagCompletionFunc("refresh-externals", chezmoi.RefreshExternalsFlagCompletionFunc), rootCmd.RegisterFlagCompletionFunc("use-builtin-age", autoBoolFlagCompletionFunc), @@ -2892,7 +2926,7 @@ func newConfigFile(bds *xdg.BaseDirectorySpecification) ConfigFile { MinDuration: 1 * time.Second, filter: chezmoi.NewEntryTypeFilter(chezmoi.EntryTypesAll, chezmoi.EntryTypesNone), }, - Format: writeDataFormatJSON, + Format: "json", Git: gitCmdConfig{ Command: "git", }, diff --git a/internal/cmd/datacmd.go b/internal/cmd/datacmd.go index 45176248832..de5c5271aa5 100644 --- a/internal/cmd/datacmd.go +++ b/internal/cmd/datacmd.go @@ -1,11 +1,17 @@ package cmd import ( + "cmp" + "github.com/spf13/cobra" "github.com/twpayne/chezmoi/v2/internal/chezmoi" ) +type dataCmdConfig struct { + format *choiceFlag +} + func (c *Config) newDataCmd() *cobra.Command { dataCmd := &cobra.Command{ Use: "data", @@ -19,7 +25,10 @@ func (c *Config) newDataCmd() *cobra.Command { ), } - dataCmd.Flags().VarP(&c.Format, "format", "f", "Output format") + dataCmd.Flags().VarP(c.data.format, "format", "f", "Output format") + if err := dataCmd.RegisterFlagCompletionFunc("format", c.data.format.FlagCompletionFunc()); err != nil { + panic(err) + } return dataCmd } @@ -31,5 +40,5 @@ func (c *Config) runDataCmd(cmd *cobra.Command, args []string) error { if err != nil { return err } - return c.marshal(c.Format, sourceState.TemplateData()) + return c.marshal(cmp.Or(c.data.format.String(), c.Format), sourceState.TemplateData()) } diff --git a/internal/cmd/dataformat.go b/internal/cmd/dataformat.go deleted file mode 100644 index 292ba142d28..00000000000 --- a/internal/cmd/dataformat.go +++ /dev/null @@ -1,98 +0,0 @@ -package cmd - -import ( - "errors" - "strings" - - "github.com/twpayne/chezmoi/v2/internal/chezmoi" -) - -// A readDataFormat is a format that chezmoi uses for reading (JSON, TOML, or -// YAML) and implements the github.com/spf13/pflag.Value interface. -type readDataFormat string - -// A writeDataFormat is format that chezmoi uses for writing (JSON or YAML) and -// implements the github.com/spf13/pflag.Value interface. -// -// TOML is not included as write format as it requires the top level value to be -// an object, and chezmoi occasionally requires the top level value to be a -// simple value or array. -type writeDataFormat string - -const ( - readDataFormatJSON readDataFormat = "json" - readDataFormatTOML readDataFormat = "toml" - readDataFormatYAML readDataFormat = "yaml" - - writeDataFormatJSON writeDataFormat = "json" - writeDataFormatYAML writeDataFormat = "yaml" -) - -var readDataFormatFlagCompletionFunc = chezmoi.FlagCompletionFunc([]string{ - string(readDataFormatJSON), - string(readDataFormatTOML), - string(readDataFormatYAML), -}) - -var writeDataFormatFlagCompletionFunc = chezmoi.FlagCompletionFunc([]string{ - string(writeDataFormatJSON), - string(writeDataFormatYAML), -}) - -// Set implements github.com/spf13/pflag.Value.Set. -func (f *readDataFormat) Set(s string) error { - switch strings.ToLower(s) { - case "json": - *f = readDataFormatJSON - case "toml": - *f = readDataFormatTOML - case "yaml": - *f = readDataFormatYAML - default: - return errors.New("invalid or unsupported data format") - } - return nil -} - -// Format returns f's format. -func (f readDataFormat) Format() chezmoi.Format { - return chezmoi.FormatsByName[string(f)] -} - -// String implements github.com/spf13/pflag.Value.String. -func (f readDataFormat) String() string { - return string(f) -} - -// Type implements github.com/spf13/pflag.Value.Type. -func (f readDataFormat) Type() string { - return "json|toml|yaml" -} - -// Format returns f's format. -func (f writeDataFormat) Format() chezmoi.Format { - return chezmoi.FormatsByName[string(f)] -} - -// Set implements github.com/spf13/pflag.Value.Set. -func (f *writeDataFormat) Set(s string) error { - switch strings.ToLower(s) { - case "json": - *f = writeDataFormatJSON - case "yaml": - *f = writeDataFormatYAML - default: - return errors.New("invalid or unsupported data format") - } - return nil -} - -// String implements github.com/spf13/pflag.Value.String. -func (f writeDataFormat) String() string { - return string(f) -} - -// Type implements github.com/spf13/pflag.Value.Type. -func (f writeDataFormat) Type() string { - return "json|yaml" -} diff --git a/internal/cmd/dumpcmd.go b/internal/cmd/dumpcmd.go index 69aa853ad00..4b5821db639 100644 --- a/internal/cmd/dumpcmd.go +++ b/internal/cmd/dumpcmd.go @@ -1,6 +1,8 @@ package cmd import ( + "cmp" + "github.com/spf13/cobra" "github.com/twpayne/chezmoi/v2/internal/chezmoi" @@ -8,6 +10,7 @@ import ( type dumpCmdConfig struct { filter *chezmoi.EntryTypeFilter + format *choiceFlag init bool parentDirs bool recursive bool @@ -28,7 +31,8 @@ func (c *Config) newDumpCmd() *cobra.Command { } dumpCmd.Flags().VarP(c.dump.filter.Exclude, "exclude", "x", "Exclude entry types") - dumpCmd.Flags().VarP(&c.Format, "format", "f", "Output format") + dumpCmd.Flags().VarP(c.dump.format, "format", "f", "Output format") + must(dumpCmd.RegisterFlagCompletionFunc("format", c.dump.format.FlagCompletionFunc())) dumpCmd.Flags().VarP(c.dump.filter.Include, "include", "i", "Include entry types") dumpCmd.Flags().BoolVar(&c.dump.init, "init", c.dump.init, "Recreate config file from template") dumpCmd.Flags().BoolVarP(&c.dump.parentDirs, "parent-dirs", "P", c.dump.parentDirs, "Dump all parent directories") @@ -49,5 +53,5 @@ func (c *Config) runDumpCmd(cmd *cobra.Command, args []string) error { }); err != nil { return err } - return c.marshal(c.Format, dumpSystem.Data()) + return c.marshal(cmp.Or(c.dump.format.String(), c.Format), dumpSystem.Data()) } diff --git a/internal/cmd/dumpconfigcmd.go b/internal/cmd/dumpconfigcmd.go index 428db1105c3..9f3c30a0ca4 100644 --- a/internal/cmd/dumpconfigcmd.go +++ b/internal/cmd/dumpconfigcmd.go @@ -1,6 +1,14 @@ package cmd -import "github.com/spf13/cobra" +import ( + "cmp" + + "github.com/spf13/cobra" +) + +type dumpConfigCmdConfig struct { + format *choiceFlag +} func (c *Config) newDumpConfigCmd() *cobra.Command { dumpConfigCmd := &cobra.Command{ @@ -15,11 +23,13 @@ func (c *Config) newDumpConfigCmd() *cobra.Command { ), } - dumpConfigCmd.Flags().VarP(&c.Format, "format", "f", "Output format") + dumpConfigCmd.Flags().VarP(c.dumpConfig.format, "format", "f", "Output format") + + must(dumpConfigCmd.RegisterFlagCompletionFunc("format", c.dumpConfig.format.FlagCompletionFunc())) return dumpConfigCmd } func (c *Config) runDumpConfigCmd(cmd *cobra.Command, args []string) error { - return c.marshal(c.Format, c) + return c.marshal(cmp.Or(c.dumpConfig.format.String(), c.Format), c) } diff --git a/internal/cmd/statecmd.go b/internal/cmd/statecmd.go index 41caaf34a0c..8de93a146c7 100644 --- a/internal/cmd/statecmd.go +++ b/internal/cmd/statecmd.go @@ -1,6 +1,7 @@ package cmd import ( + "cmp" "errors" "fmt" "io/fs" @@ -11,13 +12,19 @@ import ( ) type stateCmdConfig struct { + data stateDataCmdConfig delete stateDeleteCmdConfig deleteBucket stateDeleteBucketCmdConfig + dump stateDumpCmdConfig get stateGetCmdConfig getBucket stateGetBucketCmdConfig set stateSetCmdConfig } +type stateDataCmdConfig struct { + format *choiceFlag +} + type stateDeleteCmdConfig struct { bucket string key string @@ -27,6 +34,10 @@ type stateDeleteBucketCmdConfig struct { bucket string } +type stateDumpCmdConfig struct { + format *choiceFlag +} + type stateGetCmdConfig struct { bucket string key string @@ -34,6 +45,7 @@ type stateGetCmdConfig struct { type stateGetBucketCmdConfig struct { bucket string + format *choiceFlag } type stateSetCmdConfig struct { @@ -62,7 +74,8 @@ func (c *Config) newStateCmd() *cobra.Command { persistentStateModeReadOnly, ), } - stateDataCmd.Flags().VarP(&c.Format, "format", "f", "Output format") + stateDataCmd.Flags().VarP(c.state.data.format, "format", "f", "Output format") + must(stateDataCmd.RegisterFlagCompletionFunc("format", c.state.data.format.FlagCompletionFunc())) stateCmd.AddCommand(stateDataCmd) stateDeleteCmd := &cobra.Command{ @@ -99,7 +112,8 @@ func (c *Config) newStateCmd() *cobra.Command { persistentStateModeReadOnly, ), } - stateDumpCmd.Flags().VarP(&c.Format, "format", "f", "Output format") + stateDumpCmd.Flags().VarP(c.state.dump.format, "format", "f", "Output format") + must(stateDumpCmd.RegisterFlagCompletionFunc("format", c.state.dump.format.FlagCompletionFunc())) stateCmd.AddCommand(stateDumpCmd) stateGetCmd := &cobra.Command{ @@ -125,7 +139,8 @@ func (c *Config) newStateCmd() *cobra.Command { ), } stateGetBucketCmd.Flags().StringVar(&c.state.getBucket.bucket, "bucket", c.state.getBucket.bucket, "bucket") - stateGetBucketCmd.Flags().VarP(&c.Format, "format", "f", "Output format") + stateGetBucketCmd.Flags().VarP(c.state.getBucket.format, "format", "f", "Output format") + must(stateGetBucketCmd.RegisterFlagCompletionFunc("format", c.state.getBucket.format.FlagCompletionFunc())) stateCmd.AddCommand(stateGetBucketCmd) stateResetCmd := &cobra.Command{ @@ -162,7 +177,7 @@ func (c *Config) runStateDataCmd(cmd *cobra.Command, args []string) error { if err != nil { return err } - return c.marshal(c.Format, data) + return c.marshal(cmp.Or(c.state.data.format.String(), c.Format), data) } func (c *Config) runStateDeleteCmd(cmd *cobra.Command, args []string) error { @@ -188,7 +203,7 @@ func (c *Config) runStateDumpCmd(cmd *cobra.Command, args []string) error { if err != nil { return err } - return c.marshal(c.Format, data) + return c.marshal(cmp.Or(c.state.dump.format.String(), c.Format), data) } func (c *Config) runStateGetCmd(cmd *cobra.Command, args []string) error { @@ -204,7 +219,7 @@ func (c *Config) runStateGetBucketCmd(cmd *cobra.Command, args []string) error { if err != nil { return err } - return c.marshal(c.Format, data) + return c.marshal(cmp.Or(c.state.getBucket.format.String(), c.Format), data) } func (c *Config) runStateResetCmd(cmd *cobra.Command, args []string) error { diff --git a/internal/cmd/testdata/scripts/completion.txtar b/internal/cmd/testdata/scripts/completion.txtar index affabeff533..fff3bfd8b41 100644 --- a/internal/cmd/testdata/scripts/completion.txtar +++ b/internal/cmd/testdata/scripts/completion.txtar @@ -18,6 +18,10 @@ stdout '#compdef chezmoi' exec chezmoi __complete --color t cmp stdout golden/auto-bool-t +# test that --config-format flags are completed +exec chezmoi __complete --config-format '' +cmp stdout golden/config-format + # test that --mode values are completed exec chezmoi __complete --mode '' cmp stdout golden/mode @@ -48,15 +52,15 @@ cmp stdout golden/archive-format # test that data --format values are completed exec chezmoi __complete data --format= -cmp stdout golden/output-format +cmp stdout golden/output-format-with-empty # test that dump --format values are completed exec chezmoi __complete dump --format= -cmp stdout golden/output-format +cmp stdout golden/output-format-with-empty # test that dump-config --format values are completed exec chezmoi __complete dump-config --format= -cmp stdout golden/output-format +cmp stdout golden/output-format-with-empty # test that managed path style values are completed exec chezmoi __complete managed --path-style= @@ -64,11 +68,11 @@ cmp stdout golden/path-style # test that state data --format values are completed exec chezmoi __complete state data --format= -cmp stdout golden/output-format +cmp stdout golden/output-format-with-empty # test that state dump --format values are completed exec chezmoi __complete state dump --format= -cmp stdout golden/output-format +cmp stdout golden/output-format-with-empty # test that status path style values are completed exec chezmoi __complete status --path-style= @@ -93,6 +97,12 @@ zip t true :4 +-- golden/config-format -- + +json +toml +yaml +:4 -- golden/entry-type-set -- all always @@ -120,6 +130,11 @@ file symlink :4 -- golden/output-format -- +json +yaml +:4 +-- golden/output-format-with-empty -- + json yaml :4 diff --git a/internal/cmd/testdata/scripts/edgecases.txtar b/internal/cmd/testdata/scripts/edgecases.txtar index dccdf603a29..6fc6e5967f7 100644 --- a/internal/cmd/testdata/scripts/edgecases.txtar +++ b/internal/cmd/testdata/scripts/edgecases.txtar @@ -22,11 +22,11 @@ stderr 'not allowed in \.chezmoitemplates directory' # test that chezmoi data returns an error if an unknown read format is specified ! exec chezmoi init --config-format=yml -stderr 'invalid or unsupported data format' +stderr 'flag: invalid value' # test that chezmoi data returns an error if an unknown write format is specified ! exec chezmoi data --format=yml -stderr 'invalid or unsupported data format' +stderr 'flag: invalid value' skip 'FIXME make the following test pass'
chore
Use choiceFlag for data formats
ecdb07b693aa30e899ceba70363277ede3239a16
2022-03-24 13:55:06
Austin Ziegler
docs: Adjust documents for 1Password CLI 2.0.0 changes
false
diff --git a/assets/chezmoi.io/docs/reference/templates/functions/onepassword.md b/assets/chezmoi.io/docs/reference/templates/functions/onepassword.md index 150cc88e86f..9cc544105ee 100644 --- a/assets/chezmoi.io/docs/reference/templates/functions/onepassword.md +++ b/assets/chezmoi.io/docs/reference/templates/functions/onepassword.md @@ -19,11 +19,32 @@ be interactively prompted to sign in. {{ (onepassword "$UUID").details.password }} {{ (onepassword "$UUID" "$VAULT_UUID").details.password }} {{ (onepassword "$UUID" "$VAULT_UUID" "$ACCOUNT_NAME").details.password }} + ``` + + If using 1Password 1.0, then *vault-uuid* is optional. + + ``` {{ (onepassword "$UUID" "" "$ACCOUNT_NAME").details.password }} ``` !!! info - If you're using [1Password CLI 2.0](https://developer.1password.com/), then - the structure of the data returned by the `onepassword` template function - will be different and you will need to update your templates. + If you're using [1Password CLI 2.0](https://developer.1password.com/), there + are changes to be aware of. + + !!! warning + + The structure of the data returned by the `onepassword` template function + will be different and you will need to update your templates. The structure + has not yet been finalized. + + !!! warning + + Neither *vault-uuid* nor *account-name* may be empty strings if specified. + Older versions of 1Password CLI would ignore empty strings for arguments. + + !!! warning + + Unless using biometric authentication, or when using without prompting, it + is recommended that instead of *account-name*, the UUID of the account is + used. This can be shown with `op account list`. diff --git a/assets/chezmoi.io/docs/reference/templates/functions/onepasswordDetailsFields.md b/assets/chezmoi.io/docs/reference/templates/functions/onepasswordDetailsFields.md index ec88974e9b6..632114443d7 100644 --- a/assets/chezmoi.io/docs/reference/templates/functions/onepasswordDetailsFields.md +++ b/assets/chezmoi.io/docs/reference/templates/functions/onepasswordDetailsFields.md @@ -22,6 +22,11 @@ accounts). {{ (onepasswordDetailsFields "$UUID").password.value }} {{ (onepasswordDetailsFields "$UUID" "$VAULT_UUID").password.value }} {{ (onepasswordDetailsFields "$UUID" "$VAULT_UUID" "$ACCOUNT_NAME").password.value }} + ``` + + If using 1Password 1.0, then *vault-uuid* is optional. + + ``` {{ (onepasswordDetailsFields "$UUID" "" "$ACCOUNT_NAME").password.value }} ``` @@ -72,12 +77,22 @@ accounts). !!! info - If you're using [1Password CLI 2.0](https://developer.1password.com/), then - the structure of the data returned by the `onepasswordDetailsFields` + If you're using [1Password CLI 2.0](https://developer.1password.com/), there + are changes to be aware of. + + !!! warning + + The structure of the data returned by the `onepasswordDetailsFields` template function will be different and you will need to update your - templates. + templates. The structure has not yet been finalized. + + !!! warning + + Neither *vault-uuid* nor *account-name* may be empty strings if specified. + Older versions of 1Password CLI would ignore empty strings for arguments. !!! warning - The structure of the data returned will not be finalized until 1Password - CLI 2.0 is released. + Unless using biometric authentication, or when using without prompting, it + is recommended that instead of *account-name*, the UUID of the account is + used. This can be shown with `op account list`. diff --git a/assets/chezmoi.io/docs/reference/templates/functions/onepasswordDocument.md b/assets/chezmoi.io/docs/reference/templates/functions/onepasswordDocument.md index c2b1721d09a..31726f2ec16 100644 --- a/assets/chezmoi.io/docs/reference/templates/functions/onepasswordDocument.md +++ b/assets/chezmoi.io/docs/reference/templates/functions/onepasswordDocument.md @@ -19,5 +19,26 @@ by default you will be interactively prompted to sign in. {{- onepasswordDocument "$UUID" -}} {{- onepasswordDocument "$UUID" "$VAULT_UUID" -}} {{- onepasswordDocument "$UUID" "$VAULT_UUID" "$ACCOUNT_NAME" -}} + ``` + + If using 1Password 1.0, then *vault-uuid* is optional. + + ``` {{- onepasswordDocument "$UUID" "" "$ACCOUNT_NAME" -}} ``` + +!!! info + + If you're using [1Password CLI 2.0](https://developer.1password.com/), there + are changes to be aware of. + + !!! warning + + Neither *vault-uuid* nor *account-name* may be empty strings if specified. + Older versions of 1Password CLI would ignore empty strings for arguments. + + !!! warning + + Unless using biometric authentication, or when using without prompting, it + is recommended that instead of *account-name*, the UUID of the account is + used. This can be shown with `op account list`. diff --git a/assets/chezmoi.io/docs/reference/templates/functions/onepasswordItemFields.md b/assets/chezmoi.io/docs/reference/templates/functions/onepasswordItemFields.md index 1bf4ad3b993..d868077329d 100644 --- a/assets/chezmoi.io/docs/reference/templates/functions/onepasswordItemFields.md +++ b/assets/chezmoi.io/docs/reference/templates/functions/onepasswordItemFields.md @@ -67,7 +67,22 @@ in the environment, by default you will be interactively prompted to sign in. !!! info - If you're using [1Password CLI - 2.0](https://developer.1password.com/docs/cli/), then the structure of the - data returned by the `onepasswordDetailsFields` template function will be - different and you will need to update your templates. + If you're using [1Password CLI 2.0](https://developer.1password.com/), there + are changes to be aware of. + + !!! warning + + The structure of the data returned by the `onepasswordItemFields` template + function will be different and you will need to update your templates. The + structure has not yet been finalized. + + !!! warning + + Neither *vault-uuid* nor *account-name* may be empty strings if specified. + Older versions of 1Password CLI would ignore empty strings for arguments. + + !!! warning + + Unless using biometric authentication, or when using without prompting, it + is recommended that instead of *account-name*, the UUID of the account is + used. This can be shown with `op account list`.
docs
Adjust documents for 1Password CLI 2.0.0 changes
4ad25a934ea8687cf7e166af106668055d23e11d
2021-10-26 04:33:30
Tom Payne
chore: Fix GitHub Action changes output
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index f822709c2f9..5e0c0888323 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -1,6 +1,8 @@ name: main on: pull_request: + branches: + - master push: branches: - master @@ -14,7 +16,7 @@ jobs: changes: runs-on: ubuntu-20.04 outputs: - code: ${{ steps.filter.output.code }} + code: ${{ steps.filter.outputs.code }} steps: - name: Checkout uses: actions/checkout@v2
chore
Fix GitHub Action changes output
28c7fb80f26bb25878fd9e19c2c32c5858aa63b6
2024-10-23 23:57:44
Tom Payne
chore: Fix links to special files
false
diff --git a/assets/chezmoi.io/docs/reference/commands/add.md b/assets/chezmoi.io/docs/reference/commands/add.md index 7b0f8b4b87e..b7ec233938d 100644 --- a/assets/chezmoi.io/docs/reference/commands/add.md +++ b/assets/chezmoi.io/docs/reference/commands/add.md @@ -102,6 +102,6 @@ $ chezmoi add ~/.oh-my-zsh --exact --recursive `chezmoi add` will fail if the entry being added is in a directory implicitly created by an - [external](../special-files-and-directories/chezmoiexternal-format.md). + [external](../special-files/chezmoiexternal-format.md). See [this GitHub issue](https://github.com/twpayne/chezmoi/issues/1574) for details. diff --git a/assets/chezmoi.io/docs/user-guide/frequently-asked-questions/usage.md b/assets/chezmoi.io/docs/user-guide/frequently-asked-questions/usage.md index d1034a8dfe1..1ab99c08f44 100644 --- a/assets/chezmoi.io/docs/user-guide/frequently-asked-questions/usage.md +++ b/assets/chezmoi.io/docs/user-guide/frequently-asked-questions/usage.md @@ -53,7 +53,7 @@ called `.chezmoiignore` in the source state. Patterns are supported, and you can change what's ignored from machine to machine. The full usage and syntax is described in the [reference -manual](../../reference/special-files-and-directories/chezmoiignore.md). +manual](../../reference/special-files/chezmoiignore.md). ## 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? diff --git a/assets/chezmoi.io/docs/user-guide/include-files-from-elsewhere.md b/assets/chezmoi.io/docs/user-guide/include-files-from-elsewhere.md index 8185f2c2b09..0c65a670a1e 100644 --- a/assets/chezmoi.io/docs/user-guide/include-files-from-elsewhere.md +++ b/assets/chezmoi.io/docs/user-guide/include-files-from-elsewhere.md @@ -2,7 +2,7 @@ The sections below contain examples of how to use `.chezmoiexternal.toml` to include files from external sources. For more details, check the [reference -manual](../reference/special-files-and-directories/chezmoiexternal-format.md) . +manual](../reference/special-files/chezmoiexternal-format.md) . ## Include a subdirectory from a URL @@ -78,7 +78,7 @@ update Oh My Zsh and its plugins, refresh the downloaded archives. If your external dependency target directory can contain cache files that are added during normal use, chezmoi will report that files have changed on `chezmoi apply`. To avoid this, add the cache directory to your - [`.chezmoiignore`](../reference/special-files-and-directories/chezmoiignore.md) + [`.chezmoiignore`](../reference/special-files/chezmoiignore.md) file. For example, Oh My Zsh may cache completions in `.oh-my-zsh/cache/completions/`,
chore
Fix links to special files
ce6a653eb8b39077dc53db6cd33dd54c0f31c48f
2021-10-09 21:01:22
Tom Payne
chore: Improve logging of encryption
false
diff --git a/internal/chezmoi/debugencryption.go b/internal/chezmoi/debugencryption.go index c7d60ff29a9..892f883d86c 100644 --- a/internal/chezmoi/debugencryption.go +++ b/internal/chezmoi/debugencryption.go @@ -1,19 +1,22 @@ package chezmoi import ( - "github.com/rs/zerolog/log" + "github.com/rs/zerolog" "github.com/twpayne/chezmoi/v2/internal/chezmoilog" ) // A DebugEncryption logs all calls to an Encryption. type DebugEncryption struct { + logger *zerolog.Logger encryption Encryption } -// NewDebugEncryption returns a new DebugEncryption. -func NewDebugEncryption(encryption Encryption) *DebugEncryption { +// NewDebugEncryption returns a new DebugEncryption that logs methods on +// encryption to logger. +func NewDebugEncryption(encryption Encryption, logger *zerolog.Logger) *DebugEncryption { return &DebugEncryption{ + logger: logger, encryption: encryption, } } @@ -21,7 +24,7 @@ func NewDebugEncryption(encryption Encryption) *DebugEncryption { // Decrypt implements Encryption.Decrypt. func (e *DebugEncryption) Decrypt(ciphertext []byte) ([]byte, error) { plaintext, err := e.encryption.Decrypt(ciphertext) - log.Err(err). + e.logger.Err(err). Bytes("ciphertext", chezmoilog.Output(ciphertext, err)). Bytes("plaintext", chezmoilog.Output(plaintext, err)). Msg("Decrypt") @@ -31,7 +34,7 @@ func (e *DebugEncryption) Decrypt(ciphertext []byte) ([]byte, error) { // DecryptToFile implements Encryption.DecryptToFile. func (e *DebugEncryption) DecryptToFile(plaintextAbsPath AbsPath, ciphertext []byte) error { err := e.encryption.DecryptToFile(plaintextAbsPath, ciphertext) - log.Err(err). + e.logger.Err(err). Stringer("plaintextAbsPath", plaintextAbsPath). Bytes("ciphertext", chezmoilog.Output(ciphertext, err)). Msg("DecryptToFile") @@ -41,7 +44,7 @@ func (e *DebugEncryption) DecryptToFile(plaintextAbsPath AbsPath, ciphertext []b // Encrypt implements Encryption.Encrypt. func (e *DebugEncryption) Encrypt(plaintext []byte) ([]byte, error) { ciphertext, err := e.encryption.Encrypt(plaintext) - log.Err(err). + e.logger.Err(err). Bytes("plaintext", chezmoilog.Output(plaintext, err)). Bytes("ciphertext", chezmoilog.Output(ciphertext, err)). Msg("Encrypt") @@ -51,7 +54,7 @@ func (e *DebugEncryption) Encrypt(plaintext []byte) ([]byte, error) { // EncryptFile implements Encryption.EncryptFile. func (e *DebugEncryption) EncryptFile(plaintextAbsPath AbsPath) ([]byte, error) { ciphertext, err := e.encryption.EncryptFile(plaintextAbsPath) - log.Err(err). + e.logger.Err(err). Stringer("plaintextAbsPath", plaintextAbsPath). Bytes("ciphertext", chezmoilog.Output(ciphertext, err)). Msg("EncryptFile") diff --git a/internal/cmd/config.go b/internal/cmd/config.go index 779c35dec89..ad4bc4a8308 100644 --- a/internal/cmd/config.go +++ b/internal/cmd/config.go @@ -47,6 +47,7 @@ import ( const ( logComponentKey = "component" + logComponentValueEncryption = "encryption" logComponentValuePersistentState = "persistentState" logComponentValueSystem = "system" ) @@ -1575,7 +1576,8 @@ func (c *Config) persistentPreRunRootE(cmd *cobra.Command, args []string) error return fmt.Errorf("%s: unknown encryption", c.Encryption) } if c.debug { - c.encryption = chezmoi.NewDebugEncryption(c.encryption) + encryptionLogger := log.With().Str(logComponentKey, logComponentValueEncryption).Logger() + c.encryption = chezmoi.NewDebugEncryption(c.encryption, &encryptionLogger) } // Create the config directory if needed.
chore
Improve logging of encryption
b4a177489e079710c2f96501463aa1db67328506
2021-10-11 23:58:36
Tom Payne
chore: Add more .chezmoiignore tests
false
diff --git a/internal/cmd/testdata/scripts/ignore.txt b/internal/cmd/testdata/scripts/ignore.txt index ba0a4490572..e421d07198b 100644 --- a/internal/cmd/testdata/scripts/ignore.txt +++ b/internal/cmd/testdata/scripts/ignore.txt @@ -7,6 +7,60 @@ exists $HOME/.file ! exists $HOME/README.md ! exists $HOME/.dir +chhome home2/user + +# test that chezmoi manage lists all managed files +chezmoi managed +cmp stdout golden/managed-all + +# test that chezmoiignore ignores all files in a directory +cp golden/.chezmoiignore-dir $CHEZMOISOURCEDIR/.chezmoiignore +chezmoi managed +cmp stdout golden/managed-ignore-dir + +# test that chezmoiignore ignores all files in a subdirectory +cp golden/.chezmoiignore-dir-subdir $CHEZMOISOURCEDIR/.chezmoiignore +chezmoi managed +cmp stdout golden/managed-ignore-dir-subdir + +# test that chezmoiignore ignores all files matching a simple pattern +cp golden/.chezmoiignore-star-slash-star-dot-txt $CHEZMOISOURCEDIR/.chezmoiignore +chezmoi managed +cmp stdout golden/managed-ignore-star-slash-star-dot-txt + +# test that chezmoiignore ignores all files matching a doublestar pattern +cp golden/.chezmoiignore-star-star-slash-star-dot-txt $CHEZMOISOURCEDIR/.chezmoiignore +chezmoi managed +cmp stdout golden/managed-ignore-star-star-slash-star-dot-txt + +-- golden/.chezmoiignore-dir -- +.dir +-- golden/.chezmoiignore-dir-subdir -- +.dir/subdir/ +-- golden/.chezmoiignore-star-slash-star-dot-txt -- +*/*.txt +-- golden/.chezmoiignore-star-star-slash-star-dot-txt -- +**/*.txt +-- golden/managed-all -- +.dir +.dir/file.txt +.dir/subdir +.dir/subdir/file.txt +.file.txt +-- golden/managed-ignore-dir -- +.file.txt +-- golden/managed-ignore-dir-subdir -- +.dir +.dir/file.txt +.file.txt +-- golden/managed-ignore-star-slash-star-dot-txt -- +.dir +.dir/subdir +.dir/subdir/file.txt +.file.txt +-- golden/managed-ignore-star-star-slash-star-dot-txt -- +.dir +.dir/subdir -- home/user/.local/share/chezmoi/.chezmoiignore -- README.md .dir @@ -15,3 +69,9 @@ README.md {{ end }} -- home/user/.local/share/chezmoi/README.md -- # contents of README.md +-- home2/user/.local/share/chezmoi/dot_file.txt -- +# contents of .file.txt +-- home2/user/.local/share/chezmoi/dot_dir/file.txt -- +# contents of .dir/file.txt +-- home2/user/.local/share/chezmoi/dot_dir/subdir/file.txt -- +# contents of .dir/subdir/file.txt
chore
Add more .chezmoiignore tests
14b790299c0598ccd8e1011d289b4813c2ba5c8b
2022-02-14 04:35:18
Tom Payne
chore: Improve source-path command short help text
false
diff --git a/pkg/cmd/sourcepathcmd.go b/pkg/cmd/sourcepathcmd.go index 2a2f43c5079..3edc594594f 100644 --- a/pkg/cmd/sourcepathcmd.go +++ b/pkg/cmd/sourcepathcmd.go @@ -12,7 +12,7 @@ import ( func (c *Config) newSourcePathCmd() *cobra.Command { sourcePathCmd := &cobra.Command{ Use: "source-path [target]...", - Short: "Print the path of a target in the source state", + Short: "Print the source path of a target", Long: mustLongHelp("source-path"), Example: example("source-path"), ValidArgsFunction: c.targetValidArgs,
chore
Improve source-path command short help text
788f805a980c653a9b6e24df5f693e3887c72e4f
2024-05-31 05:17:16
Tom Payne
fix: Don't panic on unexpected bubbletea messages
false
diff --git a/internal/cmd/readhttpresponse.go b/internal/cmd/readhttpresponse.go index dfa8d840729..a36f70ebcfb 100644 --- a/internal/cmd/readhttpresponse.go +++ b/internal/cmd/readhttpresponse.go @@ -1,7 +1,6 @@ package cmd import ( - "fmt" "io" "net/http" "strings" @@ -62,10 +61,8 @@ func (m httpProgressModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { default: return m, nil } - case tea.WindowSizeMsg: - return m, nil default: - panic(fmt.Sprintf("%T: unknown message type", msg)) + return m, nil } } @@ -101,10 +98,8 @@ func (m httpSpinnerModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { default: return m, nil } - case tea.WindowSizeMsg: - return m, nil default: - panic(fmt.Sprintf("%T: unknown message type", msg)) + return m, nil } }
fix
Don't panic on unexpected bubbletea messages
91823e32ecf3da096afc458be0aebd158102f848
2024-04-25 03:48:44
Tom Payne
feat: Add --tree flag to managed command
false
diff --git a/internal/cmd/managedcmd.go b/internal/cmd/managedcmd.go index 732caaee2d4..5c2efa2cae5 100644 --- a/internal/cmd/managedcmd.go +++ b/internal/cmd/managedcmd.go @@ -1,10 +1,6 @@ package cmd import ( - "fmt" - "sort" - "strings" - "github.com/spf13/cobra" "github.com/twpayne/chezmoi/v2/internal/chezmoi" @@ -13,6 +9,7 @@ import ( type managedCmdConfig struct { filter *chezmoi.EntryTypeFilter pathStyle chezmoi.PathStyle + tree bool } func (c *Config) newManagedCmd() *cobra.Command { @@ -30,6 +27,7 @@ func (c *Config) newManagedCmd() *cobra.Command { managedCmd.Flags().VarP(c.managed.filter.Exclude, "exclude", "x", "Exclude entry types") managedCmd.Flags().VarP(c.managed.filter.Include, "include", "i", "Include entry types") 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") return managedCmd } @@ -93,10 +91,7 @@ func (c *Config) runManagedCmd(cmd *cobra.Command, args []string, sourceState *c }, ) - sort.Strings(paths) - builder := strings.Builder{} - for _, path := range paths { - fmt.Fprintln(&builder, path) - } - return c.writeOutputString(builder.String()) + return c.writePaths(paths, writePathsOptions{ + tree: c.managed.tree, + }) } diff --git a/internal/cmd/testdata/scripts/managedtree.txtar b/internal/cmd/testdata/scripts/managedtree.txtar new file mode 100644 index 00000000000..5d5f8c47063 --- /dev/null +++ b/internal/cmd/testdata/scripts/managedtree.txtar @@ -0,0 +1,20 @@ +mksourcedir + +# test that chezmoi managed --tree produces tree-like output +exec chezmoi managed --tree +cmp stdout golden/stdout + +-- golden/stdout -- +.create +.dir + file + subdir + file +.empty +.executable +.file +.private +.readonly +.remove +.symlink +.template
feat
Add --tree flag to managed command
c1a5b9265b8fb7ea981f036700c1f31a276f533f
2022-09-01 08:07:52
dependabot[bot]
chore(deps): bump actions/setup-go from 3.2.1 to 3.3.0
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 5414a324629..a9c2a3a96a9 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -123,7 +123,7 @@ jobs: runs-on: ubuntu-18.04 steps: - uses: actions/checkout@2541b1294d2704b0964813337f33b291d3f8596b - - uses: actions/setup-go@84cbf8094393cdc5fe1fe1671ff2647332956b1a + - uses: actions/setup-go@268d8c0ca0432bb2cf416faae41297df9d262d7f with: cache: true go-version: ${{ matrix.go-version }} @@ -150,7 +150,7 @@ jobs: runs-on: macos-11 steps: - uses: actions/checkout@2541b1294d2704b0964813337f33b291d3f8596b - - uses: actions/setup-go@84cbf8094393cdc5fe1fe1671ff2647332956b1a + - uses: actions/setup-go@268d8c0ca0432bb2cf416faae41297df9d262d7f with: cache: true go-version: ${{ env.GO_VERSION }} @@ -182,7 +182,7 @@ jobs: - uses: actions/checkout@2541b1294d2704b0964813337f33b291d3f8596b with: fetch-depth: 0 - - uses: actions/setup-go@84cbf8094393cdc5fe1fe1671ff2647332956b1a + - uses: actions/setup-go@268d8c0ca0432bb2cf416faae41297df9d262d7f with: cache: true go-version: ${{ env.GO_VERSION }} @@ -286,7 +286,7 @@ jobs: runs-on: windows-2019 steps: - uses: actions/checkout@2541b1294d2704b0964813337f33b291d3f8596b - - uses: actions/setup-go@84cbf8094393cdc5fe1fe1671ff2647332956b1a + - uses: actions/setup-go@268d8c0ca0432bb2cf416faae41297df9d262d7f with: cache: true go-version: ${{ env.GO_VERSION }} @@ -326,7 +326,7 @@ jobs: runs-on: ubuntu-18.04 steps: - uses: actions/checkout@2541b1294d2704b0964813337f33b291d3f8596b - - uses: actions/setup-go@84cbf8094393cdc5fe1fe1671ff2647332956b1a + - uses: actions/setup-go@268d8c0ca0432bb2cf416faae41297df9d262d7f with: cache: true go-version: ${{ env.GO_VERSION }} @@ -350,7 +350,7 @@ jobs: runs-on: ubuntu-18.04 steps: - uses: actions/checkout@2541b1294d2704b0964813337f33b291d3f8596b - - uses: actions/setup-go@84cbf8094393cdc5fe1fe1671ff2647332956b1a + - uses: actions/setup-go@268d8c0ca0432bb2cf416faae41297df9d262d7f with: cache: true go-version: ${{ env.GO_VERSION }} @@ -388,7 +388,7 @@ jobs: - uses: actions/checkout@2541b1294d2704b0964813337f33b291d3f8596b with: fetch-depth: 0 - - uses: actions/setup-go@84cbf8094393cdc5fe1fe1671ff2647332956b1a + - uses: actions/setup-go@268d8c0ca0432bb2cf416faae41297df9d262d7f with: cache: true go-version: ${{ env.GO_VERSION }}
chore
bump actions/setup-go from 3.2.1 to 3.3.0
14e337a4d35e4be55de9e6cc5ecd1c1fc24f759a
2021-11-23 00:35:21
Tom Payne
chore: Don't panic when logging HTTP timeouts
false
diff --git a/internal/chezmoi/sourcestate.go b/internal/chezmoi/sourcestate.go index 2ae1d04e771..ec454aa1253 100644 --- a/internal/chezmoi/sourcestate.go +++ b/internal/chezmoi/sourcestate.go @@ -1153,12 +1153,19 @@ func (s *SourceState) getExternalDataRaw( return nil, err } resp, err := s.httpClient.Do(req) - s.logger.Err(err). - Str("method", req.Method). - Int("statusCode", resp.StatusCode). - Str("status", resp.Status). - Stringer("url", req.URL). - Msg("HTTP") + if resp != nil { + s.logger.Err(err). + Str("method", req.Method). + Int("statusCode", resp.StatusCode). + Str("status", resp.Status). + Stringer("url", req.URL). + Msg("HTTP") + } else { + s.logger.Err(err). + Str("method", req.Method). + Stringer("url", req.URL). + Msg("HTTP") + } if err != nil { return nil, err } diff --git a/internal/cmd/upgradecmd.go b/internal/cmd/upgradecmd.go index 3be8db153a4..31f58a6480e 100644 --- a/internal/cmd/upgradecmd.go +++ b/internal/cmd/upgradecmd.go @@ -241,12 +241,19 @@ func (c *Config) downloadURL(ctx context.Context, url string) ([]byte, error) { return nil, err } resp, err := c.httpClient.Do(req) - c.logger.Err(err). - Str("method", req.Method). - Int("statusCode", resp.StatusCode). - Str("status", resp.Status). - Stringer("url", req.URL). - Msg("HTTP") + if resp != nil { + c.logger.Err(err). + Str("method", req.Method). + Int("statusCode", resp.StatusCode). + Str("status", resp.Status). + Stringer("url", req.URL). + Msg("HTTP") + } else { + c.logger.Err(err). + Str("method", req.Method). + Stringer("url", req.URL). + Msg("HTTP") + } if err != nil { return nil, err }
chore
Don't panic when logging HTTP timeouts
326359c246a9304abecf9429dcbf9224269c7ad7
2022-12-30 00:15:13
Tom Payne
chore: Rename identifiers for consistency
false
diff --git a/pkg/cmd/initcmd.go b/pkg/cmd/initcmd.go index aa6c99041a8..4cc212eb075 100644 --- a/pkg/cmd/initcmd.go +++ b/pkg/cmd/initcmd.go @@ -38,59 +38,59 @@ type initCmdConfig struct { ssh bool } -var dotfilesRepoGuesses = []struct { - rx *regexp.Regexp - httpRepoGuessRepl string - httpUsernameGuessRepl string - sshRepoGuessRepl string +var repoGuesses = []struct { + rx *regexp.Regexp + httpRepoGuessRepl string + sshRepoGuessRepl string + usernameGuessRepl string }{ { - rx: regexp.MustCompile(`\A([-0-9A-Za-z]+)\z`), - httpRepoGuessRepl: "https://github.com/$1/dotfiles.git", - httpUsernameGuessRepl: "$1", - sshRepoGuessRepl: "[email protected]:$1/dotfiles.git", + rx: regexp.MustCompile(`\A([-0-9A-Za-z]+)\z`), + httpRepoGuessRepl: "https://github.com/$1/dotfiles.git", + sshRepoGuessRepl: "[email protected]:$1/dotfiles.git", + usernameGuessRepl: "$1", }, { - rx: regexp.MustCompile(`\A([-0-9A-Za-z]+)/([-0-9A-Za-z]+)(\.git)?\z`), - httpRepoGuessRepl: "https://github.com/$1/$2.git", - httpUsernameGuessRepl: "$1", - sshRepoGuessRepl: "[email protected]:$1/$2.git", + rx: regexp.MustCompile(`\A([-0-9A-Za-z]+)/([-0-9A-Za-z]+)(\.git)?\z`), + httpRepoGuessRepl: "https://github.com/$1/$2.git", + sshRepoGuessRepl: "[email protected]:$1/$2.git", + usernameGuessRepl: "$1", }, { - rx: regexp.MustCompile(`\A([-.0-9A-Za-z]+)/([-0-9A-Za-z]+)\z`), - httpRepoGuessRepl: "https://$1/$2/dotfiles.git", - httpUsernameGuessRepl: "$2", - sshRepoGuessRepl: "git@$1:$2/dotfiles.git", + rx: regexp.MustCompile(`\A([-.0-9A-Za-z]+)/([-0-9A-Za-z]+)\z`), + httpRepoGuessRepl: "https://$1/$2/dotfiles.git", + sshRepoGuessRepl: "git@$1:$2/dotfiles.git", + usernameGuessRepl: "$2", }, { - rx: regexp.MustCompile(`\A([-0-9A-Za-z]+)/([-0-9A-Za-z]+)/([-.0-9A-Za-z]+)\z`), - httpRepoGuessRepl: "https://$1/$2/$3.git", - httpUsernameGuessRepl: "$2", - sshRepoGuessRepl: "git@$1:$2/$3.git", + rx: regexp.MustCompile(`\A([-0-9A-Za-z]+)/([-0-9A-Za-z]+)/([-.0-9A-Za-z]+)\z`), + httpRepoGuessRepl: "https://$1/$2/$3.git", + sshRepoGuessRepl: "git@$1:$2/$3.git", + usernameGuessRepl: "$2", }, { - rx: regexp.MustCompile(`\A([-.0-9A-Za-z]+)/([-0-9A-Za-z]+)/([-0-9A-Za-z]+)(\.git)?\z`), - httpRepoGuessRepl: "https://$1/$2/$3.git", - httpUsernameGuessRepl: "$2", - sshRepoGuessRepl: "git@$1:$2/$3.git", + rx: regexp.MustCompile(`\A([-.0-9A-Za-z]+)/([-0-9A-Za-z]+)/([-0-9A-Za-z]+)(\.git)?\z`), + httpRepoGuessRepl: "https://$1/$2/$3.git", + sshRepoGuessRepl: "git@$1:$2/$3.git", + usernameGuessRepl: "$2", }, { - rx: regexp.MustCompile(`\A(https?://)([-.0-9A-Za-z]+)/([-0-9A-Za-z]+)/([-0-9A-Za-z]+)(\.git)?\z`), - httpRepoGuessRepl: "$1$2/$3/$4.git", - httpUsernameGuessRepl: "$3", - sshRepoGuessRepl: "git@$2:$3/$4.git", + rx: regexp.MustCompile(`\A(https?://)([-.0-9A-Za-z]+)/([-0-9A-Za-z]+)/([-0-9A-Za-z]+)(\.git)?\z`), + httpRepoGuessRepl: "$1$2/$3/$4.git", + sshRepoGuessRepl: "git@$2:$3/$4.git", + usernameGuessRepl: "$3", }, { - rx: regexp.MustCompile(`\Asr\.ht/~([a-z_][a-z0-9_-]+)\z`), - httpRepoGuessRepl: "https://git.sr.ht/~$1/dotfiles", - httpUsernameGuessRepl: "$1", - sshRepoGuessRepl: "[email protected]:~$1/dotfiles", + rx: regexp.MustCompile(`\Asr\.ht/~([a-z_][a-z0-9_-]+)\z`), + httpRepoGuessRepl: "https://git.sr.ht/~$1/dotfiles", + sshRepoGuessRepl: "[email protected]:~$1/dotfiles", + usernameGuessRepl: "$1", }, { - rx: regexp.MustCompile(`\Asr\.ht/~([a-z_][a-z0-9_-]+)/([-0-9A-Za-z]+)\z`), - httpRepoGuessRepl: "https://git.sr.ht/~$1/$2", - httpUsernameGuessRepl: "$1", - sshRepoGuessRepl: "[email protected]:~$1/$2", + rx: regexp.MustCompile(`\Asr\.ht/~([a-z_][a-z0-9_-]+)/([-0-9A-Za-z]+)\z`), + httpRepoGuessRepl: "https://git.sr.ht/~$1/$2", + sshRepoGuessRepl: "[email protected]:~$1/$2", + usernameGuessRepl: "$1", }, } @@ -132,7 +132,7 @@ func (c *Config) newInitCmd() *cobra.Command { flags.BoolVarP(&c.init.purge, "purge", "p", c.init.purge, "Purge config and source directories after running") flags.BoolVarP(&c.init.purgeBinary, "purge-binary", "P", c.init.purgeBinary, "Purge chezmoi binary after running") flags.BoolVar(&c.init.recurseSubmodules, "recurse-submodules", c.init.recurseSubmodules, "Checkout submodules recursively") //nolint:lll - flags.BoolVar(&c.init.ssh, "ssh", c.init.ssh, "Use ssh instead of https when guessing dotfile repo URL") + flags.BoolVar(&c.init.ssh, "ssh", c.init.ssh, "Use ssh instead of https when guessing repo URL") return initCmd } @@ -169,14 +169,14 @@ func (c *Config) runInitCmd(cmd *cobra.Command, args []string) error { return err } } else { - var username, dotfilesRepoURL string + var username, repoURLStr string if c.init.guessRepoURL { - username, dotfilesRepoURL = guessDotfilesRepoURL(args[0], c.init.ssh) + username, repoURLStr = guessRepoURL(args[0], c.init.ssh) } else { - dotfilesRepoURL = args[0] + repoURLStr = args[0] } if useBuiltinGit { - if err := c.builtinGitClone(username, dotfilesRepoURL, workingTreeRawPath); err != nil { + if err := c.builtinGitClone(username, repoURLStr, workingTreeRawPath); err != nil { return err } } else { @@ -198,15 +198,15 @@ func (c *Config) runInitCmd(cmd *cobra.Command, args []string) error { "--depth", strconv.Itoa(c.init.depth), ) } - dotfilesRepoURL, err := url.Parse(dotfilesRepoURL) + repoURL, err := url.Parse(repoURLStr) if err != nil { return err } - if dotfilesRepoURL.User == nil { - dotfilesRepoURL.User = url.User(username) + if repoURL.User == nil { + repoURL.User = url.User(username) } args = append(args, - dotfilesRepoURL.String(), + repoURL.String(), workingTreeRawPath.String(), ) if err := c.run(chezmoi.EmptyAbsPath, c.Git.Command, args); err != nil { @@ -259,8 +259,8 @@ func (c *Config) runInitCmd(cmd *cobra.Command, args []string) error { } // builtinGitClone clones a repo using the builtin git command. -func (c *Config) builtinGitClone(username, url string, workingTreeRawPath chezmoi.AbsPath) error { - endpoint, err := transport.NewEndpoint(url) +func (c *Config) builtinGitClone(username, repoURLStr string, workingTreeRawPath chezmoi.AbsPath) error { + endpoint, err := transport.NewEndpoint(repoURLStr) if err != nil { return err } @@ -274,7 +274,7 @@ func (c *Config) builtinGitClone(username, url string, workingTreeRawPath chezmo referenceName = plumbing.NewBranchReferenceName(c.init.branch) } cloneOptions := git.CloneOptions{ - URL: url, + URL: repoURLStr, Depth: c.init.depth, ReferenceName: referenceName, RecurseSubmodules: git.DefaultSubmoduleRecursionDepth, @@ -291,7 +291,7 @@ func (c *Config) builtinGitClone(username, url string, workingTreeRawPath chezmo return err } - if _, err := fmt.Fprintf(c.stdout, "chezmoi: %s: %v\n", url, err); err != nil { + if _, err := fmt.Fprintf(c.stdout, "chezmoi: %s: %v\n", repoURLStr, err); err != nil { return err } var basicAuth http.BasicAuth @@ -360,19 +360,19 @@ func (o loggableGitCloneOptions) MarshalZerologObject(e *zerolog.Event) { } } -// guessDotfilesRepoURL guesses the user's username and dotfile repo from arg. -func guessDotfilesRepoURL(arg string, ssh bool) (username, repo string) { - for _, dotfileRepoGuess := range dotfilesRepoGuesses { - if !dotfileRepoGuess.rx.MatchString(arg) { +// guessRepoURL guesses the user's username and repo from arg. +func guessRepoURL(arg string, ssh bool) (username, repo string) { + for _, repoGuess := range repoGuesses { + if !repoGuess.rx.MatchString(arg) { continue } switch { - case ssh && dotfileRepoGuess.sshRepoGuessRepl != "": - repo = dotfileRepoGuess.rx.ReplaceAllString(arg, dotfileRepoGuess.sshRepoGuessRepl) + case ssh && repoGuess.sshRepoGuessRepl != "": + repo = repoGuess.rx.ReplaceAllString(arg, repoGuess.sshRepoGuessRepl) return - case !ssh && dotfileRepoGuess.httpRepoGuessRepl != "": - username = dotfileRepoGuess.rx.ReplaceAllString(arg, dotfileRepoGuess.httpUsernameGuessRepl) - repo = dotfileRepoGuess.rx.ReplaceAllString(arg, dotfileRepoGuess.httpRepoGuessRepl) + case !ssh && repoGuess.httpRepoGuessRepl != "": + username = repoGuess.rx.ReplaceAllString(arg, repoGuess.usernameGuessRepl) + repo = repoGuess.rx.ReplaceAllString(arg, repoGuess.httpRepoGuessRepl) return } } diff --git a/pkg/cmd/initcmd_test.go b/pkg/cmd/initcmd_test.go index 1730c960347..a43c158b0b3 100644 --- a/pkg/cmd/initcmd_test.go +++ b/pkg/cmd/initcmd_test.go @@ -12,7 +12,7 @@ import ( "github.com/twpayne/chezmoi/v2/pkg/chezmoitest" ) -func TestGuessDotfilesRepoURL(t *testing.T) { +func TestGuessRepoURL(t *testing.T) { for _, tc := range []struct { arg string expectedHTTPRepoURL string @@ -99,12 +99,12 @@ func TestGuessDotfilesRepoURL(t *testing.T) { } { t.Run(tc.arg, func(t *testing.T) { ssh := false - actualHTTPUsername, actualHTTPRepoURL := guessDotfilesRepoURL(tc.arg, ssh) + actualHTTPUsername, actualHTTPRepoURL := guessRepoURL(tc.arg, ssh) assert.Equal(t, tc.expectedHTTPUsername, actualHTTPUsername, "HTTPUsername") assert.Equal(t, tc.expectedHTTPRepoURL, actualHTTPRepoURL, "HTTPRepoURL") ssh = true - actualSSHUsername, actualSSHRepoURL := guessDotfilesRepoURL(tc.arg, ssh) + actualSSHUsername, actualSSHRepoURL := guessRepoURL(tc.arg, ssh) assert.Equal(t, "", actualSSHUsername, "SSHUsername") assert.Equal(t, tc.expectedSSHRepoURL, actualSSHRepoURL, "SSHRepoURL") })
chore
Rename identifiers for consistency
f4cde7d8706f31cfe50e6d25effec345587a95b5
2025-02-25 06:14:22
Tom Payne
chore: Tidy up install.sh generator
false
diff --git a/internal/cmds/generate-install.sh/main.go b/internal/cmds/generate-install.sh/main.go index a7b77eba8e3..8bb0674316e 100644 --- a/internal/cmds/generate-install.sh/main.go +++ b/internal/cmds/generate-install.sh/main.go @@ -2,6 +2,7 @@ package main import ( "cmp" + _ "embed" "encoding/json" "flag" "fmt" @@ -18,6 +19,9 @@ import ( var ( binDir = flag.String("b", "bin", "binary directory") output = flag.String("o", "", "output") + + //go:embed install.sh.tmpl + installShTmpl string ) type platform struct { @@ -114,7 +118,7 @@ func run() error { }) // Generate install.sh. - installShTemplate, err := template.ParseFiles("internal/cmds/generate-install.sh/install.sh.tmpl") + installShTemplate, err := template.New("install.sh.tmpl").Parse(installShTmpl) if err != nil { return err }
chore
Tidy up install.sh generator
9042768f8dcd0bd87ae59ab40f8f707194d3bad7
2024-08-15 18:20:53
Tom Payne
chore: Update dependencies
false
diff --git a/go.mod b/go.mod index b83bf7246ec..a48585f9abe 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.0-beta.12 + github.com/1password/onepassword-sdk-go v0.1.1 github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.7.0 github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.1.0 github.com/Masterminds/sprig/v3 v3.2.3 @@ -45,12 +45,12 @@ require ( github.com/zalando/go-keyring v0.2.5 github.com/zricethezav/gitleaks/v8 v8.18.4 go.etcd.io/bbolt v1.3.10 - golang.org/x/crypto v0.25.0 - golang.org/x/crypto/x509roots/fallback v0.0.0-20240726163919-3375612bf41a + golang.org/x/crypto v0.26.0 + golang.org/x/crypto/x509roots/fallback v0.0.0-20240806160748-b2d3a6a4b4d3 golang.org/x/oauth2 v0.22.0 golang.org/x/sync v0.8.0 - golang.org/x/sys v0.23.0 - golang.org/x/term v0.22.0 + golang.org/x/sys v0.24.0 + golang.org/x/term v0.23.0 gopkg.in/ini.v1 v1.67.0 gopkg.in/yaml.v3 v3.0.1 howett.net/plist v1.0.1 @@ -59,7 +59,7 @@ require ( require ( dario.cat/mergo v1.0.0 // indirect - github.com/Azure/azure-sdk-for-go/sdk/azcore v1.13.0 // indirect + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.14.0 // indirect github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0 // indirect github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.0.1 // indirect github.com/AzureAD/microsoft-authentication-library-for-go v1.2.2 // indirect @@ -82,7 +82,7 @@ require ( github.com/aws/aws-sdk-go-v2/service/sso v1.22.4 // indirect github.com/aws/aws-sdk-go-v2/service/ssooidc v1.26.4 // indirect github.com/aws/aws-sdk-go-v2/service/sts v1.30.3 // indirect - github.com/aws/smithy-go v1.20.3 // indirect + github.com/aws/smithy-go v1.20.4 // indirect github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect github.com/aymerick/douceur v0.2.0 // indirect github.com/bradenhilton/cityhash v1.0.0 // indirect @@ -145,19 +145,19 @@ require ( github.com/skeema/knownhosts v1.3.0 // indirect github.com/sourcegraph/conc v0.3.0 // indirect github.com/spf13/afero v1.11.0 // indirect - github.com/spf13/cast v1.6.0 // indirect + github.com/spf13/cast v1.7.0 // indirect github.com/spf13/viper v1.19.0 // indirect github.com/subosito/gotenv v1.6.0 // indirect - github.com/tetratelabs/wazero v1.7.3 // indirect + github.com/tetratelabs/wazero v1.8.0 // indirect github.com/xanzy/ssh-agent v0.3.3 // indirect github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect github.com/yuin/goldmark v1.7.4 // indirect github.com/yuin/goldmark-emoji v1.0.3 // indirect go.uber.org/multierr v1.11.0 // indirect - golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 // indirect - golang.org/x/net v0.27.0 // indirect - golang.org/x/text v0.16.0 // indirect - golang.org/x/tools v0.23.0 // indirect + golang.org/x/exp v0.0.0-20240808152545-0cdaa3abc0fa // indirect + golang.org/x/net v0.28.0 // indirect + golang.org/x/text v0.17.0 // indirect + golang.org/x/tools v0.24.0 // indirect gopkg.in/warnings.v0 v0.1.2 // indirect ) diff --git a/go.sum b/go.sum index 3f50da38292..ef70402e8eb 100644 --- a/go.sum +++ b/go.sum @@ -20,10 +20,10 @@ 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.0-beta.12 h1:v9b2fow1cutaCWRsIU1sVxVSzzR90mfkDCwYJeaadWc= -github.com/1password/onepassword-sdk-go v0.1.0-beta.12/go.mod h1:7wEQynLBXBC4svNx3X82QmCy0Adhm4e+UkM9t9mSSWA= -github.com/Azure/azure-sdk-for-go/sdk/azcore v1.13.0 h1:GJHeeA2N7xrG3q30L2UXDyuWRzDM900/65j70wcM4Ww= -github.com/Azure/azure-sdk-for-go/sdk/azcore v1.13.0/go.mod h1:l38EPgmsp71HHLq9j7De57JcKOWPyhrsW1Awm1JS6K0= +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/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.7.0 h1:tfLQ34V6F7tVSwoTf/4lH5sE0o6eCJuNDTmH09nDpbc= github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.7.0/go.mod h1:9kIvujWAA58nmPmWB1m23fyWic1kYZMxD9CxaWn4Qpg= github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0 h1:ywEEhmNahHBihViHepv3xPBn1663uRv2t2q/ESv9seY= @@ -92,8 +92,8 @@ github.com/aws/aws-sdk-go-v2/service/ssooidc v1.26.4 h1:yiwVzJW2ZxZTurVbYWA7QOrA github.com/aws/aws-sdk-go-v2/service/ssooidc v1.26.4/go.mod h1:0oxfLkpz3rQ/CHlx5hB7H69YUpFiI1tql6Q6Ne+1bCw= github.com/aws/aws-sdk-go-v2/service/sts v1.30.3 h1:ZsDKRLXGWHk8WdtyYMoGNO7bTudrvuKpDKgMVRlepGE= github.com/aws/aws-sdk-go-v2/service/sts v1.30.3/go.mod h1:zwySh8fpFyXp9yOr/KVzxOl8SRqgf/IDw5aUt9UKFcQ= -github.com/aws/smithy-go v1.20.3 h1:ryHwveWzPV5BIof6fyDvor6V3iUL7nTfiTKXHiW05nE= -github.com/aws/smithy-go v1.20.3/go.mod h1:krry+ya/rV9RDcV/Q16kpu6ypI4K2czasz0NC3qS14E= +github.com/aws/smithy-go v1.20.4 h1:2HK1zBdPgRbjFOHlfeQZfpC4r72MOb9bZkiFwggKO+4= +github.com/aws/smithy-go v1.20.4/go.mod h1:irrKGvNn1InZwb2d7fkIRNucdfwR8R+Ts3wxYa/cJHg= 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= github.com/aymanbagabas/go-udiff v0.2.0 h1:TK0fH4MteXUDspT88n8CKzvK0X9O2xu9yQjWpi6yML8= @@ -411,8 +411,8 @@ github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIK github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8= github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY= github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= -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/cast v1.7.0 h1:ntdiHjuueXFgm5nzDRdOS4yfT43P5Fnud6DH50rz/7w= +github.com/spf13/cast v1.7.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM= github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y= github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= @@ -439,8 +439,8 @@ github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8 github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= github.com/tailscale/hujson v0.0.0-20221223112325-20486734a56a h1:SJy1Pu0eH1C29XwJucQo73FrleVK6t4kYz4NVhp34Yw= github.com/tailscale/hujson v0.0.0-20221223112325-20486734a56a/go.mod h1:DFSS3NAGHthKo1gTlmEcSBiZrRJXi28rLNd/1udP1c8= -github.com/tetratelabs/wazero v1.7.3 h1:PBH5KVahrt3S2AHgEjKu4u+LlDbbk+nsGE3KLucy6Rw= -github.com/tetratelabs/wazero v1.7.3/go.mod h1:ytl6Zuh20R/eROuyDaGPkp82O9C/DJfXAwJfQ3X6/7Y= +github.com/tetratelabs/wazero v1.8.0 h1:iEKu0d4c2Pd+QSRieYbnQC9yiFlMS9D+Jr0LsRmcF4g= +github.com/tetratelabs/wazero v1.8.0/go.mod h1:yAI0XTsMBhREkM/YDAK/zNou3GoiAce1P6+rp/wQhjs= github.com/twpayne/go-expect v0.0.1 h1:cRJ552FIdQzs4z98Q2OLQsGLSbkB7Xpm/IU6cyQ6mUM= github.com/twpayne/go-expect v0.0.1/go.mod h1:+ffr+YtUt8ifebyvRQ3NhVTiLch/HnfxsAQqO5LeXss= github.com/twpayne/go-pinentry/v4 v4.0.0 h1:8WcNa+UDVRzz7y9OEEU/nRMX+UGFPCAvl5XsqWRxTY4= @@ -505,16 +505,16 @@ golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0 golang.org/x/crypto v0.3.0/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4= golang.org/x/crypto v0.3.1-0.20221117191849-2c476679df9a/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4= golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= -golang.org/x/crypto v0.25.0 h1:ypSNr+bnYL2YhwoMt2zPxHFmbAN1KZs/njMG3hxUp30= -golang.org/x/crypto v0.25.0/go.mod h1:T+wALwcMOSE0kXgUAnPAHqTLW+XHgcELELW8VaDgm/M= -golang.org/x/crypto/x509roots/fallback v0.0.0-20240726163919-3375612bf41a h1:+mrX96OoIUobm534myLOZMfVxVLWu/TpbYrUu6sn4tQ= -golang.org/x/crypto/x509roots/fallback v0.0.0-20240726163919-3375612bf41a/go.mod h1:kNa9WdvYnzFwC79zRpLRMJbdEFlhyM5RPFBBZp/wWH8= -golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 h1:2dVuKD2vS7b0QIHQbpyTISPd0LeHDbnYEryqj5Q1ug8= -golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56/go.mod h1:M4RDyNAINzryxdtnbRXRL/OHtkFuWGRjvuhBJpk2IlY= +golang.org/x/crypto v0.26.0 h1:RrRspgV4mU+YwB4FYnuBoKsUapNIL5cohGAmSH3azsw= +golang.org/x/crypto v0.26.0/go.mod h1:GY7jblb9wI+FOo5y8/S2oY4zWP07AkOJ4+jxCqdqn54= +golang.org/x/crypto/x509roots/fallback v0.0.0-20240806160748-b2d3a6a4b4d3 h1:oWb21rU9Q9XrRwXLB7jHc1rbp6EiiimZZv5MLxpu4T0= +golang.org/x/crypto/x509roots/fallback v0.0.0-20240806160748-b2d3a6a4b4d3/go.mod h1:kNa9WdvYnzFwC79zRpLRMJbdEFlhyM5RPFBBZp/wWH8= +golang.org/x/exp v0.0.0-20240808152545-0cdaa3abc0fa h1:ELnwvuAXPNtPk1TJRuGkI9fDTwym6AYBu0qzT8AcHdI= +golang.org/x/exp v0.0.0-20240808152545-0cdaa3abc0fa/go.mod h1:akd2r19cwCdwSwWeIdzYQGa/EZZyqcOdwWiwj5L5eKQ= 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.19.0 h1:fEdghXQSo20giMthA7cd28ZC+jts4amQ3YMXiP5oMQ8= -golang.org/x/mod v0.19.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/mod v0.20.0 h1:utOm6MM3R3dnawAiJgn0y+xvuYRsm1RKM/4giyfDgV0= +golang.org/x/mod v0.20.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= 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= @@ -522,8 +522,8 @@ golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug golang.org/x/net v0.2.0/go.mod h1:KqCZLdyyvdV855qA2rE3GC2aiw5xGR5TEjj8smXukLY= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= -golang.org/x/net v0.27.0 h1:5K3Njcw06/l2y9vpGCSdcxWOYHOUk3dVNGDXN+FvAys= -golang.org/x/net v0.27.0/go.mod h1:dDi0PyhWNoiUOrAS8uXv/vnScO4wnHQO4mj9fn/RytE= +golang.org/x/net v0.28.0 h1:a9JDOJc5GMUJ0+UDqmLT86WiEy7iWyIhz8gz8E4e5hE= +golang.org/x/net v0.28.0/go.mod h1:yqtgsTWOOnlGLG9GFRrK3++bGOUEkNBoHZc8MEDWPNg= golang.org/x/oauth2 v0.22.0 h1:BzDx2FehcG7jJwgWLELCdmLuxk2i+x9UDpSiss2u0ZA= golang.org/x/oauth2 v0.22.0/go.mod h1:XYTD2NtWslqkgxebSiOHnXEap4TF09sJSc7H1sXbhtI= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -550,8 +550,8 @@ golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 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.23.0 h1:YfKFowiIMvtgl1UERQoTPPToxltDeZfbj4H7dVUCwmM= -golang.org/x/sys v0.23.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg= +golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/telemetry v0.0.0-20240521205824-bda55230c457 h1:zf5N6UOrA487eEFacMePxjXAJctxKmyjKUsjA11Uzuk= golang.org/x/telemetry v0.0.0-20240521205824-bda55230c457/go.mod h1:pRgIJT+bRLFKnoM1ldnzKoxTIn14Yxz928LQRYYgIN0= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= @@ -559,8 +559,8 @@ golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuX golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= -golang.org/x/term v0.22.0 h1:BbsgPEJULsl2fV/AT3v15Mjva5yXKQDyKf+TbDz7QJk= -golang.org/x/term v0.22.0/go.mod h1:F3qCibpT5AMpCRfhfT53vVJwhLtIVHhB9XDjfFvnMI4= +golang.org/x/term v0.23.0 h1:F6D4vR+EHoL9/sWAWgAR1H2DcHr4PareCbAaCo1RpuU= +golang.org/x/term v0.23.0/go.mod h1:DgV24QBUrK6jhZXl+20l6UWznPlwAHm1Q1mGHtydmSk= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= @@ -568,16 +568,16 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= 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.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4= -golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI= +golang.org/x/text v0.17.0 h1:XtiM5bkSOt+ewxlOE/aE/AKEHibwj/6gvWMl9Rsh0Qc= +golang.org/x/text v0.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= 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= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/tools v0.23.0 h1:SGsXPZ+2l4JsgaCKkx+FQ9YZ5XEtA1GZYuoDjenLjvg= -golang.org/x/tools v0.23.0/go.mod h1:pnu6ufv6vQkll6szChhK3C3L/ruaIv5eBeztNG8wtsI= +golang.org/x/tools v0.24.0 h1:J1shsA93PJUEVaUSaay7UXAyE8aimq3GW0pjlolpa24= +golang.org/x/tools v0.24.0/go.mod h1:YhNqVBIfWHdzvTLs0d8LCuMhkKUgSUKldakyV7W/WDQ= 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=
chore
Update dependencies
8714b95999fcfc7247a3ee70e4232f438b610c82
2022-02-20 12:53:55
Tom Payne
chore: Tolerate GitHub rate limiting in tests
false
diff --git a/pkg/cmd/testdata/scripts/doctor_unix.txt b/pkg/cmd/testdata/scripts/doctor_unix.txt index fb259d4f1c9..93153569e4b 100644 --- a/pkg/cmd/testdata/scripts/doctor_unix.txt +++ b/pkg/cmd/testdata/scripts/doctor_unix.txt @@ -21,7 +21,7 @@ mksourcedir # test that chezmoi doctor behaves as expected chezmoi doctor stdout '^ok\s+version\s+' -stdout '^warning\s+latest-version\s+' +stdout '^\w+\s+latest-version\s+' stdout '^ok\s+os-arch\s+' ! stdout '^\S+\s+systeminfo\s+' stdout '^ok\s+uname\s+'
chore
Tolerate GitHub rate limiting in tests
8bb70ab636b2581ca564270f10a7698862c80770
2022-07-22 11:52:20
Tom Payne
chore: Rename variable for consistency
false
diff --git a/pkg/cmd/inittemplatefuncs.go b/pkg/cmd/inittemplatefuncs.go index f27346d11ef..1a5b133a57a 100644 --- a/pkg/cmd/inittemplatefuncs.go +++ b/pkg/cmd/inittemplatefuncs.go @@ -15,17 +15,17 @@ func (c *Config) exitInitTemplateFunc(code int) string { panic(chezmoi.ExitCodeError(code)) } -func (c *Config) promptBoolInitTemplateFunc(field string, args ...bool) bool { +func (c *Config) promptBoolInitTemplateFunc(prompt string, args ...bool) bool { switch len(args) { case 0: - value, err := parseBool(c.promptStringInitTemplateFunc(field)) + value, err := parseBool(c.promptStringInitTemplateFunc(prompt)) if err != nil { panic(err) } return value case 1: - promptStr := field + " (default " + strconv.FormatBool(args[0]) + ")" - valueStr := c.promptStringInitTemplateFunc(promptStr) + prompt += " (default " + strconv.FormatBool(args[0]) + ")" + valueStr := c.promptStringInitTemplateFunc(prompt) if valueStr == "" { return args[0] } @@ -40,16 +40,16 @@ func (c *Config) promptBoolInitTemplateFunc(field string, args ...bool) bool { } } -func (c *Config) promptIntInitTemplateFunc(field string, args ...int64) int64 { +func (c *Config) promptIntInitTemplateFunc(prompt string, args ...int64) int64 { switch len(args) { case 0: - value, err := strconv.ParseInt(c.promptStringInitTemplateFunc(field), 10, 64) + value, err := strconv.ParseInt(c.promptStringInitTemplateFunc(prompt), 10, 64) if err != nil { panic(err) } return value case 1: - promptStr := field + " (default " + strconv.FormatInt(args[0], 10) + ")" + promptStr := prompt + " (default " + strconv.FormatInt(args[0], 10) + ")" valueStr := c.promptStringInitTemplateFunc(promptStr) if valueStr == "" { return args[0]
chore
Rename variable for consistency
d29344f043ae660d46a5bdea63dbc0a8075f499e
2022-06-05 03:17:05
Lue
fix: Improve quality of POSIX shell scripts
false
diff --git a/assets/scripts/install.sh b/assets/scripts/install.sh index 1b5f5673755..70b7c1732a5 100644 --- a/assets/scripts/install.sh +++ b/assets/scripts/install.sh @@ -7,19 +7,19 @@ set -e -BINDIR=${BINDIR:-./bin} -CHEZMOI_USER_REPO=${CHEZMOI_USER_REPO:-twpayne/chezmoi} +BINDIR="${BINDIR:-./bin}" +CHEZMOI_USER_REPO="${CHEZMOI_USER_REPO:-twpayne/chezmoi}" TAGARG=latest LOG_LEVEL=2 -EXECARGS= -GITHUB_DOWNLOAD=https://github.com/${CHEZMOI_USER_REPO}/releases/download +GITHUB_DOWNLOAD="https://github.com/${CHEZMOI_USER_REPO}/releases/download" -tmpdir=$(mktemp -d) -trap 'rm -rf ${tmpdir}' EXIT +tmpdir="$(mktemp -d)" +trap 'rm -rf -- "${tmpdir}"' EXIT +trap 'exit' INT TERM usage() { - this="$1" + this="${1}" cat <<EOF ${this}: download chezmoi and optionally run chezmoi @@ -33,13 +33,14 @@ EOF } main() { - parse_args "$@" + parse_args "${@}" + shift "$((OPTIND - 1))" - GOOS=$(get_goos) - GOARCH=$(get_goarch) + GOOS="$(get_goos)" + GOARCH="$(get_goarch)" check_goos_goarch "${GOOS}/${GOARCH}" - TAG="$(real_tag $TAGARG)" + TAG="$(real_tag "${TAGARG}")" VERSION="${TAG#v}" log_info "found version ${VERSION} for ${TAGARG}/${GOOS}/${GOARCH}" @@ -85,19 +86,18 @@ main() { # verify checksums hash_sha256_verify "${tmpdir}/${TARBALL}" "${tmpdir}/${CHECKSUMS}" - (cd "${tmpdir}" && untar "${TARBALL}") + (cd -- "${tmpdir}" && untar "${TARBALL}") # install binary if [ ! -d "${BINDIR}" ]; then install -d "${BINDIR}" fi BINARY="chezmoi${BINSUFFIX}" - install "${tmpdir}/${BINARY}" "${BINDIR}/" + install -t "${BINDIR}/" "${tmpdir}/${BINARY}" log_info "installed ${BINDIR}/${BINARY}" - if [ -n "${EXECARGS}" ]; then - # shellcheck disable=SC2086 - exec "${BINDIR}/${BINARY}" $EXECARGS + if [ -n "${1+n}" ]; then + exec "${BINDIR}/${BINARY}" "${@}" fi } @@ -106,23 +106,21 @@ parse_args() { case "${arg}" in b) BINDIR="${OPTARG}" ;; d) LOG_LEVEL=3 ;; - h | \?) usage "$0" ;; + h | \?) usage "${0}" ;; t) TAGARG="${OPTARG}" ;; *) return 1 ;; esac done - shift $((OPTIND - 1)) - EXECARGS="$*" } get_goos() { - os=$(uname -s | tr '[:upper:]' '[:lower:]') + 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:]') + kernel="$(uname -o | tr '[:upper:]' '[:lower:]')" case "${kernel}" in illumos*) goos="illumos" ;; solaris*) goos="solaris" ;; @@ -131,11 +129,11 @@ get_goos() { ;; *) goos="${os}" ;; esac - echo "${goos}" + printf '%s' "${goos}" } get_goarch() { - arch=$(uname -m) + arch="$(uname -m)" case "${arch}" in aarch64) goarch="arm64" ;; armv*) goarch="arm" ;; @@ -146,11 +144,11 @@ get_goarch() { x86_64) goarch="amd64" ;; *) goarch="${arch}" ;; esac - echo "${goarch}" + printf '%s' "${goarch}" } check_goos_goarch() { - case "$1" in + case "${1}" in darwin/amd64) return 0 ;; darwin/arm64) return 0 ;; freebsd/386) return 0 ;; @@ -178,7 +176,7 @@ check_goos_goarch() { windows/amd64) return 0 ;; windows/arm) return 0 ;; *) - echo "$1: unsupported platform" 1>&2 + printf '%s: unsupported platform\n' "${1}" 1>&2 return 1 ;; esac @@ -187,12 +185,12 @@ check_goos_goarch() { get_libc() { if is_command ldd; then case "$(ldd --version 2>&1 | tr '[:upper:]' '[:lower:]')" in - *glibc*|"*gnu libc*") - echo glibc + *glibc*|*"gnu libc"*) + printf glibc return ;; *musl*) - echo musl + printf musl return ;; esac @@ -200,7 +198,7 @@ get_libc() { if is_command getconf; then case "$(getconf GNU_LIBC_VERSION 2>&1)" in *glibc*) - echo glibc + printf glibc return ;; esac @@ -210,15 +208,15 @@ get_libc() { } real_tag() { - tag=$1 + 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") + 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=$(echo "${json}" | tr -s '\n' ' ' | sed 's/.*"tag_name":"//' | sed 's/".*//') + 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 @@ -227,25 +225,25 @@ real_tag() { return 1 fi log_debug "found tag ${real_tag} for ${tag}" - echo "${real_tag}" + printf '%s' "${real_tag}" } http_get() { - tmpfile=$(mktemp) - http_download "${tmpfile}" "$1" "$2" || return 1 - body=$(cat "${tmpfile}") + tmpfile="$(mktemp)" + http_download "${tmpfile}" "${1}" "${2}" || return 1 + body="$(cat "${tmpfile}")" rm -f "${tmpfile}" - echo "${body}" + printf '%s\n' "${body}" } http_download_curl() { - local_file=$1 - source_url=$2 - header=$3 + local_file="${1}" + source_url="${2}" + header="${3}" if [ -z "${header}" ]; then - code=$(curl -w '%{http_code}' -sL -o "${local_file}" "${source_url}") + 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}") + 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}" @@ -255,9 +253,9 @@ http_download_curl() { } http_download_wget() { - local_file=$1 - source_url=$2 - header=$3 + local_file="${1}" + source_url="${2}" + header="${3}" if [ -z "${header}" ]; then wget -q -O "${local_file}" "${source_url}" || return 1 else @@ -266,12 +264,12 @@ http_download_wget() { } http_download() { - log_debug "http_download $2" + log_debug "http_download ${2}" if is_command curl; then - http_download_curl "$@" || return 1 + http_download_curl "${@}" || return 1 return elif is_command wget; then - http_download_wget "$@" || return 1 + http_download_wget "${@}" || return 1 return fi log_crit "http_download unable to find wget or curl" @@ -279,19 +277,19 @@ http_download() { } hash_sha256() { - target=$1 + target="${1}" if is_command sha256sum; then - hash=$(sha256sum "${target}") || return 1 - echo "${hash}" | cut -d ' ' -f 1 + 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 - echo "${hash}" | cut -d ' ' -f 1 + 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 - echo "${hash}" | cut -d ' ' -f 1 + 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 - echo "${hash}" | cut -d ' ' -f a + 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 @@ -299,17 +297,17 @@ hash_sha256() { } hash_sha256_verify() { - target=$1 - checksums=$2 - basename=${target##*/} + target="${1}" + checksums="${2}" + basename="${target##*/}" - want=$(grep "${basename}" "${checksums}" 2>/dev/null | tr '\t' ' ' | cut -d ' ' -f 1) + 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}") + got="$(hash_sha256 "${target}")" if [ "${want}" != "${got}" ]; then log_err "hash_sha256_verify checksum for ${target} did not verify ${want} vs ${got}" return 1 @@ -317,11 +315,11 @@ hash_sha256_verify() { } untar() { - tarball=$1 + tarball="${1}" case "${tarball}" in *.tar.gz | *.tgz) tar -xzf "${tarball}" ;; *.tar) tar -xf "${tarball}" ;; - *.zip) unzip "${tarball}" ;; + *.zip) unzip -- "${tarball}" ;; *) log_err "untar unknown archive format for ${tarball}" return 1 @@ -330,27 +328,27 @@ untar() { } is_command() { - command -v "$1" >/dev/null + type "${1}" >/dev/null 2>&1 } log_debug() { [ 3 -le "${LOG_LEVEL}" ] || return 0 - echo debug "$@" 1>&2 + printf 'debug %s\n' "${*}" 1>&2 } log_info() { [ 2 -le "${LOG_LEVEL}" ] || return 0 - echo info "$@" 1>&2 + printf 'info %s\n' "${*}" 1>&2 } log_err() { [ 1 -le "${LOG_LEVEL}" ] || return 0 - echo error "$@" 1>&2 + printf 'error %s\n' "${*}" 1>&2 } log_crit() { [ 0 -le "${LOG_LEVEL}" ] || return 0 - echo critical "$@" 1>&2 + printf 'critical %s\n' "${*}" 1>&2 } -main "$@" +main "${@}" diff --git a/assets/scripts/stow-to-chezmoi.sh b/assets/scripts/stow-to-chezmoi.sh index cb797465d7b..35b4cb119b9 100755 --- a/assets/scripts/stow-to-chezmoi.sh +++ b/assets/scripts/stow-to-chezmoi.sh @@ -1,29 +1,31 @@ -#!/usr/bin/env bash +#!/bin/sh set -e -BASEDIR="${1:-$HOME}" +BASEDIR="${1:-${HOME}}" STOWDIR="${2:-dotfiles}" BASEDIR="$( - unset CDPATH - cd "${BASEDIR}" >/dev/null 2>&1 - pwd + unset -v CDPATH + cd -- "${BASEDIR}" >/dev/null 2>&1 + pwd && printf . )" +BASEDIR="${BASEDIR%??}" # if we have greadlink, use that -READLINK="$(which greadlink 2>/dev/null || which readlink)" +READLINK="$(command -v greadlink 2>/dev/null || command -v readlink)" removelink() { - [ -L "$1" ] && ( - LINK_DEST="$($READLINK -f "$1")" - rm "$1" - echo -ne "${LINK_DEST} ==> $1\t" - if cp -R "${LINK_DEST}" "$1"; then - echo "Done" + [ -h "${1}" ] && ( + LINK_DEST="$("${READLINK}" -f -- "${1}" && printf .)" + LINK_DEST="${LINK_DEST%??}" + rm -- "${1}" + printf '%s ==> %s\t' "${LINK_DEST}" "${1}" >&2 + if cp -r -- "${LINK_DEST}" "${1}"; then + printf 'Done\n' >&2 else - echo "FAILED" - return 1 + printf 'FAILED\n' >&2 + exit 1 fi ) } @@ -31,32 +33,37 @@ removelink() { work_file="$(mktemp)" act_file="$(mktemp)" -trap 'rm -f ${work_file} ${act_file}' EXIT +# attempt to clean up temporary files on exit +trap 'rm -f -- "${work_file}" "${act_file}"' EXIT +trap 'exit' INT TERM -find "${BASEDIR}" -not -path "${BASEDIR}/${STOWDIR}*" -type l >"${work_file}" || echo "Find skipped some files" +find "${BASEDIR}" \! -path '* +*' \! -path "${BASEDIR}/${STOWDIR}*" -type l >"${work_file}" || \ + printf "Find skipped some files\n" >&2 while read -r f; do - target="$($READLINK -f "${f}" || echo '')" - if [[ "${target}" == "${BASEDIR}/${STOWDIR}/"* ]]; then - echo "Add $f" - echo "${f}" >>"${act_file}" - fi + target="$("${READLINK}" -f -- "${f}" || :)" + case "${target}" in + "${BASEDIR}/${STOWDIR}/"*) + printf 'Add %s\n' "${f}" >&2 + printf '%s\n' "${f}" >>"${act_file}" + ;; + esac done <"${work_file}" -read -p "Migrate the above to chezmoi? y/N" -r migrate +printf 'Migrate the above to chezmoi? y/N ' >&2 +read -r migrate case "${migrate}" in -[Yy]*) - echo "Migrating..." - ;; -*) exit 1 ;; + [Yy]*) printf 'Migrating...\n' >&2 ;; + *) exit 1 ;; esac -mkdir -p "${BASEDIR}/.local/share" +mkdir -p -- "${BASEDIR}/.local/share" while read -r f; do if removelink "${f}"; then - chezmoi --source "${BASEDIR}/.local/share/chezmoi" --destination "${BASEDIR}" add "${f}" + chezmoi --source "${BASEDIR}/.local/share/chezmoi" --destination "${BASEDIR}" add -- "${f}" else - echo "Unable to move: $f" + printf 'Unable to move: %s\n' "${f}" >&2 fi done <"${act_file}" diff --git a/internal/cmds/generate-install.sh/install.sh.tmpl b/internal/cmds/generate-install.sh/install.sh.tmpl index 9699fe163e9..f8532c1c73c 100644 --- a/internal/cmds/generate-install.sh/install.sh.tmpl +++ b/internal/cmds/generate-install.sh/install.sh.tmpl @@ -7,19 +7,19 @@ set -e -BINDIR=${BINDIR:-./bin} -CHEZMOI_USER_REPO=${CHEZMOI_USER_REPO:-twpayne/chezmoi} +BINDIR="${BINDIR:-./bin}" +CHEZMOI_USER_REPO="${CHEZMOI_USER_REPO:-twpayne/chezmoi}" TAGARG=latest LOG_LEVEL=2 -EXECARGS= -GITHUB_DOWNLOAD=https://github.com/${CHEZMOI_USER_REPO}/releases/download +GITHUB_DOWNLOAD="https://github.com/${CHEZMOI_USER_REPO}/releases/download" -tmpdir=$(mktemp -d) -trap 'rm -rf ${tmpdir}' EXIT +tmpdir="$(mktemp -d)" +trap 'rm -rf -- "${tmpdir}"' EXIT +trap 'exit' INT TERM usage() { - this="$1" + this="${1}" cat <<EOF ${this}: download chezmoi and optionally run chezmoi @@ -33,13 +33,14 @@ EOF } main() { - parse_args "$@" + parse_args "${@}" + shift "$((OPTIND - 1))" - GOOS=$(get_goos) - GOARCH=$(get_goarch) + GOOS="$(get_goos)" + GOARCH="$(get_goarch)" check_goos_goarch "${GOOS}/${GOARCH}" - TAG="$(real_tag $TAGARG)" + TAG="$(real_tag "${TAGARG}")" VERSION="${TAG#v}" log_info "found version ${VERSION} for ${TAGARG}/${GOOS}/${GOARCH}" @@ -85,19 +86,18 @@ main() { # verify checksums hash_sha256_verify "${tmpdir}/${TARBALL}" "${tmpdir}/${CHECKSUMS}" - (cd "${tmpdir}" && untar "${TARBALL}") + (cd -- "${tmpdir}" && untar "${TARBALL}") # install binary if [ ! -d "${BINDIR}" ]; then install -d "${BINDIR}" fi BINARY="chezmoi${BINSUFFIX}" - install "${tmpdir}/${BINARY}" "${BINDIR}/" + install -t "${BINDIR}/" "${tmpdir}/${BINARY}" log_info "installed ${BINDIR}/${BINARY}" - if [ -n "${EXECARGS}" ]; then - # shellcheck disable=SC2086 - exec "${BINDIR}/${BINARY}" $EXECARGS + if [ -n "${1+n}" ]; then + exec "${BINDIR}/${BINARY}" "${@}" fi } @@ -106,23 +106,21 @@ parse_args() { case "${arg}" in b) BINDIR="${OPTARG}" ;; d) LOG_LEVEL=3 ;; - h | \?) usage "$0" ;; + h | \?) usage "${0}" ;; t) TAGARG="${OPTARG}" ;; *) return 1 ;; esac done - shift $((OPTIND - 1)) - EXECARGS="$*" } get_goos() { - os=$(uname -s | tr '[:upper:]' '[:lower:]') + 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:]') + kernel="$(uname -o | tr '[:upper:]' '[:lower:]')" case "${kernel}" in illumos*) goos="illumos" ;; solaris*) goos="solaris" ;; @@ -131,11 +129,11 @@ get_goos() { ;; *) goos="${os}" ;; esac - echo "${goos}" + printf '%s' "${goos}" } get_goarch() { - arch=$(uname -m) + arch="$(uname -m)" case "${arch}" in aarch64) goarch="arm64" ;; armv*) goarch="arm" ;; @@ -146,16 +144,16 @@ get_goarch() { x86_64) goarch="amd64" ;; *) goarch="${arch}" ;; esac - echo "${goarch}" + printf '%s' "${goarch}" } check_goos_goarch() { - case "$1" in + case "${1}" in {{- range .Platforms }} {{ .GOOS }}/{{ .GOARCH }}) return 0 ;; {{- end }} *) - echo "$1: unsupported platform" 1>&2 + printf '%s: unsupported platform\n' "${1}" 1>&2 return 1 ;; esac @@ -164,12 +162,12 @@ check_goos_goarch() { get_libc() { if is_command ldd; then case "$(ldd --version 2>&1 | tr '[:upper:]' '[:lower:]')" in - *glibc*|"*gnu libc*") - echo glibc + *glibc*|*"gnu libc"*) + printf glibc return ;; *musl*) - echo musl + printf musl return ;; esac @@ -177,7 +175,7 @@ get_libc() { if is_command getconf; then case "$(getconf GNU_LIBC_VERSION 2>&1)" in *glibc*) - echo glibc + printf glibc return ;; esac @@ -187,15 +185,15 @@ get_libc() { } real_tag() { - tag=$1 + 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") + 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=$(echo "${json}" | tr -s '\n' ' ' | sed 's/.*"tag_name":"//' | sed 's/".*//') + 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 @@ -204,25 +202,25 @@ real_tag() { return 1 fi log_debug "found tag ${real_tag} for ${tag}" - echo "${real_tag}" + printf '%s' "${real_tag}" } http_get() { - tmpfile=$(mktemp) - http_download "${tmpfile}" "$1" "$2" || return 1 - body=$(cat "${tmpfile}") + tmpfile="$(mktemp)" + http_download "${tmpfile}" "${1}" "${2}" || return 1 + body="$(cat "${tmpfile}")" rm -f "${tmpfile}" - echo "${body}" + printf '%s\n' "${body}" } http_download_curl() { - local_file=$1 - source_url=$2 - header=$3 + local_file="${1}" + source_url="${2}" + header="${3}" if [ -z "${header}" ]; then - code=$(curl -w '%{http_code}' -sL -o "${local_file}" "${source_url}") + 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}") + 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}" @@ -232,9 +230,9 @@ http_download_curl() { } http_download_wget() { - local_file=$1 - source_url=$2 - header=$3 + local_file="${1}" + source_url="${2}" + header="${3}" if [ -z "${header}" ]; then wget -q -O "${local_file}" "${source_url}" || return 1 else @@ -243,12 +241,12 @@ http_download_wget() { } http_download() { - log_debug "http_download $2" + log_debug "http_download ${2}" if is_command curl; then - http_download_curl "$@" || return 1 + http_download_curl "${@}" || return 1 return elif is_command wget; then - http_download_wget "$@" || return 1 + http_download_wget "${@}" || return 1 return fi log_crit "http_download unable to find wget or curl" @@ -256,19 +254,19 @@ http_download() { } hash_sha256() { - target=$1 + target="${1}" if is_command sha256sum; then - hash=$(sha256sum "${target}") || return 1 - echo "${hash}" | cut -d ' ' -f 1 + 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 - echo "${hash}" | cut -d ' ' -f 1 + 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 - echo "${hash}" | cut -d ' ' -f 1 + 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 - echo "${hash}" | cut -d ' ' -f a + 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 @@ -276,17 +274,17 @@ hash_sha256() { } hash_sha256_verify() { - target=$1 - checksums=$2 - basename=${target##*/} + target="${1}" + checksums="${2}" + basename="${target##*/}" - want=$(grep "${basename}" "${checksums}" 2>/dev/null | tr '\t' ' ' | cut -d ' ' -f 1) + 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}") + got="$(hash_sha256 "${target}")" if [ "${want}" != "${got}" ]; then log_err "hash_sha256_verify checksum for ${target} did not verify ${want} vs ${got}" return 1 @@ -294,11 +292,11 @@ hash_sha256_verify() { } untar() { - tarball=$1 + tarball="${1}" case "${tarball}" in *.tar.gz | *.tgz) tar -xzf "${tarball}" ;; *.tar) tar -xf "${tarball}" ;; - *.zip) unzip "${tarball}" ;; + *.zip) unzip -- "${tarball}" ;; *) log_err "untar unknown archive format for ${tarball}" return 1 @@ -307,27 +305,27 @@ untar() { } is_command() { - command -v "$1" >/dev/null + type "${1}" >/dev/null 2>&1 } log_debug() { [ 3 -le "${LOG_LEVEL}" ] || return 0 - echo debug "$@" 1>&2 + printf 'debug %s\n' "${*}" 1>&2 } log_info() { [ 2 -le "${LOG_LEVEL}" ] || return 0 - echo info "$@" 1>&2 + printf 'info %s\n' "${*}" 1>&2 } log_err() { [ 1 -le "${LOG_LEVEL}" ] || return 0 - echo error "$@" 1>&2 + printf 'error %s\n' "${*}" 1>&2 } log_crit() { [ 0 -le "${LOG_LEVEL}" ] || return 0 - echo critical "$@" 1>&2 + printf 'critical %s\n' "${*}" 1>&2 } -main "$@" +main "${@}"
fix
Improve quality of POSIX shell scripts
27938e654fa0c9e2b0692357540008c6fbb8870c
2021-11-01 02:00:37
Tom Payne
feat: Allow equivalent directory entries in source state and externals
false
diff --git a/internal/chezmoi/sourcestate.go b/internal/chezmoi/sourcestate.go index 363dd0e3768..74fad2e8c2b 100644 --- a/internal/chezmoi/sourcestate.go +++ b/internal/chezmoi/sourcestate.go @@ -803,7 +803,19 @@ func (s *SourceState) Read(ctx context.Context, options *ReadOptions) error { if s.Ignore(externalRelPath) { continue } - externalSourceStateEntries, err := s.readExternal(ctx, externalRelPath, s.externals[externalRelPath], options) + external := s.externals[externalRelPath] + parentRelPath, _ := externalRelPath.Split() + var parentSourceRelPath SourceRelPath + dirAttr := DirAttr{ + Exact: external.Exact, + } + switch parentSourceStateEntry, err := s.root.MkdirAll(parentRelPath, dirAttr, external.URL, s.umask); { + case err != nil: + return err + case parentSourceStateEntry != nil: + parentSourceRelPath = parentSourceStateEntry.SourceRelPath() + } + externalSourceStateEntries, err := s.readExternal(ctx, externalRelPath, parentSourceRelPath, external, options) if err != nil { return err } @@ -874,6 +886,11 @@ func (s *SourceState) Read(ctx context.Context, options *ReadOptions) error { continue } + // Allow duplicate equivalent source entries for directories. + if allEquivalentDirs(sourceStateEntries) { + continue + } + origins := make([]string, 0, len(sourceStateEntries)) for _, sourceStateEntry := range sourceStateEntries { origins = append(origins, sourceStateEntry.Origin()) @@ -893,27 +910,6 @@ func (s *SourceState) Read(ctx context.Context, options *ReadOptions) error { s.root.Set(targetRelPath, sourceEntries[0]) } - // Generate directory entries for any missing directories. - generatedDirEntries := make(map[RelPath]*SourceStateDir) - _ = s.root.ForEachNode(EmptyRelPath, func(targetRelPath RelPath, node *sourceStateEntryTreeNode) error { - if targetRelPath.Empty() { - return nil - } - if node.sourceStateEntry != nil { - return nil - } - var sourceRelPath SourceRelPath - _, targetNameRelPath := targetRelPath.Split() - sourceStateDir := s.newSourceStateDir(sourceRelPath, DirAttr{ - TargetName: targetNameRelPath.String(), - }) - generatedDirEntries[targetRelPath] = sourceStateDir - return nil - }) - for targetRelPath, sourceStateDir := range generatedDirEntries { - s.root.Set(targetRelPath, sourceStateDir) - } - return nil } @@ -1588,12 +1584,12 @@ func (s *SourceState) newSourceStateFileEntryFromSymlink(actualStateSymlink *Act } // readExternal reads an external and returns its SourceStateEntries. -func (s *SourceState) readExternal(ctx context.Context, externalRelPath RelPath, external External, options *ReadOptions) (map[RelPath][]SourceStateEntry, error) { +func (s *SourceState) readExternal(ctx context.Context, externalRelPath RelPath, parentSourceRelPath SourceRelPath, external External, options *ReadOptions) (map[RelPath][]SourceStateEntry, error) { switch external.Type { case ExternalTypeArchive: - return s.readExternalArchive(ctx, externalRelPath, external, options) + return s.readExternalArchive(ctx, externalRelPath, parentSourceRelPath, external, options) case ExternalTypeFile: - return s.readExternalFile(ctx, externalRelPath, external, options) + return s.readExternalFile(ctx, externalRelPath, parentSourceRelPath, external, options) default: return nil, fmt.Errorf("%s: unknown external type: %s", externalRelPath, external.Type) } @@ -1601,7 +1597,7 @@ func (s *SourceState) readExternal(ctx context.Context, externalRelPath RelPath, // readExternalArchive reads an external archive and returns its // SourceStateEntries. -func (s *SourceState) readExternalArchive(ctx context.Context, externalRelPath RelPath, external External, options *ReadOptions) (map[RelPath][]SourceStateEntry, error) { +func (s *SourceState) readExternalArchive(ctx context.Context, externalRelPath RelPath, parentSourceRelPath SourceRelPath, external External, options *ReadOptions) (map[RelPath][]SourceStateEntry, error) { data, err := s.getExternalData(ctx, externalRelPath, external, options) if err != nil { return nil, err @@ -1615,26 +1611,28 @@ func (s *SourceState) readExternalArchive(ctx context.Context, externalRelPath R if external.Encrypted { urlPath = strings.TrimSuffix(urlPath, s.encryption.EncryptedSuffix()) } - sourceStateEntries := map[RelPath][]SourceStateEntry{ - externalRelPath: { - &SourceStateDir{ - Attr: DirAttr{ - TargetName: externalRelPath.Base(), - Exact: external.Exact, - }, - origin: external.URL, - targetStateEntry: &TargetStateDir{ - perm: 0o777 &^ s.umask, - }, - }, + dirAttr := DirAttr{ + TargetName: externalRelPath.Base(), + Exact: external.Exact, + } + sourceStateDir := &SourceStateDir{ + Attr: dirAttr, + origin: external.URL, + sourceRelPath: parentSourceRelPath.Join(NewSourceRelPath(dirAttr.SourceName())), + targetStateEntry: &TargetStateDir{ + perm: 0o777 &^ s.umask, }, } + sourceStateEntries := map[RelPath][]SourceStateEntry{ + externalRelPath: {sourceStateDir}, + } format := external.Format if format == ArchiveFormatUnknown { format = GuessArchiveFormat(urlPath, data) } + sourceRelPaths := make(map[RelPath]SourceRelPath) if err := walkArchive(data, format, func(name string, info fs.FileInfo, r io.Reader, linkname string) error { if external.StripComponents > 0 { components := strings.Split(name, "/") @@ -1652,20 +1650,25 @@ func (s *SourceState) readExternalArchive(ctx context.Context, externalRelPath R return nil } + dirTargetRelPath, _ := targetRelPath.Split() + dirSourceRelPath := sourceRelPaths[dirTargetRelPath] + var sourceStateEntry SourceStateEntry switch { case info.IsDir(): targetStateEntry := &TargetStateDir{ perm: info.Mode().Perm() &^ s.umask, } + dirAttr := DirAttr{ + TargetName: info.Name(), + Exact: external.Exact, + Private: isPrivate(info), + ReadOnly: isReadOnly(info), + } sourceStateEntry = &SourceStateDir{ - Attr: DirAttr{ - TargetName: info.Name(), - Exact: external.Exact, - Private: isPrivate(info), - ReadOnly: isReadOnly(info), - }, + Attr: dirAttr, origin: external.URL, + sourceRelPath: parentSourceRelPath.Join(dirSourceRelPath, NewSourceRelPath(dirAttr.SourceName())), targetStateEntry: targetStateEntry, } case info.Mode()&fs.ModeType == 0: @@ -1691,18 +1694,21 @@ func (s *SourceState) readExternalArchive(ctx context.Context, externalRelPath R lazyContents: lazyContents, Attr: fileAttr, origin: external.URL, + sourceRelPath: parentSourceRelPath.Join(dirSourceRelPath, NewSourceRelPath(fileAttr.SourceName(s.encryption.EncryptedSuffix()))), targetStateEntry: targetStateEntry, } case info.Mode()&fs.ModeType == fs.ModeSymlink: targetStateEntry := &TargetStateSymlink{ lazyLinkname: newLazyLinkname(linkname), } + fileAttr := FileAttr{ + TargetName: info.Name(), + Type: SourceFileTypeSymlink, + } sourceStateEntry = &SourceStateFile{ - Attr: FileAttr{ - TargetName: info.Name(), - Type: SourceFileTypeSymlink, - }, + Attr: fileAttr, origin: external.URL, + sourceRelPath: parentSourceRelPath.Join(dirSourceRelPath, NewSourceRelPath(fileAttr.SourceName(s.encryption.EncryptedSuffix()))), targetStateEntry: targetStateEntry, } default: @@ -1718,7 +1724,7 @@ func (s *SourceState) readExternalArchive(ctx context.Context, externalRelPath R } // readExternalFile reads an external file and returns its SourceStateEntries. -func (s *SourceState) readExternalFile(ctx context.Context, externalRelPath RelPath, external External, options *ReadOptions) (map[RelPath][]SourceStateEntry, error) { +func (s *SourceState) readExternalFile(ctx context.Context, externalRelPath RelPath, parentSourceRelPath SourceRelPath, external External, options *ReadOptions) (map[RelPath][]SourceStateEntry, error) { lazyContents := newLazyContentsFunc(func() ([]byte, error) { return s.getExternalData(ctx, externalRelPath, external, options) }) @@ -1733,6 +1739,7 @@ func (s *SourceState) readExternalFile(ctx context.Context, externalRelPath RelP } sourceStateEntry := &SourceStateFile{ origin: external.URL, + sourceRelPath: parentSourceRelPath.Join(NewSourceRelPath(fileAttr.SourceName(s.encryption.EncryptedSuffix()))), targetStateEntry: targetStateEntry, } return map[RelPath][]SourceStateEntry{ @@ -1755,3 +1762,22 @@ func (s *SourceState) sourceStateEntry(actualStateEntry ActualStateEntry, destAb panic(fmt.Sprintf("%T: unsupported type", actualStateEntry)) } } + +// allEquivalentDirs returns if sourceStateEntries are all equivalent +// directories. +func allEquivalentDirs(sourceStateEntries []SourceStateEntry) bool { + sourceStateDir0, ok := sourceStateEntries[0].(*SourceStateDir) + if !ok { + return false + } + for _, sourceStateEntry := range sourceStateEntries[1:] { + sourceStateDir, ok := sourceStateEntry.(*SourceStateDir) + if !ok { + return false + } + if sourceStateDir0.Attr != sourceStateDir.Attr { + return false + } + } + return true +} diff --git a/internal/chezmoi/sourcestate_test.go b/internal/chezmoi/sourcestate_test.go index be1d2216fdf..da88bcd5474 100644 --- a/internal/chezmoi/sourcestate_test.go +++ b/internal/chezmoi/sourcestate_test.go @@ -547,6 +547,72 @@ func TestSourceStateAdd(t *testing.T) { } } +func TestSourceStateAddInExternal(t *testing.T) { + buffer := &bytes.Buffer{} + 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()) + archiveData := buffer.Bytes() + + httpServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, err := w.Write(archiveData) + require.NoError(t, err) + })) + defer httpServer.Close() + + root := map[string]interface{}{ + "/home/user": map[string]interface{}{ + ".dir/file2": "# contents of .dir/file2\n", + ".local/share/chezmoi": map[string]interface{}{ + ".chezmoiexternal.toml": chezmoitest.JoinLines( + `[".dir"]`, + ` type = "archive"`, + ` url = "`+httpServer.URL+`/archive.tar"`, + ` stripComponents = 1`, + ), + "dot_dir": &vfst.Dir{Perm: 0o777}, + }, + }, + } + + chezmoitest.WithTestFS(t, root, func(fileSystem vfs.FS) { + ctx := context.Background() + system := NewRealSystem(fileSystem) + persistentState := NewMockPersistentState() + s := NewSourceState( + WithBaseSystem(system), + WithCacheDir(NewAbsPath("/home/user/.cache/chezmoi")), + WithDestDir(NewAbsPath("/home/user")), + WithSourceDir(NewAbsPath("/home/user/.local/share/chezmoi")), + WithSystem(system), + ) + require.NoError(t, s.Read(ctx, nil)) + + destAbsPath := NewAbsPath("/home/user/.dir/file2") + fileInfo, err := system.Stat(destAbsPath) + require.NoError(t, err) + destAbsPathInfos := map[AbsPath]fs.FileInfo{ + destAbsPath: fileInfo, + } + require.NoError(t, s.Add(system, persistentState, system, destAbsPathInfos, &AddOptions{ + Include: NewEntryTypeSet(EntryTypesAll), + })) + + vfst.RunTests(t, fileSystem, "", + vfst.TestPath("/home/user/.local/share/chezmoi/dot_dir", + vfst.TestIsDir, + vfst.TestModePerm(0o777&^chezmoitest.Umask), + ), + vfst.TestPath("/home/user/.local/share/chezmoi/dot_dir/file2", + vfst.TestModeIsRegular, + vfst.TestModePerm(0o666&^chezmoitest.Umask), + vfst.TestContentsString("# contents of .dir/file2\n"), + ), + ) + }) +} + func TestSourceStateApplyAll(t *testing.T) { for _, tc := range []struct { name string diff --git a/internal/chezmoi/sourcestatetreenode.go b/internal/chezmoi/sourcestatetreenode.go index 067eead7687..62d09f64d91 100644 --- a/internal/chezmoi/sourcestatetreenode.go +++ b/internal/chezmoi/sourcestatetreenode.go @@ -1,6 +1,10 @@ package chezmoi -import "sort" +import ( + "fmt" + "io/fs" + "sort" +) // A sourceStateEntryTreeNode is a node in a tree of SourceStateEntries. type sourceStateEntryTreeNode struct { @@ -81,6 +85,56 @@ func (n *sourceStateEntryTreeNode) Map() map[RelPath]SourceStateEntry { return m } +// MkdirAll creates SourceStateDirs for all components of targetRelPath if they +// do not already exist and returns the SourceStateDir of relPath. +func (n *sourceStateEntryTreeNode) MkdirAll(targetRelPath RelPath, dirAttr DirAttr, origin string, umask fs.FileMode) (*SourceStateDir, error) { + if targetRelPath == EmptyRelPath { + return nil, nil + } + + node := n + var sourceRelPath SourceRelPath + componentRelPaths := targetRelPath.SplitAll() + var sourceStateDir *SourceStateDir + for i, componentRelPath := range componentRelPaths { + if node.children == nil { + node.children = make(map[RelPath]*sourceStateEntryTreeNode) + } + if child, ok := node.children[componentRelPath]; ok { + node = child + } else { + child = newSourceStateTreeNode() + node.children[componentRelPath] = child + node = child + } + + switch { + case node.sourceStateEntry == nil: + attr := dirAttr + attr.TargetName = componentRelPath.String() + targetStateDir := &TargetStateDir{ + perm: attr.perm() &^ umask, + } + sourceRelPath = sourceRelPath.Join(NewSourceRelPath(attr.SourceName())) + sourceStateDir = &SourceStateDir{ + Attr: attr, + origin: origin, + sourceRelPath: sourceRelPath, + targetStateEntry: targetStateDir, + } + node.sourceStateEntry = sourceStateDir + default: + var ok bool + sourceStateDir, ok = node.sourceStateEntry.(*SourceStateDir) + if !ok { + return nil, fmt.Errorf("%s: not a directory", componentRelPaths[0].Join(componentRelPaths[1:i+1]...)) + } + sourceRelPath = sourceRelPath.Join(NewSourceRelPath(sourceStateDir.Attr.SourceName())) + } + } + return sourceStateDir, nil +} + // Set sets the SourceStateEntry at relPath to sourceStateEntry. func (n *sourceStateEntryTreeNode) Set(targetRelPath RelPath, sourceStateEntry SourceStateEntry) { if targetRelPath.Empty() { diff --git a/internal/cmd/testdata/scripts/external.txt b/internal/cmd/testdata/scripts/external.txt index a1a681748dd..6914919c05c 100644 --- a/internal/cmd/testdata/scripts/external.txt +++ b/internal/cmd/testdata/scripts/external.txt @@ -59,6 +59,11 @@ cmp $HOME/.dir1/file golden/dir/file cmp $HOME/.dir2/dir2/file golden/dir/file cmp $HOME/.dir3/dir3/dir3/file golden/dir/file +chhome home9/user + +# test that duplicate equivalent directories are allowed +chezmoi apply --force + -- archive/dir/file -- # contents of dir/file -- golden/.file -- @@ -120,5 +125,12 @@ subdir: type = "archive" url = "{{ env "HTTPD_URL" }}/archive.tar.gz" stripComponents = 2 +-- home9/user/.local/share/chezmoi/.chezmoiexternal.toml -- +[".dir"] + type = "archive" + url = "{{ env "HTTPD_URL" }}/archive.tar.gz" + stripComponents = 1 +-- home9/user/.local/share/chezmoi/dot_dir/file2 -- +# contents of .dir/file2 -- www/.file -- # contents of .file
feat
Allow equivalent directory entries in source state and externals
87c1a9155e17d174e00eadca101becb2075db418
2022-06-12 21:06:02
Cyrus Yip
docs: Use modeline to set filetype in VIM
false
diff --git a/assets/chezmoi.io/docs/user-guide/frequently-asked-questions/design.md b/assets/chezmoi.io/docs/user-guide/frequently-asked-questions/design.md index 0280bb270d3..3bfe692aa5a 100644 --- a/assets/chezmoi.io/docs/user-guide/frequently-asked-questions/design.md +++ b/assets/chezmoi.io/docs/user-guide/frequently-asked-questions/design.md @@ -30,7 +30,10 @@ merge-all` will help you resolve any differences. If you chose to edit files in the source state and you're using VIM then [`github.com/alker0/chezmoi.vim`](https://github.com/alker0/chezmoi.vim) gives -you syntax highlighting, however you edit your files. +you syntax highlighting, however you edit your files. Besides using the +plugin, you can use modeline to tell VIM the correct filetype. For example, +put `# vim: filetype=zsh` at the top of `dot_zshrc`, and VIM will treat +`dot_zshrc` as zsh file. ## Why doesn't chezmoi use symlinks like GNU Stow?
docs
Use modeline to set filetype in VIM
ba985c958ccbfa8d9d83aba2c0dc858c47e9a388
2023-08-13 23:07:11
Tom Payne
chore: Reformat long lines
false
diff --git a/internal/cmd/interactivetemplatefuncs.go b/internal/cmd/interactivetemplatefuncs.go index 455ec44d8b0..a9d73896df7 100644 --- a/internal/cmd/interactivetemplatefuncs.go +++ b/internal/cmd/interactivetemplatefuncs.go @@ -108,7 +108,11 @@ func (c *Config) promptBoolOnceInteractiveTemplateFunc( return c.promptBoolInteractiveTemplateFunc(prompt, args...) } -func (c *Config) promptChoiceInteractiveTemplateFunc(prompt string, choices []any, args ...string) string { +func (c *Config) promptChoiceInteractiveTemplateFunc( + prompt string, + choices []any, + args ...string, +) string { if len(args) > 1 { err := fmt.Errorf("want 2 or 3 arguments, got %d", len(args)+2) panic(err) @@ -130,7 +134,13 @@ func (c *Config) promptChoiceInteractiveTemplateFunc(prompt string, choices []an return value } -func (c *Config) promptChoiceOnceInteractiveTemplateFunc(m map[string]any, path any, prompt string, choices []any, args ...string) string { +func (c *Config) promptChoiceOnceInteractiveTemplateFunc( + m map[string]any, + path any, + prompt string, + choices []any, + args ...string, +) string { if len(args) > 1 { err := fmt.Errorf("want 4 or 5 arguments, got %d", len(args)+4) panic(err)
chore
Reformat long lines
511168f580311a4a337a0fc2d4f63dae268e85b9
2023-10-29 22:21:24
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 dbc9a1b8e16..7dc5a5e1cc9 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/v55/github#RepositoryRelease). +bindings](https://pkg.go.dev/github.com/google/go-github/v56/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/gitHubLatestTag.md b/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubLatestTag.md index 34154755801..6f5d39bbf88 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/v55/github#RepositoryTag). +bindings](https://pkg.go.dev/github.com/google/go-github/v56/github#RepositoryTag). Calls to `gitHubLatestTag` are cached the same as [`githubTags`](/reference/templates/functions/gitHubTags/), so calling 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 33f5fe36edb..b32908d7f4a 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/v55/github#RepositoryRelease). +bindings](https://pkg.go.dev/github.com/google/go-github/v56/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 0ec076305e2..68cee11126f 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/v55/github#RepositoryTag). +bindings](https://pkg.go.dev/github.com/google/go-github/v56/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 b61d5d2fbcf..e877d25818d 100644 --- a/go.mod +++ b/go.mod @@ -9,22 +9,22 @@ require ( github.com/Masterminds/sprig/v3 v3.2.3 github.com/Shopify/ejson v1.4.1 github.com/alecthomas/assert/v2 v2.4.0 - github.com/aws/aws-sdk-go-v2 v1.21.1 - github.com/aws/aws-sdk-go-v2/config v1.18.44 - github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.21.4 - github.com/bmatcuk/doublestar/v4 v4.6.0 + github.com/aws/aws-sdk-go-v2 v1.21.2 + github.com/aws/aws-sdk-go-v2/config v1.19.1 + github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.21.6 + github.com/bmatcuk/doublestar/v4 v4.6.1 github.com/bradenhilton/mozillainstallhash v1.0.1 github.com/charmbracelet/bubbles v0.16.1 github.com/charmbracelet/bubbletea v0.24.2 github.com/charmbracelet/glamour v0.6.0 github.com/coreos/go-semver v0.3.1 - github.com/fsnotify/fsnotify v1.6.0 - github.com/go-git/go-git/v5 v5.9.0 - github.com/google/go-github/v55 v55.0.0 + github.com/fsnotify/fsnotify v1.7.0 + github.com/go-git/go-git/v5 v5.10.0 + github.com/google/go-github/v56 v56.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.13 - github.com/klauspost/compress v1.17.0 + github.com/klauspost/compress v1.17.2 github.com/mitchellh/copystructure v1.2.0 github.com/mitchellh/mapstructure v1.5.0 github.com/muesli/combinator v0.3.0 @@ -43,7 +43,7 @@ require ( github.com/ulikunitz/xz v0.5.11 github.com/withfig/autocomplete-tools/integrations/cobra v1.2.1 github.com/zalando/go-keyring v0.2.3 - go.etcd.io/bbolt v1.3.7 + go.etcd.io/bbolt v1.3.8 golang.org/x/crypto v0.14.0 golang.org/x/exp v0.0.0-20231006140011-7918f672742d golang.org/x/oauth2 v0.13.0 @@ -59,7 +59,7 @@ require ( require ( dario.cat/mergo v1.0.0 // indirect github.com/Azure/azure-sdk-for-go/sdk/azcore v1.8.0 // indirect - github.com/Azure/azure-sdk-for-go/sdk/internal v1.3.0 // indirect + github.com/Azure/azure-sdk-for-go/sdk/internal v1.4.0 // indirect github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.0.0 // indirect github.com/AzureAD/microsoft-authentication-library-for-go v1.2.0 // indirect github.com/Masterminds/goutils v1.1.1 // indirect @@ -71,22 +71,22 @@ 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.13.42 // indirect - github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.13.12 // indirect - github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.42 // indirect - github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.36 // indirect - github.com/aws/aws-sdk-go-v2/internal/ini v1.3.44 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.36 // indirect - github.com/aws/aws-sdk-go-v2/service/sso v1.15.1 // indirect - github.com/aws/aws-sdk-go-v2/service/ssooidc v1.17.2 // indirect - github.com/aws/aws-sdk-go-v2/service/sts v1.23.1 // indirect + github.com/aws/aws-sdk-go-v2/credentials v1.13.43 // indirect + github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.13.13 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.43 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.37 // indirect + github.com/aws/aws-sdk-go-v2/internal/ini v1.3.45 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.37 // indirect + github.com/aws/aws-sdk-go-v2/service/sso v1.15.2 // indirect + github.com/aws/aws-sdk-go-v2/service/ssooidc v1.17.3 // indirect + github.com/aws/aws-sdk-go-v2/service/sts v1.23.2 // indirect github.com/aws/smithy-go v1.15.0 // indirect github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect github.com/aymerick/douceur v0.2.0 // indirect github.com/bradenhilton/cityhash v1.0.0 // indirect github.com/charmbracelet/harmonica v0.2.0 // indirect - github.com/charmbracelet/lipgloss v0.9.0 // indirect - github.com/cloudflare/circl v1.3.3 // indirect + github.com/charmbracelet/lipgloss v0.9.1 // indirect + github.com/cloudflare/circl v1.3.6 // indirect github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81 // indirect github.com/cyphar/filepath-securejoin v0.2.4 // indirect github.com/danieljoos/wincred v1.2.0 // indirect @@ -101,7 +101,7 @@ require ( github.com/golang/protobuf v1.5.3 // indirect github.com/google/btree v1.1.2 // indirect github.com/google/go-querystring v1.1.0 // indirect - github.com/google/uuid v1.3.1 // indirect + github.com/google/uuid v1.4.0 // indirect github.com/gorilla/css v1.0.0 // indirect github.com/hexops/gotextdiff v1.0.3 // indirect github.com/huandu/xstrings v1.4.0 // indirect @@ -113,7 +113,7 @@ require ( github.com/kylelemons/godebug v1.1.0 // indirect github.com/lucasb-eyer/go-colorful v1.2.0 // indirect github.com/mattn/go-colorable v0.1.13 // indirect - github.com/mattn/go-isatty v0.0.19 // 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.15 // indirect github.com/microcosm-cc/bluemonday v1.0.25 // indirect @@ -131,7 +131,7 @@ require ( github.com/skeema/knownhosts v1.2.1 // indirect github.com/spf13/cast v1.5.1 // indirect github.com/xanzy/ssh-agent v0.3.3 // indirect - github.com/yuin/goldmark v1.5.6 // indirect + github.com/yuin/goldmark v1.6.0 // indirect github.com/yuin/goldmark-emoji v1.0.2 // indirect golang.org/x/mod v0.13.0 // indirect golang.org/x/net v0.17.0 // indirect @@ -143,6 +143,7 @@ require ( ) exclude ( + github.com/microcosm-cc/bluemonday v1.0.26 // https://github.com/microcosm-cc/bluemonday/pull/195 github.com/sergi/go-diff v1.2.0 // https://github.com/sergi/go-diff/issues/123 github.com/sergi/go-diff v1.3.0 github.com/sergi/go-diff v1.3.1 // https://github.com/twpayne/chezmoi/issues/2706 diff --git a/go.sum b/go.sum index b0fc63731f4..e9acecdfdbc 100644 --- a/go.sum +++ b/go.sum @@ -12,8 +12,8 @@ github.com/Azure/azure-sdk-for-go/sdk/azcore v1.8.0 h1:9kDVnTz3vbfweTqAUmk/a/pH5 github.com/Azure/azure-sdk-for-go/sdk/azcore v1.8.0/go.mod h1:3Ug6Qzto9anB6mGlEdgYMDF5zHQ+wwhEaYR4s17PHMw= github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.4.0 h1:BMAjVKJM0U/CYF27gA0ZMmXGkOcvfFtD0oHVZ1TIPRI= github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.4.0/go.mod h1:1fXstnBMas5kzG+S3q8UoJcmyU6nUeunJcMDHcRYHhs= -github.com/Azure/azure-sdk-for-go/sdk/internal v1.3.0 h1:sXr+ck84g/ZlZUOZiNELInmMgOsuGwdjjVkEIde0OtY= -github.com/Azure/azure-sdk-for-go/sdk/internal v1.3.0/go.mod h1:okt5dMMTOFjX/aovMlrjvvXoPMBVSPzk9185BT0+eZM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.4.0 h1:TuEMD+E+1aTjjLICGQOW6vLe8UWES7kopac9mUXL56Y= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.4.0/go.mod h1:s4kgfzA0covAXNicZHDMN58jExvcng2mC/DepXiF1EI= github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.0.1 h1:8TkzQBrN9PWIwo7ekdd696KpC6IfTltV2/F8qKKBWik= github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.0.1/go.mod h1:aprFpXPQiTyG5Rkz6Ot5pvU6y6YKg/AKYOcLCoxN0bk= github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.0.0 h1:D3occbWoio4EBLkbkevetNMAVX197GkzbUMtqjGWn80= @@ -50,30 +50,30 @@ 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.21.1 h1:wjHYshtPpYOZm+/mu3NhVgRRc0baM6LJZOmxPZ5Cwzs= -github.com/aws/aws-sdk-go-v2 v1.21.1/go.mod h1:ErQhvNuEMhJjweavOYhxVkn2RUx7kQXVATHrjKtxIpM= -github.com/aws/aws-sdk-go-v2/config v1.18.44 h1:U10NQ3OxiY0dGGozmVIENIDnCT0W432PWxk2VO8wGnY= -github.com/aws/aws-sdk-go-v2/config v1.18.44/go.mod h1:pHxnQBldd0heEdJmolLBk78D1Bf69YnKLY3LOpFImlU= -github.com/aws/aws-sdk-go-v2/credentials v1.13.42 h1:KMkjpZqcMOwtRHChVlHdNxTUUAC6NC/b58mRZDIdcRg= -github.com/aws/aws-sdk-go-v2/credentials v1.13.42/go.mod h1:7ltKclhvEB8305sBhrpls24HGxORl6qgnQqSJ314Uw8= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.13.12 h1:3j5lrl9kVQrJ1BU4O0z7MQ8sa+UXdiLuo4j0V+odNI8= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.13.12/go.mod h1:JbFpcHDBdsex1zpIKuVRorZSQiZEyc3MykNCcjgz174= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.42 h1:817VqVe6wvwE46xXy6YF5RywvjOX6U2zRQQ6IbQFK0s= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.42/go.mod h1:oDfgXoBBmj+kXnqxDDnIDnC56QBosglKp8ftRCTxR+0= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.36 h1:7ZApaXzWbo8slc+W5TynuUlB4z66g44h7uqa3/d/BsY= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.36/go.mod h1:rwr4WnmFi3RJO0M4dxbJtgi9BPLMpVBMX1nUte5ha9U= -github.com/aws/aws-sdk-go-v2/internal/ini v1.3.44 h1:quOJOqlbSfeJTboXLjYXM1M9T52LBXqLoTPlmsKLpBo= -github.com/aws/aws-sdk-go-v2/internal/ini v1.3.44/go.mod h1:LNy+P1+1LiRcCsVYr/4zG5n8zWFL0xsvZkOybjbftm8= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.36 h1:YXlm7LxwNlauqb2OrinWlcvtsflTzP8GaMvYfQBhoT4= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.36/go.mod h1:ou9ffqJ9hKOVZmjlC6kQ6oROAyG1M4yBKzR+9BKbDwk= -github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.21.4 h1:LUtjmUxYPkiFkiVyvLmHVcuthVPnEKd0hEprTOVRTS0= -github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.21.4/go.mod h1:Bph0xA97xjEciochtR3JKrgGHt1psILMtFgu3KAbiBE= -github.com/aws/aws-sdk-go-v2/service/sso v1.15.1 h1:ZN3bxw9OYC5D6umLw6f57rNJfGfhg1DIAAcKpzyUTOE= -github.com/aws/aws-sdk-go-v2/service/sso v1.15.1/go.mod h1:PieckvBoT5HtyB9AsJRrYZFY2Z+EyfVM/9zG6gbV8DQ= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.17.2 h1:fSCCJuT5i6ht8TqGdZc5Q5K9pz/atrf7qH4iK5C9XzU= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.17.2/go.mod h1:5eNtr+vNc5vVd92q7SJ+U/HszsIdhZBEyi9dkMRKsp8= -github.com/aws/aws-sdk-go-v2/service/sts v1.23.1 h1:ASNYk1ypWAxRhJjKS0jBnTUeDl7HROOpeSMu1xDA/I8= -github.com/aws/aws-sdk-go-v2/service/sts v1.23.1/go.mod h1:2cnsAhVT3mqusovc2stUSUrSBGTcX9nh8Tu6xh//2eI= +github.com/aws/aws-sdk-go-v2 v1.21.2 h1:+LXZ0sgo8quN9UOKXXzAWRT3FWd4NxeXWOZom9pE7GA= +github.com/aws/aws-sdk-go-v2 v1.21.2/go.mod h1:ErQhvNuEMhJjweavOYhxVkn2RUx7kQXVATHrjKtxIpM= +github.com/aws/aws-sdk-go-v2/config v1.19.1 h1:oe3vqcGftyk40icfLymhhhNysAwk0NfiwkDi2GTPMXs= +github.com/aws/aws-sdk-go-v2/config v1.19.1/go.mod h1:ZwDUgFnQgsazQTnWfeLWk5GjeqTQTL8lMkoE1UXzxdE= +github.com/aws/aws-sdk-go-v2/credentials v1.13.43 h1:LU8vo40zBlo3R7bAvBVy/ku4nxGEyZe9N8MqAeFTzF8= +github.com/aws/aws-sdk-go-v2/credentials v1.13.43/go.mod h1:zWJBz1Yf1ZtX5NGax9ZdNjhhI4rgjfgsyk6vTY1yfVg= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.13.13 h1:PIktER+hwIG286DqXyvVENjgLTAwGgoeriLDD5C+YlQ= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.13.13/go.mod h1:f/Ib/qYjhV2/qdsf79H3QP/eRE4AkVyEf6sk7XfZ1tg= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.43 h1:nFBQlGtkbPzp/NjZLuFxRqmT91rLJkgvsEQs68h962Y= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.43/go.mod h1:auo+PiyLl0n1l8A0e8RIeR8tOzYPfZZH/JNlrJ8igTQ= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.37 h1:JRVhO25+r3ar2mKGP7E0LDl8K9/G36gjlqca5iQbaqc= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.37/go.mod h1:Qe+2KtKml+FEsQF/DHmDV+xjtche/hwoF75EG4UlHW8= +github.com/aws/aws-sdk-go-v2/internal/ini v1.3.45 h1:hze8YsjSh8Wl1rYa1CJpRmXP21BvOBuc76YhW0HsuQ4= +github.com/aws/aws-sdk-go-v2/internal/ini v1.3.45/go.mod h1:lD5M20o09/LCuQ2mE62Mb/iSdSlCNuj6H5ci7tW7OsE= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.37 h1:WWZA/I2K4ptBS1kg0kV1JbBtG/umed0vwHRrmcr9z7k= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.37/go.mod h1:vBmDnwWXWxNPFRMmG2m/3MKOe+xEcMDo1tanpaWCcck= +github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.21.6 h1:y3n83jEM6EuawrD5HZCh3eMj9RsfxniVLcXlyFMNITM= +github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.21.6/go.mod h1:A108ijf0IFtqhYApU+Gia80aPSAUfi9dItm+h5fWGJE= +github.com/aws/aws-sdk-go-v2/service/sso v1.15.2 h1:JuPGc7IkOP4AaqcZSIcyqLpFSqBWK32rM9+a1g6u73k= +github.com/aws/aws-sdk-go-v2/service/sso v1.15.2/go.mod h1:gsL4keucRCgW+xA85ALBpRFfdSLH4kHOVSnLMSuBECo= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.17.3 h1:HFiiRkf1SdaAmV3/BHOFZ9DjFynPHj8G/UIO1lQS+fk= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.17.3/go.mod h1:a7bHA82fyUXOm+ZSWKU6PIoBxrjSprdLoM8xPYvzYVg= +github.com/aws/aws-sdk-go-v2/service/sts v1.23.2 h1:0BkLfgeDjfZnZ+MhB3ONb01u9pwFYTCZVhlsSSBvlbU= +github.com/aws/aws-sdk-go-v2/service/sts v1.23.2/go.mod h1:Eows6e1uQEsc4ZaHANmsPRzAKcVDrcmjjWiih2+HUUQ= github.com/aws/smithy-go v1.15.0 h1:PS/durmlzvAFpQHDs4wi4sNNP9ExsqZh6IlfdHXgKK8= github.com/aws/smithy-go v1.15.0/go.mod h1:Tg+OJXh4MB2R/uN61Ko2f6hTZwB/ZYGOtib8J3gBHzA= github.com/aymanbagabas/go-osc52 v1.0.3 h1:DTwqENW7X9arYimJrPeGZcV0ln14sGMt3pHZspWD+Mg= @@ -82,8 +82,8 @@ github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiE github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= 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.0 h1:HTuxyug8GyFbRkrffIpzNCSK4luc0TY3wzXvzIZhEXc= -github.com/bmatcuk/doublestar/v4 v4.6.0/go.mod h1:xBQ8jztBU6kakFMg+8WGxn0c6z1fTSPVIjEY1Wr7jzc= +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/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= @@ -98,10 +98,11 @@ github.com/charmbracelet/glamour v0.6.0 h1:wi8fse3Y7nfcabbbDuwolqTqMQPMnVPeZhDM2 github.com/charmbracelet/glamour v0.6.0/go.mod h1:taqWV4swIMMbWALc0m7AfE9JkPSU8om2538k9ITBxOc= github.com/charmbracelet/harmonica v0.2.0 h1:8NxJWRWg/bzKqqEaaeFNipOu77YR5t8aSwG4pgaUBiQ= github.com/charmbracelet/harmonica v0.2.0/go.mod h1:KSri/1RMQOZLbw7AHqgcBycp8pgJnQMYYT8QZRqZ1Ao= -github.com/charmbracelet/lipgloss v0.9.0 h1:BHIM7U4vX77xGEld8GrTKspBMtSv7j0wxPCH73nrdxE= -github.com/charmbracelet/lipgloss v0.9.0/go.mod h1:h8KDyaivONasw1Bhb4nWiKlk4P1wHPly+3+3v6EFMmA= -github.com/cloudflare/circl v1.3.3 h1:fE/Qz0QdIGqeWfnwq0RE0R7MI51s0M2E4Ga9kq5AEMs= +github.com/charmbracelet/lipgloss v0.9.1 h1:PNyd3jvaJbg4jRHKWXnCj1akQm4rh8dbEzN1p/u1KWg= +github.com/charmbracelet/lipgloss v0.9.1/go.mod h1:1mPmG4cxScwUQALAAnacHaigiiHB9Pmr+v1VEawJl6I= github.com/cloudflare/circl v1.3.3/go.mod h1:5XYMA4rFBvNIrhs50XuiBJ15vF2pZn4nnUKZrLbUZFA= +github.com/cloudflare/circl v1.3.6 h1:/xbKIqSHbZXHwkhbrhrt2YOHIwYJlXH94E3tI/gDlUg= +github.com/cloudflare/circl v1.3.6/go.mod h1:5XYMA4rFBvNIrhs50XuiBJ15vF2pZn4nnUKZrLbUZFA= github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81 h1:q2hJAaP1k2wIvVRd/hEHD7lacgqrCPS+k8g1MndzfWY= github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81/go.mod h1:YynlIjWYF8myEu6sdkwKIvGQq+cOckRm6So2avqoYAk= github.com/coreos/go-semver v0.3.1 h1:yi21YpKnrx1gt5R+la8n5WgS0kCrsPp33dmEyHReZr4= @@ -134,18 +135,18 @@ github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ= github.com/frankban/quicktest v1.14.5 h1:dfYrrRyLtiqT9GyKXgdh+k4inNeTvmGbuSgZ3lx3GhA= github.com/frankban/quicktest v1.14.5/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= -github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= -github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= +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/gliderlabs/ssh v0.3.5 h1:OcaySEmAQJgyYcArR+gGGTHCyE7nvhEMTlYY+Dp8CpY= github.com/gliderlabs/ssh v0.3.5/go.mod h1:8XB4KraRrX39qHhT6yxPsHedjA08I/uBVwj4xC+/+z4= github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 h1:+zs/tPmkDkHx3U66DAb0lQFJrpS6731Oaa12ikc+DiI= github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376/go.mod h1:an3vInlBmSxCcxctByoQdvwPiA7DTK7jaaFDBTtu0ic= github.com/go-git/go-billy/v5 v5.5.0 h1:yEY4yhzCDuMGSv83oGxiBotRzhwhNr8VZyphhiu+mTU= github.com/go-git/go-billy/v5 v5.5.0/go.mod h1:hmexnoNsr2SJU1Ju67OaNz5ASJY3+sHgFRpCtpDCKow= -github.com/go-git/go-git-fixtures/v4 v4.3.2-0.20230305113008-0c11038e723f h1:Pz0DHeFij3XFhoBRGUDPzSJ+w2UcK5/0JvF8DRI58r8= -github.com/go-git/go-git-fixtures/v4 v4.3.2-0.20230305113008-0c11038e723f/go.mod h1:8LHG1a3SRW71ettAD/jW13h8c6AqjVSeL11RAdgaqpo= -github.com/go-git/go-git/v5 v5.9.0 h1:cD9SFA7sHVRdJ7AYck1ZaAa/yeuBvGPxwXDL8cxrObY= -github.com/go-git/go-git/v5 v5.9.0/go.mod h1:RKIqga24sWdMGZF+1Ekv9kylsDz6LzdTSI2s/OsZWE0= +github.com/go-git/go-git-fixtures/v4 v4.3.2-0.20231010084843-55a94097c399 h1:eMje31YglSBqCdIqdhKBW8lokaMrL3uTkpGYlE2OOT4= +github.com/go-git/go-git-fixtures/v4 v4.3.2-0.20231010084843-55a94097c399/go.mod h1:1OCfN199q1Jm3HZlxleg+Dw/mwps2Wbk9frAWm+4FII= +github.com/go-git/go-git/v5 v5.10.0 h1:F0x3xXrAWmhwtzoCokU4IMPcBdncG+HAAqi9FcOOjbQ= +github.com/go-git/go-git/v5 v5.10.0/go.mod h1:1FOZ/pQnqw24ghP2n7cunVl0ON55BsjPYvhWHvZGhoo= 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= @@ -166,15 +167,15 @@ github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/google/go-github/v55 v55.0.0 h1:4pp/1tNMB9X/LuAhs5i0KQAE40NmiR/y6prLNb9x9cg= -github.com/google/go-github/v55 v55.0.0/go.mod h1:JLahOTA1DnXzhxEymmFF5PP2tSS9JVNj68mSZNDwskA= +github.com/google/go-github/v56 v56.0.0 h1:TysL7dMa/r7wsQi44BjqlwaHvwlFlqkK8CtBWCX3gb4= +github.com/google/go-github/v56 v56.0.0/go.mod h1:D8cdcX98YWJvi7TLo7zM4/h8ZTx6u6fwGEkCdisopo0= 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= github.com/google/renameio/v2 v2.0.0/go.mod h1:BtmJXm5YlszgC+TD4HOEEUFgkJP3nLxehU6hfe7jRt4= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4= -github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.4.0 h1:MtMxsa51/r9yyhkyLsVeVt0B+BGQZzpQiTQ4eHZ8bc4= +github.com/google/uuid v1.4.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gopherjs/gopherjs v0.0.0-20200217142428-fce0ec30dd00 h1:l5lAOZEym3oK3SQ2HBHWsJUfbNBiTXJDeW2QDxw9AQ0= github.com/gopherjs/gopherjs v0.0.0-20200217142428-fce0ec30dd00/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/css v1.0.0 h1:BQqNyPTi50JCFMTw/b67hByjMVXZRwGha6wxVGkeihY= @@ -208,8 +209,8 @@ github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7 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.0 h1:Rnbp4K9EjcDuVuHtd0dgA4qNuv9yKDYKK1ulpJwgrqM= -github.com/klauspost/compress v1.17.0/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= +github.com/klauspost/compress v1.17.2 h1:RlWWUY/Dr4fL8qk9YG7DTZ7PDgME2V4csBXA8L/ixi4= +github.com/klauspost/compress v1.17.2/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= 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= @@ -227,8 +228,9 @@ github.com/matryer/is v1.2.0/go.mod h1:2fLPjFQM9rhQ15aVEtbuwhJinnOqrmgXPNdZsdwlW github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= -github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4= github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= @@ -351,15 +353,15 @@ github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9dec github.com/yuin/goldmark v1.3.7/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yuin/goldmark v1.5.2/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -github.com/yuin/goldmark v1.5.6 h1:COmQAWTCcGetChm3Ig7G/t8AFAN00t+o8Mt4cf7JpwA= -github.com/yuin/goldmark v1.5.6/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +github.com/yuin/goldmark v1.6.0 h1:boZcn2GTjpsynOsC0iJHnBWa4Bi0qzfJjthwauItG68= +github.com/yuin/goldmark v1.6.0/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yuin/goldmark-emoji v1.0.1/go.mod h1:2w1E6FEWLcDQkoTE+7HU6QF1F6SLlNGjRIBbIZQFqkQ= github.com/yuin/goldmark-emoji v1.0.2 h1:c/RgTShNgHTtc6xdz2KKI74jJr6rWi7FPgnP9GAsO5s= github.com/yuin/goldmark-emoji v1.0.2/go.mod h1:RhP/RWpexdp+KHs7ghKnifRoIs/Bq4nDS7tRbCkOwKY= github.com/zalando/go-keyring v0.2.3 h1:v9CUu9phlABObO4LPWycf+zwMG7nlbb3t/B5wa97yms= github.com/zalando/go-keyring v0.2.3/go.mod h1:HL4k+OXQfJUWaMnqyuSOc0drfGPX2b51Du6K+MRgZMk= -go.etcd.io/bbolt v1.3.7 h1:j+zJOnnEjF/kyHlDDgGnVL/AIqIJPq8UoB2GSNfkUfQ= -go.etcd.io/bbolt v1.3.7/go.mod h1:N9Mkw9X8x5fupy0IKsmuqVtoGDyxsaDlbk4Rd05IAQw= +go.etcd.io/bbolt v1.3.8 h1:xs88BrvEv273UsB79e0hcVrlUWmS0a8upikMFhSyAtA= +go.etcd.io/bbolt v1.3.8/go.mod h1:N9Mkw9X8x5fupy0IKsmuqVtoGDyxsaDlbk4Rd05IAQw= go.etcd.io/gofail v0.1.0 h1:XItAMIhOojXFQMgrxjnd2EIIHun/d5qL0Pf7FzVTkFg= go.etcd.io/gofail v0.1.0/go.mod h1:VZBCXYGZhHAinaBiiqYvuDynvahNsAyLFwB3kEHKz1M= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= @@ -405,7 +407,6 @@ golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/internal/chezmoi/github.go b/internal/chezmoi/github.go index 24a010af726..c03c485b3f8 100644 --- a/internal/chezmoi/github.go +++ b/internal/chezmoi/github.go @@ -5,7 +5,7 @@ import ( "net/http" "os" - "github.com/google/go-github/v55/github" + "github.com/google/go-github/v56/github" "golang.org/x/oauth2" ) diff --git a/internal/cmd/doctorcmd.go b/internal/cmd/doctorcmd.go index aea190c33d3..39ce11e4c30 100644 --- a/internal/cmd/doctorcmd.go +++ b/internal/cmd/doctorcmd.go @@ -19,7 +19,7 @@ import ( "time" "github.com/coreos/go-semver/semver" - "github.com/google/go-github/v55/github" + "github.com/google/go-github/v56/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 e2ea23def3f..dcda6746feb 100644 --- a/internal/cmd/githubtemplatefuncs.go +++ b/internal/cmd/githubtemplatefuncs.go @@ -6,7 +6,7 @@ import ( "strings" "time" - "github.com/google/go-github/v55/github" + "github.com/google/go-github/v56/github" "github.com/twpayne/chezmoi/v2/internal/chezmoi" ) diff --git a/internal/cmd/upgradecmd.go b/internal/cmd/upgradecmd.go index c36ba7c3e8d..a1e72f97c91 100644 --- a/internal/cmd/upgradecmd.go +++ b/internal/cmd/upgradecmd.go @@ -20,7 +20,7 @@ import ( "strings" "github.com/coreos/go-semver/semver" - "github.com/google/go-github/v55/github" + "github.com/google/go-github/v56/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 97b94be4fb8..f05dc8cc718 100644 --- a/internal/cmd/upgradecmd_unix.go +++ b/internal/cmd/upgradecmd_unix.go @@ -14,7 +14,7 @@ import ( "strings" "github.com/coreos/go-semver/semver" - "github.com/google/go-github/v55/github" + "github.com/google/go-github/v56/github" vfs "github.com/twpayne/go-vfs/v4" "github.com/twpayne/chezmoi/v2/internal/chezmoi" diff --git a/internal/cmd/upgradecmd_windows.go b/internal/cmd/upgradecmd_windows.go index a96c031b1f8..d7bde013580 100644 --- a/internal/cmd/upgradecmd_windows.go +++ b/internal/cmd/upgradecmd_windows.go @@ -11,7 +11,7 @@ import ( "path/filepath" "github.com/coreos/go-semver/semver" - "github.com/google/go-github/v55/github" + "github.com/google/go-github/v56/github" vfs "github.com/twpayne/go-vfs/v4" "github.com/twpayne/chezmoi/v2/internal/chezmoi" diff --git a/internal/cmds/execute-template/main.go b/internal/cmds/execute-template/main.go index 3f0911fdca9..cf589840ee0 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/v55/github" + "github.com/google/go-github/v56/github" "github.com/google/renameio/v2/maybe" "gopkg.in/yaml.v3"
chore
Update dependencies
3436563dd671dbd4f75bfc81cc8f27b4631d5332
2024-01-13 23:19:12
Tom Payne
fix: Improve robustness of keepassxc-cli integration in open mode
false
diff --git a/internal/cmd/keepassxctemplatefuncs.go b/internal/cmd/keepassxctemplatefuncs.go index 188fcfdad2f..651ab2c4fea 100644 --- a/internal/cmd/keepassxctemplatefuncs.go +++ b/internal/cmd/keepassxctemplatefuncs.go @@ -8,7 +8,9 @@ import ( "os" "os/exec" "regexp" + "strconv" "strings" + "time" "github.com/Netflix/go-expect" "github.com/coreos/go-semver/semver" @@ -72,7 +74,7 @@ func (c *Config) keepassxcAttachmentTemplateFunc(entry, name string) string { if err != nil { panic(err) } - tempFilename := tempDir.JoinString(name).String() + tempFilename := tempDir.JoinString("attachment-" + strconv.FormatInt(time.Now().UnixNano(), 10)).String() if _, err := c.keepassxcOutputOpen("attachment-export", "--quiet", entry, name, tempFilename); err != nil { panic(err) } @@ -246,8 +248,15 @@ func (c *Config) keepassxcOutputOpen(command string, args ...string) ([]byte, er c.Keepassxc.prompt = keepassxcPromptRx.FindString(output) } - // Send the command. - line := strings.Join(append([]string{command}, args...), " ") + // Build the command line. Strings with spaces and other non-word characters + // need to be quoted. + quotedArgs := make([]string, 0, len(args)) + for _, arg := range args { + quotedArgs = append(quotedArgs, maybeQuote(arg)) + } + line := strings.Join(append([]string{command}, quotedArgs...), " ") + + // Send the line. if _, err := c.Keepassxc.console.SendLine(line); err != nil { return nil, err } @@ -257,14 +266,22 @@ func (c *Config) keepassxcOutputOpen(command string, args ...string) ([]byte, er if err != nil { return nil, err } + outputLines := strings.Split(output, "\r\n") + + // Trim the echoed command from the output, which is the first line. + // keepassxc-cli version 2.7.6 on macOS inserts " \b" somewhere in the + // echoed command. Rather than trying to match this, remove the first line + // entirely. + if len(outputLines) > 0 { + outputLines = outputLines[1:] + } - // Trim the command from the output. - output = strings.TrimPrefix(output, line+"\r\n") - - // Trim the prompt from the output. - output = strings.TrimSuffix(output, c.Keepassxc.prompt) + // Trim the prompt from the output, which is the last line. + if len(outputLines) > 0 { + outputLines = outputLines[:len(outputLines)-1] + } - return []byte(output), nil + return []byte(strings.Join(outputLines, "\r\n")), nil } // keepassxcParseOutput parses a list of key-value pairs. diff --git a/internal/cmd/keepassxctemplatefuncs_test.go b/internal/cmd/keepassxctemplatefuncs_test.go index a9fc008459c..fefe722eda8 100644 --- a/internal/cmd/keepassxctemplatefuncs_test.go +++ b/internal/cmd/keepassxctemplatefuncs_test.go @@ -63,15 +63,16 @@ func TestKeepassxcTemplateFuncs(t *testing.T) { assert.NoError(t, err) tempDir := t.TempDir() - database := filepath.Join(tempDir, "Passwords.kdbx") - databasePassword := "test-database-password" - entryName := "test-entry" - entryUsername := "test-username" - entryPassword := "test-password" - attachmentName := "test-attachment-name" - attachmentData := "test-attachment-data" - importFile := filepath.Join(tempDir, "import-file") - assert.NoError(t, os.WriteFile(importFile, []byte(attachmentData), 0o666)) + + // The following test data includes spaces and slashes to test quoting. + database := filepath.Join(tempDir, "KeePassXC Passwords.kdbx") + databasePassword := "test / database / password" + groupName := "test group" + entryName := groupName + "/test entry" + entryUsername := "test / username" + entryPassword := "test / password" + attachmentName := "test / attachment name" + attachmentData := "test / attachment data" // Create a KeePassXC database. dbCreateCmd := exec.Command(command, "db-create", "--set-password", database) @@ -83,6 +84,15 @@ func TestKeepassxcTemplateFuncs(t *testing.T) { dbCreateCmd.Stderr = os.Stderr assert.NoError(t, dbCreateCmd.Run()) + // Create a group in the database. + mkdirCmd := exec.Command(command, "mkdir", database, groupName) + mkdirCmd.Stdin = strings.NewReader(chezmoitest.JoinLines( + databasePassword, + )) + mkdirCmd.Stdout = os.Stdout + mkdirCmd.Stderr = os.Stderr + assert.NoError(t, mkdirCmd.Run()) + // Create an entry in the database. addCmd := exec.Command(command, "add", database, entryName, "--username", entryUsername, "--password-prompt") addCmd.Stdin = strings.NewReader(chezmoitest.JoinLines( @@ -94,6 +104,8 @@ func TestKeepassxcTemplateFuncs(t *testing.T) { assert.NoError(t, addCmd.Run()) // Import an attachment to the entry in the database. + importFile := filepath.Join(tempDir, "import file") + assert.NoError(t, os.WriteFile(importFile, []byte(attachmentData), 0o666)) attachmentImportCmd := exec.Command(command, "attachment-import", database, entryName, attachmentName, importFile) attachmentImportCmd.Stdin = strings.NewReader(chezmoitest.JoinLines( databasePassword, diff --git a/internal/cmd/templatefuncs.go b/internal/cmd/templatefuncs.go index e7c27654512..8e1502d0dbe 100644 --- a/internal/cmd/templatefuncs.go +++ b/internal/cmd/templatefuncs.go @@ -675,11 +675,7 @@ func writeIniMap(w io.Writer, data map[string]any, sectionPrefix string) error { } subsections = append(subsections, subsection) case string: - if needsQuote(value) { - fmt.Fprintf(w, "%s = %q\n", key, value) - } else { - fmt.Fprintf(w, "%s = %s\n", key, value) - } + fmt.Fprintf(w, "%s = %s\n", key, maybeQuote(value)) default: return fmt.Errorf("%s%s: %T: unsupported type", sectionPrefix, key, value) } @@ -698,6 +694,13 @@ func writeIniMap(w io.Writer, data map[string]any, sectionPrefix string) error { return nil } +func maybeQuote(s string) string { + if needsQuote(s) { + return strconv.Quote(s) + } + return s +} + func needsQuote(s string) bool { if s == "" { return true diff --git a/internal/cmd/templatefuncs_test.go b/internal/cmd/templatefuncs_test.go index fc457741b0e..b48b00acd52 100644 --- a/internal/cmd/templatefuncs_test.go +++ b/internal/cmd/templatefuncs_test.go @@ -640,15 +640,17 @@ func TestToIniTemplateFunc(t *testing.T) { }{ { data: map[string]any{ - "bool": true, - "float": 1.0, - "int": 1, - "string": "string", + "bool": true, + "float": 1.0, + "int": 1, + "quotedString": "\"", + "string": "string", }, expected: chezmoitest.JoinLines( `bool = true`, `float = 1.000000`, `int = 1`, + `quotedString = "\""`, `string = string`, ), },
fix
Improve robustness of keepassxc-cli integration in open mode
9b28fcaab61f3dce8fa2339febcde49fce1caea1
2022-10-20 01:18:57
Tom Payne
feat: Add option to exclude scripts that are always run
false
diff --git a/assets/chezmoi.io/docs/reference/command-line-flags/common.md b/assets/chezmoi.io/docs/reference/command-line-flags/common.md index a32954c2fd7..44328eecde5 100644 --- a/assets/chezmoi.io/docs/reference/command-line-flags/common.md +++ b/assets/chezmoi.io/docs/reference/command-line-flags/common.md @@ -11,18 +11,19 @@ Set the output format. Include target state entries of type *types*. *types* is a comma-separated list of types: -| Type | Description | -| ----------- | --------------------- | -| `all` | All entries (default) | -| `none` | No entries | -| `dirs` | Directories | -| `files` | Files | -| `remove` | Removes | -| `scripts` | Scripts | -| `symlinks` | Symbolic links | -| `encrypted` | Encrypted entries | -| `externals` | External entries | -| `templates` | Templates | +| Type | Description | +| ----------- | --------------------------- | +| `all` | All entries (default) | +| `none` | No entries | +| `dirs` | Directories | +| `files` | Files | +| `remove` | Removes | +| `scripts` | Scripts | +| `symlinks` | Symbolic links | +| `always` | Scripts that are always run | +| `encrypted` | Encrypted entries | +| `externals` | External entries | +| `templates` | Templates | Types can be preceded with `no` to remove them. diff --git a/pkg/chezmoi/attr.go b/pkg/chezmoi/attr.go index b5145b9b452..29b58bb03c4 100644 --- a/pkg/chezmoi/attr.go +++ b/pkg/chezmoi/attr.go @@ -46,7 +46,8 @@ type ScriptCondition string // Script conditions. const ( - ScriptConditionAlways ScriptCondition = "" + ScriptConditionNone ScriptCondition = "" + ScriptConditionAlways ScriptCondition = "always" ScriptConditionOnce ScriptCondition = "once" ScriptConditionOnChange ScriptCondition = "onchange" ) @@ -166,7 +167,7 @@ func parseFileAttr(sourceName, encryptedSuffix string) FileAttr { var ( sourceFileType = SourceFileTypeFile name = sourceName - condition = ScriptConditionAlways + condition = ScriptConditionNone empty = false encrypted = false executable = false @@ -208,6 +209,8 @@ func parseFileAttr(sourceName, encryptedSuffix string) FileAttr { case strings.HasPrefix(name, onChangePrefix): name = mustTrimPrefix(name, onChangePrefix) condition = ScriptConditionOnChange + default: + condition = ScriptConditionAlways } switch { case strings.HasPrefix(name, beforePrefix): diff --git a/pkg/chezmoi/attr_test.go b/pkg/chezmoi/attr_test.go index afd40f2bee6..2ef6c8231c8 100644 --- a/pkg/chezmoi/attr_test.go +++ b/pkg/chezmoi/attr_test.go @@ -242,6 +242,7 @@ func TestFileAttrLiteral(t *testing.T) { sourceName: "run_literal_once_script", fileAttr: FileAttr{ TargetName: "once_script", + Condition: ScriptConditionAlways, Type: SourceFileTypeScript, }, }, diff --git a/pkg/chezmoi/entrytypeset.go b/pkg/chezmoi/entrytypeset.go index b6bead6d3f6..0e6b2dfb71c 100644 --- a/pkg/chezmoi/entrytypeset.go +++ b/pkg/chezmoi/entrytypeset.go @@ -30,6 +30,7 @@ const ( EntryTypeEncrypted EntryTypeExternals EntryTypeTemplates + EntryTypeAlways // EntryTypesAll is all entry types. EntryTypesAll EntryTypeBits = EntryTypeDirs | @@ -39,7 +40,8 @@ const ( EntryTypeSymlinks | EntryTypeEncrypted | EntryTypeExternals | - EntryTypeTemplates + EntryTypeTemplates | + EntryTypeAlways // EntryTypesNone is no entry types. EntryTypesNone EntryTypeBits = 0 @@ -49,6 +51,7 @@ var ( // entryTypeBits is a map from human-readable strings to EntryTypeBits. entryTypeBits = map[string]EntryTypeBits{ "all": EntryTypesAll, + "always": EntryTypeAlways, "dirs": EntryTypeDirs, "files": EntryTypeFiles, "remove": EntryTypeRemove, @@ -63,10 +66,12 @@ var ( entryTypeCompletions = []string{ "all", + "always", "dirs", "encrypted", "externals", "files", + "noalways", "nodirs", "noencrypted", "noexternals", @@ -149,6 +154,8 @@ func (s *EntryTypeSet) ContainsSourceStateEntry(sourceStateEntry SourceStateEntr return true case s.bits&EntryTypeSymlinks != 0 && sourceAttr.Type == SourceFileTypeSymlink: return true + case s.bits&EntryTypeAlways != 0 && sourceAttr.Condition == ScriptConditionAlways: + return true case s.bits&EntryTypeEncrypted != 0 && sourceAttr.Encrypted: return true case s.bits&EntryTypeExternals != 0 && !sourceStateEntry.origin.Path().Empty(): @@ -219,6 +226,8 @@ func (s *EntryTypeSet) ContainsTargetStateEntry(targetStateEntry TargetStateEntr return true case s.bits&EntryTypeTemplates != 0 && sourceAttr.Template: return true + case s.bits&EntryTypeAlways != 0 && sourceAttr.Condition == ScriptConditionAlways: + return true default: return false } diff --git a/pkg/chezmoi/entrytypeset_test.go b/pkg/chezmoi/entrytypeset_test.go index 53c5330ec7b..42d82006ee6 100644 --- a/pkg/chezmoi/entrytypeset_test.go +++ b/pkg/chezmoi/entrytypeset_test.go @@ -125,6 +125,7 @@ func TestEntryTypeSetFlagCompletionFunc(t *testing.T) { toComplete: "a", expectedCompletions: []string{ "all", + "always", }, }, { diff --git a/pkg/chezmoi/sourcestate.go b/pkg/chezmoi/sourcestate.go index f9518dbd1c6..0546503819a 100644 --- a/pkg/chezmoi/sourcestate.go +++ b/pkg/chezmoi/sourcestate.go @@ -1607,6 +1607,9 @@ func (s *SourceState) newScriptTargetStateEntryFunc( name: targetRelPath, condition: fileAttr.Condition, interpreter: interpreter, + sourceAttr: SourceAttr{ + Condition: fileAttr.Condition, + }, }, nil } } diff --git a/pkg/chezmoi/sourcestate_test.go b/pkg/chezmoi/sourcestate_test.go index f765d83f218..21e3f75875e 100644 --- a/pkg/chezmoi/sourcestate_test.go +++ b/pkg/chezmoi/sourcestate_test.go @@ -972,11 +972,16 @@ func TestSourceStateRead(t *testing.T) { Attr: FileAttr{ TargetName: "script", Type: SourceFileTypeScript, + Condition: ScriptConditionAlways, }, lazyContents: newLazyContents([]byte("# contents of .script\n")), targetStateEntry: &TargetStateScript{ name: NewRelPath("script"), lazyContents: newLazyContents([]byte("# contents of .script\n")), + condition: ScriptConditionAlways, + sourceAttr: SourceAttr{ + Condition: ScriptConditionAlways, + }, }, }, }), @@ -997,11 +1002,16 @@ func TestSourceStateRead(t *testing.T) { Attr: FileAttr{ TargetName: "script", Type: SourceFileTypeScript, + Condition: ScriptConditionAlways, }, lazyContents: newLazyContents([]byte("# contents of script\n")), targetStateEntry: &TargetStateScript{ name: NewRelPath("script"), lazyContents: newLazyContents([]byte("# contents of script\n")), + condition: ScriptConditionAlways, + sourceAttr: SourceAttr{ + Condition: ScriptConditionAlways, + }, }, }, }), diff --git a/pkg/chezmoi/sourcestateentry.go b/pkg/chezmoi/sourcestateentry.go index 9e02ae5edb6..dc130d6ee2f 100644 --- a/pkg/chezmoi/sourcestateentry.go +++ b/pkg/chezmoi/sourcestateentry.go @@ -11,6 +11,7 @@ import ( // A SourceAttr contains attributes of the source. type SourceAttr struct { + Condition ScriptCondition Encrypted bool External bool Template bool diff --git a/pkg/cmd/managedcmd_test.go b/pkg/cmd/managedcmd_test.go index 7b8b1edfaae..1fede37136a 100644 --- a/pkg/cmd/managedcmd_test.go +++ b/pkg/cmd/managedcmd_test.go @@ -60,7 +60,7 @@ func TestManagedCmd(t *testing.T) { "/home/user/.local/share/chezmoi/run_script.tmpl": "{{ fail \"Template should not be executed\" }}\n", }, args: []string{ - "--include", "scripts", + "--include", "always,scripts", }, expectedOutput: chezmoitest.JoinLines( "script", diff --git a/pkg/cmd/testdata/scripts/exclude.txtar b/pkg/cmd/testdata/scripts/exclude.txtar index 2a906ffdcb7..f0725e0d620 100644 --- a/pkg/cmd/testdata/scripts/exclude.txtar +++ b/pkg/cmd/testdata/scripts/exclude.txtar @@ -15,9 +15,24 @@ exec chezmoi diff [!windows] cmp stdout golden/diff-no-scripts.diff [windows] cmp stdout golden/diff-no-scripts-windows.diff +chhome home2/user + +# test that chezmoi diff --exclude=always excludes scripts that are always run +exec chezmoi diff --exclude=always +cmp stdout golden/diff-exclude-always.diff + -- golden/chezmoi.toml -- [diff] exclude = ["scripts"] +-- golden/diff-exclude-always.diff -- +diff --git a/script-once.sh b/script-once.sh +index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..d7dff6100cefc930f4161600c12b6f7ea37b7d3a 100755 +--- a/script-once.sh ++++ b/script-once.sh +@@ -0,0 +1,3 @@ ++#!/bin/sh ++ ++echo once -- golden/diff-no-scripts-windows.diff -- diff --git a/.file b/.file new file mode 100666 @@ -72,3 +87,11 @@ index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..3747a7ba08ee591c41b7c518e430d280 #!/bin/sh echo $* +-- home2/user/.local/share/chezmoi/run_once_script-once.sh -- +#!/bin/sh + +echo once +-- home2/user/.local/share/chezmoi/run_script-always.sh -- +#!/bin/sh + +echo always
feat
Add option to exclude scripts that are always run
24716ce712f068b862b6f68639e9b6d542650a05
2022-07-14 00:00:52
Tom Forbes
chore: Add https:// to the curl install command
false
diff --git a/assets/chezmoi.io/docs/index.md b/assets/chezmoi.io/docs/index.md index f750a39a99f..8827428a05a 100644 --- a/assets/chezmoi.io/docs/index.md +++ b/assets/chezmoi.io/docs/index.md @@ -7,7 +7,7 @@ dotfiles from your GitHub dotfiles repo on a new, empty machine with a single command: ```console -$ sh -c "$(curl -fsLS chezmoi.io/get)" -- init --apply $GITHUB_USERNAME +$ sh -c "$(curl -fsLS https://chezmoi.io/get)" -- init --apply $GITHUB_USERNAME ``` Updating your dotfiles on any machine is a single command: diff --git a/assets/chezmoi.io/docs/install.md.tmpl b/assets/chezmoi.io/docs/install.md.tmpl index 80012ef46cf..c5c6096d1c5 100644 --- a/assets/chezmoi.io/docs/install.md.tmpl +++ b/assets/chezmoi.io/docs/install.md.tmpl @@ -11,13 +11,13 @@ with a single command: === "curl" ```sh - sh -c "$(curl -fsLS chezmoi.io/get)" + sh -c "$(curl -fsLS https://chezmoi.io/get)" ``` === "wget" ```sh - sh -c "$(wget -qO- chezmoi.io/get)" + sh -c "$(wget -qO- https://chezmoi.io/get)" ``` === "PowerShell" @@ -33,7 +33,7 @@ with a single command: chezmoi and your dotfiles with the single command: ```sh - sh -c "$(curl -fsLS chezmoi.io/get)" -- init --apply $GITHUB_USERNAME + sh -c "$(curl -fsLS https://chezmoi.io/get)" -- init --apply $GITHUB_USERNAME ``` !!! hint @@ -42,7 +42,7 @@ with a single command: for example: ```sh - sh -c "$(curl -fsLS chezmoi.io/get)" -- -b $HOME/.local/bin + sh -c "$(curl -fsLS https://chezmoi.io/get)" -- -b $HOME/.local/bin ``` ## One-line package install diff --git a/assets/chezmoi.io/docs/user-guide/daily-operations.md b/assets/chezmoi.io/docs/user-guide/daily-operations.md index 9831250b032..7c14a472970 100644 --- a/assets/chezmoi.io/docs/user-guide/daily-operations.md +++ b/assets/chezmoi.io/docs/user-guide/daily-operations.md @@ -92,7 +92,7 @@ arguments to the newly installed chezmoi binary. If your dotfiles repo is shell: ```console -$ sh -c "$(curl -fsLS chezmoi.io/get)" -- init --apply $GITHUB_USERNAME +$ sh -c "$(curl -fsLS https://chezmoi.io/get)" -- init --apply $GITHUB_USERNAME ``` If your dotfiles repo has a different name to `dotfiles`, or if you host your @@ -105,5 +105,5 @@ chezmoi, including the source directory and chezmoi's configuration directory, with a single command: ```console -$ sh -c "$(curl -fsLS chezmoi.io/get)" -- init --one-shot $GITHUB_USERNAME +$ sh -c "$(curl -fsLS https://chezmoi.io/get)" -- init --one-shot $GITHUB_USERNAME ```
chore
Add https:// to the curl install command
b6aa1ebd46a2195b9bfaf9e1da2afc6e6a93fe8e
2021-01-24 11:09:26
Justin Grote
fix: Windows exe matching
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 7ee6f03d332..23a9131abf3 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -49,12 +49,16 @@ jobs: uses: actions/upload-artifact@v2 with: name: chezmoi2-${{ matrix.os }} - path: dist/chezmoi2 + path: | + dist/chezmoi2 + dist/chezmoi2.exe - name: Artifact uses: actions/upload-artifact@v2 with: name: chezmoi-${{ matrix.os }} - path: dist/chezmoi + path: | + dist/chezmoi + dist/chezmoi.exe test-release: runs-on: ubuntu-18.04 steps:
fix
Windows exe matching
431d2af0d0d536bdba49e94b5fc5c4c7e069017c
2022-06-13 06:17:24
Tom Payne
chore: Fix version numbers in links
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 87897ba6ed7..8ec76f04597 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 @@ -293,11 +293,11 @@ articles: title: "Fédérer une communauté technique autour d'un projet Open Source" url: 'https://www.podcastics.com/podcast/episode/federer-une-communaute-technique-autour-dun-projet-open-source-131694/' - date: '2022-06-02' - version: '2.17.2' + version: '2.17.1' title: 'Local Env as Code: Is it possible yet' url: https://www.cncf.io/blog/2022/06/02/local-env-as-code-is-it-possible-yet/ - date: '2022-06-11' - version: '2.17.2' + version: '2.17.1' title: 'chezmoi で Linux と macOS 両方で使える dotfiles を作る' lang: 'JP' url: https://www.docswell.com/s/iosiftakakura/K2EXM5-2022-06-11-chezmoi
chore
Fix version numbers in links
8feb68d14f693f2e723fd924fbc56a676539ea62
2023-05-01 23:58:59
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 2d4cc0f2dd4..37be81cd6fa 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/v51/github#RepositoryRelease). +bindings](https://pkg.go.dev/github.com/google/go-github/v52/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/gitHubLatestTag.md b/assets/chezmoi.io/docs/reference/templates/github-functions/gitHubLatestTag.md index 9fd366a4498..b836c1ef2ca 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/v51/github#RepositoryTag). +bindings](https://pkg.go.dev/github.com/google/go-github/v52/github#RepositoryTag). Calls to `gitHubLatestTag` are cached so calling `gitHubLatestTag` with the same *owner-repo* will only result in one call to the GitHub API. diff --git a/go.mod b/go.mod index 4887428ce7f..b79dc42ce21 100644 --- a/go.mod +++ b/go.mod @@ -6,9 +6,9 @@ require ( filippo.io/age v1.1.1 github.com/Masterminds/sprig/v3 v3.2.3 github.com/Shopify/ejson v1.3.3 - github.com/aws/aws-sdk-go-v2 v1.17.8 - github.com/aws/aws-sdk-go-v2/config v1.18.21 - github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.19.4 + github.com/aws/aws-sdk-go-v2 v1.18.0 + github.com/aws/aws-sdk-go-v2/config v1.18.22 + github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.19.6 github.com/bmatcuk/doublestar/v4 v4.6.0 github.com/bradenhilton/mozillainstallhash v1.0.1 github.com/charmbracelet/bubbles v0.15.0 @@ -17,7 +17,7 @@ require ( github.com/coreos/go-semver v0.3.1 github.com/fsnotify/fsnotify v1.6.0 github.com/go-git/go-git/v5 v5.6.1 - github.com/google/go-github/v51 v51.0.0 + github.com/google/go-github/v52 v52.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.12 @@ -42,7 +42,7 @@ require ( go.etcd.io/bbolt v1.3.7 go.uber.org/multierr v1.11.0 golang.org/x/crypto v0.8.0 - golang.org/x/exp v0.0.0-20230420155640-133eef4313cb + golang.org/x/exp v0.0.0-20230425010034-47ecfdc1ba53 golang.org/x/oauth2 v0.7.0 golang.org/x/sync v0.1.0 golang.org/x/sys v0.7.0 @@ -57,20 +57,20 @@ 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-20230417170513-8ee5748c52b5 // indirect + github.com/ProtonMail/go-crypto v0.0.0-20230426101702-58e86b294756 // indirect github.com/acomagu/bufpipe v1.0.4 // indirect github.com/alecthomas/chroma v0.10.0 // indirect github.com/alessio/shellescape v1.4.1 // indirect github.com/atotto/clipboard v0.1.4 // indirect - github.com/aws/aws-sdk-go-v2/credentials v1.13.20 // indirect - github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.13.2 // indirect - github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.32 // indirect - github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.26 // indirect - github.com/aws/aws-sdk-go-v2/internal/ini v1.3.33 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.26 // indirect - github.com/aws/aws-sdk-go-v2/service/sso v1.12.8 // indirect - github.com/aws/aws-sdk-go-v2/service/ssooidc v1.14.8 // indirect - github.com/aws/aws-sdk-go-v2/service/sts v1.18.9 // indirect + github.com/aws/aws-sdk-go-v2/credentials v1.13.21 // indirect + github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.13.3 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.33 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.27 // indirect + github.com/aws/aws-sdk-go-v2/internal/ini v1.3.34 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.27 // indirect + github.com/aws/aws-sdk-go-v2/service/sso v1.12.9 // indirect + github.com/aws/aws-sdk-go-v2/service/ssooidc v1.14.9 // indirect + github.com/aws/aws-sdk-go-v2/service/sts v1.18.10 // indirect github.com/aws/smithy-go v1.13.5 // 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 b272159d6a0..132c49f90f2 100644 --- a/go.sum +++ b/go.sum @@ -13,8 +13,8 @@ github.com/Microsoft/go-winio v0.5.2/go.mod h1:WpS1mjBmmwHBEWmogvA2mj8546UReBk4v 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-20230217124315-7d5c6f04bbb8/go.mod h1:I0gYDMZ6Z5GRU7l58bNFSkPTFN6Yl12dsUlAZ8xy98g= -github.com/ProtonMail/go-crypto v0.0.0-20230417170513-8ee5748c52b5 h1:QXMwHM/lB4ZQhdEF7JUTNgYOJR/gWoFbgQ/2Aj1h3Dk= -github.com/ProtonMail/go-crypto v0.0.0-20230417170513-8ee5748c52b5/go.mod h1:8TI4H3IbrackdNgv+92dI+rhpCaLqM0IfpgCgenFvRE= +github.com/ProtonMail/go-crypto v0.0.0-20230426101702-58e86b294756 h1:L6S7kR7SlhQKplIBpkra3s6yhcZV51lhRnXmYc4HohI= +github.com/ProtonMail/go-crypto v0.0.0-20230426101702-58e86b294756/go.mod h1:8TI4H3IbrackdNgv+92dI+rhpCaLqM0IfpgCgenFvRE= github.com/Shopify/ejson v1.3.3 h1:dPzgmvFhUPTJIzwdF5DaqbwW1dWaoR8ADKRdSTy6Mss= github.com/Shopify/ejson v1.3.3/go.mod h1:VZMUtDzvBW/PAXRUF5fzp1ffb1ucT8MztrZXXLYZurw= github.com/acomagu/bufpipe v1.0.4 h1:e3H4WUzM3npvo5uv95QuJM3cQspFNtFBzvJ2oNjKIDQ= @@ -29,30 +29,30 @@ 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.17.8 h1:GMupCNNI7FARX27L7GjCJM8NgivWbRgpjNI/hOQjFS8= -github.com/aws/aws-sdk-go-v2 v1.17.8/go.mod h1:uzbQtefpm44goOPmdKyAlXSNcwlRgF3ePWVW6EtJvvw= -github.com/aws/aws-sdk-go-v2/config v1.18.21 h1:ENTXWKwE8b9YXgQCsruGLhvA9bhg+RqAsL9XEMEsa2c= -github.com/aws/aws-sdk-go-v2/config v1.18.21/go.mod h1:+jPQiVPz1diRnjj6VGqWcLK6EzNmQ42l7J3OqGTLsSY= -github.com/aws/aws-sdk-go-v2/credentials v1.13.20 h1:oZCEFcrMppP/CNiS8myzv9JgOzq2s0d3v3MXYil/mxQ= -github.com/aws/aws-sdk-go-v2/credentials v1.13.20/go.mod h1:xtZnXErtbZ8YGXC3+8WfajpMBn5Ga/3ojZdxHq6iI8o= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.13.2 h1:jOzQAesnBFDmz93feqKnsTHsXrlwWORNZMFHMV+WLFU= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.13.2/go.mod h1:cDh1p6XkSGSwSRIArWRc6+UqAQ7x4alQ0QfpVR6f+co= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.32 h1:dpbVNUjczQ8Ae3QKHbpHBpfvaVkRdesxpTOe9pTouhU= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.32/go.mod h1:RudqOgadTWdcS3t/erPQo24pcVEoYyqj/kKW5Vya21I= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.26 h1:QH2kOS3Ht7x+u0gHCh06CXL/h6G8LQJFpZfFBYBNboo= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.26/go.mod h1:vq86l7956VgFr0/FWQ2BWnK07QC3WYsepKzy33qqY5U= -github.com/aws/aws-sdk-go-v2/internal/ini v1.3.33 h1:HbH1VjUgrCdLJ+4lnnuLI4iVNRvBbBELGaJ5f69ClA8= -github.com/aws/aws-sdk-go-v2/internal/ini v1.3.33/go.mod h1:zG2FcwjQarWaqXSCGpgcr3RSjZ6dHGguZSppUL0XR7Q= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.26 h1:uUt4XctZLhl9wBE1L8lobU3bVN8SNUP7T+olb0bWBO4= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.26/go.mod h1:Bd4C/4PkVGubtNe5iMXu5BNnaBi/9t/UsFspPt4ram8= -github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.19.4 h1:OExvHqoV5C/Ddo9KjPCf1HaQZC/h1jY1cCgWBivV8dY= -github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.19.4/go.mod h1:QNYziZIPDbKmKRoTHi9wkgqVidknyiGHfig1UNOojqk= -github.com/aws/aws-sdk-go-v2/service/sso v1.12.8 h1:5cb3D6xb006bPTqEfCNaEA6PPEfBXxxy4NNeX/44kGk= -github.com/aws/aws-sdk-go-v2/service/sso v1.12.8/go.mod h1:GNIveDnP+aE3jujyUSH5aZ/rktsTM5EvtKnCqBZawdw= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.14.8 h1:NZaj0ngZMzsubWZbrEFSB4rgSQRbFq38Sd6KBxHuOIU= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.14.8/go.mod h1:44qFP1g7pfd+U+sQHLPalAPKnyfTZjJsYR4xIwsJy5o= -github.com/aws/aws-sdk-go-v2/service/sts v1.18.9 h1:Qf1aWwnsNkyAoqDqmdM3nHwN78XQjec27LjM6b9vyfI= -github.com/aws/aws-sdk-go-v2/service/sts v1.18.9/go.mod h1:yyW88BEPXA2fGFyI2KCcZC3dNpiT0CZAHaF+i656/tQ= +github.com/aws/aws-sdk-go-v2 v1.18.0 h1:882kkTpSFhdgYRKVZ/VCgf7sd0ru57p2JCxz4/oN5RY= +github.com/aws/aws-sdk-go-v2 v1.18.0/go.mod h1:uzbQtefpm44goOPmdKyAlXSNcwlRgF3ePWVW6EtJvvw= +github.com/aws/aws-sdk-go-v2/config v1.18.22 h1:7vkUEmjjv+giht4wIROqLs+49VWmiQMMHSduxmoNKLU= +github.com/aws/aws-sdk-go-v2/config v1.18.22/go.mod h1:mN7Li1wxaPxSSy4Xkr6stFuinJGf3VZW3ZSNvO0q6sI= +github.com/aws/aws-sdk-go-v2/credentials v1.13.21 h1:VRiXnPEaaPeGeoFcXvMZOB5K/yfIXOYE3q97Kgb0zbU= +github.com/aws/aws-sdk-go-v2/credentials v1.13.21/go.mod h1:90Dk1lJoMyspa/EDUrldTxsPns0wn6+KpRKpdAWc0uA= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.13.3 h1:jJPgroehGvjrde3XufFIJUZVK5A2L9a3KwSFgKy9n8w= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.13.3/go.mod h1:4Q0UFP0YJf0NrsEuEYHpM9fTSEVnD16Z3uyEF7J9JGM= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.33 h1:kG5eQilShqmJbv11XL1VpyDbaEJzWxd4zRiCG30GSn4= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.33/go.mod h1:7i0PF1ME/2eUPFcjkVIwq+DOygHEoK92t5cDqNgYbIw= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.27 h1:vFQlirhuM8lLlpI7imKOMsjdQLuN9CPi+k44F/OFVsk= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.27/go.mod h1:UrHnn3QV/d0pBZ6QBAEQcqFLf8FAzLmoUfPVIueOvoM= +github.com/aws/aws-sdk-go-v2/internal/ini v1.3.34 h1:gGLG7yKaXG02/jBlg210R7VgQIotiQntNhsCFejawx8= +github.com/aws/aws-sdk-go-v2/internal/ini v1.3.34/go.mod h1:Etz2dj6UHYuw+Xw830KfzCfWGMzqvUTCjUj5b76GVDc= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.27 h1:0iKliEXAcCa2qVtRs7Ot5hItA2MsufrphbRFlz1Owxo= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.27/go.mod h1:EOwBD4J4S5qYszS5/3DpkejfuK+Z5/1uzICfPaZLtqw= +github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.19.6 h1:xC25kY/HSssnA1lC0GFT8mfhmrpMql/24bkyWYDRgzU= +github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.19.6/go.mod h1:3ARttS6G6U3auEdKfaN4GlnfS9UxYE9nqub1+0YGycA= +github.com/aws/aws-sdk-go-v2/service/sso v1.12.9 h1:GAiaQWuQhQQui76KjuXeShmyXqECwQ0mGRMc/rwsL+c= +github.com/aws/aws-sdk-go-v2/service/sso v1.12.9/go.mod h1:ouy2P4z6sJN70fR3ka3wD3Ro3KezSxU6eKGQI2+2fjI= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.14.9 h1:TraLwncRJkWqtIBVKI/UqBymq4+hL+3MzUOtUATuzkA= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.14.9/go.mod h1:AFvkxc8xfBe8XA+5St5XIHHrQQtkxqrRincx4hmMHOk= +github.com/aws/aws-sdk-go-v2/service/sts v1.18.10 h1:6UbNM/KJhMBfOI5+lpVcJ/8OA7cBSz0O6OX37SRKlSw= +github.com/aws/aws-sdk-go-v2/service/sts v1.18.10/go.mod h1:BgQOMsg8av8jset59jelyPW7NoZcZXLVpDsXunGDrk8= github.com/aws/smithy-go v1.13.5 h1:hgz0X/DX0dGqTYpGALqXJoRKRj5oQ7150i5FdTePzO8= github.com/aws/smithy-go v1.13.5/go.mod h1:Tg+OJXh4MB2R/uN61Ko2f6hTZwB/ZYGOtib8J3gBHzA= github.com/aymanbagabas/go-osc52 v1.0.3/go.mod h1:zT8H+Rk4VSabYN90pWyugflM3ZhpTZNC7cASDfUCdT4= @@ -136,8 +136,8 @@ github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/google/go-github/v51 v51.0.0 h1:KCjsbgPV28VoRftdP+K2mQL16jniUsLAJknsOVKwHyU= -github.com/google/go-github/v51 v51.0.0/go.mod h1:kZj/rn/c1lSUbr/PFWl2hhusPV7a5XNYKcwPrd5L3Us= +github.com/google/go-github/v52 v52.0.0 h1:uyGWOY+jMQ8GVGSX8dkSwCzlehU3WfdxQ7GweO/JP7M= +github.com/google/go-github/v52 v52.0.0/go.mod h1:WJV6VEEUPuMo5pXqqa2ZCZEdbQqua4zAk2MZTIo+m+4= 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= @@ -339,8 +339,8 @@ golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58 golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= golang.org/x/crypto v0.8.0 h1:pd9TJtTueMTVQXzk8E2XESSMQDj/U7OUu0PqJqPXQjQ= golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE= -golang.org/x/exp v0.0.0-20230420155640-133eef4313cb h1:rhjz/8Mbfa8xROFiH+MQphmAmgqRM0bOMnytznhWEXk= -golang.org/x/exp v0.0.0-20230420155640-133eef4313cb/go.mod h1:V1LtkGg67GoY2N1AnLN78QLrzxkLyJw7RJb1gzOOz9w= +golang.org/x/exp v0.0.0-20230425010034-47ecfdc1ba53 h1:5llv2sWeaMSnA3w2kS57ouQQ4pudlXrR0dCgw51QK9o= +golang.org/x/exp v0.0.0-20230425010034-47ecfdc1ba53/go.mod h1:V1LtkGg67GoY2N1AnLN78QLrzxkLyJw7RJb1gzOOz9w= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.6.0/go.mod h1:4mET923SAdbXp2ki8ey+zGs1SLqsuM2Y0uvdZR/fUNI= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= diff --git a/internal/cmds/execute-template/main.go b/internal/cmds/execute-template/main.go index ec7dbac0f97..0591d83c9b5 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/v51/github" + "github.com/google/go-github/v52/github" "github.com/google/renameio/v2/maybe" "gopkg.in/yaml.v3" diff --git a/pkg/chezmoi/github.go b/pkg/chezmoi/github.go index d028deb956f..2ed45167bc8 100644 --- a/pkg/chezmoi/github.go +++ b/pkg/chezmoi/github.go @@ -5,7 +5,7 @@ import ( "net/http" "os" - "github.com/google/go-github/v51/github" + "github.com/google/go-github/v52/github" "golang.org/x/oauth2" ) diff --git a/pkg/cmd/doctorcmd.go b/pkg/cmd/doctorcmd.go index 82c081d8fc2..2b42ff5e084 100644 --- a/pkg/cmd/doctorcmd.go +++ b/pkg/cmd/doctorcmd.go @@ -19,7 +19,7 @@ import ( "time" "github.com/coreos/go-semver/semver" - "github.com/google/go-github/v51/github" + "github.com/google/go-github/v52/github" "github.com/spf13/cobra" "github.com/twpayne/go-xdg/v6" diff --git a/pkg/cmd/githubtemplatefuncs.go b/pkg/cmd/githubtemplatefuncs.go index d6c336de60a..4f97f0e6f24 100644 --- a/pkg/cmd/githubtemplatefuncs.go +++ b/pkg/cmd/githubtemplatefuncs.go @@ -6,7 +6,7 @@ import ( "strings" "time" - "github.com/google/go-github/v51/github" + "github.com/google/go-github/v52/github" "github.com/twpayne/chezmoi/v2/pkg/chezmoi" ) diff --git a/pkg/cmd/upgradecmd.go b/pkg/cmd/upgradecmd.go index 6215f01cb10..90504f4ebae 100644 --- a/pkg/cmd/upgradecmd.go +++ b/pkg/cmd/upgradecmd.go @@ -20,7 +20,7 @@ import ( "strings" "github.com/coreos/go-semver/semver" - "github.com/google/go-github/v51/github" + "github.com/google/go-github/v52/github" "github.com/spf13/cobra" vfs "github.com/twpayne/go-vfs/v4"
chore
Update dependencies
116f8b7f1e29fae060174f3c50ca1010d1459a21
2024-11-08 04:01:34
Tom Payne
chore: Update dependencies
false
diff --git a/go.mod b/go.mod index b79387288ba..675d12e058b 100644 --- a/go.mod +++ b/go.mod @@ -6,18 +6,18 @@ require ( filippo.io/age v1.2.0 github.com/1password/onepassword-sdk-go v0.1.3 github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.8.0 - github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.2.0 + github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.3.0 github.com/Masterminds/sprig/v3 v3.3.0 github.com/Netflix/go-expect v0.0.0-20220104043353-73e0943537d2 - github.com/Shopify/ejson v1.5.2 + github.com/Shopify/ejson v1.5.3 github.com/alecthomas/assert/v2 v2.11.0 - github.com/aws/aws-sdk-go-v2 v1.32.3 - github.com/aws/aws-sdk-go-v2/config v1.28.1 - github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.34.3 + github.com/aws/aws-sdk-go-v2 v1.32.4 + github.com/aws/aws-sdk-go-v2/config v1.28.2 + github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.34.4 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.2 + github.com/charmbracelet/bubbletea v1.2.0 github.com/charmbracelet/glamour v0.8.0 github.com/coreos/go-semver v0.3.1 github.com/fsnotify/fsnotify v1.8.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-20241022195102-750a45fe5e47 + golang.org/x/crypto/x509roots/fallback v0.0.0-20241104001025-71ed71b4faf9 golang.org/x/oauth2 v0.23.0 golang.org/x/sync v0.8.0 golang.org/x/sys v0.26.0 @@ -64,32 +64,32 @@ require ( github.com/Azure/azure-sdk-for-go/sdk/azcore v1.16.0 // indirect github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0 // indirect github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.1.0 // indirect - github.com/AzureAD/microsoft-authentication-library-for-go v1.2.3 // indirect + github.com/AzureAD/microsoft-authentication-library-for-go v1.3.1 // indirect github.com/BobuSumisu/aho-corasick v1.0.3 // indirect github.com/Masterminds/goutils v1.1.1 // indirect github.com/Masterminds/semver/v3 v3.3.0 // indirect github.com/Microsoft/go-winio v0.6.2 // indirect - github.com/ProtonMail/go-crypto v1.0.0 // indirect + github.com/ProtonMail/go-crypto v1.1.0 // indirect github.com/alecthomas/chroma/v2 v2.14.0 // indirect github.com/alecthomas/repr v0.4.0 // indirect github.com/atotto/clipboard v0.1.4 // indirect - github.com/aws/aws-sdk-go-v2/credentials v1.17.42 // indirect - github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.18 // indirect - github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.22 // indirect - github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.22 // indirect + github.com/aws/aws-sdk-go-v2/credentials v1.17.43 // indirect + github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.19 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.23 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.23 // indirect github.com/aws/aws-sdk-go-v2/internal/ini v1.8.1 // indirect github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.0 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.3 // indirect - github.com/aws/aws-sdk-go-v2/service/sso v1.24.3 // indirect - github.com/aws/aws-sdk-go-v2/service/ssooidc v1.28.3 // indirect - github.com/aws/aws-sdk-go-v2/service/sts v1.32.3 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.4 // indirect + github.com/aws/aws-sdk-go-v2/service/sso v1.24.4 // indirect + github.com/aws/aws-sdk-go-v2/service/ssooidc v1.28.4 // indirect + github.com/aws/aws-sdk-go-v2/service/sts v1.32.4 // indirect github.com/aws/smithy-go v1.22.0 // indirect github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect github.com/aymerick/douceur v0.2.0 // indirect github.com/bradenhilton/cityhash v1.0.0 // indirect github.com/charmbracelet/harmonica v0.2.0 // indirect github.com/charmbracelet/lipgloss v1.0.0 // indirect - github.com/charmbracelet/x/ansi v0.4.2 // indirect + github.com/charmbracelet/x/ansi v0.4.5 // indirect github.com/charmbracelet/x/term v0.2.0 // indirect github.com/cloudflare/circl v1.5.0 // indirect github.com/creack/pty/v2 v2.0.0-20231209135443-03db72c7b76c // indirect @@ -100,7 +100,7 @@ require ( 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.0 // indirect + github.com/extism/go-sdk v1.6.1 // indirect github.com/fatih/semgroup v1.3.0 // indirect github.com/gitleaks/go-gitdiff v0.9.1 // indirect github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 // indirect diff --git a/go.sum b/go.sum index d8bd4b8bacc..ed7ad4f01a1 100644 --- a/go.sum +++ b/go.sum @@ -32,14 +32,14 @@ github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.3.0 h1:+m0M/LFxN43KvUL github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.3.0/go.mod h1:PwOyop78lveYMRs6oCxjiVyBdyCgIYH6XHIVZO9/SFQ= github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0 h1:ywEEhmNahHBihViHepv3xPBn1663uRv2t2q/ESv9seY= github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0/go.mod h1:iZDifYGJTIgIIkYRNWPENUnqx6bJ2xnSDFI2tjwZNuY= -github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.2.0 h1:TkNl6WlpHdZSMt0Zngw8y0c9ZMi3GwmYl0kKNbW9PvU= -github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.2.0/go.mod h1:ukmL56lWl275SgNFijuwx0Wv6n6HmzzpPWW4kMoy/wY= +github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.3.0 h1:WLUIpeyv04H0RCcQHaA4TNoyrQ39Ox7V+re+iaqzTe0= +github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.3.0/go.mod h1:hd8hTTIY3VmUVPRHNH7GVCHO3SHgXkJKZHReby/bnUQ= github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.1.0 h1:eXnN9kaS8TiDwXjoie3hMRLuwdUBUMW9KRgOqB3mCaw= github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.1.0/go.mod h1:XIpam8wumeZ5rVMuhdDQLMfIPDf1WO3IzrCRO3e3e3o= github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1 h1:WJTmL004Abzc5wDB5VtZG2PJk5ndYDgVacGqfirKxjM= github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1/go.mod h1:tCcJZ0uHAmvjsVYzEFivsRTN00oz5BEsRgQHu5JZ9WE= -github.com/AzureAD/microsoft-authentication-library-for-go v1.2.3 h1:6LyjnnaLpcOKK0fbYisI+mb8CE7iNe7i89nMNQxFxs8= -github.com/AzureAD/microsoft-authentication-library-for-go v1.2.3/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI= +github.com/AzureAD/microsoft-authentication-library-for-go v1.3.1 h1:gUDtaZk8heteyfdmv+pcfHvhR9llnh7c7GMwZ8RVG04= +github.com/AzureAD/microsoft-authentication-library-for-go v1.3.1/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI= github.com/BobuSumisu/aho-corasick v1.0.3 h1:uuf+JHwU9CHP2Vx+wAy6jcksJThhJS9ehR8a+4nPE9g= github.com/BobuSumisu/aho-corasick v1.0.3/go.mod h1:hm4jLcvZKI2vRF2WDU1N4p/jpWtpOzp3nLmi9AzX/XE= github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ= @@ -53,10 +53,10 @@ github.com/Masterminds/sprig/v3 v3.3.0/go.mod h1:Zy1iXRYNqNLUolqCpL4uhk6SHUMAOSC github.com/Microsoft/go-winio v0.5.2/go.mod h1:WpS1mjBmmwHBEWmogvA2mj8546UReBk4v8QkMxJ6pZY= github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= 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.2 h1:sXUlmNd5MFHfxIvchQqkbksYmKmHb05coSYhMpWpUNs= -github.com/Shopify/ejson v1.5.2/go.mod h1:bVvQ3MaBCfMOkIp1rWZcot3TruYXCc7qUUbI1tjs/YM= +github.com/ProtonMail/go-crypto v1.1.0 h1:OnlSGxXflfrWJESDsGQOmACNQRM9IflG3q8XTrOqvbE= +github.com/ProtonMail/go-crypto v1.1.0/go.mod h1:rA3QumHc/FZ8pAHreoekgiAbzpNsfQAosU5td4SnOrE= +github.com/Shopify/ejson v1.5.3 h1:2TfdPKTkHXADrvxQrW+mOpl+btx0kDn4/kjzOQ1gIH8= +github.com/Shopify/ejson v1.5.3/go.mod h1:bVvQ3MaBCfMOkIp1rWZcot3TruYXCc7qUUbI1tjs/YM= github.com/alecthomas/assert/v2 v2.11.0 h1:2Q9r3ki8+JYXvGsDyBXwH3LcJ+WK5D0gc5E8vS6K3D0= github.com/alecthomas/assert/v2 v2.11.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k= github.com/alecthomas/chroma/v2 v2.14.0 h1:R3+wzpnUArGcQz7fCETQBzO5n9IMNi13iIs46aU4V9E= @@ -71,32 +71,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.32.3 h1:T0dRlFBKcdaUPGNtkBSwHZxrtis8CQU17UpNBZYd0wk= -github.com/aws/aws-sdk-go-v2 v1.32.3/go.mod h1:2SK5n0a2karNTv5tbP1SjsX0uhttou00v/HpXKM1ZUo= -github.com/aws/aws-sdk-go-v2/config v1.28.1 h1:oxIvOUXy8x0U3fR//0eq+RdCKimWI900+SV+10xsCBw= -github.com/aws/aws-sdk-go-v2/config v1.28.1/go.mod h1:bRQcttQJiARbd5JZxw6wG0yIK3eLeSCPdg6uqmmlIiI= -github.com/aws/aws-sdk-go-v2/credentials v1.17.42 h1:sBP0RPjBU4neGpIYyx8mkU2QqLPl5u9cmdTWVzIpHkM= -github.com/aws/aws-sdk-go-v2/credentials v1.17.42/go.mod h1:FwZBfU530dJ26rv9saAbxa9Ej3eF/AK0OAY86k13n4M= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.18 h1:68jFVtt3NulEzojFesM/WVarlFpCaXLKaBxDpzkQ9OQ= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.18/go.mod h1:Fjnn5jQVIo6VyedMc0/EhPpfNlPl7dHV916O6B+49aE= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.22 h1:Jw50LwEkVjuVzE1NzkhNKkBf9cRN7MtE1F/b2cOKTUM= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.22/go.mod h1:Y/SmAyPcOTmpeVaWSzSKiILfXTVJwrGmYZhcRbhWuEY= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.22 h1:981MHwBaRZM7+9QSR6XamDzF/o7ouUGxFzr+nVSIhrs= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.22/go.mod h1:1RA1+aBEfn+CAB/Mh0MB6LsdCYCnjZm7tKXtnk499ZQ= +github.com/aws/aws-sdk-go-v2 v1.32.4 h1:S13INUiTxgrPueTmrm5DZ+MiAo99zYzHEFh1UNkOxNE= +github.com/aws/aws-sdk-go-v2 v1.32.4/go.mod h1:2SK5n0a2karNTv5tbP1SjsX0uhttou00v/HpXKM1ZUo= +github.com/aws/aws-sdk-go-v2/config v1.28.2 h1:FLvWA97elBiSPdIol4CXfIAY1wlq3KzoSgkMuZSuSe8= +github.com/aws/aws-sdk-go-v2/config v1.28.2/go.mod h1:hNmQsKfUqpKz2yfnZUB60GCemPmeqAalVTui0gOxjAE= +github.com/aws/aws-sdk-go-v2/credentials v1.17.43 h1:SEGdVOOE1Wyr2XFKQopQ5GYjym3nYHcphesdt78rNkY= +github.com/aws/aws-sdk-go-v2/credentials v1.17.43/go.mod h1:3aiza5kSyAE4eujSanOkSkAmX/RnVqslM+GRQ/Xvv4c= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.19 h1:woXadbf0c7enQ2UGCi8gW/WuKmE0xIzxBF/eD94jMKQ= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.19/go.mod h1:zminj5ucw7w0r65bP6nhyOd3xL6veAUMc3ElGMoLVb4= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.23 h1:A2w6m6Tmr+BNXjDsr7M90zkWjsu4JXHwrzPg235STs4= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.23/go.mod h1:35EVp9wyeANdujZruvHiQUAo9E3vbhnIO1mTCAxMlY0= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.23 h1:pgYW9FCabt2M25MoHYCfMrVY2ghiiBKYWUVXfwZs+sU= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.23/go.mod h1:c48kLgzO19wAu3CPkDWC28JbaJ+hfQlsdl7I2+oqIbk= github.com/aws/aws-sdk-go-v2/internal/ini v1.8.1 h1:VaRN3TlFdd6KxX1x3ILT5ynH6HvKgqdiXoTxAF4HQcQ= github.com/aws/aws-sdk-go-v2/internal/ini v1.8.1/go.mod h1:FbtygfRFze9usAadmnGJNc8KsP346kEe+y2/oyhGAGc= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.0 h1:TToQNkvGguu209puTojY/ozlqy2d/SFNcoLIqTFi42g= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.0/go.mod h1:0jp+ltwkf+SwG2fm/PKo8t4y8pJSgOCO4D8Lz3k0aHQ= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.3 h1:qcxX0JYlgWH3hpPUnd6U0ikcl6LLA9sLkXE2w1fpMvY= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.3/go.mod h1:cLSNEmI45soc+Ef8K/L+8sEA3A3pYFEYf5B5UI+6bH4= -github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.34.3 h1:CyA6J82ePPoh1Nj8ErOR2e/JRlzfFzWpGwGMFzFjwZg= -github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.34.3/go.mod h1:EliITPlGcBz0FRiVl7lRLtzI1cnDybFcfLYMZedOInE= -github.com/aws/aws-sdk-go-v2/service/sso v1.24.3 h1:UTpsIf0loCIWEbrqdLb+0RxnTXfWh2vhw4nQmFi4nPc= -github.com/aws/aws-sdk-go-v2/service/sso v1.24.3/go.mod h1:FZ9j3PFHHAR+w0BSEjK955w5YD2UwB/l/H0yAK3MJvI= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.28.3 h1:2YCmIXv3tmiItw0LlYf6v7gEHebLY45kBEnPezbUKyU= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.28.3/go.mod h1:u19stRyNPxGhj6dRm+Cdgu6N75qnbW7+QN0q0dsAk58= -github.com/aws/aws-sdk-go-v2/service/sts v1.32.3 h1:wVnQ6tigGsRqSWDEEyH6lSAJ9OyFUsSnbaUWChuSGzs= -github.com/aws/aws-sdk-go-v2/service/sts v1.32.3/go.mod h1:VZa9yTFyj4o10YGsmDO4gbQJUvvhY72fhumT8W4LqsE= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.4 h1:tHxQi/XHPK0ctd/wdOw0t7Xrc2OxcRCnVzv8lwWPu0c= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.4/go.mod h1:4GQbF1vJzG60poZqWatZlhP31y8PGCCVTvIGPdaaYJ0= +github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.34.4 h1:YQheBh+MS27cJG1K6VO3A6AzNhkq8ETp1g7l0KMcdss= +github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.34.4/go.mod h1:FTCjaQxTVVQqLQ4ktBsLNZPnJ9pVLkJ6F0qVwtALaxk= +github.com/aws/aws-sdk-go-v2/service/sso v1.24.4 h1:BqE3NRG6bsODh++VMKMsDmFuJTHrdD4rJZqHjDeF6XI= +github.com/aws/aws-sdk-go-v2/service/sso v1.24.4/go.mod h1:wrMCEwjFPms+V86TCQQeOxQF/If4vT44FGIOFiMC2ck= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.28.4 h1:zcx9LiGWZ6i6pjdcoE9oXAB6mUdeyC36Ia/QEiIvYdg= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.28.4/go.mod h1:Tp/ly1cTjRLGBBmNccFumbZ8oqpZlpdhFf80SrRh4is= +github.com/aws/aws-sdk-go-v2/service/sts v1.32.4 h1:yDxvkz3/uOKfxnv8YhzOi9m+2OGIxF+on3KOISbK5IU= +github.com/aws/aws-sdk-go-v2/service/sts v1.32.4/go.mod h1:9XEUty5v5UAsMiFOBJrNibZgwCeOma73jgGwwhgffa8= github.com/aws/smithy-go v1.22.0 h1:uunKnWlcoL3zO7q+gG2Pk53joueEOsnNB28QdMsmiMM= github.com/aws/smithy-go v1.22.0/go.mod h1:irrKGvNn1InZwb2d7fkIRNucdfwR8R+Ts3wxYa/cJHg= github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= @@ -119,21 +119,20 @@ 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.1.2 h1:naQXF2laRxyLyil/i7fxdpiz1/k06IKquhm4vBfHsIc= -github.com/charmbracelet/bubbletea v1.1.2/go.mod h1:9HIU/hBV24qKjlehyj8z1r/tR9TYTQEag+cWZnuXo8E= +github.com/charmbracelet/bubbletea v1.2.0 h1:WYHclJaFDOz4dPxiGx7owwb8P4000lYPcuXPIALS5Z8= +github.com/charmbracelet/bubbletea v1.2.0/go.mod h1:viLoDL7hG4njLJSKU2gw7kB3LSEmWsrM80rO1dBJWBI= 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= github.com/charmbracelet/harmonica v0.2.0/go.mod h1:KSri/1RMQOZLbw7AHqgcBycp8pgJnQMYYT8QZRqZ1Ao= github.com/charmbracelet/lipgloss v1.0.0 h1:O7VkGDvqEdGi93X+DeqsQ7PKHDgtQfF8j8/O2qFMQNg= github.com/charmbracelet/lipgloss v1.0.0/go.mod h1:U5fy9Z+C38obMs+T+tJqst9VGzlOYGj4ri9reL3qUlo= -github.com/charmbracelet/x/ansi v0.4.2 h1:0JM6Aj/g/KC154/gOP4vfxun0ff6itogDYk41kof+qk= -github.com/charmbracelet/x/ansi v0.4.2/go.mod h1:dk73KoMTT5AX5BsX0KrqhsTqAnhZZoCBjs7dGWp4Ktw= +github.com/charmbracelet/x/ansi v0.4.5 h1:LqK4vwBNaXw2AyGIICa5/29Sbdq58GbGdFngSexTdRM= +github.com/charmbracelet/x/ansi v0.4.5/go.mod h1:dk73KoMTT5AX5BsX0KrqhsTqAnhZZoCBjs7dGWp4Ktw= github.com/charmbracelet/x/exp/golden v0.0.0-20240815200342-61de596daa2b h1:MnAMdlwSltxJyULnrYbkZpp4k58Co7Tah3ciKhSNo0Q= github.com/charmbracelet/x/exp/golden v0.0.0-20240815200342-61de596daa2b/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U= 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.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= @@ -170,8 +169,8 @@ github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ= 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.0 h1:crFRMhjcPAn6R9M4eIvkjHQs7CLBs3yzPqwnj+uwzdg= -github.com/extism/go-sdk v1.6.0/go.mod h1:yRolc4PvIUQ9J/BBB3QZ5EY1MtXAN2jqBGDGR3Sk54M= +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/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.3.0 h1:pTEnmcEze/BUf4UmVn9f1ZT1OckkBTNRV9w9k/I2/y4= @@ -516,12 +515,10 @@ 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.3.1-0.20221117191849-2c476679df9a/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4= -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-20241022195102-750a45fe5e47 h1:m1OiIChtSir3E2VcmUbCjURt0/sRo1QBSduRjcLFJ1o= -golang.org/x/crypto/x509roots/fallback v0.0.0-20241022195102-750a45fe5e47/go.mod h1:kNa9WdvYnzFwC79zRpLRMJbdEFlhyM5RPFBBZp/wWH8= +golang.org/x/crypto/x509roots/fallback v0.0.0-20241104001025-71ed71b4faf9 h1:4cEcP5+OjGppY79LCQ5Go2B1Boix2x0v6pvA01P3FoA= +golang.org/x/crypto/x509roots/fallback v0.0.0-20241104001025-71ed71b4faf9/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= @@ -532,9 +529,7 @@ golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLL 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.2.0/go.mod h1:KqCZLdyyvdV855qA2rE3GC2aiw5xGR5TEjj8smXukLY= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= golang.org/x/net v0.30.0 h1:AcW1SDZMkb8IpzCdQUaIq2sP4sZ4zw+55h6ynffypl4= golang.org/x/net v0.30.0/go.mod h1:2wGyMJ5iFasEhkwi13ChkO/t1ECNC4X4eBKkVFyYFlU= golang.org/x/oauth2 v0.23.0 h1:PbgcYx2W7i4LvjJWEbf0ngHV6qJYr86PkAV3bXdLEbs= @@ -557,8 +552,6 @@ golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -569,16 +562,13 @@ golang.org/x/telemetry v0.0.0-20240521205824-bda55230c457 h1:zf5N6UOrA487eEFacMe golang.org/x/telemetry v0.0.0-20240521205824-bda55230c457/go.mod h1:pRgIJT+bRLFKnoM1ldnzKoxTIn14Yxz928LQRYYgIN0= 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= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= -golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= golang.org/x/term v0.25.0 h1:WtHI/ltw4NvSUig5KARz9h521QvRC8RmF/cuYqifU24= golang.org/x/term v0.25.0/go.mod h1:RPyXicDX+6vLxogjjRxjgD2TKtmAO6NZBsBRfrOLu7M= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= 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.19.0 h1:kTxAhCbGbxhK0IwgSKiMO5awPoDQ0RpfiVYBfK860YM=
chore
Update dependencies
68fff1c1b56a5a61cff0b33281ca418a09301155
2021-12-20 02:40:21
Tom Payne
fix: Fix include template function on Windows with absolute path
false
diff --git a/internal/cmd/templatefuncs.go b/internal/cmd/templatefuncs.go index dd1c75d658e..b9aa39fe37f 100644 --- a/internal/cmd/templatefuncs.go +++ b/internal/cmd/templatefuncs.go @@ -5,7 +5,6 @@ import ( "fmt" "io/fs" "os/exec" - "path" "path/filepath" "runtime" @@ -35,7 +34,7 @@ func (c *Config) fromYamlTemplateFunc(s string) interface{} { func (c *Config) includeTemplateFunc(filename string) string { var absPath chezmoi.AbsPath - if path.IsAbs(filename) { + if filepath.IsAbs(filename) { var err error absPath, err = chezmoi.NewAbsPathFromExtPath(filename, c.homeDirAbsPath) if err != nil { diff --git a/internal/cmd/testdata/scripts/templatefuncs.txt b/internal/cmd/testdata/scripts/templatefuncs.txt index 436ed6f9b49..dde55da0058 100644 --- a/internal/cmd/testdata/scripts/templatefuncs.txt +++ b/internal/cmd/testdata/scripts/templatefuncs.txt @@ -8,16 +8,8 @@ [darwin] stdout 'Darwin Kernel Version' # test include template function with absolute path -# -# this test is disabled on Windows because the backslashes in Windows paths are -# interpreted as a escape characters in the string constant, which breaks the -# test -# -# FIXME fix this test on Windows -[!windows] exec echo {{ "$HOME/.include" }} -[!windows] stdin stdout -[!windows] chezmoi execute-template -[!windows] cmpenv stdout golden/include-abspath +chezmoi execute-template '{{ joinPath (env "HOME") ".include" | include }}' +cmp stdout golden/include-abspath # test include template function with relative paths chezmoi execute-template '{{ include ".include" }}' @@ -131,10 +123,10 @@ echo '</plist>' -- golden/expected -- 255 -- golden/include-abspath -- -$HOME/.include +# contents of .include -- golden/include-relpath -- # contents of .local/share/chezmoi/.include -- home/user/.include -- -# contents of $HOME/.include +# contents of .include -- home/user/.local/share/chezmoi/.include -- # contents of .local/share/chezmoi/.include
fix
Fix include template function on Windows with absolute path
87fc2f1cc1ab419181fc49b5853c8406162afc89
2023-01-03 02:16:23
Tom Payne
chore: Update goreleaser config for v1.14
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 339507404e7..f6e1af263bf 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -31,6 +31,7 @@ jobs: - '**/*.ps1' - '**/*.tmpl' - '.github/workflows/**' + - '.goreleaser.yaml' - 'Makefile' - 'assets/docker/**' - 'assets/scripts/**' diff --git a/.goreleaser.yaml b/.goreleaser.yaml index 22cd99c5a47..9e446a3529e 100644 --- a/.goreleaser.yaml +++ b/.goreleaser.yaml @@ -83,11 +83,18 @@ archives: - LICENSE - README.md - completions/* - replacements: - 386: i386 + name_template: >- + {{- .ProjectName }}_ + {{- .Version }}_ + {{- .Os }}_ + {{- if eq .Arch "386" }}i386 + {{- else if eq .Arch "mips64" }}mips64_hardfloat + {{- else if eq .Arch "mips64le" }}mips64le_hardfloat + {{- else }}{{ .Arch }}{{ end -}} format_overrides: - goos: windows format: zip + rlcp: true - id: glibc builds: - chezmoi-cgo-glibc @@ -96,6 +103,7 @@ archives: - README.md - completions/* name_template: '{{ .ProjectName }}_{{ .Version }}_{{ .Os }}-glibc_{{ .Arch }}' + rlcp: true - id: musl builds: - chezmoi-cgo-musl @@ -104,6 +112,7 @@ archives: - README.md - completions/* name_template: '{{ .ProjectName }}_{{ .Version }}_{{ .Os }}-musl_{{ .Arch }}' + rlcp: true changelog: use: github-native @@ -139,10 +148,13 @@ nfpms: bindir: /usr/bin overrides: deb: - file_name_template: '{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}' - replacements: - 386: i386 - arm: armel + file_name_template: >- + {{- .ProjectName }}_ + {{- .Version }}_ + {{- .Os }}_ + {{- if eq .Arch "386" }}i386 + {{- else if eq .Arch "arm" }}armel + {{- else }}{{ .Arch }}{{ end -}} contents: - src: completions/chezmoi-completion.bash dst: /usr/share/bash-completion/completions/chezmoi @@ -151,12 +163,14 @@ nfpms: - src: completions/chezmoi.zsh dst: /usr/share/zsh/vendor-completions/_chezmoi rpm: - file_name_template: '{{ .ProjectName }}-{{ .Version }}-{{ .Arch }}' - replacements: - amd64: x86_64 - 386: i686 - arm: armhfp - arm64: aarch64 + file_name_template: >- + {{- .ProjectName }}- + {{- .Version }}- + {{- if eq .Arch "amd64" }}x86_64 + {{- else if eq .Arch "386" }}i686 + {{- else if eq .Arch "arm" }}armhfp + {{- else if eq .Arch "arm64" }}aarch64 + {{- else }}{{ .Arch }}{{ end -}} contents: - src: completions/chezmoi-completion.bash dst: /usr/share/bash-completion/completions/chezmoi @@ -234,3 +248,4 @@ source: prefix_template: '{{ .ProjectName }}-{{ .Version }}/' files: - COMMIT + rlcp: true
chore
Update goreleaser config for v1.14
7800ef4046a17ad4ee8671069073217cd9d778b7
2024-07-15 05:33:57
Braden Hilton
chore: update goreleaser config
false
diff --git a/.goreleaser.yaml b/.goreleaser.yaml index 51f5de00834..7387ffe4d8b 100644 --- a/.goreleaser.yaml +++ b/.goreleaser.yaml @@ -215,7 +215,7 @@ chocolateys: project_url: https://chezmoi.io url_template: https://github.com/twpayne/chezmoi/releases/download/v{{ .Version }}/{{ .ArtifactName }} icon_url: https://github.com/twpayne/chezmoi/raw/master/assets/images/logo-144px.png - copyright: Copyright © Tom Payne, 2018-2023 + copyright: Copyright (c) 2018-{{ .Now.Format "2006" }} Tom Payne license_url: https://github.com/twpayne/chezmoi/blob/master/LICENSE project_source_url: https://github.com/twpayne/chezmoi docs_url: https://chezmoi.io @@ -232,7 +232,7 @@ chocolateys: chezmoi scales from the trivial (e.g. copying a few dotfiles onto a Raspberry Pi, development container, or virtual machine) to complex long-lived multi-machine development environments (e.g. keeping any number of home and work, Linux, macOS, and Windows machines in sync). In all cases you only need to maintain a single source of truth (a single branch in git) and getting started only requires adding a single binary to your machine (which you can do with `curl`, `wget`, or `scp`). chezmoi has strong support for security, allowing you to manage secrets (e.g. passwords, access tokens, and private keys) securely and seamlessly using a password manager and/or encrypt whole files with your favorite encryption tool. - release_notes: https://github.com/twpayne/chezmoi/releases/tag/v{{ .Version }} + release_notes: '{{ .Changelog }}' api_key: '{{ .Env.CHOCOLATEY_API_KEY }}' release: @@ -305,7 +305,7 @@ winget: email: [email protected] homepage: https://chezmoi.io license_url: https://github.com/twpayne/chezmoi/blob/master/LICENSE - copyright: Copyright (c) 2018-2023 Tom Payne + copyright: Copyright (c) 2018-{{ .Now.Format "2006" }} Tom Payne release_notes: '{{ .Changelog }}' release_notes_url: https://github.com/twpayne/chezmoi/releases/tag/{{ .Tag }} tags:
chore
update goreleaser config
5aca99adac101cff3a131fce12ef15a86e03f2ad
2022-01-10 05:15:35
Tom Payne
feat: Disable custom completions by default
false
diff --git a/docs/REFERENCE.md b/docs/REFERENCE.md index c081ca81755..57d6e3dad03 100644 --- a/docs/REFERENCE.md +++ b/docs/REFERENCE.md @@ -381,6 +381,7 @@ The following configuration variables are available: | `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 | +| `completion` | `custom` | bool | `false` | Enable custom shell completions | | `diff` | `args` | []string | *see `diff` below* | Extra args to external diff command | | | `command` | string | *none* | External diff command | | | `exclude` | []string | *none* | Entry types to exclude from diffs | diff --git a/internal/cmd/completioncmd.go b/internal/cmd/completioncmd.go index bf54ced21d7..0b2c67f8899 100644 --- a/internal/cmd/completioncmd.go +++ b/internal/cmd/completioncmd.go @@ -7,6 +7,10 @@ import ( "github.com/spf13/cobra" ) +type completionCmdConfig struct { + Custom bool `mapstructure:"custom"` +} + func (c *Config) newCompletionCmd() *cobra.Command { completionCmd := &cobra.Command{ Use: "completion shell", diff --git a/internal/cmd/config.go b/internal/cmd/config.go index a6dc3a805e0..9b2fa8e2f89 100644 --- a/internal/cmd/config.go +++ b/internal/cmd/config.go @@ -122,13 +122,14 @@ type Config struct { keyring keyringData // Command configurations, settable in the config file. - Add addCmdConfig `mapstructure:"add"` - CD cdCmdConfig `mapstructure:"cd"` - Diff diffCmdConfig `mapstructure:"diff"` - Docs docsCmdConfig `mapstructure:"docs"` - Edit editCmdConfig `mapstructure:"edit"` - Git gitCmdConfig `mapstructure:"git"` - Merge mergeCmdConfig `mapstructure:"merge"` + Add addCmdConfig `mapstructure:"add"` + CD cdCmdConfig `mapstructure:"cd"` + Completion completionCmdConfig `mapstructure:"completion"` + Diff diffCmdConfig `mapstructure:"diff"` + Docs docsCmdConfig `mapstructure:"docs"` + Edit editCmdConfig `mapstructure:"edit"` + Git gitCmdConfig `mapstructure:"git"` + Merge mergeCmdConfig `mapstructure:"merge"` // Command configurations, not settable in the config file. apply applyCmdConfig @@ -1954,6 +1955,10 @@ func (c *Config) targetRelPathsBySourcePath( func (c *Config) targetValidArgs( cmd *cobra.Command, args []string, toComplete string, ) ([]string, cobra.ShellCompDirective) { + if !c.Completion.Custom { + return nil, cobra.ShellCompDirectiveDefault + } + toCompleteAbsPath, err := chezmoi.NewAbsPathFromExtPath(toComplete, c.homeDirAbsPath) if err != nil { cobra.CompErrorln(err.Error()) diff --git a/internal/cmd/testdata/scripts/completion_unix.txt b/internal/cmd/testdata/scripts/completion_unix.txt index fc65224f36a..d5da7e3aade 100644 --- a/internal/cmd/testdata/scripts/completion_unix.txt +++ b/internal/cmd/testdata/scripts/completion_unix.txt @@ -44,6 +44,9 @@ $HOME/.file -- golden/complete-target-home-dot-f -- $HOME/.file :4 +-- home/user/.config/chezmoi/chezmoi.toml -- +[completion] + custom = true -- home/user/.local/share/chezmoi/dot_dir/file -- # contents of .dir/file -- home/user/.local/share/chezmoi/dot_file --
feat
Disable custom completions by default
155232a7406fef60eda245491afd8f0c6e92193e
2022-08-07 02:47:11
Tom Payne
chore: Don't print exit status when exiting
false
diff --git a/pkg/cmd/cmd.go b/pkg/cmd/cmd.go index 348e21c2cbe..bcc1501aa0a 100644 --- a/pkg/cmd/cmd.go +++ b/pkg/cmd/cmd.go @@ -126,12 +126,12 @@ func (v VersionInfo) MarshalZerologObject(e *zerolog.Event) { // 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) + var errExitCode chezmoi.ExitCodeError + if errors.As(err, &errExitCode) { + return int(errExitCode) } - errExitCode := chezmoi.ExitCodeError(1) - _ = errors.As(err, &errExitCode) - return int(errExitCode) + fmt.Fprintf(os.Stderr, "chezmoi: %v\n", err) + return 1 } return 0 }
chore
Don't print exit status when exiting
7dfcfcf3c273d5d180fe8b1606b4688c5f590ab0
2024-04-26 23:29:18
Tom Payne
fix: Remove unmanaged files from exact_ directories containing external files
false
diff --git a/internal/chezmoi/sourcestate.go b/internal/chezmoi/sourcestate.go index 48c0d9d26f9..343086e22e2 100644 --- a/internal/chezmoi/sourcestate.go +++ b/internal/chezmoi/sourcestate.go @@ -1108,6 +1108,14 @@ func (s *SourceState) Read(ctx context.Context, options *ReadOptions) error { allSourceStateEntries[targetRelPath] = append(allSourceStateEntries[targetRelPath], sourceStateEntry) } + // Where there are multiple SourceStateEntries for a single target, replace + // them with a single canonical SourceStateEntry if possible. + for targetRelPath, sourceStateEntries := range allSourceStateEntries { + if sourceStateEntry, ok := canonicalSourceStateEntry(sourceStateEntries); ok { + allSourceStateEntries[targetRelPath] = []SourceStateEntry{sourceStateEntry} + } + } + // Generate SourceStateRemoves for exact directories. for targetRelPath, sourceStateEntries := range allSourceStateEntries { if len(sourceStateEntries) != 1 { @@ -1231,11 +1239,6 @@ func (s *SourceState) Read(ctx context.Context, options *ReadOptions) error { continue } - // Allow duplicate equivalent source entries for directories. - if allEquivalentDirs(sourceStateEntries) { - continue - } - origins := make([]string, 0, len(sourceStateEntries)) for _, sourceStateEntry := range sourceStateEntries { origins = append(origins, sourceStateEntry.Origin().OriginString()) @@ -2793,9 +2796,12 @@ func (e *External) OriginString() string { return e.URL + " defined in " + e.sourceAbsPath.String() } -// allEquivalentDirs returns if sourceStateEntries are all equivalent -// directories. -func allEquivalentDirs(sourceStateEntries []SourceStateEntry) bool { +// canonicalSourceStateEntry returns the canonical SourceStateEntry for the +// given sourceStateEntries. +// +// This only applies to directories, where SourceStateImplicitDirs are +// considered equivalent to all SourceStateDirs. +func canonicalSourceStateEntry(sourceStateEntries []SourceStateEntry) (SourceStateEntry, bool) { // Find all directories to check for equivalence. var firstSourceStateDir *SourceStateDir sourceStateDirs := make([]SourceStateEntry, 0, len(sourceStateEntries)) @@ -2807,29 +2813,37 @@ func allEquivalentDirs(sourceStateEntries []SourceStateEntry) bool { case *SourceStateImplicitDir: sourceStateDirs = append(sourceStateDirs, sourceStateEntry) default: - return false + return nil, false } } - // If there are no SourceStateDirs then there are no equivalent directories. - if len(sourceStateDirs) == 0 { - return false - } - - // Check for equivalence. - for _, sourceStateDir := range sourceStateDirs { - switch sourceStateDir := sourceStateDir.(type) { - case *SourceStateDir: - if sourceStateDir.Attr != firstSourceStateDir.Attr { - return false + switch len(sourceStateDirs) { + case 0: + // If there are no SourceStateDirs then there are no equivalent directories. + return nil, false + case 1: + return sourceStateDirs[0], true + default: + // Check for equivalence. + for _, sourceStateDir := range sourceStateDirs { + switch sourceStateDir := sourceStateDir.(type) { + case *SourceStateDir: + if sourceStateDir.Attr != firstSourceStateDir.Attr { + return nil, false + } + case *SourceStateImplicitDir: + // SourceStateImplicitDirs are considered equivalent to all other + // directories. } - case *SourceStateImplicitDir: - // SourceStateImplicitDirs are considered equivalent to all other - // directories. } + // If all directories are equivalent then return the first real + // *SourceStateDir, if it exists. + if firstSourceStateDir != nil { + return firstSourceStateDir, true + } + // Otherwise, return the first entry which is a *SourceStateImplicitDir. + return sourceStateDirs[0], true } - - return true } // isAppleDoubleFile returns true if the file looks like and has the diff --git a/internal/cmd/applycmd_test.go b/internal/cmd/applycmd_test.go index 94041d531ba..c65be9c0497 100644 --- a/internal/cmd/applycmd_test.go +++ b/internal/cmd/applycmd_test.go @@ -2,6 +2,8 @@ package cmd import ( "io/fs" + "net/http" + "net/http/httptest" "path/filepath" "testing" @@ -264,3 +266,39 @@ func TestIssue3216(t *testing.T) { assert.NoError(t, newTestConfig(t, fileSystem).execute([]string{"apply"})) }) } + +func TestIssue3703(t *testing.T) { + httpServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, err := w.Write([]byte("contents of file\n")) + assert.NoError(t, err) + })) + defer httpServer.Close() + + chezmoitest.WithTestFS(t, map[string]any{ + "/home/user": map[string]any{ + ".local": map[string]any{ + "bin": map[string]any{ + "unmanaged": "", + }, + "share/chezmoi": map[string]any{ + ".chezmoiexternal.toml.tmpl": chezmoitest.JoinLines( + `[".local/bin/file"]`, + ` type = "file"`, + ` url = "`+httpServer.URL+`/file"`, + ), + "dot_local/exact_bin/.keep": "", + }, + }, + }, + }, func(fileSystem vfs.FS) { + assert.NoError(t, newTestConfig(t, fileSystem).execute([]string{"apply"})) + vfst.RunTests(t, fileSystem, ".local/bin", + vfst.TestPath("/home/user/.local/bin/file", + vfst.TestContentsString("contents of file\n"), + ), + vfst.TestPath("/home/user/.local/bin/unmanaged", + vfst.TestDoesNotExist(), + ), + ) + }) +} diff --git a/internal/cmd/testdata/scripts/issue3703.txtar b/internal/cmd/testdata/scripts/issue3703.txtar new file mode 100644 index 00000000000..313f283f64c --- /dev/null +++ b/internal/cmd/testdata/scripts/issue3703.txtar @@ -0,0 +1,16 @@ +httpd www + +# test that chezmoi apply removes unmanaged files from an exact_ directory containing an external +exists $HOME/.local/bin/unmanaged +exec chezmoi apply --debug +cmp $HOME/.local/bin/file www/file +! exists $HOME/.local/bin/unmanaged + +-- home/user/.local/bin/unmanaged -- +-- home/user/.local/share/chezmoi/.chezmoiexternal.toml.tmpl -- +[".local/bin/file"] + type = "file" + url = "{{ env "HTTPD_URL" }}/file" +-- home/user/.local/share/chezmoi/dot_local/exact_bin/.keep -- +-- www/file -- +# contents of file
fix
Remove unmanaged files from exact_ directories containing external files
268b961902416d062594ddf7dbcdf9ce20875643
2023-05-01 16:46:26
dependabot[bot]
chore(deps): bump github/codeql-action from 2.2.9 to 2.3.2
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 24f8bf40723..c7e8c354895 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -47,10 +47,10 @@ jobs: - uses: actions/checkout@8f4b7f84864484a7bf31766abe9204da3cbe65b3 with: fetch-depth: 1 - - uses: github/codeql-action/init@04df1262e6247151b5ac09cd2c303ac36ad3f62b + - uses: github/codeql-action/init@f3feb00acb00f31a6f60280e6ace9ca31d91c76a with: languages: go - - uses: github/codeql-action/analyze@04df1262e6247151b5ac09cd2c303ac36ad3f62b + - uses: github/codeql-action/analyze@f3feb00acb00f31a6f60280e6ace9ca31d91c76a misspell: runs-on: ubuntu-22.04 steps:
chore
bump github/codeql-action from 2.2.9 to 2.3.2
9487805c73f86fe89a30514b121a22c57240c8da
2025-03-05 06:10:24
Tom Payne
chore: Update GitHub Actions
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 3e598db3130..8c2c5501374 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -338,7 +338,7 @@ jobs: with: cache-prefix: website-go go-version: ${{ env.GO_VERSION }} - - uses: astral-sh/setup-uv@1edb52594c857e2b5b13128931090f0640537287 + - uses: astral-sh/setup-uv@f94ec6bedd8674c4426838e6b50417d36b6ab231 with: enable-cache: true version: ${{ env.UV_VERSION }} @@ -527,7 +527,7 @@ jobs: with: cache-prefix: website-go go-version: ${{ env.GO_VERSION }} - - uses: astral-sh/setup-uv@1edb52594c857e2b5b13128931090f0640537287 + - uses: astral-sh/setup-uv@f94ec6bedd8674c4426838e6b50417d36b6ab231 with: enable-cache: true version: ${{ env.UV_VERSION }}
chore
Update GitHub Actions
4034b96b45ddd42517aacd63e446611585d46a8f
2025-01-09 04:32:15
Tom Payne
chore: Update dependencies
false
diff --git a/go.mod b/go.mod index 3ad700eaebd..6a7eccab473 100644 --- a/go.mod +++ b/go.mod @@ -50,8 +50,8 @@ require ( github.com/zricethezav/gitleaks/v8 v8.22.1 go.etcd.io/bbolt v1.3.11 go.uber.org/automaxprocs v1.6.0 - golang.org/x/crypto v0.31.0 - golang.org/x/crypto/x509roots/fallback v0.0.0-20250102161546-4a75ba54c28f + golang.org/x/crypto v0.32.0 + golang.org/x/crypto/x509roots/fallback v0.0.0-20250106144430-8929309228b4 golang.org/x/oauth2 v0.25.0 golang.org/x/sync v0.10.0 golang.org/x/sys v0.29.0 @@ -66,7 +66,7 @@ require ( al.essio.dev/pkg/shellescape v1.5.1 // indirect dario.cat/mergo v1.0.1 // indirect filippo.io/edwards25519 v1.1.0 // indirect - github.com/Azure/azure-sdk-for-go/sdk/azcore v1.16.0 // indirect + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.17.0 // indirect github.com/Azure/azure-sdk-for-go/sdk/internal v1.10.0 // indirect github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.1.0 // indirect github.com/AzureAD/microsoft-authentication-library-for-go v1.3.2 // indirect @@ -74,8 +74,8 @@ require ( github.com/Masterminds/goutils v1.1.1 // indirect github.com/Masterminds/semver/v3 v3.3.1 // indirect github.com/Microsoft/go-winio v0.6.2 // indirect - github.com/ProtonMail/go-crypto v1.1.3 // indirect - github.com/alecthomas/chroma/v2 v2.14.0 // indirect + github.com/ProtonMail/go-crypto v1.1.4 // indirect + github.com/alecthomas/chroma/v2 v2.15.0 // indirect github.com/alecthomas/repr v0.4.0 // indirect github.com/atotto/clipboard v0.1.4 // indirect github.com/aws/aws-sdk-go-v2/credentials v1.17.48 // indirect @@ -99,7 +99,7 @@ require ( github.com/charmbracelet/x/ansi v0.6.0 // indirect github.com/charmbracelet/x/term v0.2.1 // indirect github.com/cloudflare/circl v1.5.0 // indirect - github.com/cpuguy83/go-md2man/v2 v2.0.5 // indirect + github.com/cpuguy83/go-md2man/v2 v2.0.6 // indirect github.com/creack/pty/v2 v2.0.0-20231209135443-03db72c7b76c // indirect github.com/cyphar/filepath-securejoin v0.3.6 // indirect github.com/danieljoos/wincred v1.2.2 // indirect @@ -173,13 +173,13 @@ require ( github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 // indirect github.com/yuin/goldmark v1.7.8 // indirect github.com/yuin/goldmark-emoji v1.0.4 // indirect - go.opentelemetry.io/proto/otlp v1.4.0 // 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-20250103183323-7d7fa50e5329 // indirect + golang.org/x/exp v0.0.0-20250106191152-7588d65b2ba8 // indirect golang.org/x/mod v0.22.0 // indirect - golang.org/x/net v0.33.0 // indirect + golang.org/x/net v0.34.0 // indirect golang.org/x/text v0.21.0 // indirect - golang.org/x/tools v0.28.0 // indirect - google.golang.org/protobuf v1.36.1 // indirect + golang.org/x/tools v0.29.0 // indirect + google.golang.org/protobuf v1.36.2 // indirect gopkg.in/warnings.v0 v0.1.2 // indirect ) diff --git a/go.sum b/go.sum index e92d61aa4c4..d63e21d3d7c 100644 --- a/go.sum +++ b/go.sum @@ -26,8 +26,8 @@ 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.5 h1:Lrhc3vuTu5q2TW84LqSzTniFqinvssDFul+C4fyxa5Q= github.com/1password/onepassword-sdk-go v0.1.5/go.mod h1:Wb3xGWJSzazA699hlAULC/kK5gvjxyTEP5uZNyP21Ro= -github.com/Azure/azure-sdk-for-go/sdk/azcore v1.16.0 h1:JZg6HRh6W6U4OLl6lk7BZ7BLisIzM9dG1R50zUk9C/M= -github.com/Azure/azure-sdk-for-go/sdk/azcore v1.16.0/go.mod h1:YL1xnZ6QejvQHWJrX/AvhFl4WW4rqHVoKspWNVwFk0M= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.17.0 h1:g0EZJwz7xkXQiZAI5xi9f3WWFYBlX1CPTrR+NDToRkQ= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.17.0/go.mod h1:XCW7KnZet0Opnr7HccfUw1PLc4CjHqpcaxW8DHklNkQ= github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.8.0 h1:B/dfvscEQtew9dVuoxqxrUKKv8Ih2f55PydknDamU+g= github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.8.0/go.mod h1:fiPSssYvltE08HJchL04dOy+RD4hgrjph0cwGGMntdI= github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.3.0 h1:+m0M/LFxN43KvULkDNfdXOgrjtg6UYJPFBJyuEcRCAw= @@ -57,14 +57,14 @@ github.com/Masterminds/sprig/v3 v3.3.0/go.mod h1:Zy1iXRYNqNLUolqCpL4uhk6SHUMAOSC github.com/Microsoft/go-winio v0.5.2/go.mod h1:WpS1mjBmmwHBEWmogvA2mj8546UReBk4v8QkMxJ6pZY= github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= -github.com/ProtonMail/go-crypto v1.1.3 h1:nRBOetoydLeUb4nHajyO2bKqMLfWQ/ZPwkXqXxPxCFk= -github.com/ProtonMail/go-crypto v1.1.3/go.mod h1:rA3QumHc/FZ8pAHreoekgiAbzpNsfQAosU5td4SnOrE= +github.com/ProtonMail/go-crypto v1.1.4 h1:G5U5asvD5N/6/36oIw3k2bOfBn5XVcZrb7PBjzzKKoE= +github.com/ProtonMail/go-crypto v1.1.4/go.mod h1:rA3QumHc/FZ8pAHreoekgiAbzpNsfQAosU5td4SnOrE= github.com/Shopify/ejson v1.5.3 h1:2TfdPKTkHXADrvxQrW+mOpl+btx0kDn4/kjzOQ1gIH8= github.com/Shopify/ejson v1.5.3/go.mod h1:bVvQ3MaBCfMOkIp1rWZcot3TruYXCc7qUUbI1tjs/YM= github.com/alecthomas/assert/v2 v2.11.0 h1:2Q9r3ki8+JYXvGsDyBXwH3LcJ+WK5D0gc5E8vS6K3D0= github.com/alecthomas/assert/v2 v2.11.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k= -github.com/alecthomas/chroma/v2 v2.14.0 h1:R3+wzpnUArGcQz7fCETQBzO5n9IMNi13iIs46aU4V9E= -github.com/alecthomas/chroma/v2 v2.14.0/go.mod h1:QolEbTfmUHIMVpBqxeDnNBj2uoeI4EbYP4i6n68SG4I= +github.com/alecthomas/chroma/v2 v2.15.0 h1:LxXTQHFoYrstG2nnV9y2X5O94sOBzf0CIUpSTbpxvMc= +github.com/alecthomas/chroma/v2 v2.15.0/go.mod h1:gUhVLrPDXPtp/f+L1jo9xepo9gL4eLwRuGAunSZMkio= github.com/alecthomas/repr v0.4.0 h1:GhI2A8MACjfegCPVq9f1FLvIBS+DrQ2KQBFZP1iFzXc= github.com/alecthomas/repr v0.4.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8= @@ -150,8 +150,8 @@ github.com/coreos/go-semver v0.3.1/go.mod h1:irMmmIw/7yzSRPWryHsK7EYSg09caPQL03V 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.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= -github.com/cpuguy83/go-md2man/v2 v2.0.5 h1:ZtcqGrnekaHpVLArFSe4HK5DoKx1T0rq2DwVB0alcyc= -github.com/cpuguy83/go-md2man/v2 v2.0.5/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/cpuguy83/go-md2man/v2 v2.0.6 h1:XJtiaUW6dEEqVuZiMTn1ldk455QWwEIsMIJlo5vtkx0= +github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s= github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE= github.com/creack/pty/v2 v2.0.0-20231209135443-03db72c7b76c h1:5l8y/PgjeX1aUyZxXabtAf2ahCYQaqWzlFzQgU16o0U= @@ -271,8 +271,8 @@ github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8= github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0= github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 h1:+ngKgrYPPJrOjhax5N+uePQ0Fh1Z7PheYoUI/0nzkPA= github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.24.0 h1:TmHmbvxPmaegwhDubVz0lICL0J5Ka2vwTzhoePEXsGE= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.24.0/go.mod h1:qztMSjm835F2bXf+5HKAPIS5qsmQDqZna/PgVt4rWtI= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.25.1 h1:VNqngBF40hVlDloBruUehVYC3ArSgIyScOAyMRqBxRg= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.25.1/go.mod h1:RBRO7fro65R6tjKzYgLAFo0t1QEXY1Dp+i/bvpRiqiQ= 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.28.2 h1:mXfkRHrpHN4YY3RqL09nXU1eHKLNiuAN4kHvDQ16k/8= @@ -595,8 +595,8 @@ go.opentelemetry.io/otel/sdk v1.28.0 h1:b9d7hIry8yZsgtbmM0DKyPWMMUMlK9NEKuIG4aBq go.opentelemetry.io/otel/sdk v1.28.0/go.mod h1:oYj7ClPUA7Iw3m+r7GeEjz0qckQRJK2B8zjcZEfu7Pg= go.opentelemetry.io/otel/trace v1.28.0 h1:GhQ9cUuQGmNDd5BTCP2dAvv75RdMxEfTmYejp+lkx9g= go.opentelemetry.io/otel/trace v1.28.0/go.mod h1:jPyXzNPg6da9+38HEwElrQiHlVMTnVfM3/yv2OlIHaI= -go.opentelemetry.io/proto/otlp v1.4.0 h1:TA9WRvW6zMwP+Ssb6fLoUIuirti1gGbP28GcKG1jgeg= -go.opentelemetry.io/proto/otlp v1.4.0/go.mod h1:PPBWZIP98o2ElSqI35IHfu7hIhSwvc5N38Jw8pXuGFY= +go.opentelemetry.io/proto/otlp v1.5.0 h1:xJvq7gMzB31/d406fB8U5CBdyQGw4P399D1aQWU/3i4= +go.opentelemetry.io/proto/otlp v1.5.0/go.mod h1:keN8WnHxOy8PG0rQZjJJ5A2ebUoafqWp0eVQ4yIXvJ4= 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/automaxprocs v1.6.0 h1:O3y2/QNTOdbF+e/dpXNNW7Rx2hZ4sTIPyybbxyNqTUs= @@ -610,12 +610,12 @@ golang.org/x/arch v0.6.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= 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.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U= -golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk= -golang.org/x/crypto/x509roots/fallback v0.0.0-20250102161546-4a75ba54c28f h1:B/I8f2Dxu7QKgLEDtWFOcJuORyzo783N3l2izF8PP04= -golang.org/x/crypto/x509roots/fallback v0.0.0-20250102161546-4a75ba54c28f/go.mod h1:kNa9WdvYnzFwC79zRpLRMJbdEFlhyM5RPFBBZp/wWH8= -golang.org/x/exp v0.0.0-20250103183323-7d7fa50e5329 h1:9kj3STMvgqy3YA4VQXBrN7925ICMxD5wzMRcgA30588= -golang.org/x/exp v0.0.0-20250103183323-7d7fa50e5329/go.mod h1:qj5a5QZpwLU2NLQudwIN5koi3beDhSAlJwa67PuM98c= +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-20250106144430-8929309228b4 h1:2UmVXDw2sT/v4mRp1tucroUkHyqAbK1SXfh+ss3sKsE= +golang.org/x/crypto/x509roots/fallback v0.0.0-20250106144430-8929309228b4/go.mod h1:kNa9WdvYnzFwC79zRpLRMJbdEFlhyM5RPFBBZp/wWH8= +golang.org/x/exp v0.0.0-20250106191152-7588d65b2ba8 h1:yqrTHse8TCMW1M1ZCP+VAR/l0kKxwaAIqN/il7x4voA= +golang.org/x/exp v0.0.0-20250106191152-7588d65b2ba8/go.mod h1:tujkw807nyEEAamNbDrEGzRav+ilXA7PCRAd6xsmwiU= 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= @@ -626,8 +626,8 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v 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.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I= -golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4= +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/oauth2 v0.25.0 h1:CY4y7XT9v0cRI9oupztF8AgiIu99L/ksR/Xp/6jrZ70= golang.org/x/oauth2 v0.25.0/go.mod h1:XYTD2NtWslqkgxebSiOHnXEap4TF09sJSc7H1sXbhtI= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -676,8 +676,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.28.0 h1:WuB6qZ4RPCQo5aP3WdKZS7i595EdWqWR8vqJTlwTVK8= -golang.org/x/tools v0.28.0/go.mod h1:dcIOrVd3mfQKTgrDVQHqCPMWy6lnhfhtX3hLXYVLfRw= +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/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= @@ -688,14 +688,14 @@ google.golang.org/appengine v1.6.8 h1:IhEN5q69dyKagZPYMSdIjS2HqprW324FRQZJcGqPAs google.golang.org/appengine v1.6.8/go.mod h1:1jJ3jBArFh5pcgW8gCtRJnepW8FzD1V44FJffLiz/Ds= google.golang.org/genproto v0.0.0-20240213162025-012b6fc9bca9 h1:9+tzLLstTlPTRyJTh+ah5wIMsBW5c4tQwGTN3thOW9Y= google.golang.org/genproto v0.0.0-20240213162025-012b6fc9bca9/go.mod h1:mqHbVIp48Muh7Ywss/AD6I5kNVKZMmAa/QEW58Gxp2s= -google.golang.org/genproto/googleapis/api v0.0.0-20241118233622-e639e219e697 h1:pgr/4QbFyktUv9CtQ/Fq4gzEE6/Xs7iCXbktaGzLHbQ= -google.golang.org/genproto/googleapis/api v0.0.0-20241118233622-e639e219e697/go.mod h1:+D9ySVjN8nY8YCVjc5O7PZDIdZporIDY3KaGfJunh88= -google.golang.org/genproto/googleapis/rpc v0.0.0-20241118233622-e639e219e697 h1:LWZqQOEjDyONlF1H6afSWpAL/znlREo2tHfLoe+8LMA= -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.1 h1:yBPeRvTftaleIgM3PZ/WBIZ7XM/eEYAaEyCwvyjq/gk= -google.golang.org/protobuf v1.36.1/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= +google.golang.org/genproto/googleapis/api v0.0.0-20250102185135-69823020774d h1:H8tOf8XM88HvKqLTxe755haY6r1fqqzLbEnfrmLXlSA= +google.golang.org/genproto/googleapis/api v0.0.0-20250102185135-69823020774d/go.mod h1:2v7Z7gP2ZUOGsaFyxATQSRoBnKygqVq2Cwnvom7QiqY= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250102185135-69823020774d h1:xJJRGY7TJcvIlpSrN3K6LAWgNFUILlO+OMAqtg9aqnw= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250102185135-69823020774d/go.mod h1:3ENsm/5D1mzDyhpzeRi1NR784I0BcofWBoSc5QqqMK4= +google.golang.org/grpc v1.69.2 h1:U3S9QEtbXC0bYNvRtcoklF3xGtLViumSYxWykJS+7AU= +google.golang.org/grpc v1.69.2/go.mod h1:vyjdE6jLBI76dgpDojsFGNaHlxdjXN9ghpnd2o7JGZ4= +google.golang.org/protobuf v1.36.2 h1:R8FeyR1/eLmkutZOM5CWghmo5itiG9z0ktFlTVLuTmU= +google.golang.org/protobuf v1.36.2/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=
chore
Update dependencies
fb595f2c1407018789c0d77745c602334ed11f82
2022-09-25 21:05:25
Tom Payne
docs: Add link to article
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 411aaf74587..09560e80600 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 @@ -306,3 +306,8 @@ articles: title: 'Using chezmoi to automate dotfiles / config files (+ my bashrc)' format: Video url: https://www.youtube.com/watch?v=id5UKYuX4-A +- date: '2022-09-13' + version: '2.22.1' + title: 'Come installare Chezmoi: gestisci in modo sicuro i dotfile su più macchine' + lang: 'IT' + url: https://grayguide.net/it/come-installare-chezmoi-gestisci-in-modo-sicuro-i-dotfile-su-piu-macchine
docs
Add link to article
c320e7a19aa13901b32cd7e5ffcbd10e45531e63
2024-09-09 05:17:43
Tom Payne
chore: Update tools
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 9bfa7ffbcc7..0fd8f1146b8 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -21,7 +21,7 @@ env: GOLANGCI_LINT_VERSION: 1.60.3 # https://github.com/golangci/golangci-lint/releases GOLINES_VERSION: 0.12.2 # https://github.com/segmentio/golines/releases GORELEASER_VERSION: 2.2.0 # https://github.com/goreleaser/goreleaser/releases - GOVERSIONINFO_VERSION: 1.4.0 # https://github.com/josephspurrier/goversioninfo/releases + GOVERSIONINFO_VERSION: 1.4.1 # https://github.com/josephspurrier/goversioninfo/releases RAGE_VERSION: 0.10.0 # https://github.com/str4d/rage/releases jobs: changes:
chore
Update tools
829c62985b7cbbbb5f14477cddf263e74744a008
2024-06-17 04:40:05
Tom Payne
chore: Update dependencies
false
diff --git a/go.mod b/go.mod index b6e0f0e736e..2c8f09565ab 100644 --- a/go.mod +++ b/go.mod @@ -5,7 +5,7 @@ go 1.21.4 toolchain go1.22.0 require ( - filippo.io/age v1.1.1 + filippo.io/age v1.2.0 github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.6.0 github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.1.0 github.com/Masterminds/sprig/v3 v3.2.3 @@ -14,7 +14,7 @@ require ( github.com/alecthomas/assert/v2 v2.10.0 github.com/aws/aws-sdk-go-v2 v1.27.2 github.com/aws/aws-sdk-go-v2/config v1.27.18 - github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.29.3 + github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.30.0 github.com/bmatcuk/doublestar/v4 v4.6.1 github.com/bradenhilton/mozillainstallhash v1.0.1 github.com/charmbracelet/bubbles v0.18.0 @@ -27,7 +27,7 @@ require ( 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.8 + github.com/klauspost/compress v1.17.9 github.com/mitchellh/copystructure v1.2.0 github.com/mitchellh/mapstructure v1.5.0 github.com/muesli/combinator v0.3.0 @@ -35,7 +35,7 @@ require ( github.com/pelletier/go-toml/v2 v2.2.2 github.com/rogpeppe/go-internal v1.12.0 github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3 - github.com/spf13/cobra v1.8.0 + github.com/spf13/cobra v1.8.1 github.com/spf13/pflag v1.0.5 github.com/tailscale/hujson v0.0.0-20221223112325-20486734a56a github.com/twpayne/go-pinentry/v4 v4.0.0 @@ -44,7 +44,7 @@ require ( github.com/twpayne/go-xdg/v6 v6.1.3 github.com/ulikunitz/xz v0.5.12 github.com/zalando/go-keyring v0.2.5 - github.com/zricethezav/gitleaks/v8 v8.18.3 + 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/oauth2 v0.21.0 @@ -149,10 +149,10 @@ require ( github.com/subosito/gotenv v1.6.0 // indirect github.com/xanzy/ssh-agent v0.3.3 // indirect github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect - github.com/yuin/goldmark v1.7.1 // indirect + github.com/yuin/goldmark v1.7.2 // indirect github.com/yuin/goldmark-emoji v1.0.2 // indirect go.uber.org/multierr v1.11.0 // indirect - golang.org/x/exp v0.0.0-20240604190554-fc45aab8b7f8 // indirect + golang.org/x/exp v0.0.0-20240613232115-7f521ea00fb8 // indirect golang.org/x/net v0.26.0 // indirect golang.org/x/text v0.16.0 // indirect golang.org/x/tools v0.22.0 // indirect diff --git a/go.sum b/go.sum index 899471d9582..afdd7e17baa 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,5 @@ +c2sp.org/CCTV/age v0.0.0-20240306222714-3ec4d716e805 h1:u2qwJeEvnypw+OCPUHmoZE3IqwfuN5kgDfo5MLzpNM0= +c2sp.org/CCTV/age v0.0.0-20240306222714-3ec4d716e805/go.mod h1:FomMrUJ2Lxt5jCLmZkG3FHa72zUprnhd3v/Z18Snm4w= cloud.google.com/go v0.112.1 h1:uJSeirPke5UNZHIb4SxfZklVSiWWVqW4oXlETwZziwM= cloud.google.com/go v0.112.1/go.mod h1:+Vbu+Y1UU+I1rjmzeMOb/8RfkKJK2Gyxi1X6jJCZLo4= cloud.google.com/go/compute v1.24.0 h1:phWcR2eWzRJaL/kOiJwfFsPs4BaKq1j6vnpZrc1YlVg= @@ -14,10 +16,10 @@ cloud.google.com/go/storage v1.35.1 h1:B59ahL//eDfx2IIKFBeT5Atm9wnNmj3+8xG/W4WB/ 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= +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/Azure/azure-sdk-for-go/sdk/azcore v1.12.0 h1:1nGuui+4POelzDwI7RG56yfQJHCnKvwfMoU7VsEp+Zg= github.com/Azure/azure-sdk-for-go/sdk/azcore v1.12.0/go.mod h1:99EvauvlcJ1U06amZiksfYz/3aFGyIhWGHVyiZXtBAI= github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.6.0 h1:U2rTu3Ef+7w9FHKIAXM6ZyqF3UOWJZ12zIm8zECAFfg= @@ -80,8 +82,8 @@ github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.11.2 h1:Ji0DY1x 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.11 h1:o4T+fKxA3gTMcluBNZZXE9DNaMkJuUL1O3mffCUjoJo= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.11/go.mod h1:84oZdJ+VjuJKs9v1UTC9NaodRZRseOXCTgku+vQJWR8= -github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.29.3 h1:+pg3v9mWOmnR01Pxd0dcsDWSLN0GWbcFiKf2YgZ4+SY= -github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.29.3/go.mod h1:M9TqBwpQ7AC6zu1Yji7vijRliqir7hxjuRcnxIk7jCc= +github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.30.0 h1:nqR1mkoDntCpOwdlEfa2pZLiwvQeF4Mi56WzOTyuF/s= +github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.30.0/go.mod h1:M9TqBwpQ7AC6zu1Yji7vijRliqir7hxjuRcnxIk7jCc= github.com/aws/aws-sdk-go-v2/service/sso v1.20.11 h1:gEYM2GSpr4YNWc6hCd5nod4+d4kd9vWIAWrmGuLdlMw= github.com/aws/aws-sdk-go-v2/service/sso v1.20.11/go.mod h1:gVvwPdPNYehHSP9Rs7q27U1EU+3Or2ZpXvzAYJNh63w= github.com/aws/aws-sdk-go-v2/service/ssooidc v1.24.5 h1:iXjh3uaH3vsVcnyZX7MqCoCfcyxIrVE9iOQruRaWPrQ= @@ -129,8 +131,8 @@ github.com/coreos/go-semver v0.3.1 h1:yi21YpKnrx1gt5R+la8n5WgS0kCrsPp33dmEyHReZr 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/cpuguy83/go-md2man/v2 v2.0.4 h1:wfIWP927BUkWJb2NmU/kNDYIBTh/ziUX91+lVfRxZq4= +github.com/cpuguy83/go-md2man/v2 v2.0.4/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= @@ -272,8 +274,8 @@ github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7 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.8 h1:YcnTYrq7MikUT7k0Yb5eceMmALQPYBW/Xltxn0NAMnU= -github.com/klauspost/compress v1.17.8/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw= +github.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA= +github.com/klauspost/compress v1.17.9/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= @@ -404,8 +406,8 @@ github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNo github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= 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/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM= +github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y= 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= @@ -450,14 +452,14 @@ github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavM github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= github.com/yuin/goldmark v1.3.7/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -github.com/yuin/goldmark v1.7.1 h1:3bajkSilaCbjdKVsKdZjZCLBNPL9pYzrCakKaf4U49U= -github.com/yuin/goldmark v1.7.1/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E= +github.com/yuin/goldmark v1.7.2 h1:NjGd7lO7zrUn/A7eKwn5PEOt4ONYGqpxSEeZuduvgxc= +github.com/yuin/goldmark v1.7.2/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E= github.com/yuin/goldmark-emoji v1.0.2 h1:c/RgTShNgHTtc6xdz2KKI74jJr6rWi7FPgnP9GAsO5s= github.com/yuin/goldmark-emoji v1.0.2/go.mod h1:RhP/RWpexdp+KHs7ghKnifRoIs/Bq4nDS7tRbCkOwKY= github.com/zalando/go-keyring v0.2.5 h1:Bc2HHpjALryKD62ppdEzaFG6VxL6Bc+5v0LYpN8Lba8= github.com/zalando/go-keyring v0.2.5/go.mod h1:HL4k+OXQfJUWaMnqyuSOc0drfGPX2b51Du6K+MRgZMk= -github.com/zricethezav/gitleaks/v8 v8.18.3 h1:t+tMrQCMMlT/binrVyp8PMYs5vjiKBfph3WncYSE9j8= -github.com/zricethezav/gitleaks/v8 v8.18.3/go.mod h1:3EFYK+ZNDHPNQinyZTVGHG7/sFsApEZ9DrCGA1AP63M= +github.com/zricethezav/gitleaks/v8 v8.18.4 h1:mWOfVGO8ksok21iOb7h4DZMcUxyvsol8l6o1uNOQxww= +github.com/zricethezav/gitleaks/v8 v8.18.4/go.mod h1:3EFYK+ZNDHPNQinyZTVGHG7/sFsApEZ9DrCGA1AP63M= go.etcd.io/bbolt v1.3.10 h1:+BqfJTcCzTItrop8mq/lbzL8wSGtj94UO/3U31shqG0= go.etcd.io/bbolt v1.3.10/go.mod h1:bK3UQLPJZly7IlNmV7uVHJDxfe5aK9Ll93e/74Y9oEQ= go.etcd.io/etcd/api/v3 v3.5.12 h1:W4sw5ZoU2Juc9gBWuLk5U6fHfNVyY1WC5g9uiXZio/c= @@ -496,8 +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/exp v0.0.0-20240604190554-fc45aab8b7f8 h1:LoYXNGAShUG3m/ehNk4iFctuhGX/+R1ZpfJ4/ia80JM= -golang.org/x/exp v0.0.0-20240604190554-fc45aab8b7f8/go.mod h1:jj3sYF3dwk5D+ghuXyeI3r5MFf+NT2An6/9dOA95KSI= +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= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.18.0 h1:5+9lSbEzPSdWkH32vYPBwEpX8KwDbM52Ud9xBUvNlb0=
chore
Update dependencies
0f58586f49ae5b7f1aefe25d846e6d1531694035
2022-09-20 03:51:49
Daniel Slatkin
docs: Elaborate on once vs onchange attributes
false
diff --git a/assets/chezmoi.io/docs/reference/source-state-attributes.md b/assets/chezmoi.io/docs/reference/source-state-attributes.md index ecaf19177cd..2ac5e66c6a9 100644 --- a/assets/chezmoi.io/docs/reference/source-state-attributes.md +++ b/assets/chezmoi.io/docs/reference/source-state-attributes.md @@ -11,25 +11,25 @@ names. 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 destination | -| `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 | -| `literal_` | Stop parsing prefix attributes | -| `modify_` | Treat the contents as a script that modifies an existing file | -| `once_` | Only run the script if it has not been run before | -| `onchange_` | Only run the script if its contents have changed from the last time it was run | -| `private_` | Remove all group and world permissions from the target file or directory | -| `readonly_` | Remove all write permissions from the target file or directory | -| `remove_` | Remove the file or symlink if it exists or the directory if it is empty | -| `run_` | Treat the contents as a script to run | -| `symlink_` | Create a symlink instead of a regular file | +| Prefix | Effect | +| ------------- | ----------------------------------------------------------------------------------- | +| `after_` | Run script after updating the destination | +| `before_` | Run script before updating the destination | +| `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 | +| `literal_` | Stop parsing prefix attributes | +| `modify_` | Treat the contents as a script that modifies an existing file | +| `once_` | Only run the script if its contents have not been run before | +| `onchange_` | Only run the script if its contents have not been run before with the same filename | +| `private_` | Remove all group and world permissions from the target file or directory | +| `readonly_` | Remove all write permissions from the target file or directory | +| `remove_` | Remove the file or symlink if it exists or the directory if it is empty | +| `run_` | Treat the contents as a script to run | +| `symlink_` | Create a symlink instead of a regular file | | Suffix | Effect | | ---------- | --------------------------------------------------- |
docs
Elaborate on once vs onchange attributes
c24c5240fd5e13a2d5a1a96e825aca3c7d69b7cd
2021-12-26 08:19:40
Tom Payne
docs: Add doc on alias
false
diff --git a/docs/FAQ.md b/docs/FAQ.md index 355e19ffdc4..037b8cb07ab 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -585,7 +585,12 @@ directory. "chezmoi" splits to "chez moi" and pronounced /ʃeɪ mwa/ (shay-moi) meaning "at my house" in French. It's seven letters long, which is an appropriate length for -a command that is only run occasionally. +a command that is only run occasionally. If you prefer a shorter command, add an +alias to your shell configuration, for example: + +```sh +alias cz=chezmoi +``` ---
docs
Add doc on alias
187112da4ef1f5eb92c925cdf58ce92665c3d602
2022-05-16 23:58:29
Tom Payne
fix: Connect password manager std{in,err} to os.Std{in,err}
false
diff --git a/pkg/cmd/bitwardentemplatefuncs.go b/pkg/cmd/bitwardentemplatefuncs.go index d1052b76928..b31dbc55711 100644 --- a/pkg/cmd/bitwardentemplatefuncs.go +++ b/pkg/cmd/bitwardentemplatefuncs.go @@ -2,6 +2,7 @@ package cmd import ( "encoding/json" + "os" "os/exec" "strings" ) @@ -60,8 +61,8 @@ func (c *Config) bitwardenOutput(args []string) ([]byte, error) { name := c.Bitwarden.Command args = append([]string{"get"}, args...) cmd := exec.Command(name, args...) - cmd.Stdin = c.stdin - cmd.Stderr = c.stderr + cmd.Stdin = os.Stdin + cmd.Stderr = os.Stderr output, err := c.baseSystem.IdempotentCmdOutput(cmd) if err != nil { return nil, newCmdOutputError(cmd, output, err) diff --git a/pkg/cmd/gopasstemplatefuncs.go b/pkg/cmd/gopasstemplatefuncs.go index 9cc4d4b3d63..04f951c9a8b 100644 --- a/pkg/cmd/gopasstemplatefuncs.go +++ b/pkg/cmd/gopasstemplatefuncs.go @@ -1,6 +1,7 @@ package cmd import ( + "os" "os/exec" "regexp" @@ -83,8 +84,8 @@ func (c *Config) gopassRawTemplateFunc(id string) string { func (c *Config) gopassOutput(args ...string) ([]byte, error) { name := c.Gopass.Command cmd := exec.Command(name, args...) - cmd.Stdin = c.stdin - cmd.Stderr = c.stderr + cmd.Stdin = os.Stdin + cmd.Stderr = os.Stderr output, err := c.baseSystem.IdempotentCmdOutput(cmd) if err != nil { return nil, newCmdOutputError(cmd, output, err) diff --git a/pkg/cmd/keepassxctemplatefuncs.go b/pkg/cmd/keepassxctemplatefuncs.go index 8fc241c03a4..b5e64b45185 100644 --- a/pkg/cmd/keepassxctemplatefuncs.go +++ b/pkg/cmd/keepassxctemplatefuncs.go @@ -5,6 +5,7 @@ import ( "bytes" "errors" "fmt" + "os" "os/exec" "regexp" @@ -131,7 +132,7 @@ func (c *Config) keepassxcOutput(name string, args []string) ([]byte, error) { } cmd := exec.Command(name, args...) cmd.Stdin = bytes.NewBufferString(c.Keepassxc.password + "\n") - cmd.Stderr = c.stderr + cmd.Stderr = os.Stderr output, err := c.baseSystem.IdempotentCmdOutput(cmd) if err != nil { return nil, newCmdOutputError(cmd, output, err) diff --git a/pkg/cmd/lastpasstemplatefuncs.go b/pkg/cmd/lastpasstemplatefuncs.go index d0c7dc777d4..d7ae26a4125 100644 --- a/pkg/cmd/lastpasstemplatefuncs.go +++ b/pkg/cmd/lastpasstemplatefuncs.go @@ -5,6 +5,7 @@ import ( "bytes" "encoding/json" "fmt" + "os" "os/exec" "regexp" "strings" @@ -85,8 +86,8 @@ func (c *Config) lastpassData(id string) ([]map[string]interface{}, error) { func (c *Config) lastpassOutput(args ...string) ([]byte, error) { name := c.Lastpass.Command cmd := exec.Command(name, args...) - cmd.Stdin = c.stdin - cmd.Stderr = c.stderr + cmd.Stdin = os.Stdin + cmd.Stderr = os.Stderr output, err := c.baseSystem.IdempotentCmdOutput(cmd) if err != nil { return nil, err diff --git a/pkg/cmd/onepasswordtemplatefuncs.go b/pkg/cmd/onepasswordtemplatefuncs.go index 7342a6b9b59..bcc45eacd7a 100644 --- a/pkg/cmd/onepasswordtemplatefuncs.go +++ b/pkg/cmd/onepasswordtemplatefuncs.go @@ -1,7 +1,6 @@ package cmd import ( - "bytes" "encoding/json" "fmt" "os" @@ -270,9 +269,8 @@ func (c *Config) onepasswordGetOrRefreshSessionToken(args *onepasswordArgs) (str //nolint:gosec cmd := exec.Command(c.Onepassword.Command, commandArgs...) - cmd.Stdin = c.stdin - stderr := &bytes.Buffer{} - cmd.Stderr = stderr + cmd.Stdin = os.Stdin + cmd.Stderr = os.Stderr output, err := c.baseSystem.IdempotentCmdOutput(cmd) if err != nil { return "", newCmdOutputError(cmd, output, err) @@ -344,9 +342,8 @@ func (c *Config) onepasswordOutput(args *onepasswordArgs, withSessionToken withS //nolint:gosec cmd := exec.Command(c.Onepassword.Command, commandArgs...) - cmd.Stdin = c.stdin - stderr := &bytes.Buffer{} - cmd.Stderr = stderr + cmd.Stdin = os.Stdin + cmd.Stderr = os.Stderr output, err := c.baseSystem.IdempotentCmdOutput(cmd) if err != nil { return nil, newCmdOutputError(cmd, output, err) diff --git a/pkg/cmd/passtemplatefuncs.go b/pkg/cmd/passtemplatefuncs.go index d267ec96f48..f5496b411e4 100644 --- a/pkg/cmd/passtemplatefuncs.go +++ b/pkg/cmd/passtemplatefuncs.go @@ -2,6 +2,7 @@ package cmd import ( "bytes" + "os" "os/exec" "github.com/twpayne/chezmoi/v2/pkg/chezmoi" @@ -52,8 +53,8 @@ func (c *Config) passOutput(id string) ([]byte, error) { args := []string{"show", id} //nolint:gosec cmd := exec.Command(c.Pass.Command, args...) - cmd.Stdin = c.stdin - cmd.Stderr = c.stderr + cmd.Stdin = os.Stdin + cmd.Stderr = os.Stderr output, err := c.baseSystem.IdempotentCmdOutput(cmd) if err != nil { return nil, newCmdOutputError(cmd, output, err) diff --git a/pkg/cmd/secrettemplatefuncs.go b/pkg/cmd/secrettemplatefuncs.go index 3cec6de7b13..3d76e307db3 100644 --- a/pkg/cmd/secrettemplatefuncs.go +++ b/pkg/cmd/secrettemplatefuncs.go @@ -3,6 +3,7 @@ package cmd import ( "bytes" "encoding/json" + "os" "os/exec" "strings" ) @@ -21,8 +22,8 @@ func (c *Config) secretTemplateFunc(args ...string) string { //nolint:gosec cmd := exec.Command(c.Secret.Command, args...) - cmd.Stdin = c.stdin - cmd.Stderr = c.stderr + cmd.Stdin = os.Stdin + cmd.Stderr = os.Stderr output, err := c.baseSystem.IdempotentCmdOutput(cmd) if err != nil { panic(newCmdOutputError(cmd, output, err)) @@ -45,8 +46,8 @@ func (c *Config) secretJSONTemplateFunc(args ...string) interface{} { //nolint:gosec cmd := exec.Command(c.Secret.Command, args...) - cmd.Stdin = c.stdin - cmd.Stderr = c.stderr + cmd.Stdin = os.Stdin + cmd.Stderr = os.Stderr output, err := c.baseSystem.IdempotentCmdOutput(cmd) if err != nil { panic(newCmdOutputError(cmd, output, err)) diff --git a/pkg/cmd/vaulttemplatefuncs.go b/pkg/cmd/vaulttemplatefuncs.go index 74a983d6bfd..4683d9680a9 100644 --- a/pkg/cmd/vaulttemplatefuncs.go +++ b/pkg/cmd/vaulttemplatefuncs.go @@ -2,6 +2,7 @@ package cmd import ( "encoding/json" + "os" "os/exec" ) @@ -18,8 +19,8 @@ func (c *Config) vaultTemplateFunc(key string) interface{} { args := []string{"kv", "get", "-format=json", key} //nolint:gosec cmd := exec.Command(c.Vault.Command, args...) - cmd.Stdin = c.stdin - cmd.Stderr = c.stderr + cmd.Stdin = os.Stdin + cmd.Stderr = os.Stderr output, err := c.baseSystem.IdempotentCmdOutput(cmd) if err != nil { panic(newCmdOutputError(cmd, output, err))
fix
Connect password manager std{in,err} to os.Std{in,err}
f6ecfdb0e4c7cb59924d5870d7ece5e7711d1073
2024-07-09 03:57:24
Tom Payne
fix: Use scriptTempDir for modify_ scripts
false
diff --git a/internal/chezmoi/sourcestate.go b/internal/chezmoi/sourcestate.go index 5ac5e11ae94..9a72d2d17eb 100644 --- a/internal/chezmoi/sourcestate.go +++ b/internal/chezmoi/sourcestate.go @@ -120,6 +120,8 @@ type SourceState struct { sourceDirAbsPath AbsPath destDirAbsPath AbsPath cacheDirAbsPath AbsPath + createScriptTempDirOnce sync.Once + scriptTempDirAbsPath AbsPath umask fs.FileMode encryption Encryption ignore *patternSet @@ -231,6 +233,13 @@ func WithReadTemplates(readTemplates bool) SourceStateOption { } } +// WithScriptTempDir sets the source directory. +func WithScriptTempDir(scriptDirAbsPath AbsPath) SourceStateOption { + return func(s *SourceState) { + s.scriptTempDirAbsPath = scriptDirAbsPath + } +} + // WithSourceDir sets the source directory. func WithSourceDir(sourceDirAbsPath AbsPath) SourceStateOption { return func(s *SourceState) { @@ -1826,6 +1835,8 @@ func (s *SourceState) newModifyTargetStateEntryFunc( ) targetStateEntryFunc { return func(destSystem System, destAbsPath AbsPath) (TargetStateEntry, error) { contentsFunc := func() (contents []byte, err error) { + // FIXME this should share code with RealSystem.RunScript + // Read the current contents of the target. var currentContents []byte currentContents, err = destSystem.ReadFile(destAbsPath) @@ -1886,9 +1897,19 @@ func (s *SourceState) newModifyTargetStateEntryFunc( return } + // Create the script temporary directory, if needed. + s.createScriptTempDirOnce.Do(func() { + if !s.scriptTempDirAbsPath.Empty() { + err = os.MkdirAll(s.scriptTempDirAbsPath.String(), 0o700) + } + }) + if err != nil { + return + } + // Write the modifier to a temporary file. var tempFile *os.File - if tempFile, err = os.CreateTemp("", "*."+fileAttr.TargetName); err != nil { + if tempFile, err = os.CreateTemp(s.scriptTempDirAbsPath.String(), "*."+fileAttr.TargetName); err != nil { return } defer chezmoierrors.CombineFunc(&err, func() error { diff --git a/internal/cmd/config.go b/internal/cmd/config.go index 5afe3253fc3..d61bacec588 100644 --- a/internal/cmd/config.go +++ b/internal/cmd/config.go @@ -1749,6 +1749,7 @@ func (c *Config) newSourceState( chezmoi.WithLogger(sourceStateLogger), chezmoi.WithMode(c.Mode), chezmoi.WithPriorityTemplateData(c.Data), + chezmoi.WithScriptTempDir(c.ScriptTempDir), chezmoi.WithSourceDir(c.SourceDirAbsPath), chezmoi.WithSystem(c.sourceSystem), chezmoi.WithTemplateFuncs(c.templateFuncs), diff --git a/internal/cmd/testdata/scripts/scripttempdir.txtar b/internal/cmd/testdata/scripts/scripttempdir.txtar index 037492e4ad8..fb8299ea5ca 100644 --- a/internal/cmd/testdata/scripts/scripttempdir.txtar +++ b/internal/cmd/testdata/scripts/scripttempdir.txtar @@ -1,14 +1,19 @@ [windows] skip 'UNIX only' -# test that chezmoi apply with a scriptTempDir set creates a temporary directory +# test that chezmoi apply with a scriptTempDir set creates a temporary directory and runs scripts from that directory expandenv $CHEZMOICONFIGDIR/chezmoi.toml exec chezmoi apply -stdout ok +stdout $WORK/script-tmp/.*script\.sh/run_$ +grep $WORK/script-tmp/.*/modify_ $HOME/.file exists $WORK/script-tmp -- home/user/.config/chezmoi/chezmoi.toml -- scriptTempDir = "$WORK/script-tmp" +-- home/user/.local/share/chezmoi/modify_dot_file -- +#!/bin/sh + +echo $0/modify_ -- home/user/.local/share/chezmoi/run_script.sh -- #!/bin/sh -echo ok +echo $0/run_
fix
Use scriptTempDir for modify_ scripts
7a8d7e049822a583972e55917f70924055d319c1
2022-07-30 05:32:07
Tom Payne
chore: Fix case
false
diff --git a/pkg/cmd/initcmd.go b/pkg/cmd/initcmd.go index b1a4f58d947..468e112b038 100644 --- a/pkg/cmd/initcmd.go +++ b/pkg/cmd/initcmd.go @@ -110,7 +110,7 @@ func (c *Config) newInitCmd() *cobra.Command { } flags := initCmd.Flags() - flags.BoolVarP(&c.init.apply, "apply", "a", c.init.apply, "update destination directory") + flags.BoolVarP(&c.init.apply, "apply", "a", c.init.apply, "Update destination directory") flags.StringVar(&c.init.branch, "branch", c.init.branch, "Set initial branch to checkout") flags.VarP(&c.init.configPath, "config-path", "C", "Path to write generated config file") flags.BoolVar(&c.init.data, "data", c.init.data, "Include existing template data")
chore
Fix case
a993410a44d35f115a9244d4923b59970a526cdc
2024-11-07 23:26:01
Tom Payne
chore: Use choiceFlag for path style
false
diff --git a/internal/chezmoi/pathstyle.go b/internal/chezmoi/pathstyle.go deleted file mode 100644 index 320de16e32c..00000000000 --- a/internal/chezmoi/pathstyle.go +++ /dev/null @@ -1,88 +0,0 @@ -package chezmoi - -import ( - "fmt" - "strings" -) - -type ( - PathStyle string - PathStyleSimple string -) - -const ( - PathStyleAbsolute PathStyle = "absolute" - PathStyleRelative PathStyle = "relative" - PathStyleSourceAbsolute PathStyle = "source-absolute" - PathStyleSourceRelative PathStyle = "source-relative" -) - -var ( - PathStyleStrings = []string{ - PathStyleAbsolute.String(), - PathStyleRelative.String(), - PathStyleSourceAbsolute.String(), - PathStyleSourceRelative.String(), - } - - PathStyleFlagCompletionFunc = FlagCompletionFunc(PathStyleStrings) - - PathStyleSimpleStrings = []string{ - PathStyleAbsolute.String(), - PathStyleRelative.String(), - } - - PathStyleSimpleFlagCompletionFunc = FlagCompletionFunc(PathStyleSimpleStrings) -) - -// Set implements github.com/spf13/pflag.Value.Set. -func (p *PathStyle) Set(s string) error { - uniqueAbbreviations := UniqueAbbreviations(PathStyleStrings) - pathStyleStr, ok := uniqueAbbreviations[s] - if !ok { - return fmt.Errorf("%s: unknown path style", s) - } - *p = PathStyle(pathStyleStr) - return nil -} - -func (p PathStyle) String() string { - return string(p) -} - -// Type implements github.com/spf13/pflag.Value.Type. -func (p PathStyle) Type() string { - return strings.Join(PathStyleStrings, "|") -} - -func (p PathStyle) Copy() *PathStyle { - return &p -} - -// Set implements github.com/spf13/pflag.Value.Set. -func (p *PathStyleSimple) Set(s string) error { - uniqueAbbreviations := UniqueAbbreviations(PathStyleSimpleStrings) - pathStyleStr, ok := uniqueAbbreviations[s] - if !ok { - return fmt.Errorf("%s: unknown path style", s) - } - *p = PathStyleSimple(pathStyleStr) - return nil -} - -func (p PathStyleSimple) String() string { - return string(p) -} - -// Type implements github.com/spf13/pflag.Value.Type. -func (p PathStyleSimple) Type() string { - return strings.Join(PathStyleSimpleStrings, "|") -} - -func (p PathStyleSimple) Copy() *PathStyleSimple { - return &p -} - -func (p PathStyleSimple) ToPathStyle() PathStyle { - return PathStyle(p) -} diff --git a/internal/cmd/config.go b/internal/cmd/config.go index 4643f4024f7..769fb906f26 100644 --- a/internal/cmd/config.go +++ b/internal/cmd/config.go @@ -314,10 +314,9 @@ var ( whitespaceRx = regexp.MustCompile(`\s+`) commonFlagCompletionFuncs = map[string]func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective){ - "exclude": chezmoi.EntryTypeSetFlagCompletionFunc, - "include": chezmoi.EntryTypeSetFlagCompletionFunc, - "path-style": chezmoi.PathStyleFlagCompletionFunc, - "secrets": severityFlagCompletionFunc, + "exclude": chezmoi.EntryTypeSetFlagCompletionFunc, + "include": chezmoi.EntryTypeSetFlagCompletionFunc, + "secrets": severityFlagCompletionFunc, } ) @@ -383,7 +382,7 @@ func newConfig(options ...configOption) (*Config, error) { }, managed: managedCmdConfig{ filter: chezmoi.NewEntryTypeFilter(chezmoi.EntryTypesAll, chezmoi.EntryTypesNone), - pathStyle: chezmoi.PathStyleRelative, + pathStyle: newChoiceFlag("relative", []string{"absolute", "relative", "source-absolute", "source-relative"}), }, mergeAll: mergeAllCmdConfig{ recursive: true, @@ -404,7 +403,7 @@ func newConfig(options ...configOption) (*Config, error) { }, }, unmanaged: unmanagedCmdConfig{ - pathStyle: chezmoi.PathStyleSimple(chezmoi.PathStyleRelative), + pathStyle: newChoiceFlag("relative", []string{"absolute", "relative"}), }, // Configuration. @@ -2939,7 +2938,7 @@ func newConfigFile(bds *xdg.BaseDirectorySpecification) ConfigFile { }, Status: statusCmdConfig{ Exclude: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesNone), - PathStyle: chezmoi.PathStyleRelative.Copy(), + PathStyle: newChoiceFlag("relative", []string{"absolute", "relative"}), include: chezmoi.NewEntryTypeSet(chezmoi.EntryTypesAll), recursive: true, }, diff --git a/internal/cmd/managedcmd.go b/internal/cmd/managedcmd.go index fc662e3226e..6f7d710acb1 100644 --- a/internal/cmd/managedcmd.go +++ b/internal/cmd/managedcmd.go @@ -10,7 +10,7 @@ import ( type managedCmdConfig struct { filter *chezmoi.EntryTypeFilter - pathStyle chezmoi.PathStyle + pathStyle *choiceFlag tree bool } @@ -30,7 +30,8 @@ func (c *Config) newManagedCmd() *cobra.Command { managedCmd.Flags().VarP(c.managed.filter.Exclude, "exclude", "x", "Exclude entry types") managedCmd.Flags().VarP(c.managed.filter.Include, "include", "i", "Include entry types") - managedCmd.Flags().VarP(&c.managed.pathStyle, "path-style", "p", "Path style") + managedCmd.Flags().VarP(c.managed.pathStyle, "path-style", "p", "Path style") + must(managedCmd.RegisterFlagCompletionFunc("path-style", c.managed.pathStyle.FlagCompletionFunc())) managedCmd.Flags().BoolVarP(&c.managed.tree, "tree", "t", c.managed.tree, "Print paths as a tree") return managedCmd @@ -80,14 +81,14 @@ func (c *Config) runManagedCmd(cmd *cobra.Command, args []string, sourceState *c } var path fmt.Stringer - switch c.managed.pathStyle { - case chezmoi.PathStyleAbsolute: + switch c.managed.pathStyle.String() { + case "absolute": path = c.DestDirAbsPath.Join(targetRelPath) - case chezmoi.PathStyleRelative: + case "relative": path = targetRelPath - case chezmoi.PathStyleSourceAbsolute: + case "source-absolute": path = c.SourceDirAbsPath.Join(sourceStateEntry.SourceRelPath().RelPath()) - case chezmoi.PathStyleSourceRelative: + case "source-relative": path = sourceStateEntry.SourceRelPath().RelPath() } paths = append(paths, path) diff --git a/internal/cmd/statuscmd.go b/internal/cmd/statuscmd.go index 84363f5c3d5..326a1b3d5b7 100644 --- a/internal/cmd/statuscmd.go +++ b/internal/cmd/statuscmd.go @@ -1,7 +1,6 @@ package cmd import ( - "errors" "fmt" "io/fs" "log/slog" @@ -15,7 +14,7 @@ import ( type statusCmdConfig struct { Exclude *chezmoi.EntryTypeSet `json:"exclude" mapstructure:"exclude" yaml:"exclude"` - PathStyle *chezmoi.PathStyle `json:"pathStyle" mapstructure:"pathStyle" yaml:"pathStyle"` + PathStyle *choiceFlag `json:"pathStyle" mapstructure:"pathStyle" yaml:"pathStyle"` include *chezmoi.EntryTypeSet init bool parentDirs bool @@ -39,6 +38,7 @@ func (c *Config) newStatusCmd() *cobra.Command { statusCmd.Flags().VarP(c.Status.Exclude, "exclude", "x", "Exclude entry types") statusCmd.Flags().VarP(c.Status.PathStyle, "path-style", "p", "Path style") + must(statusCmd.RegisterFlagCompletionFunc("path-style", c.Status.PathStyle.FlagCompletionFunc())) statusCmd.Flags().VarP(c.Status.include, "include", "i", "Include entry types") statusCmd.Flags().BoolVar(&c.Status.init, "init", c.Status.init, "Recreate config file from template") statusCmd.Flags(). @@ -72,15 +72,13 @@ func (c *Config) runStatusCmd(cmd *cobra.Command, args []string) error { if x != ' ' || y != ' ' { var path string - switch *c.Status.PathStyle { - case chezmoi.PathStyleAbsolute: + switch pathStyle := c.Status.PathStyle.String(); pathStyle { + case "absolute": path = c.DestDirAbsPath.Join(targetRelPath).String() - case chezmoi.PathStyleRelative: + case "relative": path = targetRelPath.String() - case chezmoi.PathStyleSourceAbsolute: - return errors.New("source-absolute not supported for status") - case chezmoi.PathStyleSourceRelative: - return errors.New("source-relative not supported for status") + default: + return fmt.Errorf("%s: invalid path style", pathStyle) } fmt.Fprintf(&builder, "%c%c %s\n", x, y, path) diff --git a/internal/cmd/statuscmd_test.go b/internal/cmd/statuscmd_test.go index c8b68d5082f..7c88e8ab7aa 100644 --- a/internal/cmd/statuscmd_test.go +++ b/internal/cmd/statuscmd_test.go @@ -52,6 +52,16 @@ func TestStatusCmd(t *testing.T) { ` M .symlink`, ), }, + { + name: "path_style", + root: map[string]any{ + "/home/user/.config/chezmoi/chezmoi.toml": chezmoitest.JoinLines( + `[status]`, + ` pathStyle = "relative"`, + ), + "/home/user/.local/share/chezmoi": &vfst.Dir{Perm: 0o755}, + }, + }, } { t.Run(tc.name, func(t *testing.T) { chezmoitest.WithTestFS(t, tc.root, func(fileSystem vfs.FS) { diff --git a/internal/cmd/testdata/scripts/completion.txtar b/internal/cmd/testdata/scripts/completion.txtar index 80146957a63..a46a701911b 100644 --- a/internal/cmd/testdata/scripts/completion.txtar +++ b/internal/cmd/testdata/scripts/completion.txtar @@ -64,7 +64,7 @@ cmp stdout golden/output-format-with-empty # test that managed path style values are completed exec chezmoi __complete managed --path-style= -cmp stdout golden/path-style +cmp stdout golden/path-style-with-source # test that state data --format values are completed exec chezmoi __complete state data --format= @@ -137,6 +137,10 @@ yaml -- golden/path-style -- absolute relative +:4 +-- golden/path-style-with-source -- +absolute +relative source-absolute source-relative :4 diff --git a/internal/cmd/testdata/scripts/unmanaged.txtar b/internal/cmd/testdata/scripts/unmanaged.txtar index a197c4b2674..ffb53a7de81 100644 --- a/internal/cmd/testdata/scripts/unmanaged.txtar +++ b/internal/cmd/testdata/scripts/unmanaged.txtar @@ -33,7 +33,7 @@ cmp stdout golden/unmanaged-with-some-managed # test chezmoi unmanaged --path-style=source-absolute ! exec chezmoi unmanaged --path-style=source-absolute -stderr 'source-absolute: unknown path style' +stderr 'flag: invalid value' -- golden/unmanaged -- .local diff --git a/internal/cmd/unmanagedcmd.go b/internal/cmd/unmanagedcmd.go index b87616658cc..d332224f762 100644 --- a/internal/cmd/unmanagedcmd.go +++ b/internal/cmd/unmanagedcmd.go @@ -12,7 +12,7 @@ import ( ) type unmanagedCmdConfig struct { - pathStyle chezmoi.PathStyleSimple + pathStyle *choiceFlag tree bool } @@ -29,11 +29,10 @@ func (c *Config) newUnmanagedCmd() *cobra.Command { ), } - unmanagedCmd.Flags().VarP(&c.unmanaged.pathStyle, "path-style", "p", "Path style") + unmanagedCmd.Flags().VarP(c.unmanaged.pathStyle, "path-style", "p", "Path style") + must(unmanagedCmd.RegisterFlagCompletionFunc("path-style", c.unmanaged.pathStyle.FlagCompletionFunc())) unmanagedCmd.Flags().BoolVarP(&c.unmanaged.tree, "tree", "t", c.unmanaged.tree, "Print paths as a tree") - must(unmanagedCmd.RegisterFlagCompletionFunc("path-style", chezmoi.PathStyleSimpleFlagCompletionFunc)) - return unmanagedCmd } @@ -101,10 +100,13 @@ func (c *Config) runUnmanagedCmd(cmd *cobra.Command, args []string, sourceState paths := make([]fmt.Stringer, 0, len(unmanagedRelPaths.Elements())) for relPath := range unmanagedRelPaths { var path fmt.Stringer - if c.unmanaged.pathStyle.ToPathStyle() == chezmoi.PathStyleAbsolute { + switch pathStyle := c.unmanaged.pathStyle.String(); pathStyle { + case "absolute": path = c.DestDirAbsPath.Join(relPath) - } else { + case "relative": path = relPath + default: + return fmt.Errorf("%s: invalid path style", pathStyle) } paths = append(paths, path) }
chore
Use choiceFlag for path style
8ba1988d472246f7f60709e6074c64e8531ea3ed
2024-10-26 05:25:00
Tom Payne
fix: Fix panic when --keep-going is set
false
diff --git a/internal/cmd/lazywriter.go b/internal/cmd/lazywriter.go index e7b63629734..19201d359fd 100644 --- a/internal/cmd/lazywriter.go +++ b/internal/cmd/lazywriter.go @@ -1,11 +1,16 @@ package cmd -import "io" +import ( + "io" + "sync" +) // A lazyWriter only opens its destination on first write. type lazyWriter struct { + mutex sync.Mutex openFunc func() (io.WriteCloser, error) writeCloser io.WriteCloser + err error } func newLazyWriter(openFunc func() (io.WriteCloser, error)) *lazyWriter { @@ -15,6 +20,8 @@ func newLazyWriter(openFunc func() (io.WriteCloser, error)) *lazyWriter { } func (w *lazyWriter) Close() error { + w.mutex.Lock() + defer w.mutex.Unlock() if w.writeCloser == nil { return nil } @@ -22,13 +29,14 @@ func (w *lazyWriter) Close() error { } func (w *lazyWriter) Write(p []byte) (int, error) { - if w.writeCloser == nil { - writeCloser, err := w.openFunc() + w.mutex.Lock() + defer w.mutex.Unlock() + if w.openFunc != nil { + w.writeCloser, w.err = w.openFunc() w.openFunc = nil - if err != nil { - return 0, err - } - w.writeCloser = writeCloser + } + if w.err != nil { + return 0, w.err } return w.writeCloser.Write(p) } diff --git a/internal/cmd/testdata/scripts/issue4027.txtar b/internal/cmd/testdata/scripts/issue4027.txtar new file mode 100644 index 00000000000..0eee680d59c --- /dev/null +++ b/internal/cmd/testdata/scripts/issue4027.txtar @@ -0,0 +1,13 @@ +# test that chezmoi diff --keep-going does not panic when the diff pager command does not exist +! exec chezmoi diff --keep-going +! stderr panic +[!windows] stderr '/not/exist: no such file or directory' +[windows] stderr '"/not/exist": executable file not found in %PATH%' + +-- home/user/.config/chezmoi/chezmoi.toml -- +[diff] + pager = "/not/exist" +-- home/user/.local/share/chezmoi/dot_file1 -- +# contents of .file1 +-- home/user/.local/share/chezmoi/dot_file2 -- +# contents of .file2
fix
Fix panic when --keep-going is set
2409bd65a06fdd5ff69af94bc6a3df053d7a8320
2025-01-25 11:26:55
Tom Payne
chore: Fix comments in autocommit tests
false
diff --git a/internal/cmd/testdata/scripts/autocommit.txtar b/internal/cmd/testdata/scripts/autocommit.txtar index 1ed0d473760..23986acf21a 100644 --- a/internal/cmd/testdata/scripts/autocommit.txtar +++ b/internal/cmd/testdata/scripts/autocommit.txtar @@ -6,22 +6,22 @@ mkhomedir exec chezmoi init -# test that chezmoi add creates and pushes a commit +# test that chezmoi add creates a commit exec chezmoi add $HOME${/}.file exec git -C $CHEZMOISOURCEDIR show HEAD stdout 'Add \.file' -# test that chezmoi edit creates and pushes a commit +# test that chezmoi edit createspushes a commit exec chezmoi edit $HOME${/}.file exec git -C $CHEZMOISOURCEDIR show HEAD stdout 'Update \.file' -# test that chezmoi chattr creates and pushes a commit +# test that chezmoi chattr creates a commit exec chezmoi chattr +executable $HOME${/}.file exec git -C $CHEZMOISOURCEDIR show HEAD stdout 'Change attributes of \.file' -# test that chezmoi add on a directory creates and pushes a commit +# test that chezmoi add on a directory creates a commit exec chezmoi add $HOME${/}.dir exec git -C $CHEZMOISOURCEDIR show HEAD stdout 'Add \.dir/file' @@ -35,12 +35,12 @@ exec chezmoi edit $HOME${/}.dir${/}file exec git -C $CHEZMOISOURCEDIR show HEAD stdout 'Copy \.file to \.file2' -# test that chezmoi chattr on a file in a directory creates and pushes a commit +# test that chezmoi chattr on a file in a directory creates a commit exec chezmoi chattr --debug +private $HOME${/}.dir/file exec git -C $CHEZMOISOURCEDIR show HEAD stdout 'Change attributes of \.dir' -# test that chezmoi forget creates and pushes a commit +# test that chezmoi forget creates and commit exec chezmoi forget --force $HOME${/}.file2 exec git -C $CHEZMOISOURCEDIR show HEAD stdout 'Remove \.file2'
chore
Fix comments in autocommit tests
6a8778a13f71ed407a502884d27b5196bdbd4ed6
2024-12-09 22:20:53
Ruslan Sayfutdinov
chore: Run single Ubuntu build if there are no code changes
false
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 1a052c07d13..250dd156fe1 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -284,9 +284,11 @@ jobs: contents: read steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + if: github.event_name == 'push' || needs.changes.outputs.code == 'true' || (matrix.umask == '022' && matrix.test-index == 0) with: fetch-depth: 0 - uses: ./.github/actions/setup-go + if: github.event_name == 'push' || needs.changes.outputs.code == 'true' || (matrix.umask == '022' && matrix.test-index == 0) with: go-version: ${{ env.GO_VERSION }} - name: install-age @@ -297,15 +299,18 @@ jobs: sudo install -m 755 age/age /usr/local/bin sudo install -m 755 age/age-keygen /usr/local/bin - name: install-rage + if: github.event_name == 'push' || needs.changes.outputs.code == 'true' run: | cd "$(mktemp -d)" curl -fsSL "https://github.com/str4d/rage/releases/download/v${RAGE_VERSION}/rage-v${RAGE_VERSION}-x86_64-linux.tar.gz" | tar xzf - sudo install -m 755 rage/rage /usr/local/bin sudo install -m 755 rage/rage-keygen /usr/local/bin - name: build + if: github.event_name == 'push' || needs.changes.outputs.code == 'true' || (matrix.umask == '022' && matrix.test-index == 0) run: | go build -v ./... - name: run + if: github.event_name == 'push' || needs.changes.outputs.code == 'true' || (matrix.umask == '022' && matrix.test-index == 0) run: | go run . --version - name: test-umask-${{ matrix.umask }}
chore
Run single Ubuntu build if there are no code changes
f3071f48747caefe55aa1a9aab4acf6f7495fe81
2022-02-21 07:55:56
Tom Payne
chore: Rename logo image
false
diff --git a/README.md b/README.md index 89a9b17ae94..cc00efc495e 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# ![chezmoi logo](logo-144px.svg) chezmoi +# ![chezmoi logo](logo.svg) chezmoi [![GitHub Release](https://img.shields.io/github/release/twpayne/chezmoi.svg)](https://github.com/twpayne/chezmoi/releases) diff --git a/logo-144px.svg b/logo.svg similarity index 100% rename from logo-144px.svg rename to logo.svg
chore
Rename logo image
c5d370b5a4e92d4c38f9d75adb7efbe573cc17c8
2022-01-11 04:36:21
Simon Elsbrock
docs: Personal access token not needed with `--ssh`
false
diff --git a/docs/HOWTO.md b/docs/HOWTO.md index dd7b5bff607..2161ed05a80 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -128,8 +128,8 @@ with the repo, for example when pulling or pushing changes. chezmoi itself does not store any credentials, but instead relies on your local git configuration for these operations. -When using a private repo on GitHub, when prompted for a password you will need -to enter a [GitHub personal access +When using a private repo on GitHub without `--ssh`, when prompted for a +password you will need to enter a [GitHub personal access token](https://docs.github.com/en/github/authenticating-to-github/keeping-your-account-and-data-secure/creating-a-personal-access-token). For more information on these changes, read the [GitHub blog post on Token authentication requirements for Git
docs
Personal access token not needed with `--ssh`
75b54b7d6c4f28945b33f46bc834baa24aa9ba36
2024-11-07 23:26:01
Tom Payne
chore: Use choiceFlag for severity
false
diff --git a/internal/cmd/addcmd.go b/internal/cmd/addcmd.go index 881ae20a8c4..f6456defde8 100644 --- a/internal/cmd/addcmd.go +++ b/internal/cmd/addcmd.go @@ -10,10 +10,12 @@ import ( "github.com/twpayne/chezmoi/v2/internal/chezmoi" ) +var allowedSecretsValues = []string{"ignore", "warning", "error"} + type addCmdConfig struct { - Encrypt bool `json:"encrypt" mapstructure:"encrypt" yaml:"encrypt"` - Secrets severity `json:"secrets" mapstructure:"secrets" yaml:"secrets"` - TemplateSymlinks bool `json:"templateSymlinks" mapstructure:"templateSymlinks" yaml:"templateSymlinks"` + Encrypt bool `json:"encrypt" mapstructure:"encrypt" yaml:"encrypt"` + Secrets *choiceFlag `json:"secrets" mapstructure:"secrets" yaml:"secrets"` + TemplateSymlinks bool `json:"templateSymlinks" mapstructure:"templateSymlinks" yaml:"templateSymlinks"` autoTemplate bool create bool exact bool @@ -53,7 +55,8 @@ func (c *Config) newAddCmd() *cobra.Command { addCmd.Flags().BoolVarP(&c.Add.prompt, "prompt", "p", c.Add.prompt, "Prompt before adding each entry") addCmd.Flags().BoolVarP(&c.Add.quiet, "quiet", "q", c.Add.quiet, "Suppress warnings") addCmd.Flags().BoolVarP(&c.Add.recursive, "recursive", "r", c.Add.recursive, "Recurse into subdirectories") - addCmd.Flags().Var(&c.Add.Secrets, "secrets", "Scan for secrets when adding unencrypted files") + addCmd.Flags().Var(c.Add.Secrets, "secrets", "Scan for secrets when adding unencrypted files") + must(addCmd.RegisterFlagCompletionFunc("secrets", c.Add.Secrets.FlagCompletionFunc())) addCmd.Flags().BoolVarP(&c.Add.template, "template", "T", c.Add.template, "Add files as templates") addCmd.Flags(). BoolVar(&c.Add.TemplateSymlinks, "template-symlinks", c.Add.TemplateSymlinks, "Add symlinks with target in source or home dirs as templates") @@ -69,7 +72,7 @@ func (c *Config) defaultOnIgnoreFunc(targetRelPath chezmoi.RelPath) { func (c *Config) defaultPreAddFunc(targetRelPath chezmoi.RelPath, fileInfo fs.FileInfo) error { // Scan unencrypted files for secrets, if configured. - if c.Add.Secrets != severityIgnore && fileInfo.Mode().Type() == 0 && !c.Add.Encrypt { + if c.Add.Secrets.String() != "ignore" && fileInfo.Mode().Type() == 0 && !c.Add.Encrypt { absPath := c.DestDirAbsPath.Join(targetRelPath) content, err := c.destSystem.ReadFile(absPath) if err != nil { @@ -83,7 +86,7 @@ func (c *Config) defaultPreAddFunc(targetRelPath chezmoi.RelPath, fileInfo fs.Fi for _, finding := range findings { c.errorf("%s:%d: %s\n", absPath, finding.StartLine+1, finding.Description) } - if !c.force && c.Add.Secrets == severityError && len(findings) > 0 { + if !c.force && c.Add.Secrets.String() == "error" && len(findings) > 0 { return chezmoi.ExitCodeError(1) } } diff --git a/internal/cmd/config.go b/internal/cmd/config.go index 769fb906f26..ff8db38f258 100644 --- a/internal/cmd/config.go +++ b/internal/cmd/config.go @@ -316,7 +316,6 @@ var ( commonFlagCompletionFuncs = map[string]func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective){ "exclude": chezmoi.EntryTypeSetFlagCompletionFunc, "include": chezmoi.EntryTypeSetFlagCompletionFunc, - "secrets": severityFlagCompletionFunc, } ) @@ -2911,7 +2910,7 @@ func newConfigFile(bds *xdg.BaseDirectorySpecification) ConfigFile { // Command configurations. Add: addCmdConfig{ - Secrets: severityWarning, + Secrets: newChoiceFlag("warning", allowedSecretsValues), filter: chezmoi.NewEntryTypeFilter(chezmoi.EntryTypesAll, chezmoi.EntryTypesNone), recursive: true, }, diff --git a/internal/cmd/config_test.go b/internal/cmd/config_test.go index dddd4d30df4..5eaff1e3339 100644 --- a/internal/cmd/config_test.go +++ b/internal/cmd/config_test.go @@ -126,7 +126,7 @@ func TestConfigFileFormatRoundTrip(t *testing.T) { Recipients: []string{}, }, Add: addCmdConfig{ - Secrets: severityError, + Secrets: newChoiceFlag("warning", nil), }, CD: cdCmdConfig{ Args: []string{}, diff --git a/internal/cmd/mackupcmd_darwin.go b/internal/cmd/mackupcmd_darwin.go index b693d417de0..67795355fc7 100644 --- a/internal/cmd/mackupcmd_darwin.go +++ b/internal/cmd/mackupcmd_darwin.go @@ -53,7 +53,8 @@ func (c *Config) newMackupCmd() *cobra.Command { requiresSourceDirectory, ), } - mackupAddCmd.Flags().Var(&c.Add.Secrets, "secrets", "Scan for secrets when adding unencrypted files") + mackupAddCmd.Flags().Var(c.Add.Secrets, "secrets", "Scan for secrets when adding unencrypted files") + must(mackupAddCmd.RegisterFlagCompletionFunc("secrets", c.Add.Secrets.FlagCompletionFunc())) mackupCmd.AddCommand(mackupAddCmd) return mackupCmd diff --git a/internal/cmd/severity.go b/internal/cmd/severity.go deleted file mode 100644 index c1906c56cb1..00000000000 --- a/internal/cmd/severity.go +++ /dev/null @@ -1,60 +0,0 @@ -package cmd - -import ( - "fmt" - "strings" - - "github.com/twpayne/chezmoi/v2/internal/chezmoi" -) - -type severity string - -const ( - severityIgnore severity = "ignore" - severityWarning severity = "warning" - severityError severity = "error" -) - -var severityFlagCompletionFunc = chezmoi.FlagCompletionFunc([]string{ - "i", "ignore", - "w", "warning", - "e", "error", -}) - -// MarshalJSON implements encoding/json.Marshaler.MarshalJSON. -func (s severity) MarshalJSON() ([]byte, error) { - switch s { - case severityIgnore: - return []byte(`"ignore"`), nil - case severityWarning: - return []byte(`"warning"`), nil - case severityError: - return []byte(`"error"`), nil - default: - return []byte(`"unknown"`), nil - } -} - -// Set implements github.com/spf13/pflag.Value.Set. -func (s *severity) Set(str string) error { - switch strings.ToLower(str) { - case "i", "ignore": - *s = severityIgnore - case "w", "warning": - *s = severityWarning - case "e", "error": - *s = severityError - default: - return fmt.Errorf("%s: unknown severity", str) - } - return nil -} - -func (s *severity) String() string { - return string(*s) -} - -// Type implements github.com/spf13/pflag.Value.Type. -func (s *severity) Type() string { - return "ignore|warning|error" -} diff --git a/internal/cmd/testdata/scripts/completion.txtar b/internal/cmd/testdata/scripts/completion.txtar index a46a701911b..a8c3c8e66fc 100644 --- a/internal/cmd/testdata/scripts/completion.txtar +++ b/internal/cmd/testdata/scripts/completion.txtar @@ -150,12 +150,9 @@ auto never :4 -- golden/secrets -- -i +error ignore -w warning -e -error :4 -- golden/unmanaged-path-style -- absolute diff --git a/internal/cmd/testdata/scripts/completion_unix.txtar b/internal/cmd/testdata/scripts/completion_unix.txtar index 7c0e07007a5..38b6d6993cb 100644 --- a/internal/cmd/testdata/scripts/completion_unix.txtar +++ b/internal/cmd/testdata/scripts/completion_unix.txtar @@ -40,7 +40,6 @@ private .file :4 -- golden/complete-secrets-e -- -e error :4 -- golden/complete-target-home --
chore
Use choiceFlag for severity
8f98e1a5638fa16825aff973019023c1099fbcc8
2022-11-23 03:36:13
Tom Payne
fix: Respect diff filter in removes with external diff tool
false
diff --git a/pkg/chezmoi/externaldiffsystem.go b/pkg/chezmoi/externaldiffsystem.go index 4d94e3decdb..e915602de0c 100644 --- a/pkg/chezmoi/externaldiffsystem.go +++ b/pkg/chezmoi/externaldiffsystem.go @@ -134,8 +134,15 @@ func (s *ExternalDiffSystem) Readlink(name AbsPath) (string, error) { // Remove implements System.Remove. func (s *ExternalDiffSystem) Remove(name AbsPath) error { if s.filter.IncludeEntryTypeBits(EntryTypeRemove) { - if err := s.runDiffCommand(name, devNullAbsPath); err != nil { + switch fileInfo, err := s.system.Lstat(name); { + case errors.Is(err, fs.ErrNotExist): + // Do nothing. + case err != nil: return err + case s.filter.IncludeFileInfo(fileInfo): + if err := s.runDiffCommand(name, devNullAbsPath); err != nil { + return err + } } } return s.system.Remove(name) @@ -144,8 +151,15 @@ func (s *ExternalDiffSystem) Remove(name AbsPath) error { // RemoveAll implements System.RemoveAll. func (s *ExternalDiffSystem) RemoveAll(name AbsPath) error { if s.filter.IncludeEntryTypeBits(EntryTypeRemove) { - if err := s.runDiffCommand(name, devNullAbsPath); err != nil { + switch fileInfo, err := s.system.Lstat(name); { + case errors.Is(err, fs.ErrNotExist): + // Do nothing. + case err != nil: return err + case s.filter.IncludeFileInfo(fileInfo): + if err := s.runDiffCommand(name, devNullAbsPath); err != nil { + return err + } } } return s.system.RemoveAll(name) diff --git a/pkg/cmd/testdata/scripts/issue2573.txt b/pkg/cmd/testdata/scripts/issue2573.txt new file mode 100644 index 00000000000..b21ebdc34f4 --- /dev/null +++ b/pkg/cmd/testdata/scripts/issue2573.txt @@ -0,0 +1,17 @@ +[windows] skip 'UNIX only' +chmod 755 bin/diff + +# test that chezmoi apply --verbose with an external diff command and dirs excluded does not run the diff command when a directory is removed +exec chezmoi apply --verbose +! stdout diff + +-- bin/diff -- +#!/bin/sh + +echo diff $* +-- home/user/.config/chezmoi/chezmoi.toml -- +[diff] + command = "diff" + exclude = ["dirs"] +-- home/user/.dir/subdir/.keep -- +-- home/user/.local/share/chezmoi/exact_dot_dir/.keep --
fix
Respect diff filter in removes with external diff tool
569601a3066d9dcaab30502f6caf63442ec23bbb
2024-01-24 07:34:40
Philippe Altherr
fix: Change init to default to --config if --config-path is absent
false
diff --git a/internal/cmd/addcmd.go b/internal/cmd/addcmd.go index 4912bb0d35e..03904f10d30 100644 --- a/internal/cmd/addcmd.go +++ b/internal/cmd/addcmd.go @@ -208,7 +208,7 @@ func (c *Config) runAddCmd(cmd *cobra.Command, args []string, sourceState *chezm ProtectedAbsPaths: []chezmoi.AbsPath{ c.CacheDirAbsPath, c.WorkingTreeAbsPath, - c.configFileAbsPath, + c.getConfigFileAbsPath(), persistentStateFileAbsPath, c.sourceDirAbsPath, }, diff --git a/internal/cmd/catconfigcmd.go b/internal/cmd/catconfigcmd.go index d8b34035bbe..0bd269b7211 100644 --- a/internal/cmd/catconfigcmd.go +++ b/internal/cmd/catconfigcmd.go @@ -20,7 +20,7 @@ func (c *Config) newCatConfigCmd() *cobra.Command { } func (c *Config) runCatConfigCmd(cmd *cobra.Command, args []string) error { - data, err := c.baseSystem.ReadFile(c.configFileAbsPath) + data, err := c.baseSystem.ReadFile(c.getConfigFileAbsPath()) if err != nil { return err } diff --git a/internal/cmd/config.go b/internal/cmd/config.go index e02a718f059..7d04a1ba39f 100644 --- a/internal/cmd/config.go +++ b/internal/cmd/config.go @@ -215,16 +215,17 @@ type Config struct { versionStr string // Configuration. - fileSystem vfs.FS - bds *xdg.BaseDirectorySpecification - configFileAbsPath chezmoi.AbsPath - configFileAbsPathErr error - baseSystem chezmoi.System - sourceSystem chezmoi.System - destSystem chezmoi.System - persistentState chezmoi.PersistentState - httpClient *http.Client - logger *zerolog.Logger + fileSystem vfs.FS + bds *xdg.BaseDirectorySpecification + defaultConfigFileAbsPath chezmoi.AbsPath + defaultConfigFileAbsPathErr error + customConfigFileAbsPath chezmoi.AbsPath + baseSystem chezmoi.System + sourceSystem chezmoi.System + destSystem chezmoi.System + persistentState chezmoi.PersistentState + httpClient *http.Client + logger *zerolog.Logger // Computed configuration. commandDirAbsPath chezmoi.AbsPath @@ -500,7 +501,7 @@ func newConfig(options ...configOption) (*Config, error) { if err != nil { return nil, err } - c.configFileAbsPath, c.configFileAbsPathErr = c.defaultConfigFile(c.fileSystem, c.bds) + c.defaultConfigFileAbsPath, c.defaultConfigFileAbsPathErr = c.defaultConfigFile(c.fileSystem, c.bds) c.SourceDirAbsPath, err = c.defaultSourceDir(c.fileSystem, c.bds) if err != nil { return nil, err @@ -511,6 +512,13 @@ func newConfig(options ...configOption) (*Config, error) { return c, nil } +func (c *Config) getConfigFileAbsPath() chezmoi.AbsPath { + if c.customConfigFileAbsPath.Empty() { + return c.defaultConfigFileAbsPath + } + return c.customConfigFileAbsPath +} + // Close closes resources associated with c. func (c *Config) Close() error { errs := make([]error, 0, len(c.tempDirs)) @@ -749,7 +757,11 @@ func (c *Config) createAndReloadConfigFile(cmd *cobra.Command) error { // Write the config. configPath := c.init.configPath if c.init.configPath.Empty() { - configPath = chezmoi.NewAbsPath(c.bds.ConfigHome).Join(chezmoiRelPath, configTemplate.targetRelPath) + if c.customConfigFileAbsPath.Empty() { + configPath = chezmoi.NewAbsPath(c.bds.ConfigHome).Join(chezmoiRelPath, configTemplate.targetRelPath) + } else { + configPath = c.customConfigFileAbsPath + } } if err := chezmoi.MkdirAll(c.baseSystem, configPath.Dir(), fs.ModePerm); err != nil { return err @@ -1182,6 +1194,7 @@ func (c *Config) execute(args []string) error { return err } rootCmd.SetArgs(args) + return rootCmd.Execute() } @@ -1553,7 +1566,7 @@ func (c *Config) newRootCmd() (*cobra.Command, error) { persistentFlags.BoolVarP(&c.Verbose, "verbose", "v", c.Verbose, "Make output more verbose") persistentFlags.VarP(&c.WorkingTreeAbsPath, "working-tree", "W", "Set working tree directory") - persistentFlags.VarP(&c.configFileAbsPath, "config", "c", "Set config file") + persistentFlags.VarP(&c.customConfigFileAbsPath, "config", "c", "Set config file") persistentFlags.Var(&c.configFormat, "config-format", "Set config file format") persistentFlags.Var(&c.cpuProfile, "cpu-profile", "Write a CPU profile to path") persistentFlags.BoolVar(&c.debug, "debug", c.debug, "Include debug information in output") @@ -1750,7 +1763,7 @@ func (c *Config) persistentPostRunRootE(cmd *cobra.Command, args []string) error } if annotations.hasTag(modifiesConfigFile) { - configFileContents, err := c.baseSystem.ReadFile(c.configFileAbsPath) + configFileContents, err := c.baseSystem.ReadFile(c.getConfigFileAbsPath()) switch { case errors.Is(err, fs.ErrNotExist): err = nil @@ -1758,7 +1771,7 @@ func (c *Config) persistentPostRunRootE(cmd *cobra.Command, args []string) error // err is already set, do nothing. default: var format chezmoi.Format - if format, err = chezmoi.FormatFromAbsPath(c.configFileAbsPath); err == nil { + if format, err = chezmoi.FormatFromAbsPath(c.getConfigFileAbsPath()); err == nil { var config map[string]any if err = format.Unmarshal(configFileContents, &config); err != nil { //nolint:revive // err is already set, do nothing. @@ -1768,7 +1781,7 @@ func (c *Config) persistentPostRunRootE(cmd *cobra.Command, args []string) error } } if err != nil { - c.errorf("warning: %s: %v\n", c.configFileAbsPath, err) + c.errorf("warning: %s: %v\n", c.getConfigFileAbsPath(), err) } } @@ -1868,15 +1881,15 @@ func (c *Config) persistentPreRunRootE(cmd *cobra.Command, args []string) error // Read the config file. if annotations.hasTag(doesNotRequireValidConfig) { - if c.configFileAbsPathErr == nil { + if c.defaultConfigFileAbsPathErr == nil { _ = c.readConfig() } } else { - if c.configFileAbsPathErr != nil { - return c.configFileAbsPathErr + if c.defaultConfigFileAbsPathErr != nil { + return c.defaultConfigFileAbsPathErr } if err := c.readConfig(); err != nil { - return fmt.Errorf("invalid config: %s: %w", c.configFileAbsPath, err) + return fmt.Errorf("invalid config: %s: %w", c.getConfigFileAbsPath(), err) } } @@ -2031,7 +2044,7 @@ func (c *Config) persistentPreRunRootE(cmd *cobra.Command, args []string) error // Create the config directory if needed. if annotations.hasTag(requiresConfigDirectory) { - if err := chezmoi.MkdirAll(c.baseSystem, c.configFileAbsPath.Dir(), fs.ModePerm); err != nil { + if err := chezmoi.MkdirAll(c.baseSystem, c.getConfigFileAbsPath().Dir(), fs.ModePerm); err != nil { return err } } @@ -2156,8 +2169,8 @@ 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 + if !c.getConfigFileAbsPath().Empty() { + return c.getConfigFileAbsPath().Dir().Join(persistentStateFileRelPath), nil } for _, configDir := range c.bds.ConfigDirs { configDirAbsPath, err := chezmoi.NewAbsPathFromExtPath(configDir, c.homeDirAbsPath) @@ -2280,7 +2293,7 @@ func (c *Config) newTemplateData(cmd *cobra.Command) *templateData { command: cmd.Name(), commandDir: c.commandDirAbsPath, config: c.ConfigFile.toMap(), - configFile: c.configFileAbsPath, + configFile: c.getConfigFileAbsPath(), executable: chezmoi.NewAbsPath(executable), fqdnHostname: fqdnHostname, gid: gid, @@ -2308,7 +2321,7 @@ func (c *Config) newTemplateData(cmd *cobra.Command) *templateData { // readConfig reads the config file, if it exists. func (c *Config) readConfig() error { - switch err := c.decodeConfigFile(c.configFileAbsPath, &c.ConfigFile); { + switch err := c.decodeConfigFile(c.getConfigFileAbsPath(), &c.ConfigFile); { case errors.Is(err, fs.ErrNotExist): return nil default: diff --git a/internal/cmd/doctorcmd.go b/internal/cmd/doctorcmd.go index 8165d0c6822..249e5b7c740 100644 --- a/internal/cmd/doctorcmd.go +++ b/internal/cmd/doctorcmd.go @@ -191,7 +191,7 @@ func (c *Config) runDoctorCmd(cmd *cobra.Command, args []string) error { &configFileCheck{ basename: chezmoiRelPath, bds: c.bds, - expected: c.configFileAbsPath, + expected: c.getConfigFileAbsPath(), }, &dirCheck{ name: "source-dir", diff --git a/internal/cmd/editconfigcmd.go b/internal/cmd/editconfigcmd.go index 201af11aa69..d1cc9973685 100644 --- a/internal/cmd/editconfigcmd.go +++ b/internal/cmd/editconfigcmd.go @@ -24,5 +24,5 @@ func (c *Config) newEditConfigCmd() *cobra.Command { } func (c *Config) runEditConfigCmd(cmd *cobra.Command, args []string) error { - return c.runEditor([]string{c.configFileAbsPath.String()}) + return c.runEditor([]string{c.getConfigFileAbsPath().String()}) } diff --git a/internal/cmd/editconfigtemplatecmd.go b/internal/cmd/editconfigtemplatecmd.go index 7abfd8439b3..cf85fa4aa16 100644 --- a/internal/cmd/editconfigtemplatecmd.go +++ b/internal/cmd/editconfigtemplatecmd.go @@ -39,9 +39,9 @@ func (c *Config) runEditConfigTemplateCmd(cmd *cobra.Command, args []string, sou !errors.Is(err, fs.ErrExist) { return err } - configFileBase := "." + c.configFileAbsPath.Base() + ".tmpl" + configFileBase := "." + c.getConfigFileAbsPath().Base() + ".tmpl" configTemplateAbsPath = c.sourceDirAbsPath.JoinString(configFileBase) - switch data, err := c.baseSystem.ReadFile(c.configFileAbsPath); { + switch data, err := c.baseSystem.ReadFile(c.getConfigFileAbsPath()); { case errors.Is(err, fs.ErrNotExist): // Do nothing. case err != nil: diff --git a/internal/cmd/purgecmd.go b/internal/cmd/purgecmd.go index 1d2db3687eb..eca2a74efc2 100644 --- a/internal/cmd/purgecmd.go +++ b/internal/cmd/purgecmd.go @@ -60,7 +60,7 @@ func (c *Config) doPurge(options *doPurgeOptions) error { } if options.config { - absPaths = append(absPaths, c.configFileAbsPath.Dir(), c.configFileAbsPath) + absPaths = append(absPaths, c.getConfigFileAbsPath().Dir(), c.getConfigFileAbsPath()) } if options.persistentState { diff --git a/internal/cmd/testdata/scripts/init.txtar b/internal/cmd/testdata/scripts/init.txtar index fd5ada80a81..de36b843453 100644 --- a/internal/cmd/testdata/scripts/init.txtar +++ b/internal/cmd/testdata/scripts/init.txtar @@ -94,6 +94,14 @@ grep '# edited' $HOME/.file chhome home10/user +# test chezmoi --config init +mkgitconfig +exec chezmoi --config=$HOME/.chezmoi.toml init file://$WORK/home/user/.local/share/chezmoi +cmp $HOME/.chezmoi.toml golden/chezmoi.toml +! exists $CHEZMOICONFIGDIR/chezmoi.toml + +chhome home10-old/user + # test chezmoi init --config-path mkgitconfig exec chezmoi init --config-path=$HOME/.chezmoi.toml file://$WORK/home/user/.local/share/chezmoi diff --git a/internal/cmd/testdata/scripts/initconfig.txtar b/internal/cmd/testdata/scripts/initconfig.txtar new file mode 100644 index 00000000000..fbee94d47fe --- /dev/null +++ b/internal/cmd/testdata/scripts/initconfig.txtar @@ -0,0 +1,135 @@ +[windows] skip 'test requires path separator to be forward slash' +# test the init command with 3 different sets of --config/--config-format options + + +#### test chezmoi init + +chhome home1/user +mkdir $CHEZMOISOURCEDIR + +# test that chezmoi init writes the initial config into the defaul config dir +cp golden/chezmoi1.yaml $CHEZMOISOURCEDIR/.chezmoi.yaml.tmpl +exec chezmoi init +cmp $CHEZMOICONFIGDIR/chezmoi.yaml golden/chezmoi1.yaml + +# test that chezmoi init writes an updated config into the defaul config dir +cp golden/chezmoi2.yaml $CHEZMOISOURCEDIR/.chezmoi.yaml.tmpl +exec chezmoi init +cmp $CHEZMOICONFIGDIR/chezmoi.yaml golden/chezmoi2.yaml + +# test that chezmoi init writes a config of a new format into the defaul config dir +rm $CHEZMOISOURCEDIR/.chezmoi.yaml.tmpl +cp golden/chezmoi3.toml $CHEZMOISOURCEDIR/.chezmoi.toml.tmpl +exec chezmoi init +cmp $CHEZMOICONFIGDIR/chezmoi.yaml golden/chezmoi2.yaml +cmp $CHEZMOICONFIGDIR/chezmoi.toml golden/chezmoi3.toml + +# check that the last operation broke chezmoi +! exec chezmoi status +! stdout . +cmpenv stderr golden/error1.log + +# check that deleting the old config file fixes the issue +rm $CHEZMOICONFIGDIR/chezmoi.yaml +exec chezmoi status +! stdout . +! stderr . + +# check that the state file was written into the default config dir +exists $CHEZMOICONFIGDIR/chezmoistate.boltdb + + +#### test chezmoi --config=path init + +chhome home2/user +mkdir $CHEZMOISOURCEDIR + +# test that chezmoi --config=path init writes the initial config into path +cp golden/chezmoi1.yaml $CHEZMOISOURCEDIR/.chezmoi.yaml.tmpl +exec chezmoi --config=$HOME/.chezmoi/athome.yaml init +cmp $HOME/.chezmoi/athome.yaml golden/chezmoi1.yaml + +# test that chezmoi --config=path init writes an updated config into path +cp golden/chezmoi2.yaml $CHEZMOISOURCEDIR/.chezmoi.yaml.tmpl +exec chezmoi --config=$HOME/.chezmoi/athome.yaml init +cmp $HOME/.chezmoi/athome.yaml golden/chezmoi2.yaml + +# test that chezmoi --config=path init writes a config of a new format into path +rm $CHEZMOISOURCEDIR/.chezmoi.yaml.tmpl +cp golden/chezmoi3.toml $CHEZMOISOURCEDIR/.chezmoi.toml.tmpl +exec chezmoi --config=$HOME/.chezmoi/athome.yaml init +cmp $HOME/.chezmoi/athome.yaml golden/chezmoi3.toml + +# check that the last operation broke chezmoi +! exec chezmoi --config=$HOME/.chezmoi/athome.yaml status +! stdout . +cmpenv stderr golden/error2.log + +# check that renaming the file and updating the config path fixes the issue +mv $HOME/.chezmoi/athome.yaml $HOME/.chezmoi/athome.toml +exec chezmoi --config=$HOME/.chezmoi/athome.toml status +! stdout . +! stderr . + +# check that the state file was written next to the config file +exists $HOME/.chezmoi/chezmoistate.boltdb + +# check that nothing was ever written into the default config dir +! exists $CHEZMOICONFIGDIR/chezmoi.toml +! exists $CHEZMOICONFIGDIR/chezmoistate.boltdb + + +#### test chezmoi --config=path --config-format=format init + +chhome home3/user +mkdir $CHEZMOISOURCEDIR + +# test that chezmoi --config=path --config-format=format init writes the initial config into path +cp golden/chezmoi1.yaml $CHEZMOISOURCEDIR/.chezmoi.yaml.tmpl +exec chezmoi --config=$HOME/.chezmoi/athome.txt --config-format=yaml init +cmp $HOME/.chezmoi/athome.txt golden/chezmoi1.yaml + +# test that chezmoi --config=path --config-format=format init writes an updated config into path +cp golden/chezmoi2.yaml $CHEZMOISOURCEDIR/.chezmoi.yaml.tmpl +exec chezmoi --config=$HOME/.chezmoi/athome.txt --config-format=yaml init +cmp $HOME/.chezmoi/athome.txt golden/chezmoi2.yaml + +# test that chezmoi --config=path --config-format=format init writes a config of a new format into path +rm $CHEZMOISOURCEDIR/.chezmoi.yaml.tmpl +cp golden/chezmoi3.toml $CHEZMOISOURCEDIR/.chezmoi.toml.tmpl +exec chezmoi --config=$HOME/.chezmoi/athome.txt --config-format=yaml init +cmp $HOME/.chezmoi/athome.txt golden/chezmoi3.toml + +# check that the last operation broke chezmoi +! exec chezmoi --config=$HOME/.chezmoi/athome.txt --config-format=yaml status +! stdout . +cmpenv stderr golden/error3.log + +# check that updating the config format fixes the issue +exec chezmoi --config=$HOME/.chezmoi/athome.txt --config-format=toml status +! stdout . +! stderr . + +# check that the state file was written next to the config file +exists $HOME/.chezmoi/chezmoistate.boltdb + +# check that nothing was ever written into the default config dir +! exists $CHEZMOICONFIGDIR/chezmoi.toml +! exists $CHEZMOICONFIGDIR/chezmoistate.boltdb + + +-- golden/chezmoi1.yaml -- +data: + email: "[email protected]" +-- golden/chezmoi2.yaml -- +data: + email: "[email protected]" +-- golden/chezmoi3.toml -- +[data] + email = "[email protected]" +-- golden/error1.log -- +chezmoi: multiple config files: $CHEZMOICONFIGDIR/chezmoi.toml and $CHEZMOICONFIGDIR/chezmoi.yaml +-- golden/error2.log -- +chezmoi: invalid config: $HOME/.chezmoi/athome.yaml: yaml: unmarshal errors: line 1: cannot unmarshal !!seq into map[string]interface {} +-- golden/error3.log -- +chezmoi: invalid config: $HOME/.chezmoi/athome.txt: yaml: unmarshal errors: line 1: cannot unmarshal !!seq into map[string]interface {} diff --git a/internal/cmd/testdata/scripts/issue3127.txtar b/internal/cmd/testdata/scripts/issue3127.txtar new file mode 100644 index 00000000000..360bd8f1ef8 --- /dev/null +++ b/internal/cmd/testdata/scripts/issue3127.txtar @@ -0,0 +1,27 @@ +mkdir $CHEZMOISOURCEDIR + +# test that chezmoi --config=path init --config-path=path writes the initial config into path +cp golden/config1.toml $CHEZMOISOURCEDIR/.chezmoi.toml.tmpl +exec chezmoi --config=$HOME/config/athome.toml init --config-path=$HOME/config/athome.toml +cmp $HOME/config/athome.toml golden/config1.toml + +# test that chezmoi --config=path init --config-path=path writes an updated config into path +cp golden/config2.toml $CHEZMOISOURCEDIR/.chezmoi.toml.tmpl +exec chezmoi --config=$HOME/config/athome.toml init --config-path=$HOME/config/athome.toml +cmp $HOME/config/athome.toml golden/config2.toml + +# test that chezmoi --config=path init writes an updated config into path +cp golden/config3.toml $CHEZMOISOURCEDIR/.chezmoi.toml.tmpl +exec chezmoi --config=$HOME/config/athome.toml init +cmp $HOME/config/athome.toml golden/config3.toml + + +-- golden/config1.toml -- +[data] + email = "[email protected]" +-- golden/config2.toml -- +[data] + email = "[email protected]" +-- golden/config3.toml -- +[data] + email = "[email protected]"
fix
Change init to default to --config if --config-path is absent
006230cc05fc1fe017c942758ee92aee3058d9c5
2023-06-05 03:49:01
Tom Payne
fix: Fix parsing of flags to secret keyring delete command
false
diff --git a/pkg/cmd/secretkeyringcmd.go b/pkg/cmd/secretkeyringcmd.go index b0498a9db7c..d996dc493f7 100644 --- a/pkg/cmd/secretkeyringcmd.go +++ b/pkg/cmd/secretkeyringcmd.go @@ -43,8 +43,8 @@ func (c *Config) newSecretKeyringCmd() *cobra.Command { RunE: c.runSecretKeyringDeleteCmdE, } secretKeyringDeletePersistentFlags := keyringDeleteCmd.PersistentFlags() - secretKeyringDeletePersistentFlags.StringVar(&c.secret.keyring.get.service, "service", "", "service") - secretKeyringDeletePersistentFlags.StringVar(&c.secret.keyring.get.user, "user", "", "user") + secretKeyringDeletePersistentFlags.StringVar(&c.secret.keyring.delete.service, "service", "", "service") + secretKeyringDeletePersistentFlags.StringVar(&c.secret.keyring.delete.user, "user", "", "user") markPersistentFlagsRequired(keyringDeleteCmd, "service", "user") keyringCmd.AddCommand(keyringDeleteCmd)
fix
Fix parsing of flags to secret keyring delete command
9d1325b235d1f65c843e900e85ceef644d7221d9
2023-08-06 17:26:22
Arran Ubels
feat: Add isExecutable template function
false
diff --git a/assets/chezmoi.io/docs/reference/templates/functions/isExecutable.md b/assets/chezmoi.io/docs/reference/templates/functions/isExecutable.md new file mode 100644 index 00000000000..45b41b25b14 --- /dev/null +++ b/assets/chezmoi.io/docs/reference/templates/functions/isExecutable.md @@ -0,0 +1,11 @@ +# `isExecutable` *file* + +`isExecutable` returns true if a file is executable. + +!!! example + + ``` + {{ if isExecutable "/bin/echo" }} + # echo is executable + {{ end }} + ``` diff --git a/assets/chezmoi.io/mkdocs.yml b/assets/chezmoi.io/mkdocs.yml index f3415a88a47..5d9bd59d49a 100644 --- a/assets/chezmoi.io/mkdocs.yml +++ b/assets/chezmoi.io/mkdocs.yml @@ -195,6 +195,7 @@ nav: - include: reference/templates/functions/include.md - includeTemplate: reference/templates/functions/includeTemplate.md - ioreg: reference/templates/functions/ioreg.md + - isExecutable: reference/templates/functions/isExecutable.md - joinPath: reference/templates/functions/joinPath.md - jq: reference/templates/functions/jq.md - lookPath: reference/templates/functions/lookPath.md diff --git a/internal/chezmoi/chezmoi_unix.go b/internal/chezmoi/chezmoi_unix.go index dd8a57d2683..2aa7df61bd6 100644 --- a/internal/chezmoi/chezmoi_unix.go +++ b/internal/chezmoi/chezmoi_unix.go @@ -15,8 +15,8 @@ func init() { unix.Umask(int(Umask)) } -// isExecutable returns if fileInfo is executable. -func isExecutable(fileInfo fs.FileInfo) bool { +// IsExecutable returns if fileInfo is executable. +func IsExecutable(fileInfo fs.FileInfo) bool { return fileInfo.Mode().Perm()&0o111 != 0 } diff --git a/internal/chezmoi/chezmoi_windows.go b/internal/chezmoi/chezmoi_windows.go index 741fb0af623..6d0cd141e09 100644 --- a/internal/chezmoi/chezmoi_windows.go +++ b/internal/chezmoi/chezmoi_windows.go @@ -13,10 +13,10 @@ const nativeLineEnding = "\r\n" var pathExts = strings.Split(os.Getenv("PATHEXT"), string(filepath.ListSeparator)) -// isExecutable checks if the file is a regular file and has an extension listed +// IsExecutable checks if the file is a regular file and has an extension listed // in the PATHEXT environment variable as per // https://www.nextofwindows.com/what-is-pathext-environment-variable-in-windows. -func isExecutable(fileInfo fs.FileInfo) bool { +func IsExecutable(fileInfo fs.FileInfo) bool { if !fileInfo.Mode().IsRegular() { return false } diff --git a/internal/chezmoi/sourcestate.go b/internal/chezmoi/sourcestate.go index de514895b5a..21cc440f8e4 100644 --- a/internal/chezmoi/sourcestate.go +++ b/internal/chezmoi/sourcestate.go @@ -2092,7 +2092,7 @@ func (s *SourceState) newSourceStateFileEntryFromFile( fileAttr := FileAttr{ TargetName: fileInfo.Name(), Encrypted: options.Encrypt, - Executable: isExecutable(fileInfo), + Executable: IsExecutable(fileInfo), Private: isPrivate(fileInfo), ReadOnly: isReadOnly(fileInfo), Template: options.Template, @@ -2316,7 +2316,7 @@ func (s *SourceState) readExternalArchive( TargetName: fileInfo.Name(), Type: SourceFileTypeFile, Empty: fileInfo.Size() == 0, - Executable: isExecutable(fileInfo), + Executable: IsExecutable(fileInfo), Private: isPrivate(fileInfo), ReadOnly: isReadOnly(fileInfo), } @@ -2448,7 +2448,7 @@ func (s *SourceState) readExternalArchiveFile( TargetName: fileInfo.Name(), Type: SourceFileTypeFile, Empty: fileInfo.Size() == 0, - Executable: isExecutable(fileInfo) || external.Executable, + Executable: IsExecutable(fileInfo) || external.Executable, Private: isPrivate(fileInfo), ReadOnly: isReadOnly(fileInfo), } @@ -2530,7 +2530,7 @@ func (s *SourceState) readExternalDir( TargetName: fileInfo.Name(), Type: SourceFileTypeFile, Empty: true, - Executable: isExecutable(fileInfo), + Executable: IsExecutable(fileInfo), Private: isPrivate(fileInfo), ReadOnly: isReadOnly(fileInfo), } diff --git a/internal/cmd/config.go b/internal/cmd/config.go index 7fa56d818af..782d364449f 100644 --- a/internal/cmd/config.go +++ b/internal/cmd/config.go @@ -420,6 +420,7 @@ func newConfig(options ...configOption) (*Config, error) { "include": c.includeTemplateFunc, "includeTemplate": c.includeTemplateTemplateFunc, "ioreg": c.ioregTemplateFunc, + "isExecutable": c.isExecutableTemplateFunc, "joinPath": c.joinPathTemplateFunc, "jq": c.jqTemplateFunc, "keepassxc": c.keepassxcTemplateFunc, diff --git a/internal/cmd/templatefuncs.go b/internal/cmd/templatefuncs.go index 5231386a0d0..9537bd2e75c 100644 --- a/internal/cmd/templatefuncs.go +++ b/internal/cmd/templatefuncs.go @@ -315,6 +315,17 @@ func (c *Config) lookPathTemplateFunc(file string) string { } } +func (c *Config) isExecutableTemplateFunc(file string) bool { + switch fileInfo, err := c.fileSystem.Stat(file); { + case err == nil: + return chezmoi.IsExecutable(fileInfo) + case errors.Is(err, fs.ErrNotExist): + return false + default: + panic(err) + } +} + func (c *Config) lstatTemplateFunc(name string) any { switch fileInfo, err := c.fileSystem.Lstat(name); { case err == nil: diff --git a/internal/cmd/testdata/scripts/templatefuncs.txtar b/internal/cmd/testdata/scripts/templatefuncs.txtar index 0a95f6e4867..f41c74ceb2e 100644 --- a/internal/cmd/testdata/scripts/templatefuncs.txtar +++ b/internal/cmd/testdata/scripts/templatefuncs.txtar @@ -68,6 +68,14 @@ stdout a${/}b exec chezmoi execute-template '{{ dict "key" "value" | jq ".key" | first }}' stdout ^value$ +# test isExecutable template function positive test case +[!windows] exec chezmoi execute-template '{{ if isExecutable "/bin/echo" }}executable{{end}}' +[!windows] stdout ^executable$ + +# test isExecutable template function negative test case +[!windows] exec chezmoi execute-template '{{ if isExecutable "/etc/fstat" }}executable{{end}}' +[!windows] stdout ^$ + # test lookPath template function to find in PATH exec chezmoi execute-template '{{ lookPath "go" }}' stdout go$exe
feat
Add isExecutable template function
410f85e9c19e8959b74e65de42cb541447dba41a
2021-11-09 04:48:39
Tom Payne
chore: Add test for chattr --dry-run --verbose
false
diff --git a/internal/cmd/testdata/scripts/chattr.txt b/internal/cmd/testdata/scripts/chattr.txt index a5637b0e435..2921868aa0d 100644 --- a/internal/cmd/testdata/scripts/chattr.txt +++ b/internal/cmd/testdata/scripts/chattr.txt @@ -124,6 +124,14 @@ chezmoi chattr +executable,+private,+readonly,+template $HOME${/}.modify ! exists $CHEZMOISOURCEDIR/modify_dot_modify exists $CHEZMOISOURCEDIR/modify_private_readonly_executable_dot_modify.tmpl +# test that chezmoi chattr --dry-run --verbose generates a diff when a file is renamed +chezmoi chattr --dry-run --verbose +executable $HOME${/}.file +cmp stdout golden/chattr-diff + +-- golden/chattr-diff -- +diff --git a/dot_file b/executable_dot_file +rename from dot_file +rename to executable_dot_file -- home/user/.local/share/chezmoi/run_script -- #!/bin/sh -- home/user/.local/share/chezmoi/modify_dot_modify --
chore
Add test for chattr --dry-run --verbose
9b4cd47609d8af01e276a8d082171ebe98a2c178
2022-10-31 01:04:01
Tom Payne
chore: Minor documentation tweaks
false
diff --git a/assets/chezmoi.io/docs/quick-start.md b/assets/chezmoi.io/docs/quick-start.md index fef987d5d26..2da83244bdc 100644 --- a/assets/chezmoi.io/docs/quick-start.md +++ b/assets/chezmoi.io/docs/quick-start.md @@ -74,7 +74,7 @@ $ git commit -m "Initial commit" and then push your repo: ```console -$ git remote add origin https://github.com/username/dotfiles.git +$ git remote add origin https://github.com/$GITHUB_USERNAME/dotfiles.git $ git branch -M main $ git push -u origin main ``` @@ -119,7 +119,7 @@ sequenceDiagram On a second machine, initialize chezmoi with your dotfiles repo: ```console -$ chezmoi init https://github.com/username/dotfiles.git +$ chezmoi init https://github.com/$GITHUB_USERNAME/dotfiles.git ``` This will check out the repo and any submodules and optionally create a chezmoi @@ -157,13 +157,6 @@ On any machine, you can pull and apply the latest changes from your repo with: $ chezmoi update -v ``` -Alternatively, you can install your dotfiles on new machine with a single -command: - -```console -$ chezmoi init --apply https://github.com/username/dotfiles.git -``` - These commands are summarized in the this sequence diagram: ```mermaid @@ -185,7 +178,14 @@ sequenceDiagram You can install your dotfiles on new machine with a single command: ```console -$ chezmoi init --apply https://github.com/username/dotfiles.git +$ chezmoi init --apply https://github.com/$GITHUB_USERNAME/dotfiles.git +``` + +If you use GitHub and your dotfiles repo is called `dotfiles` then this can be +shortened to: + +```console +$ chezmoi init --apply $GITHUB_USERNAME ``` This command is summarized in the this sequence diagram: diff --git a/assets/chezmoi.io/docs/user-guide/setup.md b/assets/chezmoi.io/docs/user-guide/setup.md index 70668b03f09..1b194f76e3c 100644 --- a/assets/chezmoi.io/docs/user-guide/setup.md +++ b/assets/chezmoi.io/docs/user-guide/setup.md @@ -28,7 +28,7 @@ example: ```console $ chezmoi cd -$ git remote add origin https://github.com/username/dotfiles.git +$ git remote add origin https://github.com/$GITHUB_USERNAME/dotfiles.git $ git push -u origin main $ exit ``` @@ -36,7 +36,7 @@ $ exit On another machine you can checkout this repo: ```console -$ chezmoi init https://github.com/username/dotfiles.git +$ chezmoi init https://github.com/$GITHUB_USERNAME/dotfiles.git ``` You can then see what would be changed: @@ -54,7 +54,7 @@ $ chezmoi apply The above commands can be combined into a single init, checkout, and apply: ```console -$ chezmoi init --apply --verbose https://github.com/username/dotfiles.git +$ chezmoi init --apply --verbose https://github.com/$GITHUB_USERNAME/dotfiles.git ``` These commands are summarized this sequence diagram:
chore
Minor documentation tweaks
c37915689551662548f65d33126d24bfdd3a225f
2022-11-02 03:34:47
Tom Payne
feat: Add line ending template directive
false
diff --git a/pkg/chezmoi/chezmoi_unix.go b/pkg/chezmoi/chezmoi_unix.go index 2271189ea6c..7c82368ac50 100644 --- a/pkg/chezmoi/chezmoi_unix.go +++ b/pkg/chezmoi/chezmoi_unix.go @@ -9,6 +9,8 @@ import ( "golang.org/x/sys/unix" ) +const nativeLineEnding = "\n" + func init() { Umask = fs.FileMode(unix.Umask(0)) unix.Umask(int(Umask)) diff --git a/pkg/chezmoi/chezmoi_windows.go b/pkg/chezmoi/chezmoi_windows.go index 359281df077..a807449fd41 100644 --- a/pkg/chezmoi/chezmoi_windows.go +++ b/pkg/chezmoi/chezmoi_windows.go @@ -4,6 +4,8 @@ import ( "io/fs" ) +const nativeLineEnding = "\r\n" + // isExecutable returns false on Windows. func isExecutable(fileInfo fs.FileInfo) bool { return false diff --git a/pkg/chezmoi/sourcestate.go b/pkg/chezmoi/sourcestate.go index d536beefd1f..e211d4ede06 100644 --- a/pkg/chezmoi/sourcestate.go +++ b/pkg/chezmoi/sourcestate.go @@ -47,6 +47,7 @@ const ( ) var ( + lineEndingRx = regexp.MustCompile(`(?m)(?:\r\n|\r|\n)`) modifyTemplateRx = regexp.MustCompile(`(?m)^.*chezmoi:modify-template.*$(?:\r?\n)?`) templateDirectiveRx = regexp.MustCompile(`(?m)^.*?chezmoi:template:(.*)$(?:\r?\n)?`) templateDirectiveKeyValuePairRx = regexp.MustCompile(`\s*(\S+)=("(?:[^"]|\\")*"|\S+)`) diff --git a/pkg/chezmoi/sourcestate_test.go b/pkg/chezmoi/sourcestate_test.go index 7fbebaea419..e414dfdd08b 100644 --- a/pkg/chezmoi/sourcestate_test.go +++ b/pkg/chezmoi/sourcestate_test.go @@ -832,6 +832,40 @@ func TestSourceStateApplyAll(t *testing.T) { } } +func TestSourceStateExecuteTemplateData(t *testing.T) { + for _, tc := range []struct { + name string + dataStr string + expectedStr string + }{ + { + name: "line_ending_lf", + dataStr: "" + + "unix\n" + + "\n" + + "windows\r\n" + + "\r\n" + + "# chezmoi:template:line-ending=lf\n", + expectedStr: chezmoitest.JoinLines( + "unix", + "", + "windows", + "", + ), + }, + } { + t.Run(tc.name, func(t *testing.T) { + s := NewSourceState() + actual, err := s.ExecuteTemplateData(ExecuteTemplateDataOptions{ + Name: tc.name, + Data: []byte(tc.dataStr), + }) + assert.NoError(t, err) + assert.Equal(t, tc.expectedStr, string(actual)) + }) + } +} + func TestSourceStateRead(t *testing.T) { for _, tc := range []struct { name string @@ -1769,6 +1803,20 @@ func TestTemplateOptionsParseDirectives(t *testing.T) { Options: []string{"missingkey=zero"}, }, }, + { + name: "line_ending_crlf", + dataStr: "chezmoi:template:line-ending=crlf", + expected: TemplateOptions{ + LineEnding: "\r\n", + }, + }, + { + name: "line_ending_quoted", + dataStr: `chezmoi:template:line-ending="\n"`, + expected: TemplateOptions{ + LineEnding: "\n", + }, + }, } { t.Run(tc.name, func(t *testing.T) { var actual TemplateOptions diff --git a/pkg/chezmoi/template.go b/pkg/chezmoi/template.go index ced8b0cd26e..a5ae1ac0475 100644 --- a/pkg/chezmoi/template.go +++ b/pkg/chezmoi/template.go @@ -16,6 +16,7 @@ type Template struct { // TemplateOptions are template options that can be set with directives. type TemplateOptions struct { LeftDelimiter string + LineEnding string RightDelimiter string Options []string } @@ -52,7 +53,7 @@ func (t *Template) Execute(data any) ([]byte, error) { if err := t.template.ExecuteTemplate(&builder, t.name, data); err != nil { return nil, err } - return []byte(builder.String()), nil + return []byte(replaceLineEndings(builder.String(), t.options.LineEnding)), nil } // parseAndRemoveDirectives updates o by parsing all template directives in data @@ -73,6 +74,17 @@ func (o *TemplateOptions) parseAndRemoveDirectives(data []byte) []byte { switch key { case "left-delimiter": o.LeftDelimiter = value + case "line-ending": + switch string(keyValuePairMatch[2]) { + case "crlf": + o.LineEnding = "\r\n" + case "lf": + o.LineEnding = "\n" + case "native": + o.LineEnding = nativeLineEnding + default: + o.LineEnding = value + } case "right-delimiter": o.RightDelimiter = value case "missing-key": @@ -94,3 +106,12 @@ func removeMatches(data []byte, matchesIndexes [][]int) []byte { slices = append(slices, data[matchesIndexes[len(matchesIndexes)-1][1]:]) return bytes.Join(slices, nil) } + +// replaceLineEndings replaces all line endings in s with lineEnding. If +// lineEnding is empty it returns s unchanged. +func replaceLineEndings(s, lineEnding string) string { + if lineEnding == "" { + return s + } + return lineEndingRx.ReplaceAllString(s, lineEnding) +} diff --git a/pkg/chezmoi/template_test.go b/pkg/chezmoi/template_test.go index e3e1d19cc65..2576370db40 100644 --- a/pkg/chezmoi/template_test.go +++ b/pkg/chezmoi/template_test.go @@ -35,6 +35,35 @@ func TestTemplateParseAndExecute(t *testing.T) { "0", ), }, + { + name: "line_ending_crlf", + dataStr: "" + + "unix\n" + + "\n" + + "windows\r\n" + + "\r\n" + + "# chezmoi:template:line-ending=crlf\n", + expectedStr: "" + + "unix\r\n" + + "\r\n" + + "windows\r\n" + + "\r\n", + }, + { + name: "line_ending_lf", + dataStr: "" + + "unix\n" + + "\n" + + "windows\r\n" + + "\r\n" + + "# chezmoi:template:line-ending=lf\n", + expectedStr: chezmoitest.JoinLines( + "unix", + "", + "windows", + "", + ), + }, } { t.Run(tc.name, func(t *testing.T) { tmpl, err := ParseTemplate(tc.name, []byte(tc.dataStr), nil, TemplateOptions{})
feat
Add line ending template directive