chore: enable errorlint linter on util folder (#18588)

Signed-off-by: Matthieu MOREL <matthieu.morel35@gmail.com>
This commit is contained in:
Matthieu MOREL
2024-06-11 16:42:32 +02:00
committed by GitHub
parent 355ec75bed
commit d7e99224d4
40 changed files with 118 additions and 104 deletions

View File

@@ -2,7 +2,7 @@ issues:
exclude:
- SA5011
exclude-rules:
- path: "(applicationset|cmpserver|controller|reposerver|server|util)/"
- path: "(applicationset|cmpserver|controller|reposerver|server)/"
linters:
- errorlint
max-issues-per-linter: 0

View File

@@ -483,7 +483,7 @@ func readAppsFromStdin(apps *[]*argoappv1.Application) error {
}
err = readApps(data, apps)
if err != nil {
return fmt.Errorf("unable to read manifest from stdin: %v", err)
return fmt.Errorf("unable to read manifest from stdin: %w", err)
}
return nil
}

View File

@@ -23,7 +23,7 @@ func constructAppsetFromFileUrl(fileURL string) ([]*argoprojiov1alpha1.Applicati
// read uri
err := readAppsetFromURI(fileURL, &appset)
if err != nil {
return nil, fmt.Errorf("error reading applicationset from file %s: %s", fileURL, err)
return nil, fmt.Errorf("error reading applicationset from file %s: %w", fileURL, err)
}
return appset, nil

View File

@@ -130,7 +130,7 @@ func GetKubePublicEndpoint(client kubernetes.Interface) (string, error) {
config := &clientcmdapiv1.Config{}
err = yaml.Unmarshal([]byte(kubeconfig), config)
if err != nil {
return "", fmt.Errorf("failed to parse cluster-info kubeconfig: %v", err)
return "", fmt.Errorf("failed to parse cluster-info kubeconfig: %w", err)
}
if len(config.Clusters) == 0 {
return "", fmt.Errorf("cluster-info kubeconfig does not have any clusters")

View File

@@ -126,7 +126,7 @@ func readProjFromStdin(proj *v1alpha1.AppProject) error {
reader := bufio.NewReader(os.Stdin)
err := config.UnmarshalReader(reader, &proj)
if err != nil {
return fmt.Errorf("unable to read manifest from stdin: %v", err)
return fmt.Errorf("unable to read manifest from stdin: %w", err)
}
return nil
}

View File

@@ -821,7 +821,7 @@ func (s *Service) runManifestGenAsync(ctx context.Context, repoRoot, commitSHA,
// rather than a copy of the cache that occurred before (a potentially lengthy) manifest generation.
innerRes := &cache.CachedManifestResponse{}
cacheErr := s.cache.GetManifests(cacheKey, appSourceCopy, q.RefSources, q, q.Namespace, q.TrackingMethod, q.AppLabelKey, q.AppName, innerRes, refSourceCommitSHAs)
if cacheErr != nil && cacheErr != cache.ErrCacheMiss {
if cacheErr != nil && !errors.Is(cacheErr, cache.ErrCacheMiss) {
logCtx.Warnf("manifest cache get error %s: %v", appSourceCopy.String(), cacheErr)
ch.errCh <- cacheErr
return
@@ -957,7 +957,7 @@ func (s *Service) getManifestCacheEntry(cacheKey string, q *apiclient.ManifestRe
return true, res.ManifestResponse, nil
}
if err != cache.ErrCacheMiss {
if !errors.Is(err, cache.ErrCacheMiss) {
log.Warnf("manifest cache error %s: %v", q.ApplicationSource.String(), err)
} else {
log.Infof("manifest cache miss: %s/%s", q.ApplicationSource.String(), cacheKey)
@@ -2029,7 +2029,7 @@ func (s *Service) createGetAppDetailsCacheHandler(res *apiclient.RepoAppDetailsR
return true, nil
}
if err != cache.ErrCacheMiss {
if !errors.Is(err, cache.ErrCacheMiss) {
log.Warnf("app details cache error %s: %v", revision, q.Source)
} else {
log.Infof("app details cache miss: %s/%s", revision, q.Source)
@@ -2234,7 +2234,7 @@ func (s *Service) GetRevisionMetadata(ctx context.Context, q *apiclient.RepoServ
return metadata, nil
}
} else {
if err != cache.ErrCacheMiss {
if !errors.Is(err, cache.ErrCacheMiss) {
log.Warnf("revision metadata cache error %s/%s: %v", q.Repo.Repo, q.Revision, err)
} else {
log.Infof("revision metadata cache miss: %s/%s", q.Repo.Repo, q.Revision)
@@ -2297,7 +2297,7 @@ func (s *Service) GetRevisionChartDetails(ctx context.Context, q *apiclient.Repo
log.Infof("revision chart details cache hit: %s/%s/%s", q.Repo.Repo, q.Name, q.Revision)
return details, nil
} else {
if err == cache.ErrCacheMiss {
if errors.Is(err, cache.ErrCacheMiss) {
log.Infof("revision metadata cache miss: %s/%s/%s", q.Repo.Repo, q.Name, q.Revision)
} else {
log.Warnf("revision metadata cache error %s/%s/%s: %v", q.Repo.Repo, q.Name, q.Revision, err)
@@ -2782,7 +2782,7 @@ func (s *Service) updateCachedRevision(logCtx *log.Entry, oldRev string, newRev
err := s.cache.SetNewRevisionManifests(newRev, oldRev, request.ApplicationSource, request.RefSources, request, request.Namespace, request.TrackingMethod, request.AppLabelKey, request.AppName, repoRefs)
if err != nil {
if err == cache.ErrCacheMiss {
if errors.Is(err, cache.ErrCacheMiss) {
logCtx.Debugf("manifest cache miss during comparison for application %s in repo %s from revision %s", request.AppName, request.GetRepo().Repo, oldRev)
return nil
}

View File

@@ -128,16 +128,16 @@ func DetectConfigManagementPlugin(ctx context.Context, appPath, repoPath, plugin
func matchRepositoryCMP(ctx context.Context, appPath, repoPath string, client pluginclient.ConfigManagementPluginServiceClient, env []string, tarExcludedGlobs []string) (bool, bool, error) {
matchRepoStream, err := client.MatchRepository(ctx, grpc_retry.Disable())
if err != nil {
return false, false, fmt.Errorf("error getting stream client: %s", err)
return false, false, fmt.Errorf("error getting stream client: %w", err)
}
err = cmp.SendRepoStream(ctx, appPath, repoPath, matchRepoStream, env, tarExcludedGlobs)
if err != nil {
return false, false, fmt.Errorf("error sending stream: %s", err)
return false, false, fmt.Errorf("error sending stream: %w", err)
}
resp, err := matchRepoStream.CloseAndRecv()
if err != nil {
return false, false, fmt.Errorf("error receiving stream response: %s", err)
return false, false, fmt.Errorf("error receiving stream response: %w", err)
}
return resp.GetIsSupported(), resp.GetIsDiscoveryEnabled(), nil
}

View File

@@ -47,23 +47,23 @@ func (e *OutOfBoundsSymlinkError) Error() string {
func CheckOutOfBoundsSymlinks(basePath string) error {
absBasePath, err := filepath.Abs(basePath)
if err != nil {
return fmt.Errorf("failed to get absolute path: %v", err)
return fmt.Errorf("failed to get absolute path: %w", err)
}
return filepath.Walk(absBasePath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return fmt.Errorf("failed to walk for symlinks in %s: %v", absBasePath, err)
return fmt.Errorf("failed to walk for symlinks in %s: %w", absBasePath, err)
}
if files.IsSymlink(info) {
// We don't use filepath.EvalSymlinks because it fails without returning a path
// if the target doesn't exist.
linkTarget, err := os.Readlink(path)
if err != nil {
return fmt.Errorf("failed to read link %s: %v", path, err)
return fmt.Errorf("failed to read link %s: %w", path, err)
}
// get the path of the symlink relative to basePath, used for error description
linkRelPath, err := filepath.Rel(absBasePath, path)
if err != nil {
return fmt.Errorf("failed to get relative path for symlink: %v", err)
return fmt.Errorf("failed to get relative path for symlink: %w", err)
}
// deny all absolute symlinks
if filepath.IsAbs(linkTarget) {
@@ -78,7 +78,7 @@ func CheckOutOfBoundsSymlinks(basePath string) error {
newDir := filepath.Join(currentDir, part)
rel, err := filepath.Rel(absBasePath, newDir)
if err != nil {
return fmt.Errorf("failed to get relative path for symlink target: %v", err)
return fmt.Errorf("failed to get relative path for symlink target: %w", err)
}
if rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
// return an error so we don't keep traversing the tree

View File

@@ -469,7 +469,7 @@ func GetRefSources(ctx context.Context, sources argoappv1.ApplicationSources, pr
if source.Ref != "" {
repo, err := getRepository(ctx, source.RepoURL, project)
if err != nil {
return nil, fmt.Errorf("failed to get repository %s: %v", source.RepoURL, err)
return nil, fmt.Errorf("failed to get repository %s: %w", source.RepoURL, err)
}
refKey := "$" + source.Ref
revision := source.TargetRevision
@@ -501,7 +501,7 @@ func ValidateDestination(ctx context.Context, dest *argoappv1.ApplicationDestina
if dest.Server == "" {
server, err := getDestinationServer(ctx, db, dest.Name)
if err != nil {
return fmt.Errorf("unable to find destination server: %v", err)
return fmt.Errorf("unable to find destination server: %w", err)
}
if server == "" {
return fmt.Errorf("application references destination cluster %s which does not exist", dest.Name)

View File

@@ -400,7 +400,7 @@ func preDiffNormalize(lives, targets []*unstructured.Unstructured, diffConfig Di
}
err := diffConfig.Validate()
if err != nil {
return nil, fmt.Errorf("preDiffNormalize error: %s", err)
return nil, fmt.Errorf("preDiffNormalize error: %w", err)
}
results := &NormalizationResult{}

View File

@@ -30,7 +30,7 @@ func Normalize(live, config *unstructured.Unstructured, trustedManagers []string
configCopy := config.DeepCopy()
results, err := newTypedResults(liveCopy, configCopy, pt)
if err != nil {
return nil, nil, fmt.Errorf("error building typed results: %s", err)
return nil, nil, fmt.Errorf("error building typed results: %w", err)
}
normalized := false
@@ -38,7 +38,7 @@ func Normalize(live, config *unstructured.Unstructured, trustedManagers []string
if trustedManager(mf.Manager, trustedManagers) {
err := normalize(mf, results)
if err != nil {
return nil, nil, fmt.Errorf("error normalizing manager %s: %s", mf.Manager, err)
return nil, nil, fmt.Errorf("error normalizing manager %s: %w", mf.Manager, err)
}
normalized = true
}
@@ -93,16 +93,16 @@ type typedResults struct {
func newTypedResults(live, config *unstructured.Unstructured, pt *typed.ParseableType) (*typedResults, error) {
typedLive, err := pt.FromUnstructured(live.Object)
if err != nil {
return nil, fmt.Errorf("error creating typedLive: %s", err)
return nil, fmt.Errorf("error creating typedLive: %w", err)
}
typedConfig, err := pt.FromUnstructured(config.Object)
if err != nil {
return nil, fmt.Errorf("error creating typedConfig: %s", err)
return nil, fmt.Errorf("error creating typedConfig: %w", err)
}
comparison, err := typedLive.Compare(typedConfig)
if err != nil {
return nil, fmt.Errorf("error comparing typed resources: %s", err)
return nil, fmt.Errorf("error comparing typed resources: %w", err)
}
return &typedResults{
live: typedLive,

View File

@@ -3,6 +3,7 @@ package normalizers
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
@@ -84,7 +85,7 @@ func (np *jqNormalizerPatch) Apply(data []byte) ([]byte, error) {
return nil, fmt.Errorf("JQ patch did not return any data")
}
if err, ok = first.(error); ok {
if err == context.DeadlineExceeded {
if errors.Is(err, context.DeadlineExceeded) {
return nil, fmt.Errorf("JQ patch execution timed out (%v)", np.jqExecutionTimeout.String())
}
return nil, fmt.Errorf("JQ patch returned error: %w", err)

5
util/cache/redis.go vendored
View File

@@ -5,6 +5,7 @@ import (
"compress/gzip"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
@@ -127,7 +128,7 @@ func (r *redisCache) Set(item *Item) error {
func (r *redisCache) Get(key string, obj interface{}) error {
var data []byte
err := r.cache.Get(context.TODO(), r.getKey(key), &data)
if err == rediscache.ErrCacheMiss {
if errors.Is(err, rediscache.ErrCacheMiss) {
err = ErrCacheMiss
}
if err != nil {
@@ -182,7 +183,7 @@ func (rh *redisHook) ProcessHook(next redis.ProcessHook) redis.ProcessHook {
startTime := time.Now()
err := next(ctx, cmd)
rh.registry.IncRedisRequest(err != nil && err != redis.Nil)
rh.registry.IncRedisRequest(err != nil && !errors.Is(err, redis.Nil))
rh.registry.ObserveRedisRequestDuration(time.Since(startTime))
return err

View File

@@ -68,7 +68,7 @@ func CreateServiceAccount(
_, err := clientset.CoreV1().ServiceAccounts(namespace).Create(context.Background(), &serviceAccount, metav1.CreateOptions{})
if err != nil {
if !apierr.IsAlreadyExists(err) {
return fmt.Errorf("Failed to create service account %q in namespace %q: %v", serviceAccountName, namespace, err)
return fmt.Errorf("Failed to create service account %q in namespace %q: %w", serviceAccountName, namespace, err)
}
log.Infof("ServiceAccount %q already exists in namespace %q", serviceAccountName, namespace)
return nil
@@ -81,11 +81,11 @@ func upsert(kind string, name string, create func() (interface{}, error), update
_, err := create()
if err != nil {
if !apierr.IsAlreadyExists(err) {
return fmt.Errorf("Failed to create %s %q: %v", kind, name, err)
return fmt.Errorf("Failed to create %s %q: %w", kind, name, err)
}
_, err = update()
if err != nil {
return fmt.Errorf("Failed to update %s %q: %v", kind, name, err)
return fmt.Errorf("Failed to update %s %q: %w", kind, name, err)
}
log.Infof("%s %q updated", kind, name)
} else {
@@ -341,7 +341,7 @@ func UninstallClusterManagerRBAC(clientset kubernetes.Interface) error {
func UninstallRBAC(clientset kubernetes.Interface, namespace, bindingName, roleName, serviceAccount string) error {
if err := clientset.RbacV1().ClusterRoleBindings().Delete(context.Background(), bindingName, metav1.DeleteOptions{}); err != nil {
if !apierr.IsNotFound(err) {
return fmt.Errorf("Failed to delete ClusterRoleBinding: %v", err)
return fmt.Errorf("Failed to delete ClusterRoleBinding: %w", err)
}
log.Infof("ClusterRoleBinding %q not found", bindingName)
} else {
@@ -350,7 +350,7 @@ func UninstallRBAC(clientset kubernetes.Interface, namespace, bindingName, roleN
if err := clientset.RbacV1().ClusterRoles().Delete(context.Background(), roleName, metav1.DeleteOptions{}); err != nil {
if !apierr.IsNotFound(err) {
return fmt.Errorf("Failed to delete ClusterRole: %v", err)
return fmt.Errorf("Failed to delete ClusterRole: %w", err)
}
log.Infof("ClusterRole %q not found", roleName)
} else {
@@ -359,7 +359,7 @@ func UninstallRBAC(clientset kubernetes.Interface, namespace, bindingName, roleN
if err := clientset.CoreV1().ServiceAccounts(namespace).Delete(context.Background(), serviceAccount, metav1.DeleteOptions{}); err != nil {
if !apierr.IsNotFound(err) {
return fmt.Errorf("Failed to delete ServiceAccount: %v", err)
return fmt.Errorf("Failed to delete ServiceAccount: %w", err)
}
log.Infof("ServiceAccount %q in namespace %q not found", serviceAccount, namespace)
} else {
@@ -388,7 +388,7 @@ func ParseServiceAccountToken(token string) (*ServiceAccountClaims, error) {
var claims ServiceAccountClaims
_, _, err := parser.ParseUnverified(token, &claims)
if err != nil {
return nil, fmt.Errorf("Failed to parse service account token: %s", err)
return nil, fmt.Errorf("Failed to parse service account token: %w", err)
}
return &claims, nil
}

View File

@@ -5,6 +5,7 @@ import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"math"
@@ -178,7 +179,7 @@ func receiveFile(ctx context.Context, receiver StreamReceiver, checksum, dst str
}
req, err := receiver.Recv()
if err != nil {
if err == io.EOF {
if errors.Is(err, io.EOF) {
break
}
return nil, fmt.Errorf("stream Recv error: %w", err)

View File

@@ -80,11 +80,11 @@ func (db *db) CreateRepository(ctx context.Context, r *appsv1.Repository) (*apps
func (db *db) GetRepository(ctx context.Context, repoURL, project string) (*appsv1.Repository, error) {
repository, err := db.getRepository(ctx, repoURL, project)
if err != nil {
return repository, fmt.Errorf("unable to get repository %q: %v", repoURL, err)
return repository, fmt.Errorf("unable to get repository %q: %w", repoURL, err)
}
if err := db.enrichCredsToRepo(ctx, repository); err != nil {
return repository, fmt.Errorf("unable to enrich repository %q info with credentials: %v", repoURL, err)
return repository, fmt.Errorf("unable to enrich repository %q info with credentials: %w", repoURL, err)
}
return repository, err
@@ -125,11 +125,11 @@ func (db *db) getRepository(ctx context.Context, repoURL, project string) (*apps
secretsBackend := db.repoBackend()
exists, err := secretsBackend.RepositoryExists(ctx, repoURL, project, true)
if err != nil {
return nil, fmt.Errorf("unable to check if repository %q exists from secrets backend: %v", repoURL, err)
return nil, fmt.Errorf("unable to check if repository %q exists from secrets backend: %w", repoURL, err)
} else if exists {
repository, err := secretsBackend.GetRepository(ctx, repoURL, project)
if err != nil {
return nil, fmt.Errorf("unable to get repository %q from secrets backend: %v", repoURL, err)
return nil, fmt.Errorf("unable to get repository %q from secrets backend: %w", repoURL, err)
}
return repository, nil
}
@@ -137,11 +137,11 @@ func (db *db) getRepository(ctx context.Context, repoURL, project string) (*apps
legacyBackend := db.legacyRepoBackend()
exists, err = legacyBackend.RepositoryExists(ctx, repoURL, project, true)
if err != nil {
return nil, fmt.Errorf("unable to check if repository %q exists from legacy backend: %v", repoURL, err)
return nil, fmt.Errorf("unable to check if repository %q exists from legacy backend: %w", repoURL, err)
} else if exists {
repository, err := legacyBackend.GetRepository(ctx, repoURL, project)
if err != nil {
return nil, fmt.Errorf("unable to get repository %q from legacy backend: %v", repoURL, err)
return nil, fmt.Errorf("unable to get repository %q from legacy backend: %w", repoURL, err)
}
return repository, nil
}

View File

@@ -76,7 +76,7 @@ func (s *secretsRepositoryBackend) hasRepoTypeLabel(secretName string) (bool, er
func (s *secretsRepositoryBackend) GetRepoCredsBySecretName(_ context.Context, name string) (*appsv1.RepoCreds, error) {
secret, err := s.db.getSecret(name, map[string]*corev1.Secret{})
if err != nil {
return nil, fmt.Errorf("failed to get secret %s: %v", name, err)
return nil, fmt.Errorf("failed to get secret %s: %w", name, err)
}
return s.secretToRepoCred(secret)
}
@@ -171,7 +171,7 @@ func (s *secretsRepositoryBackend) RepositoryExists(ctx context.Context, repoURL
return false, nil
}
return false, fmt.Errorf("failed to get repository secret for %q: %v", repoURL, err)
return false, fmt.Errorf("failed to get repository secret for %q: %w", repoURL, err)
}
return secret != nil, nil

View File

@@ -15,12 +15,12 @@ func GenerateDexConfigYAML(argocdSettings *settings.ArgoCDSettings, disableTls b
}
redirectURL, err := argocdSettings.RedirectURL()
if err != nil {
return nil, fmt.Errorf("failed to infer redirect url from config: %v", err)
return nil, fmt.Errorf("failed to infer redirect url from config: %w", err)
}
var dexCfg map[string]interface{}
err = yaml.Unmarshal([]byte(argocdSettings.DexConfig), &dexCfg)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal dex.config from configmap: %v", err)
return nil, fmt.Errorf("failed to unmarshal dex.config from configmap: %w", err)
}
dexCfg["issuer"] = argocdSettings.IssuerURL()
dexCfg["storage"] = map[string]interface{}{

View File

@@ -1,5 +1,7 @@
package errors
import "errors"
type credentialsConfigurationError struct {
causingError error
}
@@ -15,6 +17,6 @@ func NewCredentialsConfigurationError(err error) error {
// IsCredentialsConfigurationError checks if the given error is a wrapped credentials configuration error.
func IsCredentialsConfigurationError(err error) bool {
_, ok := err.(*credentialsConfigurationError)
return ok
var ccErr *credentialsConfigurationError
return errors.As(err, &ccErr)
}

View File

@@ -322,13 +322,13 @@ func (m *nativeGitClient) Init() error {
if err == nil {
return nil
}
if err != git.ErrRepositoryNotExists {
if !errors.Is(err, git.ErrRepositoryNotExists) {
return err
}
log.Infof("Initializing %s to %s", m.repoURL, m.root)
err = os.RemoveAll(m.root)
if err != nil {
return fmt.Errorf("unable to clean repo at %s: %v", m.root, err)
return fmt.Errorf("unable to clean repo at %s: %w", m.root, err)
}
err = os.MkdirAll(m.root, 0755)
if err != nil {

View File

@@ -249,13 +249,13 @@ func InitializeGnuPG() error {
// re-initialize key ring.
err = removeKeyRing(gnuPgHome)
if err != nil {
return fmt.Errorf("re-initializing keyring at %s failed: %v", gnuPgHome, err)
return fmt.Errorf("re-initializing keyring at %s failed: %w", gnuPgHome, err)
}
}
err = os.WriteFile(filepath.Join(gnuPgHome, canaryMarkerFilename), []byte("canary"), 0644)
if err != nil {
return fmt.Errorf("could not create canary: %v", err)
return fmt.Errorf("could not create canary: %w", err)
}
f, err := os.CreateTemp("", "gpg-key-recipe")

View File

@@ -46,7 +46,7 @@ func (j *jsonpbMarshalleble) MarshalJSON() ([]byte, error) {
m := &jsonpb.Marshaler{}
err := m.Marshal(&b, j.Message)
if err != nil {
return nil, fmt.Errorf("jsonpb serializer failed: %v", err)
return nil, fmt.Errorf("jsonpb serializer failed: %w", err)
}
return b.Bytes(), nil
}

View File

@@ -238,7 +238,7 @@ func (c *nativeHelmChart) GetIndex(noCache bool, maxIndexSize int64) (*Index, er
var data []byte
if !noCache && c.indexCache != nil {
if err := c.indexCache.GetHelmIndex(c.repoURL, &data); err != nil && err != cache.ErrCacheMiss {
if err := c.indexCache.GetHelmIndex(c.repoURL, &data); err != nil && !errors.Is(err, cache.ErrCacheMiss) {
log.Warnf("Failed to load index cache for repo: %s: %v", c.repoURL, err)
}
}
@@ -416,7 +416,7 @@ func (c *nativeHelmChart) GetTags(chart string, noCache bool) (*TagsList, error)
var data []byte
if !noCache && c.indexCache != nil {
if err := c.indexCache.GetHelmIndex(tagsURL, &data); err != nil && err != cache.ErrCacheMiss {
if err := c.indexCache.GetHelmIndex(tagsURL, &data); err != nil && !errors.Is(err, cache.ErrCacheMiss) {
log.Warnf("Failed to load index cache for repo: %s: %v", tagsURL, err)
}
}
@@ -426,11 +426,11 @@ func (c *nativeHelmChart) GetTags(chart string, noCache bool) (*TagsList, error)
start := time.Now()
repo, err := remote.NewRepository(tagsURL)
if err != nil {
return nil, fmt.Errorf("failed to initialize repository: %v", err)
return nil, fmt.Errorf("failed to initialize repository: %w", err)
}
tlsConf, err := newTLSConfig(c.creds)
if err != nil {
return nil, fmt.Errorf("failed setup tlsConfig: %v", err)
return nil, fmt.Errorf("failed setup tlsConfig: %w", err)
}
client := &http.Client{Transport: &http.Transport{
Proxy: proxy.GetCallback(c.proxy),
@@ -460,7 +460,7 @@ func (c *nativeHelmChart) GetTags(chart string, noCache bool) (*TagsList, error)
})
if err != nil {
return nil, fmt.Errorf("failed to get tags: %v", err)
return nil, fmt.Errorf("failed to get tags: %w", err)
}
log.WithFields(
log.Fields{"seconds": time.Since(start).Seconds(), "chart": chart, "repo": c.repoURL},
@@ -474,7 +474,7 @@ func (c *nativeHelmChart) GetTags(chart string, noCache bool) (*TagsList, error)
} else {
err := json.Unmarshal(data, tags)
if err != nil {
return nil, fmt.Errorf("failed to decode tags: %v", err)
return nil, fmt.Errorf("failed to decode tags: %w", err)
}
}

View File

@@ -130,7 +130,7 @@ func Version(shortForm bool) (string, error) {
// short: "v3.3.1+g249e521"
version, err := executil.RunWithRedactor(cmd, redactor)
if err != nil {
return "", fmt.Errorf("could not get helm version: %s", err)
return "", fmt.Errorf("could not get helm version: %w", err)
}
return strings.TrimSpace(version), nil
}
@@ -160,7 +160,7 @@ func (h *helm) GetParameters(valuesFiles []pathutil.ResolvedFilePath, appPath, r
fileValues, err = os.ReadFile(file)
}
if err != nil {
return nil, fmt.Errorf("failed to read value file %s: %s", file, err)
return nil, fmt.Errorf("failed to read value file %s: %w", file, err)
}
values = append(values, string(fileValues))
}
@@ -169,7 +169,7 @@ func (h *helm) GetParameters(valuesFiles []pathutil.ResolvedFilePath, appPath, r
for _, file := range values {
values := map[string]interface{}{}
if err := yaml.Unmarshal([]byte(file), &values); err != nil {
return nil, fmt.Errorf("failed to parse values: %s", err)
return nil, fmt.Errorf("failed to parse values: %w", err)
}
flatVals(values, output)
}

View File

@@ -1,6 +1,7 @@
package helm
import (
"errors"
"fmt"
"time"
@@ -34,12 +35,12 @@ func (e Entries) MaxVersion(constraints *semver.Constraints) (*semver.Version, e
v, err := semver.NewVersion(entry.Version)
//Invalid semantic version ignored
if err == semver.ErrInvalidSemVer {
if errors.Is(err, semver.ErrInvalidSemVer) {
log.Debugf("Invalid sementic version: %s", entry.Version)
continue
}
if err != nil {
return nil, fmt.Errorf("invalid constraint in index: %v", err)
return nil, fmt.Errorf("invalid constraint in index: %w", err)
}
if constraints.Check(v) {
versions = append(versions, v)

View File

@@ -1,6 +1,7 @@
package helm
import (
"errors"
"fmt"
log "github.com/sirupsen/logrus"
@@ -18,12 +19,12 @@ func (t TagsList) MaxVersion(constraints *semver.Constraints) (*semver.Version,
v, err := semver.NewVersion(tag)
//Invalid semantic version ignored
if err == semver.ErrInvalidSemVer {
if errors.Is(err, semver.ErrInvalidSemVer) {
log.Debugf("Invalid semantic version: %s", tag)
continue
}
if err != nil {
return nil, fmt.Errorf("invalid constraint in tags: %v", err)
return nil, fmt.Errorf("invalid constraint in tags: %w", err)
}
if constraints.Check(v) {
versions = append(versions, v)

View File

@@ -107,14 +107,14 @@ func Untgz(dstPath string, r io.Reader, maxSize int64, preserveFileMode bool) er
if os.IsNotExist(err) {
realPath = linkTarget
} else if err != nil {
return fmt.Errorf("error checking symlink realpath: %s", err)
return fmt.Errorf("error checking symlink realpath: %w", err)
}
if !Inbound(realPath, dstPath) {
return fmt.Errorf("illegal filepath in symlink: %s", linkTarget)
}
err = os.Symlink(realPath, target)
if err != nil {
return fmt.Errorf("error creating symlink: %s", err)
return fmt.Errorf("error creating symlink: %w", err)
}
case tar.TypeReg:
var mode os.FileMode = 0644
@@ -155,7 +155,7 @@ func (t *tgz) tgzFile(path string, fi os.FileInfo, err error) error {
relativePath, err := RelativePath(path, t.srcPath)
if err != nil {
return fmt.Errorf("relative path error: %s", err)
return fmt.Errorf("relative path error: %w", err)
}
if t.inclusions != nil && base != "." && !fi.IsDir() {
@@ -197,7 +197,7 @@ func (t *tgz) tgzFile(path string, fi os.FileInfo, err error) error {
if IsSymlink(fi) {
link, err = os.Readlink(path)
if err != nil {
return fmt.Errorf("error getting link target: %s", err)
return fmt.Errorf("error getting link target: %w", err)
}
}

View File

@@ -57,11 +57,11 @@ func CreateTempDir(baseDir string) (string, error) {
}
newUUID, err := uuid.NewRandom()
if err != nil {
return "", fmt.Errorf("error creating directory name: %s", err)
return "", fmt.Errorf("error creating directory name: %w", err)
}
tempDir := path.Join(base, newUUID.String())
if err := os.MkdirAll(tempDir, 0755); err != nil {
return "", fmt.Errorf("error creating tempDir: %s", err)
return "", fmt.Errorf("error creating tempDir: %w", err)
}
return tempDir, nil
}

View File

@@ -1,6 +1,7 @@
package path
import (
"errors"
"fmt"
"net/url"
"os"
@@ -25,8 +26,8 @@ func resolveSymbolicLinkRecursive(path string, maxDepth int) (string, error) {
resolved, err := os.Readlink(path)
if err != nil {
// path is not a symbolic link
_, ok := err.(*os.PathError)
if ok {
var pathErr *os.PathError
if errors.As(err, &pathErr) {
return path, nil
}
// Other error has occurred

View File

@@ -406,7 +406,7 @@ func Version(shortForm bool) (string, error) {
// short: "{kustomize/v3.8.1 2020-07-16T00:58:46Z }"
version, err := executil.Run(cmd)
if err != nil {
return "", fmt.Errorf("could not get kustomize version: %s", err)
return "", fmt.Errorf("could not get kustomize version: %w", err)
}
version = strings.TrimSpace(version)
if shortForm {

View File

@@ -103,7 +103,7 @@ func ValidateLocalConfig(config LocalConfig) error {
return nil
}
if _, err := config.ResolveContext(config.CurrentContext); err != nil {
return fmt.Errorf("Local config invalid: %s", err)
return fmt.Errorf("Local config invalid: %w", err)
}
return nil
}

View File

@@ -5,6 +5,7 @@ import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"os"
@@ -137,7 +138,7 @@ func SendRepoStream(repoStream RepoStreamSender, appStream ApplicationStreamRece
for {
part, err := appStream.Recv()
if err != nil {
if err == io.EOF {
if errors.Is(err, io.EOF) {
break
}
return fmt.Errorf("stream Recv error: %w", err)
@@ -218,7 +219,7 @@ func receiveFile(ctx context.Context, receiver RepoStreamReceiver, checksum, dst
}
req, err := receiver.Recv()
if err != nil {
if err == io.EOF {
if errors.Is(err, io.EOF) {
break
}
return nil, fmt.Errorf("stream Recv error: %w", err)

View File

@@ -3,6 +3,7 @@ package oidc
import (
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"html"
"html/template"
@@ -113,7 +114,7 @@ func NewClientApp(settings *settings.ArgoCDSettings, dexServerAddr string, dexTl
log.Infof("Creating client app (%s)", a.clientID)
u, err := url.Parse(settings.URL)
if err != nil {
return nil, fmt.Errorf("parse redirect-uri: %v", err)
return nil, fmt.Errorf("parse redirect-uri: %w", err)
}
transport := &http.Transport{
@@ -572,7 +573,7 @@ func (a *ClientApp) GetUserInfo(actualClaims jwt.MapClaims, issuerURL, userInfoP
err := a.clientCache.Get(formatAccessTokenCacheKey(AccessTokenCachePrefix, sub), &encAccessToken)
// without an accessToken we can't query the user info endpoint
// thus the user needs to reauthenticate for argocd to get a new accessToken
if err == cache.ErrCacheMiss {
if errors.Is(err, cache.ErrCacheMiss) {
return claims, true, fmt.Errorf("no accessToken for %s: %w", sub, err)
} else if err != nil {
return claims, true, fmt.Errorf("couldn't read accessToken from cache for %s: %w", sub, err)

View File

@@ -66,7 +66,7 @@ func (p *providerImpl) newGoOIDCProvider() (*gooidc.Provider, error) {
ctx := gooidc.ClientContext(context.Background(), p.client)
prov, err := gooidc.NewProvider(ctx, p.issuerURL)
if err != nil {
return nil, fmt.Errorf("Failed to query provider %q: %v", p.issuerURL, err)
return nil, fmt.Errorf("Failed to query provider %q: %w", p.issuerURL, err)
}
s, _ := ParseConfig(prov)
log.Infof("OIDC supported scopes: %v", s.ScopesSupported)

View File

@@ -1,9 +1,11 @@
package oidc
import (
"errors"
"html/template"
"log"
"net/http"
"reflect"
)
type tokenTmplData struct {
@@ -55,10 +57,11 @@ func renderTemplate(w http.ResponseWriter, tmpl *template.Template, data interfa
return
}
switch err := err.(type) {
case *template.Error:
var templateErr *template.Error
switch {
case errors.As(err, &templateErr):
// An ExecError guarantees that Execute has not written to the underlying reader.
log.Printf("Error rendering template %s: %s", tmpl.Name(), err)
log.Printf("Error rendering template %s: %s", tmpl.Name(), reflect.TypeOf(err))
// TODO(ericchiang): replace with better internal server error.
http.Error(w, "Internal server error", http.StatusInternalServerError)

View File

@@ -20,7 +20,7 @@ func parseJWT(p string) ([]byte, error) {
}
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return nil, fmt.Errorf("malformed jwt payload: %v", err)
return nil, fmt.Errorf("malformed jwt payload: %w", err)
}
return payload, nil
}
@@ -58,11 +58,11 @@ type jwtWithOnlyAudClaim struct {
func getUnverifiedAudClaim(rawIDToken string) ([]string, error) {
payload, err := parseJWT(rawIDToken)
if err != nil {
return nil, fmt.Errorf("malformed jwt: %v", err)
return nil, fmt.Errorf("malformed jwt: %w", err)
}
var token jwtWithOnlyAudClaim
if err = json.Unmarshal(payload, &token); err != nil {
return nil, fmt.Errorf("failed to unmarshal claims: %v", err)
return nil, fmt.Errorf("failed to unmarshal claims: %w", err)
}
return token.Aud, nil
}

View File

@@ -292,7 +292,7 @@ func (mgr *SessionManager) GetLoginFailures() map[string]LoginAttempts {
var failures map[string]LoginAttempts
err := mgr.storage.GetLoginAttempts(&failures)
if err != nil {
if err != appstate.ErrCacheMiss {
if !errors.Is(err, appstate.ErrCacheMiss) {
log.Errorf("Could not retrieve login attempts: %v", err)
}
failures = make(map[string]LoginAttempts)

View File

@@ -7,6 +7,7 @@ import (
"crypto/tls"
"crypto/x509"
"encoding/base64"
"errors"
"fmt"
"math/big"
"net/url"
@@ -1073,7 +1074,7 @@ func (mgr *SettingsManager) GetResourceCompareOptions() (ArgoCDDiffOptions, erro
func (mgr *SettingsManager) GetHelmSettings() (*v1alpha1.HelmOptions, error) {
argoCDCM, err := mgr.getConfigMap()
if err != nil {
return nil, fmt.Errorf("failed to get argo-cd config map: %v", err)
return nil, fmt.Errorf("failed to get argo-cd config map: %w", err)
}
helmOptions := &v1alpha1.HelmOptions{}
if value, ok := argoCDCM.Data[helmValuesFileSchemesKey]; ok {
@@ -1509,7 +1510,7 @@ func validateExternalURL(u string) error {
}
URL, err := url.Parse(u)
if err != nil {
return fmt.Errorf("Failed to parse URL: %v", err)
return fmt.Errorf("Failed to parse URL: %w", err)
}
if URL.Scheme != "http" && URL.Scheme != "https" {
return fmt.Errorf("URL must include http or https protocol")
@@ -2050,8 +2051,8 @@ func (mgr *SettingsManager) notifySubscribers(newSettings *ArgoCDSettings) {
}
func isIncompleteSettingsError(err error) bool {
_, ok := err.(*incompleteSettingsError)
return ok
var incompleteSettingsErr *incompleteSettingsError
return errors.As(err, &incompleteSettingsErr)
}
// InitializeSettings is used to initialize empty admin password, signature, certificate etc if missing
@@ -2220,7 +2221,7 @@ func (mgr *SettingsManager) GetNamespace() string {
func (mgr *SettingsManager) GetResourceCustomLabels() ([]string, error) {
argoCDCM, err := mgr.getConfigMap()
if err != nil {
return []string{}, fmt.Errorf("failed getting configmap: %v", err)
return []string{}, fmt.Errorf("failed getting configmap: %w", err)
}
labels := argoCDCM.Data[resourceCustomLabelsKey]
if labels != "" {

View File

@@ -33,7 +33,7 @@ func CompressFiles(appPath string, included []string, excluded []string) (*os.Fi
appName := filepath.Base(appPath)
tempDir, err := files.CreateTempDir(os.TempDir())
if err != nil {
return nil, 0, "", fmt.Errorf("error creating tempDir for compressing files: %s", err)
return nil, 0, "", fmt.Errorf("error creating tempDir for compressing files: %w", err)
}
tgzFile, err := os.CreateTemp(tempDir, appName)
if err != nil {

View File

@@ -235,7 +235,7 @@ func generate(opts CertOptions) ([]byte, crypto.PrivateKey, error) {
return nil, nil, fmt.Errorf("Unrecognized elliptic curve: %q", opts.ECDSACurve)
}
if err != nil {
return nil, nil, fmt.Errorf("failed to generate private key: %s", err)
return nil, nil, fmt.Errorf("failed to generate private key: %w", err)
}
var notBefore time.Time
@@ -255,7 +255,7 @@ func generate(opts CertOptions) ([]byte, crypto.PrivateKey, error) {
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, nil, fmt.Errorf("failed to generate serial number: %s", err)
return nil, nil, fmt.Errorf("failed to generate serial number: %w", err)
}
if opts.Organization == "" {
@@ -289,7 +289,7 @@ func generate(opts CertOptions) ([]byte, crypto.PrivateKey, error) {
certBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, publicKey(privateKey), privateKey)
if err != nil {
return nil, nil, fmt.Errorf("Failed to create certificate: %s", err)
return nil, nil, fmt.Errorf("Failed to create certificate: %w", err)
}
return certBytes, privateKey, nil
}
@@ -348,11 +348,11 @@ func LoadX509CertPool(paths ...string) (*x509.CertPool, error) {
continue
}
// ...but everything else is considered an error
return nil, fmt.Errorf("could not load TLS certificate: %v", err)
return nil, fmt.Errorf("could not load TLS certificate: %w", err)
} else {
f, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("failure to load TLS certificates from %s: %v", path, err)
return nil, fmt.Errorf("failure to load TLS certificates from %s: %w", path, err)
}
if ok := pool.AppendCertsFromPEM(f); !ok {
return nil, fmt.Errorf("invalid cert data in %s", path)
@@ -366,7 +366,7 @@ func LoadX509CertPool(paths ...string) (*x509.CertPool, error) {
func LoadX509Cert(path string) (*x509.Certificate, error) {
bytes, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("could not read certificate file: %v", err)
return nil, fmt.Errorf("could not read certificate file: %w", err)
}
block, _ := pem.Decode(bytes)
if block == nil {
@@ -374,7 +374,7 @@ func LoadX509Cert(path string) (*x509.Certificate, error) {
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, fmt.Errorf("could not parse certificate: %v", err)
return nil, fmt.Errorf("could not parse certificate: %w", err)
}
return cert, nil
}
@@ -427,7 +427,7 @@ func CreateServerTLSConfig(tlsCertPath, tlsKeyPath string, hosts []string) (*tls
log.Infof("Loading TLS configuration from cert=%s and key=%s", tlsCertPath, tlsKeyPath)
c, err := tls.LoadX509KeyPair(tlsCertPath, tlsKeyPath)
if err != nil {
return nil, fmt.Errorf("Unable to initialize TLS configuration with cert=%s and key=%s: %v", tlsCertPath, tlsKeyPath, err)
return nil, fmt.Errorf("Unable to initialize TLS configuration with cert=%s and key=%s: %w", tlsCertPath, tlsKeyPath, err)
}
cert = &c
}