Selaa lähdekoodia

Better linter settings + linting errors fix

DarthSim 5 vuotta sitten
vanhempi
commit
aa2e8bd90e
10 muutettua tiedostoa jossa 84 lisäystä ja 70 poistoa
  1. 30 19
      .golangci.yml
  2. 1 1
      .lefthook/pre-commit/lint
  3. 4 3
      bufpool.go
  4. 7 5
      config.go
  5. 1 1
      download.go
  6. 1 1
      gcs_transport.go
  7. 12 10
      log.go
  8. 20 18
      process.go
  9. 8 10
      processing_options.go
  10. 0 2
      webp.go

+ 30 - 19
.golangci.yml

@@ -1,35 +1,46 @@
 run:
   skip-dirs:
     - .tmp
+    - vendor
 
 linters:
-  fast: true
+  disable-all: true
   enable:
-    - golint
-    - govet
-    - gosimple
-    - goconst
+    - deadcode
+    # - errcheck
+    - gocritic
+    # - goconst
     - goimports
+    - gosimple
+    - govet
+    - ineffassign
     - staticcheck
-  disable:
-    - errcheck
+    - structcheck
+    - stylecheck
+    - typecheck
+    - unused
+    - varcheck
+
+linters-settings:
+  govet:
+    # report about shadowed variables
+    check-shadowing: true
 
 issues:
   exclude-rules:
-    - path: _test\.go
-      linters:
-        - goconst
+    # - path: _test\.go
+    #   linters:
+    #     - goconst
 
     # False positives on CGO generated code
-    - linters:
-        - staticcheck
+    - linters: [staticcheck]
       text: "SA4000:"
+      path: vips\.go
 
-    - path: listen(_no)?_reuseport\.go
-      linters:
-        - typecheck
-      text: "declar"
+    # False positives on CGO generated code
+    - linters: [gocritic]
+      text: "dupSubExpr"
+      path: vips\.go
 
-    - linters:
-        - typecheck
-      text: "could not import C"
+    - linters: [stylecheck]
+      text: "ST1005:"

+ 1 - 1
.lefthook/pre-commit/lint

@@ -7,4 +7,4 @@ fi
 export CGO_LDFLAGS_ALLOW="-s|-w"
 export CGO_CFLAGS_ALLOW="-Xpreprocessor"
 
