Files
Sebastian Unterschütz e5bde9c61f
Test / test (push) Successful in 4m4s
Release / release (push) Successful in 7m39s
feat: add host actions, lifecycle hooks and operational tools
2026-11-18 10:41:36 +01:00

74 lines
2.5 KiB
Go

package config
import (
"fmt"
"regexp"
"strings"
"time"
)
// HostCommand defines a local command and the prefix of its generated host aliases.
type HostCommand struct {
PostRun string `mapstructure:"post_run"`
Match SSHMatch `mapstructure:"match"`
Confirm bool `mapstructure:"confirm"`
Timeout string `mapstructure:"timeout"`
AliasPrefix string `mapstructure:"alias_prefix" yaml:"alias_prefix"`
Args []string `mapstructure:"args" yaml:"args"`
}
func (c *Config) ValidateCommands() error {
prefixes := make(map[string]bool)
for name, command := range c.Commands {
if strings.ContainsRune(command.PostRun, 0) {
return fmt.Errorf("commands.%s.post_run contains NUL", name)
}
if command.Match != (SSHMatch{}) {
if err := command.Match.Validate("commands." + name); err != nil {
return err
}
}
if command.Timeout != "" {
d, err := time.ParseDuration(command.Timeout)
if err != nil || d <= 0 {
return fmt.Errorf("commands.%s.timeout requires a positive duration", name)
}
}
if name == "" || ValidateCommandAlias(name) != nil {
return fmt.Errorf("commands.%s: name must be a non-reserved shell identifier", name)
}
if command.AliasPrefix != "" {
if !regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*$`).MatchString(command.AliasPrefix) {
return fmt.Errorf("commands.%s.alias_prefix must be a shell identifier", name)
}
if prefixes[command.AliasPrefix] {
return fmt.Errorf("commands.%s: duplicate alias_prefix %q", name, command.AliasPrefix)
}
prefixes[command.AliasPrefix] = true
}
if len(command.Args) == 0 || strings.TrimSpace(command.Args[0]) == "" {
return fmt.Errorf("commands.%s.args requires an executable", name)
}
target := false
for i, arg := range command.Args {
if strings.ContainsRune(arg, 0) {
return fmt.Errorf("commands.%s.args cannot contain NUL", name)
}
if i == 0 && strings.ContainsAny(arg, "{}") {
return fmt.Errorf("commands.%s: executable cannot contain placeholders", name)
}
if strings.Contains(arg, "{host}") || strings.Contains(arg, "{address}") || strings.Contains(arg, "{target}") {
target = true
}
rest := strings.NewReplacer("{host}", "", "{address}", "", "{target}", "").Replace(arg)
if strings.ContainsAny(rest, "{}") {
return fmt.Errorf("commands.%s: supported placeholders are {host}, {address}, {target}", name)
}
}
if !target {
return fmt.Errorf("commands.%s.args requires {host}, {address}, or {target}", name)
}
}
return nil
}