migrate from com.* to alternatives (#14103)

* remove github.com/unknwon/com from models

* dont use "com.ToStr()"

* replace "com.ToStr" with "fmt.Sprint" where its easy to do

* more refactor

* fix test

* just "proxy" Copy func for now

* as per @lunny
This commit is contained in:
6543 2020-12-25 09:59:32 +00:00 committed by GitHub
parent 04ae0f2f3f
commit a19447aed1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
46 changed files with 230 additions and 220 deletions

View File

@ -26,7 +26,6 @@ import (
"github.com/dgrijalva/jwt-go" "github.com/dgrijalva/jwt-go"
"github.com/kballard/go-shellquote" "github.com/kballard/go-shellquote"
"github.com/unknwon/com"
"github.com/urfave/cli" "github.com/urfave/cli"
) )
@ -105,7 +104,10 @@ func runServ(c *cli.Context) error {
if len(keys) != 2 || keys[0] != "key" { if len(keys) != 2 || keys[0] != "key" {
fail("Key ID format error", "Invalid key argument: %s", c.Args()[0]) fail("Key ID format error", "Invalid key argument: %s", c.Args()[0])
} }
keyID := com.StrTo(keys[1]).MustInt64() keyID, err := strconv.ParseInt(keys[1], 10, 64)
if err != nil {
fail("Key ID format error", "Invalid key argument: %s", c.Args()[1])
}
cmd := os.Getenv("SSH_ORIGINAL_COMMAND") cmd := os.Getenv("SSH_ORIGINAL_COMMAND")
if len(cmd) == 0 { if len(cmd) == 0 {

View File

@ -37,7 +37,6 @@ import (
"github.com/go-git/go-git/v5/config" "github.com/go-git/go-git/v5/config"
"github.com/go-git/go-git/v5/plumbing" "github.com/go-git/go-git/v5/plumbing"
context2 "github.com/gorilla/context" context2 "github.com/gorilla/context"
"github.com/unknwon/com"
"xorm.io/xorm" "xorm.io/xorm"
) )
@ -111,7 +110,7 @@ func runPR() {
models.LoadFixtures() models.LoadFixtures()
util.RemoveAll(setting.RepoRootPath) util.RemoveAll(setting.RepoRootPath)
util.RemoveAll(models.LocalCopyPath()) util.RemoveAll(models.LocalCopyPath())
com.CopyDir(path.Join(curDir, "integrations/gitea-repositories-meta"), setting.RepoRootPath) util.CopyDir(path.Join(curDir, "integrations/gitea-repositories-meta"), setting.RepoRootPath)
log.Printf("[PR] Setting up router\n") log.Printf("[PR] Setting up router\n")
//routers.GlobalInit() //routers.GlobalInit()

View File

@ -24,7 +24,6 @@ import (
"code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/util"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/unknwon/com"
) )
func withKeyFile(t *testing.T, keyname string, callback func(string)) { func withKeyFile(t *testing.T, keyname string, callback func(string)) {
@ -112,7 +111,9 @@ func onGiteaRun(t *testing.T, callback func(*testing.T, *url.URL), prepare ...bo
func doGitClone(dstLocalPath string, u *url.URL) func(*testing.T) { func doGitClone(dstLocalPath string, u *url.URL) func(*testing.T) {
return func(t *testing.T) { return func(t *testing.T) {
assert.NoError(t, git.CloneWithArgs(context.Background(), u.String(), dstLocalPath, allowLFSFilters(), git.CloneRepoOptions{})) assert.NoError(t, git.CloneWithArgs(context.Background(), u.String(), dstLocalPath, allowLFSFilters(), git.CloneRepoOptions{}))
assert.True(t, com.IsExist(filepath.Join(dstLocalPath, "README.md"))) exist, err := util.IsExist(filepath.Join(dstLocalPath, "README.md"))
assert.NoError(t, err)
assert.True(t, exist)
} }
} }
@ -122,7 +123,9 @@ func doGitCloneFail(u *url.URL) func(*testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
defer util.RemoveAll(tmpDir) defer util.RemoveAll(tmpDir)
assert.Error(t, git.Clone(u.String(), tmpDir, git.CloneRepoOptions{})) assert.Error(t, git.Clone(u.String(), tmpDir, git.CloneRepoOptions{}))
assert.False(t, com.IsExist(filepath.Join(tmpDir, "README.md"))) exist, err := util.IsExist(filepath.Join(tmpDir, "README.md"))
assert.NoError(t, err)
assert.False(t, exist)
} }
} }

View File

@ -37,7 +37,6 @@ import (
"github.com/PuerkitoBio/goquery" "github.com/PuerkitoBio/goquery"
"github.com/go-chi/chi" "github.com/go-chi/chi"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/unknwon/com"
) )
var c chi.Router var c chi.Router
@ -231,8 +230,7 @@ func prepareTestEnv(t testing.TB, skip ...int) func() {
assert.NoError(t, models.LoadFixtures()) assert.NoError(t, models.LoadFixtures())
assert.NoError(t, util.RemoveAll(setting.RepoRootPath)) assert.NoError(t, util.RemoveAll(setting.RepoRootPath))
assert.NoError(t, com.CopyDir(path.Join(filepath.Dir(setting.AppPath), "integrations/gitea-repositories-meta"), assert.NoError(t, util.CopyDir(path.Join(filepath.Dir(setting.AppPath), "integrations/gitea-repositories-meta"), setting.RepoRootPath))
setting.RepoRootPath))
return deferFn return deferFn
} }
@ -473,6 +471,5 @@ func resetFixtures(t *testing.T) {
assert.NoError(t, queue.GetManager().FlushAll(context.Background(), -1)) assert.NoError(t, queue.GetManager().FlushAll(context.Background(), -1))
assert.NoError(t, models.LoadFixtures()) assert.NoError(t, models.LoadFixtures())
assert.NoError(t, util.RemoveAll(setting.RepoRootPath)) assert.NoError(t, util.RemoveAll(setting.RepoRootPath))
assert.NoError(t, com.CopyDir(path.Join(filepath.Dir(setting.AppPath), "integrations/gitea-repositories-meta"), assert.NoError(t, util.CopyDir(path.Join(filepath.Dir(setting.AppPath), "integrations/gitea-repositories-meta"), setting.RepoRootPath))
setting.RepoRootPath))
} }

View File

