From a3a93aef11f9ff6eca38e9147b022a0649b73bdf Mon Sep 17 00:00:00 2001
From: Unknown <joe2010xtmf@163.com>
Date: Tue, 18 Mar 2014 01:33:53 -0400
Subject: [PATCH 01/16] Add some config options

---
 conf/app.ini         | 26 +++++++++++++++++++-------
 models/user.go       |  2 +-
 modules/base/conf.go | 31 ++++++++++++++++++++++++++-----
 web.go               | 13 +++++++++++++
 4 files changed, 59 insertions(+), 13 deletions(-)

diff --git a/conf/app.ini b/conf/app.ini
index 1c7021072f..9d4ee0b594 100644
--- a/conf/app.ini
+++ b/conf/app.ini
@@ -1,12 +1,14 @@
-# App name that shows on every page title
+; App name that shows on every page title
 APP_NAME = Gogs: Go Git Service
-# !!MUST CHANGE TO YOUR USER NAME!!
+; !!MUST CHANGE TO YOUR USER NAME!!
 RUN_USER = lunny
+; Either "dev", "prod" or "test", based on martini
+RUN_MODE = dev
 
 [repository]
 ROOT = /Users/%(RUN_USER)s/git/gogs-repositories
-LANG_IGNS=Google Go|C|Python|Ruby|C Sharp
-LICENSES=Apache v2 License|GPL v2|MIT License|Affero GPL|BSD (3-Clause) License
+LANG_IGNS = Google Go|C|Python|Ruby|C Sharp
+LICENSES = Apache v2 License|GPL v2|MIT License|Affero GPL|BSD (3-Clause) License
 
 [server]
 DOMAIN = gogits.org
@@ -14,15 +16,25 @@ HTTP_ADDR =
 HTTP_PORT = 3000
 
 [database]
-# Either "mysql" or "postgres", it's your choice
+; Either "mysql" or "postgres", it's your choice
 DB_TYPE = mysql
 HOST = 
 NAME = gogs
 USER = root
 PASSWD =
-# For "postgres" only, either "disable" or "verify-full"
+; For "postgres" only, either "disable", "require" or "verify-full"
 SSL_MODE = disable
 
 [security]
-# !!CHANGE THIS TO KEEP YOUR USER DATA SAFE!!
+; !!CHANGE THIS TO KEEP YOUR USER DATA SAFE!!
 USER_PASSWD_SALT = !#@FDEWREWR&*(
+
+[mailer]
+ENABLED = true
+; Name displayed in mail title
+NAME = %(APP_NAME)s
+; Mail server
+HOST = 
+; Mailer user name and password
+USER = 
+PASSWD = 
\ No newline at end of file
diff --git a/models/user.go b/models/user.go
index 87c644b2b6..80af9bd4ba 100644
--- a/models/user.go
+++ b/models/user.go
@@ -252,7 +252,7 @@ func LoginUserPlain(name, passwd string) (*User, error) {
 	} else if !has {
 		err = ErrUserNotExist
 	}
-	return &user, nil
+	return &user, err
 }
 
 // FollowUser marks someone be another's follower.
diff --git a/modules/base/conf.go b/modules/base/conf.go
index 9ed5545e8a..83c7f8872d 100644
--- a/modules/base/conf.go
+++ b/modules/base/conf.go
@@ -13,13 +13,23 @@ import (
 
 	"github.com/Unknwon/com"
 	"github.com/Unknwon/goconfig"
+
+	"github.com/gogits/gogs/modules/log"
 )
 
+// Mailer represents a mail service.
+type Mailer struct {
+	Name         string
+	Host         string
+	User, Passwd string
+}
+
 var (
-	AppVer  string
-	AppName string
-	Domain  string
-	Cfg     *goconfig.ConfigFile
+	AppVer      string
+	AppName     string
+	Domain      string
+	Cfg         *goconfig.ConfigFile
+	MailService *Mailer
 )
 
 func exeDir() (string, error) {
@@ -59,6 +69,17 @@ func init() {
 	}
 	Cfg.BlockMode = false
 
-	AppName = Cfg.MustValue("", "APP_NAME")
+	AppName = Cfg.MustValue("", "APP_NAME", "Gogs: Go Git Service")
 	Domain = Cfg.MustValue("server", "DOMAIN")
+
+	// Check mailer setting.
+	if Cfg.MustBool("mailer", "ENABLED") {
+		MailService = &Mailer{
+			Name:   Cfg.MustValue("mailer", "NAME", AppName),
+			Host:   Cfg.MustValue("mailer", "HOST", "127.0.0.1:25"),
+			User:   Cfg.MustValue("mailer", "USER", "example@example.com"),
+			Passwd: Cfg.MustValue("mailer", "PASSWD", "******"),
+		}
+		log.Info("Mail Service Enabled")
+	}
 }
diff --git a/web.go b/web.go
index ca504ea560..cc20097907 100644
--- a/web.go
+++ b/web.go
@@ -8,6 +8,7 @@ import (
 	"fmt"
 	"html/template"
 	"net/http"
+	"strings"
 
 	"github.com/codegangsta/cli"
 	"github.com/codegangsta/martini"
@@ -34,8 +35,20 @@ gogs web`,
 	Flags:  []cli.Flag{},
 }
 
+// Check run mode(Default of martini is Dev).
+func checkRunMode() {
+	switch base.Cfg.MustValue("", "RUN_MODE") {
+	case "prod":
+		martini.Env = martini.Prod
+	case "test":
+		martini.Env = martini.Test
+	}
+	log.Info("Run Mode: %s", strings.Title(martini.Env))
+}
+
 func runWeb(*cli.Context) {
 	log.Info("%s %s", base.AppName, base.AppVer)
+	checkRunMode()
 
 	m := martini.Classic()
 

From 76644c2fcc29d89dfea2248966527d1996628184 Mon Sep 17 00:00:00 2001
From: Unknown <joe2010xtmf@163.com>
Date: Tue, 18 Mar 2014 04:19:10 -0400
Subject: [PATCH 02/16] Support go build.io

---
 .gobuild.yml | 7 +++++++
 conf/app.ini | 2 +-
 2 files changed, 8 insertions(+), 1 deletion(-)
 create mode 100644 .gobuild.yml

diff --git a/.gobuild.yml b/.gobuild.yml
new file mode 100644
index 0000000000..d667c93082
--- /dev/null
+++ b/.gobuild.yml
@@ -0,0 +1,7 @@
+filesets:
+    includes:
+        - templates
+        - public
+        - conf
+        - LICENSE
+        - README.md
\ No newline at end of file
diff --git a/conf/app.ini b/conf/app.ini
index 9d4ee0b594..5dc21a676e 100644
--- a/conf/app.ini
+++ b/conf/app.ini
@@ -30,7 +30,7 @@ SSL_MODE = disable
 USER_PASSWD_SALT = !#@FDEWREWR&*(
 
 [mailer]
-ENABLED = true
+ENABLED = false
 ; Name displayed in mail title
 NAME = %(APP_NAME)s
 ; Mail server

From ccd43b09b22f551070c2656dd2f4c7f347619a1c Mon Sep 17 00:00:00 2001
From: "shengxiang[skyblue]" <ssx205@gmail.com>
Date: Tue, 18 Mar 2014 21:58:58 +0800
Subject: [PATCH 03/16] add some comment

---
 models/action.go        |  4 +--
 routers/user/setting.go |  2 ++
 update.go               |  4 +--
 web.go                  | 58 ++++++++++++++++++++++-------------------
 4 files changed, 37 insertions(+), 31 deletions(-)

diff --git a/models/action.go b/models/action.go
index 7917929df4..d388bca991 100644
--- a/models/action.go
+++ b/models/action.go
@@ -22,8 +22,8 @@ const (
 // Action represents user operation type and information to the repository.
 type Action struct {
 	Id          int64
-	UserId      int64 // Receiver user id.
-	OpType      int
+	UserId      int64  // Receiver user id.
+	OpType      int    // Operations: CREATE DELETE STAR ...
 	ActUserId   int64  // Action user id.
 	ActUserName string // Action user name.
 	RepoId      int64
diff --git a/routers/user/setting.go b/routers/user/setting.go
index 91e992b18e..ea42f70cfa 100644
--- a/routers/user/setting.go
+++ b/routers/user/setting.go
@@ -14,6 +14,7 @@ import (
 	"github.com/gogits/gogs/modules/middleware"
 )
 
+// render user setting page (email, website modify)
 func Setting(ctx *middleware.Context, form auth.UpdateProfileForm) {
 	ctx.Data["Title"] = "Setting"
 	ctx.Data["PageIsUserSetting"] = true
@@ -26,6 +27,7 @@ func Setting(ctx *middleware.Context, form auth.UpdateProfileForm) {
 		return
 	}
 
+	// below is for POST requests
 	if hasErr, ok := ctx.Data["HasError"]; ok && hasErr.(bool) {
 		ctx.Render.HTML(200, "user/setting", ctx.Data)
 		return
diff --git a/update.go b/update.go
index 23d8fb028a..baa433d75c 100644
--- a/update.go
+++ b/update.go
@@ -10,8 +10,7 @@ import (
 
 	"github.com/codegangsta/cli"
 
-	git "github.com/gogits/git"
-
+	"github.com/gogits/git"
 	"github.com/gogits/gogs/models"
 	"github.com/gogits/gogs/modules/log"
 )
@@ -25,6 +24,7 @@ gogs serv provide access auth for repositories`,
 	Flags:  []cli.Flag{},
 }
 
