refactor: move LoadFile to hrp/loader

This commit is contained in:
lilong.129
2024-08-19 22:42:53 +08:00
parent a9b864dc96
commit 89d0d4bb96
13 changed files with 106 additions and 109 deletions

View File

@@ -1,6 +1,7 @@
package hrp
import (
"bytes"
"io/fs"
"os"
"path/filepath"
@@ -8,6 +9,11 @@ import (
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
"gopkg.in/yaml.v2"
"github.com/httprunner/httprunner/v4/hrp/internal/builtin"
"github.com/httprunner/httprunner/v4/hrp/internal/code"
"github.com/httprunner/httprunner/v4/hrp/internal/json"
)
// LoadTestCases load testcases from TestCasePath or TestCase
@@ -63,3 +69,67 @@ func LoadTestCases(tests ...ITestCase) ([]*TestCase, error) {
log.Info().Int("count", len(testCases)).Msg("load testcases successfully")
return testCases, nil
}
// LoadFile loads file content with file extension and assigns to structObj
func LoadFile(path string, structObj interface{}) (err error) {
log.Info().Str("path", path).Msg("load file")
file, err := builtin.ReadFile(path)
if err != nil {
return errors.Wrap(err, "read file failed")
}
// remove BOM at the beginning of file
file = bytes.TrimLeft(file, "\xef\xbb\xbf")
ext := filepath.Ext(path)
switch ext {
case ".json", ".har":
decoder := json.NewDecoder(bytes.NewReader(file))
decoder.UseNumber()
err = decoder.Decode(structObj)
if err != nil {
err = errors.Wrap(code.LoadJSONError, err.Error())
}
case ".yaml", ".yml":
err = yaml.Unmarshal(file, structObj)
if err != nil {
err = errors.Wrap(code.LoadYAMLError, err.Error())
}
case ".env":
err = parseEnvContent(file, structObj)
if err != nil {
err = errors.Wrap(code.LoadEnvError, err.Error())
}
default:
err = code.UnsupportedFileExtension
}
return err
}
func parseEnvContent(file []byte, obj interface{}) error {
envMap := obj.(map[string]string)
lines := strings.Split(string(file), "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
// empty line or comment line
continue
}
var kv []string
if strings.Contains(line, "=") {
kv = strings.SplitN(line, "=", 2)
} else if strings.Contains(line, ":") {
kv = strings.SplitN(line, ":", 2)
}
if len(kv) != 2 {
return errors.New(".env format error")
}
key := strings.TrimSpace(kv[0])
value := strings.TrimSpace(kv[1])
envMap[key] = value
// set env
log.Info().Str("key", key).Msg("set env")
os.Setenv(key, value)
}
return nil
}