@ -27,7 +27,6 @@ import (
"code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/util"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/unknwon/com"
"xorm.io/xorm" "xorm.io/xorm"
) )
@ -60,7 +59,7 @@ func initMigrationTest(t *testing.T) func() {
assert.True(t, len(setting.RepoRootPath) != 0) assert.True(t, len(setting.RepoRootPath) != 0)
assert.NoError(t, util.RemoveAll(setting.RepoRootPath)) assert.NoError(t, util.RemoveAll(setting.RepoRootPath))
assert.NoError(t, com.CopyDir(path.Join(filepath.Dir(setting.AppPath), "integrations/gitea-repositories-meta"), setting.RepoRootPath)) assert.NoError(t, util.CopyDir(path.Join(filepath.Dir(setting.AppPath), "integrations/gitea-repositories-meta"), setting.RepoRootPath))
setting.CheckLFSVersion() setting.CheckLFSVersion()
setting.InitDBConfig() setting.InitDBConfig()

View File

@ -18,7 +18,6 @@ import (
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
"github.com/unknwon/com"
"xorm.io/builder" "xorm.io/builder"
) )
@ -266,7 +265,7 @@ func (a *Action) GetIssueInfos() []string {
// GetIssueTitle returns the title of first issue associated // GetIssueTitle returns the title of first issue associated
// with the action. // with the action.
func (a *Action) GetIssueTitle() string { func (a *Action) GetIssueTitle() string {
index := com.StrTo(a.GetIssueInfos()[0]).MustInt64() index, _ := strconv.ParseInt(a.GetIssueInfos()[0], 10, 64)
issue, err := GetIssueByIndex(a.RepoID, index) issue, err := GetIssueByIndex(a.RepoID, index)
if err != nil { if err != nil {
log.Error("GetIssueByIndex: %v", err) log.Error("GetIssueByIndex: %v", err)
@ -278,7 +277,7 @@ func (a *Action) GetIssueTitle() string {
// GetIssueContent returns the content of first issue associated with // GetIssueContent returns the content of first issue associated with
// this action. // this action.
func (a *Action) GetIssueContent() string { func (a *Action) GetIssueContent() string {
index := com.StrTo(a.GetIssueInfos()[0]).MustInt64() index, _ := strconv.ParseInt(a.GetIssueInfos()[0], 10, 64)
issue, err := GetIssueByIndex(a.RepoID, index) issue, err := GetIssueByIndex(a.RepoID, index)
if err != nil { if err != nil {
log.Error("GetIssueByIndex: %v", err) log.Error("GetIssueByIndex: %v", err)

View File

@ -12,8 +12,6 @@ import (
"code.gitea.io/gitea/modules/storage" "code.gitea.io/gitea/modules/storage"
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/util"
"github.com/unknwon/com"
) )
//NoticeType describes the notice type //NoticeType describes the notice type
@ -36,7 +34,7 @@ type Notice struct {
// TrStr returns a translation format string. // TrStr returns a translation format string.
func (n *Notice) TrStr() string { func (n *Notice) TrStr() string {
return "admin.notices.type_" + com.ToStr(n.Type) return fmt.Sprintf("admin.notices.type_%d", n.Type)
} }
// CreateNotice creates new system notice. // CreateNotice creates new system notice.

View File

@ -16,7 +16,6 @@ import (
"code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/util"
"github.com/gobwas/glob" "github.com/gobwas/glob"
"github.com/unknwon/com"
) )
// ProtectedBranch struct // ProtectedBranch struct
@ -483,7 +482,7 @@ func updateTeamWhitelist(repo *Repository, currentWhitelist, newWhitelist []int6
whitelist = make([]int64, 0, len(teams)) whitelist = make([]int64, 0, len(teams))
for i := range teams { for i := range teams {
if com.IsSliceContainsInt64(newWhitelist, teams[i].ID) { if util.IsInt64InSlice(teams[i].ID, newWhitelist) {
whitelist = append(whitelist, teams[i].ID) whitelist = append(whitelist, teams[i].ID)
} }
} }

View File

@ -20,7 +20,6 @@ import (
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/util"
"github.com/unknwon/com"
"xorm.io/builder" "xorm.io/builder"
"xorm.io/xorm" "xorm.io/xorm"
) )
@ -386,7 +385,7 @@ func (issue *Issue) State() api.StateType {
// HashTag returns unique hash tag for issue. // HashTag returns unique hash tag for issue.
func (issue *Issue) HashTag() string { func (issue *Issue) HashTag() string {
return "issue-" + com.ToStr(issue.ID) return fmt.Sprintf("issue-%d", issue.ID)
} }
// IsPoster returns true if given user by ID is the poster. // IsPoster returns true if given user by ID is the poster.
@ -1374,7 +1373,8 @@ func parseCountResult(results []map[string][]byte) int64 {
return 0 return 0
} }
for _, result := range results[0] { for _, result := range results[0] {
return com.StrTo(string(result)).MustInt64() c, _ := strconv.ParseInt(string(result), 10, 64)
return c
} }
return 0 return 0
} }

View File

@ -22,7 +22,6 @@ import (
"code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
"github.com/unknwon/com"
"xorm.io/builder" "xorm.io/builder"
"xorm.io/xorm" "xorm.io/xorm"
) )
@ -367,7 +366,7 @@ func (c *Comment) HashTag() string {
// EventTag returns unique event hash tag for comment. // EventTag returns unique event hash tag for comment.
func (c *Comment) EventTag() string { func (c *Comment) EventTag() string {
return "event-" + com.ToStr(c.ID) return fmt.Sprintf("event-%d", c.ID)
} }
// LoadLabel if comment.Type is CommentTypeLabel, then load Label // LoadLabel if comment.Type is CommentTypeLabel, then load Label

View File

@ -10,7 +10,6 @@ import (
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/references" "code.gitea.io/gitea/modules/references"
"github.com/unknwon/com"
"xorm.io/xorm" "xorm.io/xorm"
) )
@ -324,7 +323,7 @@ func (comment *Comment) RefIssueIdent() string {
return "" return ""
} }
// FIXME: check this name for cross-repository references (#7901 if it gets merged) // FIXME: check this name for cross-repository references (#7901 if it gets merged)
return "#" + com.ToStr(comment.RefIssue.Index) return fmt.Sprintf("#%d", comment.RefIssue.Index)
} }
// __________ .__ .__ __________ __ // __________ .__ .__ __________ __

View File

@ -12,6 +12,7 @@ import (
"fmt" "fmt"
"net/smtp" "net/smtp"
"net/textproto" "net/textproto"
"strconv"
"strings" "strings"
"code.gitea.io/gitea/modules/auth/ldap" "code.gitea.io/gitea/modules/auth/ldap"
@ -20,8 +21,8 @@ import (
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util"
"github.com/unknwon/com"
"xorm.io/xorm" "xorm.io/xorm"
"xorm.io/xorm/convert" "xorm.io/xorm/convert"
) )
@ -180,7 +181,9 @@ func Cell2Int64(val xorm.Cell) int64 {
switch (*val).(type) { switch (*val).(type) {
case []uint8: case []uint8:
log.Trace("Cell2Int64 ([]uint8): %v", *val) log.Trace("Cell2Int64 ([]uint8): %v", *val)
return com.StrTo(string((*val).([]uint8))).MustInt64()
v, _ := strconv.ParseInt(string((*val).([]uint8)), 10, 64)
return v
} }
return (*val).(int64) return (*val).(int64)
} }
@ -200,7 +203,7 @@ func (source *LoginSource) BeforeSet(colName string, val xorm.Cell) {
case LoginSSPI: case LoginSSPI:
source.Cfg = new(SSPIConfig) source.Cfg = new(SSPIConfig)
default: default:
panic("unrecognized login source type: " + com.ToStr(*val)) panic(fmt.Sprintf("unrecognized login source type: %v", *val))
} }
} }
} }
@ -610,7 +613,7 @@ func LoginViaSMTP(user *User, login, password string, sourceID int64, cfg *SMTPC
idx := strings.Index(login, "@") idx := strings.Index(login, "@")
if idx == -1 { if idx == -1 {
return nil, ErrUserNotExist{0, login, 0} return nil, ErrUserNotExist{0, login, 0}
} else if !com.IsSliceContainsStr(strings.Split(cfg.AllowedDomains, ","), login[idx+1:]) { } else if !util.IsStringInSlice(login[idx+1:], strings.Split(cfg.AllowedDomains, ","), true) {
return nil, ErrUserNotExist{0, login, 0} return nil, ErrUserNotExist{0, login, 0}
} }
} }

View File

