This commit is contained in:
Unknwon 2014-12-31 18:37:29 +08:00
parent e1c5008238
commit bd555551ce
6 changed files with 148 additions and 141 deletions

View File

@ -27,6 +27,7 @@ github.com/mattn/go-sqlite3 = commit:a80c27ba33
github.com/nfnt/resize = commit:581d15cb53 github.com/nfnt/resize = commit:581d15cb53
github.com/russross/blackfriday = commit:05b8cefd6a github.com/russross/blackfriday = commit:05b8cefd6a
github.com/saintfish/chardet = commit:3af4cd4741 github.com/saintfish/chardet = commit:3af4cd4741
gopkg.in/ini.v1
[res] [res]
include = conf|etc|public|scripts|templates include = conf|etc|public|scripts|templates

View File

@ -49,18 +49,19 @@ func init() {
} }
func LoadModelsConfig() { func LoadModelsConfig() {
DbCfg.Type = setting.Cfg.MustValue("database", "DB_TYPE") sec := setting.Cfg.Section("database")
DbCfg.Type = sec.Key("DB_TYPE").String()
if DbCfg.Type == "sqlite3" { if DbCfg.Type == "sqlite3" {
UseSQLite3 = true UseSQLite3 = true
} }
DbCfg.Host = setting.Cfg.MustValue("database", "HOST") DbCfg.Host = sec.Key("HOST").String()
DbCfg.Name = setting.Cfg.MustValue("database", "NAME") DbCfg.Name = sec.Key("NAME").String()
DbCfg.User = setting.Cfg.MustValue("database", "USER") DbCfg.User = sec.Key("USER").String()
if len(DbCfg.Pwd) == 0 { if len(DbCfg.Pwd) == 0 {
DbCfg.Pwd = setting.Cfg.MustValue("database", "PASSWD") DbCfg.Pwd = sec.Key("PASSWD").String()
} }
DbCfg.SslMode = setting.Cfg.MustValue("database", "SSL_MODE") DbCfg.SslMode = sec.Key("SSL_MODE").String()
DbCfg.Path = setting.Cfg.MustValue("database", "PATH", "data/gogs.db") DbCfg.Path = sec.Key("PATH").MustString("data/gogs.db")
} }
func getEngine() (*xorm.Engine, error) { func getEngine() (*xorm.Engine, error) {

View File

@ -42,7 +42,7 @@ func (m Message) Content() string {
var mailQueue chan *Message var mailQueue chan *Message
func NewMailerContext() { func NewMailerContext() {
mailQueue = make(chan *Message, setting.Cfg.MustInt("mailer", "SEND_BUFFER_LEN", 10)) mailQueue = make(chan *Message, setting.Cfg.Section("mailer").Key("SEND_BUFFER_LEN").MustInt(10))
go processMailQueue() go processMailQueue()
} }

View File

@ -16,9 +16,9 @@ import (
"time" "time"
"github.com/Unknwon/com" "github.com/Unknwon/com"
"github.com/Unknwon/goconfig"
"github.com/macaron-contrib/oauth2" "github.com/macaron-contrib/oauth2"
"github.com/macaron-contrib/session" "github.com/macaron-contrib/session"
"gopkg.in/ini.v1"
"github.com/gogits/gogs/modules/log" "github.com/gogits/gogs/modules/log"
// "github.com/gogits/gogs/modules/ssh" // "github.com/gogits/gogs/modules/ssh"
@ -115,7 +115,7 @@ var (
Langs, Names []string Langs, Names []string
// Global setting objects. // Global setting objects.
Cfg *goconfig.ConfigFile Cfg *ini.File
ConfRootPath string ConfRootPath string
CustomPath string // Custom directory path. CustomPath string // Custom directory path.
ProdMode bool ProdMode bool
@ -156,7 +156,7 @@ func NewConfigContext() {
} }
ConfRootPath = path.Join(workDir, "conf") ConfRootPath = path.Join(workDir, "conf")
Cfg, err = goconfig.LoadConfigFile(path.Join(workDir, "conf/app.ini")) Cfg, err = ini.Load(path.Join(workDir, "conf/app.ini"))
if err != nil { if err != nil {
log.Fatal(4, "Fail to parse 'conf/app.ini': %v", err) log.Fatal(4, "Fail to parse 'conf/app.ini': %v", err)
} }
@ -168,15 +168,18 @@ func NewConfigContext() {
cfgPath := path.Join(CustomPath, "conf/app.ini") cfgPath := path.Join(CustomPath, "conf/app.ini")
if com.IsFile(cfgPath) { if com.IsFile(cfgPath) {
if err = Cfg.AppendFiles(cfgPath); err != nil { if err = Cfg.Append(cfgPath); err != nil {
log.Fatal(4, "Fail to load custom 'conf/app.ini': %v", err) log.Fatal(4, "Fail to load custom 'conf/app.ini': %v", err)
} }
} else { } else {
log.Warn("No custom 'conf/app.ini' found, please go to '/install'") log.Warn("No custom 'conf/app.ini' found, please go to '/install'")
} }
AppName = Cfg.MustValue("", "APP_NAME", "Gogs: Go Git Service") LogRootPath = Cfg.Section("log").Key("ROOT_PATH").MustString(path.Join(workDir, "log"))
AppUrl = Cfg.MustValue("server", "ROOT_URL", "http://localhost:3000/")
sec := Cfg.Section("server")
AppName = Cfg.Section("").Key("APP_NAME").MustString("Gogs: Go Git Service")
AppUrl = sec.Key("ROOT_URL").MustString("http://localhost:3000/")
if AppUrl[len(AppUrl)-1] != '/' { if AppUrl[len(AppUrl)-1] != '/' {
AppUrl += "/" AppUrl += "/"
} }
@ -189,43 +192,43 @@ func NewConfigContext() {
AppSubUrl = strings.TrimSuffix(url.Path, "/") AppSubUrl = strings.TrimSuffix(url.Path, "/")
Protocol = HTTP Protocol = HTTP
if Cfg.MustValue("server", "PROTOCOL") == "https" { if sec.Key("PROTOCOL").String() == "https" {
Protocol = HTTPS Protocol = HTTPS
CertFile = Cfg.MustValue("server", "CERT_FILE") CertFile = sec.Key("CERT_FILE").String()
KeyFile = Cfg.MustValue("server", "KEY_FILE") KeyFile = sec.Key("KEY_FILE").String()
} } else if sec.Key("PROTOCOL").String() == "fcgi" {
if Cfg.MustValue("server", "PROTOCOL") == "fcgi" {
Protocol = FCGI Protocol = FCGI
} }
Domain = Cfg.MustValue("server", "DOMAIN", "localhost") Domain = sec.Key("DOMAIN").MustString("localhost")
HttpAddr = Cfg.MustValue("server", "HTTP_ADDR", "0.0.0.0") HttpAddr = sec.Key("HTTP_ADDR").MustString("0.0.0.0")
HttpPort = Cfg.MustValue("server", "HTTP_PORT", "3000") HttpPort = sec.Key("HTTP_PORT").MustString("3000")
SshPort = Cfg.MustInt("server", "SSH_PORT", 22) SshPort = sec.Key("SSH_PORT").MustInt(22)
OfflineMode = Cfg.MustBool("server", "OFFLINE_MODE") OfflineMode = sec.Key("OFFLINE_MODE").MustBool()
DisableRouterLog = Cfg.MustBool("server", "DISABLE_ROUTER_LOG") DisableRouterLog = sec.Key("DISABLE_ROUTER_LOG").MustBool()
StaticRootPath = Cfg.MustValue("server", "STATIC_ROOT_PATH", workDir) StaticRootPath = sec.Key("STATIC_ROOT_PATH").MustString(workDir)
LogRootPath = Cfg.MustValue("log", "ROOT_PATH", path.Join(workDir, "log")) EnableGzip = sec.Key("ENABLE_GZIP").MustBool()
EnableGzip = Cfg.MustBool("server", "ENABLE_GZIP")
switch Cfg.MustValue("server", "LANDING_PAGE", "home") { switch sec.Key("LANDING_PAGE").MustString("home") {
case "explore": case "explore":
LandingPageUrl = LANDING_PAGE_EXPLORE LandingPageUrl = LANDING_PAGE_EXPLORE
default: default:
LandingPageUrl = LANDING_PAGE_HOME LandingPageUrl = LANDING_PAGE_HOME
} }
InstallLock = Cfg.MustBool("security", "INSTALL_LOCK") sec = Cfg.Section("security")
SecretKey = Cfg.MustValue("security", "SECRET_KEY") InstallLock = sec.Key("INSTALL_LOCK").MustBool()
LogInRememberDays = Cfg.MustInt("security", "LOGIN_REMEMBER_DAYS") SecretKey = sec.Key("SECRET_KEY").String()
CookieUserName = Cfg.MustValue("security", "COOKIE_USERNAME") LogInRememberDays = sec.Key("LOGIN_REMEMBER_DAYS").MustInt()
CookieRememberName = Cfg.MustValue("security", "COOKIE_REMEMBER_NAME") CookieUserName = sec.Key("COOKIE_USERNAME").String()
ReverseProxyAuthUser = Cfg.MustValue("security", "REVERSE_PROXY_AUTHENTICATION_USER", "X-WEBAUTH-USER") CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").String()
ReverseProxyAuthUser = sec.Key("REVERSE_PROXY_AUTHENTICATION_USER").MustString("X-WEBAUTH-USER")
AttachmentPath = Cfg.MustValue("attachment", "PATH", "data/attachments") sec = Cfg.Section("attachment")
AttachmentAllowedTypes = Cfg.MustValue("attachment", "ALLOWED_TYPES", "image/jpeg|image/png") AttachmentPath = sec.Key("PATH").MustString("data/attachments")
AttachmentMaxSize = Cfg.MustInt64("attachment", "MAX_SIZE", 32) AttachmentAllowedTypes = sec.Key("ALLOWED_TYPES").MustString("image/jpeg|image/png")
AttachmentMaxFiles = Cfg.MustInt("attachment", "MAX_FILES", 10) AttachmentMaxSize = sec.Key("MAX_SIZE").MustInt64(32)
AttachmentEnabled = Cfg.MustBool("attachment", "ENABLE", true) AttachmentMaxFiles = sec.Key("MAX_FILES").MustInt(10)
AttachmentEnabled = sec.Key("ENABLE").MustBool(true)
TimeFormat = map[string]string{ TimeFormat = map[string]string{
"ANSIC": time.ANSIC, "ANSIC": time.ANSIC,
@ -243,13 +246,13 @@ func NewConfigContext() {
"StampMilli": time.StampMilli, "StampMilli": time.StampMilli,
"StampMicro": time.StampMicro, "StampMicro": time.StampMicro,
"StampNano": time.StampNano, "StampNano": time.StampNano,
}[Cfg.MustValue("time", "FORMAT", "RFC1123")] }[Cfg.Section("time").Key("FORMAT").MustString("RFC1123")]
if err = os.MkdirAll(AttachmentPath, os.ModePerm); err != nil { if err = os.MkdirAll(AttachmentPath, os.ModePerm); err != nil {
log.Fatal(4, "Could not create directory %s: %s", AttachmentPath, err) log.Fatal(4, "Could not create directory %s: %s", AttachmentPath, err)
} }
RunUser = Cfg.MustValue("", "RUN_USER") RunUser = Cfg.Section("").Key("RUN_USER").String()
curUser := os.Getenv("USER") curUser := os.Getenv("USER")
if len(curUser) == 0 { if len(curUser) == 0 {
curUser = os.Getenv("USERNAME") curUser = os.Getenv("USERNAME")
@ -264,36 +267,37 @@ func NewConfigContext() {
if err != nil { if err != nil {
log.Fatal(4, "Fail to get home directory: %v", err) log.Fatal(4, "Fail to get home directory: %v", err)
} }
RepoRootPath = Cfg.MustValue("repository", "ROOT", filepath.Join(homeDir, "gogs-repositories")) sec = Cfg.Section("repository")
RepoRootPath = sec.Key("ROOT").MustString(filepath.Join(homeDir, "gogs-repositories"))
if !filepath.IsAbs(RepoRootPath) { if !filepath.IsAbs(RepoRootPath) {
RepoRootPath = filepath.Join(workDir, RepoRootPath) RepoRootPath = filepath.Join(workDir, RepoRootPath)
} else { } else {
RepoRootPath = filepath.Clean(RepoRootPath) RepoRootPath = filepath.Clean(RepoRootPath)
} }
if err = os.MkdirAll(RepoRootPath, os.ModePerm); err != nil { if err = os.MkdirAll(RepoRootPath, os.ModePerm); err != nil {
log.Fatal(4, "Fail to create repository root path(%s): %v", RepoRootPath, err) log.Fatal(4, "Fail to create repository root path(%s): %v", RepoRootPath, err)
} }
ScriptType = Cfg.MustValue("repository", "SCRIPT_TYPE", "bash") ScriptType = sec.Key("SCRIPT_TYPE").MustString("bash")
PictureService = Cfg.MustValueRange("picture", "SERVICE", "server", []string{"server"}) sec = Cfg.Section("picture")
AvatarUploadPath = Cfg.MustValue("picture", "AVATAR_UPLOAD_PATH", "data/avatars") PictureService = sec.Key("SERVICE").In("server", []string{"server"})
AvatarUploadPath = sec.Key("AVATAR_UPLOAD_PATH").MustString("data/avatars")
os.MkdirAll(AvatarUploadPath, os.ModePerm) os.MkdirAll(AvatarUploadPath, os.ModePerm)
switch sec.Key("GRAVATAR_SOURCE").MustString("gravatar") {
switch Cfg.MustValue("picture", "GRAVATAR_SOURCE", "gravatar") {
case "duoshuo": case "duoshuo":
GravatarSource = "http://gravatar.duoshuo.com/avatar/" GravatarSource = "http://gravatar.duoshuo.com/avatar/"
default: default:
GravatarSource = "//1.gravatar.com/avatar/" GravatarSource = "//1.gravatar.com/avatar/"
} }
DisableGravatar = Cfg.MustBool("picture", "DISABLE_GRAVATAR") DisableGravatar = sec.Key("DISABLE_GRAVATAR").MustBool()
MaxGitDiffLines = Cfg.MustInt("git", "MAX_GITDIFF_LINES", 10000) sec = Cfg.Section("git")
GitFsckArgs = Cfg.MustValueArray("git", "FSCK_ARGS", " ") MaxGitDiffLines = sec.Key("MAX_GITDIFF_LINES").MustInt(10000)
GitGcArgs = Cfg.MustValueArray("git", "GC_ARGS", " ") GitFsckArgs = sec.Key("FSCK_ARGS").Strings(" ")
GitGcArgs = sec.Key("GC_ARGS").Strings(" ")
Langs = Cfg.MustValueArray("i18n", "LANGS", ",") Langs = Cfg.Section("i18n").Key("LANGS").Strings(",")
Names = Cfg.MustValueArray("i18n", "NAMES", ",") Names = Cfg.Section("i18n").Key("NAMES").Strings(",")
HasRobotsTxt = com.IsFile(path.Join(CustomPath, "robots.txt")) HasRobotsTxt = com.IsFile(path.Join(CustomPath, "robots.txt"))
} }
@ -311,13 +315,13 @@ var Service struct {
} }
func newService() { func newService() {
Service.ActiveCodeLives = Cfg.MustInt("service", "ACTIVE_CODE_LIVE_MINUTES", 180) Service.ActiveCodeLives = Cfg.Section("service").Key("ACTIVE_CODE_LIVE_MINUTES").MustInt(180)
Service.ResetPwdCodeLives = Cfg.MustInt("service", "RESET_PASSWD_CODE_LIVE_MINUTES", 180) Service.ResetPwdCodeLives = Cfg.Section("service").Key("RESET_PASSWD_CODE_LIVE_MINUTES").MustInt(180)
Service.DisableRegistration = Cfg.MustBool("service", "DISABLE_REGISTRATION") Service.DisableRegistration = Cfg.Section("service").Key("DISABLE_REGISTRATION").MustBool()
Service.RequireSignInView = Cfg.MustBool("service", "REQUIRE_SIGNIN_VIEW") Service.RequireSignInView = Cfg.Section("service").Key("REQUIRE_SIGNIN_VIEW").MustBool()
Service.EnableCacheAvatar = Cfg.MustBool("service", "ENABLE_CACHE_AVATAR") Service.EnableCacheAvatar = Cfg.Section("service").Key("ENABLE_CACHE_AVATAR").MustBool()
Service.EnableReverseProxyAuth = Cfg.MustBool("service", "ENABLE_REVERSE_PROXY_AUTHENTICATION") Service.EnableReverseProxyAuth = Cfg.Section("service").Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
Service.EnableReverseProxyAutoRegister = Cfg.MustBool("service", "ENABLE_REVERSE_PROXY_AUTO_REGISTERATION") Service.EnableReverseProxyAutoRegister = Cfg.Section("service").Key("ENABLE_REVERSE_PROXY_AUTO_REGISTERATION").MustBool()
} }
var logLevels = map[string]string{ var logLevels = map[string]string{
@ -333,17 +337,17 @@ func newLogService() {
log.Info("%s %s", AppName, AppVer) log.Info("%s %s", AppName, AppVer)
// Get and check log mode. // Get and check log mode.
LogModes = strings.Split(Cfg.MustValue("log", "MODE", "console"), ",") LogModes = strings.Split(Cfg.Section("log").Key("MODE").MustString("console"), ",")
LogConfigs = make([]string, len(LogModes)) LogConfigs = make([]string, len(LogModes))
for i, mode := range LogModes { for i, mode := range LogModes {
mode = strings.TrimSpace(mode) mode = strings.TrimSpace(mode)
modeSec := "log." + mode sec, err := Cfg.GetSection("log." + mode)
if _, err := Cfg.GetSection(modeSec); err != nil { if err != nil {
log.Fatal(4, "Unknown log mode: %s", mode) log.Fatal(4, "Unknown log mode: %s", mode)
} }
// Log level. // Log level.
levelName := Cfg.MustValueRange("log."+mode, "LEVEL", "Trace", levelName := Cfg.Section("log."+mode).Key("LEVEL").In("Trace",
[]string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"}) []string{"Trace", "Debug", "Info", "Warn", "Error", "Critical"})
level, ok := logLevels[levelName] level, ok := logLevels[levelName]
if !ok { if !ok {
@ -355,42 +359,42 @@ func newLogService() {
case "console": case "console":
LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level) LogConfigs[i] = fmt.Sprintf(`{"level":%s}`, level)
case "file": case "file":
logPath := Cfg.MustValue(modeSec, "FILE_NAME", path.Join(LogRootPath, "gogs.log")) logPath := sec.Key("FILE_NAME").MustString(path.Join(LogRootPath, "gogs.log"))
os.MkdirAll(path.Dir(logPath), os.ModePerm) os.MkdirAll(path.Dir(logPath), os.ModePerm)
LogConfigs[i] = fmt.Sprintf( LogConfigs[i] = fmt.Sprintf(
`{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level, `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level,
logPath, logPath,
Cfg.MustBool(modeSec, "LOG_ROTATE", true), sec.Key("LOG_ROTATE").MustBool(true),
Cfg.MustInt(modeSec, "MAX_LINES", 1000000), sec.Key("MAX_LINES").MustInt(1000000),
1<<uint(Cfg.MustInt(modeSec, "MAX_SIZE_SHIFT", 28)), 1<<uint(sec.Key("MAX_SIZE_SHIFT").MustInt(28)),
Cfg.MustBool(modeSec, "DAILY_ROTATE", true), sec.Key("DAILY_ROTATE").MustBool(true),
Cfg.MustInt(modeSec, "MAX_DAYS", 7)) sec.Key("MAX_DAYS").MustInt(7))
case "conn": case "conn":
LogConfigs[i] = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level, LogConfigs[i] = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
Cfg.MustBool(modeSec, "RECONNECT_ON_MSG"), sec.Key("RECONNECT_ON_MSG").MustBool(),
Cfg.MustBool(modeSec, "RECONNECT"), sec.Key("RECONNECT").MustBool(),
Cfg.MustValueRange(modeSec, "PROTOCOL", "tcp", []string{"tcp", "unix", "udp"}), sec.Key("PROTOCOL").In("tcp", []string{"tcp", "unix", "udp"}),
Cfg.MustValue(modeSec, "ADDR", ":7020")) sec.Key("ADDR").MustString(":7020"))
case "smtp": case "smtp":
LogConfigs[i] = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":"%s","subject":"%s"}`, level, LogConfigs[i] = fmt.Sprintf(`{"level":%s,"username":"%s","password":"%s","host":"%s","sendTos":"%s","subject":"%s"}`, level,
Cfg.MustValue(modeSec, "USER", "example@example.com"), sec.Key("USER").MustString("example@example.com"),
Cfg.MustValue(modeSec, "PASSWD", "******"), sec.Key("PASSWD").MustString("******"),
Cfg.MustValue(modeSec, "HOST", "127.0.0.1:25"), sec.Key("HOST").MustString("127.0.0.1:25"),
Cfg.MustValue(modeSec, "RECEIVERS", "[]"), sec.Key("RECEIVERS").MustString("[]"),
Cfg.MustValue(modeSec, "SUBJECT", "Diagnostic message from serve")) sec.Key("SUBJECT").MustString("Diagnostic message from serve"))
case "database": case "database":
LogConfigs[i] = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level, LogConfigs[i] = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
Cfg.MustValue(modeSec, "DRIVER"), sec.Key("DRIVER").String(),
Cfg.MustValue(modeSec, "CONN")) sec.Key("CONN").String())
} }
log.NewLogger(Cfg.MustInt64("log", "BUFFER_LEN", 10000), mode, LogConfigs[i]) log.NewLogger(Cfg.Section("log").Key("BUFFER_LEN").MustInt64(10000), mode, LogConfigs[i])
log.Info("Log Mode: %s(%s)", strings.Title(mode), levelName) log.Info("Log Mode: %s(%s)", strings.Title(mode), levelName)
} }
} }
func newCacheService() { func newCacheService() {
CacheAdapter = Cfg.MustValueRange("cache", "ADAPTER", "memory", []string{"memory", "redis", "memcache"}) CacheAdapter = Cfg.Section("cache").Key("ADAPTER").In("memory", []string{"memory", "redis", "memcache"})
if EnableRedis { if EnableRedis {
log.Info("Redis Enabled") log.Info("Redis Enabled")
} }
@ -400,9 +404,9 @@ func newCacheService() {
switch CacheAdapter { switch CacheAdapter {
case "memory": case "memory":
CacheInternal = Cfg.MustInt("cache", "INTERVAL", 60) CacheInternal = Cfg.Section("cache").Key("INTERVAL").MustInt(60)
case "redis", "memcache": case "redis", "memcache":
CacheConn = strings.Trim(Cfg.MustValue("cache", "HOST"), "\" ") CacheConn = strings.Trim(Cfg.Section("cache").Key("HOST").String(), "\" ")
default: default:
log.Fatal(4, "Unknown cache adapter: %s", CacheAdapter) log.Fatal(4, "Unknown cache adapter: %s", CacheAdapter)
} }
@ -411,14 +415,14 @@ func newCacheService() {
} }
func newSessionService() { func newSessionService() {
SessionConfig.Provider = Cfg.MustValueRange("session", "PROVIDER", "memory", SessionConfig.Provider = Cfg.Section("session").Key("PROVIDER").In("memory",
[]string{"memory", "file", "redis", "mysql"}) []string{"memory", "file", "redis", "mysql"})
SessionConfig.ProviderConfig = strings.Trim(Cfg.MustValue("session", "PROVIDER_CONFIG"), "\" ") SessionConfig.ProviderConfig = strings.Trim(Cfg.Section("session").Key("PROVIDER_CONFIG").String(), "\" ")
SessionConfig.CookieName = Cfg.MustValue("session", "COOKIE_NAME", "i_like_gogits") SessionConfig.CookieName = Cfg.Section("session").Key("COOKIE_NAME").MustString("i_like_gogits")
SessionConfig.CookiePath = AppSubUrl SessionConfig.CookiePath = AppSubUrl
SessionConfig.Secure = Cfg.MustBool("session", "COOKIE_SECURE") SessionConfig.Secure = Cfg.Section("session").Key("COOKIE_SECURE").MustBool()
SessionConfig.Gclifetime = Cfg.MustInt64("session", "GC_INTERVAL_TIME", 86400) SessionConfig.Gclifetime = Cfg.Section("session").Key("GC_INTERVAL_TIME").MustInt64(86400)
SessionConfig.Maxlifetime = Cfg.MustInt64("session", "SESSION_LIFE_TIME", 86400) SessionConfig.Maxlifetime = Cfg.Section("session").Key("SESSION_LIFE_TIME").MustInt64(86400)
log.Info("Session Service Enabled") log.Info("Session Service Enabled")
} }
@ -450,24 +454,25 @@ var (
) )
func newMailService() { func newMailService() {
sec := Cfg.Section("mailer")
// Check mailer setting. // Check mailer setting.
if !Cfg.MustBool("mailer", "ENABLED") { if !sec.Key("ENABLED").MustBool() {
return return
} }
MailService = &Mailer{ MailService = &Mailer{
Name: Cfg.MustValue("mailer", "NAME", AppName), Name: sec.Key("NAME").MustString(AppName),
Host: Cfg.MustValue("mailer", "HOST"), Host: sec.Key("HOST").String(),
User: Cfg.MustValue("mailer", "USER"), User: sec.Key("USER").String(),
Passwd: Cfg.MustValue("mailer", "PASSWD"), Passwd: sec.Key("PASSWD").String(),
SkipVerify: Cfg.MustBool("mailer", "SKIP_VERIFY", false), SkipVerify: sec.Key("SKIP_VERIFY").MustBool(),
} }
MailService.From = Cfg.MustValue("mailer", "FROM", MailService.User) MailService.From = sec.Key("FROM").MustString(MailService.User)
log.Info("Mail Service Enabled") log.Info("Mail Service Enabled")
} }
func newRegisterMailService() { func newRegisterMailService() {
if !Cfg.MustBool("service", "REGISTER_EMAIL_CONFIRM") { if !Cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").MustBool() {
return return
} else if MailService == nil { } else if MailService == nil {
log.Warn("Register Mail Service: Mail Service is not enabled") log.Warn("Register Mail Service: Mail Service is not enabled")
@ -478,7 +483,7 @@ func newRegisterMailService() {
} }
func newNotifyMailService() { func newNotifyMailService() {
if !Cfg.MustBool("service", "ENABLE_NOTIFY_MAIL") { if !Cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").MustBool() {
return return
} else if MailService == nil { } else if MailService == nil {
log.Warn("Notify Mail Service: Mail Service is not enabled") log.Warn("Notify Mail Service: Mail Service is not enabled")
@ -489,8 +494,8 @@ func newNotifyMailService() {
} }
func newWebhookService() { func newWebhookService() {
WebhookTaskInterval = Cfg.MustInt("webhook", "TASK_INTERVAL", 1) WebhookTaskInterval = Cfg.Section("webhook").Key("TASK_INTERVAL").MustInt(1)
WebhookDeliverTimeout = Cfg.MustInt("webhook", "DELIVER_TIMEOUT", 5) WebhookDeliverTimeout = Cfg.Section("webhook").Key("DELIVER_TIMEOUT").MustInt(5)
} }
func NewServices() { func NewServices() {

View File

@ -35,7 +35,7 @@ var (
) )
func NewOauthService() { func NewOauthService() {
if !setting.Cfg.MustBool("oauth", "ENABLED") { if !setting.Cfg.Section("oauth").Key("ENABLED").MustBool() {
return return
} }
@ -48,20 +48,21 @@ func NewOauthService() {
allOauthes := []string{"github", "google", "qq", "twitter", "weibo"} allOauthes := []string{"github", "google", "qq", "twitter", "weibo"}
// Load all OAuth config data. // Load all OAuth config data.
for _, name := range allOauthes { for _, name := range allOauthes {
if !setting.Cfg.MustBool("oauth."+name, "ENABLED") { sec := setting.Cfg.Section("oauth." + name)
if !sec.Key("ENABLED").MustBool() {
continue continue
} }
setting.OauthService.OauthInfos[name] = &setting.OauthInfo{ setting.OauthService.OauthInfos[name] = &setting.OauthInfo{
Options: oauth2.Options{ Options: oauth2.Options{
ClientID: setting.Cfg.MustValue("oauth."+name, "CLIENT_ID"), ClientID: sec.Key("CLIENT_ID").String(),
ClientSecret: setting.Cfg.MustValue("oauth."+name, "CLIENT_SECRET"), ClientSecret: sec.Key("CLIENT_SECRET").String(),
Scopes: setting.Cfg.MustValueArray("oauth."+name, "SCOPES", " "), Scopes: sec.Key("SCOPES").Strings(" "),
PathLogin: "/user/login/oauth2/" + name, PathLogin: "/user/login/oauth2/" + name,
PathCallback: setting.AppSubUrl + "/user/login/" + name, PathCallback: setting.AppSubUrl + "/user/login/" + name,
RedirectURL: setting.AppUrl + "user/login/" + name, RedirectURL: setting.AppUrl + "user/login/" + name,
}, },
AuthUrl: setting.Cfg.MustValue("oauth."+name, "AUTH_URL"), AuthUrl: sec.Key("AUTH_URL").String(),
TokenUrl: setting.Cfg.MustValue("oauth."+name, "TOKEN_URL"), TokenUrl: sec.Key("TOKEN_URL").String(),
} }
socialConfigs[name] = &oauth2.Options{ socialConfigs[name] = &oauth2.Options{
ClientID: setting.OauthService.OauthInfos[name].ClientID, ClientID: setting.OauthService.OauthInfos[name].ClientID,
@ -72,35 +73,35 @@ func NewOauthService() {
enabledOauths := make([]string, 0, 10) enabledOauths := make([]string, 0, 10)
// GitHub. // GitHub.
if setting.Cfg.MustBool("oauth.github", "ENABLED") { if setting.Cfg.Section("oauth.github").Key("ENABLED").MustBool() {
setting.OauthService.GitHub = true setting.OauthService.GitHub = true
newGitHubOauth(socialConfigs["github"]) newGitHubOauth(socialConfigs["github"])
enabledOauths = append(enabledOauths, "GitHub") enabledOauths = append(enabledOauths, "GitHub")
} }
// Google. // Google.
if setting.Cfg.MustBool("oauth.google", "ENABLED") { if setting.Cfg.Section("oauth.google").Key("ENABLED").MustBool() {
setting.OauthService.Google = true setting.OauthService.Google = true
newGoogleOauth(socialConfigs["google"]) newGoogleOauth(socialConfigs["google"])
enabledOauths = append(enabledOauths, "Google") enabledOauths = append(enabledOauths, "Google")
} }
// QQ. // QQ.
if setting.Cfg.MustBool("oauth.qq", "ENABLED") { if setting.Cfg.Section("oauth.qq").Key("ENABLED").MustBool() {
setting.OauthService.Tencent = true setting.OauthService.Tencent = true
newTencentOauth(socialConfigs["qq"]) newTencentOauth(socialConfigs["qq"])
enabledOauths = append(enabledOauths, "QQ") enabledOauths = append(enabledOauths, "QQ")
} }
// Twitter. // Twitter.
// if setting.Cfg.MustBool("oauth.twitter", "ENABLED") { // if setting.Cfg.Section("oauth.twitter").Key( "ENABLED").MustBool() {
// setting.OauthService.Twitter = true // setting.OauthService.Twitter = true
// newTwitterOauth(socialConfigs["twitter"]) // newTwitterOauth(socialConfigs["twitter"])
// enabledOauths = append(enabledOauths, "Twitter") // enabledOauths = append(enabledOauths, "Twitter")
// } // }
// Weibo. // Weibo.
if setting.Cfg.MustBool("oauth.weibo", "ENABLED") { if setting.Cfg.Section("oauth.weibo").Key("ENABLED").MustBool() {
setting.OauthService.Weibo = true setting.OauthService.Weibo = true
newWeiboOauth(socialConfigs["weibo"]) newWeiboOauth(socialConfigs["weibo"])
enabledOauths = append(enabledOauths, "Weibo") enabledOauths = append(enabledOauths, "Weibo")

View File

@ -12,7 +12,6 @@ import (
"strings" "strings"
"github.com/Unknwon/com" "github.com/Unknwon/com"
"github.com/Unknwon/goconfig"
"github.com/Unknwon/macaron" "github.com/Unknwon/macaron"
"github.com/go-xorm/xorm" "github.com/go-xorm/xorm"
@ -32,7 +31,7 @@ const (
) )
func checkRunMode() { func checkRunMode() {
switch setting.Cfg.MustValue("", "RUN_MODE") { switch setting.Cfg.Section("").Key("RUN_MODE").String() {
case "prod": case "prod":
macaron.Env = macaron.PROD macaron.Env = macaron.PROD
setting.ProdMode = true setting.ProdMode = true
@ -210,40 +209,40 @@ func InstallPost(ctx *middleware.Context, form auth.InstallForm) {
} }
// Save settings. // Save settings.
setting.Cfg.SetValue("database", "DB_TYPE", models.DbCfg.Type) setting.Cfg.Section("database").Key("DB_TYPE").SetValue(models.DbCfg.Type)
setting.Cfg.SetValue("database", "HOST", models.DbCfg.Host) setting.Cfg.Section("database").Key("HOST").SetValue(models.DbCfg.Host)
setting.Cfg.SetValue("database", "NAME", models.DbCfg.Name) setting.Cfg.Section("database").Key("NAME").SetValue(models.DbCfg.Name)
setting.Cfg.SetValue("database", "USER", models.DbCfg.User) setting.Cfg.Section("database").Key("USER").SetValue(models.DbCfg.User)
setting.Cfg.SetValue("database", "PASSWD", models.DbCfg.Pwd) setting.Cfg.Section("database").Key("PASSWD").SetValue(models.DbCfg.Pwd)
setting.Cfg.SetValue("database", "SSL_MODE", models.DbCfg.SslMode) setting.Cfg.Section("database").Key("SSL_MODE").SetValue(models.DbCfg.SslMode)
setting.Cfg.SetValue("database", "PATH", models.DbCfg.Path) setting.Cfg.Section("database").Key("PATH").SetValue(models.DbCfg.Path)
setting.Cfg.SetValue("repository", "ROOT", form.RepoRootPath) setting.Cfg.Section("repository").Key("ROOT").SetValue(form.RepoRootPath)
setting.Cfg.SetValue("", "RUN_USER", form.RunUser) setting.Cfg.Section("").Key("RUN_USER").SetValue(form.RunUser)
setting.Cfg.SetValue("server", "DOMAIN", form.Domain) setting.Cfg.Section("server").Key("DOMAIN").SetValue(form.Domain)
setting.Cfg.SetValue("server", "ROOT_URL", form.AppUrl) setting.Cfg.Section("server").Key("ROOT_URL").SetValue(form.AppUrl)
if len(strings.TrimSpace(form.SmtpHost)) > 0 { if len(strings.TrimSpace(form.SmtpHost)) > 0 {
setting.Cfg.SetValue("mailer", "ENABLED", "true") setting.Cfg.Section("mailer").Key("ENABLED").SetValue("true")
setting.Cfg.SetValue("mailer", "HOST", form.SmtpHost) setting.Cfg.Section("mailer").Key("HOST").SetValue(form.SmtpHost)
setting.Cfg.SetValue("mailer", "USER", form.SmtpEmail) setting.Cfg.Section("mailer").Key("USER").SetValue(form.SmtpEmail)
setting.Cfg.SetValue("mailer", "PASSWD", form.SmtpPasswd) setting.Cfg.Section("mailer").Key("PASSWD").SetValue(form.SmtpPasswd)
setting.Cfg.SetValue("service", "REGISTER_EMAIL_CONFIRM", com.ToStr(form.RegisterConfirm == "on")) setting.Cfg.Section("service").Key("REGISTER_EMAIL_CONFIRM").SetValue(com.ToStr(form.RegisterConfirm == "on"))
setting.Cfg.SetValue("service", "ENABLE_NOTIFY_MAIL", com.ToStr(form.MailNotify == "on")) setting.Cfg.Section("service").Key("ENABLE_NOTIFY_MAIL").SetValue(com.ToStr(form.MailNotify == "on"))
} }
setting.Cfg.SetValue("", "RUN_MODE", "prod") setting.Cfg.Section("").Key("RUN_MODE").SetValue("prod")
setting.Cfg.SetValue("session", "PROVIDER", "file") setting.Cfg.Section("session").Key("PROVIDER").SetValue("file")
setting.Cfg.SetValue("log", "MODE", "file") setting.Cfg.Section("log").Key("MODE").SetValue("file")
setting.Cfg.SetValue("security", "INSTALL_LOCK", "true") setting.Cfg.Section("security").Key("INSTALL_LOCK").SetValue("true")
setting.Cfg.SetValue("security", "SECRET_KEY", base.GetRandomString(15)) setting.Cfg.Section("security").Key("SECRET_KEY").SetValue(base.GetRandomString(15))
os.MkdirAll("custom/conf", os.ModePerm) os.MkdirAll("custom/conf", os.ModePerm)
if err := goconfig.SaveConfigFile(setting.Cfg, path.Join(setting.CustomPath, "conf/app.ini")); err != nil { if err := setting.Cfg.SaveTo(path.Join(setting.CustomPath, "conf/app.ini")); err != nil {
ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), INSTALL, &form) ctx.RenderWithErr(ctx.Tr("install.save_config_failed", err), INSTALL, &form)
return return
} }