+// for command: ./gogs update
 func runUpdate(*cli.Context) {
 	userName := os.Getenv("userName")
 	userId := os.Getenv("userId")
diff --git a/web.go b/web.go
index cc20097907..a0e3971175 100644
--- a/web.go
+++ b/web.go
@@ -61,48 +61,52 @@ func runWeb(*cli.Context) {
 
 	m.Use(middleware.InitContext())
 
+	ignSignIn := middleware.SignInRequire(false)
+	reqSignIn, reqSignOut := middleware.SignInRequire(true), middleware.SignOutRequire()
 	// Routers.
-	m.Get("/", middleware.SignInRequire(false), routers.Home)
-	m.Get("/issues", middleware.SignInRequire(true), user.Issues)
-	m.Get("/pulls", middleware.SignInRequire(true), user.Pulls)
-	m.Get("/stars", middleware.SignInRequire(true), user.Stars)
-	m.Any("/user/login", middleware.SignOutRequire(), binding.BindIgnErr(auth.LogInForm{}), user.SignIn)
-	m.Any("/user/logout", middleware.SignInRequire(true), user.SignOut)
-	m.Any("/user/sign_up", middleware.SignOutRequire(), binding.BindIgnErr(auth.RegisterForm{}), user.SignUp)
-	m.Any("/user/delete", middleware.SignInRequire(true), user.Delete)
+	m.Get("/", ignSignIn, routers.Home)
+	m.Get("/issues", reqSignIn, user.Issues)
+	m.Get("/pulls", reqSignIn, user.Pulls)
+	m.Get("/stars", reqSignIn, user.Stars)
+	m.Any("/user/login", reqSignOut, binding.BindIgnErr(auth.LogInForm{}), user.SignIn)
+	m.Any("/user/logout", reqSignIn, user.SignOut)
+	m.Any("/user/sign_up", reqSignOut, binding.BindIgnErr(auth.RegisterForm{}), user.SignUp)
+	m.Any("/user/delete", reqSignIn, user.Delete)
 	m.Get("/user/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds)
 
-	m.Any("/user/setting", middleware.SignInRequire(true), binding.BindIgnErr(auth.UpdateProfileForm{}), user.Setting)
-	m.Any("/user/setting/password", middleware.SignInRequire(true), binding.BindIgnErr(auth.UpdatePasswdForm{}), user.SettingPassword)
-	m.Any("/user/setting/ssh", middleware.SignInRequire(true), binding.BindIgnErr(auth.AddSSHKeyForm{}), user.SettingSSHKeys)
-	m.Any("/user/setting/notification", middleware.SignInRequire(true), user.SettingNotification)
-	m.Any("/user/setting/security", middleware.SignInRequire(true), user.SettingSecurity)
+	m.Any("/user/setting", reqSignIn, binding.BindIgnErr(auth.UpdateProfileForm{}), user.Setting)
+	m.Any("/user/setting/password", reqSignIn, binding.BindIgnErr(auth.UpdatePasswdForm{}), user.SettingPassword)
+	m.Any("/user/setting/ssh", reqSignIn, binding.BindIgnErr(auth.AddSSHKeyForm{}), user.SettingSSHKeys)
+	m.Any("/user/setting/notification", reqSignIn, user.SettingNotification)
+	m.Any("/user/setting/security", reqSignIn, user.SettingSecurity)
 
-	m.Get("/user/:username", middleware.SignInRequire(false), user.Profile)
+	m.Get("/user/:username", ignSignIn, user.Profile)
 
-	m.Any("/repo/create", middleware.SignInRequire(true), binding.BindIgnErr(auth.CreateRepoForm{}), repo.Create)
+	m.Any("/repo/create", reqSignIn, binding.BindIgnErr(auth.CreateRepoForm{}), repo.Create)
 
 	m.Get("/help", routers.Help)
 
-	m.Post("/:username/:reponame/settings", middleware.SignInRequire(true), middleware.RepoAssignment(true), repo.SettingPost)
-	m.Get("/:username/:reponame/settings", middleware.SignInRequire(true), middleware.RepoAssignment(true), repo.Setting)
+	m.Post("/:username/:reponame/settings", reqSignIn, middleware.RepoAssignment(true), repo.SettingPost)
+	m.Get("/:username/:reponame/settings", reqSignIn, middleware.RepoAssignment(true), repo.Setting)
 
-	m.Get("/:username/:reponame/commits/:branchname", middleware.SignInRequire(false), middleware.RepoAssignment(true), repo.Commits)
-	m.Get("/:username/:reponame/issues", middleware.SignInRequire(false), middleware.RepoAssignment(true), repo.Issues)
-	m.Get("/:username/:reponame/pulls", middleware.SignInRequire(false), middleware.RepoAssignment(true), repo.Pulls)
-	m.Get("/:username/:reponame/branches", middleware.SignInRequire(false), middleware.RepoAssignment(true), repo.Branches)
+	m.Get("/:username/:reponame/commits/:branchname", ignSignIn, middleware.RepoAssignment(true), repo.Commits)
+	m.Get("/:username/:reponame/issues", ignSignIn, middleware.RepoAssignment(true), repo.Issues)
+	m.Get("/:username/:reponame/pulls", ignSignIn, middleware.RepoAssignment(true), repo.Pulls)
+	m.Get("/:username/:reponame/branches", ignSignIn, middleware.RepoAssignment(true), repo.Branches)
 	m.Get("/:username/:reponame/tree/:branchname/**",
-		middleware.SignInRequire(false), middleware.RepoAssignment(true), repo.Single)
+		ignSignIn, middleware.RepoAssignment(true), repo.Single)
 	m.Get("/:username/:reponame/tree/:branchname",
-		middleware.SignInRequire(false), middleware.RepoAssignment(true), repo.Single)
-	m.Get("/:username/:reponame/commit/:commitid/**", middleware.SignInRequire(false), middleware.RepoAssignment(true), repo.Single)
-	m.Get("/:username/:reponame/commit/:commitid", middleware.SignInRequire(false), middleware.RepoAssignment(true), repo.Single)
+		ignSignIn, middleware.RepoAssignment(true), repo.Single)
+	m.Get("/:username/:reponame/commit/:commitid/**", ignSignIn, middleware.RepoAssignment(true), repo.Single)
+	m.Get("/:username/:reponame/commit/:commitid", ignSignIn, middleware.RepoAssignment(true), repo.Single)
 
-	m.Get("/:username/:reponame", middleware.SignInRequire(false), middleware.RepoAssignment(true), repo.Single)
+	m.Get("/:username/:reponame", ignSignIn, middleware.RepoAssignment(true), repo.Single)
 
 	listenAddr := fmt.Sprintf("%s:%s",
 		base.Cfg.MustValue("server", "HTTP_ADDR"),
 		base.Cfg.MustValue("server", "HTTP_PORT", "3000"))
 	log.Info("Listen: %s", listenAddr)
-	http.ListenAndServe(listenAddr, m)
+	if err := http.ListenAndServe(listenAddr, m); err != nil {
+		log.Critical(err.Error())
+	}
 }

From fbd252c1cf26009e8880c632c8154361db33175e Mon Sep 17 00:00:00 2001
From: Unknown <joe2010xtmf@163.com>
Date: Tue, 18 Mar 2014 18:31:54 -0400
Subject: [PATCH 04/16] Mirror fix

---
 routers/dashboard.go             |  5 +++--
 routers/repo/single.go           | 10 ++++++----
 routers/user/setting.go          | 13 +++++++++----
 routers/user/user.go             | 18 ++++++++++--------
 templates/base/navbar.tmpl       |  2 +-
 templates/help.tmpl              | 11 +++++++++++
 templates/home.tmpl              |  2 +-
 templates/repo/issues.tmpl       |  9 +++++++++
 templates/repo/pulls.tmpl        |  9 +++++++++
 templates/user/issues.tmpl       | 17 +++++++++++++++++
 templates/user/notification.tmpl | 12 +-----------
 templates/user/password.tmpl     | 26 ++++++++------------------
 templates/user/publickey.tmpl    | 13 +------------
 templates/user/pulls.tmpl        | 17 +++++++++++++++++
 templates/user/security.tmpl     | 12 +-----------
 templates/user/setting.tmpl      | 12 +-----------
 templates/user/setting_nav.tmpl  | 11 +++++++++++
 templates/user/stars.tmpl        | 17 +++++++++++++++++
 18 files changed, 133 insertions(+), 83 deletions(-)
 create mode 100644 templates/help.tmpl
 create mode 100644 templates/repo/issues.tmpl
 create mode 100644 templates/repo/pulls.tmpl
 create mode 100644 templates/user/issues.tmpl
 create mode 100644 templates/user/pulls.tmpl
 create mode 100644 templates/user/setting_nav.tmpl
 create mode 100644 templates/user/stars.tmpl

diff --git a/routers/dashboard.go b/routers/dashboard.go
index ddaef0cb56..d5358f0a00 100644
--- a/routers/dashboard.go
+++ b/routers/dashboard.go
@@ -18,6 +18,7 @@ func Home(ctx *middleware.Context) {
 	ctx.Render.HTML(200, "home", ctx.Data)
 }
 
