Skip to content

Commit a222521

Browse files
authored
Merge branch 'main' into main
2 parents 8303101 + a658e2f commit a222521

File tree

101 files changed

+4700
-8383
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

101 files changed

+4700
-8383
lines changed

.air.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@ root = "."
22
tmp_dir = ".air"
33

44
[build]
5+
pre_cmd = ["killall -9 gitea 2>/dev/null || true"] # kill off potential zombie processes from previous runs
56
cmd = "make --no-print-directory backend"
67
bin = "gitea"
7-
delay = 1000
8+
delay = 2000
89
include_ext = ["go", "tmpl"]
910
include_file = ["main.go"]
1011
include_dir = ["cmd", "models", "modules", "options", "routers", "services"]

.eslintrc.yaml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -318,7 +318,7 @@ rules:
318318
jquery/no-serialize: [2]
319319
jquery/no-show: [2]
320320
jquery/no-size: [2]
321-
jquery/no-sizzle: [0]
321+
jquery/no-sizzle: [2]
322322
jquery/no-slide: [0]
323323
jquery/no-submit: [0]
324324
jquery/no-text: [0]
@@ -470,7 +470,7 @@ rules:
470470
no-jquery/no-selector-prop: [2]
471471
no-jquery/no-serialize: [2]
472472
no-jquery/no-size: [2]
473-
no-jquery/no-sizzle: [0]
473+
no-jquery/no-sizzle: [2]
474474
no-jquery/no-slide: [2]
475475
no-jquery/no-sub: [2]
476476
no-jquery/no-support: [2]

