From 1e183f60eea7c065ac84621f617c34b8eab75e24 Mon Sep 17 00:00:00 2001 From: Pierre-Olivier Mercier Date: Wed, 16 Jan 2019 04:52:34 +0100 Subject: [PATCH] libfic: extract validation_regexp execution --- libfic/flag_key.go | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/libfic/flag_key.go b/libfic/flag_key.go index 739abe14..0324325b 100644 --- a/libfic/flag_key.go +++ b/libfic/flag_key.go @@ -72,6 +72,16 @@ func getHashedFlag(raw_value []byte) [blake2b.Size]byte { return hash } +func ExecValidatorRegexp(vre string, val []byte) ([]byte, error) { + if re, err := regexp.Compile(vre); err != nil { + return val, err + } else if res := re.FindSubmatch(val); res == nil { + return val, errors.New("Expected flag doesn't pass through the validator_regexp") + } else { + return bytes.Join(res[1:], []byte("+")), nil + } +} + // AddRawFlagKey creates and fills a new struct FlagKey, from a non-hashed flag, and registers it into the database. func (e Exercice) AddRawFlagKey(name string, help string, ignorecase bool, validator_regexp *string, raw_value []byte, choicescost int64) (FlagKey, error) { if ignorecase { @@ -80,12 +90,9 @@ func (e Exercice) AddRawFlagKey(name string, help string, ignorecase bool, valid // Check that raw value passes through the regexp if validator_regexp != nil { - if re, err := regexp.Compile(*validator_regexp); err != nil { + var err error + if raw_value, err = ExecValidatorRegexp(*validator_regexp, raw_value); err != nil { return FlagKey{}, err - } else if res := re.FindSubmatch(raw_value); res == nil { - return FlagKey{}, errors.New("Expected flag doesn't pass through the validator_regexp") - } else { - raw_value = bytes.Join(res[1:], []byte("+")) } } @@ -194,10 +201,7 @@ func (k FlagKey) Check(v interface{}) int { // Check that raw value passes through the regexp if k.ValidatorRegexp != nil { - re := regexp.MustCompile(*k.ValidatorRegexp) - if res := re.FindSubmatch(val); res != nil { - val = bytes.Join(res[1:], []byte("+")) - } + val, _ = ExecValidatorRegexp(*k.ValidatorRegexp, val) } // Check that the value is not empty