forked from gitea/gitea
1
0
Fork 0
This commit is contained in:
Unknown 2014-05-25 20:11:25 -04:00
parent 87854c95a9
commit 688ec6ecbd
37 changed files with 693 additions and 482 deletions

View File

@ -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)

View File

@ -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()

View File

@ -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

View File

@ -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)
}

View File

@ -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

View File

@ -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())
}

View File

@ -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{

View File

@ -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)

View File

@ -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)

View File

@ -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) {

View File

@ -13,6 +13,8 @@ import (
"runtime"
"strings"
"time"
"github.com/gogits/gogs/modules/setting"
)
func Str2html(raw string) template.HTML {
@ -52,16 +54,16 @@ var TemplateFuncs template.FuncMap = map[string]interface{}{
return runtime.Version()
},
"AppName": func() string {
return AppName
return setting.AppName
},
"AppVer": func() string {
return AppVer
return setting.AppVer
},
"AppDomain": func() string {
return Domain
return setting.Domain
},
"CdnMode": func() bool {
return ProdMode && !OfflineMode
return setting.ProdMode && !setting.OfflineMode
},
"LoadTimes": func(startTime time.Time) string {
return fmt.Sprint(time.Since(startTime).Nanoseconds()/1e6) + "ms"

View File

@ -16,6 +16,8 @@ import (
"strconv"
"strings"
"time"
"github.com/gogits/gogs/modules/setting"
)
// Encode string to md5 hex value
@ -131,7 +133,7 @@ func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string
// create sha1 encode string
sh := sha1.New()
sh.Write([]byte(data + SecretKey + startStr + endStr + ToStr(minutes)))
sh.Write([]byte(data + setting.SecretKey + startStr + endStr + ToStr(minutes)))
encoded := hex.EncodeToString(sh.Sum(nil))
code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
@ -140,9 +142,9 @@ func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string
// AvatarLink returns avatar link by given e-mail.
func AvatarLink(email string) string {
if DisableGravatar {
if setting.DisableGravatar {
return "/img/avatar_default.jpg"
} else if Service.EnableCacheAvatar {
} else if setting.Service.EnableCacheAvatar {
return "/avatar/" + EncodeMd5(email)
}
return "//1.gravatar.com/avatar/" + EncodeMd5(email)

220
modules/bin/conf.go Normal file
View File

@ -0,0 +1,220 @@
package bin
import (
"fmt"
"io/ioutil"
"strings"
)
// bindata_read reads the given file from disk. It returns an error on failure.
func bindata_read(path, name string) ([]byte, error) {
buf, err := ioutil.ReadFile(path)
if err != nil {
err = fmt.Errorf("Error reading asset %s at %s: %v", name, path, err)
}
return buf, err
}
// conf_app_ini reads file data from disk. It returns an error on failure.
func conf_app_ini() ([]byte, error) {
return bindata_read(
"/Users/jiahuachen/Applications/Go/src/github.com/gogits/gogs/conf/app.ini",
"conf/app.ini",
)
}
// conf_content_git_bare_zip reads file data from disk. It returns an error on failure.
func conf_content_git_bare_zip() ([]byte, error) {
return bindata_read(
"/Users/jiahuachen/Applications/Go/src/github.com/gogits/gogs/conf/content/git-bare.zip",
"conf/content/git-bare.zip",
)
}
// conf_etc_supervisord_conf reads file data from disk. It returns an error on failure.
func conf_etc_supervisord_conf() ([]byte, error) {
return bindata_read(
"/Users/jiahuachen/Applications/Go/src/github.com/gogits/gogs/conf/etc/supervisord.conf",
"conf/etc/supervisord.conf",
)
}
// conf_gitignore_android reads file data from disk. It returns an error on failure.
func conf_gitignore_android() ([]byte, error) {
return bindata_read(
"/Users/jiahuachen/Applications/Go/src/github.com/gogits/gogs/conf/gitignore/Android",
"conf/gitignore/Android",
)
}
// conf_gitignore_c reads file data from disk. It returns an error on failure.
func conf_gitignore_c() ([]byte, error) {
return bindata_read(
"/Users/jiahuachen/Applications/Go/src/github.com/gogits/gogs/conf/gitignore/C",
"conf/gitignore/C",
)
}
// conf_gitignore_c_sharp reads file data from disk. It returns an error on failure.
func conf_gitignore_c_sharp() ([]byte, error) {
return bindata_read(
"/Users/jiahuachen/Applications/Go/src/github.com/gogits/gogs/conf/gitignore/C Sharp",
"conf/gitignore/C Sharp",
)
}
// conf_gitignore_c_ reads file data from disk. It returns an error on failure.
func conf_gitignore_c_() ([]byte, error) {
return bindata_read(
"/Users/jiahuachen/Applications/Go/src/github.com/gogits/gogs/conf/gitignore/C++",
"conf/gitignore/C++",
)
}
// conf_gitignore_google_go reads file data from disk. It returns an error on failure.
func conf_gitignore_google_go() ([]byte, error) {
return bindata_read(
"/Users/jiahuachen/Applications/Go/src/github.com/gogits/gogs/conf/gitignore/Google Go",
"conf/gitignore/Google Go",
)
}
// conf_gitignore_java reads file data from disk. It returns an error on failure.
func conf_gitignore_java() ([]byte, error) {
return bindata_read(
"/Users/jiahuachen/Applications/Go/src/github.com/gogits/gogs/conf/gitignore/Java",
"conf/gitignore/Java",
)
}
// conf_gitignore_objective_c reads file data from disk. It returns an error on failure.
func conf_gitignore_objective_c() ([]byte, error) {
return bindata_read(
"/Users/jiahuachen/Applications/Go/src/github.com/gogits/gogs/conf/gitignore/Objective-C",
"conf/gitignore/Objective-C",
)
}
// conf_gitignore_python reads file data from disk. It returns an error on failure.
func conf_gitignore_python() ([]byte, error) {
return bindata_read(
"/Users/jiahuachen/Applications/Go/src/github.com/gogits/gogs/conf/gitignore/Python",
"conf/gitignore/Python",
)
}
// conf_gitignore_ruby reads file data from disk. It returns an error on failure.
func conf_gitignore_ruby() ([]byte, error) {
return bindata_read(
"/Users/jiahuachen/Applications/Go/src/github.com/gogits/gogs/conf/gitignore/Ruby",
"conf/gitignore/Ruby",
)
}
// conf_license_affero_gpl reads file data from disk. It returns an error on failure.
func conf_license_affero_gpl() ([]byte, error) {
return bindata_read(
"/Users/jiahuachen/Applications/Go/src/github.com/gogits/gogs/conf/license/Affero GPL",
"conf/license/Affero GPL",
)
}
// conf_license_apache_v2_license reads file data from disk. It returns an error on failure.
func conf_license_apache_v2_license() ([]byte, error) {
return bindata_read(
"/Users/jiahuachen/Applications/Go/src/github.com/gogits/gogs/conf/license/Apache v2 License",
"conf/license/Apache v2 License",
)
}
// conf_license_artistic_license_2_0 reads file data from disk. It returns an error on failure.
func conf_license_artistic_license_2_0() ([]byte, error) {
return bindata_read(
"/Users/jiahuachen/Applications/Go/src/github.com/gogits/gogs/conf/license/Artistic License 2.0",
"conf/license/Artistic License 2.0",
)
}
// conf_license_bsd_3_clause_license reads file data from disk. It returns an error on failure.
func conf_license_bsd_3_clause_license() ([]byte, error) {
return bindata_read(
"/Users/jiahuachen/Applications/Go/src/github.com/gogits/gogs/conf/license/BSD (3-Clause) License",
"conf/license/BSD (3-Clause) License",
)
}
// conf_license_gpl_v2 reads file data from disk. It returns an error on failure.
func conf_license_gpl_v2() ([]byte, error) {
return bindata_read(
"/Users/jiahuachen/Applications/Go/src/github.com/gogits/gogs/conf/license/GPL v2",
"conf/license/GPL v2",
)
}
// conf_license_mit_license reads file data from disk. It returns an error on failure.
func conf_license_mit_license() ([]byte, error) {
return bindata_read(
"/Users/jiahuachen/Applications/Go/src/github.com/gogits/gogs/conf/license/MIT License",
"conf/license/MIT License",
)
}
// conf_mysql_sql reads file data from disk. It returns an error on failure.
func conf_mysql_sql() ([]byte, error) {
return bindata_read(
"/Users/jiahuachen/Applications/Go/src/github.com/gogits/gogs/conf/mysql.sql",
"conf/mysql.sql",
)
}
// conf_supervisor_ini reads file data from disk. It returns an error on failure.
func conf_supervisor_ini() ([]byte, error) {
return bindata_read(
"/Users/jiahuachen/Applications/Go/src/github.com/gogits/gogs/conf/supervisor.ini",
"conf/supervisor.ini",
)
}
// Asset loads and returns the asset for the given name.
// It returns an error if the asset could not be found or
// could not be loaded.
func Asset(name string) ([]byte, error) {
cannonicalName := strings.Replace(name, "\\", "/", -1)
if f, ok := _bindata[cannonicalName]; ok {
return f()
}
return nil, fmt.Errorf("Asset %s not found", name)
}
// AssetNames returns the names of the assets.
func AssetNames() []string {
names := make([]string, 0, len(_bindata))
for name := range _bindata {
names = append(names, name)
}
return names
}
// _bindata is a table, holding each asset generator, mapped to its name.
var _bindata = map[string]func() ([]byte, error){
"conf/app.ini": conf_app_ini,
"conf/content/git-bare.zip": conf_content_git_bare_zip,
"conf/etc/supervisord.conf": conf_etc_supervisord_conf,
"conf/gitignore/Android": conf_gitignore_android,
"conf/gitignore/C": conf_gitignore_c,
"conf/gitignore/C Sharp": conf_gitignore_c_sharp,
"conf/gitignore/C++": conf_gitignore_c_,
"conf/gitignore/Google Go": conf_gitignore_google_go,
"conf/gitignore/Java": conf_gitignore_java,
"conf/gitignore/Objective-C": conf_gitignore_objective_c,
"conf/gitignore/Python": conf_gitignore_python,
"conf/gitignore/Ruby": conf_gitignore_ruby,
"conf/license/Affero GPL": conf_license_affero_gpl,
"conf/license/Apache v2 License": conf_license_apache_v2_license,
"conf/license/Artistic License 2.0": conf_license_artistic_license_2_0,
"conf/license/BSD (3-Clause) License": conf_license_bsd_3_clause_license,
"conf/license/GPL v2": conf_license_gpl_v2,
"conf/license/MIT License": conf_license_mit_license,
"conf/mysql.sql": conf_mysql_sql,
"conf/supervisor.ini": conf_supervisor_ini,
}

View File

@ -6,6 +6,8 @@
package log
import (
"os"
"github.com/gogits/logs"
)
@ -69,3 +71,11 @@ func Critical(format string, v ...interface{}) {
logger.Critical(format, v...)
}
}
func Fatal(format string, v ...interface{}) {
Error(format, v...)
for _, l := range loggers {
l.Close()
}
os.Exit(2)
}

View File

@ -14,28 +14,29 @@ import (
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/middleware"
"github.com/gogits/gogs/modules/setting"
)
// Create New mail message use MailFrom and MailUser
func NewMailMessageFrom(To []string, from, subject, body string) Message {
msg := NewHtmlMessage(To, from, subject, body)
msg.User = base.MailService.User
msg.User = setting.MailService.User
return msg
}
// Create New mail message use MailFrom and MailUser
func NewMailMessage(To []string, subject, body string) Message {
return NewMailMessageFrom(To, base.MailService.User, subject, body)
return NewMailMessageFrom(To, setting.MailService.User, subject, body)
}
func GetMailTmplData(user *models.User) map[interface{}]interface{} {
data := make(map[interface{}]interface{}, 10)
data["AppName"] = base.AppName
data["AppVer"] = base.AppVer
data["AppUrl"] = base.AppUrl
data["AppLogo"] = base.AppLogo
data["ActiveCodeLives"] = base.Service.ActiveCodeLives / 60
data["ResetPwdCodeLives"] = base.Service.ResetPwdCodeLives / 60
data["AppName"] = setting.AppName
data["AppVer"] = setting.AppVer
data["AppUrl"] = setting.AppUrl
data["AppLogo"] = setting.AppLogo
data["ActiveCodeLives"] = setting.Service.ActiveCodeLives / 60
data["ResetPwdCodeLives"] = setting.Service.ResetPwdCodeLives / 60
if user != nil {
data["User"] = user
}
@ -44,7 +45,7 @@ func GetMailTmplData(user *models.User) map[interface{}]interface{} {
// create a time limit code for user active
func CreateUserActiveCode(user *models.User, startInf interface{}) string {
minutes := base.Service.ActiveCodeLives
minutes := setting.Service.ActiveCodeLives
data := base.ToStr(user.Id) + user.Email + user.LowerName + user.Passwd + user.Rands
code := base.CreateTimeLimitCode(data, minutes, startInf)
@ -139,7 +140,7 @@ func SendIssueNotifyMail(user, owner *models.User, repo *models.Repository, issu
subject := fmt.Sprintf("[%s] %s(#%d)", repo.Name, issue.Name, issue.Index)
content := fmt.Sprintf("%s<br>-<br> <a href=\"%s%s/%s/issues/%d\">View it on Gogs</a>.",
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)

View File

@ -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 {

View File

@ -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

View File

@ -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"))

View File

@ -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
}

View File

@ -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
}

View File

@ -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

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package base
package setting
import (
"fmt"
@ -14,78 +14,171 @@ import (
"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/bin"
"github.com/gogits/gogs/modules/log"
)
// Mailer represents mail service.
type Mailer struct {
Name string
Host string
User, Passwd string
}
type Scheme 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
}
const (
HTTP Scheme = "http"
HTTPS Scheme = "https"
)
var (
AppVer string
AppName string
AppLogo string
AppUrl string
SshPort int
OfflineMode bool
DisableRouterLog bool
ProdMode bool
Domain string
SecretKey string
RunUser string
// App settings.
AppVer string
AppName string
AppLogo string
AppUrl string
RepoRootPath string
ScriptType string
InstallLock bool
// 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
Cfg *goconfig.ConfigFile
MailService *Mailer
OauthService *Oauther
// 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
PictureService string
DisableGravatar bool
EnableRedis bool
EnableMemcache bool
// 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
@ -97,17 +190,12 @@ var Service struct {
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
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{
@ -119,14 +207,6 @@ var logLevels = map[string]string{
"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)
@ -137,7 +217,7 @@ func newLogService() {
mode = strings.TrimSpace(mode)
modeSec := "log." + mode
if _, err := Cfg.GetSection(modeSec); err != nil {
qlog.Fatalf("Unknown log mode: %s\n", mode)
log.Fatal("Unknown log mode: %s", mode)
}
// Log level.
@ -145,7 +225,7 @@ func newLogService() {
[]string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"})
level, ok := logLevels[levelName]
if !ok {
qlog.Fatalf("Unknown log level: %s\n", levelName)
log.Fatal("Unknown log level: %s", levelName)
}
// Generate log configuration.
@ -165,8 +245,8 @@ func newLogService() {
Cfg.MustInt(modeSec, "MAX_DAYS", 7))
case "conn":
LogConfigs[i] = fmt.Sprintf(`{"level":"%s","reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
Cfg.MustBool(modeSec, "RECONNECT_ON_MSG", false),
Cfg.MustBool(modeSec, "RECONNECT", false),
Cfg.MustBool(modeSec, "RECONNECT_ON_MSG"),
Cfg.MustBool(modeSec, "RECONNECT"),
Cfg.MustValueRange(modeSec, "PROTOCOL", "tcp", []string{"tcp", "unix", "udp"}),
Cfg.MustValue(modeSec, "ADDR", ":7020"))
case "smtp":
@ -202,13 +282,13 @@ func newCacheService() {
case "redis", "memcache":
CacheConfig = fmt.Sprintf(`{"conn":"%s"}`, Cfg.MustValue("cache", "HOST"))
default:
qlog.Fatalf("Unknown cache adapter: %s\n", CacheAdapter)
log.Fatal("Unknown cache adapter: %s", CacheAdapter)
}
var err error
Cache, err = cache.NewCache(CacheAdapter, CacheConfig)
if err != nil {
qlog.Fatalf("Init cache system failed, adapter: %s, config: %s, %v\n",
log.Fatal("Init cache system failed, adapter: %s, config: %s, %v\n",
CacheAdapter, CacheConfig, err)
}
@ -237,13 +317,38 @@ func newSessionService() {
var err error
SessionManager, err = session.NewManager(SessionProvider, *SessionConfig)
if err != nil {
qlog.Fatalf("Init session system failed, provider: %s, %v\n",
log.Fatal("Init session system failed, provider: %s, %v",
SessionProvider, err)
}
log.Info("Session Service Enabled")
}
// 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 (
MailService *Mailer
OauthService *Oauther
)
func newMailService() {
// Check mailer setting.
if !Cfg.MustBool("mailer", "ENABLED") {
@ -281,69 +386,7 @@ func newNotifyMailService() {
log.Info("Notify Mail Service Enabled")
}
func NewConfigContext() {
workDir, err := ExecDir()
if err != nil {
qlog.Fatalf("Fail to get work directory: %s\n", err)
}
cfgPath := filepath.Join(workDir, "conf/app.ini")
Cfg, err = goconfig.LoadConfigFile(cfgPath)
if err != nil {
qlog.Fatalf("Cannot load config file(%s): %v\n", cfgPath, err)
}
Cfg.BlockMode = false
cfgPaths := []string{os.Getenv("GOGS_CONFIG"), filepath.Join(workDir, "custom/conf/app.ini")}
for _, cfgPath := range cfgPaths {
if com.IsFile(cfgPath) {
if err = Cfg.AppendFiles(cfgPath); err != nil {
qlog.Fatalf("Cannot load config file(%s): %v\n", cfgPath, err)
}
}
}
AppName = Cfg.MustValue("", "APP_NAME", "Gogs: Go Git Service")
AppLogo = Cfg.MustValue("", "APP_LOGO", "img/favicon.png")
AppUrl = Cfg.MustValue("server", "ROOT_URL")
Domain = Cfg.MustValue("server", "DOMAIN")
SshPort = Cfg.MustInt("server", "SSH_PORT", 22)
OfflineMode = Cfg.MustBool("server", "OFFLINE_MODE", false)
DisableRouterLog = Cfg.MustBool("server", "DISABLE_ROUTER_LOG", false)
SecretKey = Cfg.MustValue("security", "SECRET_KEY")
InstallLock = Cfg.MustBool("security", "INSTALL_LOCK", false)
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 {
qlog.Fatalf("Expect user(%s) but current user is: %s\n", RunUser, curUser)
}
LogInRememberDays = Cfg.MustInt("security", "LOGIN_REMEMBER_DAYS")
CookieUserName = Cfg.MustValue("security", "COOKIE_USERNAME")
CookieRememberName = Cfg.MustValue("security", "COOKIE_REMEMBER_NAME")
PictureService = Cfg.MustValue("picture", "SERVICE")
DisableGravatar = Cfg.MustBool("picture", "DISABLE_GRAVATAR", false)
// Determine and create root git reposiroty path.
homeDir, err := com.HomeDir()
if err != nil {
qlog.Fatalf("Fail to get home directory): %v\n", err)
}
RepoRootPath = Cfg.MustValue("repository", "ROOT", filepath.Join(homeDir, "gogs-repositories"))
if err = os.MkdirAll(RepoRootPath, os.ModePerm); err != nil {
qlog.Fatalf("Fail to create RepoRootPath(%s): %v\n", RepoRootPath, err)
}
ScriptType = Cfg.MustValue("repository", "SCRIPT_TYPE", "bash")
}
func NewBaseServices() {
func NewServices() {
newService()
newLogService()
newCacheService()

View File

@ -15,8 +15,8 @@ import (
oauth "github.com/gogits/oauth2"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/setting"
)
type BasicUserInfo struct {
@ -40,67 +40,67 @@ var (
)
func NewOauthService() {
if !base.Cfg.MustBool("oauth", "ENABLED") {
if !setting.Cfg.MustBool("oauth", "ENABLED") {
return
}
base.OauthService = &base.Oauther{}
base.OauthService.OauthInfos = make(map[string]*base.OauthInfo)
setting.OauthService = &setting.Oauther{}
setting.OauthService.OauthInfos = make(map[string]*setting.OauthInfo)
socialConfigs := make(map[string]*oauth.Config)
allOauthes := []string{"github", "google", "qq", "twitter", "weibo"}
// Load all OAuth config data.
for _, name := range allOauthes {
base.OauthService.OauthInfos[name] = &base.OauthInfo{
ClientId: base.Cfg.MustValue("oauth."+name, "CLIENT_ID"),
ClientSecret: base.Cfg.MustValue("oauth."+name, "CLIENT_SECRET"),
Scopes: base.Cfg.MustValue("oauth."+name, "SCOPES"),
AuthUrl: base.Cfg.MustValue("oauth."+name, "AUTH_URL"),
TokenUrl: base.Cfg.MustValue("oauth."+name, "TOKEN_URL"),
setting.OauthService.OauthInfos[name] = &setting.OauthInfo{
ClientId: setting.Cfg.MustValue("oauth."+name, "CLIENT_ID"),
ClientSecret: setting.Cfg.MustValue("oauth."+name, "CLIENT_SECRET"),
Scopes: setting.Cfg.MustValue("oauth."+name, "SCOPES"),
AuthUrl: setting.Cfg.MustValue("oauth."+name, "AUTH_URL"),
TokenUrl: setting.Cfg.MustValue("oauth."+name, "TOKEN_URL"),
}
socialConfigs[name] = &oauth.Config{
ClientId: base.OauthService.OauthInfos[name].ClientId,
ClientSecret: base.OauthService.OauthInfos[name].ClientSecret,
RedirectURL: strings.TrimSuffix(base.AppUrl, "/") + SocialBaseUrl + name,
Scope: base.OauthService.OauthInfos[name].Scopes,
AuthURL: base.OauthService.OauthInfos[name].AuthUrl,
TokenURL: base.OauthService.OauthInfos[name].TokenUrl,
ClientId: setting.OauthService.OauthInfos[name].ClientId,
ClientSecret: setting.OauthService.OauthInfos[name].ClientSecret,
RedirectURL: strings.TrimSuffix(setting.AppUrl, "/") + SocialBaseUrl + name,
Scope: setting.OauthService.OauthInfos[name].Scopes,
AuthURL: setting.OauthService.OauthInfos[name].AuthUrl,
TokenURL: setting.OauthService.OauthInfos[name].TokenUrl,
}
}
enabledOauths := make([]string, 0, 10)
// GitHub.
if base.Cfg.MustBool("oauth.github", "ENABLED") {
base.OauthService.GitHub = true
if setting.Cfg.MustBool("oauth.github", "ENABLED") {
setting.OauthService.GitHub = true
newGitHubOauth(socialConfigs["github"])
enabledOauths = append(enabledOauths, "GitHub")
}
// Google.
if base.Cfg.MustBool("oauth.google", "ENABLED") {
base.OauthService.Google = true
if setting.Cfg.MustBool("oauth.google", "ENABLED") {
setting.OauthService.Google = true
newGoogleOauth(socialConfigs["google"])
enabledOauths = append(enabledOauths, "Google")
}
// QQ.
if base.Cfg.MustBool("oauth.qq", "ENABLED") {
base.OauthService.Tencent = true
if setting.Cfg.MustBool("oauth.qq", "ENABLED") {
setting.OauthService.Tencent = true
newTencentOauth(socialConfigs["qq"])
enabledOauths = append(enabledOauths, "QQ")
}
// Twitter.
if base.Cfg.MustBool("oauth.twitter", "ENABLED") {
base.OauthService.Twitter = true
if setting.Cfg.MustBool("oauth.twitter", "ENABLED") {
setting.OauthService.Twitter = true
newTwitterOauth(socialConfigs["twitter"])
enabledOauths = append(enabledOauths, "Twitter")
}
// Weibo.
if base.Cfg.MustBool("oauth.weibo", "ENABLED") {
base.OauthService.Weibo = true
if setting.Cfg.MustBool("oauth.weibo", "ENABLED") {
setting.OauthService.Weibo = true
newWeiboOauth(socialConfigs["weibo"])
enabledOauths = append(enabledOauths, "Weibo")
}

View File

@ -15,6 +15,7 @@ import (
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/middleware"
"github.com/gogits/gogs/modules/setting"
)
var startTime = time.Now()
@ -177,46 +178,46 @@ func Config(ctx *middleware.Context) {
ctx.Data["Title"] = "Server Configuration"
ctx.Data["PageIsConfig"] = true
ctx.Data["AppUrl"] = base.AppUrl
ctx.Data["Domain"] = base.Domain
ctx.Data["OfflineMode"] = base.OfflineMode
ctx.Data["DisableRouterLog"] = base.DisableRouterLog
ctx.Data["RunUser"] = base.RunUser
ctx.Data["AppUrl"] = setting.AppUrl
ctx.Data["Domain"] = setting.Domain
ctx.Data["OfflineMode"] = setting.OfflineMode
ctx.Data["DisableRouterLog"] = setting.DisableRouterLog
ctx.Data["RunUser"] = setting.RunUser
ctx.Data["RunMode"] = strings.Title(martini.Env)
ctx.Data["RepoRootPath"] = base.RepoRootPath
ctx.Data["ScriptType"] = base.ScriptType
ctx.Data["RepoRootPath"] = setting.RepoRootPath
ctx.Data["ScriptType"] = setting.ScriptType
ctx.Data["Service"] = base.Service
ctx.Data["Service"] = setting.Service
ctx.Data["DbCfg"] = models.DbCfg
ctx.Data["MailerEnabled"] = false
if base.MailService != nil {
if setting.MailService != nil {
ctx.Data["MailerEnabled"] = true
ctx.Data["Mailer"] = base.MailService
ctx.Data["Mailer"] = setting.MailService
}
ctx.Data["OauthEnabled"] = false
if base.OauthService != nil {
if setting.OauthService != nil {
ctx.Data["OauthEnabled"] = true
ctx.Data["Oauther"] = base.OauthService
ctx.Data["Oauther"] = setting.OauthService
}
ctx.Data["CacheAdapter"] = base.CacheAdapter
ctx.Data["CacheConfig"] = base.CacheConfig
ctx.Data["CacheAdapter"] = setting.CacheAdapter
ctx.Data["CacheConfig"] = setting.CacheConfig
ctx.Data["SessionProvider"] = base.SessionProvider
ctx.Data["SessionConfig"] = base.SessionConfig
ctx.Data["SessionProvider"] = setting.SessionProvider
ctx.Data["SessionConfig"] = setting.SessionConfig
ctx.Data["PictureService"] = base.PictureService
ctx.Data["DisableGravatar"] = base.DisableGravatar
ctx.Data["PictureService"] = setting.PictureService
ctx.Data["DisableGravatar"] = setting.DisableGravatar
type logger struct {
Mode, Config string
}
loggers := make([]*logger, len(base.LogModes))
for i := range base.LogModes {
loggers[i] = &logger{base.LogModes[i], base.LogConfigs[i]}
loggers := make([]*logger, len(setting.LogModes))
for i := range setting.LogModes {
loggers[i] = &logger{setting.LogModes[i], setting.LogConfigs[i]}
}
ctx.Data["Loggers"] = loggers

View File

@ -11,6 +11,7 @@ import (
"github.com/gogits/gogs/modules/auth/apiv1"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/middleware"
"github.com/gogits/gogs/modules/setting"
)
const DOC_URL = "http://gogs.io/docs"
@ -25,7 +26,7 @@ func Markdown(ctx *middleware.Context, form apiv1.MarkdownForm) {
switch form.Mode {
case "gfm":
ctx.Write(base.RenderMarkdown([]byte(form.Text),
base.AppUrl+strings.TrimPrefix(form.Context, "/")))
setting.AppUrl+strings.TrimPrefix(form.Context, "/")))
default:
ctx.Write(base.RenderRawMarkdown([]byte(form.Text), ""))
}

View File

@ -6,8 +6,8 @@ package routers
import (
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/middleware"
"github.com/gogits/gogs/modules/setting"
"github.com/gogits/gogs/routers/user"
)
@ -18,7 +18,7 @@ func Home(ctx *middleware.Context) {
}
// Check auto-login.
userName := ctx.GetCookie(base.CookieUserName)
userName := ctx.GetCookie(setting.CookieUserName)
if len(userName) != 0 {
ctx.Redirect("/user/login")
return

View File

@ -8,19 +8,19 @@ 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 TemplatePreview(ctx *middleware.Context, params martini.Params) {
ctx.Data["User"] = models.User{Name: "Unknown"}
ctx.Data["AppName"] = base.AppName
ctx.Data["AppVer"] = base.AppVer
ctx.Data["AppUrl"] = base.AppUrl
ctx.Data["AppLogo"] = base.AppLogo
ctx.Data["AppName"] = setting.AppName
ctx.Data["AppVer"] = setting.AppVer
ctx.Data["AppUrl"] = setting.AppUrl
ctx.Data["AppLogo"] = setting.AppLogo
ctx.Data["Code"] = "2014031910370000009fff6782aadb2162b4a997acb69d4400888e0b9274657374"
ctx.Data["ActiveCodeLives"] = base.Service.ActiveCodeLives / 60
ctx.Data["ResetPwdCodeLives"] = base.Service.ResetPwdCodeLives / 60
ctx.Data["ActiveCodeLives"] = setting.Service.ActiveCodeLives / 60
ctx.Data["ResetPwdCodeLives"] = setting.Service.ResetPwdCodeLives / 60
ctx.Data["CurDbValue"] = ""
ctx.HTML(200, params["_1"])
}

View File

@ -8,6 +8,7 @@ import (
"errors"
"os"
"os/exec"
"path"
"strings"
"github.com/Unknwon/goconfig"
@ -22,14 +23,15 @@ 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"
"github.com/gogits/gogs/modules/social"
)
func checkRunMode() {
switch base.Cfg.MustValue("", "RUN_MODE") {
switch setting.Cfg.MustValue("", "RUN_MODE") {
case "prod":
martini.Env = martini.Prod
base.ProdMode = true
setting.ProdMode = true
case "test":
martini.Env = martini.Test
}
@ -37,20 +39,20 @@ func checkRunMode() {
}
func NewServices() {
base.NewBaseServices()
setting.NewServices()
social.NewOauthService()
}
// GlobalInit is for global configuration reload-able.
func GlobalInit() {
base.NewConfigContext()
setting.NewConfigContext()
mailer.NewMailerContext()
models.LoadModelsConfig()
models.LoadRepoConfig()
models.NewRepoContext()
NewServices()
if base.InstallLock {
if setting.InstallLock {
if err := models.NewEngine(); err != nil {
qlog.Fatal(err)
}
@ -69,7 +71,7 @@ func renderDbOption(ctx *middleware.Context) {
}
func Install(ctx *middleware.Context, form auth.InstallForm) {
if base.InstallLock {
if setting.InstallLock {
ctx.Handle(404, "install.Install", errors.New("Installation is prohibited"))
return
}
@ -95,16 +97,16 @@ func Install(ctx *middleware.Context, form auth.InstallForm) {
}
if len(form.RepoRootPath) == 0 {
form.RepoRootPath = base.RepoRootPath
form.RepoRootPath = setting.RepoRootPath
}
if len(form.RunUser) == 0 {
form.RunUser = base.RunUser
form.RunUser = setting.RunUser
}
if len(form.Domain) == 0 {
form.Domain = base.Domain
form.Domain = setting.Domain
}
if len(form.AppUrl) == 0 {
form.AppUrl = base.AppUrl
form.AppUrl = setting.AppUrl
}
renderDbOption(ctx)
@ -119,7 +121,7 @@ func Install(ctx *middleware.Context, form auth.InstallForm) {
}
func InstallPost(ctx *middleware.Context, form auth.InstallForm) {
if base.InstallLock {
if setting.InstallLock {
ctx.Handle(404, "install.Install", errors.New("Installation is prohibited"))
return
}
@ -181,35 +183,35 @@ func InstallPost(ctx *middleware.Context, form auth.InstallForm) {
}
// Save settings.
base.Cfg.SetValue("database", "DB_TYPE", models.DbCfg.Type)
base.Cfg.SetValue("database", "HOST", models.DbCfg.Host)
base.Cfg.SetValue("database", "NAME", models.DbCfg.Name)
base.Cfg.SetValue("database", "USER", models.DbCfg.User)
base.Cfg.SetValue("database", "PASSWD", models.DbCfg.Pwd)
base.Cfg.SetValue("database", "SSL_MODE", models.DbCfg.SslMode)
base.Cfg.SetValue("database", "PATH", models.DbCfg.Path)
setting.Cfg.SetValue("database", "DB_TYPE", models.DbCfg.Type)
setting.Cfg.SetValue("database", "HOST", models.DbCfg.Host)
setting.Cfg.SetValue("database", "NAME", models.DbCfg.Name)
setting.Cfg.SetValue("database", "USER", models.DbCfg.User)
setting.Cfg.SetValue("database", "PASSWD", models.DbCfg.Pwd)
setting.Cfg.SetValue("database", "SSL_MODE", models.DbCfg.SslMode)
setting.Cfg.SetValue("database", "PATH", models.DbCfg.Path)
base.Cfg.SetValue("repository", "ROOT", form.RepoRootPath)
base.Cfg.SetValue("", "RUN_USER", form.RunUser)
base.Cfg.SetValue("server", "DOMAIN", form.Domain)
base.Cfg.SetValue("server", "ROOT_URL", form.AppUrl)
setting.Cfg.SetValue("repository", "ROOT", form.RepoRootPath)
setting.Cfg.SetValue("", "RUN_USER", form.RunUser)
setting.Cfg.SetValue("server", "DOMAIN", form.Domain)
setting.Cfg.SetValue("server", "ROOT_URL", form.AppUrl)
if len(strings.TrimSpace(form.SmtpHost)) > 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
}

View File

@ -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")
}

View File

@ -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")
}

View File

@ -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
}

View File

@ -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
*/

View File

@ -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)
}
}*/

View File

@ -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 {

View File

@ -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

View File

@ -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
}

View File

@ -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")
}