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
|
End of preview. Expand
in Data Studio
No dataset card yet
- Downloads last month
- 7