fix: pass merge commit messages to git via stdin (#39269)

`git commit --message=` passes the merge message as a single argument,
which Linux caps at 128 KiB and Windows at 32 KiB for the whole command
line. Long messages failed with `argument list too long` and the merge
box toast showed the raw HTML 500 page.

Pass the message via `--file=-` on stdin instead, and answer
fetch-action requests with JSON on server errors so the toast shows the
error text. Limits merge commit messages to 512KB which could be
extended or made configurable later.

Fixes: https://github.com/go-gitea/gitea/issues/39261
Fixes: https://github.com/go-gitea/gitea/issues/30276
Signed-off-by: wxiaoguang <wxiaoguang@gmail.com>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
This commit is contained in:
silverwind
2026-09-19 13:04:53 +00:00
committed by GitHub
co-authored by wxiaoguang
parent cc34c26172
commit cdf786ce92
21 changed files with 175 additions and 93 deletions
+11
View File
@@ -248,3 +248,14 @@ func GetFullCommitID(ctx context.Context, repo RepositoryFacade, shortID string)
} }
return strings.TrimSpace(commitID), nil return strings.TrimSpace(commitID), nil
} }
func AddObjectMessageArgument(cmd *gitcmd.Command, typ ObjectType, message string) error {
if len(message) > 512*1024 {
// It doesn't make sense to store very large messages in git objects,
// and it never succeeded in the past due to the command line argument limit (e.g.: 128K on Linux).
// If any real world user would complain about the limit, let them explain why, then make the limit configurable.
return util.NewInvalidArgumentErrorf("git %s message is too long", typ)
}
cmd.AddArguments("--file=-").WithStdinBytes([]byte(message))
return nil
}
-5
View File
@@ -8,11 +8,6 @@ import (
"os" "os"
) )
type PipeBufferReader interface {
Read(p []byte) (n int, err error)
Bytes() []byte
}
type PipeBufferWriter interface { type PipeBufferWriter interface {
Write(p []byte) (n int, err error) Write(p []byte) (n int, err error)
Bytes() []byte Bytes() []byte
+23 -28
View File
@@ -9,32 +9,10 @@ import (
"context" "context"
"errors" "errors"
"io" "io"
"strings"
"gitea.dev/modules/git/gitcmd" "gitea.dev/modules/setting"
"gitea.dev/modules/log"
) )
// ResolveReference resolves a name to a reference
func (repo *Repository) ResolveReference(ctx context.Context, name string) (string, error) {
stdout, _, err := gitcmd.NewCommand("show-ref", "--hash").
AddDynamicArguments(name).
WithRepo(repo).
RunStdString(ctx)
if err != nil {
if strings.Contains(err.Error(), "not a valid ref") {
return "", ErrNotExist{name, ""}
}
return "", err
}
stdout = strings.TrimSpace(stdout)
if stdout == "" {
return "", ErrNotExist{name, ""}
}
return stdout, nil
}
// GetRefCommitID returns the last commit ID string of given reference (branch or tag). // GetRefCommitID returns the last commit ID string of given reference (branch or tag).
func (repo *Repository) GetRefCommitID(ctx context.Context, name string) (string, error) { func (repo *Repository) GetRefCommitID(ctx context.Context, name string) (string, error) {
batch, cancel, err := repo.CatFileBatch() batch, cancel, err := repo.CatFileBatch()
@@ -60,6 +38,15 @@ func (repo *Repository) getCommit(ctx context.Context, id ObjectID) (*Commit, er
return repo.getCommitWithBatch(batch, id) return repo.getCommitWithBatch(batch, id)
} }
func limitDiscardReader(rd BufferedReader, full, limit int64) (io.Reader, func() error) {
return io.LimitReader(rd, min(full, limit)), func() error {
if full > limit {
return DiscardFull(rd, full-limit)
}
return nil
}
}
func (repo *Repository) getCommitWithBatch(batch CatFileBatch, id ObjectID) (*Commit, error) { func (repo *Repository) getCommitWithBatch(batch CatFileBatch, id ObjectID) (*Commit, error) {
info, rd, err := batch.QueryContent(id.String()) info, rd, err := batch.QueryContent(id.String())
if err != nil { if err != nil {
@@ -73,12 +60,14 @@ func (repo *Repository) getCommitWithBatch(batch CatFileBatch, id ObjectID) (*Co
case "missing": case "missing":
return nil, ErrNotExist{ID: id.String()} return nil, ErrNotExist{ID: id.String()}
case "tag": case "tag":
// then we need to parse the tag limitReader, limitDiscard := limitDiscardReader(rd, info.Size, MaxGitObjectSize)
// and load the commit data, err := io.ReadAll(limitReader)
data, err := io.ReadAll(io.LimitReader(rd, info.Size))
if err != nil { if err != nil {
return nil, err return nil, err
} }
if err = limitDiscard(); err != nil {
return nil, err
}
_, err = rd.Discard(1) _, err = rd.Discard(1)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -89,10 +78,14 @@ func (repo *Repository) getCommitWithBatch(batch CatFileBatch, id ObjectID) (*Co
} }
return repo.getCommitWithBatch(batch, tag.Object) return repo.getCommitWithBatch(batch, tag.Object)
case "commit": case "commit":
commit, err := CommitFromReader(id, io.LimitReader(rd, info.Size)) limitReader, limitDiscard := limitDiscardReader(rd, info.Size, MaxGitObjectSize)
commit, err := CommitFromReader(id, limitReader)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if err = limitDiscard(); err != nil {
return nil, err
}
_, err = rd.Discard(1) _, err = rd.Discard(1)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -100,7 +93,9 @@ func (repo *Repository) getCommitWithBatch(batch CatFileBatch, id ObjectID) (*Co
return commit, nil return commit, nil
default: default:
log.Debug("Unknown cat-file object type: %s", info.Type) if info.Type != "blob" && info.Type != "tree" {
setting.PanicInDevOrTesting("Unknown cat-file object type %s for object %s in repo %s", info.Type, id.String(), repo.LogString())
}
if err := DiscardFull(rd, info.Size+1); err != nil { if err := DiscardFull(rd, info.Size+1); err != nil {
return nil, err return nil, err
} }
-6
View File
@@ -73,12 +73,6 @@ func (repo *Repository) ReadTreeToTemporaryIndex(ctx context.Context, treeish st
return tmpIndexFilename, tmpDir, cancel, nil return tmpIndexFilename, tmpDir, cancel, nil
} }
// EmptyIndex empties the index
func (repo *Repository) EmptyIndex(ctx context.Context) error {
_, _, err := gitcmd.NewCommand("read-tree", "--empty").WithRepo(repo).RunStdString(ctx)
return err
}
// LsFiles checks if the given filenames are in the index // LsFiles checks if the given filenames are in the index
func (repo *Repository) LsFiles(ctx context.Context, filenames ...string) ([]string, error) { func (repo *Repository) LsFiles(ctx context.Context, filenames ...string) ([]string, error) {
cmd := gitcmd.NewCommand("ls-files", "-z").AddDashesAndList(filenames...) cmd := gitcmd.NewCommand("ls-files", "-z").AddDashesAndList(filenames...)
+4
View File
@@ -11,6 +11,10 @@ import (
"gitea.dev/modules/git/gitcmd" "gitea.dev/modules/git/gitcmd"
) )
// MaxGitObjectSize is used to avoid OOM when reading a large git object.
// GitHub has a limit (100M) for pushing, but Gitea doesn't have such a limit yet.
var MaxGitObjectSize int64 = 100 * 1024 * 1024
// ObjectType git object type // ObjectType git object type
type ObjectType string type ObjectType string
+5 -5
View File
@@ -27,11 +27,11 @@ func (repo *Repository) CreateTag(ctx context.Context, name, revision string) er
// CreateAnnotatedTag create one annotated tag in the repository // CreateAnnotatedTag create one annotated tag in the repository
func (repo *Repository) CreateAnnotatedTag(ctx context.Context, name, message, revision string) error { func (repo *Repository) CreateAnnotatedTag(ctx context.Context, name, message, revision string) error {
_, _, err := gitcmd.NewCommand("tag", "-a", "-m"). cmd := gitcmd.NewCommand("tag", "--annotate")
AddDynamicArguments(message). if err := AddObjectMessageArgument(cmd, ObjectTag, message); err != nil {
AddDashesAndList(name, revision). return err
WithRepo(repo). }
RunStdString(ctx) _, _, err := cmd.AddDashesAndList(name, revision).WithRepo(repo).RunStdString(ctx)
return err return err
} }
+6 -3
View File
@@ -106,12 +106,15 @@ func (repo *Repository) getTag(ctx context.Context, tagID ObjectID, name string)
return nil, ErrNotExist{ID: tagID.String()} return nil, ErrNotExist{ID: tagID.String()}
} }
// then we need to parse the tag // then we need to parse the tag and load the commit
// and load the commit limitReader, limitDiscard := limitDiscardReader(rd, info.Size, MaxGitObjectSize)
data, err := io.ReadAll(io.LimitReader(rd, size)) data, err := io.ReadAll(limitReader)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if err = limitDiscard(); err != nil {
return nil, err
}
_, err = rd.Discard(1) _, err = rd.Discard(1)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -5,6 +5,8 @@ package httplib
import ( import (
"context" "context"
"errors"
"io"
"net" "net"
"net/http" "net/http"
"net/url" "net/url"
@@ -240,3 +242,28 @@ func ParseGiteaSiteURL(ctx context.Context, s string) *GiteaSiteURL {
} }
return ret return ret
} }
func IsGiteaFetchActionRequest(req *http.Request) bool {
return req.Header.Get("X-Gitea-Fetch-Action") != ""
}
func IsClientOrNetworkError(ctx context.Context, err error) bool {
if err == nil {
return false
}
if ctx.Err() != nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return true
}
// client request corrupted (e.g.: Content-Length is sent but body is incomplete)
if errors.Is(err, io.ErrUnexpectedEOF) {
return true
}
// network error
if _, ok := errors.AsType[net.Error](err); ok {
return true
}
return false
}
+2 -1
View File
@@ -9,6 +9,7 @@ import (
"net/url" "net/url"
"strings" "strings"
"gitea.dev/modules/httplib"
"gitea.dev/modules/session" "gitea.dev/modules/session"
"gitea.dev/modules/setting" "gitea.dev/modules/setting"
"gitea.dev/modules/util" "gitea.dev/modules/util"
@@ -35,7 +36,7 @@ func DeleteRedirectToCookie(resp http.ResponseWriter) {
} }
func RedirectLinkUserLogin(req *http.Request) string { func RedirectLinkUserLogin(req *http.Request) string {
if req.Header.Get("X-Gitea-Fetch-Action") != "" { if httplib.IsGiteaFetchActionRequest(req) {
// when building the redirect link for a fetch request, the current link might be a partial page, // when building the redirect link for a fetch request, the current link might be a partial page,
// so we only redirect to the login page without redirect_to parameter // so we only redirect to the login page without redirect_to parameter
return setting.AppSubURL + "/user/login" return setting.AppSubURL + "/user/login"
+1 -1
View File
@@ -161,7 +161,7 @@ func (b *Base) Redirect(location string, status ...int) {
} }
// In case the request is made by "fetch-action" module, make JS redirect to the new location // In case the request is made by "fetch-action" module, make JS redirect to the new location
// Otherwise, the JS fetch will follow the redirection and read a "login" page, embed it to the current page, which is not expected. // Otherwise, the JS fetch will follow the redirection and read a "login" page, embed it to the current page, which is not expected.
if b.Req.Header.Get("X-Gitea-Fetch-Action") != "" { if httplib.IsGiteaFetchActionRequest(b.Req) {
b.JSON(http.StatusOK, map[string]any{"redirect": location}) b.JSON(http.StatusOK, map[string]any{"redirect": location})
return return
} }
+6 -1
View File
@@ -6,6 +6,7 @@ package context
import ( import (
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"os"
"testing" "testing"
"gitea.dev/modules/setting" "gitea.dev/modules/setting"
@@ -13,8 +14,12 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
func TestRedirect(t *testing.T) { func TestMain(m *testing.M) {
setting.IsInTesting = true setting.IsInTesting = true
os.Exit(m.Run())
}
func TestRedirect(t *testing.T) {
req, _ := http.NewRequest(http.MethodGet, "/", nil) req, _ := http.NewRequest(http.MethodGet, "/", nil)
cases := []struct { cases := []struct {
+6 -2
View File
@@ -270,8 +270,12 @@ func (ctx *Context) JSONErrorAuto(err error) {
ctx.JSON(httpCode, buildJsonErrorMap(errMsg)) ctx.JSON(httpCode, buildJsonErrorMap(errMsg))
return return
} }
log.ErrorWithSkip(1, "JSONErrorAuto: server internal error: %v", err)
ctx.JSON(http.StatusInternalServerError, buildJsonErrorMap(ctx.Locale.TrString("error.occurred"))) logLevel := util.Iif(httplib.IsClientOrNetworkError(ctx, err), log.DEBUG, log.ERROR)
log.Log(1, logLevel, "JSONErrorAuto: server internal error: %v", err)
userErrorMsg := ctx.buildUserErrorMessage("internal server error", err)
ctx.JSON(http.StatusInternalServerError, buildJsonErrorMap(userErrorMsg))
} }
func (ctx *Context) JSONError[T string | template.HTML](msg T) { func (ctx *Context) JSONError[T string | template.HTML](msg T) {
+28 -21
View File
@@ -7,13 +7,11 @@ import (
"errors" "errors"
"fmt" "fmt"
"html/template" "html/template"
"net"
"net/http" "net/http"
"net/url" "net/url"
"path" "path"
"strconv" "strconv"
"strings" "strings"
"syscall"
"time" "time"
user_model "gitea.dev/models/user" user_model "gitea.dev/models/user"
@@ -90,7 +88,7 @@ func (ctx *Context) HTML(status int, name templates.TplName) {
} }
err := ctx.Render.HTML(ctx.Resp, status, name, ctx.Data, ctx.TemplateContext) err := ctx.Render.HTML(ctx.Resp, status, name, ctx.Data, ctx.TemplateContext)
if err == nil || errors.Is(err, syscall.EPIPE) { if err == nil || httplib.IsClientOrNetworkError(ctx, err) {
return return
} }
@@ -126,13 +124,13 @@ func (ctx *Context) RenderWithErrDeprecated(msg any, tpl templates.TplName, form
// NotFound displays a 404 (Not Found) page and prints the given error, if any. // NotFound displays a 404 (Not Found) page and prints the given error, if any.
func (ctx *Context) NotFound(logErr error) { func (ctx *Context) NotFound(logErr error) {
ctx.notFoundInternal("", logErr) ctx.notFoundInternal(1, "", logErr)
} }
func (ctx *Context) notFoundInternal(logMsg string, logErr error) { func (ctx *Context) notFoundInternal(skip int, logMsg string, logErr error) {
// TODO: it's safe to show the error message to end users if the error is fully controlled by our error system // TODO: it's safe to show the error message to end users if the error is fully controlled by our error system
if logErr != nil { if logErr != nil {
log.Log(2, log.DEBUG, "%s: %v", logMsg, logErr) log.Log(skip+1, log.DEBUG, "%s: %v", logMsg, logErr)
} }
// response simple message if Accept isn't text/html // response simple message if Accept isn't text/html
@@ -155,32 +153,41 @@ func (ctx *Context) notFoundInternal(logMsg string, logErr error) {
ctx.HTML(http.StatusNotFound, "status/404") ctx.HTML(http.StatusNotFound, "status/404")
} }
func (ctx *Context) buildUserErrorMessage(msg string, err error) (userErrorMsg string) {
// it's safe to show internal error to admin users, and it helps
if !setting.IsProd || (ctx.Doer != nil && ctx.Doer.IsAdmin) {
userErrorMsg = msg
if err != nil {
userErrorMsg += ", error: " + err.Error()
}
}
return util.IfZero(userErrorMsg, ctx.Locale.TrString("error.occurred"))
}
// ServerError displays a 500 (Internal Server Error) page and prints the given error, if any. // ServerError displays a 500 (Internal Server Error) page and prints the given error, if any.
// If the error is controlled by our error system, a related 404 page can be displayed instead. // If the error is controlled by our error system, a related 404 page can be displayed instead.
func (ctx *Context) ServerError(logMsg string, logErr error) { func (ctx *Context) ServerError(logMsg string, logErr error) {
if errors.Is(logErr, util.ErrNotExist) { if errors.Is(logErr, util.ErrNotExist) {
ctx.notFoundInternal(logMsg, logErr) ctx.notFoundInternal(1, logMsg, logErr)
return return
} }
ctx.serverErrorInternal(logMsg, logErr) ctx.serverErrorInternal(1, logMsg, logErr)
} }
func (ctx *Context) serverErrorInternal(logMsg string, logErr error) { func (ctx *Context) serverErrorInternal(skip int, logMsg string, logErr error) {
if logErr != nil { if logErr != nil {
log.ErrorWithSkip(2, "%s: %v", logMsg, logErr) logLevel := util.Iif(httplib.IsClientOrNetworkError(ctx, logErr), log.DEBUG, log.ERROR)
if _, ok := logErr.(*net.OpError); ok || errors.Is(logErr, &net.OpError{}) { log.Log(skip+1, logLevel, "%s: %v", logMsg, logErr)
// This is an error within the underlying connection }
// and further rendering will not work so just return
return
}
// it's safe to show internal error to admin users, and it helps userErrorMsg := ctx.buildUserErrorMessage(logMsg, logErr)
if !setting.IsProd || (ctx.Doer != nil && ctx.Doer.IsAdmin) { if httplib.IsGiteaFetchActionRequest(ctx.Req) {
ctx.Data["ErrorMsg"] = fmt.Sprintf("%s, %s", logMsg, logErr) ctx.JSON(http.StatusInternalServerError, buildJsonErrorMap(userErrorMsg))
} return
} }
ctx.Data["Title"] = "Internal Server Error" ctx.Data["Title"] = "Internal Server Error"
ctx.Data["ErrorMsg"] = userErrorMsg
ctx.HTML(http.StatusInternalServerError, tplStatus500) ctx.HTML(http.StatusInternalServerError, tplStatus500)
} }
@@ -190,8 +197,8 @@ func (ctx *Context) serverErrorInternal(logMsg string, logErr error) {
// TODO: remove the "errCheck" and use util.ErrNotFound to check // TODO: remove the "errCheck" and use util.ErrNotFound to check
func (ctx *Context) NotFoundOrServerError(logMsg string, errCheck func(error) bool, logErr error) { func (ctx *Context) NotFoundOrServerError(logMsg string, errCheck func(error) bool, logErr error) {
if errCheck(logErr) { if errCheck(logErr) {
ctx.notFoundInternal(logMsg, logErr) ctx.notFoundInternal(1, logMsg, logErr)
return return
} }
ctx.serverErrorInternal(logMsg, logErr) ctx.serverErrorInternal(1, logMsg, logErr)
} }
+12 -2
View File
@@ -4,6 +4,7 @@
package context package context
import ( import (
"errors"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"net/url" "net/url"
@@ -27,8 +28,18 @@ func TestRemoveSessionCookieHeader(t *testing.T) {
assert.Contains(t, "other=bar", w.Header().Get("Set-Cookie")) assert.Contains(t, "other=bar", w.Header().Get("Set-Cookie"))
} }
func TestServerErrorFetchActionRespondsJSON(t *testing.T) {
req, _ := http.NewRequest(http.MethodPost, "/", nil)
req.Header.Add("X-Gitea-Fetch-Action", "1")
resp := httptest.NewRecorder()
ctx := NewWebContext(NewBaseContextForTest(t, resp, req), nil, nil)
ctx.ServerError("test", errors.New("boom"))
assert.Equal(t, http.StatusInternalServerError, resp.Code)
assert.Contains(t, resp.Header().Get("Content-Type"), "application/json")
assert.JSONEq(t, `{"errorMessage":"test, error: boom","renderFormat":"text"}`, resp.Body.String())
}
func TestRedirectToCurrentSite(t *testing.T) { func TestRedirectToCurrentSite(t *testing.T) {
setting.IsInTesting = true
defer test.MockVariableValue(&setting.AppURL, "http://localhost:3000/sub/")() defer test.MockVariableValue(&setting.AppURL, "http://localhost:3000/sub/")()
defer test.MockVariableValue(&setting.AppSubURL, "/sub")() defer test.MockVariableValue(&setting.AppSubURL, "/sub")()
cases := []struct { cases := []struct {
@@ -53,7 +64,6 @@ func TestRedirectToCurrentSite(t *testing.T) {
} }
func TestAppFullLink(t *testing.T) { func TestAppFullLink(t *testing.T) {
setting.IsInTesting = true
defer test.MockVariableValue(&setting.AppURL, "https://gitea.example.com/sub/")() defer test.MockVariableValue(&setting.AppURL, "https://gitea.example.com/sub/")()
defer test.MockVariableValue(&setting.AppSubURL, "/sub")() defer test.MockVariableValue(&setting.AppSubURL, "/sub")()
defer test.MockVariableValue(&setting.PublicURLDetection, setting.PublicURLNever)() defer test.MockVariableValue(&setting.PublicURLDetection, setting.PublicURLNever)()
+4 -1
View File
@@ -460,7 +460,10 @@ func doMergeAndPush(ctx context.Context, pr *issues_model.PullRequest, doer *use
} }
func commitAndSignNoAuthor(ctx *mergeContext, message string) error { func commitAndSignNoAuthor(ctx *mergeContext, message string) error {
cmdCommit := gitcmd.NewCommand("commit").AddOptionFormat("--message=%s", message) cmdCommit := gitcmd.NewCommand("commit")
if err := git.AddObjectMessageArgument(cmdCommit, git.ObjectCommit, message); err != nil {
return err
}
addCommitSigningOptions(cmdCommit, ctx.signKey) addCommitSigningOptions(cmdCommit, ctx.signKey)
if err := ctx.PrepareGitCmd(cmdCommit).RunWithStderr(ctx); err != nil { if err := ctx.PrepareGitCmd(cmdCommit).RunWithStderr(ctx); err != nil {
return fmt.Errorf("git commit %v: %w\n%s", ctx.pr, err, ctx.outbuf.String()) return fmt.Errorf("git commit %v: %w\n%s", ctx.pr, err, ctx.outbuf.String())
+4 -2
View File
@@ -73,8 +73,10 @@ func doMergeRebaseFastForward(ctx *mergeContext) error {
} }
if newMessage != "" { if newMessage != "" {
cmdCommit := gitcmd.NewCommand("commit", "--amend"). cmdCommit := gitcmd.NewCommand("commit", "--amend")
AddOptionFormat("--message=%s", newMessage) if err = git.AddObjectMessageArgument(cmdCommit, git.ObjectCommit, newMessage); err != nil {
return err
}
addCommitSigningOptions(cmdCommit, ctx.signKey) addCommitSigningOptions(cmdCommit, ctx.signKey)
if err := cmdCommit.WithRepo(ctx.tmpRepo).Run(ctx); err != nil { if err := cmdCommit.WithRepo(ctx.tmpRepo).Run(ctx); err != nil {
log.Error("Unable to amend commit message: %v", err) log.Error("Unable to amend commit message: %v", err)
+5 -4
View File
@@ -67,10 +67,11 @@ func doMergeStyleSquash(ctx *mergeContext, message string) error {
if setting.Repository.PullRequest.AddCoCommitterTrailers && ctx.committer.String() != sig.String() { if setting.Repository.PullRequest.AddCoCommitterTrailers && ctx.committer.String() != sig.String() {
message = AddCommitMessageTailer(message, git.CoAuthoredByTrailer, sig.String()) message = AddCommitMessageTailer(message, git.CoAuthoredByTrailer, sig.String())
} }
cmdCommit := gitcmd.NewCommand("commit"). cmdCommit := gitcmd.NewCommand("commit", "--allow-empty").
AddOptionFormat("--author='%s <%s>'", sig.Name, sig.Email). AddOptionFormat("--author='%s <%s>'", sig.Name, sig.Email)
AddOptionFormat("--message=%s", message). if err = git.AddObjectMessageArgument(cmdCommit, git.ObjectCommit, message); err != nil {
AddArguments("--allow-empty") return err
}
addCommitSigningOptions(cmdCommit, ctx.signKey) addCommitSigningOptions(cmdCommit, ctx.signKey)
if err := ctx.PrepareGitCmd(cmdCommit).RunWithStderr(ctx); err != nil { if err := ctx.PrepareGitCmd(cmdCommit).RunWithStderr(ctx); err != nil {
log.Error("git commit %-v: %v\n%s\n%s", ctx.pr, err, ctx.outbuf.String(), err.Stderr()) log.Error("git commit %-v: %v\n%s\n%s", ctx.pr, err, ctx.outbuf.String(), err.Stderr())
+18 -9
View File
@@ -6,6 +6,7 @@ package integration
import ( import (
"fmt" "fmt"
"net/http" "net/http"
"strings"
"testing" "testing"
auth_model "gitea.dev/models/auth" auth_model "gitea.dev/models/auth"
@@ -14,6 +15,7 @@ import (
user_model "gitea.dev/models/user" user_model "gitea.dev/models/user"
"gitea.dev/modules/git" "gitea.dev/modules/git"
api "gitea.dev/modules/structs" api "gitea.dev/modules/structs"
"gitea.dev/modules/test"
"gitea.dev/tests" "gitea.dev/tests"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@@ -36,20 +38,17 @@ func TestAPIGitTags(t *testing.T) {
commit, _ := gitRepo.GetBranchCommit(t.Context(), "master") commit, _ := gitRepo.GetBranchCommit(t.Context(), "master")
lTagName := "lightweightTag" lTagName := "lightweightTag"
gitRepo.CreateTag(t.Context(), lTagName, commit.ID.String()) _ = gitRepo.CreateTag(t.Context(), lTagName, commit.ID.String())
aTagName := "annotatedTag" aTagName := "annotatedTag"
aTagMessage := "my annotated message" aTagMessage := strings.Repeat("very long " /*10bytes*/, 20*1024) + "annotated message"
gitRepo.CreateAnnotatedTag(t.Context(), aTagName, aTagMessage, commit.ID.String()) _ = gitRepo.CreateAnnotatedTag(t.Context(), aTagName, aTagMessage, commit.ID.String())
aTag, _ := gitRepo.GetTag(t.Context(), aTagName) aTag, _ := gitRepo.GetTag(t.Context(), aTagName)
// SHOULD work for annotated tags // SHOULD work for annotated tags
req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/tags/%s", user.Name, repo.Name, aTag.ID.String()). req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/tags/%s", user.Name, repo.Name, aTag.ID.String()).AddTokenAuth(token)
AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK)
res := MakeRequest(t, req, http.StatusOK) tag := DecodeJSON(t, resp, &api.AnnotatedTag{})
tag := DecodeJSON(t, res, &api.AnnotatedTag{})
assert.Equal(t, aTagName, tag.Tag) assert.Equal(t, aTagName, tag.Tag)
assert.Equal(t, aTag.ID.String(), tag.SHA) assert.Equal(t, aTag.ID.String(), tag.SHA)
assert.Equal(t, commit.ID.String(), tag.Object.SHA) assert.Equal(t, commit.ID.String(), tag.Object.SHA)
@@ -58,6 +57,16 @@ func TestAPIGitTags(t *testing.T) {
assert.Equal(t, user.Email, tag.Tagger.Email) assert.Equal(t, user.Email, tag.Tagger.Email)
assert.Equal(t, repo.APIURL()+"/git/tags/"+aTag.ID.String(), tag.URL) assert.Equal(t, repo.APIURL()+"/git/tags/"+aTag.ID.String(), tag.URL)
if !git.DefaultFeatures().UsingGogit {
defer test.MockVariableValue(&git.MaxGitObjectSize, 1024)()
req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/tags/%s", user.Name, repo.Name, aTag.ID.String()).AddTokenAuth(token)
resp = MakeRequest(t, req, http.StatusOK)
tag = DecodeJSON(t, resp, &api.AnnotatedTag{})
assert.True(t, strings.HasPrefix(aTagMessage, tag.Message))
assert.Less(t, len(tag.Message), len(aTagMessage))
assert.Less(t, len(tag.Message), 1024)
}
// Should NOT work for lightweight tags // Should NOT work for lightweight tags
badReq := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/tags/%s", user.Name, repo.Name, commit.ID.String()). badReq := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/tags/%s", user.Name, repo.Name, commit.ID.String()).
AddTokenAuth(token) AddTokenAuth(token)
+13 -2
View File
@@ -51,6 +51,7 @@ type MergeOptions struct {
Style repo_model.MergeStyle Style repo_model.MergeStyle
HeadCommitID string HeadCommitID string
DeleteBranch bool DeleteBranch bool
Message string
} }
func testPullMerge(t *testing.T, session *TestSession, user, repo, pullNum string, mergeOptions MergeOptions) *httptest.ResponseRecorder { func testPullMerge(t *testing.T, session *TestSession, user, repo, pullNum string, mergeOptions MergeOptions) *httptest.ResponseRecorder {
@@ -58,6 +59,7 @@ func testPullMerge(t *testing.T, session *TestSession, user, repo, pullNum strin
"do": string(mergeOptions.Style), "do": string(mergeOptions.Style),
"head_commit_id": mergeOptions.HeadCommitID, "head_commit_id": mergeOptions.HeadCommitID,
"delete_branch_after_merge": util.Iif(mergeOptions.DeleteBranch, "on", ""), "delete_branch_after_merge": util.Iif(mergeOptions.DeleteBranch, "on", ""),
"merge_message_field": mergeOptions.Message,
} }
var resp *httptest.ResponseRecorder var resp *httptest.ResponseRecorder
require.Eventually(t, func() bool { require.Eventually(t, func() bool {
@@ -77,6 +79,15 @@ func testPullMerge(t *testing.T, session *TestSession, user, repo, pullNum strin
assert.NoError(t, err) assert.NoError(t, err)
assert.True(t, pull.HasMerged) assert.True(t, pull.HasMerged)
if mergeOptions.Message != "" {
gitRepo, err := git.OpenRepository(t.Context(), repository)
require.NoError(t, err)
defer gitRepo.Close()
commit, err := gitRepo.GetCommit(t.Context(), pull.MergedCommitID)
require.NoError(t, err)
assert.Contains(t, commit.CommitMessage.MessageRaw, mergeOptions.Message)
}
return resp return resp
} }
@@ -116,8 +127,8 @@ func TestPullMerge(t *testing.T) {
elem := strings.Split(test.RedirectURL(resp), "/") elem := strings.Split(test.RedirectURL(resp), "/")
assert.Equal(t, "pulls", elem[3]) assert.Equal(t, "pulls", elem[3])
testPullMerge(t, session, elem[1], elem[2], elem[4], MergeOptions{ testPullMerge(t, session, elem[1], elem[2], elem[4], MergeOptions{
Style: repo_model.MergeStyleMerge, Style: repo_model.MergeStyleMerge,
DeleteBranch: false, Message: strings.Repeat("x", 200*1024),
}) })
repo = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repo.ID}) repo = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repo.ID})