Merge branch 'main' into feature/bots

This commit is contained in:
Jason Song
2023-01-03 09:43:23 +08:00
committed by GitHub
105 changed files with 1084 additions and 631 deletions
+8 -3
View File
@@ -64,11 +64,16 @@ func (key *GPGKey) AfterLoad(session *xorm.Session) {
// PaddedKeyID show KeyID padded to 16 characters
func (key *GPGKey) PaddedKeyID() string {
if len(key.KeyID) > 15 {
return key.KeyID
return PaddedKeyID(key.KeyID)
}
// PaddedKeyID show KeyID padded to 16 characters
func PaddedKeyID(keyID string) string {
if len(keyID) > 15 {
return keyID
}
zeros := "0000000000000000"
return zeros[0:16-len(key.KeyID)] + key.KeyID
return zeros[0:16-len(keyID)] + keyID
}
// ListGPGKeys returns a list of public keys belongs to given user.
+2 -3
View File
@@ -5,7 +5,6 @@ package asymkey
import (
"context"
"errors"
"fmt"
"strings"
@@ -59,9 +58,9 @@ func calcFingerprintSSHKeygen(publicKeyContent string) (string, error) {
if strings.Contains(stderr, "is not a public key file") {
return "", ErrKeyUnableVerify{stderr}
}
return "", fmt.Errorf("'ssh-keygen -lf %s' failed with error '%s': %s", tmpPath, err, stderr)
return "", util.NewInvalidArgumentErrorf("'ssh-keygen -lf %s' failed with error '%s': %s", tmpPath, err, stderr)
} else if len(stdout) < 2 {
return "", errors.New("not enough output for calculating fingerprint: " + stdout)
return "", util.NewInvalidArgumentErrorf("not enough output for calculating fingerprint: %s", stdout)
}
return strings.Split(stdout, " ")[1], nil
}
+2 -3
View File
@@ -10,7 +10,6 @@ import (
"encoding/base64"
"encoding/binary"
"encoding/pem"
"errors"
"fmt"
"math/big"
"os"
@@ -122,7 +121,7 @@ func parseKeyString(content string) (string, error) {
parts := strings.SplitN(content, " ", 3)
switch len(parts) {
case 0:
return "", errors.New("empty key")
return "", util.NewInvalidArgumentErrorf("empty key")
case 1:
keyContent = parts[0]
case 2:
@@ -167,7 +166,7 @@ func CheckPublicKeyString(content string) (_ string, err error) {
content = strings.TrimRight(content, "\n\r")
if strings.ContainsAny(content, "\n\r") {
return "", errors.New("only a single line with a single key please")
return "", util.NewInvalidArgumentErrorf("only a single line with a single key please")
}
// remove any unnecessary whitespace now
+2 -2
View File
@@ -4,7 +4,6 @@
package asymkey
import (
"errors"
"fmt"
"strings"
@@ -12,6 +11,7 @@ import (
"code.gitea.io/gitea/models/perm"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/util"
)
// __________ .__ .__ .__
@@ -70,7 +70,7 @@ func CheckPrincipalKeyString(user *user_model.User, content string) (_ string, e
content = strings.TrimSpace(content)
if strings.ContainsAny(content, "\r\n") {
return "", errors.New("only a single line with a single principal please")
return "", util.NewInvalidArgumentErrorf("only a single line with a single principal please")
}
// check all the allowed principals, email, username or anything
+2 -5
View File
@@ -153,8 +153,7 @@ func generateEmailAvatarLink(email string, size int, final bool) string {
return DefaultAvatarLink()
}
enableFederatedAvatarSetting, _ := system_model.GetSetting(system_model.KeyPictureEnableFederatedAvatar)
enableFederatedAvatar := enableFederatedAvatarSetting.GetValueBool()
enableFederatedAvatar := system_model.GetSettingBool(system_model.KeyPictureEnableFederatedAvatar)
var err error
if enableFederatedAvatar && system_model.LibravatarService != nil {
@@ -175,9 +174,7 @@ func generateEmailAvatarLink(email string, size int, final bool) string {
return urlStr
}
disableGravatarSetting, _ := system_model.GetSetting(system_model.KeyPictureDisableGravatar)
disableGravatar := disableGravatarSetting.GetValueBool()
disableGravatar := system_model.GetSettingBool(system_model.KeyPictureDisableGravatar)
if !disableGravatar {
// copy GravatarSourceURL, because we will modify its Path.
avatarURLCopy := *system_model.GravatarSourceURL
+4 -1
View File
@@ -188,7 +188,10 @@ func EstimateCount(ctx context.Context, bean interface{}) (int64, error) {
case schemas.MYSQL:
_, err = e.Context(ctx).SQL("SELECT table_rows FROM information_schema.tables WHERE tables.table_name = ? AND tables.table_schema = ?;", tablename, x.Dialect().URI().DBName).Get(&rows)
case schemas.POSTGRES:
_, err = e.Context(ctx).SQL("SELECT reltuples AS estimate FROM pg_class WHERE relname = ?;", tablename).Get(&rows)
// the table can live in multiple schemas of a postgres database
// See https://wiki.postgresql.org/wiki/Count_estimate
tablename = x.TableName(bean, true)
_, err = e.Context(ctx).SQL("SELECT reltuples::bigint AS estimate FROM pg_class WHERE oid = ?::regclass;", tablename).Get(&rows)
case schemas.MSSQL:
_, err = e.Context(ctx).SQL("sp_spaceused ?;", tablename).Get(&rows)
default:
+3 -4
View File
@@ -6,7 +6,6 @@ package v1_19 //nolint
import (
"fmt"
"code.gitea.io/gitea/models/webhook"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/secret"
"code.gitea.io/gitea/modules/setting"
@@ -56,9 +55,9 @@ func batchProcess[T any](x *xorm.Engine, buf []T, query func(limit, start int) *
func AddHeaderAuthorizationEncryptedColWebhook(x *xorm.Engine) error {
// Add the column to the table
type Webhook struct {
ID int64 `xorm:"pk autoincr"`
Type webhook.HookType `xorm:"VARCHAR(16) 'type'"`
Meta string `xorm:"TEXT"` // store hook-specific attributes
ID int64 `xorm:"pk autoincr"`
Type string `xorm:"VARCHAR(16) 'type'"`
Meta string `xorm:"TEXT"` // store hook-specific attributes
// HeaderAuthorizationEncrypted should be accessed using HeaderAuthorization() and SetHeaderAuthorization()
HeaderAuthorizationEncrypted string `xorm:"TEXT"`
+4 -4
View File
@@ -7,10 +7,10 @@ import (
"testing"
"code.gitea.io/gitea/models/migrations/base"
"code.gitea.io/gitea/models/webhook"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/secret"
"code.gitea.io/gitea/modules/setting"
webhook_module "code.gitea.io/gitea/modules/webhook"
"github.com/stretchr/testify/assert"
)
@@ -18,9 +18,9 @@ import (
func Test_AddHeaderAuthorizationEncryptedColWebhook(t *testing.T) {
// Create Webhook table
type Webhook struct {
ID int64 `xorm:"pk autoincr"`
Type webhook.HookType `xorm:"VARCHAR(16) 'type'"`
Meta string `xorm:"TEXT"` // store hook-specific attributes
ID int64 `xorm:"pk autoincr"`
Type webhook_module.HookType `xorm:"VARCHAR(16) 'type'"`
Meta string `xorm:"TEXT"` // store hook-specific attributes
// HeaderAuthorizationEncrypted should be accessed using HeaderAuthorization() and SetHeaderAuthorization()
HeaderAuthorizationEncrypted string `xorm:"TEXT"`
+2 -3
View File
@@ -6,7 +6,6 @@ package models
import (
"context"
"errors"
"fmt"
"strings"
@@ -235,7 +234,7 @@ func RemoveRepository(t *organization.Team, repoID int64) error {
// It's caller's responsibility to assign organization ID.
func NewTeam(t *organization.Team) (err error) {
if len(t.Name) == 0 {
return errors.New("empty team name")
return util.NewInvalidArgumentErrorf("empty team name")
}
if err = organization.IsUsableTeamName(t.Name); err != nil {
@@ -300,7 +299,7 @@ func NewTeam(t *organization.Team) (err error) {
// UpdateTeam updates information of team.
func UpdateTeam(t *organization.Team, authChanged, includeAllChanged bool) (err error) {
if len(t.Name) == 0 {
return errors.New("empty team name")
return util.NewInvalidArgumentErrorf("empty team name")
}
if len(t.Description) > 255 {
+3 -3
View File
@@ -5,7 +5,6 @@ package conan
import (
"context"
"errors"
"strconv"
"strings"
@@ -13,13 +12,14 @@ import (
"code.gitea.io/gitea/models/packages"
conan_module "code.gitea.io/gitea/modules/packages/conan"
"code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util"
"xorm.io/builder"
)
var (
ErrRecipeReferenceNotExist = errors.New("Recipe reference does not exist")
ErrPackageReferenceNotExist = errors.New("Package reference does not exist")
ErrRecipeReferenceNotExist = util.NewNotExistErrorf("recipe reference does not exist")
ErrPackageReferenceNotExist = util.NewNotExistErrorf("package reference does not exist")
)
// RecipeExists checks if a recipe exists
+2 -2
View File
@@ -5,7 +5,6 @@ package container
import (
"context"
"errors"
"strings"
"time"
@@ -13,11 +12,12 @@ import (
"code.gitea.io/gitea/models/packages"
user_model "code.gitea.io/gitea/models/user"
container_module "code.gitea.io/gitea/modules/packages/container"
"code.gitea.io/gitea/modules/util"
"xorm.io/builder"
)
var ErrContainerBlobNotExist = errors.New("Container blob does not exist")
var ErrContainerBlobNotExist = util.NewNotExistErrorf("container blob does not exist")
type BlobSearchOptions struct {
OwnerID int64
+3 -3
View File
@@ -5,11 +5,11 @@ package packages
import (
"context"
"errors"
"fmt"
"strings"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/util"
"xorm.io/builder"
)
@@ -20,9 +20,9 @@ func init() {
var (
// ErrDuplicatePackage indicates a duplicated package error
ErrDuplicatePackage = errors.New("Package does exist already")
ErrDuplicatePackage = util.NewAlreadyExistErrorf("package already exists")
// ErrPackageNotExist indicates a package not exist error
ErrPackageNotExist = errors.New("Package does not exist")
ErrPackageNotExist = util.NewNotExistErrorf("package does not exist")
)
// Type of a package
+2 -2
View File
@@ -5,15 +5,15 @@ package packages
import (
"context"
"errors"
"time"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util"
)
// ErrPackageBlobNotExist indicates a package blob not exist error
var ErrPackageBlobNotExist = errors.New("Package blob does not exist")
var ErrPackageBlobNotExist = util.NewNotExistErrorf("package blob does not exist")
func init() {
db.RegisterModel(new(PackageBlob))
+1 -2
View File
@@ -5,7 +5,6 @@ package packages
import (
"context"
"errors"
"strings"
"time"
@@ -15,7 +14,7 @@ import (
)
// ErrPackageBlobUploadNotExist indicates a package blob upload not exist error
var ErrPackageBlobUploadNotExist = errors.New("Package blob upload does not exist")
var ErrPackageBlobUploadNotExist = util.NewNotExistErrorf("package blob upload does not exist")
func init() {
db.RegisterModel(new(PackageBlobUpload))
+2 -2
View File
@@ -5,17 +5,17 @@ package packages
import (
"context"
"errors"
"fmt"
"regexp"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util"
"xorm.io/builder"
)
var ErrPackageCleanupRuleNotExist = errors.New("Package blob does not exist")
var ErrPackageCleanupRuleNotExist = util.NewNotExistErrorf("package blob does not exist")
func init() {
db.RegisterModel(new(PackageCleanupRule))
+3 -3
View File
@@ -5,13 +5,13 @@ package packages
import (
"context"
"errors"
"strconv"
"strings"
"time"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util"
"xorm.io/builder"
)
@@ -22,9 +22,9 @@ func init() {
var (
// ErrDuplicatePackageFile indicates a duplicated package file error
ErrDuplicatePackageFile = errors.New("Package file does exist already")
ErrDuplicatePackageFile = util.NewAlreadyExistErrorf("package file already exists")
// ErrPackageFileNotExist indicates a package file not exist error
ErrPackageFileNotExist = errors.New("Package file does not exist")
ErrPackageFileNotExist = util.NewNotExistErrorf("package file does not exist")
)
// EmptyFileKey is a named constant for an empty file key
+1 -2
View File
@@ -5,7 +5,6 @@ package packages
import (
"context"
"errors"
"strconv"
"strings"
@@ -17,7 +16,7 @@ import (
)
// ErrDuplicatePackageVersion indicates a duplicated package version error
var ErrDuplicatePackageVersion = errors.New("Package version already exists")
var ErrDuplicatePackageVersion = util.NewAlreadyExistErrorf("package version already exists")
func init() {
db.RegisterModel(new(PackageVersion))
+1 -2
View File
@@ -5,7 +5,6 @@ package project
import (
"context"
"errors"
"fmt"
"code.gitea.io/gitea/models/db"
@@ -176,7 +175,7 @@ func NewProject(p *Project) error {
}
if !IsTypeValid(p.Type) {
return errors.New("project type is not valid")
return util.NewInvalidArgumentErrorf("project type is not valid")
}
ctx, committer, err := db.TxContext(db.DefaultContext)
+2 -2
View File
@@ -6,16 +6,16 @@ package repo
import (
"context"
"errors"
"time"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util"
)
// ErrMirrorNotExist mirror does not exist error
var ErrMirrorNotExist = errors.New("Mirror does not exist")
var ErrMirrorNotExist = util.NewNotExistErrorf("Mirror does not exist")
// Mirror represents mirror information of a repository.
type Mirror struct {
+3 -3
View File
@@ -5,18 +5,18 @@ package repo
import (
"context"
"errors"
"time"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util"
"xorm.io/builder"
)
// ErrPushMirrorNotExist mirror does not exist error
var ErrPushMirrorNotExist = errors.New("PushMirror does not exist")
var ErrPushMirrorNotExist = util.NewNotExistErrorf("PushMirror does not exist")
// PushMirror represents mirror information of a repository.
type PushMirror struct {
@@ -90,7 +90,7 @@ func DeletePushMirrors(ctx context.Context, opts PushMirrorOptions) error {
_, err := db.GetEngine(ctx).Where(opts.toConds()).Delete(&PushMirror{})
return err
}
return errors.New("repoID required and must be set")
return util.NewInvalidArgumentErrorf("repoID required and must be set")
}
func GetPushMirror(ctx context.Context, opts PushMirrorOptions) (*PushMirror, error) {
+1 -2
View File
@@ -6,7 +6,6 @@ package repo
import (
"context"
"errors"
"fmt"
"sort"
"strconv"
@@ -156,7 +155,7 @@ func AddReleaseAttachments(ctx context.Context, releaseID int64, attachmentUUIDs
for i := range attachments {
if attachments[i].ReleaseID != 0 {
return errors.New("release permission denied")
return util.NewPermissionDeniedErrorf("release permission denied")
}
attachments[i].ReleaseID = releaseID
// No assign value could be 0, so ignore AllCols().
+1 -2
View File
@@ -5,7 +5,6 @@ package repo
import (
"context"
"errors"
"fmt"
"strings"
@@ -708,7 +707,7 @@ func GetUserRepositories(opts *SearchRepoOptions) (RepositoryList, int64, error)
cond := builder.NewCond()
if opts.Actor == nil {
return nil, 0, errors.New("GetUserRepositories: Actor is needed but not given")
return nil, 0, util.NewInvalidArgumentErrorf("GetUserRepositories: Actor is needed but not given")
}
cond = cond.And(builder.Eq{"owner_id": opts.Actor.ID})
if !opts.Private {
+9 -8
View File
@@ -92,13 +92,13 @@ func GetSettingNoCache(key string) (*Setting, error) {
}
// GetSetting returns the setting value via the key
func GetSetting(key string) (*Setting, error) {
return cache.Get(genSettingCacheKey(key), func() (*Setting, error) {
func GetSetting(key string) (string, error) {
return cache.GetString(genSettingCacheKey(key), func() (string, error) {
res, err := GetSettingNoCache(key)
if err != nil {
return nil, err
return "", err
}
return res, nil
return res.SettingValue, nil
})
}
@@ -106,7 +106,8 @@ func GetSetting(key string) (*Setting, error) {
// none existing keys and errors are ignored and result in false
func GetSettingBool(key string) bool {
s, _ := GetSetting(key)
return s.GetValueBool()
v, _ := strconv.ParseBool(s)
return v
}
// GetSettings returns specific settings
@@ -183,8 +184,8 @@ func SetSettingNoVersion(key, value string) error {
// SetSetting updates a users' setting for a specific key
func SetSetting(setting *Setting) error {
_, err := cache.Set(genSettingCacheKey(setting.SettingKey), func() (*Setting, error) {
return setting, upsertSettingValue(strings.ToLower(setting.SettingKey), setting.SettingValue, setting.Version)
_, err := cache.GetString(genSettingCacheKey(setting.SettingKey), func() (string, error) {
return setting.SettingValue, upsertSettingValue(strings.ToLower(setting.SettingKey), setting.SettingValue, setting.Version)
})
if err != nil {
return err
@@ -266,7 +267,7 @@ func Init() error {
enableFederatedAvatar = false
}
if disableGravatar || !enableFederatedAvatar {
if enableFederatedAvatar || !disableGravatar {
var err error
GravatarSourceURL, err = url.Parse(setting.GravatarSource)
if err != nil {
+1 -1
View File
@@ -64,7 +64,7 @@ func Copy(src, dest string) error {
func CopyDir(srcPath, destPath string, filters ...func(filePath string) bool) error {
// Check if target directory exists.
if _, err := os.Stat(destPath); !errors.Is(err, os.ErrNotExist) {
return errors.New("file or directory already exists: " + destPath)
return util.NewAlreadyExistErrorf("file or directory already exists: %s", destPath)
}
err := os.MkdirAll(destPath, os.ModePerm)
+1 -3
View File
@@ -67,9 +67,7 @@ func (u *User) AvatarLinkWithSize(size int) string {
useLocalAvatar := false
autoGenerateAvatar := false
disableGravatarSetting, _ := system_model.GetSetting(system_model.KeyPictureDisableGravatar)
disableGravatar := disableGravatarSetting.GetValueBool()
disableGravatar := system_model.GetSettingBool(system_model.KeyPictureDisableGravatar)
switch {
case u.UseCustomAvatar:
+1 -2
View File
@@ -6,7 +6,6 @@ package user
import (
"context"
"errors"
"fmt"
"net/mail"
"regexp"
@@ -22,7 +21,7 @@ import (
)
// ErrEmailNotActivated e-mail address has not been activated error
var ErrEmailNotActivated = errors.New("e-mail address has not been activated")
var ErrEmailNotActivated = util.NewInvalidArgumentErrorf("e-mail address has not been activated")
// ErrEmailCharIsNotSupported e-mail address contains unsupported character
type ErrEmailCharIsNotSupported struct {
+1 -2
View File
@@ -5,7 +5,6 @@ package user
import (
"context"
"errors"
"fmt"
"code.gitea.io/gitea/models/db"
@@ -13,7 +12,7 @@ import (
)
// ErrOpenIDNotExist openid is not known
var ErrOpenIDNotExist = errors.New("OpenID is unknown")
var ErrOpenIDNotExist = util.NewNotExistErrorf("OpenID is unknown")
// UserOpenID is the list of all OpenID identities of a user.
// Since this is a middle table, name it OpenID is not suitable, so we ignore the lint here
+5 -5
View File
@@ -53,13 +53,13 @@ func genSettingCacheKey(userID int64, key string) string {
}
// GetSetting returns the setting value via the key
func GetSetting(uid int64, key string) (*Setting, error) {
return cache.Get(genSettingCacheKey(uid, key), func() (*Setting, error) {
func GetSetting(uid int64, key string) (string, error) {
return cache.GetString(genSettingCacheKey(uid, key), func() (string, error) {
res, err := GetSettingNoCache(uid, key)
if err != nil {
return nil, err
return "", err
}
return res, nil
return res.SettingValue, nil
})
}
@@ -154,7 +154,7 @@ func SetUserSetting(userID int64, key, value string) error {
return err
}
_, err := cache.Set(genSettingCacheKey(userID, key), func() (string, error) {
_, err := cache.GetString(genSettingCacheKey(userID, key), func() (string, error) {
return value, upsertUserSettingValue(userID, key, value)
})
+2 -1
View File
@@ -12,6 +12,7 @@ import (
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
webhook_module "code.gitea.io/gitea/modules/webhook"
gouuid "github.com/google/uuid"
)
@@ -107,7 +108,7 @@ type HookTask struct {
UUID string `xorm:"unique"`
api.Payloader `xorm:"-"`
PayloadContent string `xorm:"LONGTEXT"`
EventType HookEventType
EventType webhook_module.HookEventType
IsDelivered bool
Delivered int64
DeliveredString string `xorm:"-"`
+43 -104
View File
@@ -16,6 +16,7 @@ import (
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util"
webhook_module "code.gitea.io/gitea/modules/webhook"
"xorm.io/builder"
)
@@ -46,7 +47,7 @@ type ErrHookTaskNotExist struct {
UUID string
}
// IsErrWebhookNotExist checks if an error is a ErrWebhookNotExist.
// IsErrHookTaskNotExist checks if an error is a ErrHookTaskNotExist.
func IsErrHookTaskNotExist(err error) bool {
_, ok := err.(ErrHookTaskNotExist)
return ok
@@ -117,84 +118,22 @@ func IsValidHookContentType(name string) bool {
return ok
}
// HookEvents is a set of web hook events
type HookEvents struct {
Create bool `json:"create"`
Delete bool `json:"delete"`
Fork bool `json:"fork"`
Issues bool `json:"issues"`
IssueAssign bool `json:"issue_assign"`
IssueLabel bool `json:"issue_label"`
IssueMilestone bool `json:"issue_milestone"`
IssueComment bool `json:"issue_comment"`
Push bool `json:"push"`
PullRequest bool `json:"pull_request"`
PullRequestAssign bool `json:"pull_request_assign"`
PullRequestLabel bool `json:"pull_request_label"`
PullRequestMilestone bool `json:"pull_request_milestone"`
PullRequestComment bool `json:"pull_request_comment"`
PullRequestReview bool `json:"pull_request_review"`
PullRequestSync bool `json:"pull_request_sync"`
Wiki bool `json:"wiki"`
Repository bool `json:"repository"`
Release bool `json:"release"`
Package bool `json:"package"`
}
// HookEvent represents events that will delivery hook.
type HookEvent struct {
PushOnly bool `json:"push_only"`
SendEverything bool `json:"send_everything"`
ChooseEvents bool `json:"choose_events"`
BranchFilter string `json:"branch_filter"`
HookEvents `json:"events"`
}
// HookType is the type of a webhook
type HookType = string
// Types of webhooks
const (
GITEA HookType = "gitea"
GOGS HookType = "gogs"
SLACK HookType = "slack"
DISCORD HookType = "discord"
DINGTALK HookType = "dingtalk"
TELEGRAM HookType = "telegram"
MSTEAMS HookType = "msteams"
FEISHU HookType = "feishu"
MATRIX HookType = "matrix"
WECHATWORK HookType = "wechatwork"
PACKAGIST HookType = "packagist"
)
// HookStatus is the status of a web hook
type HookStatus int
// Possible statuses of a web hook
const (
HookStatusNone = iota
HookStatusSucceed
HookStatusFail
)
// Webhook represents a web hook object.
type Webhook struct {
ID int64 `xorm:"pk autoincr"`
RepoID int64 `xorm:"INDEX"` // An ID of 0 indicates either a default or system webhook
OrgID int64 `xorm:"INDEX"`
IsSystemWebhook bool
URL string `xorm:"url TEXT"`
HTTPMethod string `xorm:"http_method"`
ContentType HookContentType
Secret string `xorm:"TEXT"`
Events string `xorm:"TEXT"`
*HookEvent `xorm:"-"`
IsActive bool `xorm:"INDEX"`
Type HookType `xorm:"VARCHAR(16) 'type'"`
Meta string `xorm:"TEXT"` // store hook-specific attributes
LastStatus HookStatus // Last delivery status
ID int64 `xorm:"pk autoincr"`
RepoID int64 `xorm:"INDEX"` // An ID of 0 indicates either a default or system webhook
OrgID int64 `xorm:"INDEX"`
IsSystemWebhook bool
URL string `xorm:"url TEXT"`
HTTPMethod string `xorm:"http_method"`
ContentType HookContentType
Secret string `xorm:"TEXT"`
Events string `xorm:"TEXT"`
*webhook_module.HookEvent `xorm:"-"`
IsActive bool `xorm:"INDEX"`
Type webhook_module.HookType `xorm:"VARCHAR(16) 'type'"`
Meta string `xorm:"TEXT"` // store hook-specific attributes
LastStatus webhook_module.HookStatus // Last delivery status
// HeaderAuthorizationEncrypted should be accessed using HeaderAuthorization() and SetHeaderAuthorization()
HeaderAuthorizationEncrypted string `xorm:"TEXT"`
@@ -209,7 +148,7 @@ func init() {
// AfterLoad updates the webhook object upon setting a column
func (w *Webhook) AfterLoad() {
w.HookEvent = &HookEvent{}
w.HookEvent = &webhook_module.HookEvent{}
if err := json.Unmarshal([]byte(w.Events), w.HookEvent); err != nil {
log.Error("Unmarshal[%d]: %v", w.ID, err)
}
@@ -362,34 +301,34 @@ func (w *Webhook) HasPackageEvent() bool {
// EventCheckers returns event checkers
func (w *Webhook) EventCheckers() []struct {
Has func() bool
Type HookEventType
Type webhook_module.HookEventType
} {
return []struct {
Has func() bool
Type HookEventType
Type webhook_module.HookEventType
}{
{w.HasCreateEvent, HookEventCreate},
{w.HasDeleteEvent, HookEventDelete},
{w.HasForkEvent, HookEventFork},
{w.HasPushEvent, HookEventPush},
{w.HasIssuesEvent, HookEventIssues},
{w.HasIssuesAssignEvent, HookEventIssueAssign},
{w.HasIssuesLabelEvent, HookEventIssueLabel},
{w.HasIssuesMilestoneEvent, HookEventIssueMilestone},
{w.HasIssueCommentEvent, HookEventIssueComment},
{w.HasPullRequestEvent, HookEventPullRequest},
{w.HasPullRequestAssignEvent, HookEventPullRequestAssign},
{w.HasPullRequestLabelEvent, HookEventPullRequestLabel},
{w.HasPullRequestMilestoneEvent, HookEventPullRequestMilestone},
{w.HasPullRequestCommentEvent, HookEventPullRequestComment},
{w.HasPullRequestApprovedEvent, HookEventPullRequestReviewApproved},
{w.HasPullRequestRejectedEvent, HookEventPullRequestReviewRejected},
{w.HasPullRequestCommentEvent, HookEventPullRequestReviewComment},
{w.HasPullRequestSyncEvent, HookEventPullRequestSync},
{w.HasWikiEvent, HookEventWiki},
{w.HasRepositoryEvent, HookEventRepository},
{w.HasReleaseEvent, HookEventRelease},
{w.HasPackageEvent, HookEventPackage},
{w.HasCreateEvent, webhook_module.HookEventCreate},
{w.HasDeleteEvent, webhook_module.HookEventDelete},
{w.HasForkEvent, webhook_module.HookEventFork},
{w.HasPushEvent, webhook_module.HookEventPush},
{w.HasIssuesEvent, webhook_module.HookEventIssues},
{w.HasIssuesAssignEvent, webhook_module.HookEventIssueAssign},
{w.HasIssuesLabelEvent, webhook_module.HookEventIssueLabel},
{w.HasIssuesMilestoneEvent, webhook_module.HookEventIssueMilestone},
{w.HasIssueCommentEvent, webhook_module.HookEventIssueComment},
{w.HasPullRequestEvent, webhook_module.HookEventPullRequest},
{w.HasPullRequestAssignEvent, webhook_module.HookEventPullRequestAssign},
{w.HasPullRequestLabelEvent, webhook_module.HookEventPullRequestLabel},
{w.HasPullRequestMilestoneEvent, webhook_module.HookEventPullRequestMilestone},
{w.HasPullRequestCommentEvent, webhook_module.HookEventPullRequestComment},
{w.HasPullRequestApprovedEvent, webhook_module.HookEventPullRequestReviewApproved},
{w.HasPullRequestRejectedEvent, webhook_module.HookEventPullRequestReviewRejected},
{w.HasPullRequestCommentEvent, webhook_module.HookEventPullRequestReviewComment},
{w.HasPullRequestSyncEvent, webhook_module.HookEventPullRequestSync},
{w.HasWikiEvent, webhook_module.HookEventWiki},
{w.HasRepositoryEvent, webhook_module.HookEventRepository},
{w.HasReleaseEvent, webhook_module.HookEventRelease},
{w.HasPackageEvent, webhook_module.HookEventPackage},
}
}
@@ -453,7 +392,7 @@ func getWebhook(bean *Webhook) (*Webhook, error) {
if err != nil {
return nil, err
} else if !has {
return nil, ErrWebhookNotExist{bean.ID}
return nil, ErrWebhookNotExist{ID: bean.ID}
}
return bean, nil
}
@@ -541,7 +480,7 @@ func GetSystemOrDefaultWebhook(id int64) (*Webhook, error) {
if err != nil {
return nil, err
} else if !has {
return nil, ErrWebhookNotExist{id}
return nil, ErrWebhookNotExist{ID: id}
}
return webhook, nil
}
+6 -5
View File
@@ -13,6 +13,7 @@ import (
"code.gitea.io/gitea/modules/json"
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/util"
webhook_module "code.gitea.io/gitea/modules/webhook"
"github.com/stretchr/testify/assert"
)
@@ -46,11 +47,11 @@ func TestWebhook_History(t *testing.T) {
func TestWebhook_UpdateEvent(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
webhook := unittest.AssertExistsAndLoadBean(t, &Webhook{ID: 1})
hookEvent := &HookEvent{
hookEvent := &webhook_module.HookEvent{
PushOnly: true,
SendEverything: false,
ChooseEvents: false,
HookEvents: HookEvents{
HookEvents: webhook_module.HookEvents{
Create: false,
Push: true,
PullRequest: false,
@@ -59,7 +60,7 @@ func TestWebhook_UpdateEvent(t *testing.T) {
webhook.HookEvent = hookEvent
assert.NoError(t, webhook.UpdateEvent())
assert.NotEmpty(t, webhook.Events)
actualHookEvent := &HookEvent{}
actualHookEvent := &webhook_module.HookEvent{}
assert.NoError(t, json.Unmarshal([]byte(webhook.Events), actualHookEvent))
assert.Equal(t, *hookEvent, *actualHookEvent)
}
@@ -74,13 +75,13 @@ func TestWebhook_EventsArray(t *testing.T) {
"package",
},
(&Webhook{
HookEvent: &HookEvent{SendEverything: true},
HookEvent: &webhook_module.HookEvent{SendEverything: true},
}).EventsArray(),
)
assert.Equal(t, []string{"push"},
(&Webhook{
HookEvent: &HookEvent{PushOnly: true},
HookEvent: &webhook_module.HookEvent{PushOnly: true},
}).EventsArray(),
)
}