Refactor context flash msg and global variables (#33375)
1. add `GetSiteCookieFlashMessage` to help to parse flash message 2. clarify `handleRepoHomeFeed` logic 3. remove unnecessary global variables, use `sync.OnceValue` instead 4. add some tests for `IsUsableUsername` and `IsUsableRepoName`
This commit is contained in:
parent
6a516a0d14
commit
2c1ff8701a
30 changed files with 737 additions and 676 deletions
|
@ -8,13 +8,26 @@ import (
|
|||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"code.gitea.io/gitea/modules/setting"
|
||||
|
||||
"github.com/gobwas/glob"
|
||||
)
|
||||
|
||||
var externalTrackerRegex = regexp.MustCompile(`({?)(?:user|repo|index)+?(}?)`)
|
||||
type globalVarsStruct struct {
|
||||
externalTrackerRegex *regexp.Regexp
|
||||
validUsernamePattern *regexp.Regexp
|
||||
invalidUsernamePattern *regexp.Regexp
|
||||
}
|
||||
|
||||
var globalVars = sync.OnceValue(func() *globalVarsStruct {
|
||||
return &globalVarsStruct{
|
||||
externalTrackerRegex: regexp.MustCompile(`({?)(?:user|repo|index)+?(}?)`),
|
||||
validUsernamePattern: regexp.MustCompile(`^[\da-zA-Z][-.\w]*$`),
|
||||
invalidUsernamePattern: regexp.MustCompile(`[-._]{2,}|[-._]$`), // No consecutive or trailing non-alphanumeric chars
|
||||
}
|
||||
})
|
||||
|
||||
func isLoopbackIP(ip string) bool {
|
||||
return net.ParseIP(ip).IsLoopback()
|
||||
|
@ -105,9 +118,9 @@ func IsValidExternalTrackerURLFormat(uri string) bool {
|
|||
if !IsValidExternalURL(uri) {
|
||||
return false
|
||||
}
|
||||
|
||||
vars := globalVars()
|
||||
// check for typoed variables like /{index/ or /[repo}
|
||||
for _, match := range externalTrackerRegex.FindAllStringSubmatch(uri, -1) {
|
||||
for _, match := range vars.externalTrackerRegex.FindAllStringSubmatch(uri, -1) {
|
||||
if (match[1] == "{" || match[2] == "}") && (match[1] != "{" || match[2] != "}") {
|
||||
return false
|
||||
}
|
||||
|
@ -116,14 +129,10 @@ func IsValidExternalTrackerURLFormat(uri string) bool {
|
|||
return true
|
||||
}
|
||||
|
||||
var (
|
||||
validUsernamePattern = regexp.MustCompile(`^[\da-zA-Z][-.\w]*$`)
|
||||
invalidUsernamePattern = regexp.MustCompile(`[-._]{2,}|[-._]$`) // No consecutive or trailing non-alphanumeric chars
|
||||
)
|
||||
|
||||
// IsValidUsername checks if username is valid
|
||||
func IsValidUsername(name string) bool {
|
||||
// It is difficult to find a single pattern that is both readable and effective,
|
||||
// but it's easier to use positive and negative checks.
|
||||
return validUsernamePattern.MatchString(name) && !invalidUsernamePattern.MatchString(name)
|
||||
vars := globalVars()
|
||||
return vars.validUsernamePattern.MatchString(name) && !vars.invalidUsernamePattern.MatchString(name)
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue