format with gofumpt (#18184)

* gofumpt -w -l .

* gofumpt -w -l -extra .

* Add linter

* manual fix

* change make fmt
This commit is contained in:
6543 2022-01-20 18:46:10 +01:00 committed by GitHub
parent 1d98d205f5
commit 54e9ee37a7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
423 changed files with 1585 additions and 1758 deletions

View File

@ -17,6 +17,7 @@ linters:
- bidichk
- ineffassign
- revive
- gofumpt
enable-all: false
disable-all: true
fast: false
@ -57,6 +58,9 @@ linters-settings:
- name: errorf
- name: duplicated-imports
- name: modifies-value-receiver
gofumpt:
extra-rules: true
lang-version: 1.16
issues:
exclude-rules:

View File

@ -231,8 +231,10 @@ clean:
.PHONY: fmt
fmt:
@echo "Running gitea-fmt(with gofmt)..."
@$(GO) run build/code-batch-process.go gitea-fmt -s -w '{file-list}'
@hash xgogofumpt > /dev/null 2>&1; if [ $$? -ne 0 ]; then \
$(GO) install mvdan.cc/gofumpt@latest; \
fi
gofumpt -w -l -extra -lang 1.16 .
.PHONY: vet
vet:

View File

@ -136,7 +136,7 @@ func (fc *fileCollector) collectFiles() (res [][]string, err error) {
}
// substArgFiles expands the {file-list} to a real file list for commands
func substArgFiles(args []string, files []string) []string {
func substArgFiles(args, files []string) []string {
for i, s := range args {
if s == "{file-list}" {
newArgs := append(args[:i], files...)

View File

@ -20,8 +20,10 @@ var importPackageGroupOrders = map[string]int{
var errInvalidCommentBetweenImports = errors.New("comments between imported packages are invalid, please move comments to the end of the package line")
var importBlockBegin = []byte("\nimport (\n")
var importBlockEnd = []byte("\n)")
var (
importBlockBegin = []byte("\nimport (\n")
importBlockEnd = []byte("\n)")
)
type importLineParsed struct {
group string
@ -59,8 +61,10 @@ func parseImportLine(line string) (*importLineParsed, error) {
return il, nil
}
type importLineGroup []*importLineParsed
type importLineGroupMap map[string]importLineGroup
type (
importLineGroup []*importLineParsed
importLineGroupMap map[string]importLineGroup
)
func formatGoImports(contentBytes []byte) ([]byte, error) {
p1 := bytes.Index(contentBytes, importBlockBegin)
@ -177,7 +181,7 @@ func FormatGoImports(file string) error {
if bytes.Equal(contentBytes, formattedBytes) {
return nil
}
f, err = os.OpenFile(file, os.O_TRUNC|os.O_WRONLY, 0644)
f, err = os.OpenFile(file, os.O_TRUNC|os.O_WRONLY, 0o644)
if err != nil {
return err
}

View File

@ -20,7 +20,7 @@ import (
"github.com/shurcooL/vfsgen"
)
func needsUpdate(dir string, filename string) (bool, []byte) {
func needsUpdate(dir, filename string) (bool, []byte) {
needRegen := false
_, err := os.Stat(filename)
if err != nil {
@ -50,7 +50,6 @@ func needsUpdate(dir string, filename string) (bool, []byte) {
newHash := hasher.Sum([]byte{})
if bytes.Compare(oldHash, newHash) != 0 {
return true, newHash
}
@ -87,5 +86,5 @@ func main() {
if err != nil {
log.Fatalf("%v\n", err)
}
_ = os.WriteFile(filename+".hash", newHash, 0666)
_ = os.WriteFile(filename+".hash", newHash, 0o666)
}

View File

@ -30,9 +30,7 @@ const (
maxUnicodeVersion = 12
)
var (
flagOut = flag.String("o", "modules/emoji/emoji_data.go", "out")
)
var flagOut = flag.String("o", "modules/emoji/emoji_data.go", "out")
// Gemoji is a set of emoji data.
type Gemoji []Emoji
@ -68,7 +66,7 @@ func main() {
}
// write
err = os.WriteFile(*flagOut, buf, 0644)
err = os.WriteFile(*flagOut, buf, 0o644)
if err != nil {
log.Fatal(err)
}
@ -109,7 +107,7 @@ func generate() ([]byte, error) {
return nil, err
}
var skinTones = make(map[string]string)
skinTones := make(map[string]string)
skinTones["\U0001f3fb"] = "Light Skin Tone"
skinTones["\U0001f3fc"] = "Medium-Light Skin Tone"
@ -158,7 +156,7 @@ func generate() ([]byte, error) {
// write a JSON file to use with tribute (write before adding skin tones since we can't support them there yet)
file, _ := json.Marshal(data)
_ = os.WriteFile("assets/emoji.json", file, 0644)
_ = os.WriteFile("assets/emoji.json", file, 0o644)
// Add skin tones to emoji that support it
var (

View File

@ -34,7 +34,6 @@ func main() {
flag.Parse()
file, err := os.CreateTemp(os.TempDir(), prefix)
if err != nil {
log.Fatalf("Failed to create temp file. %s", err)
}
@ -65,7 +64,6 @@ func main() {
}
gz, err := gzip.NewReader(file)
if err != nil {
log.Fatalf("Failed to gunzip the archive. %s", err)
}
@ -96,7 +94,6 @@ func main() {
}
out, err := os.Create(path.Join(destination, strings.TrimSuffix(filepath.Base(hdr.Name), ".gitignore")))
if err != nil {
log.Fatalf("Failed to create new file. %s", err)
}
@ -119,7 +116,7 @@ func main() {
}
// Write data to dst
dst = path.Join(destination, dst)
err = os.WriteFile(dst, data, 0644)
err = os.WriteFile(dst, data, 0o644)
if err != nil {
log.Fatalf("Failed to write new file. %s", err)
}

View File

@ -34,7 +34,6 @@ func main() {
flag.Parse()
file, err := os.CreateTemp(os.TempDir(), prefix)
if err != nil {
log.Fatalf("Failed to create temp file. %s", err)
}
@ -66,7 +65,6 @@ func main() {
}
gz, err := gzip.NewReader(file)
if err != nil {
log.Fatalf("Failed to gunzip the archive. %s", err)
}
@ -100,7 +98,6 @@ func main() {
continue
}
out, err := os.Create(path.Join(destination, strings.TrimSuffix(filepath.Base(hdr.Name), ".txt")))
if err != nil {
log.Fatalf("Failed to create new file. %s", err)
}

View File

@ -22,7 +22,7 @@ import (
"golang.org/x/tools/cover"
)
func mergeProfiles(p *cover.Profile, merge *cover.Profile) {
func mergeProfiles(p, merge *cover.Profile) {
if p.Mode != merge.Mode {
log.Fatalf("cannot merge profiles with different modes")
}

View File

@ -525,7 +525,7 @@ func runCreateUser(c *cli.Context) error {
}
// always default to true
var changePassword = true
changePassword := true
// If this is the first user being created.
// Take it as the admin and don't force a password update.
@ -577,7 +577,6 @@ func runListUsers(c *cli.Context) error {
}
users, err := user_model.GetAllUsers()
if err != nil {
return err
}
@ -601,7 +600,6 @@ func runListUsers(c *cli.Context) error {
w.Flush()
return nil
}
func runDeleteUser(c *cli.Context) error {
@ -826,7 +824,6 @@ func runUpdateOauth(c *cli.Context) error {
if c.IsSet("required-claim-name") {
oAuth2Config.RequiredClaimName = c.String("required-claim-name")
}
if c.IsSet("required-claim-value") {
oAuth2Config.RequiredClaimValue = c.String("required-claim-value")
@ -843,7 +840,7 @@ func runUpdateOauth(c *cli.Context) error {
}
// update custom URL mapping
var customURLMapping = &oauth2.CustomURLMapping{}
customURLMapping := &oauth2.CustomURLMapping{}
if oAuth2Config.CustomURLMapping != nil {
customURLMapping.TokenURL = oAuth2Config.CustomURLMapping.TokenURL
@ -926,7 +923,7 @@ func runAddSMTP(c *cli.Context) error {
if !c.IsSet("port") {
return errors.New("port must be set")
}
var active = true
active := true
if c.IsSet("active") {
active = c.BoolT("active")
}
@ -994,7 +991,6 @@ func runListAuth(c *cli.Context) error {
}
authSources, err := auth.Sources()
if err != nil {
return err
}

View File

@ -17,12 +17,12 @@ import (
func TestAddLdapBindDn(t *testing.T) {
// Mock cli functions to do not exit on error
var osExiter = cli.OsExiter
osExiter := cli.OsExiter
defer func() { cli.OsExiter = osExiter }()
cli.OsExiter = func(code int) {}
// Test cases
var cases = []struct {
cases := []struct {
args []string
source *auth.Source
errMsg string
@ -243,12 +243,12 @@ func TestAddLdapBindDn(t *testing.T) {
func TestAddLdapSimpleAuth(t *testing.T) {
// Mock cli functions to do not exit on error
var osExiter = cli.OsExiter
osExiter := cli.OsExiter
defer func() { cli.OsExiter = osExiter }()
cli.OsExiter = func(code int) {}
// Test cases
var cases = []struct {
cases := []struct {
args []string
authSource *auth.Source
errMsg string
@ -474,12 +474,12 @@ func TestAddLdapSimpleAuth(t *testing.T) {
func TestUpdateLdapBindDn(t *testing.T) {
// Mock cli functions to do not exit on error
var osExiter = cli.OsExiter
osExiter := cli.OsExiter
defer func() { cli.OsExiter = osExiter }()
cli.OsExiter = func(code int) {}
// Test cases
var cases = []struct {
cases := []struct {
args []string
id int64
existingAuthSource *auth.Source
@ -907,12 +907,12 @@ func TestUpdateLdapBindDn(t *testing.T) {
func TestUpdateLdapSimpleAuth(t *testing.T) {
// Mock cli functions to do not exit on error
var osExiter = cli.OsExiter
osExiter := cli.OsExiter
defer func() { cli.OsExiter = osExiter }()
cli.OsExiter = func(code int) {}
// Test cases
var cases = []struct {
cases := []struct {
args []string
id int64
existingAuthSource *auth.Source
@ -1161,7 +1161,6 @@ func TestUpdateLdapSimpleAuth(t *testing.T) {
authSource: &auth.Source{
Type: auth.DLDAP,
Cfg: &ldap.Source{
AttributeMail: "mail",
},
},

View File

@ -180,7 +180,7 @@ func runCert(c *cli.Context) error {
}
log.Println("Written cert.pem")
keyOut, err := os.OpenFile("key.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
keyOut, err := os.OpenFile("key.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)
if err != nil {
log.Fatalf("Failed to open key.pem for writing: %v", err)
}

View File

@ -121,7 +121,6 @@ func runRecreateTable(ctx *cli.Context) error {
}
return recreateTables(x)
})
}
func runDoctor(ctx *cli.Context) error {

View File

@ -370,7 +370,7 @@ func runDump(ctx *cli.Context) error {
fatal("Failed to save %s: %v", fileName, err)
}
if err := os.Chmod(fileName, 0600); err != nil {
if err := os.Chmod(fileName, 0o600); err != nil {
log.Info("Can't change file access permissions mask to 0600: %v", err)
}
}

View File

@ -107,7 +107,7 @@ func runDumpRepository(ctx *cli.Context) error {
}
serviceType = convert.ToGitServiceType(serviceStr)
var opts = base.MigrateOptions{
opts := base.MigrateOptions{
GitServiceType: serviceType,
CloneAddr: cloneAddr,
AuthUsername: ctx.String("auth_username"),

View File

@ -109,7 +109,6 @@ type asset struct {
}
func initEmbeddedExtractor(c *cli.Context) error {
// Silence the console logger
log.DelNamedLogger("console")
log.DelNamedLogger(log.DEFAULT)
@ -260,7 +259,7 @@ func extractAsset(d string, a asset, overwrite, rename bool) error {
return fmt.Errorf("%s: %v", dir, err)
}
perms := os.ModePerm & 0666
perms := os.ModePerm & 0o666
fi, err := os.Lstat(dest)
if err != nil {
@ -296,7 +295,7 @@ func extractAsset(d string, a asset, overwrite, rename bool) error {
}
func buildAssetList(sec *section, globs []glob.Glob, c *cli.Context) []asset {
var results = make([]asset, 0, 64)
results := make([]asset, 0, 64)
for _, name := range sec.Names() {
if isdir, err := sec.IsDir(name); !isdir && err == nil {
if sec.Path == "public" &&
@ -307,9 +306,11 @@ func buildAssetList(sec *section, globs []glob.Glob, c *cli.Context) []asset {
matchName := sec.Path + "/" + name
for _, g := range globs {
if g.Match(matchName) {
results = append(results, asset{Section: sec,
results = append(results, asset{
Section: sec,
Name: name,
Path: sec.Path + "/" + name})
Path: sec.Path + "/" + name,
})
break
}
}

View File

@ -58,7 +58,8 @@ var (
Name: "timeout",
Value: 60 * time.Second,
Usage: "Timeout for the flushing process",
}, cli.BoolFlag{
},
cli.BoolFlag{
Name: "non-blocking",
Usage: "Set to true to not wait for flush to complete before returning",
},

View File

@ -71,8 +71,7 @@ func runHTTPRedirector() {
http.Redirect(w, r, target, http.StatusTemporaryRedirect)
})
var err = runHTTP("tcp", source, "HTTP Redirector", handler)
err := runHTTP("tcp", source, "HTTP Redirector", handler)
if err != nil {
log.Fatal("Failed to start port redirection: %v", err)
}

View File

@ -17,7 +17,6 @@ import (
)
func runLetsEncrypt(listenAddr, domain, directory, email string, m http.Handler) error {
// If HTTP Challenge enabled, needs to be serving on port 80. For TLSALPN needs 443.
// Due to docker port mapping this can't be checked programmatically
// TODO: these are placeholders until we add options for each in settings with appropriate warning
@ -77,7 +76,7 @@ func runLetsEncrypt(listenAddr, domain, directory, email string, m http.Handler)
go func() {
log.Info("Running Let's Encrypt handler on %s", setting.HTTPAddr+":"+setting.PortToRedirect)
// all traffic coming into HTTP will be redirect to HTTPS automatically (LE HTTP-01 validation happens here)
var err = runHTTP("tcp", setting.HTTPAddr+":"+setting.PortToRedirect, "Let's Encrypt HTTP Challenge", myACME.HTTPChallengeHandler(http.HandlerFunc(runLetsEncryptFallbackHandler)))
err := runHTTP("tcp", setting.HTTPAddr+":"+setting.PortToRedirect, "Let's Encrypt HTTP Challenge", myACME.HTTPChallengeHandler(http.HandlerFunc(runLetsEncryptFallbackHandler)))
if err != nil {
log.Fatal("Failed to start the Let's Encrypt handler on port %s: %v", setting.PortToRedirect, err)
}

View File

@ -66,7 +66,7 @@ func generate(name string) error {
return err
}
path := filepath.Join(fixturesDir, name+".yml")
if err := os.WriteFile(path, []byte(data), 0644); err != nil {
if err := os.WriteFile(path, []byte(data), 0o644); err != nil {
return fmt.Errorf("%s: %+v", path, err)
}
fmt.Printf("%s created.\n", path)

View File

@ -160,7 +160,7 @@ func runPR() {
}
func main() {
var runPRFlag = flag.Bool("run", false, "Run the PR code")
runPRFlag := flag.Bool("run", false, "Run the PR code")
flag.Parse()
if *runPRFlag {
runPR()
@ -242,11 +242,11 @@ func main() {
// Copy this file if not exist
if _, err := os.Stat(codeFilePath); os.IsNotExist(err) {
err = os.MkdirAll(filepath.Dir(codeFilePath), 0755)
err = os.MkdirAll(filepath.Dir(codeFilePath), 0o755)
if err != nil {
log.Fatalf("Failed to duplicate this code file in PR : %v", err)
}
err = os.WriteFile(codeFilePath, dat, 0644)
err = os.WriteFile(codeFilePath, dat, 0o644)
if err != nil {
log.Fatalf("Failed to duplicate this code file in PR : %v", err)
}
@ -256,6 +256,7 @@ func main() {
// Start with integration test
runCmd("go", "run", "-mod", "vendor", "-tags", "sqlite sqlite_unlock_notify", codeFilePath, "-run")
}
func runCmd(cmd ...string) {
log.Printf("Executing : %s ...\n", cmd)
c := exec.Command(cmd[0], cmd[1:]...)

View File

@ -22,7 +22,7 @@ func TestAPIAdminOrgCreate(t *testing.T) {
session := loginUser(t, "user1")
token := getTokenForLoggedInUser(t, session)
var org = api.CreateOrgOption{
org := api.CreateOrgOption{
UserName: "user2_org",
FullName: "User2's organization",
Description: "This organization created by admin for user2",
@ -56,7 +56,7 @@ func TestAPIAdminOrgCreateBadVisibility(t *testing.T) {
session := loginUser(t, "user1")
token := getTokenForLoggedInUser(t, session)
var org = api.CreateOrgOption{
org := api.CreateOrgOption{
UserName: "user2_org",
FullName: "User2's organization",
Description: "This organization created by admin for user2",
@ -74,7 +74,7 @@ func TestAPIAdminOrgCreateNotAdmin(t *testing.T) {
nonAdminUsername := "user2"
session := loginUser(t, nonAdminUsername)
token := getTokenForLoggedInUser(t, session)
var org = api.CreateOrgOption{
org := api.CreateOrgOption{
UserName: "user2_org",
FullName: "User2's organization",
Description: "This organization created by admin for user2",

View File

@ -106,7 +106,6 @@ func TestAPICreateBranch(t *testing.T) {
}
func testAPICreateBranches(t *testing.T, giteaURL *url.URL) {
username := "user2"
ctx := NewAPITestContext(t, username, "my-noo-repo")
giteaURL.Path = ctx.GitPath()

View File

@ -28,11 +28,14 @@ func TestGPGKeys(t *testing.T) {
token string
results []int
}{
{name: "NoLogin", makeRequest: MakeRequest, token: "",
{
name: "NoLogin", makeRequest: MakeRequest, token: "",
results: []int{http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized},
},
{name: "LoggedAsUser2", makeRequest: session.MakeRequest, token: token,
results: []int{http.StatusOK, http.StatusOK, http.StatusNotFound, http.StatusNoContent, http.StatusUnprocessableEntity, http.StatusNotFound, http.StatusCreated, http.StatusNotFound, http.StatusCreated}},
{
name: "LoggedAsUser2", makeRequest: session.MakeRequest, token: token,
results: []int{http.StatusOK, http.StatusOK, http.StatusNotFound, http.StatusNoContent, http.StatusUnprocessableEntity, http.StatusNotFound, http.StatusCreated, http.StatusNotFound, http.StatusCreated},
},
}
for _, tc := range tt {
@ -68,7 +71,6 @@ func TestGPGKeys(t *testing.T) {
// Check state after basic add
t.Run("CheckState", func(t *testing.T) {
var keys []*api.GPGKey
req := NewRequest(t, "GET", "/api/v1/user/gpg_keys?token="+token) // GET all keys

View File

@ -86,7 +86,6 @@ func TestAPIModifyLabels(t *testing.T) {
// DeleteLabel
req = NewRequest(t, "DELETE", singleURLStr)
session.MakeRequest(t, req, http.StatusNoContent)
}
func TestAPIAddIssueLabels(t *testing.T) {
@ -206,5 +205,4 @@ func TestAPIModifyOrgLabels(t *testing.T) {
// DeleteLabel
req = NewRequest(t, "DELETE", singleURLStr)
session.MakeRequest(t, req, http.StatusNoContent)
}

View File

@ -33,7 +33,6 @@ func TestAPIIssueSubscriptions(t *testing.T) {
token := getTokenForLoggedInUser(t, session)
testSubscription := func(issue *models.Issue, isWatching bool) {
issueRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID}).(*repo_model.Repository)
urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/subscriptions/check?token=%s", issueRepo.OwnerName, issueRepo.Name, issue.Index, token)

View File

@ -23,7 +23,7 @@ func TestAPIOrgCreate(t *testing.T) {
session := loginUser(t, "user1")
token := getTokenForLoggedInUser(t, session)
var org = api.CreateOrgOption{
org := api.CreateOrgOption{
UserName: "user1_org",
FullName: "User1's organization",
Description: "This organization created by user1",
@ -80,7 +80,7 @@ func TestAPIOrgEdit(t *testing.T) {
session := loginUser(t, "user1")
token := getTokenForLoggedInUser(t, session)
var org = api.EditOrgOption{
org := api.EditOrgOption{
FullName: "User3 organization new full name",
Description: "A new description",
Website: "https://try.gitea.io/new",
@ -107,7 +107,7 @@ func TestAPIOrgEditBadVisibility(t *testing.T) {
session := loginUser(t, "user1")
token := getTokenForLoggedInUser(t, session)
var org = api.EditOrgOption{
org := api.EditOrgOption{
FullName: "User3 organization new full name",
Description: "A new description",
Website: "https://try.gitea.io/new",
@ -126,7 +126,7 @@ func TestAPIOrgDeny(t *testing.T) {
setting.Service.RequireSignInView = false
}()
var orgName = "user1_org"
orgName := "user1_org"
req := NewRequestf(t, "GET", "/api/v1/orgs/%s", orgName)
MakeRequest(t, req, http.StatusNotFound)

View File

@ -150,7 +150,5 @@ func TestAPIPrivateServ(t *testing.T) {
assert.Equal(t, "user15", results.OwnerName)
assert.Equal(t, "big_test_private_2", results.RepoName)
assert.Equal(t, int64(20), results.RepoID)
})
}

View File

@ -80,7 +80,8 @@ func TestAPIPullReview(t *testing.T) {
req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token), &api.CreatePullReviewOptions{
Body: "body1",
// Event: "" # will result in PENDING
Comments: []api.CreatePullReviewComment{{
Comments: []api.CreatePullReviewComment{
{
Path: "README.md",
Body: "first new line",
OldLineNum: 0,
@ -147,7 +148,8 @@ func TestAPIPullReview(t *testing.T) {
req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token), &api.CreatePullReviewOptions{
// Body: "",
Event: "COMMENT",
Comments: []api.CreatePullReviewComment{{
Comments: []api.CreatePullReviewComment{
{
Path: "README.md",
Body: "first new line",
OldLineNum: 0,

View File

@ -130,7 +130,6 @@ func TestDownloadCommitDiffOrPatch(t *testing.T) {
assert.EqualValues(t,
"From f27c2b2b03dcab38beaf89b0ab4ff61f6de63441 Mon Sep 17 00:00:00 2001\nFrom: User2 <user2@example.com>\nDate: Sun, 6 Aug 2017 19:55:01 +0200\nSubject: [PATCH] good signed commit\n\n---\n readme.md | 1 +\n 1 file changed, 1 insertion(+)\n create mode 100644 readme.md\n\ndiff --git a/readme.md b/readme.md\nnew file mode 100644\nindex 0000000..458121c\n--- /dev/null\n+++ b/readme.md\n@@ -0,0 +1 @@\n+good sign\n",
resp.Body.String())
}
func TestGetFileHistory(t *testing.T) {

View File

@ -79,76 +79,99 @@ func TestAPISearchRepo(t *testing.T) {
name, requestURL string
expectedResults
}{
{name: "RepositoriesMax50", requestURL: "/api/v1/repos/search?limit=50&private=false", expectedResults: expectedResults{
{
name: "RepositoriesMax50", requestURL: "/api/v1/repos/search?limit=50&private=false", expectedResults: expectedResults{
nil: {count: 30},
user: {count: 30},
user2: {count: 30}},
user2: {count: 30},
},
{name: "RepositoriesMax10", requestURL: "/api/v1/repos/search?limit=10&private=false", expectedResults: expectedResults{
},
{
name: "RepositoriesMax10", requestURL: "/api/v1/repos/search?limit=10&private=false", expectedResults: expectedResults{
nil: {count: 10},
user: {count: 10},
user2: {count: 10}},
user2: {count: 10},
},
{name: "RepositoriesDefault", requestURL: "/api/v1/repos/search?default&private=false", expectedResults: expectedResults{
},
{
name: "RepositoriesDefault", requestURL: "/api/v1/repos/search?default&private=false", expectedResults: expectedResults{
nil: {count: 10},
user: {count: 10},
user2: {count: 10}},
user2: {count: 10},
},
{name: "RepositoriesByName", requestURL: fmt.Sprintf("/api/v1/repos/search?q=%s&private=false", "big_test_"), expectedResults: expectedResults{
},
{
name: "RepositoriesByName", requestURL: fmt.Sprintf("/api/v1/repos/search?q=%s&private=false", "big_test_"), expectedResults: expectedResults{
nil: {count: 7, repoName: "big_test_"},
user: {count: 7, repoName: "big_test_"},
user2: {count: 7, repoName: "big_test_"}},
user2: {count: 7, repoName: "big_test_"},
},
{name: "RepositoriesAccessibleAndRelatedToUser", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user.ID), expectedResults: expectedResults{
},
{
name: "RepositoriesAccessibleAndRelatedToUser", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user.ID), expectedResults: expectedResults{
nil: {count: 5},
user: {count: 9, includesPrivate: true},
user2: {count: 6, includesPrivate: true}},
user2: {count: 6, includesPrivate: true},
},
{name: "RepositoriesAccessibleAndRelatedToUser2", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user2.ID), expectedResults: expectedResults{
},
{
name: "RepositoriesAccessibleAndRelatedToUser2", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user2.ID), expectedResults: expectedResults{
nil: {count: 1},
user: {count: 2, includesPrivate: true},
user2: {count: 2, includesPrivate: true},
user4: {count: 1}},
user4: {count: 1},
},
{name: "RepositoriesAccessibleAndRelatedToUser3", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user3.ID), expectedResults: expectedResults{
},
{
name: "RepositoriesAccessibleAndRelatedToUser3", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user3.ID), expectedResults: expectedResults{
nil: {count: 1},
user: {count: 4, includesPrivate: true},
user2: {count: 3, includesPrivate: true},
user3: {count: 4, includesPrivate: true}},
user3: {count: 4, includesPrivate: true},
},
{name: "RepositoriesOwnedByOrganization", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", orgUser.ID), expectedResults: expectedResults{
},
{
name: "RepositoriesOwnedByOrganization", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", orgUser.ID), expectedResults: expectedResults{
nil: {count: 1, repoOwnerID: orgUser.ID},
user: {count: 2, repoOwnerID: orgUser.ID, includesPrivate: true},
user2: {count: 1, repoOwnerID: orgUser.ID}},
user2: {count: 1, repoOwnerID: orgUser.ID},
},
},
{name: "RepositoriesAccessibleAndRelatedToUser4", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user4.ID), expectedResults: expectedResults{
nil: {count: 3},
user: {count: 4, includesPrivate: true},
user4: {count: 7, includesPrivate: true}}},
user4: {count: 7, includesPrivate: true},
}},
{name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeSource", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s", user4.ID, "source"), expectedResults: expectedResults{
nil: {count: 0},
user: {count: 1, includesPrivate: true},
user4: {count: 1, includesPrivate: true}}},
user4: {count: 1, includesPrivate: true},
}},
{name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeFork", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s", user4.ID, "fork"), expectedResults: expectedResults{
nil: {count: 1},
user: {count: 1},
user4: {count: 2, includesPrivate: true}}},
user4: {count: 2, includesPrivate: true},
}},
{name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeFork/Exclusive", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s&exclusive=1", user4.ID, "fork"), expectedResults: expectedResults{
nil: {count: 1},
user: {count: 1},
user4: {count: 2, includesPrivate: true}}},
user4: {count: 2, includesPrivate: true},
}},
{name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeMirror", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s", user4.ID, "mirror"), expectedResults: expectedResults{
nil: {count: 2},
user: {count: 2},
user4: {count: 4, includesPrivate: true}}},
user4: {count: 4, includesPrivate: true},
}},
{name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeMirror/Exclusive", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s&exclusive=1", user4.ID, "mirror"), expectedResults: expectedResults{
nil: {count: 1},
user: {count: 1},
user4: {count: 2, includesPrivate: true}}},
user4: {count: 2, includesPrivate: true},
}},
{name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeCollaborative", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s", user4.ID, "collaborative"), expectedResults: expectedResults{
nil: {count: 0},
user: {count: 1, includesPrivate: true},
user4: {count: 1, includesPrivate: true}}},
user4: {count: 1, includesPrivate: true},
}},
}
for _, testCase := range testCases {

View File

@ -155,5 +155,4 @@ func TestAPIRepoTopic(t *testing.T) {
// Test add a topic to repo with write access (requires repo admin access)
req = NewRequestf(t, "PUT", "/api/v1/repos/%s/%s/topics/%s?token=%s", user3.Name, repo3.Name, "topicName", token4)
session.MakeRequest(t, req, http.StatusForbidden)
}

View File

@ -22,7 +22,7 @@ func TestUserHeatmap(t *testing.T) {
normalUsername := "user2"
session := loginUser(t, adminUsername)
var fakeNow = time.Date(2011, 10, 20, 0, 0, 0, 0, time.Local)
fakeNow := time.Date(2011, 10, 20, 0, 0, 0, 0, time.Local)
timeutil.Set(fakeNow)
defer timeutil.Unset()

View File

@ -54,7 +54,7 @@ func TestUserOrgs(t *testing.T) {
}
func getUserOrgs(t *testing.T, userDoer, userCheck string) (orgs []*api.Organization) {
var token = ""
token := ""
session := emptyTestSession(t)
if len(userDoer) != 0 {
session = loginUser(t, userDoer)

View File

@ -29,7 +29,8 @@ func Test_CmdKeys(t *testing.T) {
}{
{"test_empty_1", []string{"keys", "--username=git", "--type=test", "--content=test"}, true, ""},
{"test_empty_2", []string{"keys", "-e", "git", "-u", "git", "-t", "test", "-k", "test"}, true, ""},
{"with_key",
{
"with_key",
[]string{"keys", "-e", "git", "-u", "git", "-t", "ssh-rsa", "-k", "AAAAB3NzaC1yc2EAAAADAQABAAABgQDWVj0fQ5N8wNc0LVNA41wDLYJ89ZIbejrPfg/avyj3u/ZohAKsQclxG4Ju0VirduBFF9EOiuxoiFBRr3xRpqzpsZtnMPkWVWb+akZwBFAx8p+jKdy4QXR/SZqbVobrGwip2UjSrri1CtBxpJikojRIZfCnDaMOyd9Jp6KkujvniFzUWdLmCPxUE9zhTaPu0JsEP7MW0m6yx7ZUhHyfss+NtqmFTaDO+QlMR7L2QkDliN2Jl3Xa3PhuWnKJfWhdAq1Cw4oraKUOmIgXLkuiuxVQ6mD3AiFupkmfqdHq6h+uHHmyQqv3gU+/sD8GbGAhf6ftqhTsXjnv1Aj4R8NoDf9BS6KRkzkeun5UisSzgtfQzjOMEiJtmrep2ZQrMGahrXa+q4VKr0aKJfm+KlLfwm/JztfsBcqQWNcTURiCFqz+fgZw0Ey/de0eyMzldYTdXXNRYCKjs9bvBK+6SSXRM7AhftfQ0ZuoW5+gtinPrnmoOaSCEJbAiEiTO/BzOHgowiM="},
false,
"# gitea public key\ncommand=\"" + setting.AppPath + " --config=" + util.ShellEscape(setting.CustomConf) + " serv key-1\",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty,no-user-rc,restrict ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDWVj0fQ5N8wNc0LVNA41wDLYJ89ZIbejrPfg/avyj3u/ZohAKsQclxG4Ju0VirduBFF9EOiuxoiFBRr3xRpqzpsZtnMPkWVWb+akZwBFAx8p+jKdy4QXR/SZqbVobrGwip2UjSrri1CtBxpJikojRIZfCnDaMOyd9Jp6KkujvniFzUWdLmCPxUE9zhTaPu0JsEP7MW0m6yx7ZUhHyfss+NtqmFTaDO+QlMR7L2QkDliN2Jl3Xa3PhuWnKJfWhdAq1Cw4oraKUOmIgXLkuiuxVQ6mD3AiFupkmfqdHq6h+uHHmyQqv3gU+/sD8GbGAhf6ftqhTsXjnv1Aj4R8NoDf9BS6KRkzkeun5UisSzgtfQzjOMEiJtmrep2ZQrMGahrXa+q4VKr0aKJfm+KlLfwm/JztfsBcqQWNcTURiCFqz+fgZw0Ey/de0eyMzldYTdXXNRYCKjs9bvBK+6SSXRM7AhftfQ0ZuoW5+gtinPrnmoOaSCEJbAiEiTO/BzOHgowiM= user2@localhost\n",

View File

@ -55,7 +55,7 @@ func TestDumpRestore(t *testing.T) {
//
ctx := context.Background()
var opts = migrations.MigrateOptions{
opts := migrations.MigrateOptions{
GitServiceType: structs.GiteaService,
Issues: true,
Labels: true,
@ -109,11 +109,11 @@ func TestDumpRestore(t *testing.T) {
beforeBytes, err := os.ReadFile(filepath.Join(d, "issue.yml"))
assert.NoError(t, err)
var before = make([]*base.Issue, 0, 10)
before := make([]*base.Issue, 0, 10)
assert.NoError(t, yaml.Unmarshal(beforeBytes, &before))
afterBytes, err := os.ReadFile(filepath.Join(newd, "issue.yml"))
assert.NoError(t, err)
var after = make([]*base.Issue, 0, 10)
after := make([]*base.Issue, 0, 10)
assert.NoError(t, yaml.Unmarshal(afterBytes, &after))
assert.EqualValues(t, len(before), len(after))

View File

@ -120,7 +120,6 @@ func testEditFile(t *testing.T, session *TestSession, user, repo, branch, filePa
}
func testEditFileToNewBranch(t *testing.T, session *TestSession, user, repo, branch, targetBranch, filePath, newContent string) *httptest.ResponseRecorder {
// Get to the 'edit this file' page
req := NewRequest(t, "GET", path.Join(user, repo, "_edit", branch, filePath))
resp := session.MakeRequest(t, req, http.StatusOK)

View File

@ -27,12 +27,11 @@ import (
)
func withKeyFile(t *testing.T, keyname string, callback func(string)) {
tmpDir, err := os.MkdirTemp("", "key-file")
assert.NoError(t, err)
defer util.RemoveAll(tmpDir)
err = os.Chmod(tmpDir, 0700)
err = os.Chmod(tmpDir, 0o700)
assert.NoError(t, err)
keyFile := filepath.Join(tmpDir, keyname)
@ -40,7 +39,7 @@ func withKeyFile(t *testing.T, keyname string, callback func(string)) {
assert.NoError(t, err)
err = os.WriteFile(path.Join(tmpDir, "ssh"), []byte("#!/bin/bash\n"+
"ssh -o \"UserKnownHostsFile=/dev/null\" -o \"StrictHostKeyChecking=no\" -o \"IdentitiesOnly=yes\" -i \""+keyFile+"\" \"$@\""), 0700)
"ssh -o \"UserKnownHostsFile=/dev/null\" -o \"StrictHostKeyChecking=no\" -o \"IdentitiesOnly=yes\" -i \""+keyFile+"\" \"$@\""), 0o700)
assert.NoError(t, err)
// Setup ssh wrapper
@ -142,7 +141,7 @@ func doGitInitTestRepository(dstPath string) func(*testing.T) {
// forcibly set default branch to master
_, err := git.NewCommand("symbolic-ref", "HEAD", git.BranchPrefix+"master").RunInDir(dstPath)
assert.NoError(t, err)
assert.NoError(t, os.WriteFile(filepath.Join(dstPath, "README.md"), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s", dstPath)), 0644))
assert.NoError(t, os.WriteFile(filepath.Join(dstPath, "README.md"), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s", dstPath)), 0o644))
assert.NoError(t, git.AddChanges(dstPath, true))
signature := git.Signature{
Email: "test@example.com",

View File

@ -18,7 +18,7 @@ func TestGitSmartHTTP(t *testing.T) {
}
func testGitSmartHTTP(t *testing.T, u *url.URL) {
var kases = []struct {
kases := []struct {
p string
code int
}{

View File

@ -135,7 +135,6 @@ func ensureAnonymousClone(t *testing.T, u *url.URL) {
assert.NoError(t, err)
defer util.RemoveAll(dstLocalPath)
t.Run("CloneAnonymous", doGitClone(dstLocalPath, u))
}
func standardCommitAndPushTest(t *testing.T, dstPath string) (little, big string) {
@ -639,7 +638,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB
t.Run("CreateHeadBranch", doGitCreateBranch(dstPath, headBranch))
t.Run("AddCommit", func(t *testing.T) {
err := os.WriteFile(path.Join(dstPath, "test_file"), []byte("## test content"), 0666)
err := os.WriteFile(path.Join(dstPath, "test_file"), []byte("## test content"), 0o666)
if !assert.NoError(t, err) {
return
}
@ -713,7 +712,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB
}
t.Run("AddCommit2", func(t *testing.T) {
err := os.WriteFile(path.Join(dstPath, "test_file"), []byte("## test content \n ## test content 2"), 0666)
err := os.WriteFile(path.Join(dstPath, "test_file"), []byte("## test content \n ## test content 2"), 0o666)
if !assert.NoError(t, err) {
return
}

View File

@ -32,7 +32,7 @@ func TestGPGGit(t *testing.T) {
assert.NoError(t, err)
defer util.RemoveAll(tmpDir)
err = os.Chmod(tmpDir, 0700)
err = os.Chmod(tmpDir, 0o700)
assert.NoError(t, err)
oldGNUPGHome := os.Getenv("GNUPGHOME")
@ -257,7 +257,6 @@ func TestGPGGit(t *testing.T) {
}
assert.Equal(t, "gitea@fake.local", response.Verification.Signer.Email)
}))
})
}, false)
var pr api.PullRequest
@ -321,7 +320,6 @@ func TestGPGGit(t *testing.T) {
assert.NotNil(t, branch.Commit.Verification)
assert.True(t, branch.Commit.Verification.Verified)
}))
})
}, false)
}

View File

@ -268,10 +268,10 @@ func prepareTestEnv(t testing.TB, skip ...int) func() {
assert.NoError(t, err, "unable to read the new repo root: %v\n", err)
}
for _, repoDir := range repoDirs {
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0o755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0o755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0o755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0o755)
}
}
@ -564,10 +564,10 @@ func resetFixtures(t *testing.T) {
assert.NoError(t, err, "unable to read the new repo root: %v\n", err)
}
for _, repoDir := range repoDirs {
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0o755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0o755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0o755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0o755)
}
}
}

View File

@ -121,7 +121,6 @@ func TestNoLoginViewIssue(t *testing.T) {
}
func testNewIssue(t *testing.T, session *TestSession, user, repo, title, content string) string {
req := NewRequest(t, "GET", path.Join(user, repo, "issues", "new"))
resp := session.MakeRequest(t, req, http.StatusOK)
@ -149,7 +148,6 @@ func testNewIssue(t *testing.T, session *TestSession, user, repo, title, content
}
func testIssueAddComment(t *testing.T, session *TestSession, issueURL, content, status string) int64 {
req := NewRequest(t, "GET", issueURL)
resp := session.MakeRequest(t, req, http.StatusOK)
@ -244,7 +242,8 @@ func TestIssueCrossReference(t *testing.T) {
RefIssueID: issueRef.ID,
RefCommentID: 0,
RefIsPull: false,
RefAction: references.XRefActionNone})
RefAction: references.XRefActionNone,
})
// Edit title, neuter ref
testIssueChangeInfo(t, "user2", issueRefURL, "title", "Title no ref")
@ -254,7 +253,8 @@ func TestIssueCrossReference(t *testing.T) {
RefIssueID: issueRef.ID,
RefCommentID: 0,
RefIsPull: false,
RefAction: references.XRefActionNeutered})
RefAction: references.XRefActionNeutered,
})
// Ref from issue content
issueRefURL, issueRef = testIssueWithBean(t, "user2", 1, "TitleXRef", fmt.Sprintf("Description ref #%d", issueBase.Index))
@ -264,7 +264,8 @@ func TestIssueCrossReference(t *testing.T) {
RefIssueID: issueRef.ID,
RefCommentID: 0,
RefIsPull: false,
RefAction: references.XRefActionNone})
RefAction: references.XRefActionNone,
})
// Edit content, neuter ref
testIssueChangeInfo(t, "user2", issueRefURL, "content", "Description no ref")
@ -274,7 +275,8 @@ func TestIssueCrossReference(t *testing.T) {
RefIssueID: issueRef.ID,
RefCommentID: 0,
RefIsPull: false,
RefAction: references.XRefActionNeutered})
RefAction: references.XRefActionNeutered,
})
// Ref from a comment
session := loginUser(t, "user2")
@ -285,7 +287,8 @@ func TestIssueCrossReference(t *testing.T) {
RefIssueID: issueRef.ID,
RefCommentID: commentID,
RefIsPull: false,
RefAction: references.XRefActionNone}
RefAction: references.XRefActionNone,
}
unittest.AssertExistsAndLoadBean(t, comment)
// Ref from a different repository
@ -296,7 +299,8 @@ func TestIssueCrossReference(t *testing.T) {
RefIssueID: issueRef.ID,
RefCommentID: 0,
RefIsPull: false,
RefAction: references.XRefActionNone})
RefAction: references.XRefActionNone,
})
}
func testIssueWithBean(t *testing.T, user string, repoID int64, title, content string) (string, *models.Issue) {

View File

@ -29,13 +29,13 @@ func TestDetermineLocalEndpoint(t *testing.T) {
rootdotgit, _ := os.MkdirTemp("", "lfs_test")
defer os.RemoveAll(rootdotgit)
os.Mkdir(filepath.Join(rootdotgit, ".git"), 0700)
os.Mkdir(filepath.Join(rootdotgit, ".git"), 0o700)
lfsroot, _ := os.MkdirTemp("", "lfs_test")
defer os.RemoveAll(lfsroot)
// Test cases
var cases = []struct {
cases := []struct {
cloneurl string
lfsurl string
expected *url.URL

View File

@ -20,7 +20,7 @@ import (
func TestLinksNoLogin(t *testing.T) {
defer prepareTestEnv(t)()
var links = []string{
links := []string{
"/explore/repos",
"/explore/repos?q=test&tab=",
"/explore/users",
@ -49,7 +49,7 @@ func TestLinksNoLogin(t *testing.T) {
func TestRedirectsNoLogin(t *testing.T) {
defer prepareTestEnv(t)()
var redirects = map[string]string{
redirects := map[string]string{
"/user2/repo1/commits/master": "/user2/repo1/commits/branch/master",
"/user2/repo1/src/master": "/user2/repo1/src/branch/master",
"/user2/repo1/src/master/file.txt": "/user2/repo1/src/branch/master/file.txt",
@ -67,7 +67,7 @@ func TestRedirectsNoLogin(t *testing.T) {
func TestNoLoginNotExist(t *testing.T) {
defer prepareTestEnv(t)()
var links = []string{
links := []string{
"/user5/repo4/projects",
"/user5/repo4/projects/3",
}
@ -79,7 +79,7 @@ func TestNoLoginNotExist(t *testing.T) {
}
func testLinksAsUser(userName string, t *testing.T) {
var links = []string{
links := []string{
"/explore/repos",
"/explore/repos?q=test&tab=",
"/explore/users",
@ -138,7 +138,7 @@ func testLinksAsUser(userName string, t *testing.T) {
var apiRepos []*api.Repository
DecodeJSON(t, respAPI, &apiRepos)
var repoLinks = []string{
repoLinks := []string{
"",
"/issues",
"/pulls",

View File

@ -74,10 +74,10 @@ func initMigrationTest(t *testing.T) func() {
assert.NoError(t, err, "unable to read the new repo root: %v\n", err)
}
for _, repoDir := range repoDirs {
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0o755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0o755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0o755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0o755)
}
}
@ -315,6 +315,5 @@ func TestMigrations(t *testing.T) {
t.Run(fmt.Sprintf("Migrate-%s-%s", dialect, version), func(t *testing.T) {
doMigrationTest(t, version)
})
}
}

View File

@ -210,5 +210,4 @@ func TestNonasciiBranches(t *testing.T) {
}
setDefaultBranch(t, session, user, repo, "master")
}

View File

@ -18,8 +18,10 @@ import (
"github.com/stretchr/testify/assert"
)
const privateActivityTestAdmin = "user1"
const privateActivityTestUser = "user2"
const (
privateActivityTestAdmin = "user1"
privateActivityTestUser = "user2"
)
// user3 is an organization so it is not usable here
const privateActivityTestOtherUser = "user4"

View File

@ -18,7 +18,6 @@ import (
func TestRepoActivity(t *testing.T) {
onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
session := loginUser(t, "user1")
// Create PRs (1 merged & 2 proposed)

View File

@ -77,7 +77,6 @@ func TestSettingShowUserEmailProfile(t *testing.T) {
htmlDoc.doc.Find(".user.profile").Text(),
"user2@example.com",
)
}
func TestSettingLandingPage(t *testing.T) {

View File

@ -28,7 +28,7 @@ func doCheckRepositoryEmptyStatus(ctx APITestContext, isEmpty bool) func(*testin
func doAddChangesToCheckout(dstPath, filename string) func(*testing.T) {
return func(t *testing.T) {
assert.NoError(t, os.WriteFile(filepath.Join(dstPath, filename), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s at time: %v", dstPath, time.Now())), 0644))
assert.NoError(t, os.WriteFile(filepath.Join(dstPath, filename), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s at time: %v", dstPath, time.Now())), 0o644))
assert.NoError(t, git.AddChanges(dstPath, true))
signature := git.Signature{
Email: "test@example.com",

View File

@ -28,6 +28,7 @@ func TestNotViewTimetrackingControls(t *testing.T) {
testViewTimetrackingControls(t, session, "user2", "repo1", "1", false)
// user2/repo1
}
func TestViewTimetrackingControlsDisabled(t *testing.T) {
defer prepareTestEnv(t)()
session := loginUser(t, "user2")

View File

@ -186,7 +186,7 @@ DEFAULT CONFIGURATION:
}
func formatBuiltWith() string {
var version = runtime.Version()
version := runtime.Version()
if len(MakeVersion) > 0 {
version = MakeVersion + ", " + runtime.Version()
}

View File

@ -12,9 +12,9 @@ import (
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/timeutil"
"xorm.io/xorm"
"github.com/duo-labs/webauthn/webauthn"
"xorm.io/xorm"
)
// ErrWebAuthnCredentialNotExist represents a "ErrWebAuthnCRedentialNotExist" kind of error.

View File

@ -240,7 +240,6 @@ func FixIssueLabelWithOutsideLabels() (int64, error) {
WHERE
(label.org_id = 0 AND issue.repo_id != label.repo_id) OR (label.repo_id = 0 AND label.org_id != repository.owner_id)
) AS il_too )`)
if err != nil {
return 0, err
}

View File

@ -394,7 +394,6 @@ func TestIssue_InsertIssue(t *testing.T) {
issue = testInsertIssue(t, `my issue2, this is my son's love \n \r \ `, "special issue's '' comments?", 7)
_, err = db.GetEngine(db.DefaultContext).ID(issue.ID).Delete(new(Issue))
assert.NoError(t, err)
}
func TestIssue_ResolveMentions(t *testing.T) {

View File

@ -155,7 +155,6 @@ func FetchIssueContentHistoryList(dbCtx context.Context, issueID, commentID int6
Where(builder.Eq{"issue_id": issueID, "comment_id": commentID}).
OrderBy("edited_unix DESC").
Find(&res)
if err != nil {
log.Error("can not fetch issue content history list. err=%v", err)
return nil, err

View File

@ -209,7 +209,7 @@ func LFSAutoAssociate(metas []*LFSMetaObject, user *user_model.User, repoID int6
func IterateLFS(f func(mo *LFSMetaObject) error) error {
var start int
const batchSize = 100
var e = db.GetEngine(db.DefaultContext)
e := db.GetEngine(db.DefaultContext)
for {
mos := make([]*LFSMetaObject, 0, batchSize)
if err := e.Limit(batchSize, start).Find(&mos); err != nil {

View File

@ -45,7 +45,7 @@ func assertCreateIssues(t *testing.T, reponame string, isPull bool) {
}
title := "issuetitle1"
var is = &Issue{
is := &Issue{
RepoID: repo.ID,
MilestoneID: milestone.ID,
Repo: repo,
@ -130,7 +130,7 @@ func TestMigrate_InsertPullRequests(t *testing.T) {
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{Name: reponame}).(*repo_model.Repository)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}).(*user_model.User)
var i = &Issue{
i := &Issue{
RepoID: repo.ID,
Repo: repo,
Title: "title1",
@ -140,7 +140,7 @@ func TestMigrate_InsertPullRequests(t *testing.T) {
Poster: owner,
}
var p = &PullRequest{
p := &PullRequest{
Issue: i,
}

View File

@ -219,10 +219,10 @@ func prepareTestEnv(t *testing.T, skip int, syncModels ...interface{}) (*xorm.En
assert.NoError(t, err, "unable to read the new repo root: %v\n", err)
}
for _, repoDir := range repoDirs {
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0o755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0o755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0o755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0o755)
}
}

View File

@ -124,5 +124,4 @@ func Test_removeInvalidLabels(t *testing.T) {
t.Errorf("IssueLabel[%d] was deleted but should have remained", id)
}
}
}

View File

@ -85,5 +85,4 @@ func Test_deleteOrphanedIssueLabels(t *testing.T) {
pre := preMigration[id]
assert.Equal(t, pre, post, "migration changed issueLabel %d", id)
}
}

View File

@ -38,7 +38,7 @@ func Test_addPrimaryEmail2EmailAddress(t *testing.T) {
IsPrimary bool `xorm:"DEFAULT(false) NOT NULL"`
}
var users = make([]User, 0, 20)
users := make([]User, 0, 20)
err = x.Find(&users)
assert.NoError(t, err)

View File

@ -37,10 +37,10 @@ func Test_addIssueResourceIndexTable(t *testing.T) {
MaxIndex int64 `xorm:"index"`
}
var start = 0
start := 0
const batchSize = 1000
for {
var indexes = make([]ResourceIndex, 0, batchSize)
indexes := make([]ResourceIndex, 0, batchSize)
err := x.Table("issue_index").Limit(batchSize, start).Find(&indexes)
assert.NoError(t, err)

View File

@ -26,7 +26,6 @@ func (ls *LoginSourceOriginalV189) TableName() string {
}
func Test_unwrapLDAPSourceCfg(t *testing.T) {
// Prepare and load the testing database
x, deferable := prepareTestEnv(t, 0, new(LoginSourceOriginalV189))
if x == nil || t.Failed() {
@ -80,5 +79,4 @@ func Test_unwrapLDAPSourceCfg(t *testing.T) {
assert.EqualValues(t, source.ID%2 == 0, source.IsActive, "unwrapLDAPSourceCfg failed for %d", source.ID)
}
}
}

View File

@ -11,7 +11,6 @@ import (
)
func alterIssueAndCommentTextFieldsToLongText(x *xorm.Engine) error {
sess := x.NewSession()
defer sess.Close()
if err := sess.Begin(); err != nil {

View File

@ -40,10 +40,10 @@ func Test_addTableCommitStatusIndex(t *testing.T) {
MaxIndex int64 `xorm:"index"`
}
var start = 0
start := 0
const batchSize = 1000
for {
var indexes = make([]CommitStatusIndex, 0, batchSize)
indexes := make([]CommitStatusIndex, 0, batchSize)
err := x.Table("commit_status_index").Limit(batchSize, start).Find(&indexes)
assert.NoError(t, err)

View File

@ -16,7 +16,6 @@ import (
)
func addWebAuthnCred(x *xorm.Engine) error {
// Create webauthnCredential table
type webauthnCredential struct {
ID int64 `xorm:"pk autoincr"`

View File

@ -12,7 +12,6 @@ import (
)
func useBase32HexForCredIDInWebAuthnCredential(x *xorm.Engine) error {
// Create webauthnCredential table
type webauthnCredential struct {
ID int64 `xorm:"pk autoincr"`

View File

@ -718,7 +718,7 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error {
if err != nil {
return fmt.Errorf("listDeployKeys: %v", err)
}
var needRewriteKeysFile = len(deployKeys) > 0
needRewriteKeysFile := len(deployKeys) > 0
for _, dKey := range deployKeys {
if err := DeleteDeployKey(ctx, doer, dKey.ID); err != nil {
return fmt.Errorf("deleteDeployKeys: %v", err)
@ -844,7 +844,7 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error {
return err
}
var lfsPaths = make([]string, 0, len(lfsObjects))
lfsPaths := make([]string, 0, len(lfsObjects))
for _, v := range lfsObjects {
count, err := sess.Count(&LFSMetaObject{Pointer: lfs.Pointer{Oid: v.Oid}})
if err != nil {
@ -867,7 +867,7 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error {
return err
}
var archivePaths = make([]string, 0, len(archives))
archivePaths := make([]string, 0, len(archives))
for _, v := range archives {
p, _ := v.RelativePath()
archivePaths = append(archivePaths, p)
@ -893,7 +893,7 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error {
return err
}
var newAttachmentPaths = make([]string, 0, len(newAttachments))
newAttachmentPaths := make([]string, 0, len(newAttachments))
for _, attach := range newAttachments {
newAttachmentPaths = append(newAttachmentPaths, attach.RelativePath())
}

View File

@ -90,7 +90,7 @@ type FindRepoArchiversOption struct {
}
func (opts FindRepoArchiversOption) toConds() builder.Cond {
var cond = builder.NewCond()
cond := builder.NewCond()
if opts.OlderThan > 0 {
cond = cond.And(builder.Lt{"created_unix": time.Now().Add(-opts.OlderThan).Unix()})
}
@ -99,7 +99,7 @@ func (opts FindRepoArchiversOption) toConds() builder.Cond {
// FindRepoArchives find repo archivers
func FindRepoArchives(opts FindRepoArchiversOption) ([]*RepoArchiver, error) {
var archivers = make([]*RepoArchiver, 0, opts.PageSize)
archivers := make([]*RepoArchiver, 0, opts.PageSize)
start, limit := opts.GetSkipTake()
err := db.GetEngine(db.DefaultContext).Where(opts.toConds()).
Asc("created_unix").

View File

@ -241,7 +241,7 @@ func UpdateAttachmentByUUID(ctx context.Context, attach *Attachment, cols ...str
// UpdateAttachmentCtx updates the given attachment in database
func UpdateAttachmentCtx(ctx context.Context, atta *Attachment) error {
var sess = db.GetEngine(ctx).Cols("name", "issue_id", "release_id", "comment_id", "download_count")
sess := db.GetEngine(ctx).Cols("name", "issue_id", "release_id", "comment_id", "download_count")
if atta.ID != 0 && atta.UUID == "" {
sess = sess.ID(atta.ID)
} else {

View File

@ -17,10 +17,8 @@ import (
"xorm.io/xorm"
)
var (
// ErrMirrorNotExist mirror does not exist error
ErrMirrorNotExist = errors.New("Mirror does not exist")
)
var ErrMirrorNotExist = errors.New("Mirror does not exist")
// RemoteMirrorer defines base methods for pull/push mirrors.
type RemoteMirrorer interface {

View File

@ -15,10 +15,8 @@ import (
"xorm.io/xorm"
)
var (
// ErrPushMirrorNotExist mirror does not exist error
ErrPushMirrorNotExist = errors.New("PushMirror does not exist")
)
var ErrPushMirrorNotExist = errors.New("PushMirror does not exist")
// PushMirror represents mirror information of a repository.
type PushMirror struct {

View File

@ -199,5 +199,4 @@ func TestDismissReview(t *testing.T) {
assert.False(t, rejectReviewExample.Dismissed)
assert.False(t, requestReviewExample.Dismissed)
assert.True(t, approveReviewExample.Dismissed)
}

View File

@ -117,10 +117,10 @@ func MainTest(m *testing.M, pathToGiteaRoot string, fixtureFiles ...string) {
fatalTestError("unable to read the new repo root: %v\n", err)
}
for _, repoDir := range repoDirs {
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0o755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0o755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0o755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0o755)
}
}
@ -182,10 +182,10 @@ func PrepareTestEnv(t testing.TB) {
repoDirs, err := os.ReadDir(filepath.Join(setting.RepoRootPath, ownerDir.Name()))
assert.NoError(t, err)
for _, repoDir := range repoDirs {
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0o755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0o755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0o755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0o755)
}
}

View File

@ -21,10 +21,8 @@ import (
"xorm.io/builder"
)
var (
// ErrEmailNotActivated e-mail address has not been activated error
ErrEmailNotActivated = errors.New("E-mail address has not been activated")
)
var ErrEmailNotActivated = errors.New("E-mail address has not been activated")
// ErrEmailInvalid represents an error where the email address does not comply with RFC 5322
type ErrEmailInvalid struct {

View File

@ -26,7 +26,6 @@ func TestKeygen(t *testing.T) {
assert.Regexp(t, regexp.MustCompile("^-----BEGIN RSA PRIVATE KEY-----.*"), priv)
assert.Regexp(t, regexp.MustCompile("^-----BEGIN PUBLIC KEY-----.*"), pub)
}
func TestSignUsingKeys(t *testing.T) {

View File

@ -12,8 +12,7 @@ import (
)
// DBStore can be used to store app state items in local filesystem
type DBStore struct {
}
type DBStore struct{}
// Get reads the state item
func (f *DBStore) Get(item StateItem) error {

View File

@ -14,9 +14,11 @@ type testDiscoveredInfo struct{}
func (s *testDiscoveredInfo) ClaimedID() string {
return "claimedID"
}
func (s *testDiscoveredInfo) OpEndpoint() string {
return "opEndpoint"
}
func (s *testDiscoveredInfo) OpLocalID() string {
return "opLocalID"
}

View File

@ -17,8 +17,10 @@ import (
// If you have multiple servers for example, you may need to share at
// least
// the nonceStore between them.
var nonceStore = openid.NewSimpleNonceStore()
var discoveryCache = newTimedDiscoveryCache(24 * time.Hour)
var (
nonceStore = openid.NewSimpleNonceStore()
discoveryCache = newTimedDiscoveryCache(24 * time.Hour)
)
// Verify handles response from OpenID provider
func Verify(fullURL string) (id string, err error) {

View File

@ -27,7 +27,6 @@ func Auth(serviceName, userName, passwd string) (string, error) {
}
return "", errors.New("Unrecognized PAM message style")
})
if err != nil {
return "", err
}

View File

@ -61,6 +61,7 @@ func Test_PrepareWithInvalidImage(t *testing.T) {
_, err := Prepare([]byte{})
assert.EqualError(t, err, "DecodeConfig: image: unknown format")
}
func Test_PrepareWithInvalidImageSize(t *testing.T) {
setting.Avatar.MaxWidth = 5
setting.Avatar.MaxHeight = 5

View File

@ -152,7 +152,7 @@ func PrettyNumber(v int64) string {
func Subtract(left, right interface{}) interface{} {
var rleft, rright int64
var fleft, fright float64
var isInt = true
isInt := true
switch v := left.(type) {
case int:
rleft = int64(v)

View File

@ -16,9 +16,7 @@ import (
_ "gitea.com/go-chi/cache/memcache" // memcache plugin for cache
)
var (
conn mc.Cache
)
var conn mc.Cache
func newCache(cacheConfig setting.Cache) (mc.Cache, error) {
return mc.NewCacher(mc.Options{

View File

@ -113,6 +113,7 @@ func TestGetInt(t *testing.T) {
// TODO: uncommented code works in IDE but not with go test
}
func TestGetInt64(t *testing.T) {
createTestCache()

View File

@ -25,7 +25,7 @@ var UTF8BOM = []byte{'\xef', '\xbb', '\xbf'}
// ToUTF8WithFallbackReader detects the encoding of content and coverts to UTF-8 reader if possible
func ToUTF8WithFallbackReader(rd io.Reader) io.Reader {
var buf = make([]byte, 2048)
buf := make([]byte, 2048)
n, err := util.ReadAtMost(rd, buf)
if err != nil {
return io.MultiReader(bytes.NewReader(RemoveBOMIfPresent(buf[:n])), rd)

View File

@ -56,36 +56,48 @@ func TestToUTF8WithErr(t *testing.T) {
assert.Equal(t, []byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba}, []byte(res))
// "áéíóú"
res, err = ToUTF8WithErr([]byte{0xef, 0xbb, 0xbf, 0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3,
0xc3, 0xba})
res, err = ToUTF8WithErr([]byte{
0xef, 0xbb, 0xbf, 0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3,
0xc3, 0xba,
})
assert.NoError(t, err)
assert.Equal(t, []byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba}, []byte(res))
res, err = ToUTF8WithErr([]byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63,
0xF3, 0x6D, 0x6F, 0x20, 0xF1, 0x6F, 0x73, 0x41, 0x41, 0x41, 0x2e})
res, err = ToUTF8WithErr([]byte{
0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63,
0xF3, 0x6D, 0x6F, 0x20, 0xF1, 0x6F, 0x73, 0x41, 0x41, 0x41, 0x2e,
})
assert.NoError(t, err)
stringMustStartWith(t, "Hola,", res)
stringMustEndWith(t, "AAA.", res)
res, err = ToUTF8WithErr([]byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63,
0xF3, 0x6D, 0x6F, 0x20, 0x07, 0xA4, 0x6F, 0x73, 0x41, 0x41, 0x41, 0x2e})
res, err = ToUTF8WithErr([]byte{
0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63,
0xF3, 0x6D, 0x6F, 0x20, 0x07, 0xA4, 0x6F, 0x73, 0x41, 0x41, 0x41, 0x2e,
})
assert.NoError(t, err)
stringMustStartWith(t, "Hola,", res)
stringMustEndWith(t, "AAA.", res)
res, err = ToUTF8WithErr([]byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63,
0xF3, 0x6D, 0x6F, 0x20, 0x81, 0xA4, 0x6F, 0x73, 0x41, 0x41, 0x41, 0x2e})
res, err = ToUTF8WithErr([]byte{
0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63,
0xF3, 0x6D, 0x6F, 0x20, 0x81, 0xA4, 0x6F, 0x73, 0x41, 0x41, 0x41, 0x2e,
})
assert.NoError(t, err)
stringMustStartWith(t, "Hola,", res)
stringMustEndWith(t, "AAA.", res)
// Japanese (Shift-JIS)
// 日属秘ぞしちゅ。
res, err = ToUTF8WithErr([]byte{0x93, 0xFA, 0x91, 0xAE, 0x94, 0xE9, 0x82, 0xBC, 0x82, 0xB5, 0x82,
0xBF, 0x82, 0xE3, 0x81, 0x42})
res, err = ToUTF8WithErr([]byte{
0x93, 0xFA, 0x91, 0xAE, 0x94, 0xE9, 0x82, 0xBC, 0x82, 0xB5, 0x82,
0xBF, 0x82, 0xE3, 0x81, 0x42,
})
assert.NoError(t, err)
assert.Equal(t, []byte{0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3,
0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82},
assert.Equal(t, []byte{
0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3,
0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82,
},
[]byte(res))
res, err = ToUTF8WithErr([]byte{0x00, 0x00, 0x00, 0x00})
@ -108,10 +120,14 @@ func TestToUTF8WithFallback(t *testing.T) {
assert.Equal(t, []byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba}, res)
// "Hola, así cómo ños"
res = ToUTF8WithFallback([]byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63,
0xF3, 0x6D, 0x6F, 0x20, 0xF1, 0x6F, 0x73})
assert.Equal(t, []byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xC3, 0xAD, 0x20, 0x63,
0xC3, 0xB3, 0x6D, 0x6F, 0x20, 0xC3, 0xB1, 0x6F, 0x73}, res)
res = ToUTF8WithFallback([]byte{
0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63,
0xF3, 0x6D, 0x6F, 0x20, 0xF1, 0x6F, 0x73,
})
assert.Equal(t, []byte{
0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xC3, 0xAD, 0x20, 0x63,
0xC3, 0xB3, 0x6D, 0x6F, 0x20, 0xC3, 0xB1, 0x6F, 0x73,
}, res)
// "Hola, así cómo "
minmatch := []byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xC3, 0xAD, 0x20, 0x63, 0xC3, 0xB3, 0x6D, 0x6F, 0x20}
@ -127,8 +143,10 @@ func TestToUTF8WithFallback(t *testing.T) {
// Japanese (Shift-JIS)
// "日属秘ぞしちゅ。"
res = ToUTF8WithFallback([]byte{0x93, 0xFA, 0x91, 0xAE, 0x94, 0xE9, 0x82, 0xBC, 0x82, 0xB5, 0x82, 0xBF, 0x82, 0xE3, 0x81, 0x42})
assert.Equal(t, []byte{0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3,
0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82}, res)
assert.Equal(t, []byte{
0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3,
0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82,
}, res)
res = ToUTF8WithFallback([]byte{0x00, 0x00, 0x00, 0x00})
assert.Equal(t, []byte{0x00, 0x00, 0x00, 0x00}, res)
@ -148,21 +166,29 @@ func TestToUTF8(t *testing.T) {
assert.Equal(t, []byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba}, []byte(res))
// BOM + "áéíóú"
res = ToUTF8(string([]byte{0xef, 0xbb, 0xbf, 0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3,
0xc3, 0xba}))
res = ToUTF8(string([]byte{
0xef, 0xbb, 0xbf, 0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3,
0xc3, 0xba,
}))
assert.Equal(t, []byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba}, []byte(res))
// Latin1
// Hola, así cómo ños
res = ToUTF8(string([]byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63,
0xF3, 0x6D, 0x6F, 0x20, 0xF1, 0x6F, 0x73}))
assert.Equal(t, []byte{0x48, 0x6f, 0x6c, 0x61, 0x2c, 0x20, 0x61, 0x73, 0xc3, 0xad, 0x20, 0x63,
0xc3, 0xb3, 0x6d, 0x6f, 0x20, 0xc3, 0xb1, 0x6f, 0x73}, []byte(res))
res = ToUTF8(string([]byte{
0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63,
0xF3, 0x6D, 0x6F, 0x20, 0xF1, 0x6F, 0x73,
}))
assert.Equal(t, []byte{
0x48, 0x6f, 0x6c, 0x61, 0x2c, 0x20, 0x61, 0x73, 0xc3, 0xad, 0x20, 0x63,
0xc3, 0xb3, 0x6d, 0x6f, 0x20, 0xc3, 0xb1, 0x6f, 0x73,
}, []byte(res))
// Latin1
// Hola, así cómo \x07ños
res = ToUTF8(string([]byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63,
0xF3, 0x6D, 0x6F, 0x20, 0x07, 0xA4, 0x6F, 0x73}))
res = ToUTF8(string([]byte{
0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63,
0xF3, 0x6D, 0x6F, 0x20, 0x07, 0xA4, 0x6F, 0x73,
}))
// Hola,
bytesMustStartWith(t, []byte{0x48, 0x6F, 0x6C, 0x61, 0x2C}, []byte(res))
@ -173,10 +199,14 @@ func TestToUTF8(t *testing.T) {
// Japanese (Shift-JIS)
// 日属秘ぞしちゅ。
res = ToUTF8(string([]byte{0x93, 0xFA, 0x91, 0xAE, 0x94, 0xE9, 0x82, 0xBC, 0x82, 0xB5, 0x82,
0xBF, 0x82, 0xE3, 0x81, 0x42}))
assert.Equal(t, []byte{0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3,
0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82},
res = ToUTF8(string([]byte{
0x93, 0xFA, 0x91, 0xAE, 0x94, 0xE9, 0x82, 0xBC, 0x82, 0xB5, 0x82,
0xBF, 0x82, 0xE3, 0x81, 0x42,
}))
assert.Equal(t, []byte{
0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3,
0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82,
},
[]byte(res))
res = ToUTF8("\x00\x00\x00\x00")
@ -216,8 +246,10 @@ func TestToUTF8DropErrors(t *testing.T) {
// Japanese (Shift-JIS)
// "日属秘ぞしちゅ。"
res = ToUTF8DropErrors([]byte{0x93, 0xFA, 0x91, 0xAE, 0x94, 0xE9, 0x82, 0xBC, 0x82, 0xB5, 0x82, 0xBF, 0x82, 0xE3, 0x81, 0x42})
assert.Equal(t, []byte{0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3,
0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82}, res)
assert.Equal(t, []byte{
0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3,
0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82,
}, res)
res = ToUTF8DropErrors([]byte{0x00, 0x00, 0x00, 0x00})
assert.Equal(t, []byte{0x00, 0x00, 0x00, 0x00}, res)

View File

@ -269,13 +269,12 @@ func APIAuth(authMethod auth_service.Method) func(*APIContext) {
// APIContexter returns apicontext as middleware
func APIContexter() func(http.Handler) http.Handler {
var csrfOpts = getCsrfOpts()
csrfOpts := getCsrfOpts()
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
var locale = middleware.Locale(w, req)
var ctx = APIContext{
locale := middleware.Locale(w, req)
ctx := APIContext{
Context: &Context{
Resp: NewResponse(w),
Data: map[string]interface{}{},
@ -354,7 +353,7 @@ func ReferencesGitRepo(allowEmpty bool) func(ctx *APIContext) (cancel context.Ca
// NotFound handles 404s for APIContext
// String will replace message, errors will be added to a slice
func (ctx *APIContext) NotFound(objs ...interface{}) {
var message = ctx.Tr("error.not_found")
message := ctx.Tr("error.not_found")
var errors []string
for _, obj := range objs {
// Ignore nil

View File

@ -16,7 +16,7 @@ import (
func TestGenAPILinks(t *testing.T) {
setting.AppURL = "http://localhost:3000/"
var kases = map[string][]string{
kases := map[string][]string{
"api/v1/repos/jerrykan/example-repo/issues?state=all": {
`<http://localhost:3000/api/v1/repos/jerrykan/example-repo/issues?page=2&state=all>; rel="next"`,
`<http://localhost:3000/api/v1/repos/jerrykan/example-repo/issues?page=5&state=all>; rel="last"`,

View File

@ -13,8 +13,10 @@ import (
"gitea.com/go-chi/captcha"
)
var imageCaptchaOnce sync.Once
var cpt *captcha.Captcha
var (
imageCaptchaOnce sync.Once
cpt *captcha.Captcha
)
// GetImageCaptcha returns global image captcha
func GetImageCaptcha() *captcha.Captcha {

View File

@ -362,7 +362,7 @@ func (ctx *Context) ServeStream(rd io.Reader, name string) {
// Error returned an error to web browser
func (ctx *Context) Error(status int, contents ...string) {
var v = http.StatusText(status)
v := http.StatusText(status)
if len(contents) > 0 {
v = contents[0]
}
@ -606,16 +606,16 @@ func Auth(authMethod auth.Method) func(*Context) {
// Contexter initializes a classic context for a request.
func Contexter() func(next http.Handler) http.Handler {
var rnd = templates.HTMLRenderer()
var csrfOpts = getCsrfOpts()
rnd := templates.HTMLRenderer()
csrfOpts := getCsrfOpts()
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
var locale = middleware.Locale(resp, req)
var startTime = time.Now()
var link = setting.AppSubURL + strings.TrimSuffix(req.URL.EscapedPath(), "/")
locale := middleware.Locale(resp, req)
startTime := time.Now()
link := setting.AppSubURL + strings.TrimSuffix(req.URL.EscapedPath(), "/")
var ctx = Context{
ctx := Context{
Resp: NewResponse(resp),
Cache: mc.GetCache(),
Locale: locale,

View File

@ -44,9 +44,7 @@ func (ctx *PrivateContext) Err() error {
return ctx.Req.Context().Err()
}
var (
privateContextKey interface{} = "default_private_context"
)
var privateContextKey interface{} = "default_private_context"
// WithPrivateContext set up private context in request
func WithPrivateContext(req *http.Request, ctx *PrivateContext) *http.Request {

View File

@ -111,7 +111,6 @@ type CanCommitToBranchResults struct {
// and branch is not protected for push
func (r *Repository) CanCommitToBranch(ctx context.Context, doer *user_model.User) (CanCommitToBranchResults, error) {
protectedBranch, err := models.GetProtectedBranchBy(r.Repository.ID, r.BranchName)
if err != nil {
return CanCommitToBranchResults{}, err
}

View File

@ -17,9 +17,7 @@ type ResponseWriter interface {
Size() int
}
var (
_ ResponseWriter = &Response{}
)
var _ ResponseWriter = &Response{}
// Response represents a response
type Response struct {

View File

@ -83,7 +83,7 @@ func ToNotificationThread(n *models.Notification) *api.NotificationThread {
// ToNotifications convert list of Notification to api.NotificationThread list
func ToNotifications(nl models.NotificationList) []*api.NotificationThread {
var result = make([]*api.NotificationThread, 0, len(nl))
result := make([]*api.NotificationThread, 0, len(nl))
for _, n := range nl {
result = append(result, ToNotificationThread(n))
}

View File

@ -33,7 +33,6 @@ func ToCommitStatus(status *models.CommitStatus) *api.CommitStatus {
// ToCombinedStatus converts List of CommitStatus to a CombinedStatus
func ToCombinedStatus(statuses []*models.CommitStatus, repo *api.Repository) *api.CombinedStatus {
if len(statuses) == 0 {
return nil
}

View File

@ -17,8 +17,10 @@ import (
"code.gitea.io/gitea/modules/util"
)
const maxLines = 10
const guessSampleSize = 1e4 // 10k
const (
maxLines = 10
guessSampleSize = 1e4 // 10k
)
// CreateReader creates a csv.Reader with the given delimiter.
func CreateReader(input io.Reader, delimiter rune) *stdcsv.Reader {
@ -35,7 +37,7 @@ func CreateReader(input io.Reader, delimiter rune) *stdcsv.Reader {
// CreateReaderAndDetermineDelimiter tries to guess the field delimiter from the content and creates a csv.Reader.
// Reads at most guessSampleSize bytes.
func CreateReaderAndDetermineDelimiter(ctx *markup.RenderContext, rd io.Reader) (*stdcsv.Reader, error) {
var data = make([]byte, guessSampleSize)
data := make([]byte, guessSampleSize)
size, err := util.ReadAtMost(rd, data)
if err != nil {
return nil, err

View File

@ -31,7 +31,7 @@ func decodeSlashes(t *testing.T, s string) string {
}
func TestCreateReaderAndDetermineDelimiter(t *testing.T) {
var cases = []struct {
cases := []struct {
csv string
expectedRows [][]string
expectedDelimiter rune
@ -135,7 +135,7 @@ func TestDetermineDelimiterReadAllError(t *testing.T) {
}
func TestDetermineDelimiter(t *testing.T) {
var cases = []struct {
cases := []struct {
csv string
filename string
expectedDelimiter rune
@ -236,7 +236,7 @@ John Doe john@doe.com This,note,had,a,lot,of,commas,to,test,delimiters`,
}
func TestRemoveQuotedString(t *testing.T) {
var cases = []struct {
cases := []struct {
text string
expectedText string
}{
@ -301,7 +301,7 @@ abc | |123
}
func TestGuessDelimiter(t *testing.T) {
var cases = []struct {
cases := []struct {
csv string
expectedDelimiter rune
}{
@ -456,7 +456,7 @@ jkl`,
}
func TestGuessFromBeforeAfterQuotes(t *testing.T) {
var cases = []struct {
cases := []struct {
csv string
expectedDelimiter rune
}{
@ -562,7 +562,7 @@ func (l mockLocale) TrN(_cnt interface{}, key1, _keyN string, _args ...interface
}
func TestFormatError(t *testing.T) {
var cases = []struct {
cases := []struct {
err error
expectedMessage string
expectsError bool

View File

@ -296,7 +296,6 @@ func fixBrokenRepoUnits16961(ctx context.Context, logger log.Logger, autofix boo
return repo_model.UpdateRepoUnit(repoUnit)
},
)
if err != nil {
logger.Critical("Unable to iterate across repounits to fix the broken units: Error %v", err)
return err

Some files were not shown because too many files have changed in this diff Show More