From 688ec6ecbdf0e1c450aa93fdc4d760c4ae63a73f Mon Sep 17 00:00:00 2001 From: Unknown Date: Sun, 25 May 2014 20:11:25 -0400 Subject: Fixed #209 --- modules/base/conf.go | 354 ------------------------------------- modules/base/template.go | 10 +- modules/base/tool.go | 8 +- modules/bin/conf.go | 220 +++++++++++++++++++++++ modules/log/log.go | 10 ++ modules/mailer/mail.go | 21 +-- modules/mailer/mailer.go | 12 +- modules/middleware/auth.go | 6 +- modules/middleware/context.go | 5 +- modules/middleware/logger.go | 4 +- modules/middleware/render.go | 24 +-- modules/middleware/repo.go | 14 +- modules/setting/setting.go | 397 ++++++++++++++++++++++++++++++++++++++++++ modules/social/social.go | 52 +++--- 14 files changed, 704 insertions(+), 433 deletions(-) delete mode 100644 modules/base/conf.go create mode 100644 modules/bin/conf.go create mode 100644 modules/setting/setting.go (limited to 'modules') diff --git a/modules/base/conf.go b/modules/base/conf.go deleted file mode 100644 index df2bd827..00000000 --- a/modules/base/conf.go +++ /dev/null @@ -1,354 +0,0 @@ -// Copyright 2014 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. - -package base - -import ( - "fmt" - "os" - "os/exec" - "path" - "path/filepath" - "strings" - - "github.com/Unknwon/com" - "github.com/Unknwon/goconfig" - qlog "github.com/qiniu/log" - - "github.com/gogits/cache" - "github.com/gogits/session" - - "github.com/gogits/gogs/modules/log" -) - -// Mailer represents mail service. -type Mailer struct { - Name string - Host string - User, Passwd string -} - -type OauthInfo struct { - ClientId, ClientSecret string - Scopes string - AuthUrl, TokenUrl string -} - -// Oauther represents oauth service. -type Oauther struct { - GitHub, Google, Tencent, - Twitter, Weibo bool - OauthInfos map[string]*OauthInfo -} - -var ( - AppVer string - AppName string - AppLogo string - AppUrl string - SshPort int - OfflineMode bool - DisableRouterLog bool - ProdMode bool - Domain string - SecretKey string - RunUser string - - RepoRootPath string - ScriptType string - - InstallLock bool - - LogInRememberDays int - CookieUserName string - CookieRememberName string - - Cfg *goconfig.ConfigFile - MailService *Mailer - OauthService *Oauther - - LogModes []string - LogConfigs []string - - Cache cache.Cache - CacheAdapter string - CacheConfig string - - SessionProvider string - SessionConfig *session.Config - SessionManager *session.Manager - - PictureService string - DisableGravatar bool - - EnableRedis bool - EnableMemcache bool -) - -var Service struct { - RegisterEmailConfirm bool - DisableRegistration bool - RequireSignInView bool - EnableCacheAvatar bool - NotifyMail bool - ActiveCodeLives int - ResetPwdCodeLives int - LdapAuth bool -} - -// ExecDir returns absolute path execution(binary) path. -func ExecDir() (string, error) { - file, err := exec.LookPath(os.Args[0]) - if err != nil { - return "", err - } - p, err := filepath.Abs(file) - if err != nil { - return "", err - } - return path.Dir(strings.Replace(p, "\\", "/", -1)), nil -} - -var logLevels = map[string]string{ - "Trace": "0", - "Debug": "1", - "Info": "2", - "Warn": "3", - "Error": "4", - "Critical": "5", -} - -func newService() { - Service.ActiveCodeLives = Cfg.MustInt("service", "ACTIVE_CODE_LIVE_MINUTES", 180) - Service.ResetPwdCodeLives = Cfg.MustInt("service", "RESET_PASSWD_CODE_LIVE_MINUTES", 180) - Service.DisableRegistration = Cfg.MustBool("service", "DISABLE_REGISTRATION", false) - Service.RequireSignInView = Cfg.MustBool("service", "REQUIRE_SIGNIN_VIEW", false) - Service.EnableCacheAvatar = Cfg.MustBool("service", "ENABLE_CACHE_AVATAR", false) -} - -func newLogService() { - log.Info("%s %s", AppName, AppVer) - - // Get and check log mode. - LogModes = strings.Split(Cfg.MustValue("log", "MODE", "console"), ",") - LogConfigs = make([]string, len(LogModes)) - for i, mode := range LogModes { - mode = strings.TrimSpace(mode) - modeSec := "log." + mode - if _, err := Cfg.GetSection(modeSec); err != nil { - qlog.Fatalf("Unknown log mode: %s\n", mode) - } - - // Log level. - levelName := Cfg.MustValueRange("log."+mode, "LEVEL", "Trace", - []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"}) - level, ok := logLevels[levelName] - if !ok { - qlog.Fatalf("Unknown log level: %s\n", levelName) - } - - // Generate log configuration. - switch mode { - case "console": - LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level) - case "file": - logPath := Cfg.MustValue(modeSec, "FILE_NAME", "log/gogs.log") - os.MkdirAll(path.Dir(logPath), os.ModePerm) - LogConfigs[i] = fmt.Sprintf( - `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level, - logPath, - Cfg.MustBool(modeSec, "LOG_ROTATE", true), - Cfg.MustInt(modeSec, "MAX_LINES", 1000000), - 1<-
View it on Gogs.", base.RenderSpecialLink([]byte(issue.Content), owner.Name+"/"+repo.Name), - base.AppUrl, owner.Name, repo.Name, issue.Index) + setting.AppUrl, owner.Name, repo.Name, issue.Index) msg := NewMailMessageFrom(tos, user.Email, subject, content) msg.Info = fmt.Sprintf("Subject: %s, send issue notify emails", subject) SendAsync(&msg) diff --git a/modules/mailer/mailer.go b/modules/mailer/mailer.go index a293beb1..d398de60 100644 --- a/modules/mailer/mailer.go +++ b/modules/mailer/mailer.go @@ -9,8 +9,8 @@ import ( "net/smtp" "strings" - "github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/log" + "github.com/gogits/gogs/modules/setting" ) type Message struct { @@ -41,7 +41,7 @@ func (m Message) Content() string { var mailQueue chan *Message func NewMailerContext() { - mailQueue = make(chan *Message, base.Cfg.MustInt("mailer", "SEND_BUFFER_LEN", 10)) + mailQueue = make(chan *Message, setting.Cfg.MustInt("mailer", "SEND_BUFFER_LEN", 10)) go processMailQueue() } @@ -67,7 +67,7 @@ func processMailQueue() { // Direct Send mail message func Send(msg *Message) (int, error) { log.Trace("Sending mails to: %s", strings.Join(msg.To, "; ")) - host := strings.Split(base.MailService.Host, ":") + host := strings.Split(setting.MailService.Host, ":") // get message body content := msg.Content() @@ -78,14 +78,14 @@ func Send(msg *Message) (int, error) { return 0, fmt.Errorf("empty email body") } - auth := smtp.PlainAuth("", base.MailService.User, base.MailService.Passwd, host[0]) + auth := smtp.PlainAuth("", setting.MailService.User, setting.MailService.Passwd, host[0]) if msg.Massive { // send mail to multiple emails one by one num := 0 for _, to := range msg.To { body := []byte("To: " + to + "\r\n" + content) - err := smtp.SendMail(base.MailService.Host, auth, msg.From, []string{to}, body) + err := smtp.SendMail(setting.MailService.Host, auth, msg.From, []string{to}, body) if err != nil { return num, err } @@ -96,7 +96,7 @@ func Send(msg *Message) (int, error) { body := []byte("To: " + strings.Join(msg.To, ";") + "\r\n" + content) // send to multiple emails in one message - err := smtp.SendMail(base.MailService.Host, auth, msg.From, msg.To, body) + err := smtp.SendMail(setting.MailService.Host, auth, msg.From, msg.To, body) if err != nil { return 0, err } else { diff --git a/modules/middleware/auth.go b/modules/middleware/auth.go index e208fb01..214dda23 100644 --- a/modules/middleware/auth.go +++ b/modules/middleware/auth.go @@ -10,7 +10,7 @@ import ( "github.com/go-martini/martini" - "github.com/gogits/gogs/modules/base" + "github.com/gogits/gogs/modules/setting" ) type ToggleOptions struct { @@ -23,7 +23,7 @@ type ToggleOptions struct { func Toggle(options *ToggleOptions) martini.Handler { return func(ctx *Context) { // Cannot view any page before installation. - if !base.InstallLock { + if !setting.InstallLock { ctx.Redirect("/install") return } @@ -48,7 +48,7 @@ func Toggle(options *ToggleOptions) martini.Handler { ctx.SetCookie("redirect_to", "/"+url.QueryEscape(ctx.Req.RequestURI)) ctx.Redirect("/user/login") return - } else if !ctx.User.IsActive && base.Service.RegisterEmailConfirm { + } else if !ctx.User.IsActive && setting.Service.RegisterEmailConfirm { ctx.Data["Title"] = "Activate Your Account" ctx.HTML(200, "user/activate") return diff --git a/modules/middleware/context.go b/modules/middleware/context.go index e9084d33..8c837d08 100644 --- a/modules/middleware/context.go +++ b/modules/middleware/context.go @@ -28,6 +28,7 @@ import ( "github.com/gogits/gogs/modules/auth" "github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/log" + "github.com/gogits/gogs/modules/setting" ) // Context represents context of a request. @@ -325,14 +326,14 @@ func InitContext() martini.Handler { // p: p, Req: r, Res: res, - Cache: base.Cache, + Cache: setting.Cache, Render: rd, } ctx.Data["PageStartTime"] = time.Now() // start session - ctx.Session = base.SessionManager.SessionStart(res, r) + ctx.Session = setting.SessionManager.SessionStart(res, r) // Get flash. values, err := url.ParseQuery(ctx.GetCookie("gogs_flash")) diff --git a/modules/middleware/logger.go b/modules/middleware/logger.go index 1ee030a0..f918281a 100644 --- a/modules/middleware/logger.go +++ b/modules/middleware/logger.go @@ -13,7 +13,7 @@ import ( "github.com/go-martini/martini" - "github.com/gogits/gogs/modules/base" + "github.com/gogits/gogs/modules/setting" ) var isWindows bool @@ -24,7 +24,7 @@ func init() { func Logger() martini.Handler { return func(res http.ResponseWriter, req *http.Request, ctx martini.Context, log *log.Logger) { - if base.DisableRouterLog { + if setting.DisableRouterLog { return } diff --git a/modules/middleware/render.go b/modules/middleware/render.go index 66289988..b5a0d697 100644 --- a/modules/middleware/render.go +++ b/modules/middleware/render.go @@ -38,26 +38,18 @@ var helperFuncs = template.FuncMap{ } type Delims struct { - Left string - + Left string Right string } type RenderOptions struct { - Directory string - - Layout string - - Extensions []string - - Funcs []template.FuncMap - - Delims Delims - - Charset string - - IndentJSON bool - + Directory string + Layout string + Extensions []string + Funcs []template.FuncMap + Delims Delims + Charset string + IndentJSON bool HTMLContentType string } diff --git a/modules/middleware/repo.go b/modules/middleware/repo.go index 863860e7..c1acc827 100644 --- a/modules/middleware/repo.go +++ b/modules/middleware/repo.go @@ -15,8 +15,8 @@ import ( "github.com/gogits/git" "github.com/gogits/gogs/models" - "github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/log" + "github.com/gogits/gogs/modules/setting" ) func RepoAssignment(redirect bool, args ...bool) martini.Handler { @@ -159,17 +159,17 @@ func RepoAssignment(redirect bool, args ...bool) martini.Handler { ctx.Data["IsRepositoryOwner"] = ctx.Repo.IsOwner ctx.Data["BranchName"] = "" - if base.SshPort != 22 { - ctx.Repo.CloneLink.SSH = fmt.Sprintf("ssh://%s@%s/%s/%s.git", base.RunUser, base.Domain, user.LowerName, repo.LowerName) + if setting.SshPort != 22 { + ctx.Repo.CloneLink.SSH = fmt.Sprintf("ssh://%s@%s/%s/%s.git", setting.RunUser, setting.Domain, user.LowerName, repo.LowerName) } else { - ctx.Repo.CloneLink.SSH = fmt.Sprintf("%s@%s:%s/%s.git", base.RunUser, base.Domain, user.LowerName, repo.LowerName) + ctx.Repo.CloneLink.SSH = fmt.Sprintf("%s@%s:%s/%s.git", setting.RunUser, setting.Domain, user.LowerName, repo.LowerName) } - ctx.Repo.CloneLink.HTTPS = fmt.Sprintf("%s%s/%s.git", base.AppUrl, user.LowerName, repo.LowerName) + ctx.Repo.CloneLink.HTTPS = fmt.Sprintf("%s%s/%s.git", setting.AppUrl, user.LowerName, repo.LowerName) ctx.Data["CloneLink"] = ctx.Repo.CloneLink if ctx.Repo.Repository.IsGoget { - ctx.Data["GoGetLink"] = fmt.Sprintf("%s%s/%s", base.AppUrl, user.LowerName, repo.LowerName) - ctx.Data["GoGetImport"] = fmt.Sprintf("%s/%s/%s", base.Domain, user.LowerName, repo.LowerName) + ctx.Data["GoGetLink"] = fmt.Sprintf("%s%s/%s", setting.AppUrl, user.LowerName, repo.LowerName) + ctx.Data["GoGetImport"] = fmt.Sprintf("%s/%s/%s", setting.Domain, user.LowerName, repo.LowerName) } // when repo is bare, not valid branch diff --git a/modules/setting/setting.go b/modules/setting/setting.go new file mode 100644 index 00000000..451b2378 --- /dev/null +++ b/modules/setting/setting.go @@ -0,0 +1,397 @@ +// Copyright 2014 The Gogs Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package setting + +import ( + "fmt" + "os" + "os/exec" + "path" + "path/filepath" + "strings" + + "github.com/Unknwon/com" + "github.com/Unknwon/goconfig" + + "github.com/gogits/cache" + "github.com/gogits/session" + + "github.com/gogits/gogs/modules/bin" + "github.com/gogits/gogs/modules/log" +) + +type Scheme string + +const ( + HTTP Scheme = "http" + HTTPS Scheme = "https" +) + +var ( + // App settings. + AppVer string + AppName string + AppLogo string + AppUrl string + + // Server settings. + Protocol Scheme + Domain string + HttpAddr, HttpPort string + SshPort int + OfflineMode bool + DisableRouterLog bool + CertFile, KeyFile string + StaticRootPath string + + // Security settings. + InstallLock bool + SecretKey string + LogInRememberDays int + CookieUserName string + CookieRememberName string + + // Repository settings. + RepoRootPath string + ScriptType string + + // Picture settings. + PictureService string + DisableGravatar bool + + // Log settings. + LogModes []string + LogConfigs []string + + // Cache settings. + Cache cache.Cache + CacheAdapter string + CacheConfig string + + EnableRedis bool + EnableMemcache bool + + // Session settings. + SessionProvider string + SessionConfig *session.Config + SessionManager *session.Manager + + // Global setting objects. + Cfg *goconfig.ConfigFile + CustomPath string // Custom directory path. + ProdMode bool + RunUser string +) + +// WorkDir returns absolute path of work directory. +func WorkDir() (string, error) { + file, err := exec.LookPath(os.Args[0]) + if err != nil { + return "", err + } + p, err := filepath.Abs(file) + if err != nil { + return "", err + } + return path.Dir(strings.Replace(p, "\\", "/", -1)), nil +} + +// NewConfigContext initializes configuration context. +func NewConfigContext() { + workDir, err := WorkDir() + if err != nil { + log.Fatal("Fail to get work directory: %v", err) + } + + data, err := bin.Asset("conf/app.ini") + if err != nil { + log.Fatal("Fail to read 'conf/app.ini': %v", err) + } + Cfg, err = goconfig.LoadFromData(data) + if err != nil { + log.Fatal("Fail to parse 'conf/app.ini': %v", err) + } + + CustomPath = os.Getenv("GOGS_CUSTOM") + if len(CustomPath) == 0 { + CustomPath = path.Join(workDir, "custom") + } + log.Trace("Custom path: %s", CustomPath) + + cfgPath := path.Join(CustomPath, "conf/app.ini") + if com.IsFile(cfgPath) { + if err = Cfg.AppendFiles(cfgPath); err != nil { + log.Fatal("Fail to load custom 'conf/app.ini': %v", err) + } + } else { + log.Warn("No custom 'conf/app.ini' found") + } + + AppName = Cfg.MustValue("", "APP_NAME", "Gogs: Go Git Service") + AppLogo = Cfg.MustValue("", "APP_LOGO", "img/favicon.png") + AppUrl = Cfg.MustValue("server", "ROOT_URL", "http://localhost:3000") + + Protocol = HTTP + if Cfg.MustValue("server", "PROTOCOL") == "https" { + Protocol = HTTPS + CertFile = Cfg.MustValue("server", "CERT_FILE") + KeyFile = Cfg.MustValue("server", "KEY_FILE") + } + Domain = Cfg.MustValue("server", "DOMAIN", "localhost") + HttpAddr = Cfg.MustValue("server", "HTTP_ADDR", "0.0.0.0") + HttpPort = Cfg.MustValue("server", "HTTP_PORT", "3000") + SshPort = Cfg.MustInt("server", "SSH_PORT", 22) + OfflineMode = Cfg.MustBool("server", "OFFLINE_MODE") + DisableRouterLog = Cfg.MustBool("server", "DISABLE_ROUTER_LOG") + StaticRootPath = Cfg.MustValue("server", "STATIC_ROOT_PATH") + + InstallLock = Cfg.MustBool("security", "INSTALL_LOCK") + SecretKey = Cfg.MustValue("security", "SECRET_KEY") + LogInRememberDays = Cfg.MustInt("security", "LOGIN_REMEMBER_DAYS") + CookieUserName = Cfg.MustValue("security", "COOKIE_USERNAME") + CookieRememberName = Cfg.MustValue("security", "COOKIE_REMEMBER_NAME") + + RunUser = Cfg.MustValue("", "RUN_USER") + curUser := os.Getenv("USER") + if len(curUser) == 0 { + curUser = os.Getenv("USERNAME") + } + // Does not check run user when the install lock is off. + if InstallLock && RunUser != curUser { + log.Fatal("Expect user(%s) but current user is: %s", RunUser, curUser) + } + + // Determine and create root git reposiroty path. + homeDir, err := com.HomeDir() + if err != nil { + log.Fatal("Fail to get home directory: %v", err) + } + RepoRootPath = Cfg.MustValue("repository", "ROOT", filepath.Join(homeDir, "gogs-repositories")) + if err = os.MkdirAll(RepoRootPath, os.ModePerm); err != nil { + log.Fatal("Fail to create repository root path(%s): %v", RepoRootPath, err) + } + ScriptType = Cfg.MustValue("repository", "SCRIPT_TYPE", "bash") + + PictureService = Cfg.MustValueRange("picture", "SERVICE", "server", + []string{"server"}) + DisableGravatar = Cfg.MustBool("picture", "DISABLE_GRAVATAR") +} + +var Service struct { + RegisterEmailConfirm bool + DisableRegistration bool + RequireSignInView bool + EnableCacheAvatar bool + NotifyMail bool + ActiveCodeLives int + ResetPwdCodeLives int + LdapAuth bool +} + +func newService() { + Service.ActiveCodeLives = Cfg.MustInt("service", "ACTIVE_CODE_LIVE_MINUTES", 180) + Service.ResetPwdCodeLives = Cfg.MustInt("service", "RESET_PASSWD_CODE_LIVE_MINUTES", 180) + Service.DisableRegistration = Cfg.MustBool("service", "DISABLE_REGISTRATION") + Service.RequireSignInView = Cfg.MustBool("service", "REQUIRE_SIGNIN_VIEW") + Service.EnableCacheAvatar = Cfg.MustBool("service", "ENABLE_CACHE_AVATAR") +} + +var logLevels = map[string]string{ + "Trace": "0", + "Debug": "1", + "Info": "2", + "Warn": "3", + "Error": "4", + "Critical": "5", +} + +func newLogService() { + log.Info("%s %s", AppName, AppVer) + + // Get and check log mode. + LogModes = strings.Split(Cfg.MustValue("log", "MODE", "console"), ",") + LogConfigs = make([]string, len(LogModes)) + for i, mode := range LogModes { + mode = strings.TrimSpace(mode) + modeSec := "log." + mode + if _, err := Cfg.GetSection(modeSec); err != nil { + log.Fatal("Unknown log mode: %s", mode) + } + + // Log level. + levelName := Cfg.MustValueRange("log."+mode, "LEVEL", "Trace", + []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"}) + level, ok := logLevels[levelName] + if !ok { + log.Fatal("Unknown log level: %s", levelName) + } + + // Generate log configuration. + switch mode { + case "console": + LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level) + case "file": + logPath := Cfg.MustValue(modeSec, "FILE_NAME", "log/gogs.log") + os.MkdirAll(path.Dir(logPath), os.ModePerm) + LogConfigs[i] = fmt.Sprintf( + `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level, + logPath, + Cfg.MustBool(modeSec, "LOG_ROTATE", true), + Cfg.MustInt(modeSec, "MAX_LINES", 1000000), + 1<