From 688ec6ecbdf0e1c450aa93fdc4d760c4ae63a73f Mon Sep 17 00:00:00 2001 From: Unknown Date: Sun, 25 May 2014 20:11:25 -0400 Subject: Fixed #209 --- cmd/dump.go | 18 +- cmd/fix.go | 10 +- cmd/serve.go | 12 +- cmd/web.go | 40 ++-- conf/app.ini | 3 + gogs.go | 6 +- models/action.go | 3 +- models/models.go | 20 +- models/repo.go | 36 ++-- models/user.go | 9 +- 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 +++--- routers/admin/admin.go | 43 ++--- routers/api/v1/miscellaneous.go | 3 +- routers/dashboard.go | 4 +- routers/dev/template.go | 14 +- routers/install.go | 68 +++---- routers/repo/branch.go | 7 +- routers/repo/commit.go | 24 +-- routers/repo/download.go | 21 +-- routers/repo/git.go | 55 ------ routers/repo/http.go | 27 +-- routers/repo/issue.go | 5 +- routers/repo/setting.go | 3 +- routers/user/social.go | 6 +- routers/user/user.go | 47 ++--- 38 files changed, 916 insertions(+), 705 deletions(-) delete mode 100644 modules/base/conf.go create mode 100644 modules/bin/conf.go create mode 100644 modules/setting/setting.go delete mode 100644 routers/repo/git.go diff --git a/cmd/dump.go b/cmd/dump.go index 1bac1aee..2a54db1a 100644 --- a/cmd/dump.go +++ b/cmd/dump.go @@ -15,7 +15,7 @@ import ( "github.com/codegangsta/cli" "github.com/gogits/gogs/models" - "github.com/gogits/gogs/modules/base" + "github.com/gogits/gogs/modules/setting" ) var CmdDump = cli.Command{ @@ -28,14 +28,14 @@ It can be used for backup and capture Gogs server image to send to maintainer`, } func runDump(*cli.Context) { - base.NewConfigContext() + setting.NewConfigContext() models.LoadModelsConfig() models.SetEngine() - log.Printf("Dumping local repositories...%s", base.RepoRootPath) + log.Printf("Dumping local repositories...%s", setting.RepoRootPath) zip.Verbose = false defer os.Remove("gogs-repo.zip") - if err := zip.PackTo(base.RepoRootPath, "gogs-repo.zip", true); err != nil { + if err := zip.PackTo(setting.RepoRootPath, "gogs-repo.zip", true); err != nil { log.Fatalf("Fail to dump local repositories: %v", err) } @@ -53,11 +53,11 @@ func runDump(*cli.Context) { log.Fatalf("Fail to create %s: %v", fileName, err) } - execDir, _ := base.ExecDir() - z.AddFile("gogs-repo.zip", path.Join(execDir, "gogs-repo.zip")) - z.AddFile("gogs-db.sql", path.Join(execDir, "gogs-db.sql")) - z.AddFile("custom/conf/app.ini", path.Join(execDir, "custom/conf/app.ini")) - z.AddDir("log", path.Join(execDir, "log")) + workDir, _ := setting.WorkDir() + z.AddFile("gogs-repo.zip", path.Join(workDir, "gogs-repo.zip")) + z.AddFile("gogs-db.sql", path.Join(workDir, "gogs-db.sql")) + z.AddFile("custom/conf/app.ini", path.Join(workDir, "custom/conf/app.ini")) + z.AddDir("log", path.Join(workDir, "log")) if err = z.Close(); err != nil { os.Remove(fileName) log.Fatalf("Fail to save %s: %v", fileName, err) diff --git a/cmd/fix.go b/cmd/fix.go index 809c0039..3c2278ba 100644 --- a/cmd/fix.go +++ b/cmd/fix.go @@ -10,7 +10,7 @@ import ( "github.com/codegangsta/cli" "github.com/gogits/gogs/models" - "github.com/gogits/gogs/modules/base" + "github.com/gogits/gogs/modules/setting" ) var CmdFix = cli.Command{ @@ -22,14 +22,14 @@ var CmdFix = cli.Command{ } func runFix(k *cli.Context) { - execDir, _ := base.ExecDir() - newLogger(execDir) + workDir, _ := setting.WorkDir() + newLogger(workDir) - base.NewConfigContext() + setting.NewConfigContext() models.LoadModelsConfig() if models.UseSQLite3 { - os.Chdir(execDir) + os.Chdir(workDir) } models.SetEngine() diff --git a/cmd/serve.go b/cmd/serve.go index f7b0d204..47406dd0 100644 --- a/cmd/serve.go +++ b/cmd/serve.go @@ -16,7 +16,7 @@ import ( qlog "github.com/qiniu/log" "github.com/gogits/gogs/models" - "github.com/gogits/gogs/modules/base" + "github.com/gogits/gogs/modules/setting" ) var CmdServ = cli.Command{ @@ -41,14 +41,14 @@ func newLogger(logPath string) { } func setup(logPath string) { - execDir, _ := base.ExecDir() - newLogger(path.Join(execDir, logPath)) + workDir, _ := setting.WorkDir() + newLogger(path.Join(workDir, logPath)) - base.NewConfigContext() + setting.NewConfigContext() models.LoadModelsConfig() if models.UseSQLite3 { - os.Chdir(execDir) + os.Chdir(workDir) } models.SetEngine() @@ -182,7 +182,7 @@ func runServ(k *cli.Context) { models.SetRepoEnvs(user.Id, user.Name, repoName, repoUserName) gitcmd := exec.Command(verb, repoPath) - gitcmd.Dir = base.RepoRootPath + gitcmd.Dir = setting.RepoRootPath gitcmd.Stdout = os.Stdout gitcmd.Stdin = os.Stdin gitcmd.Stderr = os.Stderr diff --git a/cmd/web.go b/cmd/web.go index 0e8fc09b..2019b440 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -9,10 +9,10 @@ import ( "html/template" "net/http" "os" + "path" "github.com/codegangsta/cli" "github.com/go-martini/martini" - qlog "github.com/qiniu/log" "github.com/gogits/gogs/modules/auth" "github.com/gogits/gogs/modules/auth/apiv1" @@ -21,6 +21,7 @@ import ( "github.com/gogits/gogs/modules/log" "github.com/gogits/gogs/modules/middleware" "github.com/gogits/gogs/modules/middleware/binding" + "github.com/gogits/gogs/modules/setting" "github.com/gogits/gogs/routers" "github.com/gogits/gogs/routers/admin" "github.com/gogits/gogs/routers/api/v1" @@ -43,7 +44,8 @@ func newMartini() *martini.ClassicMartini { m := martini.New() m.Use(middleware.Logger()) m.Use(martini.Recovery()) - m.Use(martini.Static("public", martini.StaticOptions{SkipLogging: !base.DisableRouterLog})) + m.Use(martini.Static(path.Join(setting.StaticRootPath, "public"), + martini.StaticOptions{SkipLogging: !setting.DisableRouterLog})) m.MapTo(r, (*martini.Routes)(nil)) m.Action(r.Handle) return &martini.ClassicMartini{m, r} @@ -56,13 +58,14 @@ func runWeb(*cli.Context) { // Middlewares. m.Use(middleware.Renderer(middleware.RenderOptions{ + Directory: path.Join(setting.StaticRootPath, "templates"), Funcs: []template.FuncMap{base.TemplateFuncs}, IndentJSON: true, })) m.Use(middleware.InitContext()) reqSignIn := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: true}) - ignSignIn := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: base.Service.RequireSignInView}) + ignSignIn := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: setting.Service.RequireSignInView}) ignSignInAndCsrf := middleware.Toggle(&middleware.ToggleOptions{DisableCsrf: true}) reqSignOut := middleware.Toggle(&middleware.ToggleOptions{SignOutRequire: true}) @@ -241,22 +244,19 @@ func runWeb(*cli.Context) { // Not found handler. m.NotFound(routers.NotFound) - protocol := base.Cfg.MustValue("server", "PROTOCOL", "http") - listenAddr := fmt.Sprintf("%s:%s", - base.Cfg.MustValue("server", "HTTP_ADDR", "0.0.0.0"), - base.Cfg.MustValue("server", "HTTP_PORT", "3000")) - - if protocol == "http" { - log.Info("Listen: http://%s", listenAddr) - if err := http.ListenAndServe(listenAddr, m); err != nil { - qlog.Error(err.Error()) - } - } else if protocol == "https" { - log.Info("Listen: https://%s", listenAddr) - if err := http.ListenAndServeTLS(listenAddr, base.Cfg.MustValue("server", "CERT_FILE"), - base.Cfg.MustValue("server", "KEY_FILE"), m); err != nil { - qlog.Error(err.Error()) - } + var err error + listenAddr := fmt.Sprintf("%s:%s", setting.HttpAddr, setting.HttpPort) + log.Info("Listen: %v://%s", setting.Protocol, listenAddr) + switch setting.Protocol { + case setting.HTTP: + err = http.ListenAndServe(listenAddr, m) + case setting.HTTPS: + err = http.ListenAndServeTLS(listenAddr, setting.CertFile, setting.KeyFile, m) + default: + log.Fatal("Invalid protocol: %s", setting.Protocol) + } + + if err != nil { + log.Fatal("Fail to start server: %v", err) } - qlog.Fatalf("Invalid protocol: %s", protocol) } diff --git a/conf/app.ini b/conf/app.ini index 2217682c..70ca1e73 100644 --- a/conf/app.ini +++ b/conf/app.ini @@ -25,6 +25,9 @@ DISABLE_ROUTER_LOG = false ; $ go run $GOROOT/src/pkg/crypto/tls/generate_cert.go -ca=true -duration=8760h0m0s -host=myhost.example.com CERT_FILE = custom/https/cert.pem KEY_FILE = custom/https/key.pem +; Upper level of template and static file path +; default is the path where Gogs is executed +STATIC_ROOT_PATH = [database] ; Either "mysql", "postgres" or "sqlite3", it's your choice diff --git a/gogs.go b/gogs.go index bdec2a71..6bdc2e1e 100644 --- a/gogs.go +++ b/gogs.go @@ -14,13 +14,13 @@ import ( "github.com/codegangsta/cli" "github.com/gogits/gogs/cmd" - "github.com/gogits/gogs/modules/base" + "github.com/gogits/gogs/modules/setting" ) -const APP_VER = "0.3.5.0524 Alpha" +const APP_VER = "0.3.5.0525 Alpha" func init() { - base.AppVer = APP_VER + setting.AppVer = APP_VER runtime.GOMAXPROCS(runtime.NumCPU()) } diff --git a/models/action.go b/models/action.go index 62cff862..9fc9d89b 100644 --- a/models/action.go +++ b/models/action.go @@ -17,6 +17,7 @@ import ( "github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/hooks" "github.com/gogits/gogs/modules/log" + "github.com/gogits/gogs/modules/setting" ) // Operation types of user action. @@ -129,7 +130,7 @@ func CommitRepoAction(userId, repoUserId int64, userName, actEmail string, return nil } - repoLink := fmt.Sprintf("%s%s/%s", base.AppUrl, repoUserName, repoName) + repoLink := fmt.Sprintf("%s%s/%s", setting.AppUrl, repoUserName, repoName) commits := make([]*hooks.PayloadCommit, len(commit.Commits)) for i, cmt := range commit.Commits { commits[i] = &hooks.PayloadCommit{ diff --git a/models/models.go b/models/models.go index 841b1063..c9fb0a4c 100644 --- a/models/models.go +++ b/models/models.go @@ -14,7 +14,7 @@ import ( "github.com/go-xorm/xorm" _ "github.com/lib/pq" - "github.com/gogits/gogs/modules/base" + "github.com/gogits/gogs/modules/setting" ) var ( @@ -39,16 +39,16 @@ func init() { } func LoadModelsConfig() { - DbCfg.Type = base.Cfg.MustValue("database", "DB_TYPE") + DbCfg.Type = setting.Cfg.MustValue("database", "DB_TYPE") if DbCfg.Type == "sqlite3" { UseSQLite3 = true } - DbCfg.Host = base.Cfg.MustValue("database", "HOST") - DbCfg.Name = base.Cfg.MustValue("database", "NAME") - DbCfg.User = base.Cfg.MustValue("database", "USER") - DbCfg.Pwd = base.Cfg.MustValue("database", "PASSWD") - DbCfg.SslMode = base.Cfg.MustValue("database", "SSL_MODE") - DbCfg.Path = base.Cfg.MustValue("database", "PATH", "data/gogs.db") + DbCfg.Host = setting.Cfg.MustValue("database", "HOST") + DbCfg.Name = setting.Cfg.MustValue("database", "NAME") + DbCfg.User = setting.Cfg.MustValue("database", "USER") + DbCfg.Pwd = setting.Cfg.MustValue("database", "PASSWD") + DbCfg.SslMode = setting.Cfg.MustValue("database", "SSL_MODE") + DbCfg.Path = setting.Cfg.MustValue("database", "PATH", "data/gogs.db") } func NewTestEngine(x *xorm.Engine) (err error) { @@ -112,8 +112,8 @@ func SetEngine() (err error) { // WARNNING: for serv command, MUST remove the output to os.stdout, // so use log file to instead print to stdout. - execDir, _ := base.ExecDir() - logPath := execDir + "/log/xorm.log" + workDir, _ := setting.WorkDir() + logPath := workDir + "/log/xorm.log" os.MkdirAll(path.Dir(logPath), os.ModePerm) f, err := os.Create(logPath) diff --git a/models/repo.go b/models/repo.go index fe4b39c2..5ab7d76a 100644 --- a/models/repo.go +++ b/models/repo.go @@ -23,7 +23,9 @@ import ( "github.com/gogits/git" "github.com/gogits/gogs/modules/base" + "github.com/gogits/gogs/modules/bin" "github.com/gogits/gogs/modules/log" + "github.com/gogits/gogs/modules/setting" ) var ( @@ -39,26 +41,28 @@ var ( LanguageIgns, Licenses []string ) -func LoadRepoConfig() { - workDir, err := base.ExecDir() - if err != nil { - qlog.Fatalf("Fail to get work directory: %s\n", err) +// getAssetList returns corresponding asset list in 'conf'. +func getAssetList(prefix string) []string { + assets := make([]string, 0, 15) + for _, name := range bin.AssetNames() { + if strings.HasPrefix(name, prefix) { + assets = append(assets, name) + } } + return assets +} +func LoadRepoConfig() { // Load .gitignore and license files. types := []string{"gitignore", "license"} typeFiles := make([][]string, 2) for i, t := range types { - cfgPath := filepath.Join(workDir, "conf", t) - files, err := com.StatDir(cfgPath) - if err != nil { - qlog.Fatalf("Fail to get default %s files: %v\n", t, err) - } - cfgPath = filepath.Join(workDir, "custom/conf/gitignore") - if com.IsDir(cfgPath) { - customFiles, err := com.StatDir(cfgPath) + files := getAssetList(path.Join("conf", t)) + customPath := path.Join(setting.CustomPath, "conf", t) + if com.IsDir(customPath) { + customFiles, err := com.StatDir(customPath) if err != nil { - qlog.Fatalf("Fail to get custom %s files: %v\n", t, err) + log.Fatal("Fail to get custom %s files: %v", t, err) } for _, f := range customFiles { @@ -192,7 +196,7 @@ func MirrorUpdate() { return nil } - repoPath := filepath.Join(base.RepoRootPath, m.RepoName+".git") + repoPath := filepath.Join(setting.RepoRootPath, m.RepoName+".git") _, stderr, err := com.ExecCmdDir(repoPath, "git", "remote", "update") if err != nil { return errors.New("git remote update: " + stderr) @@ -434,7 +438,7 @@ func initRepository(f string, user *User, repo *Repository, initReadme bool, rep rp := strings.NewReplacer("\\", "/", " ", "\\ ") // hook/post-update if err := createHookUpdate(filepath.Join(repoPath, "hooks", "update"), - fmt.Sprintf("#!/usr/bin/env %s\n%s update $1 $2 $3\n", base.ScriptType, + fmt.Sprintf("#!/usr/bin/env %s\n%s update $1 $2 $3\n", setting.ScriptType, rp.Replace(appPath))); err != nil { return err } @@ -452,7 +456,7 @@ func initRepository(f string, user *User, repo *Repository, initReadme bool, rep } // Clone to temprory path and do the init commit. - tmpDir := filepath.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond())) + tmpDir := filepath.Join(os.TempDir(), base.ToStr(time.Now().Nanosecond())) os.MkdirAll(tmpDir, os.ModePerm) _, stderr, err := com.ExecCmd("git", "clone", repoPath, tmpDir) diff --git a/models/user.go b/models/user.go index 1a2f3a5e..dd70a35f 100644 --- a/models/user.go +++ b/models/user.go @@ -18,6 +18,7 @@ import ( "github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/log" + "github.com/gogits/gogs/modules/setting" ) // User types. @@ -73,9 +74,9 @@ func (user *User) HomeLink() string { // AvatarLink returns the user gravatar link. func (user *User) AvatarLink() string { - if base.DisableGravatar { + if setting.DisableGravatar { return "/img/avatar_default.jpg" - } else if base.Service.EnableCacheAvatar { + } else if setting.Service.EnableCacheAvatar { return "/avatar/" + user.Avatar } return "//1.gravatar.com/avatar/" + user.Avatar @@ -197,7 +198,7 @@ func getVerifyUser(code string) (user *User) { // verify active code when active account func VerifyUserActiveCode(code string) (user *User) { - minutes := base.Service.ActiveCodeLives + minutes := setting.Service.ActiveCodeLives if user = getVerifyUser(code); user != nil { // time limit code @@ -340,7 +341,7 @@ func DeleteUser(user *User) error { // UserPath returns the path absolute path of user repositories. func UserPath(userName string) string { - return filepath.Join(base.RepoRootPath, strings.ToLower(userName)) + return filepath.Join(setting.RepoRootPath, strings.ToLower(userName)) } func GetUserByKeyId(keyId int64) (*User, error) { 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< 0 { - base.Cfg.SetValue("mailer", "ENABLED", "true") - base.Cfg.SetValue("mailer", "HOST", form.SmtpHost) - base.Cfg.SetValue("mailer", "USER", form.SmtpEmail) - base.Cfg.SetValue("mailer", "PASSWD", form.SmtpPasswd) + setting.Cfg.SetValue("mailer", "ENABLED", "true") + setting.Cfg.SetValue("mailer", "HOST", form.SmtpHost) + setting.Cfg.SetValue("mailer", "USER", form.SmtpEmail) + setting.Cfg.SetValue("mailer", "PASSWD", form.SmtpPasswd) - base.Cfg.SetValue("service", "REGISTER_EMAIL_CONFIRM", base.ToStr(form.RegisterConfirm == "on")) - base.Cfg.SetValue("service", "ENABLE_NOTIFY_MAIL", base.ToStr(form.MailNotify == "on")) + setting.Cfg.SetValue("service", "REGISTER_EMAIL_CONFIRM", base.ToStr(form.RegisterConfirm == "on")) + setting.Cfg.SetValue("service", "ENABLE_NOTIFY_MAIL", base.ToStr(form.MailNotify == "on")) } - base.Cfg.SetValue("", "RUN_MODE", "prod") + setting.Cfg.SetValue("", "RUN_MODE", "prod") - base.Cfg.SetValue("security", "INSTALL_LOCK", "true") + setting.Cfg.SetValue("security", "INSTALL_LOCK", "true") os.MkdirAll("custom/conf", os.ModePerm) - if err := goconfig.SaveConfigFile(base.Cfg, "custom/conf/app.ini"); err != nil { + if err := goconfig.SaveConfigFile(setting.Cfg, path.Join(setting.CustomPath, "conf/app.ini")); err != nil { ctx.RenderWithErr("Fail to save configuration: "+err.Error(), "install", &form) return } @@ -220,7 +222,7 @@ func InstallPost(ctx *middleware.Context, form auth.InstallForm) { if _, err := models.RegisterUser(&models.User{Name: form.AdminName, Email: form.AdminEmail, Passwd: form.AdminPasswd, IsAdmin: true, IsActive: true}); err != nil { if err != models.ErrUserAlreadyExist { - base.InstallLock = false + setting.InstallLock = false ctx.RenderWithErr("Admin account setting is invalid: "+err.Error(), "install", &form) return } diff --git a/routers/repo/branch.go b/routers/repo/branch.go index 92265d2e..2e2ae692 100644 --- a/routers/repo/branch.go +++ b/routers/repo/branch.go @@ -11,9 +11,12 @@ import ( ) func Branches(ctx *middleware.Context, params martini.Params) { + ctx.Data["Title"] = "Branches" + ctx.Data["IsRepoToolbarBranches"] = true + brs, err := ctx.Repo.GitRepo.GetBranches() if err != nil { - ctx.Handle(404, "repo.Branches", err) + ctx.Handle(500, "repo.Branches", err) return } else if len(brs) == 0 { ctx.Handle(404, "repo.Branches", nil) @@ -21,7 +24,5 @@ func Branches(ctx *middleware.Context, params martini.Params) { } ctx.Data["Branches"] = brs - ctx.Data["IsRepoToolbarBranches"] = true - ctx.HTML(200, "repo/branches") } diff --git a/routers/repo/commit.go b/routers/repo/commit.go index 88b6593e..44427b8a 100644 --- a/routers/repo/commit.go +++ b/routers/repo/commit.go @@ -15,6 +15,8 @@ import ( ) func Commits(ctx *middleware.Context, params martini.Params) { + ctx.Data["IsRepoToolbarCommits"] = true + userName := ctx.Repo.Owner.Name repoName := ctx.Repo.Repository.Name @@ -47,8 +49,8 @@ func Commits(ctx *middleware.Context, params martini.Params) { nextPage = 0 } - //both `git log branchName` and `git log commitId` work - commits, err := ctx.Repo.Commit.CommitsByRange(page) + // Both `git log branchName` and `git log commitId` work. + ctx.Data["Commits"], err = ctx.Repo.Commit.CommitsByRange(page) if err != nil { ctx.Handle(500, "repo.Commits(CommitsByRange)", err) return @@ -57,14 +59,14 @@ func Commits(ctx *middleware.Context, params martini.Params) { ctx.Data["Username"] = userName ctx.Data["Reponame"] = repoName ctx.Data["CommitCount"] = commitsCount - ctx.Data["Commits"] = commits ctx.Data["LastPageNum"] = lastPage ctx.Data["NextPageNum"] = nextPage - ctx.Data["IsRepoToolbarCommits"] = true ctx.HTML(200, "repo/commits") } func Diff(ctx *middleware.Context, params martini.Params) { + ctx.Data["IsRepoToolbarCommits"] = true + userName := ctx.Repo.Owner.Name repoName := ctx.Repo.Repository.Name commitId := ctx.Repo.CommitId @@ -109,13 +111,15 @@ func Diff(ctx *middleware.Context, params martini.Params) { ctx.Data["Diff"] = diff ctx.Data["Parents"] = parents ctx.Data["DiffNotAvailable"] = diff.NumFiles() == 0 - ctx.Data["IsRepoToolbarCommits"] = true ctx.Data["SourcePath"] = "/" + path.Join(userName, repoName, "src", commitId) ctx.Data["RawPath"] = "/" + path.Join(userName, repoName, "raw", commitId) ctx.HTML(200, "repo/diff") } func SearchCommits(ctx *middleware.Context, params martini.Params) { + ctx.Data["IsSearchPage"] = true + ctx.Data["IsRepoToolbarCommits"] = true + keyword := ctx.Query("q") if len(keyword) == 0 { ctx.Redirect(ctx.Repo.RepoLink + "/commits/" + ctx.Repo.BranchName) @@ -145,12 +149,12 @@ func SearchCommits(ctx *middleware.Context, params martini.Params) { ctx.Data["Reponame"] = repoName ctx.Data["CommitCount"] = commits.Len() ctx.Data["Commits"] = commits - ctx.Data["IsSearchPage"] = true - ctx.Data["IsRepoToolbarCommits"] = true ctx.HTML(200, "repo/commits") } func FileHistory(ctx *middleware.Context, params martini.Params) { + ctx.Data["IsRepoToolbarCommits"] = true + fileName := params["_1"] if len(fileName) == 0 { Commits(ctx, params) @@ -194,8 +198,8 @@ func FileHistory(ctx *middleware.Context, params martini.Params) { nextPage = 0 } - //both `git log branchName` and `git log commitId` work - commits, err := ctx.Repo.GitRepo.CommitsByFileAndRange(branchName, fileName, page) + ctx.Data["Commits"], err = ctx.Repo.GitRepo.CommitsByFileAndRange( + branchName, fileName, page) if err != nil { ctx.Handle(500, "repo.FileHistory(CommitsByRange)", err) return @@ -205,9 +209,7 @@ func FileHistory(ctx *middleware.Context, params martini.Params) { ctx.Data["Reponame"] = repoName ctx.Data["FileName"] = fileName ctx.Data["CommitCount"] = commitsCount - ctx.Data["Commits"] = commits ctx.Data["LastPageNum"] = lastPage ctx.Data["NextPageNum"] = nextPage - ctx.Data["IsRepoToolbarCommits"] = true ctx.HTML(200, "repo/commits") } diff --git a/routers/repo/download.go b/routers/repo/download.go index e5ec1c79..5df78dc7 100644 --- a/routers/repo/download.go +++ b/routers/repo/download.go @@ -18,18 +18,17 @@ import ( ) func SingleDownload(ctx *middleware.Context, params martini.Params) { - // Get tree path treename := params["_1"] blob, err := ctx.Repo.Commit.GetBlobByPath(treename) if err != nil { - ctx.Handle(404, "repo.SingleDownload(GetBlobByPath)", err) + ctx.Handle(500, "repo.SingleDownload(GetBlobByPath)", err) return } data, err := blob.Data() if err != nil { - ctx.Handle(404, "repo.SingleDownload(Data)", err) + ctx.Handle(500, "repo.SingleDownload(Data)", err) return } @@ -47,8 +46,8 @@ func ZipDownload(ctx *middleware.Context, params martini.Params) { commitId := ctx.Repo.CommitId archivesPath := filepath.Join(ctx.Repo.GitRepo.Path, "archives/zip") if !com.IsDir(archivesPath) { - if err := os.MkdirAll(archivesPath, 0755); err != nil { - ctx.Handle(404, "ZipDownload -> os.Mkdir(archivesPath)", err) + if err := os.MkdirAll(archivesPath, 0655); err != nil { + ctx.Handle(500, "ZipDownload -> os.Mkdir(archivesPath)", err) return } } @@ -60,9 +59,8 @@ func ZipDownload(ctx *middleware.Context, params martini.Params) { return } - err := ctx.Repo.Commit.CreateArchive(archivePath, git.AT_ZIP) - if err != nil { - ctx.Handle(404, "ZipDownload -> CreateArchive "+archivePath, err) + if err := ctx.Repo.Commit.CreateArchive(archivePath, git.AT_ZIP); err != nil { + ctx.Handle(500, "ZipDownload -> CreateArchive "+archivePath, err) return } @@ -74,7 +72,7 @@ func TarGzDownload(ctx *middleware.Context, params martini.Params) { archivesPath := filepath.Join(ctx.Repo.GitRepo.Path, "archives/targz") if !com.IsDir(archivesPath) { if err := os.MkdirAll(archivesPath, 0755); err != nil { - ctx.Handle(404, "TarGzDownload -> os.Mkdir(archivesPath)", err) + ctx.Handle(500, "TarGzDownload -> os.Mkdir(archivesPath)", err) return } } @@ -86,9 +84,8 @@ func TarGzDownload(ctx *middleware.Context, params martini.Params) { return } - err := ctx.Repo.Commit.CreateArchive(archivePath, git.AT_TARGZ) - if err != nil { - ctx.Handle(404, "TarGzDownload -> CreateArchive "+archivePath, err) + if err := ctx.Repo.Commit.CreateArchive(archivePath, git.AT_TARGZ); err != nil { + ctx.Handle(500, "TarGzDownload -> CreateArchive "+archivePath, err) return } diff --git a/routers/repo/git.go b/routers/repo/git.go deleted file mode 100644 index 30c1042e..00000000 --- a/routers/repo/git.go +++ /dev/null @@ -1,55 +0,0 @@ -package repo - -import ( - "fmt" - "strings" -) - -const advertise_refs = "--advertise-refs" - -func command(cmd string, opts ...string) string { - return fmt.Sprintf("git %s %s", cmd, strings.Join(opts, " ")) -} - -/*func upload_pack(repository_path string, opts ...string) string { - cmd = "upload-pack" - opts = append(opts, "--stateless-rpc", repository_path) - return command(cmd, opts...) -} - -func receive_pack(repository_path string, opts ...string) string { - cmd = "receive-pack" - opts = append(opts, "--stateless-rpc", repository_path) - return command(cmd, opts...) -}*/ - -/*func update_server_info(repository_path, opts = {}, &block) - cmd = "update-server-info" - args = [] - opts.each {|k,v| args << command_options[k] if command_options.has_key?(k) } - opts[:args] = args - Dir.chdir(repository_path) do # "git update-server-info" does not take a parameter to specify the repository, so set the working directory to the repository - self.command(cmd, opts, &block) - end - end - - def get_config_setting(repository_path, key) - path = get_config_location(repository_path) - raise "Config file could not be found for repository in #{repository_path}." unless path - self.command("config", {:args => ["-f #{path}", key]}).chomp - end - - def get_config_location(repository_path) - non_bare = File.join(repository_path,'.git') # This is where the config file will be if the repository is non-bare - if File.exists?(non_bare) then # The repository is non-bare - non_bare_config = File.join(non_bare, 'config') - return non_bare_config if File.exists?(non_bare_config) - else # We are dealing with a bare repository - bare_config = File.join(repository_path, "config") - return bare_config if File.exists?(bare_config) - end - return nil - end - - end -*/ diff --git a/routers/repo/http.go b/routers/repo/http.go index a6189ff2..f4cc00aa 100644 --- a/routers/repo/http.go +++ b/routers/repo/http.go @@ -22,8 +22,8 @@ import ( "github.com/go-martini/martini" "github.com/gogits/gogs/models" - "github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/middleware" + "github.com/gogits/gogs/modules/setting" ) func Http(ctx *middleware.Context, params martini.Params) { @@ -59,7 +59,7 @@ func Http(ctx *middleware.Context, params martini.Params) { // only public pull don't need auth isPublicPull := !repo.IsPrivate && isPull - var askAuth = !isPublicPull || base.Service.RequireSignInView + var askAuth = !isPublicPull || setting.Service.RequireSignInView var authUser *models.User var authUsername, passwd string @@ -123,7 +123,7 @@ func Http(ctx *middleware.Context, params martini.Params) { } } - config := Config{base.RepoRootPath, "git", true, true, func(rpc string, input []byte) { + config := Config{setting.RepoRootPath, "git", true, true, func(rpc string, input []byte) { if rpc == "receive-pack" { firstLine := bytes.IndexRune(input, '\000') if firstLine > -1 { @@ -141,16 +141,6 @@ func Http(ctx *middleware.Context, params martini.Params) { handler := HttpBackend(&config) handler(ctx.ResponseWriter, ctx.Req) - - /* Webdav - dir := models.RepoPath(username, reponame) - - prefix := path.Join("/", username, params["reponame"]) - server := webdav.NewServer( - dir, prefix, true) - - server.ServeHTTP(ctx.ResponseWriter, ctx.Req) - */ } type route struct { @@ -483,14 +473,3 @@ func hdrCacheForever(w http.ResponseWriter) { w.Header().Set("Expires", fmt.Sprintf("%d", expires)) w.Header().Set("Cache-Control", "public, max-age=31536000") } - -// Main -/* -func main() { - http.HandleFunc("/", requestHandler()) - - err := http.ListenAndServe(":8080", nil) - if err != nil { - log.Fatal("ListenAndServe: ", err) - } -}*/ diff --git a/routers/repo/issue.go b/routers/repo/issue.go index 6e04288c..006b467a 100644 --- a/routers/repo/issue.go +++ b/routers/repo/issue.go @@ -19,6 +19,7 @@ import ( "github.com/gogits/gogs/modules/log" "github.com/gogits/gogs/modules/mailer" "github.com/gogits/gogs/modules/middleware" + "github.com/gogits/gogs/modules/setting" ) func Issues(ctx *middleware.Context) { @@ -242,7 +243,7 @@ func CreateIssuePost(ctx *middleware.Context, params martini.Params, form auth.C } // Mail watchers and mentions. - if base.Service.NotifyMail { + if setting.Service.NotifyMail { tos, err := mailer.SendIssueNotifyMail(ctx.User, ctx.Repo.Owner, ctx.Repo.Repository, issue) if err != nil { ctx.Handle(500, "issue.CreateIssue(SendIssueNotifyMail)", err) @@ -677,7 +678,7 @@ func Comment(ctx *middleware.Context, params martini.Params) { } // Mail watchers and mentions. - if base.Service.NotifyMail { + if setting.Service.NotifyMail { issue.Content = content tos, err := mailer.SendIssueNotifyMail(ctx.User, ctx.Repo.Owner, ctx.Repo.Repository, issue) if err != nil { diff --git a/routers/repo/setting.go b/routers/repo/setting.go index fa4973ec..fe248992 100644 --- a/routers/repo/setting.go +++ b/routers/repo/setting.go @@ -16,6 +16,7 @@ import ( "github.com/gogits/gogs/modules/log" "github.com/gogits/gogs/modules/mailer" "github.com/gogits/gogs/modules/middleware" + "github.com/gogits/gogs/modules/setting" ) func Setting(ctx *middleware.Context) { @@ -189,7 +190,7 @@ func CollaborationPost(ctx *middleware.Context) { return } - if base.Service.NotifyMail { + if setting.Service.NotifyMail { if err = mailer.SendCollaboratorMail(ctx.Render, u, ctx.User, ctx.Repo.Repository); err != nil { ctx.Handle(500, "setting.CollaborationPost(SendCollaboratorMail)", err) return diff --git a/routers/user/social.go b/routers/user/social.go index a258bad1..9a56415f 100644 --- a/routers/user/social.go +++ b/routers/user/social.go @@ -14,9 +14,9 @@ import ( "github.com/go-martini/martini" "github.com/gogits/gogs/models" - "github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/log" "github.com/gogits/gogs/modules/middleware" + "github.com/gogits/gogs/modules/setting" "github.com/gogits/gogs/modules/social" ) @@ -29,7 +29,7 @@ func extractPath(next string) string { } func SocialSignIn(ctx *middleware.Context, params martini.Params) { - if base.OauthService == nil { + if setting.OauthService == nil { ctx.Handle(404, "social.SocialSignIn(oauth service not enabled)", nil) return } @@ -45,7 +45,7 @@ func SocialSignIn(ctx *middleware.Context, params martini.Params) { code := ctx.Query("code") if code == "" { // redirect to social login page - connect.SetRedirectUrl(strings.TrimSuffix(base.AppUrl, "/") + ctx.Req.URL.Path) + connect.SetRedirectUrl(strings.TrimSuffix(setting.AppUrl, "/") + ctx.Req.URL.Path) ctx.Redirect(connect.AuthCodeURL(next)) return } diff --git a/routers/user/user.go b/routers/user/user.go index 98480a41..bdcd5241 100644 --- a/routers/user/user.go +++ b/routers/user/user.go @@ -14,6 +14,7 @@ import ( "github.com/gogits/gogs/modules/log" "github.com/gogits/gogs/modules/mailer" "github.com/gogits/gogs/modules/middleware" + "github.com/gogits/gogs/modules/setting" ) func SignIn(ctx *middleware.Context) { @@ -26,23 +27,23 @@ func SignIn(ctx *middleware.Context) { } // Check auto-login. - userName := ctx.GetCookie(base.CookieUserName) + userName := ctx.GetCookie(setting.CookieUserName) if len(userName) == 0 { ctx.HTML(200, "user/signin") return } - if base.OauthService != nil { + if setting.OauthService != nil { ctx.Data["OauthEnabled"] = true - ctx.Data["OauthService"] = base.OauthService + ctx.Data["OauthService"] = setting.OauthService } isSucceed := false defer func() { if !isSucceed { log.Trace("user.SignIn(auto-login cookie cleared): %s", userName) - ctx.SetCookie(base.CookieUserName, "", -1) - ctx.SetCookie(base.CookieRememberName, "", -1) + ctx.SetCookie(setting.CookieUserName, "", -1) + ctx.SetCookie(setting.CookieRememberName, "", -1) return } }() @@ -54,7 +55,7 @@ func SignIn(ctx *middleware.Context) { } secret := base.EncodeMd5(user.Rands + user.Passwd) - value, _ := ctx.GetSecureCookie(secret, base.CookieRememberName) + value, _ := ctx.GetSecureCookie(secret, setting.CookieRememberName) if value != user.Name { ctx.HTML(200, "user/signin") return @@ -79,9 +80,9 @@ func SignInPost(ctx *middleware.Context, form auth.LogInForm) { sid, isOauth := ctx.Session.Get("socialId").(int64) if isOauth { ctx.Data["IsSocialLogin"] = true - } else if base.OauthService != nil { + } else if setting.OauthService != nil { ctx.Data["OauthEnabled"] = true - ctx.Data["OauthService"] = base.OauthService + ctx.Data["OauthService"] = setting.OauthService } if ctx.HasError() { @@ -103,9 +104,9 @@ func SignInPost(ctx *middleware.Context, form auth.LogInForm) { if form.Remember { secret := base.EncodeMd5(user.Rands + user.Passwd) - days := 86400 * base.LogInRememberDays - ctx.SetCookie(base.CookieUserName, user.Name, days) - ctx.SetSecureCookie(secret, base.CookieRememberName, user.Name, days) + days := 86400 * setting.LogInRememberDays + ctx.SetCookie(setting.CookieUserName, user.Name, days) + ctx.SetSecureCookie(secret, setting.CookieRememberName, user.Name, days) } // Bind with social account. @@ -139,8 +140,8 @@ func SignOut(ctx *middleware.Context) { ctx.Session.Delete("socialId") ctx.Session.Delete("socialName") ctx.Session.Delete("socialEmail") - ctx.SetCookie(base.CookieUserName, "", -1) - ctx.SetCookie(base.CookieRememberName, "", -1) + ctx.SetCookie(setting.CookieUserName, "", -1) + ctx.SetCookie(setting.CookieRememberName, "", -1) ctx.Redirect("/") } @@ -148,7 +149,7 @@ func SignUp(ctx *middleware.Context) { ctx.Data["Title"] = "Sign Up" ctx.Data["PageIsSignUp"] = true - if base.Service.DisableRegistration { + if setting.Service.DisableRegistration { ctx.Data["DisableRegistration"] = true ctx.HTML(200, "user/signup") return @@ -186,7 +187,7 @@ func SignUpPost(ctx *middleware.Context, form auth.RegisterForm) { ctx.Data["Title"] = "Sign Up" ctx.Data["PageIsSignUp"] = true - if base.Service.DisableRegistration { + if setting.Service.DisableRegistration { ctx.Handle(403, "user.SignUpPost", nil) return } @@ -212,7 +213,7 @@ func SignUpPost(ctx *middleware.Context, form auth.RegisterForm) { Name: form.UserName, Email: form.Email, Passwd: form.Password, - IsActive: !base.Service.RegisterEmailConfirm || isOauth, + IsActive: !setting.Service.RegisterEmailConfirm || isOauth, } var err error @@ -243,11 +244,11 @@ func SignUpPost(ctx *middleware.Context, form auth.RegisterForm) { } // Send confirmation e-mail, no need for social account. - if !isOauth && base.Service.RegisterEmailConfirm && u.Id > 1 { + if !isOauth && setting.Service.RegisterEmailConfirm && u.Id > 1 { mailer.SendRegisterMail(ctx.Render, u) ctx.Data["IsSendRegisterMail"] = true ctx.Data["Email"] = u.Email - ctx.Data["Hours"] = base.Service.ActiveCodeLives / 60 + ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60 ctx.HTML(200, "user/activate") if err = ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil { @@ -304,11 +305,11 @@ func Activate(ctx *middleware.Context) { return } // Resend confirmation e-mail. - if base.Service.RegisterEmailConfirm { + if setting.Service.RegisterEmailConfirm { if ctx.Cache.IsExist("MailResendLimit_" + ctx.User.LowerName) { ctx.Data["ResendLimited"] = true } else { - ctx.Data["Hours"] = base.Service.ActiveCodeLives / 60 + ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60 mailer.SendActiveMail(ctx.Render, ctx.User) if err := ctx.Cache.Put("MailResendLimit_"+ctx.User.LowerName, ctx.User.LowerName, 180); err != nil { @@ -346,7 +347,7 @@ func Activate(ctx *middleware.Context) { func ForgotPasswd(ctx *middleware.Context) { ctx.Data["Title"] = "Forgot Password" - if base.MailService == nil { + if setting.MailService == nil { ctx.Data["IsResetDisable"] = true ctx.HTML(200, "user/forgot_passwd") return @@ -359,7 +360,7 @@ func ForgotPasswd(ctx *middleware.Context) { func ForgotPasswdPost(ctx *middleware.Context) { ctx.Data["Title"] = "Forgot Password" - if base.MailService == nil { + if setting.MailService == nil { ctx.Handle(403, "user.ForgotPasswdPost", nil) return } @@ -388,7 +389,7 @@ func ForgotPasswdPost(ctx *middleware.Context) { } ctx.Data["Email"] = email - ctx.Data["Hours"] = base.Service.ActiveCodeLives / 60 + ctx.Data["Hours"] = setting.Service.ActiveCodeLives / 60 ctx.Data["IsResetSent"] = true ctx.HTML(200, "user/forgot_passwd") } -- cgit v1.2.3