forked from gitea/gitea
1
0
Fork 0

Clarify the suffices and prefixes of setting.AppSubURL and setting.AppURL (#12999)

Also removes some unnecessary uses of fmt.Sprintf and adds documentation
strings

Signed-off-by: Andrew Thornton <art27@cantab.net>
This commit is contained in:
zeripath 2021-02-19 21:36:43 +00:00 committed by GitHub
parent 39aa11f9c0
commit aa4f9180e4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 53 additions and 42 deletions

View File

@ -26,7 +26,7 @@ func TestAction_GetRepoLink(t *testing.T) {
repo := AssertExistsAndLoadBean(t, &Repository{}).(*Repository) repo := AssertExistsAndLoadBean(t, &Repository{}).(*Repository)
owner := AssertExistsAndLoadBean(t, &User{ID: repo.OwnerID}).(*User) owner := AssertExistsAndLoadBean(t, &User{ID: repo.OwnerID}).(*User)
action := &Action{RepoID: repo.ID} action := &Action{RepoID: repo.ID}
setting.AppSubURL = "/suburl/" setting.AppSubURL = "/suburl"
expected := path.Join(setting.AppSubURL, owner.Name, repo.Name) expected := path.Join(setting.AppSubURL, owner.Name, repo.Name)
assert.Equal(t, expected, action.GetRepoLink()) assert.Equal(t, expected, action.GetRepoLink())
} }

View File

