From 06e0f39b56b796ed2b5f94c0d37899aff410e6c6 Mon Sep 17 00:00:00 2001 From: Runxi Yu Date: Tue, 11 Feb 2025 23:48:21 +0800 Subject: [PATCH] repo_commit: Don't crash when viewing the first commit --- handle_repo_commit.go | 31 +++++++++++++++++++++++-------- templates/repo_commit.html.tmpl | 4 ++-- diff --git a/handle_repo_commit.go b/handle_repo_commit.go index d45fd1d5981cdb716fa00c9eae2da6beaa7c1aa4..5f7d495229f182356ea6f7c5a77fdb8316e535b9 100644 --- a/handle_repo_commit.go +++ b/handle_repo_commit.go @@ -1,10 +1,12 @@ package main import ( + "errors" "net/http" "strings" "github.com/go-git/go-git/v5/plumbing" + "github.com/go-git/go-git/v5/plumbing/object" "github.com/go-git/go-git/v5/plumbing/filemode" "github.com/go-git/go-git/v5/plumbing/format/diff" "go.lindenii.runxiyu.org/lindenii-common/misc" @@ -51,17 +53,30 @@ data["commit_object"] = commit_object data["commit_id"] = commit_id_string + var patch *object.Patch parent_commit_object, err := commit_object.Parent(0) - if err != nil { + if errors.Is(err, object.ErrParentNotFound) { + commit_tree, err := commit_object.Tree() + if err != nil { + _, _ = w.Write([]byte("Error getting commit tree (for comparing against an empty tree): " + err.Error())) + return + } + patch, err = (&object.Tree{}).Patch(commit_tree) + if err != nil { + _, _ = w.Write([]byte("Error getting patch of commit: " + err.Error())) + return + } + } else if err != nil { _, _ = w.Write([]byte("Error getting parent commit object: " + err.Error())) return - } - data["parent_commit_object"] = parent_commit_object - - patch, err := parent_commit_object.Patch(commit_object) - if err != nil { - _, _ = w.Write([]byte("Error getting patch of commit: " + err.Error())) - return + } else { + data["parent_commit_hash"] = parent_commit_object.Hash.String() + + patch, err = parent_commit_object.Patch(commit_object) + if err != nil { + _, _ = w.Write([]byte("Error getting patch of commit: " + err.Error())) + return + } } data["patch"] = patch diff --git a/templates/repo_commit.html.tmpl b/templates/repo_commit.html.tmpl index d56888773de32b648b038e342c9d5ec29b731183..13832a8b000cf3bcce30218fd4506cdb065e3f7a 100644 --- a/templates/repo_commit.html.tmpl +++ b/templates/repo_commit.html.tmpl @@ -46,14 +46,14 @@
- {{ $parent_commit_object := .parent_commit_object }} + {{ $parent_commit_hash := .parent_commit_hash }} {{ $commit_object := .commit_object }} {{ range .file_patches }}