aboutsummaryrefslogtreecommitdiff
path: root/modules
diff options
context:
space:
mode:
Diffstat (limited to 'modules')
-rw-r--r--modules/base/conf.go37
-rw-r--r--modules/base/markdown.go60
-rw-r--r--modules/base/template.go106
-rw-r--r--modules/base/tool.go146
-rw-r--r--modules/log/log.go2
5 files changed, 214 insertions, 137 deletions
diff --git a/modules/base/conf.go b/modules/base/conf.go
index 3ebc4ede..0a618ab1 100644
--- a/modules/base/conf.go
+++ b/modules/base/conf.go
@@ -14,6 +14,7 @@ import (
"github.com/Unknwon/com"
"github.com/Unknwon/goconfig"
+ qlog "github.com/qiniu/log"
"github.com/gogits/cache"
"github.com/gogits/session"
@@ -105,16 +106,14 @@ func newLogService() {
LogMode = Cfg.MustValue("log", "MODE", "console")
modeSec := "log." + LogMode
if _, err := Cfg.GetSection(modeSec); err != nil {
- fmt.Printf("Unknown log mode: %s\n", LogMode)
- os.Exit(2)
+ qlog.Fatalf("Unknown log mode: %s\n", LogMode)
}
// Log level.
levelName := Cfg.MustValue("log."+LogMode, "LEVEL", "Trace")
level, ok := logLevels[levelName]
if !ok {
- fmt.Printf("Unknown log level: %s\n", levelName)
- os.Exit(2)
+ qlog.Fatalf("Unknown log level: %s\n", levelName)
}
// Generate log configuration.
@@ -151,6 +150,7 @@ func newLogService() {
Cfg.MustValue(modeSec, "CONN"))
}
+ log.Info("%s %s", AppName, AppVer)
log.NewLogger(Cfg.MustInt64("log", "BUFFER_LEN", 10000), LogMode, LogConfig)
log.Info("Log Mode: %s(%s)", strings.Title(LogMode), levelName)
}
@@ -164,16 +164,14 @@ func newCacheService() {
case "redis", "memcache":
CacheConfig = fmt.Sprintf(`{"conn":"%s"}`, Cfg.MustValue("cache", "HOST"))
default:
- fmt.Printf("Unknown cache adapter: %s\n", CacheAdapter)
- os.Exit(2)
+ qlog.Fatalf("Unknown cache adapter: %s\n", CacheAdapter)
}
var err error
Cache, err = cache.NewCache(CacheAdapter, CacheConfig)
if err != nil {
- fmt.Printf("Init cache system failed, adapter: %s, config: %s, %v\n",
+ qlog.Fatalf("Init cache system failed, adapter: %s, config: %s, %v\n",
CacheAdapter, CacheConfig, err)
- os.Exit(2)
}
log.Info("Cache Service Enabled")
@@ -199,9 +197,8 @@ func newSessionService() {
var err error
SessionManager, err = session.NewManager(SessionProvider, *SessionConfig)
if err != nil {
- fmt.Printf("Init session system failed, provider: %s, %v\n",
+ qlog.Fatalf("Init session system failed, provider: %s, %v\n",
SessionProvider, err)
- os.Exit(2)
}
log.Info("Session Service Enabled")
@@ -246,23 +243,20 @@ func NewConfigContext() {
//var err error
workDir, err := ExecDir()
if err != nil {
- fmt.Printf("Fail to get work directory: %s\n", err)
- os.Exit(2)
+ qlog.Fatalf("Fail to get work directory: %s\n", err)
}
cfgPath := filepath.Join(workDir, "conf/app.ini")
Cfg, err = goconfig.LoadConfigFile(cfgPath)
if err != nil {
- fmt.Printf("Cannot load config file(%s): %v\n", cfgPath, err)
- os.Exit(2)
+ qlog.Fatalf("Cannot load config file(%s): %v\n", cfgPath, err)
}
Cfg.BlockMode = false
cfgPath = filepath.Join(workDir, "custom/conf/app.ini")
if com.IsFile(cfgPath) {
if err = Cfg.AppendFiles(cfgPath); err != nil {
- fmt.Printf("Cannot load config file(%s): %v\n", cfgPath, err)
- os.Exit(2)
+ qlog.Fatalf("Cannot load config file(%s): %v\n", cfgPath, err)
}
}
@@ -281,8 +275,7 @@ func NewConfigContext() {
}
// Does not check run user when the install lock is off.
if InstallLock && RunUser != curUser {
- fmt.Printf("Expect user(%s) but current user is: %s\n", RunUser, curUser)
- os.Exit(2)
+ qlog.Fatalf("Expect user(%s) but current user is: %s\n", RunUser, curUser)
}
LogInRememberDays = Cfg.MustInt("security", "LOGIN_REMEMBER_DAYS")
@@ -294,13 +287,11 @@ func NewConfigContext() {
// Determine and create root git reposiroty path.
homeDir, err := com.HomeDir()
if err != nil {
- fmt.Printf("Fail to get home directory): %v\n", err)
- os.Exit(2)
+ qlog.Fatalf("Fail to get home directory): %v\n", err)
}
- RepoRootPath = Cfg.MustValue("repository", "ROOT", filepath.Join(homeDir, "git/gogs-repositories"))
+ RepoRootPath = Cfg.MustValue("repository", "ROOT", filepath.Join(homeDir, "gogs-repositories"))
if err = os.MkdirAll(RepoRootPath, os.ModePerm); err != nil {
- fmt.Printf("Fail to create RepoRootPath(%s): %v\n", RepoRootPath, err)
- os.Exit(2)
+ qlog.Fatalf("Fail to create RepoRootPath(%s): %v\n", RepoRootPath, err)
}
}
diff --git a/modules/base/markdown.go b/modules/base/markdown.go
index 962e1ae1..f0992d04 100644
--- a/modules/base/markdown.go
+++ b/modules/base/markdown.go
@@ -6,9 +6,11 @@ package base
import (
"bytes"
+ "fmt"
"net/http"
"path"
"path/filepath"
+ "regexp"
"strings"
"github.com/gogits/gfm"
@@ -87,7 +89,53 @@ func (options *CustomRender) Link(out *bytes.Buffer, link []byte, title []byte,
options.Renderer.Link(out, link, title, content)
}
+var (
+ mentionPattern = regexp.MustCompile(`@[0-9a-zA-Z_]{1,}`)
+ commitPattern = regexp.MustCompile(`(\s|^)https?.*commit/[0-9a-zA-Z]+(#+[0-9a-zA-Z-]*)?`)
+ issueFullPattern = regexp.MustCompile(`(\s|^)https?.*issues/[0-9]+(#+[0-9a-zA-Z-]*)?`)
+ issueIndexPattern = regexp.MustCompile(`(\s|^)#[0-9]+`)
+)
+
+func RenderSpecialLink(rawBytes []byte, urlPrefix string) []byte {
+ ms := mentionPattern.FindAll(rawBytes, -1)
+ for _, m := range ms {
+ rawBytes = bytes.Replace(rawBytes, m,
+ []byte(fmt.Sprintf(`<a href="/user/%s">%s</a>`, m[1:], m)), -1)
+ }
+ ms = commitPattern.FindAll(rawBytes, -1)
+ for _, m := range ms {
+ m = bytes.TrimPrefix(m, []byte(" "))
+ i := strings.Index(string(m), "commit/")
+ j := strings.Index(string(m), "#")
+ if j == -1 {
+ j = len(m)
+ }
+ rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(
+ ` <code><a href="%s">%s</a></code>`, m, ShortSha(string(m[i+7:j])))), -1)
+ }
+ ms = issueFullPattern.FindAll(rawBytes, -1)
+ for _, m := range ms {
+ m = bytes.TrimPrefix(m, []byte(" "))
+ i := strings.Index(string(m), "issues/")
+ j := strings.Index(string(m), "#")
+ if j == -1 {
+ j = len(m)
+ }
+ rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(
+ ` <a href="%s">#%s</a>`, m, ShortSha(string(m[i+7:j])))), -1)
+ }
+ ms = issueIndexPattern.FindAll(rawBytes, -1)
+ for _, m := range ms {
+ m = bytes.TrimPrefix(m, []byte(" "))
+ rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(
+ ` <a href="%s/issues/%s">%s</a>`, urlPrefix, m[1:], m)), -1)
+ }
+ return rawBytes
+}
+
func RenderMarkdown(rawBytes []byte, urlPrefix string) []byte {
+ body := RenderSpecialLink(rawBytes, urlPrefix)
+ fmt.Println(string(body))
htmlFlags := 0
// htmlFlags |= gfm.HTML_USE_XHTML
// htmlFlags |= gfm.HTML_USE_SMARTYPANTS
@@ -99,10 +147,10 @@ func RenderMarkdown(rawBytes []byte, urlPrefix string) []byte {
htmlFlags |= gfm.HTML_GITHUB_BLOCKCODE
htmlFlags |= gfm.HTML_OMIT_CONTENTS
// htmlFlags |= gfm.HTML_COMPLETE_PAGE
- renderer := &CustomRender{
- Renderer: gfm.HtmlRenderer(htmlFlags, "", ""),
- urlPrefix: urlPrefix,
- }
+ // renderer := &CustomRender{
+ // Renderer: gfm.HtmlRenderer(htmlFlags, "", ""),
+ // urlPrefix: urlPrefix,
+ // }
// set up the parser
extensions := 0
@@ -115,7 +163,7 @@ func RenderMarkdown(rawBytes []byte, urlPrefix string) []byte {
extensions |= gfm.EXTENSION_SPACE_HEADERS
extensions |= gfm.EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK
- body := gfm.Markdown(rawBytes, renderer, extensions)
-
+ // body = gfm.Markdown(body, renderer, extensions)
+ // fmt.Println(string(body))
return body
}
diff --git a/modules/base/template.go b/modules/base/template.go
index 56b77a5d..6cd8ade6 100644
--- a/modules/base/template.go
+++ b/modules/base/template.go
@@ -5,7 +5,9 @@
package base
import (
+ "bytes"
"container/list"
+ "encoding/json"
"fmt"
"html/template"
"strings"
@@ -85,3 +87,107 @@ var TemplateFuncs template.FuncMap = map[string]interface{}{
"DiffLineTypeToStr": DiffLineTypeToStr,
"ShortSha": ShortSha,
}
+
+type Actioner interface {
+ GetOpType() int
+ GetActUserName() string
+ GetActEmail() string
+ GetRepoName() string
+ GetBranch() string
+ GetContent() string
+}
+
+// ActionIcon accepts a int that represents action operation type
+// and returns a icon class name.
+func ActionIcon(opType int) string {
+ switch opType {
+ case 1: // Create repository.
+ return "plus-circle"
+ case 5: // Commit repository.
+ return "arrow-circle-o-right"
+ case 6: // Create issue.
+ return "exclamation-circle"
+ case 8: // Transfer repository.
+ return "share"
+ default:
+ return "invalid type"
+ }
+}
+
+const (
+ TPL_CREATE_REPO = `<a href="/user/%s">%s</a> created repository <a href="/%s">%s</a>`
+ TPL_COMMIT_REPO = `<a href="/user/%s">%s</a> pushed to <a href="/%s/src/%s">%s</a> at <a href="/%s">%s</a>%s`
+ TPL_COMMIT_REPO_LI = `<div><img src="%s?s=16" alt="user-avatar"/> <a href="/%s/commit/%s">%s</a> %s</div>`
+ TPL_CREATE_ISSUE = `<a href="/user/%s">%s</a> opened issue <a href="/%s/issues/%s">%s#%s</a>
+<div><img src="%s?s=16" alt="user-avatar"/> %s</div>`
+ TPL_TRANSFER_REPO = `<a href="/user/%s">%s</a> transfered repository <code>%s</code> to <a href="/%s">%s</a>`
+)
+
+type PushCommit struct {
+ Sha1 string
+ Message string
+ AuthorEmail string
+ AuthorName string
+}
+
+type PushCommits struct {
+ Len int
+ Commits []*PushCommit
+}
+
+// ActionDesc accepts int that represents action operation type
+// and returns the description.
+func ActionDesc(act Actioner) string {
+ actUserName := act.GetActUserName()
+ email := act.GetActEmail()
+ repoName := act.GetRepoName()
+ repoLink := actUserName + "/" + repoName
+ branch := act.GetBranch()
+ content := act.GetContent()
+ switch act.GetOpType() {
+ case 1: // Create repository.
+ return fmt.Sprintf(TPL_CREATE_REPO, actUserName, actUserName, repoLink, repoName)
+ case 5: // Commit repository.
+ var push *PushCommits
+ if err := json.Unmarshal([]byte(content), &push); err != nil {
+ return err.Error()
+ }
+ buf := bytes.NewBuffer([]byte("\n"))
+ for _, commit := range push.Commits {
+ buf.WriteString(fmt.Sprintf(TPL_COMMIT_REPO_LI, AvatarLink(commit.AuthorEmail), repoLink, commit.Sha1, commit.Sha1[:7], commit.Message) + "\n")
+ }
+ if push.Len > 3 {
+ buf.WriteString(fmt.Sprintf(`<div><a href="/%s/%s/commits/%s">%d other commits >></a></div>`, actUserName, repoName, branch, push.Len))
+ }
+ return fmt.Sprintf(TPL_COMMIT_REPO, actUserName, actUserName, repoLink, branch, branch, repoLink, repoLink,
+ buf.String())
+ case 6: // Create issue.
+ infos := strings.SplitN(content, "|", 2)
+ return fmt.Sprintf(TPL_CREATE_ISSUE, actUserName, actUserName, repoLink, infos[0], repoLink, infos[0],
+ AvatarLink(email), infos[1])
+ case 8: // Transfer repository.
+ newRepoLink := content + "/" + repoName
+ return fmt.Sprintf(TPL_TRANSFER_REPO, actUserName, actUserName, repoLink, newRepoLink, newRepoLink)
+ default:
+ return "invalid type"
+ }
+}
+
+func DiffTypeToStr(diffType int) string {
+ diffTypes := map[int]string{
+ 1: "add", 2: "modify", 3: "del",
+ }
+ return diffTypes[diffType]
+}
+
+func DiffLineTypeToStr(diffType int) string {
+ switch diffType {
+ case 2:
+ return "add"
+ case 3:
+ return "del"
+ case 4:
+ return "tag"
+ }
+ return "same"
+}
diff --git a/modules/base/tool.go b/modules/base/tool.go
index 3946c4b5..0f06b3e0 100644
--- a/modules/base/tool.go
+++ b/modules/base/tool.go
@@ -5,13 +5,13 @@
package base
import (
- "bytes"
+ "crypto/hmac"
"crypto/md5"
"crypto/rand"
"crypto/sha1"
"encoding/hex"
- "encoding/json"
"fmt"
+ "hash"
"math"
"strconv"
"strings"
@@ -40,6 +40,44 @@ func GetRandomString(n int, alphabets ...byte) string {
return string(bytes)
}
+// http://code.google.com/p/go/source/browse/pbkdf2/pbkdf2.go?repo=crypto
+func PBKDF2(password, salt []byte, iter, keyLen int, h func() hash.Hash) []byte {
+ prf := hmac.New(h, password)
+ hashLen := prf.Size()
+ numBlocks := (keyLen + hashLen - 1) / hashLen
+
+ var buf [4]byte
+ dk := make([]byte, 0, numBlocks*hashLen)
+ U := make([]byte, hashLen)
+ for block := 1; block <= numBlocks; block++ {
+ // N.B.: || means concatenation, ^ means XOR
+ // for each block T_i = U_1 ^ U_2 ^ ... ^ U_iter
+ // U_1 = PRF(password, salt || uint(i))
+ prf.Reset()
+ prf.Write(salt)
+ buf[0] = byte(block >> 24)
+ buf[1] = byte(block >> 16)
+ buf[2] = byte(block >> 8)
+ buf[3] = byte(block)
+ prf.Write(buf[:4])
+ dk = prf.Sum(dk)
+ T := dk[len(dk)-hashLen:]
+ copy(U, T)
+
+ // U_n = PRF(password, U_(n-1))
+ for n := 2; n <= iter; n++ {
+ prf.Reset()
+ prf.Write(U)
+ U = U[:0]
+ U = prf.Sum(U)
+ for x := range U {
+ T[x] ^= U[x]
+ }
+ }
+ }
+ return dk[:keyLen]
+}
+
// verify time limit code
func VerifyTimeLimitCode(data string, minutes int, code string) bool {
if len(code) <= 18 {
@@ -474,107 +512,3 @@ func (a argInt) Get(i int, args ...int) (r int) {
}
return
}
-
-type Actioner interface {
- GetOpType() int
- GetActUserName() string
- GetActEmail() string
- GetRepoName() string
- GetBranch() string
- GetContent() string
-}
-
-// ActionIcon accepts a int that represents action operation type
-// and returns a icon class name.
-func ActionIcon(opType int) string {
- switch opType {
- case 1: // Create repository.
- return "plus-circle"
- case 5: // Commit repository.
- return "arrow-circle-o-right"
- case 6: // Create issue.
- return "exclamation-circle"
- case 8: // Transfer repository.
- return "share"
- default:
- return "invalid type"
- }
-}
-
-const (
- TPL_CREATE_REPO = `<a href="/user/%s">%s</a> created repository <a href="/%s">%s</a>`
- TPL_COMMIT_REPO = `<a href="/user/%s">%s</a> pushed to <a href="/%s/src/%s">%s</a> at <a href="/%s">%s</a>%s`
- TPL_COMMIT_REPO_LI = `<div><img src="%s?s=16" alt="user-avatar"/> <a href="/%s/commit/%s">%s</a> %s</div>`
- TPL_CREATE_ISSUE = `<a href="/user/%s">%s</a> opened issue <a href="/%s/issues/%s">%s#%s</a>
-<div><img src="%s?s=16" alt="user-avatar"/> %s</div>`
- TPL_TRANSFER_REPO = `<a href="/user/%s">%s</a> transfered repository <code>%s</code> to <a href="/%s">%s</a>`
-)
-
-type PushCommit struct {
- Sha1 string
- Message string
- AuthorEmail string
- AuthorName string
-}
-
-type PushCommits struct {
- Len int
- Commits []*PushCommit
-}
-
-// ActionDesc accepts int that represents action operation type
-// and returns the description.
-func ActionDesc(act Actioner) string {
- actUserName := act.GetActUserName()
- email := act.GetActEmail()
- repoName := act.GetRepoName()
- repoLink := actUserName + "/" + repoName
- branch := act.GetBranch()
- content := act.GetContent()
- switch act.GetOpType() {
- case 1: // Create repository.
- return fmt.Sprintf(TPL_CREATE_REPO, actUserName, actUserName, repoLink, repoName)
- case 5: // Commit repository.
- var push *PushCommits
- if err := json.Unmarshal([]byte(content), &push); err != nil {
- return err.Error()
- }
- buf := bytes.NewBuffer([]byte("\n"))
- for _, commit := range push.Commits {
- buf.WriteString(fmt.Sprintf(TPL_COMMIT_REPO_LI, AvatarLink(commit.AuthorEmail), repoLink, commit.Sha1, commit.Sha1[:7], commit.Message) + "\n")
- }
- if push.Len > 3 {
- buf.WriteString(fmt.Sprintf(`<div><a href="/%s/%s/commits/%s">%d other commits >></a></div>`, actUserName, repoName, branch, push.Len))
- }
- return fmt.Sprintf(TPL_COMMIT_REPO, actUserName, actUserName, repoLink, branch, branch, repoLink, repoLink,
- buf.String())
- case 6: // Create issue.
- infos := strings.SplitN(content, "|", 2)
- return fmt.Sprintf(TPL_CREATE_ISSUE, actUserName, actUserName, repoLink, infos[0], repoLink, infos[0],
- AvatarLink(email), infos[1])
- case 8: // Transfer repository.
- newRepoLink := content + "/" + repoName
- return fmt.Sprintf(TPL_TRANSFER_REPO, actUserName, actUserName, repoLink, newRepoLink, newRepoLink)
- default:
- return "invalid type"
- }
-}
-
-func DiffTypeToStr(diffType int) string {
- diffTypes := map[int]string{
- 1: "add", 2: "modify", 3: "del",
- }
- return diffTypes[diffType]
-}
-
-func DiffLineTypeToStr(diffType int) string {
- switch diffType {
- case 2:
- return "add"
- case 3:
- return "del"
- case 4:
- return "tag"
- }
- return "same"
-}
diff --git a/modules/log/log.go b/modules/log/log.go
index 65150237..f21897b9 100644
--- a/modules/log/log.go
+++ b/modules/log/log.go
@@ -21,8 +21,6 @@ func init() {
func NewLogger(bufLen int64, mode, config string) {
Mode, Config = mode, config
logger = logs.NewLogger(bufLen)
- logger.EnableFuncCallDepth(true)
- logger.SetLogFuncCallDepth(4)
logger.SetLogger(mode, config)
}