From 2846ff7d31fc93659a2e90fe869ff51c885decfa Mon Sep 17 00:00:00 2001 From: Unknown Date: Sun, 6 Apr 2014 13:00:20 -0400 Subject: Fix bug related to log --- modules/base/conf.go | 36 ++++++++++++++---------------------- 1 file changed, 14 insertions(+), 22 deletions(-) (limited to 'modules/base') diff --git a/modules/base/conf.go b/modules/base/conf.go index 3ebc4ede..4a6eec70 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. @@ -164,16 +163,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 +196,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 +242,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 +274,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,14 +286,14 @@ 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")) 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) } + + log.Info("%s %s", AppName, AppVer) } func NewServices() { -- cgit v1.2.3 From 6a16866f4e0908e62c5e5b30e3dc0ef8e4cb0819 Mon Sep 17 00:00:00 2001 From: Unknown Date: Sun, 6 Apr 2014 13:41:58 -0400 Subject: Fix bug related to log --- conf/app.ini | 2 +- modules/base/conf.go | 2 +- serve.go | 3 ++- update.go | 3 ++- 4 files changed, 6 insertions(+), 4 deletions(-) (limited to 'modules/base') diff --git a/conf/app.ini b/conf/app.ini index f88c750e..43033eaa 100644 --- a/conf/app.ini +++ b/conf/app.ini @@ -14,7 +14,7 @@ LICENSES = Apache v2 License|GPL v2|MIT License|Affero GPL|Artistic License 2.0| [server] PROTOCOL = http DOMAIN = localhost -ROOT_URL = %(PROTOCOL)://%(DOMAIN)s:%(HTTP_PORT)s/ +ROOT_URL = %(PROTOCOL)s://%(DOMAIN)s:%(HTTP_PORT)s/ HTTP_ADDR = HTTP_PORT = 3000 CERT_FILE = cert.pem diff --git a/modules/base/conf.go b/modules/base/conf.go index 4a6eec70..4285b523 100644 --- a/modules/base/conf.go +++ b/modules/base/conf.go @@ -288,7 +288,7 @@ func NewConfigContext() { if err != nil { 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 { qlog.Fatalf("Fail to create RepoRootPath(%s): %v\n", RepoRootPath, err) } diff --git a/serve.go b/serve.go index e7649476..7e00db47 100644 --- a/serve.go +++ b/serve.go @@ -46,7 +46,8 @@ gogs serv provide access auth for repositories`, func newLogger(execDir string) { logPath := execDir + "/log/serv.log" os.MkdirAll(path.Dir(logPath), os.ModePerm) - f, err := os.Open(logPath) + + f, err := os.OpenFile(logPath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, os.ModePerm) if err != nil { qlog.Fatal(err) } diff --git a/update.go b/update.go index aae2e710..79ce8f52 100644 --- a/update.go +++ b/update.go @@ -32,7 +32,8 @@ gogs serv provide access auth for repositories`, func newUpdateLogger(execDir string) { logPath := execDir + "/log/update.log" os.MkdirAll(path.Dir(logPath), os.ModePerm) - f, err := os.Open(logPath) + + f, err := os.OpenFile(logPath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, os.ModePerm) if err != nil { qlog.Fatal(err) } -- cgit v1.2.3 From db1fe3483ed2c8c0962ee4395073e0b190310602 Mon Sep 17 00:00:00 2001 From: Unknown Date: Sun, 6 Apr 2014 13:54:48 -0400 Subject: Fix bug related to log --- modules/base/conf.go | 3 +-- update.go | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) (limited to 'modules/base') diff --git a/modules/base/conf.go b/modules/base/conf.go index 4285b523..0a618ab1 100644 --- a/modules/base/conf.go +++ b/modules/base/conf.go @@ -150,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) } @@ -292,8 +293,6 @@ func NewConfigContext() { if err = os.MkdirAll(RepoRootPath, os.ModePerm); err != nil { qlog.Fatalf("Fail to create RepoRootPath(%s): %v\n", RepoRootPath, err) } - - log.Info("%s %s", AppName, AppVer) } func NewServices() { diff --git a/update.go b/update.go index 79ce8f52..c9cbb35b 100644 --- a/update.go +++ b/update.go @@ -45,7 +45,7 @@ func newUpdateLogger(execDir string) { // for command: ./gogs update func runUpdate(c *cli.Context) { execDir, _ := base.ExecDir() - newLogger(execDir) + newUpdateLogger(execDir) base.NewConfigContext() models.LoadModelsConfig() -- cgit v1.2.3 From e7c8a3cb8d26da68b09f799585c03970cd243be1 Mon Sep 17 00:00:00 2001 From: Unknown Date: Sun, 6 Apr 2014 16:10:57 -0400 Subject: Add salt for every single user --- .gopmfile | 1 - README.md | 4 ++-- README_ZH.md | 2 +- gogs.go | 2 +- models/user.go | 31 ++++++++++++++++--------------- modules/base/tool.go | 40 ++++++++++++++++++++++++++++++++++++++++ routers/user/setting.go | 7 ++----- routers/user/user.go | 7 ++----- 8 files changed, 64 insertions(+), 30 deletions(-) (limited to 'modules/base') diff --git a/.gopmfile b/.gopmfile index 9bdca49f..c9fad8a0 100644 --- a/.gopmfile +++ b/.gopmfile @@ -7,7 +7,6 @@ github.com/go-martini/martini = github.com/Unknwon/com = github.com/Unknwon/cae = github.com/Unknwon/goconfig = -github.com/dchest/scrypt = github.com/nfnt/resize = github.com/lunny/xorm = github.com/go-sql-driver/mysql = diff --git a/README.md b/README.md index ede1894a..fe15328b 100644 --- a/README.md +++ b/README.md @@ -5,9 +5,9 @@ Gogs(Go Git Service) is a Self Hosted Git Service in the Go Programming Language ![Demo](http://gowalker.org/public/gogs_demo.gif) -##### Current version: 0.2.1 Alpha +##### Current version: 0.2.2 Alpha -#### Due to testing purpose, data of [try.gogits.org](http://try.gogits.org) has been reset in March 29, 2014 and will reset multiple times after. Please do NOT put your important data on the site. +#### Due to testing purpose, data of [try.gogits.org](http://try.gogits.org) has been reset in April 6, 2014 and will reset multiple times after. Please do NOT put your important data on the site. #### Other language version diff --git a/README_ZH.md b/README_ZH.md index 9b5e4641..015ee0af 100644 --- a/README_ZH.md +++ b/README_ZH.md @@ -5,7 +5,7 @@ Gogs(Go Git Service) 是一个由 Go 语言编写的自助 Git 托管服务。 ![Demo](http://gowalker.org/public/gogs_demo.gif) -##### 当前版本:0.2.1 Alpha +##### 当前版本:0.2.2 Alpha ## 开发目的 diff --git a/gogs.go b/gogs.go index 0e48ff7b..e7197482 100644 --- a/gogs.go +++ b/gogs.go @@ -19,7 +19,7 @@ import ( // Test that go1.2 tag above is included in builds. main.go refers to this definition. const go12tag = true -const APP_VER = "0.2.1.0406 Alpha" +const APP_VER = "0.2.2.0406 Alpha" func init() { base.AppVer = APP_VER diff --git a/models/user.go b/models/user.go index 2196eae8..a5a6de09 100644 --- a/models/user.go +++ b/models/user.go @@ -5,6 +5,7 @@ package models import ( + "crypto/sha256" "encoding/hex" "errors" "fmt" @@ -13,8 +14,6 @@ import ( "strings" "time" - "github.com/dchest/scrypt" - "github.com/gogits/git" "github.com/gogits/gogs/modules/base" @@ -62,6 +61,7 @@ type User struct { IsActive bool IsAdmin bool Rands string `xorm:"VARCHAR(10)"` + Salt string `xorm:"VARCHAR(10)"` Created time.Time `xorm:"created"` Updated time.Time `xorm:"updated"` } @@ -89,10 +89,9 @@ func (user *User) NewGitSig() *git.Signature { } // EncodePasswd encodes password to safe format. -func (user *User) EncodePasswd() error { - newPasswd, err := scrypt.Key([]byte(user.Passwd), []byte(base.SecretKey), 16384, 8, 1, 64) +func (user *User) EncodePasswd() { + newPasswd := base.PBKDF2([]byte(user.Passwd), []byte(user.Salt), 10000, 50, sha256.New) user.Passwd = fmt.Sprintf("%x", newPasswd) - return err } // Member represents user is member of organization. @@ -148,9 +147,9 @@ func RegisterUser(user *User) (*User, error) { user.Avatar = base.EncodeMd5(user.Email) user.AvatarEmail = user.Email user.Rands = GetUserSalt() - if err = user.EncodePasswd(); err != nil { - return nil, err - } else if _, err = orm.Insert(user); err != nil { + user.Salt = GetUserSalt() + user.EncodePasswd() + if _, err = orm.Insert(user); err != nil { 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 { @@ -384,18 +383,20 @@ func GetUserByEmail(email string) (*User, error) { // LoginUserPlain validates user by raw user name and password. func LoginUserPlain(name, passwd string) (*User, error) { - user := User{LowerName: strings.ToLower(name), Passwd: passwd} - if err := user.EncodePasswd(); err != nil { - return nil, err - } - + user := User{LowerName: strings.ToLower(name)} has, err := orm.Get(&user) if err != nil { return nil, err } else if !has { - err = ErrUserNotExist + return nil, ErrUserNotExist + } + + newUser := &User{Passwd: passwd, Salt: user.Salt} + newUser.EncodePasswd() + if user.Passwd != newUser.Passwd { + return nil, ErrUserNotExist } - return &user, err + return &user, nil } // Follow is connection request for receiving user notifycation. diff --git a/modules/base/tool.go b/modules/base/tool.go index 3946c4b5..f7d1bc2c 100644 --- a/modules/base/tool.go +++ b/modules/base/tool.go @@ -6,12 +6,14 @@ package base import ( "bytes" + "crypto/hmac" "crypto/md5" "crypto/rand" "crypto/sha1" "encoding/hex" "encoding/json" "fmt" + "hash" "math" "strconv" "strings" @@ -40,6 +42,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 { diff --git a/routers/user/setting.go b/routers/user/setting.go index 4b6d88a3..ea779e85 100644 --- a/routers/user/setting.go +++ b/routers/user/setting.go @@ -73,11 +73,7 @@ func SettingPassword(ctx *middleware.Context, form auth.UpdatePasswdForm) { user := ctx.User newUser := &models.User{Passwd: form.NewPasswd} - if err := newUser.EncodePasswd(); err != nil { - ctx.Handle(200, "setting.SettingPassword", err) - return - } - + newUser.EncodePasswd() if user.Passwd != newUser.Passwd { ctx.Data["HasError"] = true ctx.Data["ErrorMsg"] = "Old password is not correct" @@ -85,6 +81,7 @@ func SettingPassword(ctx *middleware.Context, form auth.UpdatePasswdForm) { ctx.Data["HasError"] = true ctx.Data["ErrorMsg"] = "New password and re-type password are not same" } else { + newUser.Salt = models.GetUserSalt() user.Passwd = newUser.Passwd if err := models.UpdateUser(user); err != nil { ctx.Handle(200, "setting.SettingPassword", err) diff --git a/routers/user/user.go b/routers/user/user.go index 872ed0d6..12f2bd8c 100644 --- a/routers/user/user.go +++ b/routers/user/user.go @@ -477,12 +477,9 @@ func ResetPasswd(ctx *middleware.Context) { } u.Passwd = passwd - if err := u.EncodePasswd(); err != nil { - ctx.Handle(404, "user.ResetPasswd(EncodePasswd)", err) - return - } - u.Rands = models.GetUserSalt() + u.Salt = models.GetUserSalt() + u.EncodePasswd() if err := models.UpdateUser(u); err != nil { ctx.Handle(404, "user.ResetPasswd(UpdateUser)", err) return -- cgit v1.2.3 From e2fe2209057b90e6c78a84b7c66c3395cf100e30 Mon Sep 17 00:00:00 2001 From: Unknown Date: Mon, 7 Apr 2014 00:47:19 -0400 Subject: Work on comment --- modules/base/markdown.go | 27 +++++++++++- modules/base/template.go | 106 +++++++++++++++++++++++++++++++++++++++++++++++ modules/base/tool.go | 106 ----------------------------------------------- 3 files changed, 131 insertions(+), 108 deletions(-) (limited to 'modules/base') diff --git a/modules/base/markdown.go b/modules/base/markdown.go index 962e1ae1..828f87de 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,28 @@ 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(`[^>]http[s]{0,}.*commit/[0-9a-zA-Z]{1,}`) +) + +func RenderSpecialLink(rawBytes []byte, urlPrefix string) []byte { + ms := mentionPattern.FindAll(rawBytes, -1) + for _, m := range ms { + rawBytes = bytes.Replace(rawBytes, m, + []byte(fmt.Sprintf(`%s`, m[1:], m)), -1) + } + ms = commitPattern.FindAll(rawBytes, -1) + for _, m := range ms { + rawBytes = bytes.Replace(rawBytes, m, + []byte(fmt.Sprintf(`%s`, m, 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 @@ -115,7 +138,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 = `%s created repository %s` + TPL_COMMIT_REPO = `%s pushed to %s at %s%s` + TPL_COMMIT_REPO_LI = `
user-avatar %s %s
` + TPL_CREATE_ISSUE = `%s opened issue %s#%s +
user-avatar %s
` + TPL_TRANSFER_REPO = `%s transfered repository %s to %s` +) + +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(``, 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 f7d1bc2c..0f06b3e0 100644 --- a/modules/base/tool.go +++ b/modules/base/tool.go @@ -5,13 +5,11 @@ package base import ( - "bytes" "crypto/hmac" "crypto/md5" "crypto/rand" "crypto/sha1" "encoding/hex" - "encoding/json" "fmt" "hash" "math" @@ -514,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 = `%s created repository %s` - TPL_COMMIT_REPO = `%s pushed to %s at %s%s` - TPL_COMMIT_REPO_LI = `
user-avatar %s %s
` - TPL_CREATE_ISSUE = `%s opened issue %s#%s -
user-avatar %s
` - TPL_TRANSFER_REPO = `%s transfered repository %s to %s` -) - -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(``, 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" -} -- cgit v1.2.3 From 8c9a0494ecb477a641c07be68a9c0cb8fa661d29 Mon Sep 17 00:00:00 2001 From: Unknown Date: Mon, 7 Apr 2014 01:55:22 -0400 Subject: Add @ # commit link detect on all markdown render --- modules/base/markdown.go | 45 ++++++++++++++++++++++++++++++++--------- routers/api/v1/miscellaneous.go | 2 +- routers/repo/issue.go | 8 ++++---- templates/issue/view.tmpl | 2 +- 4 files changed, 41 insertions(+), 16 deletions(-) (limited to 'modules/base') diff --git a/modules/base/markdown.go b/modules/base/markdown.go index 828f87de..f0992d04 100644 --- a/modules/base/markdown.go +++ b/modules/base/markdown.go @@ -90,8 +90,10 @@ func (options *CustomRender) Link(out *bytes.Buffer, link []byte, title []byte, } var ( - mentionPattern = regexp.MustCompile(`@[0-9a-zA-Z_]{1,}`) - commitPattern = regexp.MustCompile(`[^>]http[s]{0,}.*commit/[0-9a-zA-Z]{1,}`) + 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 { @@ -102,8 +104,31 @@ func RenderSpecialLink(rawBytes []byte, urlPrefix string) []byte { } ms = commitPattern.FindAll(rawBytes, -1) for _, m := range ms { - rawBytes = bytes.Replace(rawBytes, m, - []byte(fmt.Sprintf(`%s`, m, m)), -1) + 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( + ` %s`, 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( + ` #%s`, 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( + ` %s`, urlPrefix, m[1:], m)), -1) } return rawBytes } @@ -122,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 @@ -138,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(body, renderer, extensions) - fmt.Println(string(body)) + // body = gfm.Markdown(body, renderer, extensions) + // fmt.Println(string(body)) return body } diff --git a/routers/api/v1/miscellaneous.go b/routers/api/v1/miscellaneous.go index 0ff1eb04..babdfce9 100644 --- a/routers/api/v1/miscellaneous.go +++ b/routers/api/v1/miscellaneous.go @@ -13,6 +13,6 @@ func Markdown(ctx *middleware.Context) { content := ctx.Query("content") ctx.Render.JSON(200, map[string]interface{}{ "ok": true, - "content": string(base.RenderMarkdown([]byte(content), "")), + "content": string(base.RenderMarkdown([]byte(content), ctx.Query("repoLink"))), }) } diff --git a/routers/repo/issue.go b/routers/repo/issue.go index be925426..38522e0c 100644 --- a/routers/repo/issue.go +++ b/routers/repo/issue.go @@ -147,7 +147,7 @@ func ViewIssue(ctx *middleware.Context, params martini.Params) { return } issue.Poster = u - issue.RenderedContent = string(base.RenderMarkdown([]byte(issue.Content), "")) + issue.RenderedContent = string(base.RenderMarkdown([]byte(issue.Content), ctx.Repo.RepoLink)) // Get comments. comments, err := models.GetIssueComments(issue.Id) @@ -164,7 +164,7 @@ func ViewIssue(ctx *middleware.Context, params martini.Params) { return } comments[i].Poster = u - comments[i].Content = string(base.RenderMarkdown([]byte(comments[i].Content), "")) + comments[i].Content = string(base.RenderMarkdown([]byte(comments[i].Content), ctx.Repo.RepoLink)) } ctx.Data["Title"] = issue.Name @@ -193,7 +193,7 @@ func UpdateIssue(ctx *middleware.Context, params martini.Params, form auth.Creat return } - if ctx.User.Id != issue.PosterId { + if ctx.User.Id != issue.PosterId && !ctx.Repo.IsOwner { ctx.Handle(404, "issue.UpdateIssue", nil) return } @@ -211,7 +211,7 @@ func UpdateIssue(ctx *middleware.Context, params martini.Params, form auth.Creat ctx.JSON(200, map[string]interface{}{ "ok": true, "title": issue.Name, - "content": string(base.RenderMarkdown([]byte(issue.Content), "")), + "content": string(base.RenderMarkdown([]byte(issue.Content), ctx.Repo.RepoLink)), }) } diff --git a/templates/issue/view.tmpl b/templates/issue/view.tmpl index e619451c..16d60d35 100644 --- a/templates/issue/view.tmpl +++ b/templates/issue/view.tmpl @@ -72,7 +72,7 @@
-- cgit v1.2.3