-golangci-lint run ./*.go
+golangci-lint run

+ 4 - 3
bufpool.go

@@ -97,15 +97,16 @@ func (p *bufPool) Get(size int) *bytes.Buffer {
 
 	var buf *bytes.Buffer
 
-	if minInd >= 0 {
+	switch {
+	case minInd >= 0:
 		// We found buffer with the desired size
 		buf = p.buffers[minInd]
 		p.buffers[minInd] = nil
-	} else if maxInd >= 0 {
+	case maxInd >= 0:
 		// We didn't find buffer with the desired size
 		buf = p.buffers[maxInd]
 		p.buffers[maxInd] = nil
-	} else {
+	default:
 		// We didn't find buffers at all
 		buf = new(bytes.Buffer)
 	}

+ 7 - 5
config.go

@@ -433,15 +433,17 @@ func configure() {
 
 	if conf.LocalFileSystemRoot != "" {
 		stat, err := os.Stat(conf.LocalFileSystemRoot)
+
 		if err != nil {
 			logFatal("Cannot use local directory: %s", err)
-		} else {
-			if !stat.IsDir() {
-				logFatal("Cannot use local directory: not a directory")
-			}
 		}
+
+		if !stat.IsDir() {
+			logFatal("Cannot use local directory: not a directory")
+		}
+
 		if conf.LocalFileSystemRoot == "/" {
-			logNotice("Exposing root via IMGPROXY_LOCAL_FILESYSTEM_ROOT is unsafe")
+			logWarning("Exposing root via IMGPROXY_LOCAL_FILESYSTEM_ROOT is unsafe")
 		}
 	}
 

+ 1 - 1
download.go

@@ -41,7 +41,7 @@ type limitReader struct {
 
 func (lr *limitReader) Read(p []byte) (n int, err error) {
 	n, err = lr.r.Read(p)
-	lr.left = lr.left - n
+	lr.left -= n
 
 	if err == nil && lr.left < 0 {
 		err = errSourceFileTooBig

+ 1 - 1
gcs_transport.go

@@ -24,7 +24,7 @@ func newGCSTransport() http.RoundTripper {
 	return gcsTransport{client}
 }
 
-func (t gcsTransport) RoundTrip(req *http.Request) (resp *http.Response, err error) {
+func (t gcsTransport) RoundTrip(req *http.Request) (*http.Response, error) {
 	bkt := t.client.Bucket(req.URL.Host)
 	obj := bkt.Object(strings.TrimPrefix(req.URL.Path, "/"))
 

+ 12 - 10
log.go

@@ -30,30 +30,32 @@ func logRequest(reqID string, r *http.Request) {
 func logResponse(reqID string, status int, msg string) {
 	var color int
 
-	if status >= 500 {
+	switch {
+	case status >= 500:
 		color = 31
-	} else if status >= 400 {
+	case status >= 400:
 		color = 33
-	} else {
+	default:
 		color = 32
 	}
 
 	log.Printf(logResponseFmt, reqID, color, status, msg)
 
 	if syslogWriter != nil {
-		msg := fmt.Sprintf(logResponseSyslogFmt, reqID, status, msg)
+		syslogMsg := fmt.Sprintf(logResponseSyslogFmt, reqID, status, msg)
 
-		if status >= 500 {
+		switch {
+		case status >= 500:
 			if syslogLevel >= syslog.LOG_ERR {
-				syslogWriter.Err(msg)
+				syslogWriter.Err(syslogMsg)
 			}
-		} else if status >= 400 {
+		case status >= 400:
 			if syslogLevel >= syslog.LOG_WARNING {
-				syslogWriter.Warning(msg)
+				syslogWriter.Warning(syslogMsg)
 			}
-		} else {
+		default:
 			if syslogLevel >= syslog.LOG_NOTICE {
-				syslogWriter.Notice(msg)
+				syslogWriter.Notice(syslogMsg)
 			}
 		}
 	}

+ 20 - 18
process.go

@@ -62,13 +62,14 @@ func calcScale(width, height int, po *processingOptions, imgtype imageType) floa
 			}
 		}
 
-		if po.Width == 0 {
+		switch {
+		case po.Width == 0:
 			scale = hr
-		} else if po.Height == 0 {
+		case po.Height == 0:
 			scale = wr
-		} else if rt == resizeFit {
+		case rt == resizeFit:
 			scale = math.Min(wr, hr)
-		} else {
+		default:
 			scale = math.Max(wr, hr)
 		}
 	}
@@ -77,7 +78,7 @@ func calcScale(width, height int, po *processingOptions, imgtype imageType) floa
 		scale = 1
 	}
 
-	scale = scale * po.Dpr
+	scale *= po.Dpr
 
 	if srcW*scale < 1 {
 		scale = 1 / srcW
@@ -287,19 +288,19 @@ func transformImage(ctx context.Context, img *vipsImage, data []byte, po *proces
 
 	cropWidth = scaleSize(cropWidth, scale)
 	cropHeight = scaleSize(cropHeight, scale)
-	cropGravity.X = cropGravity.X * scale
-	cropGravity.Y = cropGravity.Y * scale
+	cropGravity.X *= scale
+	cropGravity.Y *= scale
 
 	if scale != 1 && data != nil && canScaleOnLoad(imgtype, scale) {
 		if imgtype == imageTypeWEBP || imgtype == imageTypeSVG {
 			// Do some scale-on-load
-			if err := img.Load(data, imgtype, 1, scale, 1); err != nil {
+			if err = img.Load(data, imgtype, 1, scale, 1); err != nil {
 				return err
 			}
 		} else if imgtype == imageTypeJPEG {
 			// Do some shrink-on-load
 			if shrink := calcJpegShink(scale, imgtype); shrink != 1 {
-				if err := img.Load(data, imgtype, shrink, 1.0, 1); err != nil {
+				if err = img.Load(data, imgtype, shrink, 1.0, 1); err != nil {
 					return err
 				}
 			}
@@ -460,7 +461,7 @@ func transformAnimated(ctx context.Context, img *vipsImage, data []byte, po *pro
 	framesCount := minInt(img.Height()/frameHeight, conf.MaxAnimationFrames)
 
 	// Double check dimensions because animated image has many frames
-	if err := checkDimensions(imgWidth, frameHeight*framesCount); err != nil {
+	if err = checkDimensions(imgWidth, frameHeight*framesCount); err != nil {
 		return err
 	}
 
@@ -476,7 +477,7 @@ func transformAnimated(ctx context.Context, img *vipsImage, data []byte, po *pro
 		if nPages > framesCount || canScaleOnLoad(imgtype, scale) {
 			logNotice("Animated scale on load")
 			// Do some scale-on-load and load only the needed frames
-			if err := img.Load(data, imgtype, 1, scale, framesCount); err != nil {
+			if err = img.Load(data, imgtype, 1, scale, framesCount); err != nil {
 				return err
 			}
 		}
@@ -517,11 +518,11 @@ func transformAnimated(ctx context.Context, img *vipsImage, data []byte, po *pro
 		errg.Go(func() error {
 			frame := new(vipsImage)
 
-			if err := img.Extract(frame, 0, ind*frameHeight, imgWidth, frameHeight); err != nil {
+			if err = img.Extract(frame, 0, ind*frameHeight, imgWidth, frameHeight); err != nil {
 				return err
 			}
 
-			if err := transformImage(ctx, frame, nil, po, imgtype); err != nil {
+			if err = transformImage(ctx, frame, nil, po, imgtype); err != nil {
 				return err
 			}
 
@@ -531,13 +532,13 @@ func transformAnimated(ctx context.Context, img *vipsImage, data []byte, po *pro
 		})
 	}
 
-	if err := errg.Wait(); err != nil {
+	if err = errg.Wait(); err != nil {
 		return err
 	}
 
 	checkTimeout(ctx)
 
-	if err := img.Arrayjoin(frames); err != nil {
+	if err = img.Arrayjoin(frames); err != nil {
 		return err
 	}
 
@@ -575,11 +576,12 @@ func processImage(ctx context.Context) ([]byte, context.CancelFunc, error) {
 	imgtype := getImageType(ctx)
 
 	if po.Format == imageTypeUnknown {
-		if po.PreferWebP && vipsTypeSupportSave[imageTypeWEBP] {
+		switch {
+		case po.PreferWebP && vipsTypeSupportSave[imageTypeWEBP]:
 			po.Format = imageTypeWEBP
-		} else if vipsTypeSupportSave[imgtype] && imgtype != imageTypeHEIC {
+		case vipsTypeSupportSave[imgtype] && imgtype != imageTypeHEIC:
 			po.Format = imgtype
-		} else {
+		default:
 			po.Format = imageTypeJPEG
 		}
 	} else if po.EnforceWebP && vipsTypeSupportSave[imageTypeWEBP] {

+ 8 - 10
processing_options.go

@@ -736,8 +736,6 @@ func parseURLOptions(opts []string) (urlOptions, []string) {
 }
 
 func defaultProcessingOptions(headers *processingHeaders) (*processingOptions, error) {
-	var err error
-
 	po := processingOptions{
 		Resize:      resizeFit,
 		Width:       0,
@@ -775,10 +773,12 @@ func defaultProcessingOptions(headers *processingHeaders) (*processingOptions, e
 		}
 	}
 	if _, ok := conf.Presets["default"]; ok {
-		err = applyPresetOption(&po, []string{"default"})
+		if err := applyPresetOption(&po, []string{"default"}); err != nil {
+			return &po, err
+		}
 	}
 
-	return &po, err
+	return &po, nil
 }
 
 func parsePathAdvanced(parts []string, headers *processingHeaders) (string, *processingOptions, error) {
@@ -789,7 +789,7 @@ func parsePathAdvanced(parts []string, headers *processingHeaders) (string, *pro
 
 	options, urlParts := parseURLOptions(parts)
 
-	if err := applyProcessingOptions(po, options); err != nil {
+	if err = applyProcessingOptions(po, options); err != nil {
 		return "", po, err
 	}
 
@@ -799,7 +799,7 @@ func parsePathAdvanced(parts []string, headers *processingHeaders) (string, *pro
 	}
 
 	if len(extension) > 0 {
-		if err := applyFormatOption(po, []string{extension}); err != nil {
+		if err = applyFormatOption(po, []string{extension}); err != nil {
 			return "", po, err
 		}
 	}
@@ -816,7 +816,7 @@ func parsePathPresets(parts []string, headers *processingHeaders) (string, *proc
 	presets := strings.Split(parts[0], ":")
 	urlParts := parts[1:]
 
-	if err := applyPresetOption(po, presets); err != nil {
+	if err = applyPresetOption(po, presets); err != nil {
 		return "", nil, err
 	}
 
@@ -826,7 +826,7 @@ func parsePathPresets(parts []string, headers *processingHeaders) (string, *proc
 	}
 
 	if len(extension) > 0 {
-		if err := applyFormatOption(po, []string{extension}); err != nil {
+		if err = applyFormatOption(po, []string{extension}); err != nil {
 			return "", po, err
 		}
 	}
@@ -835,8 +835,6 @@ func parsePathPresets(parts []string, headers *processingHeaders) (string, *proc
 }
 
 func parsePathBasic(parts []string, headers *processingHeaders) (string, *processingOptions, error) {
-	var err error
-
 	if len(parts) < 6 {
 		return "", nil, fmt.Errorf("Invalid basic URL format arguments: %s", strings.Join(parts, "/"))
 	}

+ 0 - 2
webp.go

@@ -89,8 +89,6 @@ func decodeWebpConfig(r io.Reader) (image.Config, error) {
 				return image.Config{}, err
 			}
 
-			const alphaBit = 1 << 4
-
 			widthMinusOne := uint32(buf[4]) | uint32(buf[5])<<8 | uint32(buf[6])<<16
 			heightMinusOne := uint32(buf[7]) | uint32(buf[8])<<8 | uint32(buf[9])<<16