internal/{derrors,worker}: move cleanup to derrors

Move the cleanup function to the derrors package and export it
so it can be used anywhere.

Change-Id: Ibb41faf96702e229c312233102f2ea3abc9e6202
Reviewed-on: https://go-review.googlesource.com/c/pkgsite-metrics/+/479236
Run-TryBot: Jonathan Amsterdam <jba@google.com>
Reviewed-by: Zvonimir Pavlinovic <zpavlinovic@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
diff --git a/internal/derrors/derrors.go b/internal/derrors/derrors.go
index d3a4d6f..d18768e 100644
--- a/internal/derrors/derrors.go
+++ b/internal/derrors/derrors.go
@@ -216,3 +216,9 @@
 	}
 	return err.Error()
 }
+
+// Cleanup calls f and combines the error with errp.
+// It is meant to be deferred.
+func Cleanup(errp *error, f func() error) {
+	*errp = errors.Join(*errp, f())
+}
diff --git a/internal/worker/analysis.go b/internal/worker/analysis.go
index 6c6ba64..e77eedd 100644
--- a/internal/worker/analysis.go
+++ b/internal/worker/analysis.go
@@ -83,7 +83,7 @@
 	if err := copyToLocalFile(localBinaryPath, executable, srcPath, s.openFile); err != nil {
 		return err
 	}
-	defer cleanup(&err, func() error { return os.Remove(localBinaryPath) })
+	defer derrors.Cleanup(&err, func() error { return os.Remove(localBinaryPath) })
 
 	binaryHash, err := hashFile(localBinaryPath)
 	if err != nil {
@@ -134,7 +134,7 @@
 
 func (s *analysisServer) scanInternal(ctx context.Context, req *analysis.ScanRequest, binaryPath string) (jt analysis.JSONTree, err error) {
 	mdir := moduleDir(req.Module, req.Version)
-	defer cleanup(&err, func() error { return os.RemoveAll(mdir) })
+	defer derrors.Cleanup(&err, func() error { return os.RemoveAll(mdir) })
 	if err := prepareModule(ctx, req.Module, req.Version, mdir, s.proxyClient, req.Insecure); err != nil {
 		return nil, err
 	}
diff --git a/internal/worker/govulncheck_scan.go b/internal/worker/govulncheck_scan.go
index ba52eb8..e310871 100644
--- a/internal/worker/govulncheck_scan.go
+++ b/internal/worker/govulncheck_scan.go
@@ -301,7 +301,7 @@
 		if mode != ModeBinary {
 			// In source analysis modes, download the module first.
 			inputPath = moduleDir(modulePath, version)
-			defer cleanup(&err, func() error { return os.RemoveAll(inputPath) })
+			defer derrors.Cleanup(&err, func() error { return os.RemoveAll(inputPath) })
 			if err := prepareModule(ctx, modulePath, version, inputPath, s.proxyClient, s.insecure); err != nil {
 				return err
 			}
diff --git a/internal/worker/scan.go b/internal/worker/scan.go
index 1a4847a..fa5fd59 100644
--- a/internal/worker/scan.go
+++ b/internal/worker/scan.go
@@ -247,9 +247,3 @@
 func moduleDir(modulePath, version string) string {
 	return filepath.Join(modulesDir, modulePath+"@"+version)
 }
-
-// cleanup calls f and combines the error with errp.
-// It is meant to be deferred.
-func cleanup(errp *error, f func() error) {
-	*errp = errors.Join(*errp, f())
-}