.gitattributes

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
* text=auto eol=lf
22
*.tmpl linguist-language=Handlebars
3+
*.pb.go linguist-generated
34
/assets/*.json linguist-generated
45
/public/assets/img/svg/*.svg linguist-generated
56
/templates/swagger/v1_json.tmpl linguist-generated

Makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -295,7 +295,7 @@ clean:
295295

296296
.PHONY: fmt
297297
fmt:
298-
GOFUMPT_PACKAGE=$(GOFUMPT_PACKAGE) $(GO) run build/code-batch-process.go gitea-fmt -w '{file-list}'
298+
@GOFUMPT_PACKAGE=$(GOFUMPT_PACKAGE) $(GO) run build/code-batch-process.go gitea-fmt -w '{file-list}'
299299
$(eval TEMPLATES := $(shell find templates -type f -name '*.tmpl'))
300300
@# strip whitespace after '{{' or '(' and before '}}' or ')' unless there is only
301301
@# whitespace before it

build/code-batch-process.go

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ func newFileCollector(fileFilter string, batchSize int) (*fileCollector, error)
6969
co.includePatterns = append(co.includePatterns, regexp.MustCompile(`.*\.go$`))
7070

7171
co.excludePatterns = append(co.excludePatterns, regexp.MustCompile(`.*\bbindata\.go$`))
72+
co.excludePatterns = append(co.excludePatterns, regexp.MustCompile(`\.pb\.go$`))
7273
co.excludePatterns = append(co.excludePatterns, regexp.MustCompile(`tests/gitea-repositories-meta`))
7374
co.excludePatterns = append(co.excludePatterns, regexp.MustCompile(`tests/integration/migration-test`))
7475
co.excludePatterns = append(co.excludePatterns, regexp.MustCompile(`modules/git/tests`))
@@ -203,17 +204,6 @@ Example:
203204
`, "file-batch-exec")
204205
}
205206

206-
func getGoVersion() string {
207-
goModFile, err := os.ReadFile("go.mod")
208-
if err != nil {
209-
log.Fatalf(`Faild to read "go.mod": %v`, err)
210-
os.Exit(1)
211-
}
212-
goModVersionRegex := regexp.MustCompile(`go \d+\.\d+`)
213-
goModVersionLine := goModVersionRegex.Find(goModFile)
214-
return string(goModVersionLine[3:])
215-
}
216-
217207
func newFileCollectorFromMainOptions(mainOptions map[string]string) (fc *fileCollector, err error) {
218208
fileFilter := mainOptions["file-filter"]
219209
if fileFilter == "" {
@@ -278,7 +268,8 @@ func main() {
278268
log.Print("the -d option is not supported by gitea-fmt")
279269
}
280270
cmdErrors = append(cmdErrors, giteaFormatGoImports(files, containsString(subArgs, "-w")))
281-
cmdErrors = append(cmdErrors, passThroughCmd("go", append([]string{"run", os.Getenv("GOFUMPT_PACKAGE"), "-extra", "-lang", getGoVersion()}, substArgs...)))
271+
cmdErrors = append(cmdErrors, passThroughCmd("gofmt", append([]string{"-w", "-r", "interface{} -> any"}, substArgs...)))
272+
cmdErrors = append(cmdErrors, passThroughCmd("go", append([]string{"run", os.Getenv("GOFUMPT_PACKAGE"), "-extra"}, substArgs...)))
282273
default:
283274
log.Fatalf("unknown cmd: %s %v", subCmd, subArgs)
284275
}

cmd/admin_user_change_password.go

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ var microcmdUserChangePassword = &cli.Command{
3636
&cli.BoolFlag{
3737
Name: "must-change-password",
3838
Usage: "User must change password",
39+
Value: true,
3940
},
4041
},
4142
}
@@ -57,23 +58,18 @@ func runChangePassword(c *cli.Context) error {
5758
return err
5859
}
5960

60-
var mustChangePassword optional.Option[bool]
61-
if c.IsSet("must-change-password") {
62-
mustChangePassword = optional.Some(c.Bool("must-change-password"))
63-
}
64-
6561
opts := &user_service.UpdateAuthOptions{
6662
Password: optional.Some(c.String("password")),
67-
MustChangePassword: mustChangePassword,
63+
MustChangePassword: optional.Some(c.Bool("must-change-password")),
6864
}
6965
if err := user_service.UpdateAuth(ctx, user, opts); err != nil {
7066
switch {
7167
case errors.Is(err, password.ErrMinLength):
72-
return fmt.Errorf("Password is not long enough. Needs to be at least %d", setting.MinPasswordLength)
68+
return fmt.Errorf("password is not long enough, needs to be at least %d characters", setting.MinPasswordLength)
7369
case errors.Is(err, password.ErrComplexity):
74-
return errors.New("Password does not meet complexity requirements")
70+
return errors.New("password does not meet complexity requirements")
7571
case errors.Is(err, password.ErrIsPwned):
76-
return errors.New("The password you chose is on a list of stolen passwords previously exposed in public data breaches. Please try again with a different password.\nFor more details, see https://haveibeenpwned.com/Passwords")
72+
return errors.New("the password is in a list of stolen passwords previously exposed in public data breaches, please try again with a different password, to see more details: https://haveibeenpwned.com/Passwords")
7773
default:
7874
return err
7975
}

cmd/admin_user_create.go

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"fmt"
99

1010
auth_model "code.gitea.io/gitea/models/auth"
11+
"code.gitea.io/gitea/models/db"
1112
user_model "code.gitea.io/gitea/models/user"
1213
pwd "code.gitea.io/gitea/modules/auth/password"
1314
"code.gitea.io/gitea/modules/optional"
@@ -46,8 +47,9 @@ var microcmdUserCreate = &cli.Command{
4647
Usage: "Generate a random password for the user",
4748
},
4849
&cli.BoolFlag{
49-
Name: "must-change-password",
50-
Usage: "Set this option to false to prevent forcing the user to change their password after initial login, (Default: true)",
50+
Name: "must-change-password",
51+
Usage: "Set to false to prevent forcing the user to change their password after initial login",
52+
DisableDefaultText: true,
5153
},
5254
&cli.IntFlag{
5355
Name: "random-password-length",
@@ -71,10 +73,10 @@ func runCreateUser(c *cli.Context) error {
7173
}
7274

7375
if c.IsSet("name") && c.IsSet("username") {
74-
return errors.New("Cannot set both --name and --username flags")
76+
return errors.New("cannot set both --name and --username flags")
7577
}
7678
if !c.IsSet("name") && !c.IsSet("username") {
77-
return errors.New("One of --name or --username flags must be set")
79+
return errors.New("one of --name or --username flags must be set")
7880
}
7981

8082
if c.IsSet("password") && c.IsSet("random-password") {
@@ -110,17 +112,21 @@ func runCreateUser(c *cli.Context) error {
110112
return errors.New("must set either password or random-password flag")
111113
}
112114

113-
// always default to true
114-
changePassword := true
115-
116-
// If this is the first user being created.
117-
// Take it as the admin and don't force a password update.
118-
if n := user_model.CountUsers(ctx, nil); n == 0 {
119-
changePassword = false
120-
}
121-
115+
isAdmin := c.Bool("admin")
116+
mustChangePassword := true // always default to true
122117
if c.IsSet("must-change-password") {
123-
changePassword = c.Bool("must-change-password")
118+
// if the flag is set, use the value provided by the user
119+
mustChangePassword = c.Bool("must-change-password")
120+
} else {
121+
// check whether there are users in the database
122+
hasUserRecord, err := db.IsTableNotEmpty(&user_model.User{})
123+
if err != nil {
124+
return fmt.Errorf("IsTableNotEmpty: %w", err)
125+
}
126+
if !hasUserRecord && isAdmin {
127+
// if this is the first admin being created, don't force to change password (keep the old behavior)
128+
mustChangePassword = false
129+
}
124130
}
125131

126132
restricted := optional.None[bool]()
@@ -136,8 +142,8 @@ func runCreateUser(c *cli.Context) error {
136142
Name: username,
137143
Email: c.String("email"),
138144
Passwd: password,
139-
IsAdmin: c.Bool("admin"),
140-
MustChangePassword: changePassword,
145+
IsAdmin: isAdmin,
146+
MustChangePassword: mustChangePassword,
141147
Visibility: visibility,
142148
}
143149

custom/conf/app.example.ini

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1556,8 +1556,9 @@ LEVEL = Info
15561556
;; The source of the username for new oauth2 accounts:
15571557
;; userid = use the userid / sub attribute
15581558
;; nickname = use the nickname attribute
1559+
;; preferred_username = use the preferred_username attribute
15591560
;; email = use the username part of the email attribute
1560-
;; Note: `nickname` and `email` options will normalize input strings using the following criteria:
1561+
;; Note: `nickname`, `preferred_username` and `email` options will normalize input strings using the following criteria:
15611562
;; - diacritics are removed
15621563
;; - the characters in the set `['´\x60]` are removed
15631564
;; - the characters in the set `[\s~+]` are replaced with `-`

docs/content/administration/command-line.en-us.md

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -83,8 +83,7 @@ Admin operations:
8383
- `--email value`: Email. Required.
8484
- `--admin`: If provided, this makes the user an admin. Optional.
8585
- `--access-token`: If provided, an access token will be created for the user. Optional. (default: false).
86-
- `--must-change-password`: If provided, the created user will be required to choose a newer password after the
87-
initial login. Optional. (default: true).
86+
- `--must-change-password`: The created user will be required to set a new password after the initial login, default: true. It could be disabled by `--must-change-password=false`.
8887
- `--random-password`: If provided, a randomly generated password will be used as the password of the created
8988
user. The value of `--password` will be discarded. Optional.
9089
- `--random-password-length`: If provided, it will be used to configure the length of the randomly generated
@@ -95,7 +94,7 @@ Admin operations:
9594
- Options:
9695
- `--username value`, `-u value`: Username. Required.
9796
- `--password value`, `-p value`: New password. Required.
98-
- `--must-change-password`: If provided, the user is required to choose a new password after the login. Optional.
97+
- `--must-change-password`: The user is required to set a new password after the login, default: true. It could be disabled by `--must-change-password=false`.
9998
- Examples:
10099
- `gitea admin user change-password --username myname --password asecurepassword`
101100
- `must-change-password`:

docs/content/administration/config-cheat-sheet.en-us.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -608,9 +608,10 @@ And the following unique queues:
608608
- `ENABLE_AUTO_REGISTRATION`: **false**: Automatically create user accounts for new oauth2 users.
609609
- `USERNAME`: **nickname**: The source of the username for new oauth2 accounts:
610610
- `userid` - use the userid / sub attribute
611-
- `nickname` - use the nickname attribute
611+
- `nickname` - use the nickname
612+
- `preferred_username` - use the preferred_username
612613
- `email` - use the username part of the email attribute
613-
- Note: `nickname` and `email` options will normalize input strings using the following criteria:
614+
- Note: `nickname`, `preferred_username` and `email` options will normalize input strings using the following criteria:
614615
- diacritics are removed
615616
- the characters in the set `['´\x60]` are removed
616617
- the characters in the set `[\s~+]` are replaced with `-`

models/db/engine.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -284,8 +284,8 @@ func MaxBatchInsertSize(bean any) int {
284284
}
285285

286286
// IsTableNotEmpty returns true if table has at least one record
287-
func IsTableNotEmpty(tableName string) (bool, error) {
288-
return x.Table(tableName).Exist()
287+
func IsTableNotEmpty(beanOrTableName any) (bool, error) {
288+
return x.Table(beanOrTableName).Exist()
289289
}
290290

291291
// DeleteAllRecords will delete all the records of this table

models/git/commit_status_summary.go

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,11 @@ import (
1515

1616
// CommitStatusSummary holds the latest commit Status of a single Commit
1717
type CommitStatusSummary struct {
18-
ID int64 `xorm:"pk autoincr"`
19-
RepoID int64 `xorm:"INDEX UNIQUE(repo_id_sha)"`
20-
SHA string `xorm:"VARCHAR(64) NOT NULL INDEX UNIQUE(repo_id_sha)"`
21-
State api.CommitStatusState `xorm:"VARCHAR(7) NOT NULL"`
18+
ID int64 `xorm:"pk autoincr"`
19+
RepoID int64 `xorm:"INDEX UNIQUE(repo_id_sha)"`
20+
SHA string `xorm:"VARCHAR(64) NOT NULL INDEX UNIQUE(repo_id_sha)"`
21+
State api.CommitStatusState `xorm:"VARCHAR(7) NOT NULL"`
22+
TargetURL string `xorm:"TEXT"`
2223
}
2324

2425
func init() {
@@ -44,9 +45,10 @@ func GetLatestCommitStatusForRepoAndSHAs(ctx context.Context, repoSHAs []RepoSHA
4445
commitStatuses := make([]*CommitStatus, 0, len(repoSHAs))
4546
for _, summary := range summaries {
4647
commitStatuses = append(commitStatuses, &CommitStatus{
47-
RepoID: summary.RepoID,
48-
SHA: summary.SHA,
49-
State: summary.State,
48+
RepoID: summary.RepoID,
49+
SHA: summary.SHA,
50+
State: summary.State,
51+
TargetURL: summary.TargetURL,
5052
})
5153
}
5254
return commitStatuses, nil
@@ -61,22 +63,24 @@ func UpdateCommitStatusSummary(ctx context.Context, repoID int64, sha string) er
6163
// mysql will return 0 when update a record which state hasn't been changed which behaviour is different from other database,
6264
// so we need to use insert in on duplicate
6365
if setting.Database.Type.IsMySQL() {
64-
_, err := db.GetEngine(ctx).Exec("INSERT INTO commit_status_summary (repo_id,sha,state) VALUES (?,?,?) ON DUPLICATE KEY UPDATE state=?",
65-
repoID, sha, state.State, state.State)
66+
_, err := db.GetEngine(ctx).Exec("INSERT INTO commit_status_summary (repo_id,sha,state,target_url) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE state=?",
67+
repoID, sha, state.State, state.TargetURL, state.State)
6668
return err
6769
}
6870

6971
if cnt, err := db.GetEngine(ctx).Where("repo_id=? AND sha=?", repoID, sha).
70-
Cols("state").
72+
Cols("state, target_url").
7173
Update(&CommitStatusSummary{
72-
State: state.State,
74+
State: state.State,
75+
TargetURL: state.TargetURL,
7376
}); err != nil {
7477
return err
7578
} else if cnt == 0 {
7679
_, err = db.GetEngine(ctx).Insert(&CommitStatusSummary{
77-
RepoID: repoID,
78-
SHA: sha,
79-
State: state.State,
80+
RepoID: repoID,
81+
SHA: sha,
82+
State: state.State,
83+
TargetURL: state.TargetURL,
8084
})
8185
return err
8286
}

models/migrations/migrations.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -580,6 +580,8 @@ var migrations = []Migration{
580580
NewMigration("Add unique index for project issue table", v1_23.AddUniqueIndexForProjectIssue),
581581
// v295 -> v296
582582
NewMigration("Add commit status summary table", v1_23.AddCommitStatusSummary),
583+
// v296 -> v297
584+
NewMigration("Add missing field of commit status summary table", v1_23.AddCommitStatusSummary2),
583585
}
584586

585587
// GetCurrentDBVersion returns the current db version

models/migrations/v1_23/v296.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// Copyright 2024 The Gitea Authors. All rights reserved.
2+
// SPDX-License-Identifier: MIT
3+
4+
package v1_23 //nolint
5+
6+
import "xorm.io/xorm"
7+
8+
func AddCommitStatusSummary2(x *xorm.Engine) error {
9+
type CommitStatusSummary struct {
10+
ID int64 `xorm:"pk autoincr"`
11+
TargetURL string `xorm:"TEXT"`
12+
}
13+
// there is no migrations because if there is no data on this table, it will fall back to get data
14+
// from commit status
15+
return x.Sync(new(CommitStatusSummary))
16+
}

modules/optional/serialization.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ func (o *Option[T]) UnmarshalYAML(value *yaml.Node) error {
3535
return nil
3636
}
3737

38-
func (o Option[T]) MarshalYAML() (interface{}, error) {
38+
func (o Option[T]) MarshalYAML() (any, error) {
3939
if !o.Has() {
4040
return nil, nil
4141
}

modules/session/store.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@ package session
66
import (
77
"net/http"
88

9+
"code.gitea.io/gitea/modules/setting"
10+
"code.gitea.io/gitea/modules/web/middleware"
11+
912
"gitea.com/go-chi/session"
1013
)
1114

@@ -18,6 +21,10 @@ type Store interface {
1821

1922
// RegenerateSession regenerates the underlying session and returns the new store
2023
func RegenerateSession(resp http.ResponseWriter, req *http.Request) (Store, error) {
24+
// Ensure that a cookie with a trailing slash does not take precedence over
25+
// the cookie written by the middleware.
26+
middleware.DeleteLegacySiteCookie(resp, setting.SessionConfig.CookieName)
27+
2128
s, err := session.RegenerateSession(resp, req)
2229
return s, err
2330
}

modules/setting/oauth2.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,13 @@ const (
2222
OAuth2UsernameNickname OAuth2UsernameType = "nickname"
2323
// OAuth2UsernameEmail username of oauth2 email field will be used as gitea name
2424
OAuth2UsernameEmail OAuth2UsernameType = "email"
25+
// OAuth2UsernameEmail username of oauth2 preferred_username field will be used as gitea name
26+
OAuth2UsernamePreferredUsername OAuth2UsernameType = "preferred_username"
2527
)
2628

2729
func (username OAuth2UsernameType) isValid() bool {
2830
switch username {
29-
case OAuth2UsernameUserid, OAuth2UsernameNickname, OAuth2UsernameEmail:
31+
case OAuth2UsernameUserid, OAuth2UsernameNickname, OAuth2UsernameEmail, OAuth2UsernamePreferredUsername:
3032
return true
3133
}
3234
return false

modules/structs/repo_compare.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
// Copyright 2024 The Gitea Authors. All rights reserved.
2+
// SPDX-License-Identifier: MIT
3+
4+
package structs
5+
6+
// Compare represents a comparison between two commits.
7+
type Compare struct {
8+
TotalCommits int `json:"total_commits"` // Total number of commits in the comparison.
9+
Commits []*Commit `json:"commits"` // List of commits in the comparison.
10+
}

0 commit comments

Comments
 (0)