1
1
mirror of https://github.com/go-gitea/gitea synced 2024-12-23 00:54:28 +00:00

Use ErrInvalidArgument in packages (#22268)

Related to
https://github.com/go-gitea/gitea/pull/22262#discussion_r1059010774

Signed-off-by: Andrew Thornton <art27@cantab.net>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: zeripath <art27@cantab.net>
Co-authored-by: Lauris BH <lauris@nix.lv>
This commit is contained in:
KN4CK3R 2022-12-31 12:49:37 +01:00 committed by GitHub
parent dce8887494
commit 3fef47b41c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
37 changed files with 144 additions and 94 deletions

View File

@ -5,7 +5,6 @@ package asymkey
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"strings" "strings"
@ -59,9 +58,9 @@ func calcFingerprintSSHKeygen(publicKeyContent string) (string, error) {
if strings.Contains(stderr, "is not a public key file") { if strings.Contains(stderr, "is not a public key file") {
return "", ErrKeyUnableVerify{stderr} 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 { } 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 return strings.Split(stdout, " ")[1], nil
} }

View File

@ -10,7 +10,6 @@ import (
"encoding/base64" "encoding/base64"
"encoding/binary" "encoding/binary"
"encoding/pem" "encoding/pem"
"errors"
"fmt" "fmt"
"math/big" "math/big"
"os" "os"
@ -122,7 +121,7 @@ func parseKeyString(content string) (string, error) {
parts := strings.SplitN(content, " ", 3) parts := strings.SplitN(content, " ", 3)
switch len(parts) { switch len(parts) {
case 0: case 0:
return "", errors.New("empty key") return "", util.NewInvalidArgumentErrorf("empty key")
case 1: case 1:
keyContent = parts[0] keyContent = parts[0]
case 2: case 2:
@ -167,7 +166,7 @@ func CheckPublicKeyString(content string) (_ string, err error) {
content = strings.TrimRight(content, "\n\r") content = strings.TrimRight(content, "\n\r")
if strings.ContainsAny(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 // remove any unnecessary whitespace now

View File

@ -4,7 +4,6 @@
package asymkey package asymkey
import ( import (
"errors"
"fmt" "fmt"
"strings" "strings"
@ -12,6 +11,7 @@ import (
"code.gitea.io/gitea/models/perm" "code.gitea.io/gitea/models/perm"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/setting" "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) content = strings.TrimSpace(content)
if strings.ContainsAny(content, "\r\n") { 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 // check all the allowed principals, email, username or anything

View File

@ -6,7 +6,6 @@ package models
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"strings" "strings"
@ -235,7 +234,7 @@ func RemoveRepository(t *organization.Team, repoID int64) error {
// It's caller's responsibility to assign organization ID. // It's caller's responsibility to assign organization ID.
func NewTeam(t *organization.Team) (err error) { func NewTeam(t *organization.Team) (err error) {
if len(t.Name) == 0 { 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 { if err = organization.IsUsableTeamName(t.Name); err != nil {
@ -300,7 +299,7 @@ func NewTeam(t *organization.Team) (err error) {
// UpdateTeam updates information of team. // UpdateTeam updates information of team.
func UpdateTeam(t *organization.Team, authChanged, includeAllChanged bool) (err error) { func UpdateTeam(t *organization.Team, authChanged, includeAllChanged bool) (err error) {
if len(t.Name) == 0 { if len(t.Name) == 0 {
return errors.New("empty team name") return util.NewInvalidArgumentErrorf("empty team name")
} }
if len(t.Description) > 255 { if len(t.Description) > 255 {

View File

@ -5,7 +5,6 @@ package conan
import ( import (
"context" "context"
"errors"
"strconv" "strconv"
"strings" "strings"
@ -13,13 +12,14 @@ import (
"code.gitea.io/gitea/models/packages" "code.gitea.io/gitea/models/packages"
conan_module "code.gitea.io/gitea/modules/packages/conan" conan_module "code.gitea.io/gitea/modules/packages/conan"
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util"
"xorm.io/builder" "xorm.io/builder"
) )
var ( var (
ErrRecipeReferenceNotExist = errors.New("Recipe reference does not exist") ErrRecipeReferenceNotExist = util.NewNotExistErrorf("recipe reference does not exist")
ErrPackageReferenceNotExist = errors.New("Package reference does not exist") ErrPackageReferenceNotExist = util.NewNotExistErrorf("package reference does not exist")
) )
// RecipeExists checks if a recipe exists // RecipeExists checks if a recipe exists

View File

@ -5,7 +5,6 @@ package container
import ( import (
"context" "context"
"errors"
"strings" "strings"
"time" "time"
@ -13,11 +12,12 @@ import (
"code.gitea.io/gitea/models/packages" "code.gitea.io/gitea/models/packages"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
container_module "code.gitea.io/gitea/modules/packages/container" container_module "code.gitea.io/gitea/modules/packages/container"
"code.gitea.io/gitea/modules/util"
"xorm.io/builder" "xorm.io/builder"
) )
var ErrContainerBlobNotExist = errors.New("Container blob does not exist") var ErrContainerBlobNotExist = util.NewNotExistErrorf("container blob does not exist")
type BlobSearchOptions struct { type BlobSearchOptions struct {
OwnerID int64 OwnerID int64

View File

@ -5,11 +5,11 @@ package packages
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"strings" "strings"
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/util"
"xorm.io/builder" "xorm.io/builder"
) )
@ -20,9 +20,9 @@ func init() {
var ( var (
// ErrDuplicatePackage indicates a duplicated package error // 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 indicates a package not exist error
ErrPackageNotExist = errors.New("Package does not exist") ErrPackageNotExist = util.NewNotExistErrorf("package does not exist")
) )
// Type of a package // Type of a package

View File

@ -5,15 +5,15 @@ package packages
import ( import (
"context" "context"
"errors"
"time" "time"
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util"
) )
// ErrPackageBlobNotExist indicates a package blob not exist error // 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() { func init() {
db.RegisterModel(new(PackageBlob)) db.RegisterModel(new(PackageBlob))

View File

@ -5,7 +5,6 @@ package packages
import ( import (
"context" "context"
"errors"
"strings" "strings"
"time" "time"
@ -15,7 +14,7 @@ import (
) )
// ErrPackageBlobUploadNotExist indicates a package blob upload not exist error // 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() { func init() {
db.RegisterModel(new(PackageBlobUpload)) db.RegisterModel(new(PackageBlobUpload))

View File

@ -5,17 +5,17 @@ package packages
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"regexp" "regexp"
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util"
"xorm.io/builder" "xorm.io/builder"
) )
var ErrPackageCleanupRuleNotExist = errors.New("Package blob does not exist") var ErrPackageCleanupRuleNotExist = util.NewNotExistErrorf("package blob does not exist")
func init() { func init() {
db.RegisterModel(new(PackageCleanupRule)) db.RegisterModel(new(PackageCleanupRule))

View File

@ -5,13 +5,13 @@ package packages
import ( import (
"context" "context"
"errors"
"strconv" "strconv"
"strings" "strings"
"time" "time"
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util"
"xorm.io/builder" "xorm.io/builder"
) )
@ -22,9 +22,9 @@ func init() {
var ( var (
// ErrDuplicatePackageFile indicates a duplicated package file error // 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 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 // EmptyFileKey is a named constant for an empty file key

View File

@ -5,7 +5,6 @@ package packages
import ( import (
"context" "context"
"errors"
"strconv" "strconv"
"strings" "strings"
@ -17,7 +16,7 @@ import (
) )
// ErrDuplicatePackageVersion indicates a duplicated package version error // 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() { func init() {
db.RegisterModel(new(PackageVersion)) db.RegisterModel(new(PackageVersion))

View File

@ -5,7 +5,6 @@ package project
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
@ -176,7 +175,7 @@ func NewProject(p *Project) error {
} }
if !IsTypeValid(p.Type) { 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) ctx, committer, err := db.TxContext(db.DefaultContext)

View File

@ -6,16 +6,16 @@ package repo
import ( import (
"context" "context"
"errors"
"time" "time"
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util"
) )
// ErrMirrorNotExist mirror does not exist error // 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. // Mirror represents mirror information of a repository.
type Mirror struct { type Mirror struct {

View File

@ -5,18 +5,18 @@ package repo
import ( import (
"context" "context"
"errors"
"time" "time"
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util"
"xorm.io/builder" "xorm.io/builder"
) )
// ErrPushMirrorNotExist mirror does not exist error // 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. // PushMirror represents mirror information of a repository.
type PushMirror struct { type PushMirror struct {
@ -90,7 +90,7 @@ func DeletePushMirrors(ctx context.Context, opts PushMirrorOptions) error {
_, err := db.GetEngine(ctx).Where(opts.toConds()).Delete(&PushMirror{}) _, err := db.GetEngine(ctx).Where(opts.toConds()).Delete(&PushMirror{})
return err 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) { func GetPushMirror(ctx context.Context, opts PushMirrorOptions) (*PushMirror, error) {

View File

@ -6,7 +6,6 @@ package repo
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"sort" "sort"
"strconv" "strconv"
@ -156,7 +155,7 @@ func AddReleaseAttachments(ctx context.Context, releaseID int64, attachmentUUIDs
for i := range attachments { for i := range attachments {
if attachments[i].ReleaseID != 0 { if attachments[i].ReleaseID != 0 {
return errors.New("release permission denied") return util.NewPermissionDeniedErrorf("release permission denied")
} }
attachments[i].ReleaseID = releaseID attachments[i].ReleaseID = releaseID
// No assign value could be 0, so ignore AllCols(). // No assign value could be 0, so ignore AllCols().

View File

@ -5,7 +5,6 @@ package repo
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"strings" "strings"
@ -708,7 +707,7 @@ func GetUserRepositories(opts *SearchRepoOptions) (RepositoryList, int64, error)
cond := builder.NewCond() cond := builder.NewCond()
if opts.Actor == nil { 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}) cond = cond.And(builder.Eq{"owner_id": opts.Actor.ID})
if !opts.Private { if !opts.Private {

View File

@ -64,7 +64,7 @@ func Copy(src, dest string) error {
func CopyDir(srcPath, destPath string, filters ...func(filePath string) bool) error { func CopyDir(srcPath, destPath string, filters ...func(filePath string) bool) error {
// Check if target directory exists. // Check if target directory exists.
if _, err := os.Stat(destPath); !errors.Is(err, os.ErrNotExist) { 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) err := os.MkdirAll(destPath, os.ModePerm)

View File

@ -6,7 +6,6 @@ package user
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"net/mail" "net/mail"
"regexp" "regexp"
@ -22,7 +21,7 @@ import (
) )
// ErrEmailNotActivated e-mail address has not been activated error // 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 // ErrEmailCharIsNotSupported e-mail address contains unsupported character
type ErrEmailCharIsNotSupported struct { type ErrEmailCharIsNotSupported struct {

View File

@ -5,7 +5,6 @@ package user
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
@ -13,7 +12,7 @@ import (
) )
// ErrOpenIDNotExist openid is not known // 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. // 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 // Since this is a middle table, name it OpenID is not suitable, so we ignore the lint here

View File

@ -5,12 +5,12 @@ package composer
import ( import (
"archive/zip" "archive/zip"
"errors"
"io" "io"
"regexp" "regexp"
"strings" "strings"
"code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/modules/validation" "code.gitea.io/gitea/modules/validation"
"github.com/hashicorp/go-version" "github.com/hashicorp/go-version"
@ -21,11 +21,11 @@ const TypeProperty = "composer.type"
var ( var (
// ErrMissingComposerFile indicates a missing composer.json file // ErrMissingComposerFile indicates a missing composer.json file
ErrMissingComposerFile = errors.New("composer.json file is missing") ErrMissingComposerFile = util.NewInvalidArgumentErrorf("composer.json file is missing")
// ErrInvalidName indicates an invalid package name // ErrInvalidName indicates an invalid package name
ErrInvalidName = errors.New("package name is invalid") ErrInvalidName = util.NewInvalidArgumentErrorf("package name is invalid")
// ErrInvalidVersion indicates an invalid package version // ErrInvalidVersion indicates an invalid package version
ErrInvalidVersion = errors.New("package version is invalid") ErrInvalidVersion = util.NewInvalidArgumentErrorf("package version is invalid")
) )
// Package represents a Composer package // Package represents a Composer package

View File

@ -5,9 +5,10 @@ package conan
import ( import (
"bufio" "bufio"
"errors"
"io" "io"
"strings" "strings"
"code.gitea.io/gitea/modules/util"
) )
// Conaninfo represents infos of a Conan package // Conaninfo represents infos of a Conan package
@ -79,7 +80,7 @@ func readSections(r io.Reader) (map[string][]string, error) {
continue continue
} }
if line != "" { if line != "" {
return nil, errors.New("Invalid conaninfo.txt") return nil, util.NewInvalidArgumentErrorf("invalid conaninfo.txt")
} }
} }
if err := scanner.Err(); err != nil { if err := scanner.Err(); err != nil {

View File

@ -4,12 +4,12 @@
package conan package conan
import ( import (
"errors"
"fmt" "fmt"
"regexp" "regexp"
"strings" "strings"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/util"
) )
const ( const (
@ -25,7 +25,7 @@ var (
namePattern = regexp.MustCompile(fmt.Sprintf(`^[a-zA-Z0-9_][a-zA-Z0-9_\+\.-]{%d,%d}$`, minChars-1, maxChars-1)) namePattern = regexp.MustCompile(fmt.Sprintf(`^[a-zA-Z0-9_][a-zA-Z0-9_\+\.-]{%d,%d}$`, minChars-1, maxChars-1))
revisionPattern = regexp.MustCompile(fmt.Sprintf(`^[a-zA-Z0-9]{1,%d}$`, maxChars)) revisionPattern = regexp.MustCompile(fmt.Sprintf(`^[a-zA-Z0-9]{1,%d}$`, maxChars))
ErrValidation = errors.New("Could not validate one or more reference fields") ErrValidation = util.NewInvalidArgumentErrorf("could not validate one or more reference fields")
) )
// RecipeReference represents a recipe <Name>/<Version>@<User>/<Channel>#<Revision> // RecipeReference represents a recipe <Name>/<Version>@<User>/<Channel>#<Revision>

View File

@ -6,10 +6,10 @@ package helm
import ( import (
"archive/tar" "archive/tar"
"compress/gzip" "compress/gzip"
"errors"
"io" "io"
"strings" "strings"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/modules/validation" "code.gitea.io/gitea/modules/validation"
"github.com/hashicorp/go-version" "github.com/hashicorp/go-version"
@ -18,13 +18,13 @@ import (
var ( var (
// ErrMissingChartFile indicates a missing Chart.yaml file // ErrMissingChartFile indicates a missing Chart.yaml file
ErrMissingChartFile = errors.New("Chart.yaml file is missing") ErrMissingChartFile = util.NewInvalidArgumentErrorf("Chart.yaml file is missing")
// ErrInvalidName indicates an invalid package name // ErrInvalidName indicates an invalid package name
ErrInvalidName = errors.New("package name is invalid") ErrInvalidName = util.NewInvalidArgumentErrorf("package name is invalid")
// ErrInvalidVersion indicates an invalid package version // ErrInvalidVersion indicates an invalid package version
ErrInvalidVersion = errors.New("package version is invalid") ErrInvalidVersion = util.NewInvalidArgumentErrorf("package version is invalid")
// ErrInvalidChart indicates an invalid chart // ErrInvalidChart indicates an invalid chart
ErrInvalidChart = errors.New("chart is invalid") ErrInvalidChart = util.NewInvalidArgumentErrorf("chart is invalid")
) )
// Metadata for a Chart file. This models the structure of a Chart.yaml file. // Metadata for a Chart file. This models the structure of a Chart.yaml file.

View File

@ -8,7 +8,6 @@ import (
"crypto/sha1" "crypto/sha1"
"crypto/sha512" "crypto/sha512"
"encoding/base64" "encoding/base64"
"errors"
"fmt" "fmt"
"io" "io"
"regexp" "regexp"
@ -16,6 +15,7 @@ import (
"time" "time"
"code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/modules/validation" "code.gitea.io/gitea/modules/validation"
"github.com/hashicorp/go-version" "github.com/hashicorp/go-version"
@ -23,15 +23,15 @@ import (
var ( var (
// ErrInvalidPackage indicates an invalid package // ErrInvalidPackage indicates an invalid package
ErrInvalidPackage = errors.New("The package is invalid") ErrInvalidPackage = util.NewInvalidArgumentErrorf("package is invalid")
// ErrInvalidPackageName indicates an invalid name // ErrInvalidPackageName indicates an invalid name
ErrInvalidPackageName = errors.New("The package name is invalid") ErrInvalidPackageName = util.NewInvalidArgumentErrorf("package name is invalid")
// ErrInvalidPackageVersion indicates an invalid version // ErrInvalidPackageVersion indicates an invalid version
ErrInvalidPackageVersion = errors.New("The package version is invalid") ErrInvalidPackageVersion = util.NewInvalidArgumentErrorf("package version is invalid")
// ErrInvalidAttachment indicates a invalid attachment // ErrInvalidAttachment indicates a invalid attachment
ErrInvalidAttachment = errors.New("The package attachment is invalid") ErrInvalidAttachment = util.NewInvalidArgumentErrorf("package attachment is invalid")
// ErrInvalidIntegrity indicates an integrity validation error // ErrInvalidIntegrity indicates an integrity validation error
ErrInvalidIntegrity = errors.New("Failed to validate integrity") ErrInvalidIntegrity = util.NewInvalidArgumentErrorf("failed to validate integrity")
) )
var nameMatch = regexp.MustCompile(`\A((@[^\s\/~'!\(\)\*]+?)[\/])?([^_.][^\s\/~'!\(\)\*]+)\z`) var nameMatch = regexp.MustCompile(`\A((@[^\s\/~'!\(\)\*]+?)[\/])?([^_.][^\s\/~'!\(\)\*]+)\z`)

View File

@ -7,13 +7,13 @@ import (
"archive/zip" "archive/zip"
"bytes" "bytes"
"encoding/xml" "encoding/xml"
"errors"
"fmt" "fmt"
"io" "io"
"path/filepath" "path/filepath"
"regexp" "regexp"
"strings" "strings"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/modules/validation" "code.gitea.io/gitea/modules/validation"
"github.com/hashicorp/go-version" "github.com/hashicorp/go-version"
@ -21,13 +21,13 @@ import (
var ( var (
// ErrMissingNuspecFile indicates a missing Nuspec file // ErrMissingNuspecFile indicates a missing Nuspec file
ErrMissingNuspecFile = errors.New("Nuspec file is missing") ErrMissingNuspecFile = util.NewInvalidArgumentErrorf("Nuspec file is missing")
// ErrNuspecFileTooLarge indicates a Nuspec file which is too large // ErrNuspecFileTooLarge indicates a Nuspec file which is too large
ErrNuspecFileTooLarge = errors.New("Nuspec file is too large") ErrNuspecFileTooLarge = util.NewInvalidArgumentErrorf("Nuspec file is too large")
// ErrNuspecInvalidID indicates an invalid id in the Nuspec file // ErrNuspecInvalidID indicates an invalid id in the Nuspec file
ErrNuspecInvalidID = errors.New("Nuspec file contains an invalid id") ErrNuspecInvalidID = util.NewInvalidArgumentErrorf("Nuspec file contains an invalid id")
// ErrNuspecInvalidVersion indicates an invalid version in the Nuspec file // ErrNuspecInvalidVersion indicates an invalid version in the Nuspec file
ErrNuspecInvalidVersion = errors.New("Nuspec file contains an invalid version") ErrNuspecInvalidVersion = util.NewInvalidArgumentErrorf("Nuspec file contains an invalid version")
) )
// PackageType specifies the package type the metadata describes // PackageType specifies the package type the metadata describes

View File

@ -7,7 +7,6 @@ import (
"archive/zip" "archive/zip"
"bytes" "bytes"
"encoding/binary" "encoding/binary"
"errors"
"fmt" "fmt"
"io" "io"
"path" "path"
@ -15,13 +14,14 @@ import (
"strings" "strings"
"code.gitea.io/gitea/modules/packages" "code.gitea.io/gitea/modules/packages"
"code.gitea.io/gitea/modules/util"
) )
var ( var (
ErrMissingPdbFiles = errors.New("Package does not contain PDB files") ErrMissingPdbFiles = util.NewInvalidArgumentErrorf("package does not contain PDB files")
ErrInvalidFiles = errors.New("Package contains invalid files") ErrInvalidFiles = util.NewInvalidArgumentErrorf("package contains invalid files")
ErrInvalidPdbMagicNumber = errors.New("Invalid Portable PDB magic number") ErrInvalidPdbMagicNumber = util.NewInvalidArgumentErrorf("invalid Portable PDB magic number")
ErrMissingPdbStream = errors.New("Missing PDB stream") ErrMissingPdbStream = util.NewInvalidArgumentErrorf("missing PDB stream")
) )
type PortablePdb struct { type PortablePdb struct {

View File

@ -6,11 +6,11 @@ package pub
import ( import (
"archive/tar" "archive/tar"
"compress/gzip" "compress/gzip"
"errors"
"io" "io"
"regexp" "regexp"
"strings" "strings"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/modules/validation" "code.gitea.io/gitea/modules/validation"
"github.com/hashicorp/go-version" "github.com/hashicorp/go-version"
@ -18,10 +18,10 @@ import (
) )
var ( var (
ErrMissingPubspecFile = errors.New("Pubspec file is missing") ErrMissingPubspecFile = util.NewInvalidArgumentErrorf("Pubspec file is missing")
ErrPubspecFileTooLarge = errors.New("Pubspec file is too large") ErrPubspecFileTooLarge = util.NewInvalidArgumentErrorf("Pubspec file is too large")
ErrInvalidName = errors.New("Package name is invalid") ErrInvalidName = util.NewInvalidArgumentErrorf("package name is invalid")
ErrInvalidVersion = errors.New("Package version is invalid") ErrInvalidVersion = util.NewInvalidArgumentErrorf("package version is invalid")
) )
var namePattern = regexp.MustCompile(`\A[a-zA-Z_][a-zA-Z0-9_]*\z`) var namePattern = regexp.MustCompile(`\A[a-zA-Z_][a-zA-Z0-9_]*\z`)

View File

@ -6,9 +6,10 @@ package rubygems
import ( import (
"bufio" "bufio"
"bytes" "bytes"
"errors"
"io" "io"
"reflect" "reflect"
"code.gitea.io/gitea/modules/util"
) )
const ( const (
@ -31,9 +32,9 @@ const (
var ( var (
// ErrUnsupportedType indicates an unsupported type // ErrUnsupportedType indicates an unsupported type
ErrUnsupportedType = errors.New("Type is unsupported") ErrUnsupportedType = util.NewInvalidArgumentErrorf("type is unsupported")
// ErrInvalidIntRange indicates an invalid number range // ErrInvalidIntRange indicates an invalid number range
ErrInvalidIntRange = errors.New("Number is not in valid range") ErrInvalidIntRange = util.NewInvalidArgumentErrorf("number is not in valid range")
) )
// RubyUserMarshal is a Ruby object that has a marshal_load function. // RubyUserMarshal is a Ruby object that has a marshal_load function.

View File

@ -6,11 +6,11 @@ package rubygems
import ( import (
"archive/tar" "archive/tar"
"compress/gzip" "compress/gzip"
"errors"
"io" "io"
"regexp" "regexp"
"strings" "strings"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/modules/validation" "code.gitea.io/gitea/modules/validation"
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
@ -18,11 +18,11 @@ import (
var ( var (
// ErrMissingMetadataFile indicates a missing metadata.gz file // ErrMissingMetadataFile indicates a missing metadata.gz file
ErrMissingMetadataFile = errors.New("Metadata file is missing") ErrMissingMetadataFile = util.NewInvalidArgumentErrorf("metadata.gz file is missing")
// ErrInvalidName indicates an invalid id in the metadata.gz file // ErrInvalidName indicates an invalid id in the metadata.gz file
ErrInvalidName = errors.New("Metadata file contains an invalid name") ErrInvalidName = util.NewInvalidArgumentErrorf("package name is invalid")
// ErrInvalidVersion indicates an invalid version in the metadata.gz file // ErrInvalidVersion indicates an invalid version in the metadata.gz file
ErrInvalidVersion = errors.New("Metadata file contains an invalid version") ErrInvalidVersion = util.NewInvalidArgumentErrorf("package version is invalid")
) )
var versionMatcher = regexp.MustCompile(`\A[0-9]+(?:\.[0-9a-zA-Z]+)*(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?\z`) var versionMatcher = regexp.MustCompile(`\A[0-9]+(?:\.[0-9a-zA-Z]+)*(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?\z`)

View File

@ -5,6 +5,7 @@ package util
import ( import (
"errors" "errors"
"fmt"
) )
// Common Errors forming the base of our error system // Common Errors forming the base of our error system
@ -34,3 +35,31 @@ func (w SilentWrap) Error() string {
func (w SilentWrap) Unwrap() error { func (w SilentWrap) Unwrap() error {
return w.Err return w.Err
} }
// NewSilentWrapErrorf returns an error that formats as the given text but unwraps as the provided error
func NewSilentWrapErrorf(unwrap error, message string, args ...interface{}) error {
if len(args) == 0 {
return SilentWrap{Message: message, Err: unwrap}
}
return SilentWrap{Message: fmt.Sprintf(message, args...), Err: unwrap}
}
// NewInvalidArgumentErrorf returns an error that formats as the given text but unwraps as an ErrInvalidArgument
func NewInvalidArgumentErrorf(message string, args ...interface{}) error {
return NewSilentWrapErrorf(ErrInvalidArgument, message, args...)
}
// NewPermissionDeniedErrorf returns an error that formats as the given text but unwraps as an ErrPermissionDenied
func NewPermissionDeniedErrorf(message string, args ...interface{}) error {
return NewSilentWrapErrorf(ErrPermissionDenied, message, args...)
}
// NewAlreadyExistErrorf returns an error that formats as the given text but unwraps as an ErrAlreadyExist
func NewAlreadyExistErrorf(message string, args ...interface{}) error {
return NewSilentWrapErrorf(ErrAlreadyExist, message, args...)
}
// NewNotExistErrorf returns an error that formats as the given text but unwraps as an ErrNotExist
func NewNotExistErrorf(message string, args ...interface{}) error {
return NewSilentWrapErrorf(ErrNotExist, message, args...)
}

View File

@ -4,6 +4,7 @@
package composer package composer
import ( import (
"errors"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
@ -200,7 +201,11 @@ func UploadPackage(ctx *context.Context) {
cp, err := composer_module.ParsePackage(buf, buf.Size()) cp, err := composer_module.ParsePackage(buf, buf.Size())
if err != nil { if err != nil {
if errors.Is(err, util.ErrInvalidArgument) {
apiError(ctx, http.StatusBadRequest, err) apiError(ctx, http.StatusBadRequest, err)
} else {
apiError(ctx, http.StatusInternalServerError, err)
}
return return
} }

View File

@ -4,6 +4,7 @@
package helm package helm
import ( import (
"errors"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
@ -163,7 +164,11 @@ func UploadPackage(ctx *context.Context) {
metadata, err := helm_module.ParseChartArchive(buf) metadata, err := helm_module.ParseChartArchive(buf)
if err != nil { if err != nil {
if errors.Is(err, util.ErrInvalidArgument) {
apiError(ctx, http.StatusBadRequest, err) apiError(ctx, http.StatusBadRequest, err)
} else {
apiError(ctx, http.StatusInternalServerError, err)
}
return return
} }

View File

@ -158,7 +158,11 @@ func DownloadPackageFileByName(ctx *context.Context) {
func UploadPackage(ctx *context.Context) { func UploadPackage(ctx *context.Context) {
npmPackage, err := npm_module.ParsePackage(ctx.Req.Body) npmPackage, err := npm_module.ParsePackage(ctx.Req.Body)
if err != nil { if err != nil {
if errors.Is(err, util.ErrInvalidArgument) {
apiError(ctx, http.StatusBadRequest, err) apiError(ctx, http.StatusBadRequest, err)
} else {
apiError(ctx, http.StatusInternalServerError, err)
}
return return
} }

View File

@ -411,7 +411,11 @@ func UploadSymbolPackage(ctx *context.Context) {
pdbs, err := nuget_module.ExtractPortablePdb(buf, buf.Size()) pdbs, err := nuget_module.ExtractPortablePdb(buf, buf.Size())
if err != nil { if err != nil {
if errors.Is(err, util.ErrInvalidArgument) {
apiError(ctx, http.StatusBadRequest, err) apiError(ctx, http.StatusBadRequest, err)
} else {
apiError(ctx, http.StatusInternalServerError, err)
}
return return
} }
defer pdbs.Close() defer pdbs.Close()
@ -507,7 +511,7 @@ func processUploadedFile(ctx *context.Context, expectedType nuget_module.Package
np, err := nuget_module.ParsePackageMetaData(buf, buf.Size()) np, err := nuget_module.ParsePackageMetaData(buf, buf.Size())
if err != nil { if err != nil {
if err == nuget_module.ErrMissingNuspecFile || err == nuget_module.ErrNuspecFileTooLarge || err == nuget_module.ErrNuspecInvalidID || err == nuget_module.ErrNuspecInvalidVersion { if errors.Is(err, util.ErrInvalidArgument) {
apiError(ctx, http.StatusBadRequest, err) apiError(ctx, http.StatusBadRequest, err)
} else { } else {
apiError(ctx, http.StatusInternalServerError, err) apiError(ctx, http.StatusInternalServerError, err)

View File

@ -4,6 +4,7 @@
package pub package pub
import ( import (
"errors"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
@ -19,6 +20,7 @@ import (
packages_module "code.gitea.io/gitea/modules/packages" packages_module "code.gitea.io/gitea/modules/packages"
pub_module "code.gitea.io/gitea/modules/packages/pub" pub_module "code.gitea.io/gitea/modules/packages/pub"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/routers/api/packages/helper" "code.gitea.io/gitea/routers/api/packages/helper"
packages_service "code.gitea.io/gitea/services/packages" packages_service "code.gitea.io/gitea/services/packages"
) )
@ -173,7 +175,11 @@ func UploadPackageFile(ctx *context.Context) {
pck, err := pub_module.ParsePackage(buf) pck, err := pub_module.ParsePackage(buf)
if err != nil { if err != nil {
if errors.Is(err, util.ErrInvalidArgument) {
apiError(ctx, http.StatusBadRequest, err)
} else {
apiError(ctx, http.StatusInternalServerError, err) apiError(ctx, http.StatusInternalServerError, err)
}
return return
} }

View File

@ -6,6 +6,7 @@ package rubygems
import ( import (
"compress/gzip" "compress/gzip"
"compress/zlib" "compress/zlib"
"errors"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
@ -217,7 +218,11 @@ func UploadPackageFile(ctx *context.Context) {
rp, err := rubygems_module.ParsePackageMetaData(buf) rp, err := rubygems_module.ParsePackageMetaData(buf)
if err != nil { if err != nil {
if errors.Is(err, util.ErrInvalidArgument) {
apiError(ctx, http.StatusBadRequest, err)
} else {
apiError(ctx, http.StatusInternalServerError, err) apiError(ctx, http.StatusInternalServerError, err)
}
return return
} }
if _, err := buf.Seek(0, io.SeekStart); err != nil { if _, err := buf.Seek(0, io.SeekStart); err != nil {