Files
backrest/internal/config/validationutil/validationutil.go
garethgeorge df4be0f7bc fix: miscellaneous bug fixes
* Fixes a problem with incorrectly scanning and removing pending events
   from the operation log for new installations
 * Fixes a bug with the operation tree incorrectly applying query
   selectors when filtering events
 * Updates tooltips and comments in PlanView and GettingStartedGuide
2024-05-18 21:14:02 -07:00

44 lines
1.2 KiB
Go

package validationutil
import (
"errors"
"fmt"
"regexp"
"strings"
)
var (
IDMaxLen = 50 // maximum length of an ID
sanitizeIDRegex = regexp.MustCompile(`[^a-zA-Z0-9_\-\.]+`) // matches invalid characters in an ID
idRegex = regexp.MustCompile(`[a-zA-Z0-9_\-\.]*`) // matches a valid ID (including empty string)
)
var (
ErrEmpty = errors.New("empty")
ErrTooLong = errors.New("too long")
ErrInvalidChars = errors.New("contains invalid characters")
)
func SanitizeID(id string) string {
return sanitizeIDRegex.ReplaceAllString(id, "_")
}
// ValidateID checks if an ID is valid.
// It returns an error if the ID contains invalid characters, is empty, or is too long.
// The maxLen parameter is the maximum length of the ID. If maxLen is 0, the ID length is not checked.
func ValidateID(id string, maxLen int) error {
if strings.HasPrefix(id, "_") && strings.HasSuffix(id, "_") {
return errors.New("IDs starting and ending with '_' are reserved by backrest")
}
if !idRegex.MatchString(id) {
return ErrInvalidChars
}
if len(id) == 0 {
return ErrEmpty
}
if maxLen > 0 && len(id) > maxLen {
return fmt.Errorf("(> %d chars): %w", maxLen, ErrTooLong)
}
return nil
}