@ -6,7 +6,7 @@ package models
import ( import (
"fmt" "fmt"
"path" "strconv"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
@ -413,7 +413,7 @@ func (n *Notification) HTMLURL() string {
// APIURL formats a URL-string to the notification // APIURL formats a URL-string to the notification
func (n *Notification) APIURL() string { func (n *Notification) APIURL() string {
return setting.AppURL + path.Join("api/v1/notifications/threads", fmt.Sprintf("%d", n.ID)) return setting.AppURL + "api/v1/notifications/threads/" + strconv.FormatInt(n.ID, 10)
} }
// NotificationList contains a list of notifications // NotificationList contains a list of notifications

View File

@ -318,7 +318,7 @@ func (repo *Repository) CommitLink(commitID string) (result string) {
// APIURL returns the repository API URL // APIURL returns the repository API URL
func (repo *Repository) APIURL() string { func (repo *Repository) APIURL() string {
return setting.AppURL + path.Join("api/v1/repos", repo.FullName()) return setting.AppURL + "api/v1/repos/" + repo.FullName()
} }
// GetCommitsCountCacheKey returns cache key used for commits count caching. // GetCommitsCountCacheKey returns cache key used for commits count caching.

View File

@ -63,7 +63,7 @@ func (u *User) generateRandomAvatar(e Engine) error {
// the local explore page. Function returns immediately. // the local explore page. Function returns immediately.
// When applicable, the link is for an avatar of the indicated size (in pixels). // When applicable, the link is for an avatar of the indicated size (in pixels).
func (u *User) SizedRelAvatarLink(size int) string { func (u *User) SizedRelAvatarLink(size int) string {
return strings.TrimSuffix(setting.AppSubURL, "/") + "/user/avatar/" + u.Name + "/" + strconv.Itoa(size) return setting.AppSubURL + "/user/avatar/" + u.Name + "/" + strconv.Itoa(size)
} }
// RealSizedAvatarLink returns a link to the user's avatar. When // RealSizedAvatarLink returns a link to the user's avatar. When

View File

@ -89,11 +89,7 @@ func isLinkStr(link string) bool {
func getIssueFullPattern() *regexp.Regexp { func getIssueFullPattern() *regexp.Regexp {
if issueFullPattern == nil { if issueFullPattern == nil {
appURL := setting.AppURL issueFullPattern = regexp.MustCompile(regexp.QuoteMeta(setting.AppURL) +
if len(appURL) > 0 && appURL[len(appURL)-1] != '/' {
appURL += "/"
}
issueFullPattern = regexp.MustCompile(appURL +
`\w+/\w+/(?:issues|pulls)/((?:\w{1,10}-)?[1-9][0-9]*)([\?|#]\S+.(\S+)?)?\b`) `\w+/\w+/(?:issues|pulls)/((?:\w{1,10}-)?[1-9][0-9]*)([\?|#]\S+.(\S+)?)?\b`)
} }
return issueFullPattern return issueFullPattern
@ -636,6 +632,9 @@ func mentionProcessor(ctx *postProcessCtx, node *html.Node) {
mention := node.Data[loc.Start:loc.End] mention := node.Data[loc.Start:loc.End]
var teams string var teams string
teams, ok := ctx.metas["teams"] teams, ok := ctx.metas["teams"]
// FIXME: util.URLJoin may not be necessary here:
// - setting.AppURL is defined to have a terminal '/' so unless mention[1:]
// is an AppSubURL link we can probably fallback to concatenation.
// team mention should follow @orgName/teamName style // team mention should follow @orgName/teamName style
if ok && strings.Contains(mention, "/") { if ok && strings.Contains(mention, "/") {
mentionOrgAndTeam := strings.Split(mention, "/") mentionOrgAndTeam := strings.Split(mention, "/")

View File

@ -66,17 +66,31 @@ const (
// settings // settings
var ( var (
// AppVer settings // AppVer is the version of the current build of Gitea. It is set in main.go from main.Version.
AppVer string AppVer string
AppBuiltWith string // AppBuiltWith represents a human readable version go runtime build version and build tags. (See main.go formatBuiltWith().)
AppStartTime time.Time AppBuiltWith string
AppName string // AppStartTime store time gitea has started
AppURL string AppStartTime time.Time
AppSubURL string // AppName is the Application name, used in the page title.
AppSubURLDepth int // Number of slashes // It maps to ini:"APP_NAME"
AppPath string AppName string
AppDataPath string // AppURL is the Application ROOT_URL. It always has a '/' suffix
AppWorkPath string // It maps to ini:"ROOT_URL"
AppURL string
// AppSubURL represents the sub-url mounting point for gitea. It is either "" or starts with '/' and ends without '/', such as '/{subpath}'.
// This value is empty if site does not have sub-url.
AppSubURL string
// AppPath represents the path to the gitea binary
AppPath string
// AppWorkPath is the "working directory" of Gitea. It maps to the environment variable GITEA_WORK_DIR.
// If that is not set it is the default set here by the linker or failing that the directory of AppPath.
//
// AppWorkPath is used as the base path for several other paths.
AppWorkPath string
// AppDataPath is the default path for storing data.
// It maps to ini:"APP_DATA_PATH" and defaults to AppWorkPath + "/data"
AppDataPath string
// Server settings // Server settings
Protocol Scheme Protocol Scheme
@ -594,8 +608,9 @@ func NewContext() {
if (Protocol == HTTP && HTTPPort != "80") || (Protocol == HTTPS && HTTPPort != "443") { if (Protocol == HTTP && HTTPPort != "80") || (Protocol == HTTPS && HTTPPort != "443") {
defaultAppURL += ":" + HTTPPort defaultAppURL += ":" + HTTPPort
} }
AppURL = sec.Key("ROOT_URL").MustString(defaultAppURL) AppURL = sec.Key("ROOT_URL").MustString(defaultAppURL + "/")
AppURL = strings.TrimSuffix(AppURL, "/") + "/" // This should be TrimRight to ensure that there is only a single '/' at the end of AppURL.
AppURL = strings.TrimRight(AppURL, "/") + "/"
// Check if has app suburl. // Check if has app suburl.
appURL, err := url.Parse(AppURL) appURL, err := url.Parse(AppURL)
@ -606,7 +621,7 @@ func NewContext() {
// This value is empty if site does not have sub-url. // This value is empty if site does not have sub-url.
AppSubURL = strings.TrimSuffix(appURL.Path, "/") AppSubURL = strings.TrimSuffix(appURL.Path, "/")
StaticURLPrefix = strings.TrimSuffix(sec.Key("STATIC_URL_PREFIX").MustString(AppSubURL), "/") StaticURLPrefix = strings.TrimSuffix(sec.Key("STATIC_URL_PREFIX").MustString(AppSubURL), "/")
AppSubURLDepth = strings.Count(AppSubURL, "/")
// Check if Domain differs from AppURL domain than update it to AppURL's domain // Check if Domain differs from AppURL domain than update it to AppURL's domain
urlHostname := appURL.Hostname() urlHostname := appURL.Hostname()
if urlHostname != Domain && net.ParseIP(urlHostname) == nil && urlHostname != "" { if urlHostname != Domain && net.ParseIP(urlHostname) == nil && urlHostname != "" {

View File

@ -364,7 +364,7 @@ func WorkerCancel(ctx *context.Context) {
mq.CancelWorkers(pid) mq.CancelWorkers(pid)
ctx.Flash.Info(ctx.Tr("admin.monitor.queue.pool.cancelling")) ctx.Flash.Info(ctx.Tr("admin.monitor.queue.pool.cancelling"))
ctx.JSON(200, map[string]interface{}{ ctx.JSON(200, map[string]interface{}{
"redirect": setting.AppSubURL + fmt.Sprintf("/admin/monitor/queue/%d", qid), "redirect": setting.AppSubURL + "/admin/monitor/queue/" + strconv.FormatInt(qid, 10),
}) })
} }
@ -387,7 +387,7 @@ func Flush(ctx *context.Context) {
log.Error("Flushing failure for %s: Error %v", mq.Name, err) log.Error("Flushing failure for %s: Error %v", mq.Name, err)
} }
}() }()
ctx.Redirect(setting.AppSubURL + fmt.Sprintf("/admin/monitor/queue/%d", qid)) ctx.Redirect(setting.AppSubURL + "/admin/monitor/queue/" + strconv.FormatInt(qid, 10))
} }
// AddWorkers adds workers to a worker group // AddWorkers adds workers to a worker group
@ -401,23 +401,23 @@ func AddWorkers(ctx *context.Context) {
number := ctx.QueryInt("number") number := ctx.QueryInt("number")
if number < 1 { if number < 1 {
ctx.Flash.Error(ctx.Tr("admin.monitor.queue.pool.addworkers.mustnumbergreaterzero")) ctx.Flash.Error(ctx.Tr("admin.monitor.queue.pool.addworkers.mustnumbergreaterzero"))
ctx.Redirect(setting.AppSubURL + fmt.Sprintf("/admin/monitor/queue/%d", qid)) ctx.Redirect(setting.AppSubURL + "/admin/monitor/queue/" + strconv.FormatInt(qid, 10))
return return
} }
timeout, err := time.ParseDuration(ctx.Query("timeout")) timeout, err := time.ParseDuration(ctx.Query("timeout"))
if err != nil { if err != nil {
ctx.Flash.Error(ctx.Tr("admin.monitor.queue.pool.addworkers.musttimeoutduration")) ctx.Flash.Error(ctx.Tr("admin.monitor.queue.pool.addworkers.musttimeoutduration"))
ctx.Redirect(setting.AppSubURL + fmt.Sprintf("/admin/monitor/queue/%d", qid)) ctx.Redirect(setting.AppSubURL + "/admin/monitor/queue/" + strconv.FormatInt(qid, 10))
return return
} }
if _, ok := mq.Managed.(queue.ManagedPool); !ok { if _, ok := mq.Managed.(queue.ManagedPool); !ok {
ctx.Flash.Error(ctx.Tr("admin.monitor.queue.pool.none")) ctx.Flash.Error(ctx.Tr("admin.monitor.queue.pool.none"))
ctx.Redirect(setting.AppSubURL + fmt.Sprintf("/admin/monitor/queue/%d", qid)) ctx.Redirect(setting.AppSubURL + "/admin/monitor/queue/" + strconv.FormatInt(qid, 10))
return return
} }
mq.AddWorkers(number, timeout) mq.AddWorkers(number, timeout)
ctx.Flash.Success(ctx.Tr("admin.monitor.queue.pool.added")) ctx.Flash.Success(ctx.Tr("admin.monitor.queue.pool.added"))
ctx.Redirect(setting.AppSubURL + fmt.Sprintf("/admin/monitor/queue/%d", qid)) ctx.Redirect(setting.AppSubURL + "/admin/monitor/queue/" + strconv.FormatInt(qid, 10))
} }
// SetQueueSettings sets the maximum number of workers and other settings for this queue // SetQueueSettings sets the maximum number of workers and other settings for this queue
@ -430,7 +430,7 @@ func SetQueueSettings(ctx *context.Context) {
} }
if _, ok := mq.Managed.(queue.ManagedPool); !ok { if _, ok := mq.Managed.(queue.ManagedPool); !ok {
ctx.Flash.Error(ctx.Tr("admin.monitor.queue.pool.none")) ctx.Flash.Error(ctx.Tr("admin.monitor.queue.pool.none"))
ctx.Redirect(setting.AppSubURL + fmt.Sprintf("/admin/monitor/queue/%d", qid)) ctx.Redirect(setting.AppSubURL + "/admin/monitor/queue/" + strconv.FormatInt(qid, 10))
return return
} }
@ -445,7 +445,7 @@ func SetQueueSettings(ctx *context.Context) {
maxNumber, err = strconv.Atoi(maxNumberStr) maxNumber, err = strconv.Atoi(maxNumberStr)
if err != nil { if err != nil {
ctx.Flash.Error(ctx.Tr("admin.monitor.queue.settings.maxnumberworkers.error")) ctx.Flash.Error(ctx.Tr("admin.monitor.queue.settings.maxnumberworkers.error"))
ctx.Redirect(setting.AppSubURL + fmt.Sprintf("/admin/monitor/queue/%d", qid)) ctx.Redirect(setting.AppSubURL + "/admin/monitor/queue/" + strconv.FormatInt(qid, 10))
return return
} }
if maxNumber < -1 { if maxNumber < -1 {
@ -459,7 +459,7 @@ func SetQueueSettings(ctx *context.Context) {
number, err = strconv.Atoi(numberStr) number, err = strconv.Atoi(numberStr)
if err != nil || number < 0 { if err != nil || number < 0 {
ctx.Flash.Error(ctx.Tr("admin.monitor.queue.settings.numberworkers.error")) ctx.Flash.Error(ctx.Tr("admin.monitor.queue.settings.numberworkers.error"))
ctx.Redirect(setting.AppSubURL + fmt.Sprintf("/admin/monitor/queue/%d", qid)) ctx.Redirect(setting.AppSubURL + "/admin/monitor/queue/" + strconv.FormatInt(qid, 10))
return return
} }
} else { } else {
@ -470,7 +470,7 @@ func SetQueueSettings(ctx *context.Context) {
timeout, err = time.ParseDuration(timeoutStr) timeout, err = time.ParseDuration(timeoutStr)
if err != nil { if err != nil {
ctx.Flash.Error(ctx.Tr("admin.monitor.queue.settings.timeout.error")) ctx.Flash.Error(ctx.Tr("admin.monitor.queue.settings.timeout.error"))
ctx.Redirect(setting.AppSubURL + fmt.Sprintf("/admin/monitor/queue/%d", qid)) ctx.Redirect(setting.AppSubURL + "/admin/monitor/queue/" + strconv.FormatInt(qid, 10))
return return
} }
} else { } else {
@ -479,5 +479,5 @@ func SetQueueSettings(ctx *context.Context) {
mq.SetPoolSettings(maxNumber, number, timeout) mq.SetPoolSettings(maxNumber, number, timeout)
ctx.Flash.Success(ctx.Tr("admin.monitor.queue.settings.changed")) ctx.Flash.Success(ctx.Tr("admin.monitor.queue.settings.changed"))
ctx.Redirect(setting.AppSubURL + fmt.Sprintf("/admin/monitor/queue/%d", qid)) ctx.Redirect(setting.AppSubURL + "/admin/monitor/queue/" + strconv.FormatInt(qid, 10))
} }

View File

@ -5,7 +5,6 @@
package org package org
import ( import (
"fmt"
"net/http" "net/http"
"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
@ -153,8 +152,7 @@ func IsMember(ctx *context.APIContext) {
} }
} }
redirectURL := fmt.Sprintf("%sapi/v1/orgs/%s/public_members/%s", redirectURL := setting.AppURL + "api/v1/orgs/" + ctx.Org.Organization.Name + "/public_members/" + userToCheck.Name
setting.AppURL, ctx.Org.Organization.Name, userToCheck.Name)
ctx.Redirect(redirectURL, 302) ctx.Redirect(redirectURL, 302)
} }

View File

@ -40,8 +40,7 @@ func Search(ctx *context.Context) {
ctx.Data["Keyword"] = keyword ctx.Data["Keyword"] = keyword
ctx.Data["Language"] = language ctx.Data["Language"] = language
ctx.Data["queryType"] = queryType ctx.Data["queryType"] = queryType
ctx.Data["SourcePath"] = setting.AppSubURL + "/" + ctx.Data["SourcePath"] = path.Join(setting.AppSubURL, ctx.Repo.Repository.Owner.Name, ctx.Repo.Repository.Name)
path.Join(ctx.Repo.Repository.Owner.Name, ctx.Repo.Repository.Name)
ctx.Data["SearchResults"] = searchResults ctx.Data["SearchResults"] = searchResults
ctx.Data["SearchResultLanguages"] = searchResultLanguages ctx.Data["SearchResultLanguages"] = searchResultLanguages
ctx.Data["RequireHighlightJS"] = true ctx.Data["RequireHighlightJS"] = true

View File

@ -174,7 +174,7 @@ func NotificationStatusPost(c *context.Context) {
if c.Written() { if c.Written() {
return return
} }
c.Data["Link"] = fmt.Sprintf("%snotifications", setting.AppURL) c.Data["Link"] = setting.AppURL + "notifications"
c.HTML(http.StatusOK, tplNotificationDiv) c.HTML(http.StatusOK, tplNotificationDiv)
} }

View File

@ -35,7 +35,7 @@ func TestIsValidSlackChannel(t *testing.T) {
} }
func TestIsExternalURL(t *testing.T) { func TestIsExternalURL(t *testing.T) {
setting.AppURL = "https://try.gitea.io" setting.AppURL = "https://try.gitea.io/"
type test struct { type test struct {
Expected bool Expected bool
RawURL string RawURL string