-func Help(ctx *middleware.Context) string {
-	return "This is help page"
+func Help(ctx *middleware.Context) {
+	ctx.Data["PageIsHelp"] = true
+	ctx.Render.HTML(200, "help", ctx.Data)
 }
diff --git a/routers/repo/single.go b/routers/repo/single.go
index 0cc41b1c8f..d64248d990 100644
--- a/routers/repo/single.go
+++ b/routers/repo/single.go
@@ -182,10 +182,12 @@ func Commits(ctx *middleware.Context, params martini.Params) {
 	ctx.Render.HTML(200, "repo/commits", ctx.Data)
 }
 
-func Issues(ctx *middleware.Context) string {
-	return "This is issues page"
+func Issues(ctx *middleware.Context) {
+	ctx.Data["IsRepoToolbarIssues"] = true
+	ctx.Render.HTML(200, "repo/issues", ctx.Data)
 }
 
-func Pulls(ctx *middleware.Context) string {
-	return "This is pulls page"
+func Pulls(ctx *middleware.Context) {
+	ctx.Data["IsRepoToolbarPulls"] = true
+	ctx.Render.HTML(200, "repo/pulls", ctx.Data)
 }
diff --git a/routers/user/setting.go b/routers/user/setting.go
index ea42f70cfa..3f60c6c6fb 100644
--- a/routers/user/setting.go
+++ b/routers/user/setting.go
@@ -14,10 +14,11 @@ import (
 	"github.com/gogits/gogs/modules/middleware"
 )
 
-// render user setting page (email, website modify)
+// Render user setting page (email, website modify)
 func Setting(ctx *middleware.Context, form auth.UpdateProfileForm) {
 	ctx.Data["Title"] = "Setting"
-	ctx.Data["PageIsUserSetting"] = true
+	ctx.Data["PageIsUserSetting"] = true // For navbar arrow.
+	ctx.Data["IsUserPageSetting"] = true // For setting nav highlight.
 
 	user := ctx.User
 	ctx.Data["Owner"] = user
@@ -50,6 +51,7 @@ func Setting(ctx *middleware.Context, form auth.UpdateProfileForm) {
 func SettingPassword(ctx *middleware.Context, form auth.UpdatePasswdForm) {
 	ctx.Data["Title"] = "Password"
 	ctx.Data["PageIsUserSetting"] = true
+	ctx.Data["IsUserPageSettingPasswd"] = true
 
 	if ctx.Req.Method == "GET" {
 		ctx.Render.HTML(200, "user/password", ctx.Data)
@@ -149,20 +151,23 @@ func SettingSSHKeys(ctx *middleware.Context, form auth.AddSSHKeyForm) {
 	}
 
 	ctx.Data["PageIsUserSetting"] = true
+	ctx.Data["IsUserPageSettingSSH"] = true
 	ctx.Data["Keys"] = keys
 	ctx.Render.HTML(200, "user/publickey", ctx.Data)
 }
 
 func SettingNotification(ctx *middleware.Context) {
-	// todo user setting notification
+	// TODO: user setting notification
 	ctx.Data["Title"] = "Notification"
 	ctx.Data["PageIsUserSetting"] = true
+	ctx.Data["IsUserPageSettingNotify"] = true
 	ctx.Render.HTML(200, "user/notification", ctx.Data)
 }
 
 func SettingSecurity(ctx *middleware.Context) {
-	// todo user setting security
+	// TODO: user setting security
 	ctx.Data["Title"] = "Security"
 	ctx.Data["PageIsUserSetting"] = true
+	ctx.Data["IsUserPageSettingSecurity"] = true
 	ctx.Render.HTML(200, "user/security", ctx.Data)
 }
diff --git a/routers/user/user.go b/routers/user/user.go
index c43cf84a24..f8c9b4d3dd 100644
--- a/routers/user/user.go
+++ b/routers/user/user.go
@@ -151,6 +151,8 @@ func SignUp(ctx *middleware.Context, form auth.RegisterForm) {
 
 func Delete(ctx *middleware.Context) {
 	ctx.Data["Title"] = "Delete Account"
+	ctx.Data["PageIsUserSetting"] = true
+	ctx.Data["IsUserPageSettingDelete"] = true
 
 	if ctx.Req.Method == "GET" {
 		ctx.Render.HTML(200, "user/delete", ctx.Data)
@@ -182,7 +184,7 @@ func Delete(ctx *middleware.Context) {
 }
 
 const (
-	feedTpl = `<i class="icon fa fa-%s"></i>
+	TPL_FEED = `<i class="icon fa fa-%s"></i>
                         <div class="info"><span class="meta">%s</span><br>%s</div>`
 )
 
@@ -194,20 +196,20 @@ func Feeds(ctx *middleware.Context, form auth.FeedsForm) {
 
 	feeds := make([]string, len(actions))
 	for i := range actions {
-		feeds[i] = fmt.Sprintf(feedTpl, base.ActionIcon(actions[i].OpType),
+		feeds[i] = fmt.Sprintf(TPL_FEED, base.ActionIcon(actions[i].OpType),
 			base.TimeSince(actions[i].Created), base.ActionDesc(actions[i], ctx.User.AvatarLink()))
 	}
 	ctx.Render.JSON(200, &feeds)
 }
 
-func Issues(ctx *middleware.Context) string {
-	return "This is issues page"
+func Issues(ctx *middleware.Context) {
+	ctx.Render.HTML(200, "user/issues", ctx.Data)
 }
 
-func Pulls(ctx *middleware.Context) string {
-	return "This is pulls page"
+func Pulls(ctx *middleware.Context) {
+	ctx.Render.HTML(200, "user/pulls", ctx.Data)
 }
 
-func Stars(ctx *middleware.Context) string {
-	return "This is stars page"
+func Stars(ctx *middleware.Context) {
+	ctx.Render.HTML(200, "user/stars", ctx.Data)
 }
diff --git a/templates/base/navbar.tmpl b/templates/base/navbar.tmpl
index 181beb5a44..4902ce2593 100644
--- a/templates/base/navbar.tmpl
+++ b/templates/base/navbar.tmpl
@@ -3,7 +3,7 @@
         <nav class="gogs-nav">
             <a id="gogs-nav-logo" class="gogs-nav-item{{if .PageIsHome}} active{{end}}" href="/"><img src="/img/favicon.png" alt="Gogs Logo" id="gogs-logo"></a>
             <a class="gogs-nav-item{{if .PageIsUserDashboard}} active{{end}}" href="/">Dashboard</a>
-            <a class="gogs-nav-item" href="/help">Help</a>{{if .IsSigned}}
+            <a class="gogs-nav-item{{if .PageIsHelp}} active{{end}}" href="/help">Help</a>{{if .IsSigned}}
             <a id="gogs-nav-out" class="gogs-nav-item navbar-right navbar-btn btn btn-danger" href="/user/logout/"><i class="fa fa-power-off fa-lg"></i></a>
             <a id="gogs-nav-avatar" class="gogs-nav-item navbar-right" href="{{.SignedUser.HomeLink}}" data-toggle="tooltip" data-placement="bottom" title="{{.SignedUserName}}">
                 <img src="{{.SignedUser.AvatarLink}}?s=28" alt="user-avatar" title="username"/>
diff --git a/templates/help.tmpl b/templates/help.tmpl
new file mode 100644
index 0000000000..b4d5d2a97e
--- /dev/null
+++ b/templates/help.tmpl
@@ -0,0 +1,11 @@
+{{template "base/head" .}}
+{{template "base/navbar" .}}
+<div id="gogs-body-nav">
+    <div class="container">
+        <h3>Help</h3>
+    </div>
+</div>
+<div id="gogs-body" class="container" data-page="user">
+    {{if .HasInfo}}<div class="alert alert-info">{{.InfoMsg}}</div>{{end}}
+</div>
+{{template "base/footer" .}}
\ No newline at end of file
diff --git a/templates/home.tmpl b/templates/home.tmpl
index 8cbb29ebb4..e077624323 100644
--- a/templates/home.tmpl
+++ b/templates/home.tmpl
@@ -1,6 +1,6 @@
 {{template "base/head" .}}
 {{template "base/navbar" .}}
 <div id="gogs-body" class="container">
-	Website is still in the progress of building...please come back later!
+	Welcome to the land of Gogs! There will be some indroduction!
 </div>
 {{template "base/footer" .}}
\ No newline at end of file
diff --git a/templates/repo/issues.tmpl b/templates/repo/issues.tmpl
new file mode 100644
index 0000000000..daacc089c3
--- /dev/null
+++ b/templates/repo/issues.tmpl
@@ -0,0 +1,9 @@
+{{template "base/head" .}}
+{{template "base/navbar" .}}
+{{template "repo/nav" .}}
+{{template "repo/toolbar" .}}
+<div id="gogs-body" class="container">
+    <div id="gogs-source">
+    </div>
+</div>
+{{template "base/footer" .}}
\ No newline at end of file
diff --git a/templates/repo/pulls.tmpl b/templates/repo/pulls.tmpl
new file mode 100644
index 0000000000..daacc089c3
--- /dev/null
+++ b/templates/repo/pulls.tmpl
@@ -0,0 +1,9 @@
+{{template "base/head" .}}
+{{template "base/navbar" .}}
+{{template "repo/nav" .}}
+{{template "repo/toolbar" .}}
+<div id="gogs-body" class="container">
+    <div id="gogs-source">
+    </div>
+</div>
+{{template "base/footer" .}}
\ No newline at end of file
diff --git a/templates/user/issues.tmpl b/templates/user/issues.tmpl
new file mode 100644
index 0000000000..94f6689456
--- /dev/null
+++ b/templates/user/issues.tmpl
@@ -0,0 +1,17 @@
+{{template "base/head" .}}
+{{template "base/navbar" .}}
+<div id="gogs-body-nav">
+    <div class="container">
+        <ul class="nav nav-pills pull-right">
+            <li><a href="/">Feed</a></li>
+            <li class="active"><a href="/issues">Issues</a></li>
+            <li><a href="/pulls">Pull Requests</a></li>
+            <li><a href="/stars">Stars</a></li>
+        </ul>
+        <h3>Issues</h3>
+    </div>
+</div>
+<div id="gogs-body" class="container" data-page="user">
+    {{if .HasInfo}}<div class="alert alert-info">{{.InfoMsg}}</div>{{end}}
+</div>
+{{template "base/footer" .}}
\ No newline at end of file
diff --git a/templates/user/notification.tmpl b/templates/user/notification.tmpl
index ecb3fa856c..7911c0fd5f 100644
--- a/templates/user/notification.tmpl
+++ b/templates/user/notification.tmpl
@@ -1,17 +1,7 @@
 {{template "base/head" .}}
 {{template "base/navbar" .}}
 <div id="gogs-body" class="container" data-page="user">
-    <div id="gogs-user-setting-nav" class="col-md-3">
-        <h4>Account Setting</h4>
-        <ul class="list-group">
-            <li class="list-group-item"><a href="/user/setting">Account Profile</a></li>
-            <li class="list-group-item"><a href="/user/setting/password">Password</a></li>
-            <li class="list-group-item list-group-item-success"><a href="/user/setting/notification">Notifications</a></li>
-            <li class="list-group-item"><a href="/user/setting/ssh/">SSH Keys</a></li>
-            <li class="list-group-item"><a href="/user/setting/security">Security</a></li>
-            <li class="list-group-item"><a href="/user/delete">Delete Account</a></li>
-        </ul>
-    </div>
+    {{template "user/setting_nav" .}}
     <div id="gogs-user-setting-container" class="col-md-9">
         <h4>Notification</h4>
     </div>
diff --git a/templates/user/password.tmpl b/templates/user/password.tmpl
index 532a57cb0f..2ee178a3fc 100644
--- a/templates/user/password.tmpl
+++ b/templates/user/password.tmpl
@@ -1,45 +1,35 @@
 {{template "base/head" .}}
 {{template "base/navbar" .}}
 <div id="gogs-body" class="container" data-page="user">
-    <div id="gogs-user-setting-nav" class="col-md-3">
-        <h4>Account Setting</h4>
-        <ul class="list-group">
-            <li class="list-group-item"><a href="/user/setting">Account Profile</a></li>
-            <li class="list-group-item list-group-item-success"><a href="/user/setting/password">Password</a></li>
-            <li class="list-group-item"><a href="/user/setting/notification">Notifications</a></li>
-            <li class="list-group-item"><a href="/user/setting/ssh/">SSH Keys</a></li>
-            <li class="list-group-item"><a href="/user/setting/security">Security</a></li>
-            <li class="list-group-item"><a href="/user/delete">Delete Account</a></li>
-        </ul>
-    </div>
+    {{template "user/setting_nav" .}}
     <div id="gogs-user-setting-container" class="col-md-9">
         <div id="gogs-setting-pwd">
             <h4>Password</h4>
             <form class="form-horizontal" id="gogs-password-form" method="post" action="/user/setting/password">{{if .IsSuccess}}
                 <p class="alert alert-success">Password is changed successfully. You can now sign in via new password.</p>{{else if .HasError}}<p class="alert alert-danger form-error">{{.ErrorMsg}}</p>{{end}}
                 <div class="form-group">
-                    <label class="col-md-2 control-label">Old Password<strong class="text-danger">*</strong></label>
-                    <div class="col-md-8">
+                    <label class="col-md-3 control-label">Old Password<strong class="text-danger">*</strong></label>
+                    <div class="col-md-7">
                         <input type="password" name="oldpasswd" class="form-control" placeholder="Type your current password" required="required">
                     </div>
                 </div>
 
                 <div class="form-group">
-                    <label class="col-md-2 control-label">New Password<strong class="text-danger">*</strong></label>
-                    <div class="col-md-8">
+                    <label class="col-md-3 control-label">New Password<strong class="text-danger">*</strong></label>
+                    <div class="col-md-7">
                         <input type="password" name="newpasswd" class="form-control" placeholder="Type your new password" required="required">
                     </div>
                 </div>
 
                 <div class="form-group">
-                    <label class="col-md-2 control-label">Re-Type<strong class="text-danger">*</strong></label>
-                    <div class="col-md-8">
+                    <label class="col-md-3 control-label">Re-Type<strong class="text-danger">*</strong></label>
+                    <div class="col-md-7">
                         <input type="password" name="retypepasswd" class="form-control" placeholder="Re-type your new password" required="required">
                     </div>
                 </div>
 
                 <div class="form-group">
-                    <div class="col-md-offset-2 col-md-8">
+                    <div class="col-md-offset-3 col-md-7">
                         <button type="submit" class="btn btn-primary">Change Password</button>&nbsp;&nbsp;
                         <a href="/forget-password/">Forgot your password?</a>
                     </div>
diff --git a/templates/user/publickey.tmpl b/templates/user/publickey.tmpl
index ef5879b54d..72467659be 100644
--- a/templates/user/publickey.tmpl
+++ b/templates/user/publickey.tmpl
@@ -1,18 +1,7 @@
 {{template "base/head" .}}
 {{template "base/navbar" .}}
 <div id="gogs-body" class="container" data-page="user">
-    <div id="gogs-user-setting-nav" class="col-md-3">
-        <h4>Account Setting</h4>
-        <ul class="list-group">
-            <li class="list-group-item"><a href="/user/setting">Account Profile</a></li>
-            <li class="list-group-item"><a href="/user/setting/password">Password</a></li>
-            <li class="list-group-item"><a href="/user/setting/notification">Notifications</a></li>
-            <li class="list-group-item list-group-item-success"><a href="/user/setting/ssh/">SSH Keys</a></li>
-            <li class="list-group-item"><a href="/user/setting/security">Security</a></li>
-            <li class="list-group-item"><a href="/user/delete">Delete Account</a></li>
-        </ul>
-    </div>
-
+    {{template "user/setting_nav" .}}
     <div id="gogs-user-setting-container" class="col-md-9">
         <div id="gogs-ssh-keys">
             <h4>SSH Keys</h4>{{if .AddSSHKeySuccess}}
diff --git a/templates/user/pulls.tmpl b/templates/user/pulls.tmpl
new file mode 100644
index 0000000000..0891f5e850
--- /dev/null
+++ b/templates/user/pulls.tmpl
@@ -0,0 +1,17 @@
+{{template "base/head" .}}
+{{template "base/navbar" .}}
+<div id="gogs-body-nav">
+    <div class="container">
+        <ul class="nav nav-pills pull-right">
+            <li><a href="/">Feed</a></li>
+            <li><a href="/issues">Issues</a></li>
+            <li class="active"><a href="/pulls">Pull Requests</a></li>
+            <li><a href="/stars">Stars</a></li>
+        </ul>
+        <h3>Pull Requests</h3>
+    </div>
+</div>
+<div id="gogs-body" class="container" data-page="user">
+    {{if .HasInfo}}<div class="alert alert-info">{{.InfoMsg}}</div>{{end}}
+</div>
+{{template "base/footer" .}}
\ No newline at end of file
diff --git a/templates/user/security.tmpl b/templates/user/security.tmpl
index cf51127d2c..a7506b5086 100644
--- a/templates/user/security.tmpl
+++ b/templates/user/security.tmpl
@@ -1,17 +1,7 @@
 {{template "base/head" .}}
 {{template "base/navbar" .}}
 <div id="gogs-body" class="container" data-page="user">
-    <div id="gogs-user-setting-nav" class="col-md-3">
-        <h4>Account Setting</h4>
-        <ul class="list-group">
-            <li class="list-group-item"><a href="/user/setting">Account Profile</a></li>
-            <li class="list-group-item"><a href="/user/setting/password">Password</a></li>
-            <li class="list-group-item"><a href="/user/setting/notification">Notifications</a></li>
-            <li class="list-group-item"><a href="/user/setting/ssh/">SSH Keys</a></li>
-            <li class="list-group-item list-group-item-success"><a href="/user/setting/security">Security</a></li>
-            <li class="list-group-item"><a href="/user/delete">Delete Account</a></li>
-        </ul>
-    </div>
+    {{template "user/setting_nav" .}}
     <div id="gogs-user-setting-container" class="col-md-9">
         <h4>Security</h4>
     </div>
diff --git a/templates/user/setting.tmpl b/templates/user/setting.tmpl
index d6a6094f3f..c38054f39b 100644
--- a/templates/user/setting.tmpl
+++ b/templates/user/setting.tmpl
@@ -1,17 +1,7 @@
 {{template "base/head" .}}
 {{template "base/navbar" .}}
 <div id="gogs-body" class="container" data-page="user">
-    <div id="gogs-user-setting-nav" class="col-md-3">
-        <h4>Account Setting</h4>
-        <ul class="list-group">
-            <li class="list-group-item list-group-item-success"><a href="/user/setting">Account Profile</a></li>
-            <li class="list-group-item"><a href="/user/setting/password">Password</a></li>
-            <li class="list-group-item"><a href="/user/setting/notification">Notifications</a></li>
-            <li class="list-group-item"><a href="/user/setting/ssh/">SSH Keys</a></li>
-            <li class="list-group-item"><a href="/user/setting/security">Security</a></li>
-            <li class="list-group-item"><a href="/user/delete">Delete Account</a></li>
-        </ul>
-    </div>
+    {{template "user/setting_nav" .}}
     <div id="gogs-user-setting-container" class="col-md-9">
         <div id="gogs-setting-pwd">
             <h4>Account Profile</h4>
diff --git a/templates/user/setting_nav.tmpl b/templates/user/setting_nav.tmpl
new file mode 100644
index 0000000000..3a500fdafe
--- /dev/null
+++ b/templates/user/setting_nav.tmpl
@@ -0,0 +1,11 @@
+<div id="gogs-user-setting-nav" class="col-md-3">
+    <h4>Account Setting</h4>
+    <ul class="list-group">
+        <li class="list-group-item{{if .IsUserPageSetting}} list-group-item-success{{end}}"><a href="/user/setting">Account Profile</a></li>
+        <li class="list-group-item{{if .IsUserPageSettingPasswd}} list-group-item-success{{end}}"><a href="/user/setting/password">Password</a></li>
+        <li class="list-group-item{{if .IsUserPageSettingNotify}} list-group-item-success{{end}}"><a href="/user/setting/notification">Notifications</a></li>
+        <li class="list-group-item{{if .IsUserPageSettingSSH}} list-group-item-success{{end}}"><a href="/user/setting/ssh/">SSH Keys</a></li>
+        <li class="list-group-item{{if .IsUserPageSettingSecurity}} list-group-item-success{{end}}"><a href="/user/setting/security">Security</a></li>
+        <li class="list-group-item{{if .IsUserPageSettingDelete}} list-group-item-success{{end}}"><a href="/user/delete">Delete Account</a></li>
+    </ul>
+</div>
\ No newline at end of file
diff --git a/templates/user/stars.tmpl b/templates/user/stars.tmpl
new file mode 100644
index 0000000000..4e6f0c92fc
--- /dev/null
+++ b/templates/user/stars.tmpl
@@ -0,0 +1,17 @@
+{{template "base/head" .}}
+{{template "base/navbar" .}}
+<div id="gogs-body-nav">
+    <div class="container">
+        <ul class="nav nav-pills pull-right">
+            <li><a href="/">Feed</a></li>
+            <li><a href="/issues">Issues</a></li>
+            <li><a href="/pulls">Pull Requests</a></li>
+            <li class="active"><a href="/stars">Stars</a></li>
+        </ul>
+        <h3>Stars</h3>
+    </div>
+</div>
+<div id="gogs-body" class="container" data-page="user">
+    {{if .HasInfo}}<div class="alert alert-info">{{.InfoMsg}}</div>{{end}}
+</div>
+{{template "base/footer" .}}
\ No newline at end of file

From 38776a0dd5762b2efbf70ebe98eeecdcd395c185 Mon Sep 17 00:00:00 2001
From: Unknown <joe2010xtmf@163.com>
Date: Tue, 18 Mar 2014 19:14:58 -0400
Subject: [PATCH 05/16] Update README

---
 README.md | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/README.md b/README.md
index fd1a14e0da..08d9787189 100644
--- a/README.md
+++ b/README.md
@@ -15,6 +15,7 @@ There are some very good products in this category such as [gitlab](http://gitla
 
 - Please see [Wiki](https://github.com/gogits/gogs/wiki) for project design, develop specification, change log and road map.
 - See [Trello Broad](https://trello.com/b/uxAoeLUl/gogs-go-git-service) to follow the develop team.
+- Try it before anything? Go down to **Installation -> Install from binary** section!.
 
 ## Features
 
@@ -33,7 +34,7 @@ Make sure you install [Prerequirements](https://github.com/gogits/gogs/wiki/Prer
 
 There are two ways to install Gogs:
 
-- [Install from binary](https://github.com/gogits/gogs/wiki/Install-from-binary)
+- [Install from binary](https://github.com/gogits/gogs/wiki/Install-from-binary): **STRONGLY RECOMMENDED** for just try and deployment!
 - [Install from source](https://github.com/gogits/gogs/wiki/Install-from-source)
 
 ## Acknowledgments

From 3da325591b5d8578f575f5fad59595f3c5efe4d6 Mon Sep 17 00:00:00 2001
From: Lunny Xiao <xiaolunwen@gmail.com>
Date: Wed, 19 Mar 2014 14:39:07 +0800
Subject: [PATCH 06/16] bug fixed for commits list

---
 models/repo.go              |  3 ++-
 modules/base/template.go    | 19 +++++++++++++++++++
 templates/repo/commits.tmpl |  5 +++--
 web.go                      |  4 ++++
 4 files changed, 28 insertions(+), 3 deletions(-)

diff --git a/models/repo.go b/models/repo.go
index c37fb4de20..1331bbf450 100644
--- a/models/repo.go
+++ b/models/repo.go
@@ -5,6 +5,7 @@
 package models
 
 import (
+	"container/list"
 	"errors"
 	"fmt"
 	"io/ioutil"
@@ -601,7 +602,7 @@ func GetLastestCommit(userName, repoName string) (*Commit, error) {
 }*/
 
 // GetCommits returns all commits of given branch of repository.
-func GetCommits(userName, reposName, branchname string) ([]*git.Commit, error) {
+func GetCommits(userName, reposName, branchname string) (*list.List, error) {
 	repo, err := git.OpenRepository(RepoPath(userName, reposName))
 	if err != nil {
 		return nil, err
diff --git a/modules/base/template.go b/modules/base/template.go
index 4517cd47aa..db79340e75 100644
--- a/modules/base/template.go
+++ b/modules/base/template.go
@@ -5,6 +5,7 @@
 package base
 
 import (
+	"container/list"
 	"html/template"
 )
 
@@ -12,6 +13,23 @@ func Str2html(raw string) template.HTML {
 	return template.HTML(raw)
 }
 
+func Range(l int) []int {
+	return make([]int, l)
+}
+
+func List(l *list.List) chan interface{} {
+	e := l.Front()
+	c := make(chan interface{})
+	go func() {
+		for e != nil {
+			c <- e.Value
+			e = e.Next()
+		}
+		close(c)
+	}()
+	return c
+}
+
 var TemplateFuncs template.FuncMap = map[string]interface{}{
 	"AppName": func() string {
 		return AppName
@@ -30,4 +48,5 @@ var TemplateFuncs template.FuncMap = map[string]interface{}{
 	"ActionIcon": ActionIcon,
 	"ActionDesc": ActionDesc,
 	"DateFormat": DateFormat,
+	"List":       List,
 }
diff --git a/templates/repo/commits.tmpl b/templates/repo/commits.tmpl
index 9190a030a3..4bffb9daf7 100644
--- a/templates/repo/commits.tmpl
+++ b/templates/repo/commits.tmpl
@@ -5,8 +5,9 @@
 <div id="gogs-body" class="container">
     <div id="gogs-commits">
     <ul>
-    {{range .Commits}}
-    <li>{{.Committer.Name}} - {{.Id}} - {{.Message}} - {{.Committer.When}}</li>
+    {{$r := List .Commits}}
+    {{range $r}}
+		    <li>{{.Committer.Name}} - {{.Id}} - {{.Message}} - {{.Committer.When}}</li>
     {{end}}
     </ul>
     </div>
diff --git a/web.go b/web.go
index ca504ea560..3ca93f307d 100644
--- a/web.go
+++ b/web.go
@@ -34,6 +34,10 @@ gogs web`,
 	Flags:  []cli.Flag{},
 }
 
+func Range(l int) []int {
+	return make([]int, l)
+}
+
 func runWeb(*cli.Context) {
 	log.Info("%s %s", base.AppName, base.AppVer)
 

From 460aa3eaa96df483981e74a6992878941f11bf00 Mon Sep 17 00:00:00 2001
From: Unknown <joe2010xtmf@163.com>
Date: Wed, 19 Mar 2014 03:24:17 -0400
Subject: [PATCH 07/16] optimize log

---
 .gitignore           |  2 +-
 conf/app.ini         | 58 +++++++++++++++++++++++++++++++++++++++++---
 modules/base/conf.go | 30 +++++++++++++++--------
 modules/log/log.go   |  2 +-
 4 files changed, 77 insertions(+), 15 deletions(-)

diff --git a/.gitignore b/.gitignore
index 6559d61a06..3e550c3fc7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -5,4 +5,4 @@ gogs
 *.db
 *.log
 custom/
-.vendor/
+.vendor/
\ No newline at end of file
diff --git a/conf/app.ini b/conf/app.ini
index 5dc21a676e..e42fc24432 100644
--- a/conf/app.ini
+++ b/conf/app.ini
@@ -2,7 +2,7 @@
 APP_NAME = Gogs: Go Git Service
 ; !!MUST CHANGE TO YOUR USER NAME!!
 RUN_USER = lunny
-; Either "dev", "prod" or "test", based on martini
+; Either "dev", "prod" or "test", default is "dev"
 RUN_MODE = dev
 
 [repository]
@@ -32,9 +32,61 @@ USER_PASSWD_SALT = !#@FDEWREWR&*(
 [mailer]
 ENABLED = false
 ; Name displayed in mail title
-NAME = %(APP_NAME)s
+SUBJECT = %(APP_NAME)s
 ; Mail server
 HOST = 
 ; Mailer user name and password
 USER = 
-PASSWD = 
\ No newline at end of file
+PASSWD = 
+
+[log]
+; Either "console", "file", "conn" or "smtp", default is "console"
+MODE = console
+; Buffer length of channel, keep it as it is if you don't know what it is.
+BUFFER_LEN = 10000
+; Either "Trace", "Debug", "Info", "Warn", "Error", "Critical", default is "Trace"
+LEVEL = Trace
+
+; For "console" mode only, all log files will be stored in "/log" directory
+[log.console]
+LEVEL = 
+
+; For "file" mode only
+[log.file]
+LEVEL = 
+FILE_NAME = "gogs.log"
+; This enables automated log rotate(switch of following options), default is true
+LOG_ROTATE = 
+; Max line number of single file, default is 1000000
+MAX_LINES = 1000000
+; Max size of single file, default is 1 << 28, 256MB
+MAX_SIZE = 1 << 28
+; Segment log daily, default is true
+DAILY_ROTATE = true
+; Expired days of log file(delete after max days), default is 7
+MAX_DAYS = 7
+
+; For "conn" mode only
+[log.conn]
+LEVEL = 
+; Reconnect host for every single message, default is false
+RECONNECT_ON_MSG = false
+; Try to reconnect when connection is lost, default is false
+RECONNECT = false
+; Either "tcp", "unix" or "udp", default is "tcp"
+PROTOCOL = tcp
+; Host address
+ADDR = 
+
+; For "smtp" mode only
+[log.smtp]
+LEVEL = 
+; Name displayed in mail title, default is "Diagnostic message from serve"
+SUBJECT = Diagnostic message from serve
+; Mail server
+HOST = 
+; Mailer user name and password
+USER = 
+PASSWD =
+; Receivers, can be one or more
+RECEIVERS = 
\ No newline at end of file
diff --git a/modules/base/conf.go b/modules/base/conf.go
index 83c7f8872d..1aafd5b44a 100644
--- a/modules/base/conf.go
+++ b/modules/base/conf.go
@@ -44,6 +44,23 @@ func exeDir() (string, error) {
 	return path.Dir(p), nil
 }
 
+func newLogService() {
+	log.NewLogger()
+}
+
+func newMailService() {
+	// Check mailer setting.
+	if Cfg.MustBool("mailer", "ENABLED") {
+		MailService = &Mailer{
+			Name:   Cfg.MustValue("mailer", "NAME", AppName),
+			Host:   Cfg.MustValue("mailer", "HOST", "127.0.0.1:25"),
+			User:   Cfg.MustValue("mailer", "USER", "example@example.com"),
+			Passwd: Cfg.MustValue("mailer", "PASSWD", "******"),
+		}
+		log.Info("Mail Service Enabled")
+	}
+}
+
 func init() {
 	var err error
 	workDir, err := exeDir()
@@ -72,14 +89,7 @@ func init() {
 	AppName = Cfg.MustValue("", "APP_NAME", "Gogs: Go Git Service")
 	Domain = Cfg.MustValue("server", "DOMAIN")
 
-	// Check mailer setting.
-	if Cfg.MustBool("mailer", "ENABLED") {
-		MailService = &Mailer{
-			Name:   Cfg.MustValue("mailer", "NAME", AppName),
-			Host:   Cfg.MustValue("mailer", "HOST", "127.0.0.1:25"),
-			User:   Cfg.MustValue("mailer", "USER", "example@example.com"),
-			Passwd: Cfg.MustValue("mailer", "PASSWD", "******"),
-		}
-		log.Info("Mail Service Enabled")
-	}
+	// Extensions.
+	newLogService()
+	newMailService()
 }
diff --git a/modules/log/log.go b/modules/log/log.go
index 0634bde655..b888f5002e 100644
--- a/modules/log/log.go
+++ b/modules/log/log.go
@@ -11,7 +11,7 @@ import (
 
 var logger *logs.BeeLogger
 
-func init() {
+func NewLogger() {
 	logger = logs.NewLogger(10000)
 	logger.SetLogger("console", "")
 }

From 01162bfc781b1f3d6bfa70196d37cae85cf2cc45 Mon Sep 17 00:00:00 2001
From: Lunny Xiao <xiaolunwen@gmail.com>
Date: Wed, 19 Mar 2014 15:46:16 +0800
Subject: [PATCH 08/16] remove unused codes

---
 models/repo.go | 5 +----
 1 file changed, 1 insertion(+), 4 deletions(-)

diff --git a/models/repo.go b/models/repo.go
index 6abfee747a..cdbb4b5f4a 100644
--- a/models/repo.go
+++ b/models/repo.go
@@ -145,10 +145,7 @@ func CreateRepository(user *User, repoName, desc, repoLang, license string, priv
 		return nil, err
 	}
 
-	rawSql := "UPDATE user SET num_repos = num_repos + 1 WHERE id = ?"
-	if base.Cfg.MustValue("database", "DB_TYPE") == "postgres" {
-		rawSql = "UPDATE \"user\" SET num_repos = num_repos + 1 WHERE id = ?"
-	}
+	rawSql := "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?"
 	if _, err = session.Exec(rawSql, user.Id); err != nil {
 		session.Rollback()
 		if err2 := os.RemoveAll(repoPath); err2 != nil {

From cef9bbd5305d42cdb4e1b807ec0fb55fcff09067 Mon Sep 17 00:00:00 2001
From: Unknown <joe2010xtmf@163.com>
Date: Wed, 19 Mar 2014 04:08:25 -0400
Subject: [PATCH 09/16] Add complete log configuration

---
 conf/app.ini         | 12 +++++-----
 gogs.go              |  2 +-
 modules/base/conf.go | 55 +++++++++++++++++++++++++++++++++++++++++++-
 modules/log/log.go   |  6 ++---
 4 files changed, 64 insertions(+), 11 deletions(-)

diff --git a/conf/app.ini b/conf/app.ini
index e42fc24432..debfcf93bd 100644
--- a/conf/app.ini
+++ b/conf/app.ini
@@ -47,20 +47,20 @@ BUFFER_LEN = 10000
 ; Either "Trace", "Debug", "Info", "Warn", "Error", "Critical", default is "Trace"
 LEVEL = Trace
 
-; For "console" mode only, all log files will be stored in "/log" directory
+; For "console" mode only
 [log.console]
 LEVEL = 
 
 ; For "file" mode only
 [log.file]
 LEVEL = 
-FILE_NAME = "gogs.log"
+FILE_NAME = log/gogs.log
 ; This enables automated log rotate(switch of following options), default is true
-LOG_ROTATE = 
+LOG_ROTATE = true
 ; Max line number of single file, default is 1000000
 MAX_LINES = 1000000
-; Max size of single file, default is 1 << 28, 256MB
-MAX_SIZE = 1 << 28
+; Max size shift of single file, default is 28 means 1 << 28, 256MB
+MAX_SIZE_SHIFT = 28
 ; Segment log daily, default is true
 DAILY_ROTATE = true
 ; Expired days of log file(delete after max days), default is 7
@@ -88,5 +88,5 @@ HOST =
 ; Mailer user name and password
 USER = 
 PASSWD =
-; Receivers, can be one or more
+; Receivers, can be one or more, e.g. ["1@example.com","2@example.com"]
 RECEIVERS = 
\ No newline at end of file
diff --git a/gogs.go b/gogs.go
index 2757fbc115..106e8b1d93 100644
--- a/gogs.go
+++ b/gogs.go
@@ -20,7 +20,7 @@ import (
 // Test that go1.1 tag above is included in builds. main.go refers to this definition.
 const go11tag = true
 
-const APP_VER = "0.1.0.0318.1"
+const APP_VER = "0.1.0.0319.1"
 
 func init() {
 	base.AppVer = APP_VER
diff --git a/modules/base/conf.go b/modules/base/conf.go
index 1aafd5b44a..6610bce1ab 100644
--- a/modules/base/conf.go
+++ b/modules/base/conf.go
@@ -44,8 +44,61 @@ func exeDir() (string, error) {
 	return path.Dir(p), nil
 }
 
+var logLevels = map[string]string{
+	"Trace":    "0",
+	"Debug":    "1",
+	"Info":     "2",
+	"Warn":     "3",
+	"Error":    "4",
+	"Critical": "5",
+}
+
 func newLogService() {
-	log.NewLogger()
+	// Get and check log mode.
+	mode := Cfg.MustValue("log", "MODE", "console")
+	modeSec := "log." + mode
+	if _, err := Cfg.GetSection(modeSec); err != nil {
+		fmt.Printf("Unknown log mode: %s\n", mode)
+		os.Exit(2)
+	}
+
+	// Log level.
+	level, ok := logLevels[Cfg.MustValue("log."+mode, "LEVEL", "Trace")]
+	if !ok {
+		fmt.Printf("Unknown log level: %s\n", Cfg.MustValue("log."+mode, "LEVEL", "Trace"))
+		os.Exit(2)
+	}
+
+	// Generate log configuration.
+	var config string
+	switch mode {
+	case "console":
+		config = fmt.Sprintf(`{"level":%s}`, level)
+	case "file":
+		config = fmt.Sprintf(
+			`{"level":%s,"filename":%s,"rotate":%v,"maxlines":%d,"maxsize",%d,"daily":%v,"maxdays":%d}`, level,
+			Cfg.MustValue(modeSec, "FILE_NAME", "log/gogs.log"),
+			Cfg.MustBool(modeSec, "LOG_ROTATE", true),
+			Cfg.MustInt(modeSec, "MAX_LINES", 1000000),
+			1<<uint(Cfg.MustInt(modeSec, "MAX_SIZE_SHIFT", 28)),
+			Cfg.MustBool(modeSec, "DAILY_ROTATE", true),
+			Cfg.MustInt(modeSec, "MAX_DAYS", 7))
+	case "conn":
+		config = 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.MustValue(modeSec, "PROTOCOL", "tcp"),
+			Cfg.MustValue(modeSec, "ADDR", ":7020"))
+	case "smtp":
+		config = fmt.Sprintf(`{"level":%s,"username":%s,"password":%s,"host":%s,"sendTos":%s,"subject":%s}`, level,
+			Cfg.MustValue(modeSec, "USER", "example@example.com"),
+			Cfg.MustValue(modeSec, "PASSWD", "******"),
+			Cfg.MustValue(modeSec, "HOST", "127.0.0.1:25"),
+			Cfg.MustValue(modeSec, "RECEIVERS", "[]"),
+			Cfg.MustValue(modeSec, "SUBJECT", "Diagnostic message from serve"))
+	}
+
+	log.NewLogger(Cfg.MustInt64("log", "BUFFER_LEN", 10000), mode, config)
 }
 
 func newMailService() {
diff --git a/modules/log/log.go b/modules/log/log.go
index b888f5002e..29782fb2ba 100644
--- a/modules/log/log.go
+++ b/modules/log/log.go
@@ -11,9 +11,9 @@ import (
 
 var logger *logs.BeeLogger
 
-func NewLogger() {
-	logger = logs.NewLogger(10000)
-	logger.SetLogger("console", "")
+func NewLogger(bufLen int64, mode, config string) {
+	logger = logs.NewLogger(bufLen)
+	logger.SetLogger(mode, config)
 }
 
 func Trace(format string, v ...interface{}) {

From 7076f466c9491b07be272d4680cfea5ed839b855 Mon Sep 17 00:00:00 2001
From: Lunny Xiao <xiaolunwen@gmail.com>
Date: Wed, 19 Mar 2014 16:42:50 +0800
Subject: [PATCH 10/16] bug fixed

---
 models/repo.go | 50 ++++++++++++++++++++++++--------------------------
 1 file changed, 24 insertions(+), 26 deletions(-)

diff --git a/models/repo.go b/models/repo.go
index cdbb4b5f4a..38ab3d4a9b 100644
--- a/models/repo.go
+++ b/models/repo.go
@@ -446,7 +446,7 @@ func GetReposFiles(userName, reposName, branchName, commitId, rpath string) ([]*
 		return nil, err
 	}
 
-	commit, err := GetCommit(userName, reposName, branchName, commitId)
+	commit, err := repo.GetCommit(branchName, commitId)
 	if err != nil {
 		return nil, err
 	}
@@ -462,8 +462,10 @@ func GetReposFiles(userName, reposName, branchName, commitId, rpath string) ([]*
 			}
 
 			var cm = commit
-
+			var i int
 			for {
+				i = i + 1
+				//fmt.Println(".....", i, cm.Id(), cm.ParentCount())
 				if cm.ParentCount() == 0 {
 					break
 				} else if cm.ParentCount() == 1 {
@@ -480,7 +482,10 @@ func GetReposFiles(userName, reposName, branchName, commitId, rpath string) ([]*
 				} else {
 					var emptyCnt = 0
 					var sameIdcnt = 0
+					var lastSameCm *git.Commit
+					//fmt.Println(".....", cm.ParentCount())
 					for i := 0; i < cm.ParentCount(); i++ {
+						//fmt.Println("parent", i, cm.Parent(i).Id())
 						p := cm.Parent(i)
 						pt, _ := repo.SubTree(p.Tree, dirname)
 						var pEntry *git.TreeEntry
@@ -488,23 +493,31 @@ func GetReposFiles(userName, reposName, branchName, commitId, rpath string) ([]*
 							pEntry = pt.EntryByName(entry.Name)
 						}
 
+						//fmt.Println("pEntry", pEntry)
+
 						if pEntry == nil {
-							if emptyCnt == cm.ParentCount()-1 {
-								goto loop
-							} else {
-								emptyCnt = emptyCnt + 1
-								continue
+							emptyCnt = emptyCnt + 1
+							if emptyCnt+sameIdcnt == cm.ParentCount() {
+								if lastSameCm == nil {
+									goto loop
+								} else {
+									cm = lastSameCm
+									break
+								}
 							}
 						} else {
+							//fmt.Println(i, "pEntry", pEntry.Id, "entry", entry.Id)
 							if !pEntry.Id.Equal(entry.Id) {
 								goto loop
 							} else {
-								if sameIdcnt == cm.ParentCount()-1 {
+								lastSameCm = cm.Parent(i)
+								sameIdcnt = sameIdcnt + 1
+								if emptyCnt+sameIdcnt == cm.ParentCount() {
 									// TODO: now follow the first parent commit?
-									cm = cm.Parent(0)
+									cm = lastSameCm
+									//fmt.Println("sameId...")
 									break
 								}
-								sameIdcnt = sameIdcnt + 1
 							}
 						}
 					}
@@ -539,22 +552,7 @@ func GetCommit(userName, repoName, branchname, commitid string) (*git.Commit, er
 		return nil, err
 	}
 
-	if commitid != "" {
-		oid, err := git.NewOidFromString(commitid)
-		if err != nil {
-			return nil, err
-		}
-		return repo.LookupCommit(oid)
-	}
-	if branchname == "" {
-		return nil, errors.New("no branch name and no commit id")
-	}
-
-	r, err := repo.LookupReference(fmt.Sprintf("refs/heads/%s", branchname))
-	if err != nil {
-		return nil, err
-	}
-	return r.LastCommit()
+	return repo.GetCommit(branchname, commitid)
 }
 
 // GetCommits returns all commits of given branch of repository.

From bd9d90d8c48965e4e78fd56147c465ba80ec5ed5 Mon Sep 17 00:00:00 2001
From: Unknown <joe2010xtmf@163.com>
Date: Wed, 19 Mar 2014 04:48:45 -0400
Subject: [PATCH 11/16] Add some log

---
 modules/base/conf.go          | 7 +++++--
 modules/middleware/context.go | 7 ++++++-
 routers/repo/repo.go          | 3 +++
 routers/user/setting.go       | 4 ++++
 routers/user/user.go          | 3 +++
 web.go                        | 2 +-
 6 files changed, 22 insertions(+), 4 deletions(-)

diff --git a/modules/base/conf.go b/modules/base/conf.go
index 6610bce1ab..9f6de56b9d 100644
--- a/modules/base/conf.go
+++ b/modules/base/conf.go
@@ -10,6 +10,7 @@ import (
 	"os/exec"
 	"path"
 	"path/filepath"
+	"strings"
 
 	"github.com/Unknwon/com"
 	"github.com/Unknwon/goconfig"
@@ -63,9 +64,10 @@ func newLogService() {
 	}
 
 	// Log level.
-	level, ok := logLevels[Cfg.MustValue("log."+mode, "LEVEL", "Trace")]
+	levelName := Cfg.MustValue("log."+mode, "LEVEL", "Trace")
+	level, ok := logLevels[levelName]
 	if !ok {
-		fmt.Printf("Unknown log level: %s\n", Cfg.MustValue("log."+mode, "LEVEL", "Trace"))
+		fmt.Printf("Unknown log level: %s\n", levelName)
 		os.Exit(2)
 	}
 
@@ -99,6 +101,7 @@ func newLogService() {
 	}
 
 	log.NewLogger(Cfg.MustInt64("log", "BUFFER_LEN", 10000), mode, config)
+	log.Info("Log Mode: %s(%s)", strings.Title(mode), levelName)
 }
 
 func newMailService() {
diff --git a/modules/middleware/context.go b/modules/middleware/context.go
index d002d3c24e..7eaf665005 100644
--- a/modules/middleware/context.go
+++ b/modules/middleware/context.go
@@ -67,8 +67,13 @@ func (ctx *Context) RenderWithErr(msg, tpl string, form auth.Form) {
 
 // Handle handles and logs error by given status.
 func (ctx *Context) Handle(status int, title string, err error) {
-	ctx.Data["ErrorMsg"] = err
 	log.Error("%s: %v", title, err)
+	if martini.Dev == martini.Prod {
+		ctx.Render.HTML(500, "status/500", ctx.Data)
+		return
+	}
+
+	ctx.Data["ErrorMsg"] = err
 	ctx.Render.HTML(status, fmt.Sprintf("status/%d", status), ctx.Data)
 }
 
diff --git a/routers/repo/repo.go b/routers/repo/repo.go
index 7171ff2640..08fe1ed15b 100644
--- a/routers/repo/repo.go
+++ b/routers/repo/repo.go
@@ -7,6 +7,7 @@ package repo
 import (
 	"github.com/gogits/gogs/models"
 	"github.com/gogits/gogs/modules/auth"
+	"github.com/gogits/gogs/modules/log"
 	"github.com/gogits/gogs/modules/middleware"
 )
 
@@ -23,6 +24,7 @@ func Create(ctx *middleware.Context, form auth.CreateRepoForm) {
 	_, err := models.CreateRepository(ctx.User, form.RepoName, form.Description,
 		form.Language, form.License, form.Visibility == "private", form.InitReadme == "on")
 	if err == nil {
+		log.Trace("%s Repository created: %s/%s", ctx.Req.RequestURI, ctx.User.LowerName, form.RepoName)
 		ctx.Render.Redirect("/"+ctx.User.Name+"/"+form.RepoName, 302)
 		return
 	} else if err == models.ErrRepoAlreadyExist {
@@ -48,6 +50,7 @@ func SettingPost(ctx *middleware.Context) {
 
 		if err := models.DeleteRepository(ctx.User.Id, ctx.Repo.Repository.Id, ctx.User.LowerName); err != nil {
 			ctx.Handle(200, "repo.Delete", err)
+			log.Trace("%s Repository deleted: %s/%s", ctx.Req.RequestURI, ctx.User.LowerName, ctx.Repo.Repository.LowerName)
 			return
 		}
 	}
diff --git a/routers/user/setting.go b/routers/user/setting.go
index 3f60c6c6fb..66289b6e4d 100644
--- a/routers/user/setting.go
+++ b/routers/user/setting.go
@@ -46,6 +46,7 @@ func Setting(ctx *middleware.Context, form auth.UpdateProfileForm) {
 
 	ctx.Data["IsSuccess"] = true
 	ctx.Render.HTML(200, "user/setting", ctx.Data)
+	log.Trace("%s User setting updated: %s", ctx.Req.RequestURI, ctx.User.LowerName)
 }
 
 func SettingPassword(ctx *middleware.Context, form auth.UpdatePasswdForm) {
@@ -82,6 +83,7 @@ func SettingPassword(ctx *middleware.Context, form auth.UpdatePasswdForm) {
 
 	ctx.Data["Owner"] = user
 	ctx.Render.HTML(200, "user/password", ctx.Data)
+	log.Trace("%s User password updated: %s", ctx.Req.RequestURI, ctx.User.LowerName)
 }
 
 func SettingSSHKeys(ctx *middleware.Context, form auth.AddSSHKeyForm) {
@@ -112,6 +114,7 @@ func SettingSSHKeys(ctx *middleware.Context, form auth.AddSSHKeyForm) {
 				"err": err.Error(),
 			})
 		} else {
+			log.Trace("%s User SSH key deleted: %s", ctx.Req.RequestURI, ctx.User.LowerName)
 			ctx.Render.JSON(200, map[string]interface{}{
 				"ok": true,
 			})
@@ -137,6 +140,7 @@ func SettingSSHKeys(ctx *middleware.Context, form auth.AddSSHKeyForm) {
 				return
 			}
 			ctx.Handle(200, "ssh.AddPublicKey", err)
+			log.Trace("%s User SSH key added: %s", ctx.Req.RequestURI, ctx.User.LowerName)
 			return
 		} else {
 			ctx.Data["AddSSHKeySuccess"] = true
diff --git a/routers/user/user.go b/routers/user/user.go
index f8c9b4d3dd..fc56997b58 100644
--- a/routers/user/user.go
+++ b/routers/user/user.go
@@ -6,6 +6,7 @@ package user
 
 import (
 	"fmt"
+	"strings"
 
 	"github.com/codegangsta/martini"
 	"github.com/martini-contrib/render"
@@ -14,6 +15,7 @@ import (
 	"github.com/gogits/gogs/models"
 	"github.com/gogits/gogs/modules/auth"
 	"github.com/gogits/gogs/modules/base"
+	"github.com/gogits/gogs/modules/log"
 	"github.com/gogits/gogs/modules/middleware"
 )
 
@@ -146,6 +148,7 @@ func SignUp(ctx *middleware.Context, form auth.RegisterForm) {
 		return
 	}
 
+	log.Trace("%s User created: %s", ctx.Req.RequestURI, strings.ToLower(form.UserName))
 	ctx.Render.Redirect("/user/login")
 }
 
diff --git a/web.go b/web.go
index a0e3971175..018d8ffd79 100644
--- a/web.go
+++ b/web.go
@@ -47,8 +47,8 @@ func checkRunMode() {
 }
 
 func runWeb(*cli.Context) {
-	log.Info("%s %s", base.AppName, base.AppVer)
 	checkRunMode()
+	log.Info("%s %s", base.AppName, base.AppVer)
 
 	m := martini.Classic()
 

From c593578a55d2f341fe1690d85ea1b1ec45bea50a Mon Sep 17 00:00:00 2001
From: Gogs <gogitservice@gmail.com>
Date: Wed, 19 Mar 2014 17:03:38 +0800
Subject: [PATCH 12/16] fix styles

---
 public/css/gogs.css     | 9 +++++++++
 public/css/markdown.css | 2 +-
 2 files changed, 10 insertions(+), 1 deletion(-)

diff --git a/public/css/gogs.css b/public/css/gogs.css
index 5352f8e397..ec1cb591e2 100755
--- a/public/css/gogs.css
+++ b/public/css/gogs.css
@@ -563,6 +563,15 @@ html, body {
     padding: 9px 20px;
 }
 
+.info-box .info-head {
+    font-weight: normal;
+}
+
+.info-box .info-content  a,
+.info-box .info-head a {
+    color: #666;
+}
+
 .file-list {
     background-color: #fafafa;
 }
diff --git a/public/css/markdown.css b/public/css/markdown.css
index e2b15c2f13..9283fb847c 100644
--- a/public/css/markdown.css
+++ b/public/css/markdown.css
@@ -105,7 +105,7 @@
 .markdown > pre {
   line-height: 1.6;
   overflow: auto;
-  background: #fff;
+  background: #f8f8f8;
   padding: 6px 10px;
   border: 1px solid #ddd;
 }

From 04e5d5b71fe39039baf72b27411e7629edbcc6a2 Mon Sep 17 00:00:00 2001
From: Unknown <joe2010xtmf@163.com>
Date: Wed, 19 Mar 2014 05:31:38 -0400
Subject: [PATCH 13/16] Use custom logger middleware

---
 modules/middleware/logger.go | 44 ++++++++++++++++++++++++++++++++++++
 web.go                       | 13 ++++++++++-
 2 files changed, 56 insertions(+), 1 deletion(-)
 create mode 100644 modules/middleware/logger.go

diff --git a/modules/middleware/logger.go b/modules/middleware/logger.go
new file mode 100644
index 0000000000..9bbedb29a3
--- /dev/null
+++ b/modules/middleware/logger.go
@@ -0,0 +1,44 @@
+// Copyright 2014 The Gogs Authors. All rights reserved.
+// Use of this source code is governed by a MIT-style
+// license that can be found in the LICENSE file.
+
+package middleware
+
+import (
+	"fmt"
+	"log"
+	"net/http"
+	"runtime"
+	"time"
+
+	"github.com/codegangsta/martini"
+)
+
+var isWindows bool
+
+func init() {
+	isWindows = runtime.GOOS == "windows"
+}
+
+func Logger() martini.Handler {
+	return func(res http.ResponseWriter, req *http.Request, ctx martini.Context, log *log.Logger) {
+		start := time.Now()
+		log.Printf("Started %s %s", req.Method, req.URL.Path)
+
+		rw := res.(martini.ResponseWriter)
+		ctx.Next()
+
+		content := fmt.Sprintf("Completed %v %s in %v", rw.Status(), http.StatusText(rw.Status()), time.Since(start))
+		if !isWindows {
+			switch rw.Status() {
+			case 200:
+				content = fmt.Sprintf("\033[1;32%s\033[0m", content)
+			case 304:
+				content = fmt.Sprintf("\033[1;33%s\033[0m", content)
+			case 404:
+				content = fmt.Sprintf("\033[1;31%s\033[0m", content)
+			}
+		}
+		log.Println(content)
+	}
+}
diff --git a/web.go b/web.go
index 018d8ffd79..97cfdcc436 100644
--- a/web.go
+++ b/web.go
@@ -46,11 +46,22 @@ func checkRunMode() {
 	log.Info("Run Mode: %s", strings.Title(martini.Env))
 }
 
+func newMartini() *martini.ClassicMartini {
+	r := martini.NewRouter()
+	m := martini.New()
+	m.Use(middleware.Logger())
+	m.Use(martini.Recovery())
+	m.Use(martini.Static("public"))
+	m.MapTo(r, (*martini.Routes)(nil))
+	m.Action(r.Handle)
+	return &martini.ClassicMartini{m, r}
+}
+
 func runWeb(*cli.Context) {
 	checkRunMode()
 	log.Info("%s %s", base.AppName, base.AppVer)
 
-	m := martini.Classic()
+	m := newMartini()
 
 	// Middlewares.
 	m.Use(render.Renderer(render.Options{Funcs: []template.FuncMap{base.TemplateFuncs}}))

From 9a666f33773c5d8b66e9ab66598414f62bcfdc11 Mon Sep 17 00:00:00 2001
From: Unknown <joe2010xtmf@163.com>
Date: Wed, 19 Mar 2014 05:35:52 -0400
Subject: [PATCH 14/16] Bug fix

---
 modules/middleware/logger.go | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/modules/middleware/logger.go b/modules/middleware/logger.go
index 9bbedb29a3..9ae620ebad 100644
--- a/modules/middleware/logger.go
+++ b/modules/middleware/logger.go
@@ -32,11 +32,11 @@ func Logger() martini.Handler {
 		if !isWindows {
 			switch rw.Status() {
 			case 200:
-				content = fmt.Sprintf("\033[1;32%s\033[0m", content)
+				content = fmt.Sprintf("\033[1;32m%s\033[0m", content)
 			case 304:
-				content = fmt.Sprintf("\033[1;33%s\033[0m", content)
+				content = fmt.Sprintf("\033[1;33m%s\033[0m", content)
 			case 404:
-				content = fmt.Sprintf("\033[1;31%s\033[0m", content)
+				content = fmt.Sprintf("\033[1;31m%s\033[0m", content)
 			}
 		}
 		log.Println(content)

From fbbae2b721c04be740d67b9d227a7578030f93b9 Mon Sep 17 00:00:00 2001
From: Unknown <joe2010xtmf@163.com>
Date: Wed, 19 Mar 2014 07:21:23 -0400
Subject: [PATCH 15/16] Working on register mail confirmation

---
 conf/app.ini                 | 12 +++++--
 models/user.go               | 25 +++++++++------
 modules/auth/mail.go         | 42 ++++++++++++++++++++++++
 modules/base/conf.go         | 29 +++++++++++++++++
 modules/base/tool.go         | 62 ++++++++++++++++++++++++++++++++++++
 modules/mailer/mail.go       | 24 ++++++++++++++
 modules/middleware/logger.go |  2 ++
 routers/user/user.go         |  7 ++--
 8 files changed, 189 insertions(+), 14 deletions(-)
 create mode 100644 modules/auth/mail.go
 create mode 100644 modules/mailer/mail.go

diff --git a/conf/app.ini b/conf/app.ini
index debfcf93bd..82d78d2334 100644
--- a/conf/app.ini
+++ b/conf/app.ini
@@ -1,5 +1,6 @@
 ; App name that shows on every page title
 APP_NAME = Gogs: Go Git Service
+APP_LOGO = img/favicon.png
 ; !!MUST CHANGE TO YOUR USER NAME!!
 RUN_USER = lunny
 ; Either "dev", "prod" or "test", default is "dev"
@@ -11,7 +12,8 @@ LANG_IGNS = Google Go|C|Python|Ruby|C Sharp
 LICENSES = Apache v2 License|GPL v2|MIT License|Affero GPL|BSD (3-Clause) License
 
 [server]
-DOMAIN = gogits.org
+DOMAIN = localhost
+ROOT_URL = http://%(DOMAIN)s:%(HTTP_PORT)s/
 HTTP_ADDR = 
 HTTP_PORT = 3000
 
@@ -27,7 +29,13 @@ SSL_MODE = disable
 
 [security]
 ; !!CHANGE THIS TO KEEP YOUR USER DATA SAFE!!
-USER_PASSWD_SALT = !#@FDEWREWR&*(
+SECRET_KEY = !#@FDEWREWR&*(
+
+[service]
+ACTIVE_CODE_LIVE_MINUTES = 180
+RESET_PASSWD_CODE_LIVE_MINUTES = 180
+; User need to confirm e-mail for registration
+REGISTER_EMAIL_CONFIRM = true
 
 [mailer]
 ENABLED = false
diff --git a/models/user.go b/models/user.go
index 80af9bd4ba..579f6a7486 100644
--- a/models/user.go
+++ b/models/user.go
@@ -19,14 +19,6 @@ import (
 	"github.com/gogits/gogs/modules/base"
 )
 
-var (
-	UserPasswdSalt string
-)
-
-func init() {
-	UserPasswdSalt = base.Cfg.MustValue("security", "USER_PASSWD_SALT")
-}
-
 // User types.
 const (
 	UT_INDIVIDUAL = iota + 1
@@ -56,6 +48,9 @@ type User struct {
 	AvatarEmail   string `xorm:"not null"`
 	Location      string
 	Website       string
+	IsActive      bool
+	Rands         string `xorm:"VARCHAR(10)"`
+	Expired       time.Time
 	Created       time.Time `xorm:"created"`
 	Updated       time.Time `xorm:"updated"`
 }
@@ -104,6 +99,11 @@ func (user *User) NewGitSig() *git.Signature {
 	}
 }
 
+// return a user salt token
+func GetUserSalt() string {
+	return base.GetRandomString(10)
+}
+
 // RegisterUser creates record of a new user.
 func RegisterUser(user *User) (err error) {
 	isExist, err := IsUserExist(user.Name)
@@ -123,6 +123,8 @@ func RegisterUser(user *User) (err error) {
 	user.LowerName = strings.ToLower(user.Name)
 	user.Avatar = base.EncodeMd5(user.Email)
 	user.AvatarEmail = user.Email
+	user.Expired = time.Now().Add(3 * 24 * time.Hour)
+	user.Rands = GetUserSalt()
 	if err = user.EncodePasswd(); err != nil {
 		return err
 	} else if _, err = orm.Insert(user); err != nil {
@@ -134,6 +136,11 @@ func RegisterUser(user *User) (err error) {
 		}
 		return err
 	}
+
+	// Send confirmation e-mail.
+	if base.Service.RegisterEmailConfitm {
+
+	}
 	return nil
 }
 
@@ -183,7 +190,7 @@ func DeleteUser(user *User) error {
 
 // EncodePasswd encodes password to safe format.
 func (user *User) EncodePasswd() error {
-	newPasswd, err := scrypt.Key([]byte(user.Passwd), []byte(UserPasswdSalt), 16384, 8, 1, 64)
+	newPasswd, err := scrypt.Key([]byte(user.Passwd), []byte(base.SecretKey), 16384, 8, 1, 64)
 	user.Passwd = fmt.Sprintf("%x", newPasswd)
 	return err
 }
diff --git a/modules/auth/mail.go b/modules/auth/mail.go
new file mode 100644
index 0000000000..6f6bf20a06
--- /dev/null
+++ b/modules/auth/mail.go
@@ -0,0 +1,42 @@
+// Copyright 2014 The Gogs Authors. All rights reserved.
+// Use of this source code is governed by a MIT-style
+// license that can be found in the LICENSE file.
+
+package auth
+
+import (
+	"encoding/hex"
+	"fmt"
+
+	"github.com/gogits/gogs/models"
+	"github.com/gogits/gogs/modules/base"
+	"github.com/gogits/gogs/modules/mailer"
+)
+
+// create a time limit code for user active
+func CreateUserActiveCode(user *models.User, startInf interface{}) string {
+	hours := base.Service.ActiveCodeLives / 60
+	data := fmt.Sprintf("%d", user.Id) + user.Email + user.LowerName + user.Passwd + user.Rands
+	code := base.CreateTimeLimitCode(data, hours, startInf)
+
+	// add tail hex username
+	code += hex.EncodeToString([]byte(user.LowerName))
+	return code
+}
+
+// Send user register mail with active code
+func SendRegisterMail(user *models.User) {
+	code := CreateUserActiveCode(user, nil)
+	subject := "Register success, Welcome"
+
+	data := mailer.GetMailTmplData(user)
+	data["Code"] = code
+	body := base.RenderTemplate("mail/auth/register_success.html", data)
+	_, _, _ = code, subject, body
+
+	// msg := mailer.NewMailMessage([]string{user.Email}, subject, body)
+	// msg.Info = fmt.Sprintf("UID: %d, send register mail", user.Id)
+
+	// // async send mail
+	// mailer.SendAsync(msg)
+}
diff --git a/modules/base/conf.go b/modules/base/conf.go
index 9f6de56b9d..ee5638ed68 100644
--- a/modules/base/conf.go
+++ b/modules/base/conf.go
@@ -28,11 +28,20 @@ type Mailer struct {
 var (
 	AppVer      string
 	AppName     string
+	AppLogo     string
+	AppUrl      string
 	Domain      string
+	SecretKey   string
 	Cfg         *goconfig.ConfigFile
 	MailService *Mailer
 )
 
+var Service struct {
+	RegisterEmailConfitm bool
+	ActiveCodeLives      int
+	ResetPwdCodeLives    int
+}
+
 func exeDir() (string, error) {
 	file, err := exec.LookPath(os.Args[0])
 	if err != nil {
@@ -54,6 +63,11 @@ 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)
+}
+
 func newLogService() {
 	// Get and check log mode.
 	mode := Cfg.MustValue("log", "MODE", "console")
@@ -117,6 +131,17 @@ func newMailService() {
 	}
 }
 
+func newRegisterService() {
+	if !Cfg.MustBool("service", "REGISTER_EMAIL_CONFIRM") {
+		return
+	} else if MailService == nil {
+		log.Warn("Register Service: Mail Service is not enabled")
+		return
+	}
+	Service.RegisterEmailConfitm = true
+	log.Info("Register Service Enabled")
+}
+
 func init() {
 	var err error
 	workDir, err := exeDir()
@@ -143,9 +168,13 @@ func init() {
 	Cfg.BlockMode = false
 
 	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")
+	SecretKey = Cfg.MustValue("security", "SECRET_KEY")
 
 	// Extensions.
 	newLogService()
 	newMailService()
+	newRegisterService()
 }
diff --git a/modules/base/tool.go b/modules/base/tool.go
index 046b2c5174..2a989b377d 100644
--- a/modules/base/tool.go
+++ b/modules/base/tool.go
@@ -7,6 +7,8 @@ package base
 import (
 	"bytes"
 	"crypto/md5"
+	"crypto/rand"
+	"crypto/sha1"
 	"encoding/hex"
 	"encoding/json"
 	"fmt"
@@ -22,6 +24,66 @@ func EncodeMd5(str string) string {
 	return hex.EncodeToString(m.Sum(nil))
 }
 
+// Random generate string
+func GetRandomString(n int) string {
+	const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
+	var bytes = make([]byte, n)
+	rand.Read(bytes)
+	for i, b := range bytes {
+		bytes[i] = alphanum[b%byte(len(alphanum))]
+	}
+	return string(bytes)
+}
+
+// create a time limit code
+// code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string
+func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string {
+	format := "YmdHi"
+
+	var start, end time.Time
+	var startStr, endStr string
+
+	if startInf == nil {
+		// Use now time create code
+		start = time.Now()
+		startStr = DateFormat(start, format)
+	} else {
+		// use start string create code
+		startStr = startInf.(string)
+		start, _ = DateParse(startStr, format)
+		startStr = DateFormat(start, format)
+	}
+
+	end = start.Add(time.Minute * time.Duration(minutes))
+	endStr = DateFormat(end, format)
+
+	// create sha1 encode string
+	sh := sha1.New()
+	sh.Write([]byte(data + SecretKey + startStr + endStr + fmt.Sprintf("%d", minutes)))
+	encoded := hex.EncodeToString(sh.Sum(nil))
+
+	code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
+	return code
+}
+
+func RenderTemplate(TplNames string, Data map[interface{}]interface{}) string {
+	// if beego.RunMode == "dev" {
+	// 	beego.BuildTemplate(beego.ViewsPath)
+	// }
+
+	// ibytes := bytes.NewBufferString("")
+	// if _, ok := beego.BeeTemplates[TplNames]; !ok {
+	// 	panic("can't find templatefile in the path:" + TplNames)
+	// }
+	// err := beego.BeeTemplates[TplNames].ExecuteTemplate(ibytes, TplNames, Data)
+	// if err != nil {
+	// 	beego.Trace("template Execute err:", err)
+	// }
+	// icontent, _ := ioutil.ReadAll(ibytes)
+	// return string(icontent)
+	return "not implement yet"
+}
+
 // AvatarLink returns avatar link by given e-mail.
 func AvatarLink(email string) string {
 	return "http://1.gravatar.com/avatar/" + EncodeMd5(email)
diff --git a/modules/mailer/mail.go b/modules/mailer/mail.go
new file mode 100644
index 0000000000..fe74af9eef
--- /dev/null
+++ b/modules/mailer/mail.go
@@ -0,0 +1,24 @@
+// Copyright 2014 The Gogs Authors. All rights reserved.
+// Use of this source code is governed by a MIT-style
+// license that can be found in the LICENSE file.
+
+package mailer
+
+import (
+	"github.com/gogits/gogs/models"
+	"github.com/gogits/gogs/modules/base"
+)
+
+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
+	data["ResetPwdCodeLives"] = base.Service.ResetPwdCodeLives
+	if user != nil {
+		data["User"] = user
+	}
+	return data
+}
diff --git a/modules/middleware/logger.go b/modules/middleware/logger.go
index 9ae620ebad..dcf8524608 100644
--- a/modules/middleware/logger.go
+++ b/modules/middleware/logger.go
@@ -37,6 +37,8 @@ func Logger() martini.Handler {
 				content = fmt.Sprintf("\033[1;33m%s\033[0m", content)
 			case 404:
 				content = fmt.Sprintf("\033[1;31m%s\033[0m", content)
+			case 500:
+				content = fmt.Sprintf("\033[1;36m%s\033[0m", content)
 			}
 		}
 		log.Println(content)
diff --git a/routers/user/user.go b/routers/user/user.go
index fc56997b58..05aeac60ec 100644
--- a/routers/user/user.go
+++ b/routers/user/user.go
@@ -131,9 +131,10 @@ func SignUp(ctx *middleware.Context, form auth.RegisterForm) {
 	}
 
 	u := &models.User{
-		Name:   form.UserName,
-		Email:  form.Email,
-		Passwd: form.Password,
+		Name:     form.UserName,
+		Email:    form.Email,
+		Passwd:   form.Password,
+		IsActive: !base.Service.RegisterEmailConfitm,
 	}
 
 	if err := models.RegisterUser(u); err != nil {

From de087c7b4a31cb0643d5432ec9d6b26e208baff2 Mon Sep 17 00:00:00 2001
From: Unknown <joe2010xtmf@163.com>
Date: Wed, 19 Mar 2014 08:27:27 -0400
Subject: [PATCH 16/16] Add send register confirm mail

---
 README.md                |   1 +
 conf/app.ini             |   5 +-
 models/user.go           |  25 ++++-----
 modules/auth/mail.go     |  11 ++--
 modules/base/conf.go     |   4 +-
 modules/base/tool.go     |  55 ++++++++++++++++++-
 modules/mailer/mail.go   |   7 +++
 modules/mailer/mailer.go | 112 +++++++++++++++++++++++++++++++++++++++
 routers/repo/repo.go     |   2 +-
 routers/user/user.go     |  10 +++-
 10 files changed, 204 insertions(+), 28 deletions(-)
 create mode 100644 modules/mailer/mailer.go

diff --git a/README.md b/README.md
index 08d9787189..c0cd9cceb2 100644
--- a/README.md
+++ b/README.md
@@ -39,6 +39,7 @@ There are two ways to install Gogs:
 
 ## Acknowledgments
 
+- Mail service is based on [WeTalk](https://github.com/beego/wetalk).
 - Logo inspired by [martini](https://github.com/martini-contrib).
 
 ## Contributors
diff --git a/conf/app.ini b/conf/app.ini
index 82d78d2334..c2c299cf63 100644
--- a/conf/app.ini
+++ b/conf/app.ini
@@ -35,14 +35,17 @@ SECRET_KEY = !#@FDEWREWR&*(
 ACTIVE_CODE_LIVE_MINUTES = 180
 RESET_PASSWD_CODE_LIVE_MINUTES = 180
 ; User need to confirm e-mail for registration
-REGISTER_EMAIL_CONFIRM = true
+REGISTER_EMAIL_CONFIRM = false
 
 [mailer]
 ENABLED = false
 ; Name displayed in mail title
 SUBJECT = %(APP_NAME)s
 ; Mail server
+; Gmail: smtp.gmail.com:587
 HOST = 
+; Mail from address
+FROM = 
 ; Mailer user name and password
 USER = 
 PASSWD = 
diff --git a/models/user.go b/models/user.go
index 579f6a7486..5f08f9e92d 100644
--- a/models/user.go
+++ b/models/user.go
@@ -105,19 +105,19 @@ func GetUserSalt() string {
 }
 
 // RegisterUser creates record of a new user.
-func RegisterUser(user *User) (err error) {
+func RegisterUser(user *User) (*User, error) {
 	isExist, err := IsUserExist(user.Name)
 	if err != nil {
-		return err
+		return nil, err
 	} else if isExist {
-		return ErrUserAlreadyExist
+		return nil, ErrUserAlreadyExist
 	}
 
 	isExist, err = IsEmailUsed(user.Email)
 	if err != nil {
-		return err
+		return nil, err
 	} else if isExist {
-		return ErrEmailAlreadyUsed
+		return nil, ErrEmailAlreadyUsed
 	}
 
 	user.LowerName = strings.ToLower(user.Name)
@@ -126,22 +126,17 @@ func RegisterUser(user *User) (err error) {
 	user.Expired = time.Now().Add(3 * 24 * time.Hour)
 	user.Rands = GetUserSalt()
 	if err = user.EncodePasswd(); err != nil {
-		return err
+		return nil, err
 	} else if _, err = orm.Insert(user); err != nil {
-		return err
+		return nil, err
 	} else if err = os.MkdirAll(UserPath(user.Name), os.ModePerm); err != nil {
 		if _, err := orm.Id(user.Id).Delete(&User{}); err != nil {
-			return errors.New(fmt.Sprintf(
+			return nil, errors.New(fmt.Sprintf(
 				"both create userpath %s and delete table record faild: %v", user.Name, err))
 		}
-		return err
+		return nil, err
 	}
-
-	// Send confirmation e-mail.
-	if base.Service.RegisterEmailConfitm {
-
-	}
-	return nil
+	return user, nil
 }
 
 // UpdateUser updates user's information.
diff --git a/modules/auth/mail.go b/modules/auth/mail.go
index 6f6bf20a06..cdfcce4f99 100644
--- a/modules/auth/mail.go
+++ b/modules/auth/mail.go
@@ -16,7 +16,7 @@ import (
 // create a time limit code for user active
 func CreateUserActiveCode(user *models.User, startInf interface{}) string {
 	hours := base.Service.ActiveCodeLives / 60
-	data := fmt.Sprintf("%d", user.Id) + user.Email + user.LowerName + user.Passwd + user.Rands
+	data := base.ToStr(user.Id) + user.Email + user.LowerName + user.Passwd + user.Rands
 	code := base.CreateTimeLimitCode(data, hours, startInf)
 
 	// add tail hex username
@@ -32,11 +32,10 @@ func SendRegisterMail(user *models.User) {
 	data := mailer.GetMailTmplData(user)
 	data["Code"] = code
 	body := base.RenderTemplate("mail/auth/register_success.html", data)
-	_, _, _ = code, subject, body
 
-	// msg := mailer.NewMailMessage([]string{user.Email}, subject, body)
-	// msg.Info = fmt.Sprintf("UID: %d, send register mail", user.Id)
+	msg := mailer.NewMailMessage([]string{user.Email}, subject, body)
+	msg.Info = fmt.Sprintf("UID: %d, send register mail", user.Id)
 
-	// // async send mail
-	// mailer.SendAsync(msg)
+	// async send mail
+	mailer.SendAsync(msg)
 }
diff --git a/modules/base/conf.go b/modules/base/conf.go
index ee5638ed68..24ee1d7f06 100644
--- a/modules/base/conf.go
+++ b/modules/base/conf.go
@@ -37,7 +37,7 @@ var (
 )
 
 var Service struct {
-	RegisterEmailConfitm bool
+	RegisterEmailConfirm bool
 	ActiveCodeLives      int
 	ResetPwdCodeLives    int
 }
@@ -138,7 +138,7 @@ func newRegisterService() {
 		log.Warn("Register Service: Mail Service is not enabled")
 		return
 	}
-	Service.RegisterEmailConfitm = true
+	Service.RegisterEmailConfirm = true
 	log.Info("Register Service Enabled")
 }
 
diff --git a/modules/base/tool.go b/modules/base/tool.go
index 2a989b377d..fc3b4c45b8 100644
--- a/modules/base/tool.go
+++ b/modules/base/tool.go
@@ -13,6 +13,7 @@ import (
 	"encoding/json"
 	"fmt"
 	"math"
+	"strconv"
 	"strings"
 	"time"
 )
@@ -59,13 +60,14 @@ func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string
 
 	// create sha1 encode string
 	sh := sha1.New()
-	sh.Write([]byte(data + SecretKey + startStr + endStr + fmt.Sprintf("%d", minutes)))
+	sh.Write([]byte(data + SecretKey + startStr + endStr + ToStr(minutes)))
 	encoded := hex.EncodeToString(sh.Sum(nil))
 
 	code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
 	return code
 }
 
+// TODO:
 func RenderTemplate(TplNames string, Data map[interface{}]interface{}) string {
 	// if beego.RunMode == "dev" {
 	// 	beego.BuildTemplate(beego.ViewsPath)
@@ -300,6 +302,57 @@ func DateFormat(t time.Time, format string) string {
 	return t.Format(format)
 }
 
+type argInt []int
+
+func (a argInt) Get(i int, args ...int) (r int) {
+	if i >= 0 && i < len(a) {
+		r = a[i]
+	}
+	if len(args) > 0 {
+		r = args[0]
+	}
+	return
+}
+
+// convert any type to string
+func ToStr(value interface{}, args ...int) (s string) {
+	switch v := value.(type) {
+	case bool:
+		s = strconv.FormatBool(v)
+	case float32:
+		s = strconv.FormatFloat(float64(v), 'f', argInt(args).Get(0, -1), argInt(args).Get(1, 32))
+	case float64:
+		s = strconv.FormatFloat(v, 'f', argInt(args).Get(0, -1), argInt(args).Get(1, 64))
+	case int:
+		s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10))
+	case int8:
+		s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10))
+	case int16:
+		s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10))
+	case int32:
+		s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10))
+	case int64:
+		s = strconv.FormatInt(v, argInt(args).Get(0, 10))
+	case uint:
+		s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10))
+	case uint8:
+		s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10))
+	case uint16:
+		s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10))
+	case uint32:
+		s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10))
+	case uint64:
+		s = strconv.FormatUint(v, argInt(args).Get(0, 10))
+	case string:
+		s = v
+	case []byte:
+		s = string(v)
+	default:
+		s = fmt.Sprintf("%v", v)
+	}
+	return s
+}
+
 type Actioner interface {
 	GetOpType() int
 	GetActUserName() string
diff --git a/modules/mailer/mail.go b/modules/mailer/mail.go
index fe74af9eef..cc4fd6d059 100644
--- a/modules/mailer/mail.go
+++ b/modules/mailer/mail.go
@@ -9,6 +9,13 @@ import (
 	"github.com/gogits/gogs/modules/base"
 )
 
+// Create New mail message use MailFrom and MailUser
+func NewMailMessage(To []string, subject, body string) Message {
+	msg := NewHtmlMessage(To, base.MailService.User, subject, body)
+	msg.User = base.MailService.User
+	return msg
+}
+
 func GetMailTmplData(user *models.User) map[interface{}]interface{} {
 	data := make(map[interface{}]interface{}, 10)
 	data["AppName"] = base.AppName
diff --git a/modules/mailer/mailer.go b/modules/mailer/mailer.go
new file mode 100644
index 0000000000..cc76acb26f
--- /dev/null
+++ b/modules/mailer/mailer.go
@@ -0,0 +1,112 @@
+// Copyright 2014 The Gogs Authors. All rights reserved.
+// Use of this source code is governed by a MIT-style
+// license that can be found in the LICENSE file.
+
+package mailer
+
+import (
+	"fmt"
+	"net/smtp"
+	"strings"
+
+	"github.com/gogits/gogs/modules/base"
+	"github.com/gogits/gogs/modules/log"
+)
+
+type Message struct {
+	To      []string
+	From    string
+	Subject string
+	Body    string
+	User    string
+	Type    string
+	Massive bool
+	Info    string
+}
+
+// create mail content
+func (m Message) Content() string {
+	// set mail type
+	contentType := "text/plain; charset=UTF-8"
+	if m.Type == "html" {
+		contentType = "text/html; charset=UTF-8"
+	}
+
+	// create mail content
+	content := "From: " + m.User + "<" + m.From +
+		">\r\nSubject: " + m.Subject + "\r\nContent-Type: " + contentType + "\r\n\r\n" + m.Body
+	return content
+}
+
+// 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, ":")
+
+	// get message body
+	content := msg.Content()
+
+	auth := smtp.PlainAuth("", base.MailService.User, base.MailService.Passwd, host[0])
+
+	if len(msg.To) == 0 {
+		return 0, fmt.Errorf("empty receive emails")
+	}
+
+	if len(msg.Body) == 0 {
+		return 0, fmt.Errorf("empty email body")
+	}
+
+	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)
+			if err != nil {
+				return num, err
+			}
+			num++
+		}
+		return num, nil
+	} else {
+		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)
+		if err != nil {
+			return 0, err
+		} else {
+			return 1, nil
+		}
+	}
+}
+
+// Async Send mail message
+func SendAsync(msg Message) {
+	// TODO may be need pools limit concurrent nums
+	go func() {
+		num, err := Send(msg)
+		tos := strings.Join(msg.To, "; ")
+		info := ""
+		if err != nil {
+			if len(msg.Info) > 0 {
+				info = ", info: " + msg.Info
+			}
+			// log failed
+			log.Error(fmt.Sprintf("Async sent email %d succeed, not send emails: %s%s err: %s", num, tos, info, err))
+			return
+		}
+		log.Trace(fmt.Sprintf("Async sent email %d succeed, sent emails: %s%s", num, tos, info))
+	}()
+}
+
+// Create html mail message
+func NewHtmlMessage(To []string, From, Subject, Body string) Message {
+	return Message{
+		To:      To,
+		From:    From,
+		Subject: Subject,
+		Body:    Body,
+		Type:    "html",
+	}
+}
diff --git a/routers/repo/repo.go b/routers/repo/repo.go
index 08fe1ed15b..61bf47c1f5 100644
--- a/routers/repo/repo.go
+++ b/routers/repo/repo.go
@@ -50,10 +50,10 @@ func SettingPost(ctx *middleware.Context) {
 
 		if err := models.DeleteRepository(ctx.User.Id, ctx.Repo.Repository.Id, ctx.User.LowerName); err != nil {
 			ctx.Handle(200, "repo.Delete", err)
-			log.Trace("%s Repository deleted: %s/%s", ctx.Req.RequestURI, ctx.User.LowerName, ctx.Repo.Repository.LowerName)
 			return
 		}
 	}
 
+	log.Trace("%s Repository deleted: %s/%s", ctx.Req.RequestURI, ctx.User.LowerName, ctx.Repo.Repository.LowerName)
 	ctx.Render.Redirect("/", 302)
 }
diff --git a/routers/user/user.go b/routers/user/user.go
index 05aeac60ec..2d6bcedce5 100644
--- a/routers/user/user.go
+++ b/routers/user/user.go
@@ -134,10 +134,11 @@ func SignUp(ctx *middleware.Context, form auth.RegisterForm) {
 		Name:     form.UserName,
 		Email:    form.Email,
 		Passwd:   form.Password,
-		IsActive: !base.Service.RegisterEmailConfitm,
+		IsActive: !base.Service.RegisterEmailConfirm,
 	}
 
-	if err := models.RegisterUser(u); err != nil {
+	var err error
+	if u, err = models.RegisterUser(u); err != nil {
 		switch err.Error() {
 		case models.ErrUserAlreadyExist.Error():
 			ctx.RenderWithErr("Username has been already taken", "user/signup", &form)
@@ -150,6 +151,11 @@ func SignUp(ctx *middleware.Context, form auth.RegisterForm) {
 	}
 
 	log.Trace("%s User created: %s", ctx.Req.RequestURI, strings.ToLower(form.UserName))
+
+	// Send confirmation e-mail.
+	if base.Service.RegisterEmailConfirm {
+		auth.SendRegisterMail(u)
+	}
 	ctx.Render.Redirect("/user/login")
 }