From 2eac7b14027ec23138ecafa84aaaf0a079c2b0a7 Mon Sep 17 00:00:00 2001
From: Gusted <postmaster@gusted.xyz>
Date: Sun, 21 Jul 2024 01:59:12 +0200
Subject: [PATCH] [BUG] Fix panic on too high page number

- Fixes a panic where the file history router would panic if the page
number was set to a page where no commits would be returned. It now
returns a 404 in such case.
- Regresion of a5b1c1b0b32a3746690fc10c9a4594a5b5b5c54f
- Panic log provided by @algernon.
- Minimal integration test added.

(cherry picked from commit 6a49e3f468455476a99c520deae7cb0526da00d1)

Co-authored-by: Gergely Nagy <forgejo@gergo.csillger.hu>
---
 routers/web/repo/commit.go     |  6 ++++++
 tests/integration/repo_test.go | 18 ++++++++++++++++++
 2 files changed, 24 insertions(+)

diff --git a/routers/web/repo/commit.go b/routers/web/repo/commit.go
index 718454e063..89e5727b16 100644
--- a/routers/web/repo/commit.go
+++ b/routers/web/repo/commit.go
@@ -244,6 +244,12 @@ func FileHistory(ctx *context.Context) {
 		ctx.ServerError("CommitsByFileAndRange", err)
 		return
 	}
+
+	if len(commits) == 0 {
+		ctx.NotFound("CommitsByFileAndRange", nil)
+		return
+	}
+
 	oldestCommit := commits[len(commits)-1]
 
 	renamedFiles, err := git.GetCommitFileRenames(ctx, ctx.Repo.GitRepo.Path, oldestCommit.ID.String())
diff --git a/tests/integration/repo_test.go b/tests/integration/repo_test.go
index 5cf9816d22..6525a2e0fd 100644
--- a/tests/integration/repo_test.go
+++ b/tests/integration/repo_test.go
@@ -995,3 +995,21 @@ func TestViewRepoOpenWith(t *testing.T) {
 		testOpenWith([]string{"test://"})
 	})
 }
+
+func TestFileHistoryPager(t *testing.T) {
+	defer tests.PrepareTestEnv(t)()
+
+	t.Run("Normal page number", func(t *testing.T) {
+		defer tests.PrintCurrentTest(t)()
+
+		req := NewRequest(t, "GET", "/user2/repo1/commits/branch/master/README.md?page=1")
+		MakeRequest(t, req, http.StatusOK)
+	})
+
+	t.Run("Too high page number", func(t *testing.T) {
+		defer tests.PrintCurrentTest(t)()
+
+		req := NewRequest(t, "GET", "/user2/repo1/commits/branch/master/README.md?page=9999")
+		MakeRequest(t, req, http.StatusNotFound)
+	})
+}