From 113d13a02672c757addc598cc95defd7a507fb8a Mon Sep 17 00:00:00 2001
From: KN4CK3R <admin@oldschoolhack.me>
Date: Tue, 9 Aug 2022 17:33:45 +0200
Subject: [PATCH] Keep download count on Container tag overwrite (#20728)
 (#20735)

Co-authored-by: 6543 <6543@obermui.de>
---
 integrations/api_packages_container_test.go | 14 +++++++++++++-
 routers/api/packages/container/manifest.go  |  3 +++
 2 files changed, 16 insertions(+), 1 deletion(-)

diff --git a/integrations/api_packages_container_test.go b/integrations/api_packages_container_test.go
index 850ac626f6..af659363d5 100644
--- a/integrations/api_packages_container_test.go
+++ b/integrations/api_packages_container_test.go
@@ -275,11 +275,23 @@ func TestPackageContainer(t *testing.T) {
 							}
 						}
 
-						// Overwrite existing tag
+						req = NewRequest(t, "GET", fmt.Sprintf("%s/manifests/%s", url, tag))
+						addTokenAuthHeader(req, userToken)
+						MakeRequest(t, req, http.StatusOK)
+
+						pv, err = packages_model.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages_model.TypeContainer, image, tag)
+						assert.NoError(t, err)
+						assert.EqualValues(t, 1, pv.DownloadCount)
+
+						// Overwrite existing tag should keep the download count
 						req = NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/manifests/%s", url, tag), strings.NewReader(manifestContent))
 						addTokenAuthHeader(req, userToken)
 						req.Header.Set("Content-Type", oci.MediaTypeDockerManifest)
 						MakeRequest(t, req, http.StatusCreated)
+
+						pv, err = packages_model.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages_model.TypeContainer, image, tag)
+						assert.NoError(t, err)
+						assert.EqualValues(t, 1, pv.DownloadCount)
 					})
 
 					t.Run("HeadManifest", func(t *testing.T) {
diff --git a/routers/api/packages/container/manifest.go b/routers/api/packages/container/manifest.go
index 319c9bcabc..8beed3dbb7 100644
--- a/routers/api/packages/container/manifest.go
+++ b/routers/api/packages/container/manifest.go
@@ -312,6 +312,9 @@ func createPackageAndVersion(ctx context.Context, mci *manifestCreationInfo, met
 				return nil, err
 			}
 
+			// keep download count on overwrite
+			_pv.DownloadCount = pv.DownloadCount
+
 			if pv, err = packages_model.GetOrInsertVersion(ctx, _pv); err != nil {
 				log.Error("Error inserting package: %v", err)
 				return nil, err