mirror of
https://github.com/argoproj/argo-cd.git
synced 2026-02-20 01:28:45 +01:00
chore(lint): enable builtinShadow rule from go-critic (#23430)
Signed-off-by: Matthieu MOREL <matthieu.morel35@gmail.com>
This commit is contained in:
@@ -53,9 +53,8 @@ linters:
|
||||
# Most of these should probably be enabled one-by-one.
|
||||
disabled-checks:
|
||||
- appendAssign
|
||||
- appendCombine
|
||||
- assignOp
|
||||
- builtinShadow
|
||||
- appendCombine # Leave disabled, multi-line assigns can be more readable.
|
||||
- assignOp # Leave disabled, assign operations can be more confusing than helpful.
|
||||
- commentedOutCode
|
||||
- deferInLoop
|
||||
- exitAfterDefer
|
||||
@@ -63,7 +62,7 @@ linters:
|
||||
- filepathJoin
|
||||
- hugeParam
|
||||
- importShadow
|
||||
- paramTypeCombine
|
||||
- paramTypeCombine # Leave disabled, there are too many failures to be worth fixing.
|
||||
- rangeValCopy
|
||||
- sloppyReassign
|
||||
- tooManyResultsChecker
|
||||
|
||||
@@ -58,9 +58,9 @@ func copyValueIntoUnexported(destination, value reflect.Value) {
|
||||
Set(value)
|
||||
}
|
||||
|
||||
func copyUnexported(copy, original reflect.Value) {
|
||||
func copyUnexported(destination, original reflect.Value) {
|
||||
unexported := reflect.NewAt(original.Type(), unsafe.Pointer(original.UnsafeAddr())).Elem()
|
||||
copyValueIntoUnexported(copy, unexported)
|
||||
copyValueIntoUnexported(destination, unexported)
|
||||
}
|
||||
|
||||
func IsJSONStr(str string) bool {
|
||||
@@ -81,7 +81,7 @@ func ConvertYAMLToJSON(str string) (string, error) {
|
||||
|
||||
// This function is in charge of searching all String fields of the object recursively and apply templating
|
||||
// thanks to https://gist.github.com/randallmlough/1fd78ec8a1034916ca52281e3b886dc7
|
||||
func (r *Render) deeplyReplace(copy, original reflect.Value, replaceMap map[string]any, useGoTemplate bool, goTemplateOptions []string) error {
|
||||
func (r *Render) deeplyReplace(destination, original reflect.Value, replaceMap map[string]any, useGoTemplate bool, goTemplateOptions []string) error {
|
||||
switch original.Kind() {
|
||||
// The first cases handle nested structures and translate them recursively
|
||||
// If it is a pointer we need to unwrap and call once again
|
||||
@@ -96,12 +96,12 @@ func (r *Render) deeplyReplace(copy, original reflect.Value, replaceMap map[stri
|
||||
}
|
||||
// Allocate a new object and set the pointer to it
|
||||
if originalValue.CanSet() {
|
||||
copy.Set(reflect.New(originalValue.Type()))
|
||||
destination.Set(reflect.New(originalValue.Type()))
|
||||
} else {
|
||||
copyUnexported(copy, original)
|
||||
copyUnexported(destination, original)
|
||||
}
|
||||
// Unwrap the newly created pointer
|
||||
if err := r.deeplyReplace(copy.Elem(), originalValue, replaceMap, useGoTemplate, goTemplateOptions); err != nil {
|
||||
if err := r.deeplyReplace(destination.Elem(), originalValue, replaceMap, useGoTemplate, goTemplateOptions); err != nil {
|
||||
// Not wrapping the error, since this is a recursive function. Avoids excessively long error messages.
|
||||
return err
|
||||
}
|
||||
@@ -126,7 +126,7 @@ func (r *Render) deeplyReplace(copy, original reflect.Value, replaceMap map[stri
|
||||
// Not wrapping the error, since this is a recursive function. Avoids excessively long error messages.
|
||||
return err
|
||||
}
|
||||
copy.Set(copyValue)
|
||||
destination.Set(copyValue)
|
||||
}
|
||||
|
||||
// If it is a struct we translate each field
|
||||
@@ -135,7 +135,7 @@ func (r *Render) deeplyReplace(copy, original reflect.Value, replaceMap map[stri
|
||||
currentType := fmt.Sprintf("%s.%s", original.Type().Field(i).Name, original.Type().PkgPath())
|
||||
// specific case time
|
||||
if currentType == "time.Time" {
|
||||
copy.Field(i).Set(original.Field(i))
|
||||
destination.Field(i).Set(original.Field(i))
|
||||
} else if currentType == "Raw.k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" || currentType == "Raw.k8s.io/apimachinery/pkg/runtime" {
|
||||
var unmarshaled any
|
||||
originalBytes := original.Field(i).Bytes()
|
||||
@@ -158,8 +158,8 @@ func (r *Render) deeplyReplace(copy, original reflect.Value, replaceMap map[stri
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal templated JSON field: %w", err)
|
||||
}
|
||||
copy.Field(i).Set(reflect.ValueOf(data))
|
||||
} else if err := r.deeplyReplace(copy.Field(i), original.Field(i), replaceMap, useGoTemplate, goTemplateOptions); err != nil {
|
||||
destination.Field(i).Set(reflect.ValueOf(data))
|
||||
} else if err := r.deeplyReplace(destination.Field(i), original.Field(i), replaceMap, useGoTemplate, goTemplateOptions); err != nil {
|
||||
// Not wrapping the error, since this is a recursive function. Avoids excessively long error messages.
|
||||
return err
|
||||
}
|
||||
@@ -167,14 +167,14 @@ func (r *Render) deeplyReplace(copy, original reflect.Value, replaceMap map[stri
|
||||
|
||||
// If it is a slice we create a new slice and translate each element
|
||||
case reflect.Slice:
|
||||
if copy.CanSet() {
|
||||
copy.Set(reflect.MakeSlice(original.Type(), original.Len(), original.Cap()))
|
||||
if destination.CanSet() {
|
||||
destination.Set(reflect.MakeSlice(original.Type(), original.Len(), original.Cap()))
|
||||
} else {
|
||||
copyValueIntoUnexported(copy, reflect.MakeSlice(original.Type(), original.Len(), original.Cap()))
|
||||
copyValueIntoUnexported(destination, reflect.MakeSlice(original.Type(), original.Len(), original.Cap()))
|
||||
}
|
||||
|
||||
for i := 0; i < original.Len(); i++ {
|
||||
if err := r.deeplyReplace(copy.Index(i), original.Index(i), replaceMap, useGoTemplate, goTemplateOptions); err != nil {
|
||||
if err := r.deeplyReplace(destination.Index(i), original.Index(i), replaceMap, useGoTemplate, goTemplateOptions); err != nil {
|
||||
// Not wrapping the error, since this is a recursive function. Avoids excessively long error messages.
|
||||
return err
|
||||
}
|
||||
@@ -182,10 +182,10 @@ func (r *Render) deeplyReplace(copy, original reflect.Value, replaceMap map[stri
|
||||
|
||||
// If it is a map we create a new map and translate each value
|
||||
case reflect.Map:
|
||||
if copy.CanSet() {
|
||||
copy.Set(reflect.MakeMap(original.Type()))
|
||||
if destination.CanSet() {
|
||||
destination.Set(reflect.MakeMap(original.Type()))
|
||||
} else {
|
||||
copyValueIntoUnexported(copy, reflect.MakeMap(original.Type()))
|
||||
copyValueIntoUnexported(destination, reflect.MakeMap(original.Type()))
|
||||
}
|
||||
for _, key := range original.MapKeys() {
|
||||
originalValue := original.MapIndex(key)
|
||||
@@ -210,7 +210,7 @@ func (r *Render) deeplyReplace(copy, original reflect.Value, replaceMap map[stri
|
||||
key = reflect.ValueOf(templatedKey)
|
||||
}
|
||||
|
||||
copy.SetMapIndex(key, copyValue)
|
||||
destination.SetMapIndex(key, copyValue)
|
||||
}
|
||||
|
||||
// Otherwise we cannot traverse anywhere so this finishes the recursion
|
||||
@@ -222,19 +222,19 @@ func (r *Render) deeplyReplace(copy, original reflect.Value, replaceMap map[stri
|
||||
// Not wrapping the error, since this is a recursive function. Avoids excessively long error messages.
|
||||
return err
|
||||
}
|
||||
if copy.CanSet() {
|
||||
copy.SetString(templated)
|
||||
if destination.CanSet() {
|
||||
destination.SetString(templated)
|
||||
} else {
|
||||
copyValueIntoUnexported(copy, reflect.ValueOf(templated))
|
||||
copyValueIntoUnexported(destination, reflect.ValueOf(templated))
|
||||
}
|
||||
return nil
|
||||
|
||||
// And everything else will simply be taken from the original
|
||||
default:
|
||||
if copy.CanSet() {
|
||||
copy.Set(original)
|
||||
if destination.CanSet() {
|
||||
destination.Set(original)
|
||||
} else {
|
||||
copyUnexported(copy, original)
|
||||
copyUnexported(destination, original)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
@@ -260,13 +260,13 @@ func (r *Render) RenderTemplateParams(tmpl *argoappsv1.Application, syncPolicy *
|
||||
}
|
||||
|
||||
original := reflect.ValueOf(tmpl)
|
||||
copy := reflect.New(original.Type()).Elem()
|
||||
destination := reflect.New(original.Type()).Elem()
|
||||
|
||||
if err := r.deeplyReplace(copy, original, params, useGoTemplate, goTemplateOptions); err != nil {
|
||||
if err := r.deeplyReplace(destination, original, params, useGoTemplate, goTemplateOptions); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
replacedTmpl := copy.Interface().(*argoappsv1.Application)
|
||||
replacedTmpl := destination.Interface().(*argoappsv1.Application)
|
||||
|
||||
// Add the 'resources-finalizer' finalizer if:
|
||||
// The template application doesn't have any finalizers, and:
|
||||
@@ -291,13 +291,13 @@ func (r *Render) RenderGeneratorParams(gen *argoappsv1.ApplicationSetGenerator,
|
||||
}
|
||||
|
||||
original := reflect.ValueOf(gen)
|
||||
copy := reflect.New(original.Type()).Elem()
|
||||
destination := reflect.New(original.Type()).Elem()
|
||||
|
||||
if err := r.deeplyReplace(copy, original, params, useGoTemplate, goTemplateOptions); err != nil {
|
||||
if err := r.deeplyReplace(destination, original, params, useGoTemplate, goTemplateOptions); err != nil {
|
||||
return nil, fmt.Errorf("failed to replace parameters in generator: %w", err)
|
||||
}
|
||||
|
||||
replacedGen := copy.Interface().(*argoappsv1.ApplicationSetGenerator)
|
||||
replacedGen := destination.Interface().(*argoappsv1.ApplicationSetGenerator)
|
||||
|
||||
return replacedGen, nil
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ import (
|
||||
|
||||
// NewContextCommand returns a new instance of an `argocd ctx` command
|
||||
func NewContextCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
|
||||
var delete bool
|
||||
var deletion bool
|
||||
command := &cobra.Command{
|
||||
Use: "context [CONTEXT]",
|
||||
Aliases: []string{"ctx"},
|
||||
@@ -35,7 +35,7 @@ argocd context cd.argoproj.io --delete`,
|
||||
localCfg, err := localconfig.ReadLocalConfig(clientOpts.ConfigPath)
|
||||
errors.CheckError(err)
|
||||
|
||||
if delete {
|
||||
if deletion {
|
||||
if len(args) == 0 {
|
||||
c.HelpFunc()(c, args)
|
||||
os.Exit(1)
|
||||
@@ -78,7 +78,7 @@ argocd context cd.argoproj.io --delete`,
|
||||
fmt.Printf("Switched to context '%s'\n", localCfg.CurrentContext)
|
||||
},
|
||||
}
|
||||
command.Flags().BoolVar(&delete, "delete", false, "Delete the context instead of switching to it")
|
||||
command.Flags().BoolVar(&deletion, "delete", false, "Delete the context instead of switching to it")
|
||||
return command
|
||||
}
|
||||
|
||||
|
||||
@@ -2010,12 +2010,12 @@ func (ctrl *ApplicationController) normalizeApplication(orig, app *appv1.Applica
|
||||
}
|
||||
}
|
||||
|
||||
func createMergePatch(orig, new any) ([]byte, bool, error) {
|
||||
func createMergePatch(orig, newV any) ([]byte, bool, error) {
|
||||
origBytes, err := json.Marshal(orig)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
newBytes, err := json.Marshal(new)
|
||||
newBytes, err := json.Marshal(newV)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
|
||||
@@ -2346,20 +2346,17 @@ func Test_syncDeleteOption(t *testing.T) {
|
||||
cm := newFakeCM()
|
||||
t.Run("without delete option object is deleted", func(t *testing.T) {
|
||||
cmObj := kube.MustToUnstructured(&cm)
|
||||
delete := ctrl.shouldBeDeleted(app, cmObj)
|
||||
assert.True(t, delete)
|
||||
assert.True(t, ctrl.shouldBeDeleted(app, cmObj))
|
||||
})
|
||||
t.Run("with delete set to false object is retained", func(t *testing.T) {
|
||||
cmObj := kube.MustToUnstructured(&cm)
|
||||
cmObj.SetAnnotations(map[string]string{"argocd.argoproj.io/sync-options": "Delete=false"})
|
||||
delete := ctrl.shouldBeDeleted(app, cmObj)
|
||||
assert.False(t, delete)
|
||||
assert.False(t, ctrl.shouldBeDeleted(app, cmObj))
|
||||
})
|
||||
t.Run("with delete set to false object is retained", func(t *testing.T) {
|
||||
cmObj := kube.MustToUnstructured(&cm)
|
||||
cmObj.SetAnnotations(map[string]string{"helm.sh/resource-policy": "keep"})
|
||||
delete := ctrl.shouldBeDeleted(app, cmObj)
|
||||
assert.False(t, delete)
|
||||
assert.False(t, ctrl.shouldBeDeleted(app, cmObj))
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -168,25 +168,25 @@ func (sharding *ClusterSharding) updateDistribution() {
|
||||
}
|
||||
|
||||
// hasShardingUpdates returns true if the sharding distribution has explicitly changed
|
||||
func hasShardingUpdates(old, new *v1alpha1.Cluster) bool {
|
||||
if old == nil || new == nil {
|
||||
func hasShardingUpdates(old, newCluster *v1alpha1.Cluster) bool {
|
||||
if old == nil || newCluster == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
// returns true if the cluster id has changed because some sharding algorithms depend on it.
|
||||
if old.ID != new.ID {
|
||||
if old.ID != newCluster.ID {
|
||||
return true
|
||||
}
|
||||
|
||||
if old.Server != new.Server {
|
||||
if old.Server != newCluster.Server {
|
||||
return true
|
||||
}
|
||||
|
||||
// return false if the shard field has not been modified
|
||||
if old.Shard == nil && new.Shard == nil {
|
||||
if old.Shard == nil && newCluster.Shard == nil {
|
||||
return false
|
||||
}
|
||||
return old.Shard == nil || new.Shard == nil || int64(*old.Shard) != int64(*new.Shard)
|
||||
return old.Shard == nil || newCluster.Shard == nil || int64(*old.Shard) != int64(*newCluster.Shard)
|
||||
}
|
||||
|
||||
// A read lock should be acquired before calling getClusterAccessor.
|
||||
|
||||
@@ -15,7 +15,7 @@ func GetRandomString() string {
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func cryptoRandSecure(max int64) int64 {
|
||||
nBig, _ := rand.Int(rand.Reader, big.NewInt(max))
|
||||
func cryptoRandSecure(maximum int64) int64 {
|
||||
nBig, _ := rand.Int(rand.Reader, big.NewInt(maximum))
|
||||
return nBig.Int64()
|
||||
}
|
||||
|
||||
6
reposerver/cache/cache.go
vendored
6
reposerver/cache/cache.go
vendored
@@ -534,11 +534,11 @@ func (cmr *CachedManifestResponse) shallowCopy() *CachedManifestResponse {
|
||||
|
||||
func (cmr *CachedManifestResponse) generateCacheEntryHash() (string, error) {
|
||||
// Copy, then remove the old hash
|
||||
copy := cmr.shallowCopy()
|
||||
copy.CacheEntryHash = ""
|
||||
shallowCopy := cmr.shallowCopy()
|
||||
shallowCopy.CacheEntryHash = ""
|
||||
|
||||
// Hash the JSON representation into a base-64-encoded FNV 64a (we don't need a cryptographic hash algorithm, since this is only for detecting data corruption)
|
||||
bytes, err := json.Marshal(copy)
|
||||
bytes, err := json.Marshal(shallowCopy)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
@@ -140,8 +140,8 @@ func pods(t *testing.T, namespace string) (*corev1.PodList, error) {
|
||||
}
|
||||
|
||||
// getDiff returns a string containing a comparison result of two applications (for test output/debug purposes)
|
||||
func getDiff(orig, new v1alpha1.Application) (string, error) {
|
||||
bytes, _, err := diff.CreateTwoWayMergePatch(orig, new, orig)
|
||||
func getDiff(orig, newApplication v1alpha1.Application) (string, error) {
|
||||
bytes, _, err := diff.CreateTwoWayMergePatch(orig, newApplication, orig)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -150,15 +150,15 @@ func getDiff(orig, new v1alpha1.Application) (string, error) {
|
||||
}
|
||||
|
||||
// getConditionDiff returns a string containing a comparison result of two ApplicationSetCondition (for test output/debug purposes)
|
||||
func getConditionDiff(orig, new []v1alpha1.ApplicationSetCondition) (string, error) {
|
||||
if len(orig) != len(new) {
|
||||
return fmt.Sprintf("mismatch between condition sizes: %v %v", len(orig), len(new)), nil
|
||||
func getConditionDiff(orig, newApplicationSetCondition []v1alpha1.ApplicationSetCondition) (string, error) {
|
||||
if len(orig) != len(newApplicationSetCondition) {
|
||||
return fmt.Sprintf("mismatch between condition sizes: %v %v", len(orig), len(newApplicationSetCondition)), nil
|
||||
}
|
||||
|
||||
var bytes []byte
|
||||
|
||||
for index := range orig {
|
||||
b, _, err := diff.CreateTwoWayMergePatch(orig[index], new[index], orig[index])
|
||||
b, _, err := diff.CreateTwoWayMergePatch(orig[index], newApplicationSetCondition[index], orig[index])
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
4
util/cache/appstate/cache.go
vendored
4
util/cache/appstate/cache.go
vendored
@@ -51,8 +51,8 @@ func (c *Cache) GetItem(key string, item any) error {
|
||||
return c.Cache.GetItem(key, item)
|
||||
}
|
||||
|
||||
func (c *Cache) SetItem(key string, item any, expiration time.Duration, delete bool) error {
|
||||
return c.Cache.SetItem(key, item, &cacheutil.CacheActionOpts{Expiration: expiration, Delete: delete})
|
||||
func (c *Cache) SetItem(key string, item any, expiration time.Duration, deletion bool) error {
|
||||
return c.Cache.SetItem(key, item, &cacheutil.CacheActionOpts{Expiration: expiration, Delete: deletion})
|
||||
}
|
||||
|
||||
func appManagedResourcesKey(appName string) string {
|
||||
|
||||
@@ -209,45 +209,45 @@ func Test_AddGPGPublicKey(t *testing.T) {
|
||||
db := NewDB(testNamespace, settings, clientset)
|
||||
|
||||
// Key should be added
|
||||
new, skipped, err := db.AddGPGPublicKey(t.Context(), testdata.Github_asc)
|
||||
keys, skipped, err := db.AddGPGPublicKey(t.Context(), testdata.Github_asc)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, new, 1)
|
||||
assert.Len(t, keys, 1)
|
||||
assert.Empty(t, skipped)
|
||||
cm, err := settings.GetConfigMapByName(common.ArgoCDGPGKeysConfigMapName)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, cm.Data, 1)
|
||||
|
||||
// Same key should not be added, but skipped
|
||||
new, skipped, err = db.AddGPGPublicKey(t.Context(), testdata.Github_asc)
|
||||
keys, skipped, err = db.AddGPGPublicKey(t.Context(), testdata.Github_asc)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, new)
|
||||
assert.Empty(t, keys)
|
||||
assert.Len(t, skipped, 1)
|
||||
cm, err = settings.GetConfigMapByName(common.ArgoCDGPGKeysConfigMapName)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, cm.Data, 1)
|
||||
|
||||
// New keys should be added
|
||||
new, skipped, err = db.AddGPGPublicKey(t.Context(), testdata.Multi_asc)
|
||||
keys, skipped, err = db.AddGPGPublicKey(t.Context(), testdata.Multi_asc)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, new, 2)
|
||||
assert.Len(t, keys, 2)
|
||||
assert.Empty(t, skipped)
|
||||
cm, err = settings.GetConfigMapByName(common.ArgoCDGPGKeysConfigMapName)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, cm.Data, 3)
|
||||
|
||||
// Same new keys should be skipped
|
||||
new, skipped, err = db.AddGPGPublicKey(t.Context(), testdata.Multi_asc)
|
||||
keys, skipped, err = db.AddGPGPublicKey(t.Context(), testdata.Multi_asc)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, new)
|
||||
assert.Empty(t, keys)
|
||||
assert.Len(t, skipped, 2)
|
||||
cm, err = settings.GetConfigMapByName(common.ArgoCDGPGKeysConfigMapName)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, cm.Data, 3)
|
||||
|
||||
// Garbage input should result in error
|
||||
new, skipped, err = db.AddGPGPublicKey(t.Context(), testdata.Garbage_asc)
|
||||
keys, skipped, err = db.AddGPGPublicKey(t.Context(), testdata.Garbage_asc)
|
||||
require.Error(t, err)
|
||||
assert.Nil(t, new)
|
||||
assert.Nil(t, keys)
|
||||
assert.Nil(t, skipped)
|
||||
cm, err = settings.GetConfigMapByName(common.ArgoCDGPGKeysConfigMapName)
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -563,16 +563,16 @@ func (s *secretsRepositoryBackend) getRepoCredsSecret(repoURL string) (*corev1.S
|
||||
}
|
||||
|
||||
func (s *secretsRepositoryBackend) getRepositoryCredentialIndex(repoCredentials []*corev1.Secret, repoURL string) int {
|
||||
max, idx := 0, -1
|
||||
maxLen, idx := 0, -1
|
||||
repoURL = git.NormalizeGitURL(repoURL)
|
||||
for i, cred := range repoCredentials {
|
||||
credURL := git.NormalizeGitURL(string(cred.Data["url"]))
|
||||
if strings.HasPrefix(repoURL, credURL) {
|
||||
if len(credURL) == max {
|
||||
if len(credURL) == maxLen {
|
||||
log.Warnf("Found multiple credentials for repoURL: %s", repoURL)
|
||||
}
|
||||
if len(credURL) > max {
|
||||
max = len(credURL)
|
||||
if len(credURL) > maxLen {
|
||||
maxLen = len(credURL)
|
||||
idx = i
|
||||
}
|
||||
}
|
||||
|
||||
72
util/env/env.go
vendored
72
util/env/env.go
vendored
@@ -11,9 +11,9 @@ import (
|
||||
)
|
||||
|
||||
// Helper function to parse a number from an environment variable. Returns a
|
||||
// default if env is not set, is not parseable to a number, exceeds max (if
|
||||
// max is greater than 0) or is less than min.
|
||||
func ParseNumFromEnv(env string, defaultValue, min, max int) int {
|
||||
// default if env is not set, is not parseable to a number, exceeds maximum (if
|
||||
// maximum is greater than 0) or is less than minimum.
|
||||
func ParseNumFromEnv(env string, defaultValue, minimum, maximum int) int {
|
||||
str := os.Getenv(env)
|
||||
if str == "" {
|
||||
return defaultValue
|
||||
@@ -24,24 +24,24 @@ func ParseNumFromEnv(env string, defaultValue, min, max int) int {
|
||||
return defaultValue
|
||||
}
|
||||
if num > math.MaxInt || num < math.MinInt {
|
||||
log.Warnf("Value in %s is %d is outside of the min and max %d allowed values. Using default %d", env, num, min, defaultValue)
|
||||
log.Warnf("Value in %s is %d is outside of the min and max %d allowed values. Using default %d", env, num, minimum, defaultValue)
|
||||
return defaultValue
|
||||
}
|
||||
if int(num) < min {
|
||||
log.Warnf("Value in %s is %d, which is less than minimum %d allowed", env, num, min)
|
||||
if int(num) < minimum {
|
||||
log.Warnf("Value in %s is %d, which is less than minimum %d allowed", env, num, minimum)
|
||||
return defaultValue
|
||||
}
|
||||
if int(num) > max {
|
||||
log.Warnf("Value in %s is %d, which is greater than maximum %d allowed", env, num, max)
|
||||
if int(num) > maximum {
|
||||
log.Warnf("Value in %s is %d, which is greater than maximum %d allowed", env, num, maximum)
|
||||
return defaultValue
|
||||
}
|
||||
return int(num)
|
||||
}
|
||||
|
||||
// Helper function to parse a int64 from an environment variable. Returns a
|
||||
// default if env is not set, is not parseable to a number, exceeds max (if
|
||||
// max is greater than 0) or is less than min.
|
||||
func ParseInt64FromEnv(env string, defaultValue, min, max int64) int64 {
|
||||
// default if env is not set, is not parseable to a number, exceeds maximum (if
|
||||
// maximum is greater than 0) or is less than minimum.
|
||||
func ParseInt64FromEnv(env string, defaultValue, minimum, maximum int64) int64 {
|
||||
str := os.Getenv(env)
|
||||
if str == "" {
|
||||
return defaultValue
|
||||
@@ -52,21 +52,21 @@ func ParseInt64FromEnv(env string, defaultValue, min, max int64) int64 {
|
||||
log.Warnf("Could not parse '%s' as a int64 from environment %s", str, env)
|
||||
return defaultValue
|
||||
}
|
||||
if num < min {
|
||||
log.Warnf("Value in %s is %d, which is less than minimum %d allowed", env, num, min)
|
||||
if num < minimum {
|
||||
log.Warnf("Value in %s is %d, which is less than minimum %d allowed", env, num, minimum)
|
||||
return defaultValue
|
||||
}
|
||||
if num > max {
|
||||
log.Warnf("Value in %s is %d, which is greater than maximum %d allowed", env, num, max)
|
||||
if num > maximum {
|
||||
log.Warnf("Value in %s is %d, which is greater than maximum %d allowed", env, num, maximum)
|
||||
return defaultValue
|
||||
}
|
||||
return num
|
||||
}
|
||||
|
||||
// Helper function to parse a float32 from an environment variable. Returns a
|
||||
// default if env is not set, is not parseable to a number, exceeds max (if
|
||||
// max is greater than 0) or is less than min (and min is greater than 0).
|
||||
func ParseFloatFromEnv(env string, defaultValue, min, max float32) float32 {
|
||||
// default if env is not set, is not parseable to a number, exceeds maximum (if
|
||||
// maximum is greater than 0) or is less than minimum (and minimum is greater than 0).
|
||||
func ParseFloatFromEnv(env string, defaultValue, minimum, maximum float32) float32 {
|
||||
str := os.Getenv(env)
|
||||
if str == "" {
|
||||
return defaultValue
|
||||
@@ -77,21 +77,21 @@ func ParseFloatFromEnv(env string, defaultValue, min, max float32) float32 {
|
||||
log.Warnf("Could not parse '%s' as a float32 from environment %s", str, env)
|
||||
return defaultValue
|
||||
}
|
||||
if float32(num) < min {
|
||||
log.Warnf("Value in %s is %f, which is less than minimum %f allowed", env, num, min)
|
||||
if float32(num) < minimum {
|
||||
log.Warnf("Value in %s is %f, which is less than minimum %f allowed", env, num, minimum)
|
||||
return defaultValue
|
||||
}
|
||||
if float32(num) > max {
|
||||
log.Warnf("Value in %s is %f, which is greater than maximum %f allowed", env, num, max)
|
||||
if float32(num) > maximum {
|
||||
log.Warnf("Value in %s is %f, which is greater than maximum %f allowed", env, num, maximum)
|
||||
return defaultValue
|
||||
}
|
||||
return float32(num)
|
||||
}
|
||||
|
||||
// Helper function to parse a float64 from an environment variable. Returns a
|
||||
// default if env is not set, is not parseable to a number, exceeds max (if
|
||||
// max is greater than 0) or is less than min (and min is greater than 0).
|
||||
func ParseFloat64FromEnv(env string, defaultValue, min, max float64) float64 {
|
||||
// default if env is not set, is not parseable to a number, exceeds maximum (if
|
||||
// maximum is greater than 0) or is less than minimum (and minimum is greater than 0).
|
||||
func ParseFloat64FromEnv(env string, defaultValue, minimum, maximum float64) float64 {
|
||||
str := os.Getenv(env)
|
||||
if str == "" {
|
||||
return defaultValue
|
||||
@@ -102,23 +102,23 @@ func ParseFloat64FromEnv(env string, defaultValue, min, max float64) float64 {
|
||||
log.Warnf("Could not parse '%s' as a float32 from environment %s", str, env)
|
||||
return defaultValue
|
||||
}
|
||||
if num < min {
|
||||
log.Warnf("Value in %s is %f, which is less than minimum %f allowed", env, num, min)
|
||||
if num < minimum {
|
||||
log.Warnf("Value in %s is %f, which is less than minimum %f allowed", env, num, minimum)
|
||||
return defaultValue
|
||||
}
|
||||
if num > max {
|
||||
log.Warnf("Value in %s is %f, which is greater than maximum %f allowed", env, num, max)
|
||||
if num > maximum {
|
||||
log.Warnf("Value in %s is %f, which is greater than maximum %f allowed", env, num, maximum)
|
||||
return defaultValue
|
||||
}
|
||||
return num
|
||||
}
|
||||
|
||||
// Helper function to parse a time duration from an environment variable. Returns a
|
||||
// default if env is not set, is not parseable to a duration, exceeds max (if
|
||||
// max is greater than 0) or is less than min.
|
||||
// default if env is not set, is not parseable to a duration, exceeds maximum (if
|
||||
// maximum is greater than 0) or is less than minimum.
|
||||
//
|
||||
// nolinit:unparam
|
||||
func ParseDurationFromEnv(env string, defaultValue, min, max time.Duration) time.Duration {
|
||||
func ParseDurationFromEnv(env string, defaultValue, minimum, maximum time.Duration) time.Duration {
|
||||
str := os.Getenv(env)
|
||||
if str == "" {
|
||||
return defaultValue
|
||||
@@ -129,12 +129,12 @@ func ParseDurationFromEnv(env string, defaultValue, min, max time.Duration) time
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
if dur < min {
|
||||
log.Warnf("Value in %s is %s, which is less than minimum %s allowed", env, dur, min)
|
||||
if dur < minimum {
|
||||
log.Warnf("Value in %s is %s, which is less than minimum %s allowed", env, dur, minimum)
|
||||
return defaultValue
|
||||
}
|
||||
if dur > max {
|
||||
log.Warnf("Value in %s is %s, which is greater than maximum %s allowed", env, dur, max)
|
||||
if dur > maximum {
|
||||
log.Warnf("Value in %s is %s, which is greater than maximum %s allowed", env, dur, maximum)
|
||||
return defaultValue
|
||||
}
|
||||
return dur
|
||||
|
||||
44
util/env/env_test.go
vendored
44
util/env/env_test.go
vendored
@@ -13,8 +13,8 @@ import (
|
||||
|
||||
func TestParseNumFromEnv(t *testing.T) {
|
||||
const envKey = "SOMEKEY"
|
||||
const min = math.MinInt + 1
|
||||
const max = math.MaxInt - 1
|
||||
const minimum = math.MinInt + 1
|
||||
const maximum = math.MaxInt - 1
|
||||
const def = 10
|
||||
testCases := []struct {
|
||||
name string
|
||||
@@ -24,8 +24,8 @@ func TestParseNumFromEnv(t *testing.T) {
|
||||
{"Valid positive number", "200", 200},
|
||||
{"Valid negative number", "-200", -200},
|
||||
{"Invalid number", "abc", def},
|
||||
{"Equals minimum", strconv.Itoa(math.MinInt + 1), min},
|
||||
{"Equals maximum", strconv.Itoa(math.MaxInt - 1), max},
|
||||
{"Equals minimum", strconv.Itoa(math.MinInt + 1), minimum},
|
||||
{"Equals maximum", strconv.Itoa(math.MaxInt - 1), maximum},
|
||||
{"Less than minimum", strconv.Itoa(math.MinInt), def},
|
||||
{"Greater than maximum", strconv.Itoa(math.MaxInt), def},
|
||||
{"Variable not set", "", def},
|
||||
@@ -34,7 +34,7 @@ func TestParseNumFromEnv(t *testing.T) {
|
||||
for _, tt := range testCases {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Setenv(envKey, tt.env)
|
||||
n := ParseNumFromEnv(envKey, def, min, max)
|
||||
n := ParseNumFromEnv(envKey, def, minimum, maximum)
|
||||
assert.Equal(t, tt.expected, n)
|
||||
})
|
||||
}
|
||||
@@ -42,8 +42,8 @@ func TestParseNumFromEnv(t *testing.T) {
|
||||
|
||||
func TestParseFloatFromEnv(t *testing.T) {
|
||||
const envKey = "SOMEKEY"
|
||||
var min float32 = -1000.5
|
||||
var max float32 = 1000.5
|
||||
var minimum float32 = -1000.5
|
||||
var maximum float32 = 1000.5
|
||||
const def float32 = 10.5
|
||||
testCases := []struct {
|
||||
name string
|
||||
@@ -54,17 +54,17 @@ func TestParseFloatFromEnv(t *testing.T) {
|
||||
{"Valid negative float", "-2.0", -2.0},
|
||||
{"Valid integer as float", "2", 2.0},
|
||||
{"Text as invalid float", "abc", def},
|
||||
{"Equals maximum", fmt.Sprintf("%v", max), max},
|
||||
{"Equals minimum", fmt.Sprintf("%v", min), min},
|
||||
{"Greater than maximum", fmt.Sprintf("%f", max+1), def},
|
||||
{"Lesser than minimum", fmt.Sprintf("%f", min-1), def},
|
||||
{"Equals maximum", fmt.Sprintf("%v", maximum), maximum},
|
||||
{"Equals minimum", fmt.Sprintf("%v", minimum), minimum},
|
||||
{"Greater than maximum", fmt.Sprintf("%f", maximum+1), def},
|
||||
{"Lesser than minimum", fmt.Sprintf("%f", minimum-1), def},
|
||||
{"Environment not set at", "", def},
|
||||
}
|
||||
|
||||
for _, tt := range testCases {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Setenv(envKey, tt.env)
|
||||
f := ParseFloatFromEnv(envKey, def, min, max)
|
||||
f := ParseFloatFromEnv(envKey, def, minimum, maximum)
|
||||
assert.InEpsilon(t, tt.expected, f, 0.0001)
|
||||
})
|
||||
}
|
||||
@@ -72,8 +72,8 @@ func TestParseFloatFromEnv(t *testing.T) {
|
||||
|
||||
func TestParseInt64FromEnv(t *testing.T) {
|
||||
const envKey = "SOMEKEY"
|
||||
const min int64 = 1
|
||||
const max int64 = math.MaxInt64 - 1
|
||||
const minimum int64 = 1
|
||||
const maximum int64 = math.MaxInt64 - 1
|
||||
const def int64 = 10
|
||||
testCases := []struct {
|
||||
name string
|
||||
@@ -82,17 +82,17 @@ func TestParseInt64FromEnv(t *testing.T) {
|
||||
}{
|
||||
{"Valid int64", "200", 200},
|
||||
{"Text as invalid int64", "abc", def},
|
||||
{"Equals maximum", strconv.FormatInt(max, 10), max},
|
||||
{"Equals minimum", strconv.FormatInt(min, 10), min},
|
||||
{"Greater than maximum", strconv.FormatInt(max+1, 10), def},
|
||||
{"Less than minimum", strconv.FormatInt(min-1, 10), def},
|
||||
{"Equals maximum", strconv.FormatInt(maximum, 10), maximum},
|
||||
{"Equals minimum", strconv.FormatInt(minimum, 10), minimum},
|
||||
{"Greater than maximum", strconv.FormatInt(maximum+1, 10), def},
|
||||
{"Less than minimum", strconv.FormatInt(minimum-1, 10), def},
|
||||
{"Environment not set", "", def},
|
||||
}
|
||||
|
||||
for _, tt := range testCases {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Setenv(envKey, tt.env)
|
||||
n := ParseInt64FromEnv(envKey, def, min, max)
|
||||
n := ParseInt64FromEnv(envKey, def, minimum, maximum)
|
||||
assert.Equal(t, tt.expected, n)
|
||||
})
|
||||
}
|
||||
@@ -101,8 +101,8 @@ func TestParseInt64FromEnv(t *testing.T) {
|
||||
func TestParseDurationFromEnv(t *testing.T) {
|
||||
envKey := "SOMEKEY"
|
||||
def := 3 * time.Second
|
||||
min := 2 * time.Second
|
||||
max := 5 * time.Second
|
||||
minimum := 2 * time.Second
|
||||
maximum := 5 * time.Second
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
@@ -136,7 +136,7 @@ func TestParseDurationFromEnv(t *testing.T) {
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Setenv(envKey, tc.env)
|
||||
val := ParseDurationFromEnv(envKey, def, min, max)
|
||||
val := ParseDurationFromEnv(envKey, def, minimum, maximum)
|
||||
assert.Equal(t, tc.expected, val)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -550,9 +550,9 @@ func Test_SyncKeyRingFromDirectory(t *testing.T) {
|
||||
tempDir := t.TempDir()
|
||||
|
||||
{
|
||||
new, removed, err := SyncKeyRingFromDirectory(tempDir)
|
||||
newKeys, removed, err := SyncKeyRingFromDirectory(tempDir)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, new)
|
||||
assert.Empty(t, newKeys)
|
||||
assert.Empty(t, removed)
|
||||
}
|
||||
|
||||
@@ -575,15 +575,15 @@ func Test_SyncKeyRingFromDirectory(t *testing.T) {
|
||||
dst.Close()
|
||||
}
|
||||
|
||||
new, removed, err := SyncKeyRingFromDirectory(tempDir)
|
||||
newKeys, removed, err := SyncKeyRingFromDirectory(tempDir)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, new, 3)
|
||||
assert.Len(t, newKeys, 3)
|
||||
assert.Empty(t, removed)
|
||||
|
||||
installed, err := GetInstalledPGPKeys(new)
|
||||
installed, err := GetInstalledPGPKeys(newKeys)
|
||||
require.NoError(t, err)
|
||||
for _, k := range installed {
|
||||
assert.Contains(t, new, k.KeyID)
|
||||
assert.Contains(t, newKeys, k.KeyID)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -592,12 +592,12 @@ func Test_SyncKeyRingFromDirectory(t *testing.T) {
|
||||
if err != nil {
|
||||
panic(err.Error())
|
||||
}
|
||||
new, removed, err := SyncKeyRingFromDirectory(tempDir)
|
||||
newKeys, removed, err := SyncKeyRingFromDirectory(tempDir)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, new)
|
||||
assert.Empty(t, newKeys)
|
||||
assert.Len(t, removed, 1)
|
||||
|
||||
installed, err := GetInstalledPGPKeys(new)
|
||||
installed, err := GetInstalledPGPKeys(newKeys)
|
||||
require.NoError(t, err)
|
||||
for _, k := range installed {
|
||||
assert.NotEqual(t, k.KeyID, removed[0])
|
||||
|
||||
@@ -22,13 +22,13 @@ func logRequest(ctx context.Context, entry *logrus.Entry, info string, pbMsg any
|
||||
claims := ctx.Value("claims")
|
||||
mapClaims, ok := claims.(jwt.MapClaims)
|
||||
if ok {
|
||||
copy := make(map[string]any)
|
||||
claimsCopy := make(map[string]any)
|
||||
for k, v := range mapClaims {
|
||||
if k != "groups" || entry.Logger.IsLevelEnabled(logrus.DebugLevel) {
|
||||
copy[k] = v
|
||||
claimsCopy[k] = v
|
||||
}
|
||||
}
|
||||
if data, err := json.Marshal(copy); err == nil {
|
||||
if data, err := json.Marshal(claimsCopy); err == nil {
|
||||
entry = entry.WithField("grpc.request.claims", string(data))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -367,13 +367,13 @@ func cleanSetParameters(val string) string {
|
||||
return val
|
||||
}
|
||||
|
||||
func replaceAllWithLookbehind(val string, old rune, new string, lookbehind rune) string {
|
||||
func replaceAllWithLookbehind(val string, old rune, newV string, lookbehind rune) string {
|
||||
var result strings.Builder
|
||||
var prevR rune
|
||||
for _, r := range val {
|
||||
if r == old {
|
||||
if prevR != lookbehind {
|
||||
result.WriteString(new)
|
||||
result.WriteString(newV)
|
||||
} else {
|
||||
result.WriteRune(old)
|
||||
}
|
||||
|
||||
@@ -18,8 +18,8 @@ func (c *inlineCloser) Close() error {
|
||||
return c.close()
|
||||
}
|
||||
|
||||
func NewCloser(close func() error) Closer {
|
||||
return &inlineCloser{close: close}
|
||||
func NewCloser(closeFn func() error) Closer {
|
||||
return &inlineCloser{close: closeFn}
|
||||
}
|
||||
|
||||
// Close is a convenience function to close a object that has a Close() method, ignoring any errors
|
||||
|
||||
@@ -32,17 +32,17 @@ func NewKubeUtil(ctx context.Context, client kubernetes.Interface) *kubeUtil {
|
||||
func (ku *kubeUtil) CreateOrUpdateSecret(ns string, name string, update updateFn) error {
|
||||
var s *corev1.Secret
|
||||
var err error
|
||||
var new bool
|
||||
var create bool
|
||||
|
||||
s, err = ku.client.CoreV1().Secrets(ns).Get(ku.ctx, name, metav1.GetOptions{})
|
||||
if err != nil {
|
||||
if !errors.IsNotFound(err) {
|
||||
return err
|
||||
}
|
||||
new = true
|
||||
create = true
|
||||
}
|
||||
|
||||
if new {
|
||||
if create {
|
||||
s = &corev1.Secret{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: name,
|
||||
@@ -54,12 +54,12 @@ func (ku *kubeUtil) CreateOrUpdateSecret(ns string, name string, update updateFn
|
||||
s.Data = make(map[string][]byte)
|
||||
}
|
||||
|
||||
err = update(s, new)
|
||||
err = update(s, create)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if new {
|
||||
if create {
|
||||
_, err = ku.client.CoreV1().Secrets(ns).Create(ku.ctx, s, metav1.CreateOptions{})
|
||||
} else {
|
||||
_, err = ku.client.CoreV1().Secrets(ns).Update(ku.ctx, s, metav1.UpdateOptions{})
|
||||
|
||||
@@ -36,13 +36,13 @@ func osTime(l *lua.LState) int {
|
||||
} else {
|
||||
tbl := l.CheckTable(1)
|
||||
sec := getIntField(tbl, "sec", 0)
|
||||
min := getIntField(tbl, "min", 0)
|
||||
minutes := getIntField(tbl, "min", 0)
|
||||
hour := getIntField(tbl, "hour", 12)
|
||||
day := getIntField(tbl, "day", -1)
|
||||
month := getIntField(tbl, "month", -1)
|
||||
year := getIntField(tbl, "year", -1)
|
||||
isdst := getBoolField(tbl, "isdst", false)
|
||||
t := time.Date(year, time.Month(month), day, hour, min, sec, 0, time.Local)
|
||||
t := time.Date(year, time.Month(month), day, hour, minutes, sec, 0, time.Local)
|
||||
// TODO dst
|
||||
if false {
|
||||
print(isdst)
|
||||
|
||||
@@ -12,8 +12,8 @@ func NewExprs() map[string]any {
|
||||
}
|
||||
}
|
||||
|
||||
func replaceAll(s, old, new string) string {
|
||||
return strings.ReplaceAll(s, old, new)
|
||||
func replaceAll(s, old, newV string) string {
|
||||
return strings.ReplaceAll(s, old, newV)
|
||||
}
|
||||
|
||||
func toUpper(s string) string {
|
||||
|
||||
Reference in New Issue
Block a user