@ -14,10 +14,10 @@ import (
"code.gitea.io/gitea/modules/secret" "code.gitea.io/gitea/modules/secret"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util"
"github.com/dgrijalva/jwt-go" "github.com/dgrijalva/jwt-go"
uuid "github.com/google/uuid" uuid "github.com/google/uuid"
"github.com/unknwon/com"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
"xorm.io/xorm" "xorm.io/xorm"
) )
@ -62,7 +62,7 @@ func (app *OAuth2Application) LoadUser() (err error) {
// ContainsRedirectURI checks if redirectURI is allowed for app // ContainsRedirectURI checks if redirectURI is allowed for app
func (app *OAuth2Application) ContainsRedirectURI(redirectURI string) bool { func (app *OAuth2Application) ContainsRedirectURI(redirectURI string) bool {
return com.IsSliceContainsStr(app.RedirectURIs, redirectURI) return util.IsStringInSlice(redirectURI, app.RedirectURIs, true)
} }
// GenerateClientSecret will generate the client secret and returns the plaintext and saves the hash at the database // GenerateClientSecret will generate the client secret and returns the plaintext and saves the hash at the database

View File

@ -34,7 +34,6 @@ import (
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/util"
"github.com/unknwon/com"
"xorm.io/builder" "xorm.io/builder"
) )
@ -85,7 +84,7 @@ func loadRepoConfig() {
} }
for _, f := range customFiles { for _, f := range customFiles {
if !com.IsSliceContainsStr(files, f) { if !util.IsStringInSlice(f, files, true) {
files = append(files, f) files = append(files, f)
} }
} }
@ -115,12 +114,12 @@ func loadRepoConfig() {
// Filter out invalid names and promote preferred licenses. // Filter out invalid names and promote preferred licenses.
sortedLicenses := make([]string, 0, len(Licenses)) sortedLicenses := make([]string, 0, len(Licenses))
for _, name := range setting.Repository.PreferredLicenses { for _, name := range setting.Repository.PreferredLicenses {
if com.IsSliceContainsStr(Licenses, name) { if util.IsStringInSlice(name, Licenses, true) {
sortedLicenses = append(sortedLicenses, name) sortedLicenses = append(sortedLicenses, name)
} }
} }
for _, name := range Licenses { for _, name := range Licenses {
if !com.IsSliceContainsStr(setting.Repository.PreferredLicenses, name) { if !util.IsStringInSlice(name, setting.Repository.PreferredLicenses, true) {
sortedLicenses = append(sortedLicenses, name) sortedLicenses = append(sortedLicenses, name)
} }
} }
@ -1933,7 +1932,7 @@ func repoStatsCheck(ctx context.Context, checker *repoChecker) {
return return
} }
for _, result := range results { for _, result := range results {
id := com.StrTo(result["id"]).MustInt64() id, _ := strconv.ParseInt(string(result["id"]), 10, 64)
select { select {
case <-ctx.Done(): case <-ctx.Done():
log.Warn("CheckRepoStats: Cancelled before checking %s for Repo[%d]", checker.desc, id) log.Warn("CheckRepoStats: Cancelled before checking %s for Repo[%d]", checker.desc, id)
@ -2001,7 +2000,7 @@ func CheckRepoStats(ctx context.Context) error {
log.Error("Select %s: %v", desc, err) log.Error("Select %s: %v", desc, err)
} else { } else {
for _, result := range results { for _, result := range results {
id := com.StrTo(result["id"]).MustInt64() id, _ := strconv.ParseInt(string(result["id"]), 10, 64)
select { select {
case <-ctx.Done(): case <-ctx.Done():
log.Warn("CheckRepoStats: Cancelled during %s for repo ID %d", desc, id) log.Warn("CheckRepoStats: Cancelled during %s for repo ID %d", desc, id)
@ -2024,7 +2023,7 @@ func CheckRepoStats(ctx context.Context) error {
log.Error("Select %s: %v", desc, err) log.Error("Select %s: %v", desc, err)
} else { } else {
for _, result := range results { for _, result := range results {
id := com.StrTo(result["id"]).MustInt64() id, _ := strconv.ParseInt(string(result["id"]), 10, 64)
select { select {
case <-ctx.Done(): case <-ctx.Done():
log.Warn("CheckRepoStats: Cancelled") log.Warn("CheckRepoStats: Cancelled")
@ -2047,7 +2046,7 @@ func CheckRepoStats(ctx context.Context) error {
log.Error("Select repository count 'num_forks': %v", err) log.Error("Select repository count 'num_forks': %v", err)
} else { } else {
for _, result := range results { for _, result := range results {
id := com.StrTo(result["id"]).MustInt64() id, _ := strconv.ParseInt(string(result["id"]), 10, 64)
select { select {
case <-ctx.Done(): case <-ctx.Done():
log.Warn("CheckRepoStats: Cancelled") log.Warn("CheckRepoStats: Cancelled")

View File

@ -6,10 +6,10 @@ package models
import ( import (
"encoding/json" "encoding/json"
"fmt"
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
"github.com/unknwon/com"
"xorm.io/xorm" "xorm.io/xorm"
"xorm.io/xorm/convert" "xorm.io/xorm/convert"
) )
@ -147,7 +147,7 @@ func (r *RepoUnit) BeforeSet(colName string, val xorm.Cell) {
case UnitTypeIssues: case UnitTypeIssues:
r.Config = new(IssuesConfig) r.Config = new(IssuesConfig)
default: default:
panic("unrecognized repo unit type: " + com.ToStr(*val)) panic(fmt.Sprintf("unrecognized repo unit type: %v", *val))
} }
} }
} }

View File

@ -20,6 +20,7 @@ import (
"math/big" "math/big"
"os" "os"
"path/filepath" "path/filepath"
"strconv"
"strings" "strings"
"sync" "sync"
"time" "time"
@ -30,7 +31,6 @@ import (
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/util"
"github.com/unknwon/com"
"golang.org/x/crypto/ssh" "golang.org/x/crypto/ssh"
"xorm.io/builder" "xorm.io/builder"
"xorm.io/xorm" "xorm.io/xorm"
@ -252,7 +252,11 @@ func SSHKeyGenParsePublicKey(key string) (string, int, error) {
} }
keyType := strings.Trim(fields[len(fields)-1], "()\r\n") keyType := strings.Trim(fields[len(fields)-1], "()\r\n")
return strings.ToLower(keyType), com.StrTo(fields[0]).MustInt(), nil length, err := strconv.ParseInt(fields[0], 10, 32)
if err != nil {
return "", 0, err
}
return strings.ToLower(keyType), int(length), nil
} }
// SSHNativeParsePublicKey extracts the key type and length using the golang SSH library. // SSHNativeParsePublicKey extracts the key type and length using the golang SSH library.
@ -744,7 +748,7 @@ func rewriteAllPublicKeys(e Engine) error {
} }
if isExist { if isExist {
bakPath := fmt.Sprintf("%s_%d.gitea_bak", fPath, time.Now().Unix()) bakPath := fmt.Sprintf("%s_%d.gitea_bak", fPath, time.Now().Unix())
if err = com.Copy(fPath, bakPath); err != nil { if err = util.CopyFile(fPath, bakPath); err != nil {
return err return err
} }
} }
@ -1226,7 +1230,7 @@ func rewriteAllPrincipalKeys(e Engine) error {
} }
if isExist { if isExist {
bakPath := fmt.Sprintf("%s_%d.gitea_bak", fPath, time.Now().Unix()) bakPath := fmt.Sprintf("%s_%d.gitea_bak", fPath, time.Now().Unix())
if err = com.Copy(fPath, bakPath); err != nil { if err = util.CopyFile(fPath, bakPath); err != nil {
return err return err
} }
} }

View File

@ -19,7 +19,6 @@ import (
"code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/util"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/unknwon/com"
"xorm.io/xorm" "xorm.io/xorm"
"xorm.io/xorm/names" "xorm.io/xorm/names"
) )
@ -82,8 +81,8 @@ func MainTest(m *testing.M, pathToGiteaRoot string) {
if err = util.RemoveAll(setting.RepoRootPath); err != nil { if err = util.RemoveAll(setting.RepoRootPath); err != nil {
fatalTestError("util.RemoveAll: %v\n", err) fatalTestError("util.RemoveAll: %v\n", err)
} }
if err = com.CopyDir(filepath.Join(pathToGiteaRoot, "integrations", "gitea-repositories-meta"), setting.RepoRootPath); err != nil { if err = util.CopyDir(filepath.Join(pathToGiteaRoot, "integrations", "gitea-repositories-meta"), setting.RepoRootPath); err != nil {
fatalTestError("com.CopyDir: %v\n", err) fatalTestError("util.CopyDir: %v\n", err)
} }
exitStatus := m.Run() exitStatus := m.Run()
@ -126,7 +125,7 @@ func PrepareTestEnv(t testing.TB) {
assert.NoError(t, PrepareTestDatabase()) assert.NoError(t, PrepareTestDatabase())
assert.NoError(t, util.RemoveAll(setting.RepoRootPath)) assert.NoError(t, util.RemoveAll(setting.RepoRootPath))
metaPath := filepath.Join(giteaRoot, "integrations", "gitea-repositories-meta") metaPath := filepath.Join(giteaRoot, "integrations", "gitea-repositories-meta")
assert.NoError(t, com.CopyDir(metaPath, setting.RepoRootPath)) assert.NoError(t, util.CopyDir(metaPath, setting.RepoRootPath))
base.SetupGiteaRoot() // Makes sure GITEA_ROOT is set base.SetupGiteaRoot() // Makes sure GITEA_ROOT is set
} }

View File

@ -32,7 +32,6 @@ import (
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/util"
"github.com/unknwon/com"
"golang.org/x/crypto/argon2" "golang.org/x/crypto/argon2"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
"golang.org/x/crypto/pbkdf2" "golang.org/x/crypto/pbkdf2"
@ -315,7 +314,7 @@ func (u *User) HTMLURL() string {
// GenerateEmailActivateCode generates an activate code based on user information and given e-mail. // GenerateEmailActivateCode generates an activate code based on user information and given e-mail.
func (u *User) GenerateEmailActivateCode(email string) string { func (u *User) GenerateEmailActivateCode(email string) string {
code := base.CreateTimeLimitCode( code := base.CreateTimeLimitCode(
com.ToStr(u.ID)+email+u.LowerName+u.Passwd+u.Rands, fmt.Sprintf("%d%s%s%s%s", u.ID, email, u.LowerName, u.Passwd, u.Rands),
setting.Service.ActiveCodeLives, nil) setting.Service.ActiveCodeLives, nil)
// Add tail hex username // Add tail hex username
@ -880,7 +879,7 @@ func VerifyUserActiveCode(code string) (user *User) {
if user = getVerifyUser(code); user != nil { if user = getVerifyUser(code); user != nil {
// time limit code // time limit code
prefix := code[:base.TimeLimitCodeLength] prefix := code[:base.TimeLimitCodeLength]
data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Passwd + user.Rands data := fmt.Sprintf("%d%s%s%s%s", user.ID, user.Email, user.LowerName, user.Passwd, user.Rands)
if base.VerifyTimeLimitCode(data, minutes, prefix) { if base.VerifyTimeLimitCode(data, minutes, prefix) {
return user return user
@ -896,7 +895,7 @@ func VerifyActiveEmailCode(code, email string) *EmailAddress {
if user := getVerifyUser(code); user != nil { if user := getVerifyUser(code); user != nil {
// time limit code // time limit code
prefix := code[:base.TimeLimitCodeLength] prefix := code[:base.TimeLimitCodeLength]
data := com.ToStr(user.ID) + email + user.LowerName + user.Passwd + user.Rands data := fmt.Sprintf("%d%s%s%s%s", user.ID, email, user.LowerName, user.Passwd, user.Rands)
if base.VerifyTimeLimitCode(data, minutes, prefix) { if base.VerifyTimeLimitCode(data, minutes, prefix) {
emailAddress := &EmailAddress{UID: user.ID, Email: email} emailAddress := &EmailAddress{UID: user.ID, Email: email}

View File

@ -26,7 +26,6 @@ import (
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
"github.com/dustin/go-humanize" "github.com/dustin/go-humanize"
"github.com/unknwon/com"
) )
// EncodeMD5 encodes string to md5 hex value. // EncodeMD5 encodes string to md5 hex value.
@ -86,8 +85,8 @@ func VerifyTimeLimitCode(data string, minutes int, code string) bool {
// split code // split code
start := code[:12] start := code[:12]
lives := code[12:18] lives := code[12:18]
if d, err := com.StrTo(lives).Int(); err == nil { if d, err := strconv.ParseInt(lives, 10, 0); err == nil {
minutes = d minutes = int(d)
} }
// right active code // right active code
@ -131,7 +130,7 @@ func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string
// create sha1 encode string // create sha1 encode string
sh := sha1.New() sh := sha1.New()
_, _ = sh.Write([]byte(data + setting.SecretKey + startStr + endStr + com.ToStr(minutes))) _, _ = sh.Write([]byte(fmt.Sprintf("%s%s%s%s%d", data, setting.SecretKey, startStr, endStr, minutes)))
encoded := hex.EncodeToString(sh.Sum(nil)) encoded := hex.EncodeToString(sh.Sum(nil))
code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded) code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
@ -223,7 +222,7 @@ func TruncateString(str string, limit int) string {
func StringsToInt64s(strs []string) ([]int64, error) { func StringsToInt64s(strs []string) ([]int64, error) {
ints := make([]int64, len(strs)) ints := make([]int64, len(strs))
for i := range strs { for i := range strs {
n, err := com.StrTo(strs[i]).Int64() n, err := strconv.ParseInt(strs[i], 10, 64)
if err != nil { if err != nil {
return ints, err return ints, err
} }

View File

@ -17,8 +17,6 @@ import (
api "code.gitea.io/gitea/modules/structs" api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/services/webhook" "code.gitea.io/gitea/services/webhook"
"github.com/unknwon/com"
) )
// ToEmail convert models.EmailAddress to api.Email // ToEmail convert models.EmailAddress to api.Email
@ -169,7 +167,7 @@ func ToPublicKey(apiLink string, key *models.PublicKey) *api.PublicKey {
return &api.PublicKey{ return &api.PublicKey{
ID: key.ID, ID: key.ID,
Key: key.Content, Key: key.Content,
URL: apiLink + com.ToStr(key.ID), URL: fmt.Sprintf("%s%d", apiLink, key.ID),
Title: key.Name, Title: key.Name,
Fingerprint: key.Fingerprint, Fingerprint: key.Fingerprint,
Created: key.CreatedUnix.AsTime(), Created: key.CreatedUnix.AsTime(),
@ -263,7 +261,7 @@ func ToDeployKey(apiLink string, key *models.DeployKey) *api.DeployKey {
KeyID: key.KeyID, KeyID: key.KeyID,
Key: key.Content, Key: key.Content,
Fingerprint: key.Fingerprint, Fingerprint: key.Fingerprint,
URL: apiLink + com.ToStr(key.ID), URL: fmt.Sprintf("%s%d", apiLink, key.ID),
Title: key.Name, Title: key.Name,
Created: key.CreatedUnix.AsTime(), Created: key.CreatedUnix.AsTime(),
ReadOnly: key.Mode == models.AccessModeRead, // All deploy keys are read-only. ReadOnly: key.Mode == models.AccessModeRead, // All deploy keys are read-only.

View File

@ -15,8 +15,6 @@ import (
"strconv" "strconv"
"strings" "strings"
"time" "time"
"github.com/unknwon/com"
) )
// GPGSettings represents the default GPG settings for this repository // GPGSettings represents the default GPG settings for this repository
@ -309,21 +307,24 @@ func parseSize(objects string) *CountObject {
for _, line := range strings.Split(objects, "\n") { for _, line := range strings.Split(objects, "\n") {
switch { switch {
case strings.HasPrefix(line, statCount): case strings.HasPrefix(line, statCount):
repoSize.Count = com.StrTo(line[7:]).MustInt64() repoSize.Count, _ = strconv.ParseInt(line[7:], 10, 64)
case strings.HasPrefix(line, statSize): case strings.HasPrefix(line, statSize):
repoSize.Size = com.StrTo(line[6:]).MustInt64() * 1024 repoSize.Size, _ = strconv.ParseInt(line[6:], 10, 64)
repoSize.Size *= 1024
case strings.HasPrefix(line, statInpack): case strings.HasPrefix(line, statInpack):
repoSize.InPack = com.StrTo(line[9:]).MustInt64() repoSize.InPack, _ = strconv.ParseInt(line[9:], 10, 64)
case strings.HasPrefix(line, statPacks): case strings.HasPrefix(line, statPacks):
repoSize.Packs = com.StrTo(line[7:]).MustInt64() repoSize.Packs, _ = strconv.ParseInt(line[7:], 10, 64)
case strings.HasPrefix(line, statSizePack): case strings.HasPrefix(line, statSizePack):
repoSize.SizePack = com.StrTo(line[11:]).MustInt64() * 1024 repoSize.Count, _ = strconv.ParseInt(line[11:], 10, 64)
repoSize.Count *= 1024
case strings.HasPrefix(line, statPrunePackage): case strings.HasPrefix(line, statPrunePackage):
repoSize.PrunePack = com.StrTo(line[16:]).MustInt64() repoSize.PrunePack, _ = strconv.ParseInt(line[16:], 10, 64)
case strings.HasPrefix(line, statGarbage): case strings.HasPrefix(line, statGarbage):
repoSize.Garbage = com.StrTo(line[9:]).MustInt64() repoSize.Garbage, _ = strconv.ParseInt(line[9:], 10, 64)
case strings.HasPrefix(line, statSizeGarbage): case strings.HasPrefix(line, statSizeGarbage):
repoSize.SizeGarbage = com.StrTo(line[14:]).MustInt64() * 1024 repoSize.SizeGarbage, _ = strconv.ParseInt(line[14:], 10, 64)
repoSize.SizeGarbage *= 1024
} }
} }
return repoSize return repoSize

View File

@ -25,7 +25,6 @@ import (
"code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/util"
"github.com/gliderlabs/ssh" "github.com/gliderlabs/ssh"
"github.com/unknwon/com"
gossh "golang.org/x/crypto/ssh" gossh "golang.org/x/crypto/ssh"
) )
@ -58,13 +57,13 @@ func getExitStatusFromError(err error) int {
} }
func sessionHandler(session ssh.Session) { func sessionHandler(session ssh.Session) {
keyID := session.Context().Value(giteaKeyID).(int64) keyID := fmt.Sprintf("%d", session.Context().Value(giteaKeyID).(int64))
command := session.RawCommand() command := session.RawCommand()
log.Trace("SSH: Payload: %v", command) log.Trace("SSH: Payload: %v", command)
args := []string{"serv", "key-" + com.ToStr(keyID), "--config=" + setting.CustomConf} args := []string{"serv", "key-" + keyID, "--config=" + setting.CustomConf}
log.Trace("SSH: Arguments: %v", args) log.Trace("SSH: Arguments: %v", args)
cmd := exec.Command(setting.AppPath, args...) cmd := exec.Command(setting.AppPath, args...)
cmd.Env = append( cmd.Env = append(

View File

@ -4,7 +4,10 @@
package util package util
import "sort" import (
"sort"
"strings"
)
// Int64Slice attaches the methods of Interface to []int64, sorting in increasing order. // Int64Slice attaches the methods of Interface to []int64, sorting in increasing order.
type Int64Slice []int64 type Int64Slice []int64
@ -36,10 +39,22 @@ func ExistsInSlice(target string, slice []string) bool {
} }
// IsStringInSlice sequential searches if string exists in slice. // IsStringInSlice sequential searches if string exists in slice.
func IsStringInSlice(target string, slice []string) bool { func IsStringInSlice(target string, slice []string, insensitive ...bool) bool {
caseInsensitive := false
if len(insensitive) != 0 && insensitive[0] {
caseInsensitive = true
target = strings.ToLower(target)
}
for i := 0; i < len(slice); i++ { for i := 0; i < len(slice); i++ {
if slice[i] == target { if caseInsensitive {
return true if strings.ToLower(slice[i]) == target {
return true
}
} else {
if slice[i] == target {
return true
}
} }
} }
return false return false

20
modules/util/copy.go Normal file
View File

@ -0,0 +1,20 @@
// Copyright 2020 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package util
import (
"github.com/unknwon/com"
)
// CopyFile copies file from source to target path.
func CopyFile(src, dest string) error {
return com.Copy(src, dest)
}
// CopyDir copy files recursively from source to target directory.
// It returns error when error occurs in underlying functions.
func CopyDir(srcPath, destPath string) error {
return com.CopyDir(srcPath, destPath)
}

View File

@ -20,7 +20,6 @@ import (
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/util"
"github.com/unknwon/com"
"xorm.io/xorm/convert" "xorm.io/xorm/convert"
) )
@ -373,7 +372,7 @@ func EditAuthSourcePost(ctx *context.Context, form auth.AuthenticationForm) {
log.Trace("Authentication changed by admin(%s): %d", ctx.User.Name, source.ID) log.Trace("Authentication changed by admin(%s): %d", ctx.User.Name, source.ID)
ctx.Flash.Success(ctx.Tr("admin.auths.update_success")) ctx.Flash.Success(ctx.Tr("admin.auths.update_success"))
ctx.Redirect(setting.AppSubURL + "/admin/auths/" + com.ToStr(form.ID)) ctx.Redirect(setting.AppSubURL + "/admin/auths/" + fmt.Sprint(form.ID))
} }
// DeleteAuthSource response for deleting an auth source // DeleteAuthSource response for deleting an auth source

View File

@ -14,8 +14,6 @@ import (
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/util"
"github.com/unknwon/com"
) )
const ( const (
@ -114,7 +112,7 @@ func ActivateEmail(ctx *context.Context) {
truefalse := map[string]bool{"1": true, "0": false} truefalse := map[string]bool{"1": true, "0": false}
uid := com.StrTo(ctx.Query("uid")).MustInt64() uid := ctx.QueryInt64("uid")
email := ctx.Query("email") email := ctx.Query("email")
primary, okp := truefalse[ctx.Query("primary")] primary, okp := truefalse[ctx.Query("primary")]
activate, oka := truefalse[ctx.Query("activate")] activate, oka := truefalse[ctx.Query("activate")]

View File

@ -6,13 +6,13 @@
package admin package admin
import ( import (
"strconv"
"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
"github.com/unknwon/com"
) )
const ( const (
@ -50,7 +50,7 @@ func DeleteNotices(ctx *context.Context) {
strs := ctx.QueryStrings("ids[]") strs := ctx.QueryStrings("ids[]")
ids := make([]int64, 0, len(strs)) ids := make([]int64, 0, len(strs))
for i := range strs { for i := range strs {
id := com.StrTo(strs[i]).MustInt64() id, _ := strconv.ParseInt(strs[i], 10, 64)
if id > 0 { if id > 0 {
ids = append(ids, id) ids = append(ids, id)
} }

View File

@ -6,6 +6,8 @@
package admin package admin
import ( import (
"fmt"
"strconv"
"strings" "strings"
"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
@ -17,8 +19,6 @@ import (
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/routers" "code.gitea.io/gitea/routers"
"code.gitea.io/gitea/services/mailer" "code.gitea.io/gitea/services/mailer"
"github.com/unknwon/com"
) )
const ( const (
@ -92,8 +92,9 @@ func NewUserPost(ctx *context.Context, form auth.AdminCreateUserForm) {
if len(form.LoginType) > 0 { if len(form.LoginType) > 0 {
fields := strings.Split(form.LoginType, "-") fields := strings.Split(form.LoginType, "-")
if len(fields) == 2 { if len(fields) == 2 {
u.LoginType = models.LoginType(com.StrTo(fields[0]).MustInt()) lType, _ := strconv.ParseInt(fields[0], 10, 0)
u.LoginSource = com.StrTo(fields[1]).MustInt64() u.LoginType = models.LoginType(lType)
u.LoginSource, _ = strconv.ParseInt(fields[1], 10, 64)
u.LoginName = form.LoginName u.LoginName = form.LoginName
} }
} }
@ -154,7 +155,7 @@ func NewUserPost(ctx *context.Context, form auth.AdminCreateUserForm) {
} }
ctx.Flash.Success(ctx.Tr("admin.users.new_success", u.Name)) ctx.Flash.Success(ctx.Tr("admin.users.new_success", u.Name))
ctx.Redirect(setting.AppSubURL + "/admin/users/" + com.ToStr(u.ID)) ctx.Redirect(setting.AppSubURL + "/admin/users/" + fmt.Sprint(u.ID))
} }
func prepareUserInfo(ctx *context.Context) *models.User { func prepareUserInfo(ctx *context.Context) *models.User {
@ -220,12 +221,12 @@ func EditUserPost(ctx *context.Context, form auth.AdminEditUserForm) {
fields := strings.Split(form.LoginType, "-") fields := strings.Split(form.LoginType, "-")
if len(fields) == 2 { if len(fields) == 2 {
loginType := models.LoginType(com.StrTo(fields[0]).MustInt()) loginType, _ := strconv.ParseInt(fields[0], 10, 0)
loginSource := com.StrTo(fields[1]).MustInt64() loginSource, _ := strconv.ParseInt(fields[1], 10, 64)
if u.LoginSource != loginSource { if u.LoginSource != loginSource {
u.LoginSource = loginSource u.LoginSource = loginSource
u.LoginType = loginType u.LoginType = models.LoginType(loginType)
} }
} }

View File

@ -15,8 +15,6 @@ import (
"code.gitea.io/gitea/modules/convert" "code.gitea.io/gitea/modules/convert"
api "code.gitea.io/gitea/modules/structs" api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/routers/api/v1/utils" "code.gitea.io/gitea/routers/api/v1/utils"
"github.com/unknwon/com"
) )
// Search search users // Search search users
@ -61,7 +59,7 @@ func Search(ctx *context.APIContext) {
opts := &models.SearchUserOptions{ opts := &models.SearchUserOptions{
Keyword: strings.Trim(ctx.Query("q"), " "), Keyword: strings.Trim(ctx.Query("q"), " "),
UID: com.StrTo(ctx.Query("uid")).MustInt64(), UID: ctx.QueryInt64("uid"),
Type: models.UserTypeIndividual, Type: models.UserTypeIndividual,
ListOptions: listOptions, ListOptions: listOptions,
} }

View File

@ -14,10 +14,9 @@ import (
"code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/convert" "code.gitea.io/gitea/modules/convert"
api "code.gitea.io/gitea/modules/structs" api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/routers/utils" "code.gitea.io/gitea/routers/utils"
"code.gitea.io/gitea/services/webhook" "code.gitea.io/gitea/services/webhook"
"github.com/unknwon/com"
) )
// GetOrgHook get an organization's webhook. If there is an error, write to // GetOrgHook get an organization's webhook. If there is an error, write to
@ -89,11 +88,11 @@ func AddRepoHook(ctx *context.APIContext, form *api.CreateHookOption) {
} }
func issuesHook(events []string, event string) bool { func issuesHook(events []string, event string) bool {
return com.IsSliceContainsStr(events, event) || com.IsSliceContainsStr(events, string(models.HookEventIssues)) return util.IsStringInSlice(event, events, true) || util.IsStringInSlice(string(models.HookEventIssues), events, true)
} }
func pullHook(events []string, event string) bool { func pullHook(events []string, event string) bool {
return com.IsSliceContainsStr(events, event) || com.IsSliceContainsStr(events, string(models.HookEventPullRequest)) return util.IsStringInSlice(event, events, true) || util.IsStringInSlice(string(models.HookEventPullRequest), events, true)
} }
// addHook add the hook specified by `form`, `orgID` and `repoID`. If there is // addHook add the hook specified by `form`, `orgID` and `repoID`. If there is
@ -112,15 +111,15 @@ func addHook(ctx *context.APIContext, form *api.CreateHookOption, orgID, repoID
HookEvent: &models.HookEvent{ HookEvent: &models.HookEvent{
ChooseEvents: true, ChooseEvents: true,
HookEvents: models.HookEvents{ HookEvents: models.HookEvents{
Create: com.IsSliceContainsStr(form.Events, string(models.HookEventCreate)), Create: util.IsStringInSlice(string(models.HookEventCreate), form.Events, true),
Delete: com.IsSliceContainsStr(form.Events, string(models.HookEventDelete)), Delete: util.IsStringInSlice(string(models.HookEventDelete), form.Events, true),
Fork: com.IsSliceContainsStr(form.Events, string(models.HookEventFork)), Fork: util.IsStringInSlice(string(models.HookEventFork), form.Events, true),
Issues: issuesHook(form.Events, "issues_only"), Issues: issuesHook(form.Events, "issues_only"),
IssueAssign: issuesHook(form.Events, string(models.HookEventIssueAssign)), IssueAssign: issuesHook(form.Events, string(models.HookEventIssueAssign)),
IssueLabel: issuesHook(form.Events, string(models.HookEventIssueLabel)), IssueLabel: issuesHook(form.Events, string(models.HookEventIssueLabel)),
IssueMilestone: issuesHook(form.Events, string(models.HookEventIssueMilestone)), IssueMilestone: issuesHook(form.Events, string(models.HookEventIssueMilestone)),
IssueComment: issuesHook(form.Events, string(models.HookEventIssueComment)), IssueComment: issuesHook(form.Events, string(models.HookEventIssueComment)),
Push: com.IsSliceContainsStr(form.Events, string(models.HookEventPush)), Push: util.IsStringInSlice(string(models.HookEventPush), form.Events, true),
PullRequest: pullHook(form.Events, "pull_request_only"), PullRequest: pullHook(form.Events, "pull_request_only"),
PullRequestAssign: pullHook(form.Events, string(models.HookEventPullRequestAssign)), PullRequestAssign: pullHook(form.Events, string(models.HookEventPullRequestAssign)),
PullRequestLabel: pullHook(form.Events, string(models.HookEventPullRequestLabel)), PullRequestLabel: pullHook(form.Events, string(models.HookEventPullRequestLabel)),
@ -128,8 +127,8 @@ func addHook(ctx *context.APIContext, form *api.CreateHookOption, orgID, repoID
PullRequestComment: pullHook(form.Events, string(models.HookEventPullRequestComment)), PullRequestComment: pullHook(form.Events, string(models.HookEventPullRequestComment)),
PullRequestReview: pullHook(form.Events, "pull_request_review"), PullRequestReview: pullHook(form.Events, "pull_request_review"),
PullRequestSync: pullHook(form.Events, string(models.HookEventPullRequestSync)), PullRequestSync: pullHook(form.Events, string(models.HookEventPullRequestSync)),
Repository: com.IsSliceContainsStr(form.Events, string(models.HookEventRepository)), Repository: util.IsStringInSlice(string(models.HookEventRepository), form.Events, true),
Release: com.IsSliceContainsStr(form.Events, string(models.HookEventRelease)), Release: util.IsStringInSlice(string(models.HookEventRelease), form.Events, true),
}, },
BranchFilter: form.BranchFilter, BranchFilter: form.BranchFilter,
}, },
@ -244,18 +243,18 @@ func editHook(ctx *context.APIContext, form *api.EditHookOption, w *models.Webho
w.PushOnly = false w.PushOnly = false
w.SendEverything = false w.SendEverything = false
w.ChooseEvents = true w.ChooseEvents = true
w.Create = com.IsSliceContainsStr(form.Events, string(models.HookEventCreate)) w.Create = util.IsStringInSlice(string(models.HookEventCreate), form.Events, true)
w.Push = com.IsSliceContainsStr(form.Events, string(models.HookEventPush)) w.Push = util.IsStringInSlice(string(models.HookEventPush), form.Events, true)
w.PullRequest = com.IsSliceContainsStr(form.Events, string(models.HookEventPullRequest)) w.PullRequest = util.IsStringInSlice(string(models.HookEventPullRequest), form.Events, true)
w.Create = com.IsSliceContainsStr(form.Events, string(models.HookEventCreate)) w.Create = util.IsStringInSlice(string(models.HookEventCreate), form.Events, true)
w.Delete = com.IsSliceContainsStr(form.Events, string(models.HookEventDelete)) w.Delete = util.IsStringInSlice(string(models.HookEventDelete), form.Events, true)
w.Fork = com.IsSliceContainsStr(form.Events, string(models.HookEventFork)) w.Fork = util.IsStringInSlice(string(models.HookEventFork), form.Events, true)
w.Issues = com.IsSliceContainsStr(form.Events, string(models.HookEventIssues)) w.Issues = util.IsStringInSlice(string(models.HookEventIssues), form.Events, true)
w.IssueComment = com.IsSliceContainsStr(form.Events, string(models.HookEventIssueComment)) w.IssueComment = util.IsStringInSlice(string(models.HookEventIssueComment), form.Events, true)
w.Push = com.IsSliceContainsStr(form.Events, string(models.HookEventPush)) w.Push = util.IsStringInSlice(string(models.HookEventPush), form.Events, true)
w.PullRequest = com.IsSliceContainsStr(form.Events, string(models.HookEventPullRequest)) w.PullRequest = util.IsStringInSlice(string(models.HookEventPullRequest), form.Events, true)
w.Repository = com.IsSliceContainsStr(form.Events, string(models.HookEventRepository)) w.Repository = util.IsStringInSlice(string(models.HookEventRepository), form.Events, true)
w.Release = com.IsSliceContainsStr(form.Events, string(models.HookEventRelease)) w.Release = util.IsStringInSlice(string(models.HookEventRelease), form.Events, true)
w.BranchFilter = form.BranchFilter w.BranchFilter = form.BranchFilter
if err := w.UpdateEvent(); err != nil { if err := w.UpdateEvent(); err != nil {

View File

@ -5,6 +5,7 @@
package routers package routers
import ( import (
"fmt"
"net/http" "net/http"
"os" "os"
"os/exec" "os/exec"
@ -22,7 +23,6 @@ import (
"code.gitea.io/gitea/modules/user" "code.gitea.io/gitea/modules/user"
"code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/util"
"github.com/unknwon/com"
"gopkg.in/ini.v1" "gopkg.in/ini.v1"
) )
@ -294,7 +294,7 @@ func InstallPost(ctx *context.Context, form auth.InstallForm) {
cfg.Section("server").Key("DISABLE_SSH").SetValue("true") cfg.Section("server").Key("DISABLE_SSH").SetValue("true")
} else { } else {
cfg.Section("server").Key("DISABLE_SSH").SetValue("false") cfg.Section("server").Key("DISABLE_SSH").SetValue("false")
cfg.Section("server").Key("SSH_PORT").SetValue(com.ToStr(form.SSHPort)) cfg.Section("server").Key("SSH_PORT").SetValue(fmt.Sprint(form.SSHPort))
} }
if form.LFSRootPath != "" { if form.LFSRootPath != "" {
@ -319,22 +319,22 @@ func InstallPost(ctx *context.Context, form auth.InstallForm) {
} else { } else {
cfg.Section("mailer").Key("ENABLED").SetValue("false") cfg.Section("mailer").Key("ENABLED").SetValue("false")
} }
cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").SetValue(com.ToStr(form.RegisterConfirm)) cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").SetValue(fmt.Sprint(form.RegisterConfirm))
cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").SetValue(com.ToStr(form.MailNotify)) cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").SetValue(fmt.Sprint(form.MailNotify))
cfg.Section("server").Key("OFFLINE_MODE").SetValue(com.ToStr(form.OfflineMode)) cfg.Section("server").Key("OFFLINE_MODE").SetValue(fmt.Sprint(form.OfflineMode))
cfg.Section("picture").Key("DISABLE_GRAVATAR").SetValue(com.ToStr(form.DisableGravatar)) cfg.Section("picture").Key("DISABLE_GRAVATAR").SetValue(fmt.Sprint(form.DisableGravatar))
cfg.Section("picture").Key("ENABLE_FEDERATED_AVATAR").SetValue(com.ToStr(form.EnableFederatedAvatar)) cfg.Section("picture").Key("ENABLE_FEDERATED_AVATAR").SetValue(fmt.Sprint(form.EnableFederatedAvatar))
cfg.Section("openid").Key("ENABLE_OPENID_SIGNIN").SetValue(com.ToStr(form.EnableOpenIDSignIn)) cfg.Section("openid").Key("ENABLE_OPENID_SIGNIN").SetValue(fmt.Sprint(form.EnableOpenIDSignIn))
cfg.Section("openid").Key("ENABLE_OPENID_SIGNUP").SetValue(com.ToStr(form.EnableOpenIDSignUp)) cfg.Section("openid").Key("ENABLE_OPENID_SIGNUP").SetValue(fmt.Sprint(form.EnableOpenIDSignUp))
cfg.Section("service").Key("DISABLE_REGISTRATION").SetValue(com.ToStr(form.DisableRegistration)) cfg.Section("service").Key("DISABLE_REGISTRATION").SetValue(fmt.Sprint(form.DisableRegistration))
cfg.Section("service").Key("ALLOW_ONLY_EXTERNAL_REGISTRATION").SetValue(com.ToStr(form.AllowOnlyExternalRegistration)) cfg.Section("service").Key("ALLOW_ONLY_EXTERNAL_REGISTRATION").SetValue(fmt.Sprint(form.AllowOnlyExternalRegistration))
cfg.Section("service").Key("ENABLE_CAPTCHA").SetValue(com.ToStr(form.EnableCaptcha)) cfg.Section("service").Key("ENABLE_CAPTCHA").SetValue(fmt.Sprint(form.EnableCaptcha))
cfg.Section("service").Key("REQUIRE_SIGNIN_VIEW").SetValue(com.ToStr(form.RequireSignInView)) cfg.Section("service").Key("REQUIRE_SIGNIN_VIEW").SetValue(fmt.Sprint(form.RequireSignInView))
cfg.Section("service").Key("DEFAULT_KEEP_EMAIL_PRIVATE").SetValue(com.ToStr(form.DefaultKeepEmailPrivate)) cfg.Section("service").Key("DEFAULT_KEEP_EMAIL_PRIVATE").SetValue(fmt.Sprint(form.DefaultKeepEmailPrivate))
cfg.Section("service").Key("DEFAULT_ALLOW_CREATE_ORGANIZATION").SetValue(com.ToStr(form.DefaultAllowCreateOrganization)) cfg.Section("service").Key("DEFAULT_ALLOW_CREATE_ORGANIZATION").SetValue(fmt.Sprint(form.DefaultAllowCreateOrganization))
cfg.Section("service").Key("DEFAULT_ENABLE_TIMETRACKING").SetValue(com.ToStr(form.DefaultEnableTimetracking)) cfg.Section("service").Key("DEFAULT_ENABLE_TIMETRACKING").SetValue(fmt.Sprint(form.DefaultEnableTimetracking))
cfg.Section("service").Key("NO_REPLY_ADDRESS").SetValue(com.ToStr(form.NoReplyAddress)) cfg.Section("service").Key("NO_REPLY_ADDRESS").SetValue(fmt.Sprint(form.NoReplyAddress))
cfg.Section("").Key("RUN_MODE").SetValue("prod") cfg.Section("").Key("RUN_MODE").SetValue("prod")

View File

@ -11,8 +11,6 @@ import (
"code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
"github.com/unknwon/com"
) )
const ( const (
@ -70,7 +68,7 @@ func Members(ctx *context.Context) {
// MembersAction response for operation to a member of organization // MembersAction response for operation to a member of organization
func MembersAction(ctx *context.Context) { func MembersAction(ctx *context.Context) {
uid := com.StrTo(ctx.Query("uid")).MustInt64() uid := ctx.QueryInt64("uid")
if uid == 0 { if uid == 0 {
ctx.Redirect(ctx.Org.OrgLink + "/members") ctx.Redirect(ctx.Org.OrgLink + "/members")
return return

View File

@ -16,8 +16,6 @@ import (
"code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/routers/utils" "code.gitea.io/gitea/routers/utils"
"github.com/unknwon/com"
) )
const ( const (
@ -50,7 +48,7 @@ func Teams(ctx *context.Context) {
// TeamsAction response for join, leave, remove, add operations to team // TeamsAction response for join, leave, remove, add operations to team
func TeamsAction(ctx *context.Context) { func TeamsAction(ctx *context.Context) {
uid := com.StrTo(ctx.Query("uid")).MustInt64() uid := ctx.QueryInt64("uid")
if uid == 0 { if uid == 0 {
ctx.Redirect(ctx.Org.OrgLink + "/teams") ctx.Redirect(ctx.Org.OrgLink + "/teams")
return return
@ -155,7 +153,7 @@ func TeamsRepoAction(ctx *context.Context) {
} }
err = ctx.Org.Team.AddRepository(repo) err = ctx.Org.Team.AddRepository(repo)
case "remove": case "remove":
err = ctx.Org.Team.RemoveRepository(com.StrTo(ctx.Query("repoid")).MustInt64()) err = ctx.Org.Team.RemoveRepository(ctx.QueryInt64("repoid"))
case "addall": case "addall":
err = ctx.Org.Team.AddAllRepositories() err = ctx.Org.Team.AddAllRepositories()
case "removeall": case "removeall":

View File

@ -114,7 +114,7 @@ func issues(ctx *context.Context, milestoneID, projectID int64, isPullOption uti
viewType := ctx.Query("type") viewType := ctx.Query("type")
sortType := ctx.Query("sort") sortType := ctx.Query("sort")
types := []string{"all", "your_repositories", "assigned", "created_by", "mentioned"} types := []string{"all", "your_repositories", "assigned", "created_by", "mentioned"}
if !com.IsSliceContainsStr(types, viewType) { if !util.IsStringInSlice(viewType, types, true) {
viewType = "all" viewType = "all"
} }
@ -981,7 +981,7 @@ func NewIssuePost(ctx *context.Context, form auth.CreateIssueForm) {
} }
log.Trace("Issue created: %d/%d", repo.ID, issue.ID) log.Trace("Issue created: %d/%d", repo.ID, issue.ID)
ctx.Redirect(ctx.Repo.RepoLink + "/issues/" + com.ToStr(issue.Index)) ctx.Redirect(ctx.Repo.RepoLink + "/issues/" + fmt.Sprint(issue.Index))
} }
// commentTag returns the CommentTag for a comment in/with the given repo, poster and issue // commentTag returns the CommentTag for a comment in/with the given repo, poster and issue
@ -1061,10 +1061,10 @@ func ViewIssue(ctx *context.Context) {
// Make sure type and URL matches. // Make sure type and URL matches.
if ctx.Params(":type") == "issues" && issue.IsPull { if ctx.Params(":type") == "issues" && issue.IsPull {
ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index)) ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + fmt.Sprint(issue.Index))
return return
} else if ctx.Params(":type") == "pulls" && !issue.IsPull { } else if ctx.Params(":type") == "pulls" && !issue.IsPull {
ctx.Redirect(ctx.Repo.RepoLink + "/issues/" + com.ToStr(issue.Index)) ctx.Redirect(ctx.Repo.RepoLink + "/issues/" + fmt.Sprint(issue.Index))
return return
} }
@ -1411,7 +1411,7 @@ func ViewIssue(ctx *context.Context) {
log.Error("IsProtectedBranch: %v", err) log.Error("IsProtectedBranch: %v", err)
} else if !protected { } else if !protected {
canDelete = true canDelete = true
ctx.Data["DeleteBranchLink"] = ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index) + "/cleanup" ctx.Data["DeleteBranchLink"] = ctx.Repo.RepoLink + "/pulls/" + fmt.Sprint(issue.Index) + "/cleanup"
} }
} }
} }

View File

@ -26,8 +26,6 @@ import (
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/storage" "code.gitea.io/gitea/modules/storage"
"github.com/unknwon/com"
) )
const ( const (
@ -579,7 +577,7 @@ func LFSAutoAssociate(ctx *context.Context) {
} }
var err error var err error
metas[i] = &models.LFSMetaObject{} metas[i] = &models.LFSMetaObject{}
metas[i].Size, err = com.StrTo(oid[idx+1:]).Int64() metas[i].Size, err = strconv.ParseInt(oid[idx+1:], 10, 64)
if err != nil { if err != nil {
ctx.ServerError("LFSAutoAssociate", fmt.Errorf("Illegal oid input: %s %v", oid, err)) ctx.ServerError("LFSAutoAssociate", fmt.Errorf("Illegal oid input: %s %v", oid, err))
return return

View File

@ -31,8 +31,6 @@ import (
"code.gitea.io/gitea/services/gitdiff" "code.gitea.io/gitea/services/gitdiff"
pull_service "code.gitea.io/gitea/services/pull" pull_service "code.gitea.io/gitea/services/pull"
repo_service "code.gitea.io/gitea/services/repository" repo_service "code.gitea.io/gitea/services/repository"
"github.com/unknwon/com"
) )
const ( const (
@ -732,7 +730,7 @@ func UpdatePullRequest(ctx *context.Context) {
// ToDo: add check if maintainers are allowed to change branch ... (need migration & co) // ToDo: add check if maintainers are allowed to change branch ... (need migration & co)
if !allowedUpdate { if !allowedUpdate {
ctx.Flash.Error(ctx.Tr("repo.pulls.update_not_allowed")) ctx.Flash.Error(ctx.Tr("repo.pulls.update_not_allowed"))
ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index)) ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + fmt.Sprint(issue.Index))
return return
} }
@ -752,18 +750,18 @@ func UpdatePullRequest(ctx *context.Context) {
return return
} }
ctx.Flash.Error(flashError) ctx.Flash.Error(flashError)
ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index)) ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + fmt.Sprint(issue.Index))
return return
} }
ctx.Flash.Error(err.Error()) ctx.Flash.Error(err.Error())
ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index)) ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + fmt.Sprint(issue.Index))
return return
} }
time.Sleep(1 * time.Second) time.Sleep(1 * time.Second)
ctx.Flash.Success(ctx.Tr("repo.pulls.update_branch_success")) ctx.Flash.Success(ctx.Tr("repo.pulls.update_branch_success"))
ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index)) ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + fmt.Sprint(issue.Index))
} }
// MergePullRequest response for merging pull request // MergePullRequest response for merging pull request
@ -775,11 +773,11 @@ func MergePullRequest(ctx *context.Context, form auth.MergePullRequestForm) {
if issue.IsClosed { if issue.IsClosed {
if issue.IsPull { if issue.IsPull {
ctx.Flash.Error(ctx.Tr("repo.pulls.is_closed")) ctx.Flash.Error(ctx.Tr("repo.pulls.is_closed"))
ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index)) ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + fmt.Sprint(issue.Index))
return return
} }
ctx.Flash.Error(ctx.Tr("repo.issues.closed_title")) ctx.Flash.Error(ctx.Tr("repo.issues.closed_title"))
ctx.Redirect(ctx.Repo.RepoLink + "/issues/" + com.ToStr(issue.Index)) ctx.Redirect(ctx.Repo.RepoLink + "/issues/" + fmt.Sprint(issue.Index))
return return
} }
@ -792,25 +790,25 @@ func MergePullRequest(ctx *context.Context, form auth.MergePullRequestForm) {
} }
if !allowedMerge { if !allowedMerge {
ctx.Flash.Error(ctx.Tr("repo.pulls.update_not_allowed")) ctx.Flash.Error(ctx.Tr("repo.pulls.update_not_allowed"))
ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index)) ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + fmt.Sprint(issue.Index))
return return
} }
if !pr.CanAutoMerge() { if !pr.CanAutoMerge() {
ctx.Flash.Error(ctx.Tr("repo.pulls.no_merge_not_ready")) ctx.Flash.Error(ctx.Tr("repo.pulls.no_merge_not_ready"))
ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index)) ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + fmt.Sprint(issue.Index))
return return
} }
if pr.HasMerged { if pr.HasMerged {
ctx.Flash.Error(ctx.Tr("repo.pulls.has_merged")) ctx.Flash.Error(ctx.Tr("repo.pulls.has_merged"))
ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index)) ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + fmt.Sprint(issue.Index))
return return
} }
if pr.IsWorkInProgress() { if pr.IsWorkInProgress() {
ctx.Flash.Error(ctx.Tr("repo.pulls.no_merge_wip")) ctx.Flash.Error(ctx.Tr("repo.pulls.no_merge_wip"))
ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index)) ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + fmt.Sprint(pr.Index))
return return
} }
@ -824,14 +822,14 @@ func MergePullRequest(ctx *context.Context, form auth.MergePullRequestForm) {
return return
} else if !isRepoAdmin { } else if !isRepoAdmin {
ctx.Flash.Error(ctx.Tr("repo.pulls.no_merge_not_ready")) ctx.Flash.Error(ctx.Tr("repo.pulls.no_merge_not_ready"))
ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index)) ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + fmt.Sprint(pr.Index))
return return
} }
} }
if ctx.HasError() { if ctx.HasError() {
ctx.Flash.Error(ctx.Data["ErrorMsg"].(string)) ctx.Flash.Error(ctx.Data["ErrorMsg"].(string))
ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index)) ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + fmt.Sprint(pr.Index))
return return
} }
@ -863,14 +861,14 @@ func MergePullRequest(ctx *context.Context, form auth.MergePullRequestForm) {
if !noDeps { if !noDeps {
ctx.Flash.Error(ctx.Tr("repo.issues.dependency.pr_close_blocked")) ctx.Flash.Error(ctx.Tr("repo.issues.dependency.pr_close_blocked"))
ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index)) ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + fmt.Sprint(pr.Index))
return return
} }
if err = pull_service.Merge(pr, ctx.User, ctx.Repo.GitRepo, models.MergeStyle(form.Do), message); err != nil { if err = pull_service.Merge(pr, ctx.User, ctx.Repo.GitRepo, models.MergeStyle(form.Do), message); err != nil {
if models.IsErrInvalidMergeStyle(err) { if models.IsErrInvalidMergeStyle(err) {
ctx.Flash.Error(ctx.Tr("repo.pulls.invalid_merge_option")) ctx.Flash.Error(ctx.Tr("repo.pulls.invalid_merge_option"))
ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index)) ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + fmt.Sprint(pr.Index))
return return
} else if models.IsErrMergeConflicts(err) { } else if models.IsErrMergeConflicts(err) {
conflictError := err.(models.ErrMergeConflicts) conflictError := err.(models.ErrMergeConflicts)
@ -884,7 +882,7 @@ func MergePullRequest(ctx *context.Context, form auth.MergePullRequestForm) {
return return
} }
ctx.Flash.Error(flashError) ctx.Flash.Error(flashError)
ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index)) ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + fmt.Sprint(pr.Index))
return return
} else if models.IsErrRebaseConflicts(err) { } else if models.IsErrRebaseConflicts(err) {
conflictError := err.(models.ErrRebaseConflicts) conflictError := err.(models.ErrRebaseConflicts)
@ -898,17 +896,17 @@ func MergePullRequest(ctx *context.Context, form auth.MergePullRequestForm) {
return return
} }
ctx.Flash.Error(flashError) ctx.Flash.Error(flashError)
ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index)) ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + fmt.Sprint(pr.Index))
return return
} else if models.IsErrMergeUnrelatedHistories(err) { } else if models.IsErrMergeUnrelatedHistories(err) {
log.Debug("MergeUnrelatedHistories error: %v", err) log.Debug("MergeUnrelatedHistories error: %v", err)
ctx.Flash.Error(ctx.Tr("repo.pulls.unrelated_histories")) ctx.Flash.Error(ctx.Tr("repo.pulls.unrelated_histories"))
ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index)) ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + fmt.Sprint(pr.Index))
return return
} else if git.IsErrPushOutOfDate(err) { } else if git.IsErrPushOutOfDate(err) {
log.Debug("MergePushOutOfDate error: %v", err) log.Debug("MergePushOutOfDate error: %v", err)
ctx.Flash.Error(ctx.Tr("repo.pulls.merge_out_of_date")) ctx.Flash.Error(ctx.Tr("repo.pulls.merge_out_of_date"))
ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index)) ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + fmt.Sprint(pr.Index))
return return
} else if git.IsErrPushRejected(err) { } else if git.IsErrPushRejected(err) {
log.Debug("MergePushRejected error: %v", err) log.Debug("MergePushRejected error: %v", err)
@ -928,7 +926,7 @@ func MergePullRequest(ctx *context.Context, form auth.MergePullRequestForm) {
} }
ctx.Flash.Error(flashError) ctx.Flash.Error(flashError)
} }
ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index)) ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + fmt.Sprint(pr.Index))
return return
} }
ctx.ServerError("Merge", err) ctx.ServerError("Merge", err)
@ -941,7 +939,7 @@ func MergePullRequest(ctx *context.Context, form auth.MergePullRequestForm) {
} }
log.Trace("Pull request merged: %d", pr.ID) log.Trace("Pull request merged: %d", pr.ID)
ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index)) ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + fmt.Sprint(pr.Index))
} }
func stopTimerIfAvailable(user *models.User, issue *models.Issue) error { func stopTimerIfAvailable(user *models.User, issue *models.Issue) error {
@ -1052,7 +1050,7 @@ func CompareAndPullRequestPost(ctx *context.Context, form auth.CreateIssueForm)
} }
ctx.Flash.Error(flashError) ctx.Flash.Error(flashError)
} }
ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pullIssue.Index)) ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + fmt.Sprint(pullIssue.Index))
return return
} }
ctx.ServerError("NewPullRequest", err) ctx.ServerError("NewPullRequest", err)
@ -1060,7 +1058,7 @@ func CompareAndPullRequestPost(ctx *context.Context, form auth.CreateIssueForm)
} }
log.Trace("Pull request created: %d/%d", repo.ID, pullIssue.ID) log.Trace("Pull request created: %d/%d", repo.ID, pullIssue.ID)
ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pullIssue.Index)) ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + fmt.Sprint(pullIssue.Index))
} }
// TriggerTask response for a trigger task request // TriggerTask response for a trigger task request
@ -1159,7 +1157,7 @@ func CleanUpPullRequest(ctx *context.Context) {
defer func() { defer func() {
ctx.JSON(200, map[string]interface{}{ ctx.JSON(200, map[string]interface{}{
"redirect": pr.BaseRepo.Link() + "/pulls/" + com.ToStr(issue.Index), "redirect": pr.BaseRepo.Link() + "/pulls/" + fmt.Sprint(issue.Index),
}) })
}() }()

View File

@ -20,9 +20,8 @@ import (
"code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs" api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/services/webhook" "code.gitea.io/gitea/services/webhook"
"github.com/unknwon/com"
) )
const ( const (
@ -100,7 +99,7 @@ func getOrgRepoCtx(ctx *context.Context) (*orgRepoCtx, error) {
func checkHookType(ctx *context.Context) string { func checkHookType(ctx *context.Context) string {
hookType := strings.ToLower(ctx.Params(":type")) hookType := strings.ToLower(ctx.Params(":type"))
if !com.IsSliceContainsStr(setting.Webhook.Types, hookType) { if !util.IsStringInSlice(hookType, setting.Webhook.Types, true) {
ctx.NotFound("checkHookType", nil) ctx.NotFound("checkHookType", nil)
return "" return ""
} }

View File

@ -12,9 +12,9 @@ import (
"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/test" "code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/modules/util"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/unknwon/com"
) )
var queueMutex sync.Mutex var queueMutex sync.Mutex
@ -144,7 +144,9 @@ func TestArchive_Basic(t *testing.T) {
for _, req := range inFlight { for _, req := range inFlight {
assert.True(t, req.IsComplete()) assert.True(t, req.IsComplete())
assert.True(t, com.IsExist(req.GetArchivePath())) exist, err := util.IsExist(req.GetArchivePath())
assert.NoError(t, err)
assert.True(t, exist)
} }
arbitraryReq := inFlight[0] arbitraryReq := inFlight[0]

View File

@ -8,6 +8,7 @@ import (
"context" "context"
"fmt" "fmt"
"net/url" "net/url"
"strconv"
"strings" "strings"
"time" "time"
@ -22,8 +23,6 @@ import (
"code.gitea.io/gitea/modules/sync" "code.gitea.io/gitea/modules/sync"
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/util"
"github.com/unknwon/com"
) )
// mirrorQueue holds an UniqueQueue object of the mirror // mirrorQueue holds an UniqueQueue object of the mirror
@ -396,11 +395,11 @@ func syncMirror(repoID string) {
}() }()
mirrorQueue.Remove(repoID) mirrorQueue.Remove(repoID)
m, err := models.GetMirrorByRepoID(com.StrTo(repoID).MustInt64()) id, _ := strconv.ParseInt(repoID, 10, 64)
m, err := models.GetMirrorByRepoID(id)
if err != nil { if err != nil {
log.Error("GetMirrorByRepoID [%s]: %v", repoID, err) log.Error("GetMirrorByRepoID [%s]: %v", repoID, err)
return return
} }
log.Trace("SyncMirrors [repo: %-v]: Running Sync", m.Repo) log.Trace("SyncMirrors [repo: %-v]: Running Sync", m.Repo)

View File

@ -21,8 +21,6 @@ import (
"code.gitea.io/gitea/modules/queue" "code.gitea.io/gitea/modules/queue"
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/util"
"github.com/unknwon/com"
) )
// prQueue represents a queue to handle update pull request tests // prQueue represents a queue to handle update pull request tests
@ -203,14 +201,13 @@ func InitializePullRequests(ctx context.Context) {
// handle passed PR IDs and test the PRs // handle passed PR IDs and test the PRs
func handle(data ...queue.Data) { func handle(data ...queue.Data) {
for _, datum := range data { for _, datum := range data {
prID := datum.(string) id, _ := strconv.ParseInt(datum.(string), 10, 64)
id := com.StrTo(prID).MustInt64()
log.Trace("Testing PR ID %d from the pull requests patch checking queue", id) log.Trace("Testing PR ID %d from the pull requests patch checking queue", id)
pr, err := models.GetPullRequestByID(id) pr, err := models.GetPullRequestByID(id)
if err != nil { if err != nil {
log.Error("GetPullRequestByID[%s]: %v", prID, err) log.Error("GetPullRequestByID[%s]: %v", datum, err)
continue continue
} else if pr.HasMerged { } else if pr.HasMerged {
continue continue

View File

@ -15,7 +15,6 @@ import (
"code.gitea.io/gitea/modules/queue" "code.gitea.io/gitea/modules/queue"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/unknwon/com"
) )
func TestPullRequest_AddToTaskQueue(t *testing.T) { func TestPullRequest_AddToTaskQueue(t *testing.T) {
@ -25,8 +24,7 @@ func TestPullRequest_AddToTaskQueue(t *testing.T) {
q, err := queue.NewChannelUniqueQueue(func(data ...queue.Data) { q, err := queue.NewChannelUniqueQueue(func(data ...queue.Data) {
for _, datum := range data { for _, datum := range data {
prID := datum.(string) id, _ := strconv.ParseInt(datum.(string), 10, 64)
id := com.StrTo(prID).MustInt64()
idChan <- id idChan <- id
} }
}, queue.ChannelUniqueQueueConfiguration{ }, queue.ChannelUniqueQueueConfiguration{

View File

@ -21,8 +21,6 @@ import (
"code.gitea.io/gitea/modules/notification" "code.gitea.io/gitea/modules/notification"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
issue_service "code.gitea.io/gitea/services/issue" issue_service "code.gitea.io/gitea/services/issue"
"github.com/unknwon/com"
) )
// NewPullRequest creates new pull request with labels for repository. // NewPullRequest creates new pull request with labels for repository.
@ -326,7 +324,7 @@ func checkIfPRContentChanged(pr *models.PullRequest, oldCommitID, newCommitID st
defer headGitRepo.Close() defer headGitRepo.Close()
// Add a temporary remote. // Add a temporary remote.
tmpRemote := "checkIfPRContentChanged-" + com.ToStr(time.Now().UnixNano()) tmpRemote := "checkIfPRContentChanged-" + fmt.Sprint(time.Now().UnixNano())
if err = headGitRepo.AddRemote(tmpRemote, pr.BaseRepo.RepoPath(), true); err != nil { if err = headGitRepo.AddRemote(tmpRemote, pr.BaseRepo.RepoPath(), true); err != nil {
return false, fmt.Errorf("AddRemote: %s/%s-%s: %v", pr.HeadRepo.OwnerName, pr.HeadRepo.Name, tmpRemote, err) return false, fmt.Errorf("AddRemote: %s/%s-%s: %v", pr.HeadRepo.OwnerName, pr.HeadRepo.Name, tmpRemote, err)
} }

View File

@ -10,8 +10,6 @@ import (
"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/notification" "code.gitea.io/gitea/modules/notification"
"code.gitea.io/gitea/modules/sync" "code.gitea.io/gitea/modules/sync"
"github.com/unknwon/com"
) )
// repoWorkingPool represents a working pool to order the parallel changes to the same repository // repoWorkingPool represents a working pool to order the parallel changes to the same repository
@ -30,12 +28,12 @@ func TransferOwnership(doer, newOwner *models.User, repo *models.Repository, tea
oldOwner := repo.Owner oldOwner := repo.Owner
repoWorkingPool.CheckIn(com.ToStr(repo.ID)) repoWorkingPool.CheckIn(fmt.Sprint(repo.ID))
if err := models.TransferOwnership(doer, newOwner.Name, repo); err != nil { if err := models.TransferOwnership(doer, newOwner.Name, repo); err != nil {
repoWorkingPool.CheckOut(com.ToStr(repo.ID)) repoWorkingPool.CheckOut(fmt.Sprint(repo.ID))
return err return err
} }
repoWorkingPool.CheckOut(com.ToStr(repo.ID)) repoWorkingPool.CheckOut(fmt.Sprint(repo.ID))
newRepo, err := models.GetRepositoryByID(repo.ID) newRepo, err := models.GetRepositoryByID(repo.ID)
if err != nil { if err != nil {
@ -61,12 +59,12 @@ func ChangeRepositoryName(doer *models.User, repo *models.Repository, newRepoNam
// repo so that we can atomically rename the repo path and updates the // repo so that we can atomically rename the repo path and updates the
// local copy's origin accordingly. // local copy's origin accordingly.
repoWorkingPool.CheckIn(com.ToStr(repo.ID)) repoWorkingPool.CheckIn(fmt.Sprint(repo.ID))
if err := models.ChangeRepositoryName(doer, repo, newRepoName); err != nil { if err := models.ChangeRepositoryName(doer, repo, newRepoName); err != nil {
repoWorkingPool.CheckOut(com.ToStr(repo.ID)) repoWorkingPool.CheckOut(fmt.Sprint(repo.ID))
return err return err
} }
repoWorkingPool.CheckOut(com.ToStr(repo.ID)) repoWorkingPool.CheckOut(fmt.Sprint(repo.ID))
notification.NotifyRenameRepository(doer, repo, oldRepoName) notification.NotifyRenameRepository(doer, repo, oldRepoName)

View File

@ -11,9 +11,9 @@ import (
"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/notification" "code.gitea.io/gitea/modules/notification"
"code.gitea.io/gitea/modules/notification/action" "code.gitea.io/gitea/modules/notification/action"
"code.gitea.io/gitea/modules/util"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/unknwon/com"
) )
var notifySync sync.Once var notifySync sync.Once
@ -37,8 +37,12 @@ func TestTransferOwnership(t *testing.T) {
transferredRepo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) transferredRepo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository)
assert.EqualValues(t, 2, transferredRepo.OwnerID) assert.EqualValues(t, 2, transferredRepo.OwnerID)
assert.False(t, com.IsExist(models.RepoPath("user3", "repo3"))) exist, err := util.IsExist(models.RepoPath("user3", "repo3"))
assert.True(t, com.IsExist(models.RepoPath("user2", "repo3"))) assert.NoError(t, err)
assert.False(t, exist)
exist, err = util.IsExist(models.RepoPath("user2", "repo3"))
assert.NoError(t, err)
assert.True(t, exist)
models.AssertExistsAndLoadBean(t, &models.Action{ models.AssertExistsAndLoadBean(t, &models.Action{
OpType: models.ActionTransferRepo, OpType: models.ActionTransferRepo,
ActUserID: 2, ActUserID: 2,

View File

@ -12,6 +12,7 @@ import (
"net" "net"
"net/http" "net/http"
"net/url" "net/url"
"strconv"
"strings" "strings"
"sync" "sync"
"time" "time"
@ -21,7 +22,6 @@ import (
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
"github.com/gobwas/glob" "github.com/gobwas/glob"
"github.com/unknwon/com"
) )
// Deliver deliver hook task // Deliver deliver hook task
@ -201,7 +201,7 @@ func DeliverHooks(ctx context.Context) {
log.Trace("DeliverHooks [repo_id: %v]", repoIDStr) log.Trace("DeliverHooks [repo_id: %v]", repoIDStr)
hookQueue.Remove(repoIDStr) hookQueue.Remove(repoIDStr)
repoID, err := com.StrTo(repoIDStr).Int64() repoID, err := strconv.ParseInt(repoIDStr, 10, 64)
if err != nil { if err != nil {
log.Error("Invalid repo ID: %s", repoIDStr) log.Error("Invalid repo ID: %s", repoIDStr)
continue continue

View File

@ -17,8 +17,6 @@ import (
repo_module "code.gitea.io/gitea/modules/repository" repo_module "code.gitea.io/gitea/modules/repository"
"code.gitea.io/gitea/modules/sync" "code.gitea.io/gitea/modules/sync"
"code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/util"
"github.com/unknwon/com"
) )
var ( var (
@ -88,8 +86,8 @@ func updateWikiPage(doer *models.User, repo *models.Repository, oldWikiName, new
if err = nameAllowed(newWikiName); err != nil { if err = nameAllowed(newWikiName); err != nil {
return err return err
} }
wikiWorkingPool.CheckIn(com.ToStr(repo.ID)) wikiWorkingPool.CheckIn(fmt.Sprint(repo.ID))
defer wikiWorkingPool.CheckOut(com.ToStr(repo.ID)) defer wikiWorkingPool.CheckOut(fmt.Sprint(repo.ID))
if err = InitWiki(repo); err != nil { if err = InitWiki(repo); err != nil {
return fmt.Errorf("InitWiki: %v", err) return fmt.Errorf("InitWiki: %v", err)
@ -242,8 +240,8 @@ func EditWikiPage(doer *models.User, repo *models.Repository, oldWikiName, newWi
// DeleteWikiPage deletes a wiki page identified by its path. // DeleteWikiPage deletes a wiki page identified by its path.
func DeleteWikiPage(doer *models.User, repo *models.Repository, wikiName string) (err error) { func DeleteWikiPage(doer *models.User, repo *models.Repository, wikiName string) (err error) {
wikiWorkingPool.CheckIn(com.ToStr(repo.ID)) wikiWorkingPool.CheckIn(fmt.Sprint(repo.ID))
defer wikiWorkingPool.CheckOut(com.ToStr(repo.ID)) defer wikiWorkingPool.CheckOut(fmt.Sprint(repo.ID))
if err = InitWiki(repo); err != nil { if err = InitWiki(repo); err != nil {
return fmt.Errorf("InitWiki: %v", err) return fmt.Errorf("InitWiki: %v", err)