mirror of
https://github.com/go-gitea/gitea.git
synced 2025-12-05 01:10:26 +00:00
Compare commits
5 Commits
1baca49870
...
ed977d9702
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ed977d9702 | ||
|
|
62d750eadb | ||
|
|
a60a8c6966 | ||
|
|
4c51acb26b | ||
|
|
543e3bf7e9 |
@@ -25,6 +25,10 @@ insert_final_newline = false
|
||||
[templates/user/auth/oidc_wellknown.tmpl]
|
||||
indent_style = space
|
||||
|
||||
[templates/shared/actions/runner_badge_*.tmpl]
|
||||
# editconfig lint requires these XML-like files to have charset defined, but the files don't have.
|
||||
charset = unset
|
||||
|
||||
[Makefile]
|
||||
indent_style = tab
|
||||
|
||||
|
||||
@@ -2334,7 +2334,7 @@ LEVEL = Info
|
||||
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; Resynchronize pre-receive, update and post-receive hooks of all repositories.
|
||||
;; Resynchronize git hooks of all repositories (pre-receive, update, post-receive, proc-receive, ...)
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;[cron.resync_all_hooks]
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
|
||||
@@ -3039,7 +3039,7 @@ dashboard.update_migration_poster_id = Update migration poster IDs
|
||||
dashboard.git_gc_repos = Garbage-collect all repositories
|
||||
dashboard.resync_all_sshkeys = Update the '.ssh/authorized_keys' file with Gitea SSH keys
|
||||
dashboard.resync_all_sshprincipals = Update the '.ssh/authorized_principals' file with Gitea SSH principals
|
||||
dashboard.resync_all_hooks = Resynchronize pre-receive, update and post-receive hooks of all repositories
|
||||
dashboard.resync_all_hooks = Resynchronize git hooks of all repositories (pre-receive, update, post-receive, proc-receive, ...)
|
||||
dashboard.reinit_missing_repos = Reinitialize all missing Git repositories for which records exist
|
||||
dashboard.sync_external_users = Synchronize external user data
|
||||
dashboard.cleanup_hook_task_table = Clean up hook_task table
|
||||
|
||||
@@ -3038,7 +3038,6 @@ dashboard.update_migration_poster_id=Actualiser les ID des affiches de migration
|
||||
dashboard.git_gc_repos=Exécuter le ramasse-miette des dépôts
|
||||
dashboard.resync_all_sshkeys=Mettre à jour le fichier « ssh/authorized_keys » avec les clés SSH Gitea.
|
||||
dashboard.resync_all_sshprincipals=Mettre à jour le fichier « .ssh/authorized_principals » avec les principaux de Gitea SSH.
|
||||
dashboard.resync_all_hooks=Re-synchroniser les déclencheurs Git pre-receive, update et post-receive de tous les dépôts.
|
||||
dashboard.reinit_missing_repos=Réinitialiser tous les dépôts Git manquants pour lesquels un enregistrement existe
|
||||
dashboard.sync_external_users=Synchroniser les données de l’utilisateur externe
|
||||
dashboard.cleanup_hook_task_table=Nettoyer la table hook_task
|
||||
|
||||
@@ -3038,7 +3038,6 @@ dashboard.update_migration_poster_id=Nuashonraigh ID póstaer imir
|
||||
dashboard.git_gc_repos=Bailitheoir bruscair gach stórais
|
||||
dashboard.resync_all_sshkeys=Nuashonraigh an comhad '.ssh/authorized_keys' le heochracha SSH Gitea
|
||||
dashboard.resync_all_sshprincipals=Nuashonraigh an comhad '.ssh/authorized_principals' le príomhoidí SSH Gitea
|
||||
dashboard.resync_all_hooks=Athshioncrónaigh crúcaí réamhghlactha, nuashonraithe agus iarghlactha na stórais uile
|
||||
dashboard.reinit_missing_repos=Aththosaigh gach stórais Git atá in easnamh a bhfuil taifid ann dóibh
|
||||
dashboard.sync_external_users=Sioncrónaigh sonraí úsáideoirí seachtracha
|
||||
dashboard.cleanup_hook_task_table=Glan suas an tábla hook_task
|
||||
|
||||
@@ -3038,7 +3038,6 @@ dashboard.update_migration_poster_id=移行する投稿者IDの更新
|
||||
dashboard.git_gc_repos=すべてのリポジトリでガベージコレクションを実行
|
||||
dashboard.resync_all_sshkeys='.ssh/authorized_keys' ファイルをGitea上のSSHキーで更新
|
||||
dashboard.resync_all_sshprincipals='.ssh/authorized_principals' ファイルをGitea上のSSHプリンシパルで更新
|
||||
dashboard.resync_all_hooks=すべてのリポジトリの pre-receive, update, post-receive フックを再同期する
|
||||
dashboard.reinit_missing_repos=レコードが存在するが見当たらないすべてのGitリポジトリを再初期化する
|
||||
dashboard.sync_external_users=外部ユーザーデータの同期
|
||||
dashboard.cleanup_hook_task_table=hook_taskテーブルのクリーンアップ
|
||||
|
||||
@@ -3039,7 +3039,6 @@ dashboard.update_migration_poster_id=Sincronizar os IDs do remetente da migraç
|
||||
dashboard.git_gc_repos=Fazer a recolha do lixo em todos os repositórios
|
||||
dashboard.resync_all_sshkeys=Sincronizar o ficheiro '.ssh/authorized_keys' com as chaves SSH do Gitea
|
||||
dashboard.resync_all_sshprincipals=Modificar o ficheiro '.ssh/authorized_principals' com os protagonistas SSH do Gitea
|
||||
dashboard.resync_all_hooks=Voltar a sincronizar automatismos de pré-acolhimento, modificação e pós-acolhimento de todos os repositórios
|
||||
dashboard.reinit_missing_repos=Reinicializar todos os repositórios Git em falta para os quais existam registos
|
||||
dashboard.sync_external_users=Sincronizar dados externos do utilizador
|
||||
dashboard.cleanup_hook_task_table=Limpar a tabela hook_task
|
||||
|
||||
@@ -3032,7 +3032,6 @@ dashboard.update_migration_poster_id=Taşıma poster kimliklerini güncelle
|
||||
dashboard.git_gc_repos=Tüm depolardaki atıkları temizle
|
||||
dashboard.resync_all_sshkeys='.ssh/authority_keys' dosyasını Gitea SSH anahtarlarıyla güncelle
|
||||
dashboard.resync_all_sshprincipals='.ssh/authorized_principals' dosyasını Gitea SSH sorumlularıyla güncelleyin
|
||||
dashboard.resync_all_hooks=Tüm depoların alma öncesi, güncelleme ve alma sonrası kancalarını yeniden senkronize edin
|
||||
dashboard.reinit_missing_repos=Kayıtları bulunanlar için tüm eksik Git depolarını yeniden başlat
|
||||
dashboard.sync_external_users=Harici kullanıcı verisini senkronize et
|
||||
dashboard.cleanup_hook_task_table=Hook_task tablosunu temizle
|
||||
|
||||
@@ -3036,7 +3036,6 @@ dashboard.update_migration_poster_id=更新迁移的发表者ID
|
||||
dashboard.git_gc_repos=对仓库进行垃圾回收
|
||||
dashboard.resync_all_sshkeys=使用 Gitea 的 SSH 密钥更新「.ssh/authorized_keys」文件。
|
||||
dashboard.resync_all_sshprincipals=使用 Gitea 的 SSH 规则更新「.ssh/authorized_principals」文件。
|
||||
dashboard.resync_all_hooks=重新同步所有仓库的 pre-receive、update 和 post-receive 钩子
|
||||
dashboard.reinit_missing_repos=重新初始化所有丢失的 Git 仓库存在的记录
|
||||
dashboard.sync_external_users=同步外部用户数据
|
||||
dashboard.cleanup_hook_task_table=清理 hook_task 表
|
||||
|
||||
@@ -81,6 +81,7 @@ import (
|
||||
"code.gitea.io/gitea/modules/log"
|
||||
"code.gitea.io/gitea/modules/setting"
|
||||
api "code.gitea.io/gitea/modules/structs"
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
"code.gitea.io/gitea/modules/web"
|
||||
"code.gitea.io/gitea/routers/api/v1/activitypub"
|
||||
"code.gitea.io/gitea/routers/api/v1/admin"
|
||||
@@ -774,7 +775,9 @@ func apiAuth(authMethod auth.Method) func(*context.APIContext) {
|
||||
return func(ctx *context.APIContext) {
|
||||
ar, err := common.AuthShared(ctx.Base, nil, authMethod)
|
||||
if err != nil {
|
||||
ctx.APIError(http.StatusUnauthorized, err)
|
||||
msg, ok := auth.ErrAsUserAuthMessage(err)
|
||||
msg = util.Iif(ok, msg, "invalid username, password or token")
|
||||
ctx.APIError(http.StatusUnauthorized, msg)
|
||||
return
|
||||
}
|
||||
ctx.Doer = ar.Doer
|
||||
|
||||
@@ -201,7 +201,7 @@ func CreateIssueDependency(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
dependencyPerm := getPermissionForRepo(ctx, target.Repo)
|
||||
dependencyPerm := getPermissionForRepo(ctx, dependency.Repo)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
@@ -262,7 +262,7 @@ func RemoveIssueDependency(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
dependencyPerm := getPermissionForRepo(ctx, target.Repo)
|
||||
dependencyPerm := getPermissionForRepo(ctx, dependency.Repo)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"net/http"
|
||||
|
||||
repo_model "code.gitea.io/gitea/models/repo"
|
||||
unit_model "code.gitea.io/gitea/models/unit"
|
||||
"code.gitea.io/gitea/services/context"
|
||||
"code.gitea.io/gitea/services/convert"
|
||||
release_service "code.gitea.io/gitea/services/release"
|
||||
@@ -58,6 +59,13 @@ func GetReleaseByTag(ctx *context.APIContext) {
|
||||
return
|
||||
}
|
||||
|
||||
if release.IsDraft { // only the users with write access can see draft releases
|
||||
if !ctx.IsSigned || !ctx.Repo.CanWrite(unit_model.TypeReleases) {
|
||||
ctx.APIErrorNotFound()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if err = release.LoadAttributes(ctx); err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
|
||||
@@ -146,7 +146,13 @@ func httpBase(ctx *context.Context) *serviceHandler {
|
||||
// rely on the results of Contexter
|
||||
if !ctx.IsSigned {
|
||||
// TODO: support digit auth - which would be Authorization header with digit
|
||||
ctx.Resp.Header().Set("WWW-Authenticate", `Basic realm="Gitea"`)
|
||||
if setting.OAuth2.Enabled {
|
||||
// `Basic realm="Gitea"` tells the GCM to use builtin OAuth2 application: https://github.com/git-ecosystem/git-credential-manager/pull/1442
|
||||
ctx.Resp.Header().Set("WWW-Authenticate", `Basic realm="Gitea"`)
|
||||
} else {
|
||||
// If OAuth2 is disabled, then use another realm to avoid GCM OAuth2 attempt
|
||||
ctx.Resp.Header().Set("WWW-Authenticate", `Basic realm="Gitea (Basic Auth)"`)
|
||||
}
|
||||
ctx.HTTPError(http.StatusUnauthorized)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -206,12 +206,11 @@ func SoftDeleteContentHistory(ctx *context.Context) {
|
||||
ctx.NotFound(issues_model.ErrCommentNotExist{})
|
||||
return
|
||||
}
|
||||
if history.CommentID != commentID {
|
||||
ctx.NotFound(issues_model.ErrCommentNotExist{})
|
||||
return
|
||||
}
|
||||
if commentID != 0 {
|
||||
if history.CommentID != commentID {
|
||||
ctx.NotFound(issues_model.ErrCommentNotExist{})
|
||||
return
|
||||
}
|
||||
|
||||
if comment, err = issues_model.GetCommentByID(ctx, commentID); err != nil {
|
||||
log.Error("can not get comment for issue content history %v. err=%v", historyID, err)
|
||||
return
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
@@ -40,6 +41,20 @@ var globalVars = sync.OnceValue(func() *globalVarsStruct {
|
||||
}
|
||||
})
|
||||
|
||||
type ErrUserAuthMessage string
|
||||
|
||||
func (e ErrUserAuthMessage) Error() string {
|
||||
return string(e)
|
||||
}
|
||||
|
||||
func ErrAsUserAuthMessage(err error) (string, bool) {
|
||||
var msg ErrUserAuthMessage
|
||||
if errors.As(err, &msg) {
|
||||
return msg.Error(), true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// Init should be called exactly once when the application starts to allow plugins
|
||||
// to allocate necessary resources
|
||||
func Init() {
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
actions_model "code.gitea.io/gitea/models/actions"
|
||||
@@ -146,7 +145,7 @@ func (b *Basic) Verify(req *http.Request, w http.ResponseWriter, store DataStore
|
||||
return nil, err
|
||||
}
|
||||
if hasWebAuthn {
|
||||
return nil, errors.New("basic authorization is not allowed while WebAuthn enrolled")
|
||||
return nil, ErrUserAuthMessage("basic authorization is not allowed while WebAuthn enrolled")
|
||||
}
|
||||
|
||||
if err := validateTOTP(req, u); err != nil {
|
||||
|
||||
@@ -542,8 +542,9 @@ func ToVerification(ctx context.Context, c *git.Commit) *api.PayloadCommitVerifi
|
||||
}
|
||||
if verif.SigningUser != nil {
|
||||
commitVerification.Signer = &api.PayloadUser{
|
||||
Name: verif.SigningUser.Name,
|
||||
Email: verif.SigningUser.Email,
|
||||
UserName: verif.SigningUser.Name,
|
||||
Name: verif.SigningUser.DisplayName(),
|
||||
Email: verif.SigningEmail, // Use the email from the signature, not from the user profile
|
||||
}
|
||||
}
|
||||
return commitVerification
|
||||
|
||||
@@ -547,11 +547,15 @@ var escapedSymbols = regexp.MustCompile(`([*[?! \\])`)
|
||||
|
||||
// IsUserAllowedToMerge check if user is allowed to merge PR with given permissions and branch protections
|
||||
func IsUserAllowedToMerge(ctx context.Context, pr *issues_model.PullRequest, p access_model.Permission, user *user_model.User) (bool, error) {
|
||||
return isUserAllowedToMergeInRepoBranch(ctx, pr.BaseRepoID, pr.BaseBranch, p, user)
|
||||
}
|
||||
|
||||
func isUserAllowedToMergeInRepoBranch(ctx context.Context, repoID int64, branch string, p access_model.Permission, user *user_model.User) (bool, error) {
|
||||
if user == nil {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
pb, err := git_model.GetFirstMatchProtectedBranchRule(ctx, pr.BaseRepoID, pr.BaseBranch)
|
||||
pb, err := git_model.GetFirstMatchProtectedBranchRule(ctx, repoID, branch)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
@@ -71,7 +71,8 @@ func doMergeStyleSquash(ctx *mergeContext, message string) error {
|
||||
}
|
||||
cmdCommit := gitcmd.NewCommand("commit").
|
||||
AddOptionFormat("--author='%s <%s>'", sig.Name, sig.Email).
|
||||
AddOptionFormat("--message=%s", message)
|
||||
AddOptionFormat("--message=%s", message).
|
||||
AddArguments("--allow-empty")
|
||||
if ctx.signKey == nil {
|
||||
cmdCommit.AddArguments("--no-gpg-sign")
|
||||
} else {
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"code.gitea.io/gitea/models/db"
|
||||
git_model "code.gitea.io/gitea/models/git"
|
||||
@@ -838,51 +839,53 @@ func GetSquashMergeCommitMessages(ctx context.Context, pr *issues_model.PullRequ
|
||||
stringBuilder := strings.Builder{}
|
||||
|
||||
if !setting.Repository.PullRequest.PopulateSquashCommentWithCommitMessages {
|
||||
// use PR's title and description as squash commit message
|
||||
message := strings.TrimSpace(pr.Issue.Content)
|
||||
stringBuilder.WriteString(message)
|
||||
if stringBuilder.Len() > 0 {
|
||||
stringBuilder.WriteRune('\n')
|
||||
if !commitMessageTrailersPattern.MatchString(message) {
|
||||
// TODO: this trailer check doesn't work with the separator line added below for the co-authors
|
||||
stringBuilder.WriteRune('\n')
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// use PR's commit messages as squash commit message
|
||||
// commits list is in reverse chronological order
|
||||
maxMsgSize := setting.Repository.PullRequest.DefaultMergeMessageSize
|
||||
for i := len(commits) - 1; i >= 0; i-- {
|
||||
commit := commits[i]
|
||||
msg := strings.TrimSpace(commit.CommitMessage)
|
||||
if msg == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
// This format follows GitHub's squash commit message style,
|
||||
// even if there are other "* " in the commit message body, they are written as-is.
|
||||
// Maybe, ideally, we should indent those lines too.
|
||||
_, _ = fmt.Fprintf(&stringBuilder, "* %s\n\n", msg)
|
||||
if maxMsgSize > 0 && stringBuilder.Len() >= maxMsgSize {
|
||||
tmp := stringBuilder.String()
|
||||
wasValidUtf8 := utf8.ValidString(tmp)
|
||||
tmp = tmp[:maxMsgSize] + "..."
|
||||
if wasValidUtf8 {
|
||||
// If the message was valid UTF-8 before truncation, ensure it remains valid after truncation
|
||||
// For non-utf8 messages, we can't do much about it, end users should use utf-8 as much as possible
|
||||
tmp = strings.ToValidUTF8(tmp, "")
|
||||
}
|
||||
stringBuilder.Reset()
|
||||
stringBuilder.WriteString(tmp)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// commits list is in reverse chronological order
|
||||
first := true
|
||||
for i := len(commits) - 1; i >= 0; i-- {
|
||||
commit := commits[i]
|
||||
|
||||
if setting.Repository.PullRequest.PopulateSquashCommentWithCommitMessages {
|
||||
maxSize := setting.Repository.PullRequest.DefaultMergeMessageSize
|
||||
if maxSize < 0 || stringBuilder.Len() < maxSize {
|
||||
var toWrite []byte
|
||||
if first {
|
||||
first = false
|
||||
toWrite = []byte(strings.TrimPrefix(commit.CommitMessage, pr.Issue.Title))
|
||||
} else {
|
||||
toWrite = []byte(commit.CommitMessage)
|
||||
}
|
||||
|
||||
if len(toWrite) > maxSize-stringBuilder.Len() && maxSize > -1 {
|
||||
toWrite = append(toWrite[:maxSize-stringBuilder.Len()], "..."...)
|
||||
}
|
||||
if _, err := stringBuilder.Write(toWrite); err != nil {
|
||||
log.Error("Unable to write commit message Error: %v", err)
|
||||
return ""
|
||||
}
|
||||
|
||||
if _, err := stringBuilder.WriteRune('\n'); err != nil {
|
||||
log.Error("Unable to write commit message Error: %v", err)
|
||||
return ""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// collect co-authors
|
||||
for _, commit := range commits {
|
||||
authorString := commit.Author.String()
|
||||
if uniqueAuthors.Add(authorString) && authorString != posterSig {
|
||||
// Compare use account as well to avoid adding the same author multiple times
|
||||
// times when email addresses are private or multiple emails are used.
|
||||
// when email addresses are private or multiple emails are used.
|
||||
commitUser, _ := user_model.GetUserByEmail(ctx, commit.Author.Email)
|
||||
if commitUser == nil || commitUser.ID != pr.Issue.Poster.ID {
|
||||
authors = append(authors, authorString)
|
||||
@@ -890,12 +893,12 @@ func GetSquashMergeCommitMessages(ctx context.Context, pr *issues_model.PullRequ
|
||||
}
|
||||
}
|
||||
|
||||
// Consider collecting the remaining authors
|
||||
// collect the remaining authors
|
||||
if limit >= 0 && setting.Repository.PullRequest.DefaultMergeMessageAllAuthors {
|
||||
skip := limit
|
||||
limit = 30
|
||||
for {
|
||||
commits, err := gitRepo.CommitsBetweenLimit(headCommit, mergeBase, limit, skip)
|
||||
commits, err = gitRepo.CommitsBetweenLimit(headCommit, mergeBase, limit, skip)
|
||||
if err != nil {
|
||||
log.Error("Unable to get commits between: %s %s Error: %v", pr.HeadBranch, pr.MergeBase, err)
|
||||
return ""
|
||||
@@ -916,19 +919,15 @@ func GetSquashMergeCommitMessages(ctx context.Context, pr *issues_model.PullRequ
|
||||
}
|
||||
}
|
||||
|
||||
if stringBuilder.Len() > 0 && len(authors) > 0 {
|
||||
// TODO: this separator line doesn't work with the trailer check (commitMessageTrailersPattern) above
|
||||
stringBuilder.WriteString("---------\n\n")
|
||||
}
|
||||
|
||||
for _, author := range authors {
|
||||
if _, err := stringBuilder.WriteString("Co-authored-by: "); err != nil {
|
||||
log.Error("Unable to write to string builder Error: %v", err)
|
||||
return ""
|
||||
}
|
||||
if _, err := stringBuilder.WriteString(author); err != nil {
|
||||
log.Error("Unable to write to string builder Error: %v", err)
|
||||
return ""
|
||||
}
|
||||
if _, err := stringBuilder.WriteRune('\n'); err != nil {
|
||||
log.Error("Unable to write to string builder Error: %v", err)
|
||||
return ""
|
||||
}
|
||||
stringBuilder.WriteString("Co-authored-by: ")
|
||||
stringBuilder.WriteString(author)
|
||||
stringBuilder.WriteRune('\n')
|
||||
}
|
||||
|
||||
return stringBuilder.String()
|
||||
|
||||
@@ -101,11 +101,11 @@ func Update(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.
|
||||
}
|
||||
|
||||
// IsUserAllowedToUpdate check if user is allowed to update PR with given permissions and branch protections
|
||||
// update PR means send new commits to PR head branch from base branch
|
||||
func IsUserAllowedToUpdate(ctx context.Context, pull *issues_model.PullRequest, user *user_model.User) (mergeAllowed, rebaseAllowed bool, err error) {
|
||||
if pull.Flow == issues_model.PullRequestFlowAGit {
|
||||
return false, false, nil
|
||||
}
|
||||
|
||||
if user == nil {
|
||||
return false, false, nil
|
||||
}
|
||||
@@ -121,54 +121,46 @@ func IsUserAllowedToUpdate(ctx context.Context, pull *issues_model.PullRequest,
|
||||
return false, false, err
|
||||
}
|
||||
|
||||
pr := &issues_model.PullRequest{
|
||||
HeadRepoID: pull.BaseRepoID,
|
||||
HeadRepo: pull.BaseRepo,
|
||||
BaseRepoID: pull.HeadRepoID,
|
||||
BaseRepo: pull.HeadRepo,
|
||||
HeadBranch: pull.BaseBranch,
|
||||
BaseBranch: pull.HeadBranch,
|
||||
}
|
||||
|
||||
pb, err := git_model.GetFirstMatchProtectedBranchRule(ctx, pr.BaseRepoID, pr.BaseBranch)
|
||||
if err != nil {
|
||||
return false, false, err
|
||||
}
|
||||
|
||||
if err := pr.LoadBaseRepo(ctx); err != nil {
|
||||
return false, false, err
|
||||
}
|
||||
prUnit, err := pr.BaseRepo.GetUnit(ctx, unit.TypePullRequests)
|
||||
if err != nil {
|
||||
// 1. check base repository's AllowRebaseUpdate configuration
|
||||
// it is a config in base repo but controls the head (fork) repo's "Update" behavior
|
||||
{
|
||||
prBaseUnit, err := pull.BaseRepo.GetUnit(ctx, unit.TypePullRequests)
|
||||
if repo_model.IsErrUnitTypeNotExist(err) {
|
||||
return false, false, nil
|
||||
return false, false, nil // the PR unit is disabled in base repo
|
||||
} else if err != nil {
|
||||
return false, false, fmt.Errorf("get base repo unit: %v", err)
|
||||
}
|
||||
log.Error("pr.BaseRepo.GetUnit(unit.TypePullRequests): %v", err)
|
||||
return false, false, err
|
||||
rebaseAllowed = prBaseUnit.PullRequestsConfig().AllowRebaseUpdate
|
||||
}
|
||||
|
||||
rebaseAllowed = prUnit.PullRequestsConfig().AllowRebaseUpdate
|
||||
|
||||
// If branch protected, disable rebase unless user is whitelisted to force push (which extends regular push)
|
||||
if pb != nil {
|
||||
pb.Repo = pull.BaseRepo
|
||||
if !pb.CanUserForcePush(ctx, user) {
|
||||
rebaseAllowed = false
|
||||
// 2. check head branch protection whether rebase is allowed, if pb not found then rebase depends on the above setting
|
||||
{
|
||||
pb, err := git_model.GetFirstMatchProtectedBranchRule(ctx, pull.HeadRepoID, pull.HeadBranch)
|
||||
if err != nil {
|
||||
return false, false, err
|
||||
}
|
||||
// If branch protected, disable rebase unless user is whitelisted to force push (which extends regular push)
|
||||
if pb != nil {
|
||||
pb.Repo = pull.HeadRepo
|
||||
rebaseAllowed = rebaseAllowed && pb.CanUserForcePush(ctx, user)
|
||||
}
|
||||
}
|
||||
|
||||
// 3. check whether user has write access to head branch
|
||||
baseRepoPerm, err := access_model.GetUserRepoPermission(ctx, pull.BaseRepo, user)
|
||||
if err != nil {
|
||||
return false, false, err
|
||||
}
|
||||
|
||||
mergeAllowed, err = IsUserAllowedToMerge(ctx, pr, headRepoPerm, user)
|
||||
mergeAllowed, err = isUserAllowedToMergeInRepoBranch(ctx, pull.HeadRepoID, pull.HeadBranch, headRepoPerm, user)
|
||||
if err != nil {
|
||||
return false, false, err
|
||||
}
|
||||
|
||||
// 4. if the pull creator allows maintainer to edit, it means the write permissions of the head branch has been
|
||||
// granted to the user with write permission of the base repository
|
||||
if pull.AllowMaintainerEdit {
|
||||
mergeAllowedMaintainer, err := IsUserAllowedToMerge(ctx, pr, baseRepoPerm, user)
|
||||
mergeAllowedMaintainer, err := isUserAllowedToMergeInRepoBranch(ctx, pull.BaseRepoID, pull.BaseBranch, baseRepoPerm, user)
|
||||
if err != nil {
|
||||
return false, false, err
|
||||
}
|
||||
@@ -176,6 +168,9 @@ func IsUserAllowedToUpdate(ctx context.Context, pull *issues_model.PullRequest,
|
||||
mergeAllowed = mergeAllowed || mergeAllowedMaintainer
|
||||
}
|
||||
|
||||
// if merge is not allowed, rebase is also not allowed
|
||||
rebaseAllowed = rebaseAllowed && mergeAllowed
|
||||
|
||||
return mergeAllowed, rebaseAllowed, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -361,7 +361,7 @@ func DeleteReleaseByID(ctx context.Context, repo *repo_model.Repository, rel *re
|
||||
if err != nil {
|
||||
return fmt.Errorf("GetProtectedTags: %w", err)
|
||||
}
|
||||
isAllowed, err := git_model.IsUserAllowedToControlTag(ctx, protectedTags, rel.TagName, rel.PublisherID)
|
||||
isAllowed, err := git_model.IsUserAllowedToControlTag(ctx, protectedTags, rel.TagName, doer.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
32
tests/integration/api_auth_test.go
Normal file
32
tests/integration/api_auth_test.go
Normal file
@@ -0,0 +1,32 @@
|
||||
// Copyright 2025 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package integration
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"code.gitea.io/gitea/tests"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestAPIAuth(t *testing.T) {
|
||||
defer tests.PrepareTestEnv(t)()
|
||||
|
||||
req := NewRequestf(t, "GET", "/api/v1/user").AddBasicAuth("user2")
|
||||
MakeRequest(t, req, http.StatusOK)
|
||||
|
||||
req = NewRequestf(t, "GET", "/api/v1/user").AddBasicAuth("user2", "wrong-password")
|
||||
resp := MakeRequest(t, req, http.StatusUnauthorized)
|
||||
assert.Contains(t, resp.Body.String(), `{"message":"invalid username, password or token"`)
|
||||
|
||||
req = NewRequestf(t, "GET", "/api/v1/user").AddBasicAuth("user-not-exist")
|
||||
resp = MakeRequest(t, req, http.StatusUnauthorized)
|
||||
assert.Contains(t, resp.Body.String(), `{"message":"invalid username, password or token"`)
|
||||
|
||||
req = NewRequestf(t, "GET", "/api/v1/users/user2/repos").AddTokenAuth("Bearer wrong_token")
|
||||
resp = MakeRequest(t, req, http.StatusUnauthorized)
|
||||
assert.Contains(t, resp.Body.String(), `{"message":"invalid username, password or token"`)
|
||||
}
|
||||
152
tests/integration/api_issue_dependency_test.go
Normal file
152
tests/integration/api_issue_dependency_test.go
Normal file
@@ -0,0 +1,152 @@
|
||||
// Copyright 2024 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package integration
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
auth_model "code.gitea.io/gitea/models/auth"
|
||||
"code.gitea.io/gitea/models/db"
|
||||
issues_model "code.gitea.io/gitea/models/issues"
|
||||
"code.gitea.io/gitea/models/perm"
|
||||
access_model "code.gitea.io/gitea/models/perm/access"
|
||||
repo_model "code.gitea.io/gitea/models/repo"
|
||||
"code.gitea.io/gitea/models/unit"
|
||||
"code.gitea.io/gitea/models/unittest"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
api "code.gitea.io/gitea/modules/structs"
|
||||
repo_service "code.gitea.io/gitea/services/repository"
|
||||
"code.gitea.io/gitea/tests"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func enableRepoDependencies(t *testing.T, repoID int64) {
|
||||
t.Helper()
|
||||
|
||||
repoUnit := unittest.AssertExistsAndLoadBean(t, &repo_model.RepoUnit{RepoID: repoID, Type: unit.TypeIssues})
|
||||
repoUnit.IssuesConfig().EnableDependencies = true
|
||||
assert.NoError(t, repo_model.UpdateRepoUnit(t.Context(), repoUnit))
|
||||
}
|
||||
|
||||
func TestAPICreateIssueDependencyCrossRepoPermission(t *testing.T) {
|
||||
defer tests.PrepareTestEnv(t)()
|
||||
|
||||
targetRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||
targetIssue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{RepoID: targetRepo.ID, Index: 1})
|
||||
dependencyRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3})
|
||||
assert.True(t, dependencyRepo.IsPrivate)
|
||||
dependencyIssue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{RepoID: dependencyRepo.ID, Index: 1})
|
||||
|
||||
enableRepoDependencies(t, targetIssue.RepoID)
|
||||
enableRepoDependencies(t, dependencyRepo.ID)
|
||||
|
||||
// remove user 40 access from target repository
|
||||
_, err := db.DeleteByID[access_model.Access](t.Context(), 30)
|
||||
assert.NoError(t, err)
|
||||
|
||||
url := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/dependencies", "user2", "repo1", targetIssue.Index)
|
||||
dependencyMeta := &api.IssueMeta{
|
||||
Owner: "org3",
|
||||
Name: "repo3",
|
||||
Index: dependencyIssue.Index,
|
||||
}
|
||||
|
||||
user40 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 40})
|
||||
// user40 has no access to both target issue and dependency issue
|
||||
writerToken := getUserToken(t, "user40", auth_model.AccessTokenScopeWriteIssue)
|
||||
req := NewRequestWithJSON(t, "POST", url, dependencyMeta).
|
||||
AddTokenAuth(writerToken)
|
||||
MakeRequest(t, req, http.StatusNotFound)
|
||||
unittest.AssertNotExistsBean(t, &issues_model.IssueDependency{
|
||||
IssueID: targetIssue.ID,
|
||||
DependencyID: dependencyIssue.ID,
|
||||
})
|
||||
|
||||
// add user40 as a collaborator to dependency repository with read permission
|
||||
assert.NoError(t, repo_service.AddOrUpdateCollaborator(t.Context(), dependencyRepo, user40, perm.AccessModeRead))
|
||||
|
||||
// try again after getting read permission to dependency repository
|
||||
req = NewRequestWithJSON(t, "POST", url, dependencyMeta).
|
||||
AddTokenAuth(writerToken)
|
||||
MakeRequest(t, req, http.StatusNotFound)
|
||||
unittest.AssertNotExistsBean(t, &issues_model.IssueDependency{
|
||||
IssueID: targetIssue.ID,
|
||||
DependencyID: dependencyIssue.ID,
|
||||
})
|
||||
|
||||
// add user40 as a collaborator to target repository with write permission
|
||||
assert.NoError(t, repo_service.AddOrUpdateCollaborator(t.Context(), targetRepo, user40, perm.AccessModeWrite))
|
||||
|
||||
req = NewRequestWithJSON(t, "POST", url, dependencyMeta).
|
||||
AddTokenAuth(writerToken)
|
||||
MakeRequest(t, req, http.StatusCreated)
|
||||
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueDependency{
|
||||
IssueID: targetIssue.ID,
|
||||
DependencyID: dependencyIssue.ID,
|
||||
})
|
||||
}
|
||||
|
||||
func TestAPIDeleteIssueDependencyCrossRepoPermission(t *testing.T) {
|
||||
defer tests.PrepareTestEnv(t)()
|
||||
|
||||
targetRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||
targetIssue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{RepoID: targetRepo.ID, Index: 1})
|
||||
dependencyRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3})
|
||||
assert.True(t, dependencyRepo.IsPrivate)
|
||||
dependencyIssue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{RepoID: dependencyRepo.ID, Index: 1})
|
||||
|
||||
enableRepoDependencies(t, targetIssue.RepoID)
|
||||
enableRepoDependencies(t, dependencyRepo.ID)
|
||||
|
||||
user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
|
||||
assert.NoError(t, issues_model.CreateIssueDependency(t.Context(), user1, targetIssue, dependencyIssue))
|
||||
|
||||
// remove user 40 access from target repository
|
||||
_, err := db.DeleteByID[access_model.Access](t.Context(), 30)
|
||||
assert.NoError(t, err)
|
||||
|
||||
url := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/dependencies", "user2", "repo1", targetIssue.Index)
|
||||
dependencyMeta := &api.IssueMeta{
|
||||
Owner: "org3",
|
||||
Name: "repo3",
|
||||
Index: dependencyIssue.Index,
|
||||
}
|
||||
|
||||
user40 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 40})
|
||||
// user40 has no access to both target issue and dependency issue
|
||||
writerToken := getUserToken(t, "user40", auth_model.AccessTokenScopeWriteIssue)
|
||||
req := NewRequestWithJSON(t, "DELETE", url, dependencyMeta).
|
||||
AddTokenAuth(writerToken)
|
||||
MakeRequest(t, req, http.StatusNotFound)
|
||||
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueDependency{
|
||||
IssueID: targetIssue.ID,
|
||||
DependencyID: dependencyIssue.ID,
|
||||
})
|
||||
|
||||
// add user40 as a collaborator to dependency repository with read permission
|
||||
assert.NoError(t, repo_service.AddOrUpdateCollaborator(t.Context(), dependencyRepo, user40, perm.AccessModeRead))
|
||||
|
||||
// try again after getting read permission to dependency repository
|
||||
req = NewRequestWithJSON(t, "DELETE", url, dependencyMeta).
|
||||
AddTokenAuth(writerToken)
|
||||
MakeRequest(t, req, http.StatusNotFound)
|
||||
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueDependency{
|
||||
IssueID: targetIssue.ID,
|
||||
DependencyID: dependencyIssue.ID,
|
||||
})
|
||||
|
||||
// add user40 as a collaborator to target repository with write permission
|
||||
assert.NoError(t, repo_service.AddOrUpdateCollaborator(t.Context(), targetRepo, user40, perm.AccessModeWrite))
|
||||
|
||||
req = NewRequestWithJSON(t, "DELETE", url, dependencyMeta).
|
||||
AddTokenAuth(writerToken)
|
||||
MakeRequest(t, req, http.StatusCreated)
|
||||
unittest.AssertNotExistsBean(t, &issues_model.IssueDependency{
|
||||
IssueID: targetIssue.ID,
|
||||
DependencyID: dependencyIssue.ID,
|
||||
})
|
||||
}
|
||||
@@ -15,6 +15,8 @@ import (
|
||||
"testing"
|
||||
|
||||
auth_model "code.gitea.io/gitea/models/auth"
|
||||
"code.gitea.io/gitea/models/db"
|
||||
access_model "code.gitea.io/gitea/models/perm/access"
|
||||
repo_model "code.gitea.io/gitea/models/repo"
|
||||
"code.gitea.io/gitea/models/unittest"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
@@ -269,6 +271,42 @@ func TestAPIGetReleaseByTag(t *testing.T) {
|
||||
assert.NotEmpty(t, err.Message)
|
||||
}
|
||||
|
||||
func TestAPIGetDraftReleaseByTag(t *testing.T) {
|
||||
defer tests.PrepareTestEnv(t)()
|
||||
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID})
|
||||
|
||||
tag := "draft-release"
|
||||
// anonymous should not be able to get draft release
|
||||
req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/%s", owner.Name, repo.Name, tag))
|
||||
MakeRequest(t, req, http.StatusNotFound)
|
||||
|
||||
// user 40 should be able to get draft release because he has write access to the repository
|
||||
token := getUserToken(t, "user40", auth_model.AccessTokenScopeReadRepository)
|
||||
req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/%s", owner.Name, repo.Name, tag)).AddTokenAuth(token)
|
||||
resp := MakeRequest(t, req, http.StatusOK)
|
||||
release := api.Release{}
|
||||
DecodeJSON(t, resp, &release)
|
||||
assert.Equal(t, "draft-release", release.Title)
|
||||
|
||||
// remove user 40 access from the repository
|
||||
_, err := db.DeleteByID[access_model.Access](t.Context(), 30)
|
||||
assert.NoError(t, err)
|
||||
|
||||
// user 40 should not be able to get draft release
|
||||
req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/%s", owner.Name, repo.Name, tag)).AddTokenAuth(token)
|
||||
MakeRequest(t, req, http.StatusNotFound)
|
||||
|
||||
// user 2 should be able to get draft release because he is the publisher
|
||||
user2Token := getUserToken(t, "user2", auth_model.AccessTokenScopeReadRepository)
|
||||
req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/%s", owner.Name, repo.Name, tag)).AddTokenAuth(user2Token)
|
||||
resp = MakeRequest(t, req, http.StatusOK)
|
||||
release = api.Release{}
|
||||
DecodeJSON(t, resp, &release)
|
||||
assert.Equal(t, "draft-release", release.Title)
|
||||
}
|
||||
|
||||
func TestAPIDeleteReleaseByTagName(t *testing.T) {
|
||||
defer tests.PrepareTestEnv(t)()
|
||||
|
||||
|
||||
@@ -19,6 +19,9 @@ import (
|
||||
|
||||
type createFileInBranchOptions struct {
|
||||
OldBranch, NewBranch string
|
||||
CommitMessage string
|
||||
CommitterName string
|
||||
CommitterEmail string
|
||||
}
|
||||
|
||||
func testCreateFileInBranch(t *testing.T, user *user_model.User, repo *repo_model.Repository, createOpts createFileInBranchOptions, files map[string]string) *api.FilesResponse {
|
||||
@@ -29,7 +32,17 @@ func testCreateFileInBranch(t *testing.T, user *user_model.User, repo *repo_mode
|
||||
|
||||
func createFileInBranch(user *user_model.User, repo *repo_model.Repository, createOpts createFileInBranchOptions, files map[string]string) (*api.FilesResponse, error) {
|
||||
ctx := context.TODO()
|
||||
opts := &files_service.ChangeRepoFilesOptions{OldBranch: createOpts.OldBranch, NewBranch: createOpts.NewBranch}
|
||||
opts := &files_service.ChangeRepoFilesOptions{
|
||||
OldBranch: createOpts.OldBranch,
|
||||
NewBranch: createOpts.NewBranch,
|
||||
Message: createOpts.CommitMessage,
|
||||
}
|
||||
if createOpts.CommitterName != "" || createOpts.CommitterEmail != "" {
|
||||
opts.Committer = &files_service.IdentityOptions{
|
||||
GitUserName: createOpts.CommitterName,
|
||||
GitUserEmail: createOpts.CommitterEmail,
|
||||
}
|
||||
}
|
||||
for path, content := range files {
|
||||
opts.Files = append(opts.Files, &files_service.ChangeRepoFile{
|
||||
Operation: "create",
|
||||
|
||||
@@ -41,17 +41,6 @@ func TestAPIUserReposNotLogin(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIUserReposWithWrongToken(t *testing.T) {
|
||||
defer tests.PrepareTestEnv(t)()
|
||||
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
wrongToken := "Bearer " + "wrong_token"
|
||||
req := NewRequestf(t, "GET", "/api/v1/users/%s/repos", user.Name).
|
||||
AddTokenAuth(wrongToken)
|
||||
resp := MakeRequest(t, req, http.StatusUnauthorized)
|
||||
|
||||
assert.Contains(t, resp.Body.String(), "user does not exist")
|
||||
}
|
||||
|
||||
func TestAPISearchRepo(t *testing.T) {
|
||||
defer tests.PrepareTestEnv(t)()
|
||||
const keyword = "test"
|
||||
|
||||
@@ -271,8 +271,8 @@ type RequestWrapper struct {
|
||||
*http.Request
|
||||
}
|
||||
|
||||
func (req *RequestWrapper) AddBasicAuth(username string) *RequestWrapper {
|
||||
req.Request.SetBasicAuth(username, userPassword)
|
||||
func (req *RequestWrapper) AddBasicAuth(username string, password ...string) *RequestWrapper {
|
||||
req.Request.SetBasicAuth(username, util.OptionalArg(password, userPassword))
|
||||
return req
|
||||
}
|
||||
|
||||
|
||||
@@ -33,6 +33,7 @@ import (
|
||||
api "code.gitea.io/gitea/modules/structs"
|
||||
"code.gitea.io/gitea/modules/test"
|
||||
"code.gitea.io/gitea/modules/translation"
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
"code.gitea.io/gitea/services/automerge"
|
||||
"code.gitea.io/gitea/services/automergequeue"
|
||||
pull_service "code.gitea.io/gitea/services/pull"
|
||||
@@ -41,6 +42,7 @@ import (
|
||||
files_service "code.gitea.io/gitea/services/repository/files"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type MergeOptions struct {
|
||||
@@ -1180,3 +1182,172 @@ func TestPullNonMergeForAdminWithBranchProtection(t *testing.T) {
|
||||
session.MakeRequest(t, mergeReq, http.StatusMethodNotAllowed)
|
||||
})
|
||||
}
|
||||
|
||||
func TestPullSquashMergeEmpty(t *testing.T) {
|
||||
onGiteaRun(t, func(t *testing.T, u *url.URL) {
|
||||
session := loginUser(t, "user1")
|
||||
testEditFileToNewBranch(t, session, "user2", "repo1", "master", "pr-squash-empty", "README.md", "Hello, World (Edited)\n")
|
||||
resp := testPullCreate(t, session, "user2", "repo1", false, "master", "pr-squash-empty", "This is a pull title")
|
||||
|
||||
elem := strings.Split(test.RedirectURL(resp), "/")
|
||||
assert.Equal(t, "pulls", elem[3])
|
||||
|
||||
httpContext := NewAPITestContext(t, "user2", "repo1", auth_model.AccessTokenScopeWriteRepository)
|
||||
dstPath := t.TempDir()
|
||||
|
||||
u.Path = httpContext.GitPath()
|
||||
u.User = url.UserPassword("user2", userPassword)
|
||||
|
||||
t.Run("Clone", doGitClone(dstPath, u))
|
||||
doGitCheckoutBranch(dstPath, "-b", "pr-squash-empty", "remotes/origin/pr-squash-empty")(t)
|
||||
doGitCheckoutBranch(dstPath, "master")(t)
|
||||
_, _, err := gitcmd.NewCommand("cherry-pick").AddArguments("pr-squash-empty").
|
||||
WithDir(dstPath).
|
||||
RunStdString(t.Context())
|
||||
assert.NoError(t, err)
|
||||
|
||||
doGitPushTestRepository(dstPath)(t)
|
||||
|
||||
testPullMerge(t, session, elem[1], elem[2], elem[4], MergeOptions{
|
||||
Style: repo_model.MergeStyleSquash,
|
||||
DeleteBranch: false,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
func TestPullSquashMessage(t *testing.T) {
|
||||
onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
|
||||
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
user2Session := loginUser(t, user2.Name)
|
||||
|
||||
defer test.MockVariableValue(&setting.Repository.PullRequest.PopulateSquashCommentWithCommitMessages, true)()
|
||||
defer test.MockVariableValue(&setting.Repository.PullRequest.DefaultMergeMessageSize, 80)()
|
||||
|
||||
repo, err := repo_service.CreateRepository(t.Context(), user2, user2, repo_service.CreateRepoOptions{
|
||||
Name: "squash-message-test",
|
||||
Description: "Test squash message",
|
||||
AutoInit: true,
|
||||
Readme: "Default",
|
||||
DefaultBranch: "main",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
type commitInfo struct {
|
||||
userName string
|
||||
commitMessage string
|
||||
}
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
commitInfos []*commitInfo
|
||||
expectedMessage string
|
||||
}{
|
||||
{
|
||||
name: "Single-line messages",
|
||||
commitInfos: []*commitInfo{
|
||||
{
|
||||
userName: user2.Name,
|
||||
commitMessage: "commit msg 1",
|
||||
},
|
||||
{
|
||||
userName: user2.Name,
|
||||
commitMessage: "commit msg 2",
|
||||
},
|
||||
},
|
||||
expectedMessage: `* commit msg 1
|
||||
|
||||
* commit msg 2
|
||||
|
||||
`,
|
||||
},
|
||||
{
|
||||
name: "Multiple-line messages",
|
||||
commitInfos: []*commitInfo{
|
||||
{
|
||||
userName: user2.Name,
|
||||
commitMessage: `commit msg 1
|
||||
|
||||
Commit description.`,
|
||||
},
|
||||
{
|
||||
userName: user2.Name,
|
||||
commitMessage: `commit msg 2
|
||||
|
||||
- Detail 1
|
||||
- Detail 2`,
|
||||
},
|
||||
},
|
||||
expectedMessage: `* commit msg 1
|
||||
|
||||
Commit description.
|
||||
|
||||
* commit msg 2
|
||||
|
||||
- Detail 1
|
||||
- Detail 2
|
||||
|
||||
`,
|
||||
},
|
||||
{
|
||||
name: "Too long message",
|
||||
commitInfos: []*commitInfo{
|
||||
{
|
||||
userName: user2.Name,
|
||||
commitMessage: `loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong message`,
|
||||
},
|
||||
},
|
||||
expectedMessage: `* looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo...`,
|
||||
},
|
||||
{
|
||||
name: "Test Co-authored-by",
|
||||
commitInfos: []*commitInfo{
|
||||
{
|
||||
userName: user2.Name,
|
||||
commitMessage: "commit msg 1",
|
||||
},
|
||||
{
|
||||
userName: "user4",
|
||||
commitMessage: "commit msg 2",
|
||||
},
|
||||
},
|
||||
expectedMessage: `* commit msg 1
|
||||
|
||||
* commit msg 2
|
||||
|
||||
---------
|
||||
|
||||
Co-authored-by: user4 <user4@example.com>
|
||||
`,
|
||||
},
|
||||
}
|
||||
|
||||
for tcNum, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
branchName := "test-branch-" + strconv.Itoa(tcNum)
|
||||
for infoIdx, info := range tc.commitInfos {
|
||||
createFileOpts := createFileInBranchOptions{
|
||||
CommitMessage: info.commitMessage,
|
||||
CommitterName: info.userName,
|
||||
CommitterEmail: util.Iif(info.userName != "", info.userName+"@example.com", ""),
|
||||
OldBranch: util.Iif(infoIdx == 0, "main", branchName),
|
||||
NewBranch: branchName,
|
||||
}
|
||||
testCreateFileInBranch(t, user2, repo, createFileOpts, map[string]string{"dummy-file-" + strconv.Itoa(infoIdx): "dummy content"})
|
||||
}
|
||||
resp := testPullCreateDirectly(t, user2Session, createPullRequestOptions{
|
||||
BaseRepoOwner: user2.Name,
|
||||
BaseRepoName: repo.Name,
|
||||
BaseBranch: repo.DefaultBranch,
|
||||
HeadBranch: branchName,
|
||||
Title: "Pull for " + branchName,
|
||||
})
|
||||
elems := strings.Split(test.RedirectURL(resp), "/")
|
||||
pullIndex, err := strconv.ParseInt(elems[4], 10, 64)
|
||||
assert.NoError(t, err)
|
||||
pullRequest := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{BaseRepoID: repo.ID, Index: pullIndex})
|
||||
squashMergeCommitMessage := pull_service.GetSquashMergeCommitMessages(t.Context(), pullRequest)
|
||||
assert.Equal(t, tc.expectedMessage, squashMergeCommitMessage)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -11,7 +11,11 @@ import (
|
||||
"time"
|
||||
|
||||
auth_model "code.gitea.io/gitea/models/auth"
|
||||
git_model "code.gitea.io/gitea/models/git"
|
||||
issues_model "code.gitea.io/gitea/models/issues"
|
||||
"code.gitea.io/gitea/models/perm"
|
||||
repo_model "code.gitea.io/gitea/models/repo"
|
||||
"code.gitea.io/gitea/models/unit"
|
||||
"code.gitea.io/gitea/models/unittest"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
"code.gitea.io/gitea/modules/gitrepo"
|
||||
@@ -58,6 +62,14 @@ func TestAPIPullUpdate(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func enableRepoAllowUpdateWithRebase(t *testing.T, repoID int64, allow bool) {
|
||||
t.Helper()
|
||||
|
||||
repoUnit := unittest.AssertExistsAndLoadBean(t, &repo_model.RepoUnit{RepoID: repoID, Type: unit.TypePullRequests})
|
||||
repoUnit.PullRequestsConfig().AllowRebaseUpdate = allow
|
||||
assert.NoError(t, repo_model.UpdateRepoUnit(t.Context(), repoUnit))
|
||||
}
|
||||
|
||||
func TestAPIPullUpdateByRebase(t *testing.T) {
|
||||
onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
|
||||
// Create PR to test
|
||||
@@ -73,10 +85,32 @@ func TestAPIPullUpdateByRebase(t *testing.T) {
|
||||
assert.Equal(t, 1, diffCount.Ahead)
|
||||
assert.NoError(t, pr.LoadIssue(t.Context()))
|
||||
|
||||
enableRepoAllowUpdateWithRebase(t, pr.BaseRepo.ID, false)
|
||||
|
||||
session := loginUser(t, "user2")
|
||||
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository)
|
||||
req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/pulls/%d/update?style=rebase", pr.BaseRepo.OwnerName, pr.BaseRepo.Name, pr.Issue.Index).
|
||||
AddTokenAuth(token)
|
||||
session.MakeRequest(t, req, http.StatusForbidden)
|
||||
|
||||
enableRepoAllowUpdateWithRebase(t, pr.BaseRepo.ID, true)
|
||||
assert.NoError(t, pr.LoadHeadRepo(t.Context()))
|
||||
|
||||
// use a user which have write access to the pr but not write permission to the head repository to do the rebase
|
||||
user40 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 40})
|
||||
err = repo_service.AddOrUpdateCollaborator(t.Context(), pr.BaseRepo, user40, perm.AccessModeWrite)
|
||||
assert.NoError(t, err)
|
||||
token40 := getUserToken(t, "user40", auth_model.AccessTokenScopeWriteRepository)
|
||||
|
||||
req = NewRequestf(t, "POST", "/api/v1/repos/%s/%s/pulls/%d/update?style=rebase", pr.BaseRepo.OwnerName, pr.BaseRepo.Name, pr.Issue.Index).
|
||||
AddTokenAuth(token40)
|
||||
session.MakeRequest(t, req, http.StatusForbidden)
|
||||
|
||||
err = repo_service.AddOrUpdateCollaborator(t.Context(), pr.HeadRepo, user40, perm.AccessModeWrite)
|
||||
assert.NoError(t, err)
|
||||
|
||||
req = NewRequestf(t, "POST", "/api/v1/repos/%s/%s/pulls/%d/update?style=rebase", pr.BaseRepo.OwnerName, pr.BaseRepo.Name, pr.Issue.Index).
|
||||
AddTokenAuth(token40)
|
||||
session.MakeRequest(t, req, http.StatusOK)
|
||||
|
||||
// Test GetDiverging after update
|
||||
@@ -87,6 +121,49 @@ func TestAPIPullUpdateByRebase(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestAPIPullUpdateByRebase2(t *testing.T) {
|
||||
onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
|
||||
// Create PR to test
|
||||
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
org26 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 26})
|
||||
pr := createOutdatedPR(t, user, org26)
|
||||
assert.NoError(t, pr.LoadBaseRepo(t.Context()))
|
||||
assert.NoError(t, pr.LoadIssue(t.Context()))
|
||||
|
||||
enableRepoAllowUpdateWithRebase(t, pr.BaseRepo.ID, false)
|
||||
|
||||
session := loginUser(t, "user2")
|
||||
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository)
|
||||
req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/pulls/%d/update?style=rebase", pr.BaseRepo.OwnerName, pr.BaseRepo.Name, pr.Issue.Index).
|
||||
AddTokenAuth(token)
|
||||
session.MakeRequest(t, req, http.StatusForbidden)
|
||||
|
||||
enableRepoAllowUpdateWithRebase(t, pr.BaseRepo.ID, true)
|
||||
assert.NoError(t, pr.LoadHeadRepo(t.Context()))
|
||||
|
||||
// add a protected branch rule to the head branch to block rebase
|
||||
pb := git_model.ProtectedBranch{
|
||||
RepoID: pr.HeadRepo.ID,
|
||||
RuleName: pr.HeadBranch,
|
||||
CanPush: false,
|
||||
CanForcePush: false,
|
||||
}
|
||||
err := git_model.UpdateProtectBranch(t.Context(), pr.HeadRepo, &pb, git_model.WhitelistOptions{})
|
||||
assert.NoError(t, err)
|
||||
req = NewRequestf(t, "POST", "/api/v1/repos/%s/%s/pulls/%d/update?style=rebase", pr.BaseRepo.OwnerName, pr.BaseRepo.Name, pr.Issue.Index).
|
||||
AddTokenAuth(token)
|
||||
session.MakeRequest(t, req, http.StatusForbidden)
|
||||
|
||||
// remove the protected branch rule to allow rebase
|
||||
err = git_model.DeleteProtectedBranch(t.Context(), pr.HeadRepo, pb.ID)
|
||||
assert.NoError(t, err)
|
||||
|
||||
req = NewRequestf(t, "POST", "/api/v1/repos/%s/%s/pulls/%d/update?style=rebase", pr.BaseRepo.OwnerName, pr.BaseRepo.Name, pr.Issue.Index).
|
||||
AddTokenAuth(token)
|
||||
session.MakeRequest(t, req, http.StatusOK)
|
||||
})
|
||||
}
|
||||
|
||||
func createOutdatedPR(t *testing.T, actor, forkOrg *user_model.User) *issues_model.PullRequest {
|
||||
baseRepo, err := repo_service.CreateRepository(t.Context(), actor, actor, repo_service.CreateRepoOptions{
|
||||
Name: "repo-pr-update",
|
||||
|
||||
@@ -149,12 +149,18 @@ func TestRepushTag(t *testing.T) {
|
||||
// delete the tag
|
||||
_, _, err = gitcmd.NewCommand("push", "origin", "--delete", "v2.0").WithDir(dstPath).RunStdString(t.Context())
|
||||
assert.NoError(t, err)
|
||||
// query the release by API and it should be a draft
|
||||
|
||||
// query the release by API with no auth and it should be 404
|
||||
req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/%s", owner.Name, repo.Name, "v2.0"))
|
||||
MakeRequest(t, req, http.StatusNotFound)
|
||||
|
||||
// query the release by API and it should be a draft
|
||||
req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/%s", owner.Name, repo.Name, "v2.0")).AddTokenAuth(token)
|
||||
resp := MakeRequest(t, req, http.StatusOK)
|
||||
var respRelease *api.Release
|
||||
DecodeJSON(t, resp, &respRelease)
|
||||
assert.True(t, respRelease.IsDraft)
|
||||
|
||||
// re-push the tag
|
||||
_, _, err = gitcmd.NewCommand("push", "origin", "--tags", "v2.0").WithDir(dstPath).RunStdString(t.Context())
|
||||
assert.NoError(t, err)
|
||||
|
||||
Reference in New Issue
Block a user