From e41ab839c7dbbdffc60a4e02775f24add9d126d9 Mon Sep 17 00:00:00 2001 From: Unknown Date: Fri, 4 Apr 2014 18:55:17 -0400 Subject: Use session for rolling back --- models/repo.go | 43 ++++++++++++++++++++++++++++++++++++------- 1 file changed, 36 insertions(+), 7 deletions(-) (limited to 'models/repo.go') diff --git a/models/repo.go b/models/repo.go index e8ebce92..acee6f6a 100644 --- a/models/repo.go +++ b/models/repo.go @@ -381,45 +381,62 @@ func TransferOwnership(user *User, newOwner string, repo *Repository) (err error if err = orm.Find(&accesses, &Access{RepoName: user.LowerName + "/" + repo.LowerName}); err != nil { return err } + + sess := orm.NewSession() + defer sess.Close() + if err = sess.Begin(); err != nil { + return err + } + for i := range accesses { accesses[i].RepoName = newUser.LowerName + "/" + repo.LowerName if accesses[i].UserName == user.LowerName { accesses[i].UserName = newUser.LowerName } - if err = UpdateAccess(&accesses[i]); err != nil { + if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil { return err } } // Update repository. repo.OwnerId = newUser.Id - if _, err := orm.Id(repo.Id).Update(repo); err != nil { + if _, err := sess.Id(repo.Id).Update(repo); err != nil { + sess.Rollback() return err } // Update user repository number. rawSql := "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?" - if _, err = orm.Exec(rawSql, newUser.Id); err != nil { + if _, err = sess.Exec(rawSql, newUser.Id); err != nil { + sess.Rollback() return err } rawSql = "UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?" - if _, err = orm.Exec(rawSql, user.Id); err != nil { + if _, err = sess.Exec(rawSql, user.Id); err != nil { + sess.Rollback() return err } // Add watch of new owner to repository. if !IsWatching(newUser.Id, repo.Id) { if err = WatchRepo(newUser.Id, repo.Id, true); err != nil { + sess.Rollback() return err } } if err = TransferRepoAction(user, newUser, repo); err != nil { + sess.Rollback() return err } // Change repository directory name. - return os.Rename(RepoPath(user.Name, repo.Name), RepoPath(newUser.Name, repo.Name)) + if err = os.Rename(RepoPath(user.Name, repo.Name), RepoPath(newUser.Name, repo.Name)); err != nil { + sess.Rollback() + return err + } + + return sess.Commit() } // ChangeRepositoryName changes all corresponding setting from old repository name to new one. @@ -429,15 +446,27 @@ func ChangeRepositoryName(userName, oldRepoName, newRepoName string) (err error) if err = orm.Find(&accesses, &Access{RepoName: strings.ToLower(userName + "/" + oldRepoName)}); err != nil { return err } + + sess := orm.NewSession() + defer sess.Close() + if err = sess.Begin(); err != nil { + return err + } + for i := range accesses { accesses[i].RepoName = userName + "/" + newRepoName - if err = UpdateAccess(&accesses[i]); err != nil { + if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil { return err } } // Change repository directory name. - return os.Rename(RepoPath(userName, oldRepoName), RepoPath(userName, newRepoName)) + if err = os.Rename(RepoPath(userName, oldRepoName), RepoPath(userName, newRepoName)); err != nil { + sess.Rollback() + return err + } + + return sess.Commit() } func UpdateRepository(repo *Repository) error { -- cgit v1.2.3 From 22feddf804c7fbf3418cbbc8e7302da271da4e5a Mon Sep 17 00:00:00 2001 From: Unknown Date: Mon, 7 Apr 2014 14:24:58 -0400 Subject: Fix #66 --- models/repo.go | 14 ++++++++++---- modules/base/markdown.go | 14 +++++++------- 2 files changed, 17 insertions(+), 11 deletions(-) (limited to 'models/repo.go') diff --git a/models/repo.go b/models/repo.go index acee6f6a..bb5c3637 100644 --- a/models/repo.go +++ b/models/repo.go @@ -138,11 +138,8 @@ func CreateRepository(user *User, repoName, desc, repoLang, license string, priv IsPrivate: private, IsBare: repoLang == "" && license == "" && !initReadme, } - repoPath := RepoPath(user.Name, repoName) - if err = initRepository(repoPath, user, repo, initReadme, repoLang, license); err != nil { - return nil, err - } + sess := orm.NewSession() defer sess.Close() sess.Begin() @@ -207,6 +204,10 @@ func CreateRepository(user *User, repoName, desc, repoLang, license string, priv log.Error("repo.CreateRepository(WatchRepo): %v", err) } + if err = initRepository(repoPath, user, repo, initReadme, repoLang, license); err != nil { + return nil, err + } + return repo, nil } @@ -332,6 +333,11 @@ func initRepository(f string, user *User, repo *Repository, initReadme bool, rep return nil } + // for update use + os.Setenv("userName", user.Name) + os.Setenv("userId", base.ToStr(user.Id)) + os.Setenv("repoName", repo.Name) + // Apply changes and commit. return initRepoCommit(tmpDir, user.NewGitSig()) } diff --git a/modules/base/markdown.go b/modules/base/markdown.go index ce1e2f5b..1893ccee 100644 --- a/modules/base/markdown.go +++ b/modules/base/markdown.go @@ -133,8 +133,8 @@ func RenderSpecialLink(rawBytes []byte, urlPrefix string) []byte { } func RenderMarkdown(rawBytes []byte, urlPrefix string) []byte { - body := RenderSpecialLink(rawBytes, urlPrefix) - fmt.Println(string(body)) + // body := RenderSpecialLink(rawBytes, urlPrefix) + // fmt.Println(string(body)) htmlFlags := 0 // htmlFlags |= gfm.HTML_USE_XHTML // htmlFlags |= gfm.HTML_USE_SMARTYPANTS @@ -146,10 +146,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 @@ -162,7 +162,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) + body := gfm.Markdown(rawBytes, renderer, extensions) // fmt.Println(string(body)) return body } -- cgit v1.2.3 From 115a349131242201953a3f5693141679049355c6 Mon Sep 17 00:00:00 2001 From: Unknown Date: Tue, 8 Apr 2014 12:41:33 -0400 Subject: Fix #67 --- README.md | 2 +- README_ZH.md | 2 +- gogs.go | 2 +- models/repo.go | 12 ++++++++---- modules/base/conf.go | 1 + modules/base/template.go | 3 +++ routers/install.go | 1 + serve.go | 5 +---- templates/base/head.tmpl | 16 +++++++++++++--- 9 files changed, 30 insertions(+), 14 deletions(-) (limited to 'models/repo.go') diff --git a/README.md b/README.md index fe15328b..a4e8901c 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ More importantly, Gogs only needs one binary to setup your own project hosting o ## Features - Activity timeline -- SSH/HTTPS(Clone only) protocol support. +- SSH/HTTP(S) protocol support. - Register/delete/rename account. - Create/delete/watch/rename/transfer public repository. - Repository viewer. diff --git a/README_ZH.md b/README_ZH.md index 015ee0af..2f801541 100644 --- a/README_ZH.md +++ b/README_ZH.md @@ -23,7 +23,7 @@ Gogs 完全使用 Go 语言来实现对 Git 数据的操作,实现 **零** 依 ## 功能特性 - 活动时间线 -- SSH/HTTPS(仅限 Clone) 协议支持 +- SSH/HTTP(S) 协议支持 - 注册/删除/重命名用户 - 创建/删除/关注/重命名/转移公开仓库 - 仓库浏览器 diff --git a/gogs.go b/gogs.go index df268980..4616141e 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.2.0407 Alpha" +const APP_VER = "0.2.2.0408 Alpha" func init() { base.AppVer = APP_VER diff --git a/models/repo.go b/models/repo.go index bb5c3637..4f58f407 100644 --- a/models/repo.go +++ b/models/repo.go @@ -261,6 +261,13 @@ func createHookUpdate(hookPath, content string) error { return err } +// SetRepoEnvs sets environment variables for command update. +func SetRepoEnvs(userId int64, userName, repoName string) { + os.Setenv("userId", base.ToStr(userId)) + os.Setenv("userName", userName) + os.Setenv("repoName", repoName) +} + // InitRepository initializes README and .gitignore if needed. func initRepository(f string, user *User, repo *Repository, initReadme bool, repoLang, license string) error { repoPath := RepoPath(user.Name, repo.Name) @@ -333,10 +340,7 @@ func initRepository(f string, user *User, repo *Repository, initReadme bool, rep return nil } - // for update use - os.Setenv("userName", user.Name) - os.Setenv("userId", base.ToStr(user.Id)) - os.Setenv("repoName", repo.Name) + SetRepoEnvs(user.Id, user.Name, repo.Name) // Apply changes and commit. return initRepoCommit(tmpDir, user.NewGitSig()) diff --git a/modules/base/conf.go b/modules/base/conf.go index 69df49dc..871595e4 100644 --- a/modules/base/conf.go +++ b/modules/base/conf.go @@ -43,6 +43,7 @@ var ( AppName string AppLogo string AppUrl string + IsProdMode bool Domain string SecretKey string RunUser string diff --git a/modules/base/template.go b/modules/base/template.go index 6cd8ade6..5a42107c 100644 --- a/modules/base/template.go +++ b/modules/base/template.go @@ -56,6 +56,9 @@ var TemplateFuncs template.FuncMap = map[string]interface{}{ "AppDomain": func() string { return Domain }, + "IsProdMode": func() bool { + return IsProdMode + }, "LoadTimes": func(startTime time.Time) string { return fmt.Sprint(time.Since(startTime).Nanoseconds()/1e6) + "ms" }, diff --git a/routers/install.go b/routers/install.go index 1c4e6181..b9e8bb29 100644 --- a/routers/install.go +++ b/routers/install.go @@ -27,6 +27,7 @@ func checkRunMode() { switch base.Cfg.MustValue("", "RUN_MODE") { case "prod": martini.Env = martini.Prod + base.IsProdMode = true case "test": martini.Env = martini.Test } diff --git a/serve.go b/serve.go index 7e00db47..3843da61 100644 --- a/serve.go +++ b/serve.go @@ -177,10 +177,7 @@ func runServ(k *cli.Context) { qlog.Fatal("Unknown command") } - // for update use - os.Setenv("userName", user.Name) - os.Setenv("userId", strconv.Itoa(int(user.Id))) - os.Setenv("repoName", repoName) + models.SetRepoEnvs(user.Id, user.Name, repoName) gitcmd := exec.Command(verb, repoPath) gitcmd.Dir = base.RepoRootPath diff --git a/templates/base/head.tmpl b/templates/base/head.tmpl index 7f56ed70..2f88e918 100644 --- a/templates/base/head.tmpl +++ b/templates/base/head.tmpl @@ -11,14 +11,24 @@ + {{if IsProdMode}} + + + + + + {{else}} - - - + {{end}} + + + + + {{if .Title}}{{.Title}} - {{end}}{{AppName}} -- cgit v1.2.3 From 5d4025cb5a629716bf84f4f5bf3baa97af716df4 Mon Sep 17 00:00:00 2001 From: Unknown Date: Wed, 9 Apr 2014 21:42:25 -0400 Subject: Add go get meta support --- README.md | 2 +- README_ZH.md | 2 +- gogs.go | 2 +- models/repo.go | 1 + models/user.go | 11 ++++++++++- modules/base/markdown.go | 4 ++-- routers/repo/repo.go | 1 + routers/user/user.go | 14 ++++++++++++++ templates/base/head.tmpl | 1 + templates/repo/setting.tmpl | 13 +++++++++++++ templates/repo/single_bare.tmpl | 14 ++++++++++++++ templates/repo/toolbar.tmpl | 2 +- templates/user/forgot_passwd.tmpl | 2 ++ 13 files changed, 62 insertions(+), 7 deletions(-) (limited to 'models/repo.go') diff --git a/README.md b/README.md index a4e8901c..619f9a9d 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ 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.2 Alpha +##### Current version: 0.2.3 Alpha #### 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. diff --git a/README_ZH.md b/README_ZH.md index 2f801541..35a0b763 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.2 Alpha +##### 当前版本:0.2.3 Alpha ## 开发目的 diff --git a/gogs.go b/gogs.go index 45be7e87..29710071 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.2.0409 Alpha" +const APP_VER = "0.2.3.0409 Alpha" func init() { base.AppVer = APP_VER diff --git a/models/repo.go b/models/repo.go index 4f58f407..573e0f4e 100644 --- a/models/repo.go +++ b/models/repo.go @@ -79,6 +79,7 @@ type Repository struct { NumOpenIssues int `xorm:"-"` IsPrivate bool IsBare bool + IsGoget bool Created time.Time `xorm:"created"` Updated time.Time `xorm:"updated"` } diff --git a/models/user.go b/models/user.go index 0fcf7243..b2fddd0a 100644 --- a/models/user.go +++ b/models/user.go @@ -289,11 +289,21 @@ func DeleteUser(user *User) error { // TODO: check issues, other repos' commits + // Delete all followers. + if _, err = orm.Delete(&Follow{FollowId: user.Id}); err != nil { + return err + } + // Delete all feeds. if _, err = orm.Delete(&Action{UserId: user.Id}); err != nil { return err } + // Delete all watches. + if _, err = orm.Delete(&Watch{UserId: user.Id}); err != nil { + return err + } + // Delete all accesses. if _, err = orm.Delete(&Access{UserName: user.LowerName}); err != nil { return err @@ -316,7 +326,6 @@ func DeleteUser(user *User) error { } _, err = orm.Delete(user) - // TODO: delete and update follower information. return err } diff --git a/modules/base/markdown.go b/modules/base/markdown.go index e1ff3856..cc180775 100644 --- a/modules/base/markdown.go +++ b/modules/base/markdown.go @@ -133,7 +133,7 @@ func RenderSpecialLink(rawBytes []byte, urlPrefix string) []byte { } func RenderMarkdown(rawBytes []byte, urlPrefix string) []byte { - // body := RenderSpecialLink(rawBytes, urlPrefix) + body := RenderSpecialLink(rawBytes, urlPrefix) // fmt.Println(string(body)) htmlFlags := 0 // htmlFlags |= gfm.HTML_USE_XHTML @@ -162,7 +162,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/routers/repo/repo.go b/routers/repo/repo.go index 32c198f2..aebaa65a 100644 --- a/routers/repo/repo.go +++ b/routers/repo/repo.go @@ -427,6 +427,7 @@ func SettingPost(ctx *middleware.Context) { ctx.Repo.Repository.Description = ctx.Query("desc") ctx.Repo.Repository.Website = ctx.Query("site") + ctx.Repo.Repository.IsGoget = ctx.Query("goget") == "on" if err := models.UpdateRepository(ctx.Repo.Repository); err != nil { ctx.Handle(404, "repo.SettingPost(update)", err) return diff --git a/routers/user/user.go b/routers/user/user.go index f6a39b86..084d0bbd 100644 --- a/routers/user/user.go +++ b/routers/user/user.go @@ -396,6 +396,10 @@ func Activate(ctx *middleware.Context) { } else { ctx.Data["Hours"] = base.Service.ActiveCodeLives / 60 mailer.SendActiveMail(ctx.Render, ctx.User) + + if err := ctx.Cache.Put("MailResendLimit_"+ctx.User.LowerName, ctx.User.LowerName, 180); err != nil { + log.Error("Set cache(MailResendLimit) fail: %v", err) + } } } else { ctx.Data["ServiceNotEnabled"] = true @@ -451,7 +455,17 @@ func ForgotPasswd(ctx *middleware.Context) { return } + if ctx.Cache.IsExist("MailResendLimit_" + u.LowerName) { + ctx.Data["ResendLimited"] = true + ctx.HTML(200, "user/forgot_passwd") + return + } + mailer.SendResetPasswdMail(ctx.Render, u) + if err = ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil { + log.Error("Set cache(MailResendLimit) fail: %v", err) + } + ctx.Data["Email"] = email ctx.Data["Hours"] = base.Service.ActiveCodeLives / 60 ctx.Data["IsResetSent"] = true diff --git a/templates/base/head.tmpl b/templates/base/head.tmpl index 2f88e918..648eb7c4 100644 --- a/templates/base/head.tmpl +++ b/templates/base/head.tmpl @@ -9,6 +9,7 @@ + {{if .Repository.IsGoget}}{{end}} {{if IsProdMode}} diff --git a/templates/repo/setting.tmpl b/templates/repo/setting.tmpl index 85d08c59..1adf0090 100644 --- a/templates/repo/setting.tmpl +++ b/templates/repo/setting.tmpl @@ -43,6 +43,7 @@ +
+ +
+
+
+ +
+
+
+
diff --git a/templates/repo/single_bare.tmpl b/templates/repo/single_bare.tmpl index fc0a3bd9..3f639153 100644 --- a/templates/repo/single_bare.tmpl +++ b/templates/repo/single_bare.tmpl @@ -9,6 +9,20 @@

Quick Guide

+
+ {{.CsrfTokenHtml}} +

Clone from existing repository

+
+ + + + + + + +
+
+

Clone this repository

diff --git a/templates/repo/toolbar.tmpl b/templates/repo/toolbar.tmpl index d8ab2621..9c137e51 100644 --- a/templates/repo/toolbar.tmpl +++ b/templates/repo/toolbar.tmpl @@ -11,7 +11,7 @@
  • {{if .Repository.NumOpenIssues}}{{.Repository.NumOpenIssues}} {{end}}Issues
  • {{if .IsRepoToolbarIssues}}
  • {{if .IsRepoToolbarIssuesList}} - {{else}}{{end}}
  • + {{end}} {{end}}
  • {{if .Repository.NumReleases}}{{.Repository.NumReleases}} {{end}}Releases
  • {{if .IsRepoToolbarReleases}} diff --git a/templates/user/forgot_passwd.tmpl b/templates/user/forgot_passwd.tmpl index ff25406f..a099ff27 100644 --- a/templates/user/forgot_passwd.tmpl +++ b/templates/user/forgot_passwd.tmpl @@ -24,6 +24,8 @@
    {{else if .IsResetDisable}}

    Sorry, mail service is not enabled.

    + {{else if .ResendLimited}} +

    Sorry, you are sending e-mail too frequently, please wait 3 minutes.

    {{end}}
    -- cgit v1.2.3 From 306aa5bffe7868207ed7b773c1aedbf3f0a659ad Mon Sep 17 00:00:00 2001 From: Unknown Date: Thu, 10 Apr 2014 22:03:31 -0400 Subject: Add support default branch --- models/repo.go | 1 + modules/middleware/repo.go | 10 +++++++--- routers/repo/repo.go | 29 +++++++++++++---------------- templates/install.tmpl | 4 ---- templates/repo/diff.tmpl | 8 ++++++++ templates/repo/setting.tmpl | 11 +++++++---- 6 files changed, 36 insertions(+), 27 deletions(-) (limited to 'models/repo.go') diff --git a/models/repo.go b/models/repo.go index 573e0f4e..91dc7102 100644 --- a/models/repo.go +++ b/models/repo.go @@ -80,6 +80,7 @@ type Repository struct { IsPrivate bool IsBare bool IsGoget bool + DefaultBranch string Created time.Time `xorm:"created"` Updated time.Time `xorm:"updated"` } diff --git a/modules/middleware/repo.go b/modules/middleware/repo.go index 2139742c..ae9f04b1 100644 --- a/modules/middleware/repo.go +++ b/modules/middleware/repo.go @@ -76,7 +76,7 @@ func RepoAssignment(redirect bool, args ...bool) martini.Handler { ctx.Redirect("/") return } - ctx.Handle(404, "RepoAssignment", err) + ctx.Handle(500, "RepoAssignment", err) return } repo.NumOpenIssues = repo.NumIssues - repo.NumClosedIssues @@ -86,7 +86,7 @@ func RepoAssignment(redirect bool, args ...bool) martini.Handler { gitRepo, err := git.OpenRepository(models.RepoPath(userName, repoName)) if err != nil { - ctx.Handle(404, "RepoAssignment Invalid repo "+models.RepoPath(userName, repoName), err) + ctx.Handle(500, "RepoAssignment Invalid repo "+models.RepoPath(userName, repoName), err) return } ctx.Repo.GitRepo = gitRepo @@ -138,7 +138,10 @@ func RepoAssignment(redirect bool, args ...bool) martini.Handler { } } else { - branchName = "master" + branchName = ctx.Repo.Repository.DefaultBranch + if len(branchName) == 0 { + branchName = "master" + } goto detect } @@ -157,6 +160,7 @@ func RepoAssignment(redirect bool, args ...bool) martini.Handler { } ctx.Data["BranchName"] = ctx.Repo.BranchName + ctx.Data["Branches"], _ = models.GetBranches(ctx.User.Name, ctx.Repo.Repository.Name) ctx.Data["CommitId"] = ctx.Repo.CommitId ctx.Data["IsRepositoryWatching"] = ctx.Repo.IsWatching } diff --git a/routers/repo/repo.go b/routers/repo/repo.go index b2897d0f..1ae4a374 100644 --- a/routers/repo/repo.go +++ b/routers/repo/repo.go @@ -323,27 +323,29 @@ func SettingPost(ctx *middleware.Context) { switch ctx.Query("action") { case "update": - isNameChanged := false newRepoName := ctx.Query("name") // Check if repository name has been changed. if ctx.Repo.Repository.Name != newRepoName { isExist, err := models.IsRepositoryExist(ctx.Repo.Owner, newRepoName) if err != nil { - ctx.Handle(404, "repo.SettingPost(update: check existence)", err) + ctx.Handle(500, "repo.SettingPost(update: check existence)", err) return } else if isExist { ctx.RenderWithErr("Repository name has been taken in your repositories.", "repo/setting", nil) return } else if err = models.ChangeRepositoryName(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name, newRepoName); err != nil { - ctx.Handle(404, "repo.SettingPost(change repository name)", err) + ctx.Handle(500, "repo.SettingPost(change repository name)", err) return } log.Trace("%s Repository name changed: %s/%s -> %s", ctx.Req.RequestURI, ctx.User.Name, ctx.Repo.Repository.Name, newRepoName) - isNameChanged = true ctx.Repo.Repository.Name = newRepoName } + br := ctx.Query("branch") + if models.IsBranchExist(ctx.User.Name, ctx.Repo.Repository.Name, br) { + ctx.Repo.Repository.DefaultBranch = br + } ctx.Repo.Repository.Description = ctx.Query("desc") ctx.Repo.Repository.Website = ctx.Query("site") ctx.Repo.Repository.IsGoget = ctx.Query("goget") == "on" @@ -351,14 +353,10 @@ func SettingPost(ctx *middleware.Context) { ctx.Handle(404, "repo.SettingPost(update)", err) return } - - ctx.Data["IsSuccess"] = true - if isNameChanged { - ctx.Redirect(fmt.Sprintf("/%s/%s/settings", ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)) - } else { - ctx.HTML(200, "repo/setting") - } log.Trace("%s Repository updated: %s/%s", ctx.Req.RequestURI, ctx.Repo.Owner.Name, ctx.Repo.Repository.Name) + + ctx.Flash.Success("Repository options has been successfully updated.") + ctx.Redirect(fmt.Sprintf("/%s/%s/settings", ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)) case "transfer": if len(ctx.Repo.Repository.Name) == 0 || ctx.Repo.Repository.Name != ctx.Query("repository") { ctx.RenderWithErr("Please make sure you entered repository name is correct.", "repo/setting", nil) @@ -369,19 +367,18 @@ func SettingPost(ctx *middleware.Context) { // Check if new owner exists. isExist, err := models.IsUserExist(newOwner) if err != nil { - ctx.Handle(404, "repo.SettingPost(transfer: check existence)", err) + ctx.Handle(500, "repo.SettingPost(transfer: check existence)", err) return } else if !isExist { ctx.RenderWithErr("Please make sure you entered owner name is correct.", "repo/setting", nil) return } else if err = models.TransferOwnership(ctx.User, newOwner, ctx.Repo.Repository); err != nil { - ctx.Handle(404, "repo.SettingPost(transfer repository)", err) + ctx.Handle(500, "repo.SettingPost(transfer repository)", err) return } log.Trace("%s Repository transfered: %s/%s -> %s", ctx.Req.RequestURI, ctx.User.Name, ctx.Repo.Repository.Name, newOwner) ctx.Redirect("/") - return case "delete": if len(ctx.Repo.Repository.Name) == 0 || ctx.Repo.Repository.Name != ctx.Query("repository") { ctx.RenderWithErr("Please make sure you entered repository name is correct.", "repo/setting", nil) @@ -389,11 +386,11 @@ 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) + ctx.Handle(500, "repo.Delete", err) return } - log.Trace("%s Repository deleted: %s/%s", ctx.Req.RequestURI, ctx.User.LowerName, ctx.Repo.Repository.LowerName) + ctx.Redirect("/") } } diff --git a/templates/install.tmpl b/templates/install.tmpl index 3aa64ccd..c1fd7665 100644 --- a/templates/install.tmpl +++ b/templates/install.tmpl @@ -184,11 +184,7 @@ Enable Register Confirmation
    - - -
    -
    @@ -65,7 +65,7 @@
  • {{.NumForks}}

    - {{.Name}} + {{.Name}}{{if .IsPrivate}} Private{{end}}

    {{.Description}}

    Last updated {{.Updated|TimeSince}}
    diff --git a/templates/user/signin.tmpl b/templates/user/signin.tmpl index 4ea41738..d402c292 100644 --- a/templates/user/signin.tmpl +++ b/templates/user/signin.tmpl @@ -3,15 +3,11 @@
    {{.CsrfTokenHtml}} -

    Log in - -

    + {{if .IsSocialLogin}} +

    Social login: 2nd step associate account

    + {{else}} +

    Log in

    + {{end}} {{template "base/alert" .}}
    @@ -26,8 +22,8 @@
    - -
    + + {{if not .IsSocialLogin}}
    -
    +
    {{end}}
    - Forgot your password? + {{if not .IsSocialLogin}}Forgot your password?{{end}}
    -
    + {{if not .IsSocialLogin}}
    @@ -54,10 +50,7 @@ {{if .OauthEnabled}}

    or

    - - {{if .OauthGitHubEnabled}} - - GitHub - {{end}} + {{if .OauthService.GitHub}}GitHub{{end}} + {{if .OauthService.Google}}Google{{end}} + {{if .OauthService.Tencent}}Twitter{{end}} + {{if .OauthService.Tencent}}QQ{{end}}
    - {{end}} + {{end}}{{end}}
    {{template "base/footer" .}} diff --git a/templates/user/signup.tmpl b/templates/user/signup.tmpl index 6cf48a4d..02951599 100644 --- a/templates/user/signup.tmpl +++ b/templates/user/signup.tmpl @@ -1,15 +1,15 @@ {{template "base/head" .}} {{template "base/navbar" .}} -
    +
    {{.CsrfTokenHtml}} {{if .DisenableRegisteration}} Sorry, registeration has been disenabled, you can only get account from administrator. {{else}} {{if .IsSocialLogin}} -

    Social login: 2nd step complete information

    +

    Social login: 2nd step complete information

    {{else}} -

    Sign Up

    +

    Sign Up

    {{end}} {{template "base/alert" .}}
    -- cgit v1.2.3 From d2b53dd43b3bc9719985033bc92b76abb9515b4d Mon Sep 17 00:00:00 2001 From: Unknown Date: Sun, 13 Apr 2014 21:00:12 -0400 Subject: Add weibo oauth --- README.md | 3 +- README_ZH.md | 3 +- conf/app.ini | 8 ++++++ gogs.go | 2 +- models/action.go | 14 ++++++++-- models/oauth2.go | 6 ++++ models/repo.go | 2 +- modules/base/conf.go | 2 +- modules/base/template.go | 22 ++++++++++++++- modules/middleware/repo.go | 7 +++++ modules/social/social.go | 62 ++++++++++++++++++++++++++++++++++++++++- routers/admin/admin.go | 6 ++++ routers/user/setting.go | 24 +++++++++++++--- templates/admin/config.tmpl | 26 +++++++++++++++-- templates/repo/toolbar.tmpl | 2 +- templates/user/publickey.tmpl | 4 +-- templates/user/setting_nav.tmpl | 1 + templates/user/signin.tmpl | 5 ++-- templates/user/social.tmpl | 17 +++++++++++ web.go | 3 +- 20 files changed, 198 insertions(+), 21 deletions(-) create mode 100644 templates/user/social.tmpl (limited to 'models/repo.go') diff --git a/README.md b/README.md index 34f8b66f..20dc8806 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ 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.8 Alpha +##### Current version: 0.2.9 Alpha ### NOTICES @@ -40,6 +40,7 @@ More importantly, Gogs only needs one binary to setup your own project hosting o - Mail service(register, issue). - Administration panel. - Supports MySQL, PostgreSQL and SQLite3. +- Social account login(GitHub, Google, QQ, Weibo) ## Installation diff --git a/README_ZH.md b/README_ZH.md index beb5a105..97ab07ff 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.8 Alpha +##### 当前版本:0.2.9 Alpha ## 开发目的 @@ -31,6 +31,7 @@ Gogs 完全使用 Go 语言来实现对 Git 数据的操作,实现 **零** 依 - 邮件服务(注册、Issue) - 管理员面板 - 支持 MySQL、PostgreSQL 以及 SQLite3 +- 社交帐号登录(GitHub、Google、QQ、微博) ## 安装部署 diff --git a/conf/app.ini b/conf/app.ini index 4eaf0a33..c7091996 100644 --- a/conf/app.ini +++ b/conf/app.ini @@ -109,6 +109,14 @@ SCOPES = all AUTH_URL = https://api.twitter.com/oauth/authorize TOKEN_URL = https://api.twitter.com/oauth/access_token +[oauth.weibo] +ENABLED = false +CLIENT_ID = +CLIENT_SECRET = +SCOPES = all +AUTH_URL = https://api.weibo.com/oauth2/authorize +TOKEN_URL = https://api.weibo.com/oauth2/access_token + [cache] ; Either "memory", "redis", or "memcache", default is "memory" ADAPTER = memory diff --git a/gogs.go b/gogs.go index 7a7d3ac8..de2bbc77 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.8.0413 Alpha" +const APP_VER = "0.2.9.0413 Alpha" func init() { base.AppVer = APP_VER diff --git a/models/action.go b/models/action.go index a642a82c..3edb884e 100644 --- a/models/action.go +++ b/models/action.go @@ -8,6 +8,8 @@ import ( "encoding/json" "time" + // "github.com/gogits/git" + "github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/log" ) @@ -22,6 +24,7 @@ const ( OP_CREATE_ISSUE OP_PULL_REQUEST OP_TRANSFER_REPO + OP_PUSH_TAG ) // Action represents user operation type and other information to repository., @@ -67,7 +70,14 @@ func (a Action) GetContent() string { // CommitRepoAction adds new action for committing repository. func CommitRepoAction(userId int64, userName, actEmail string, repoId int64, repoName string, refName string, commit *base.PushCommits) error { - log.Trace("action.CommitRepoAction(start): %d/%s", userId, repoName) + // log.Trace("action.CommitRepoAction(start): %d/%s", userId, repoName) + + opType := OP_COMMIT_REPO + // Check it's tag push or branch. + // if git.IsTagExist(RepoPath(userName, repoName), refName) { + // opType = OP_PUSH_TAG + // commit = &base.PushCommits{} + // } bs, err := json.Marshal(commit) if err != nil { @@ -76,7 +86,7 @@ func CommitRepoAction(userId int64, userName, actEmail string, } if err = NotifyWatchers(&Action{ActUserId: userId, ActUserName: userName, ActEmail: actEmail, - OpType: OP_COMMIT_REPO, Content: string(bs), RepoId: repoId, RepoName: repoName, RefName: refName}); err != nil { + OpType: opType, Content: string(bs), RepoId: repoId, RepoName: repoName, RefName: refName}); err != nil { log.Error("action.CommitRepoAction(notify watchers): %d/%s", userId, repoName) return err } diff --git a/models/oauth2.go b/models/oauth2.go index 38d21fda..d1ae4611 100644 --- a/models/oauth2.go +++ b/models/oauth2.go @@ -68,3 +68,9 @@ func GetOauth2ById(id int64) (oa *Oauth2, err error) { } return oa, nil } + +// GetOauthByUserId returns list of oauthes that are releated to given user. +func GetOauthByUserId(uid int64) (oas []*Oauth2, err error) { + err = orm.Find(&oas, Oauth2{Uid: uid}) + return oas, err +} diff --git a/models/repo.go b/models/repo.go index 1a5a95f0..bb0c164e 100644 --- a/models/repo.go +++ b/models/repo.go @@ -75,9 +75,9 @@ type Repository struct { NumStars int NumForks int NumIssues int - NumReleases int `xorm:"NOT NULL"` NumClosedIssues int NumOpenIssues int `xorm:"-"` + NumTags int `xorm:"-"` IsPrivate bool IsMirror bool IsBare bool diff --git a/modules/base/conf.go b/modules/base/conf.go index 0eca5f4f..957ec57b 100644 --- a/modules/base/conf.go +++ b/modules/base/conf.go @@ -38,7 +38,7 @@ type OauthInfo struct { // Oauther represents oauth service. type Oauther struct { GitHub, Google, Tencent bool - Twitter bool + Twitter, Weibo bool OauthInfos map[string]*OauthInfo } diff --git a/modules/base/template.go b/modules/base/template.go index 62414979..79aeeb9d 100644 --- a/modules/base/template.go +++ b/modules/base/template.go @@ -92,6 +92,7 @@ var TemplateFuncs template.FuncMap = map[string]interface{}{ "DiffTypeToStr": DiffTypeToStr, "DiffLineTypeToStr": DiffLineTypeToStr, "ShortSha": ShortSha, + "Oauth2Icon": Oauth2Icon, } type Actioner interface { @@ -109,7 +110,7 @@ func ActionIcon(opType int) string { switch opType { case 1: // Create repository. return "plus-circle" - case 5: // Commit repository. + case 5, 9: // Commit repository. return "arrow-circle-o-right" case 6: // Create issue. return "exclamation-circle" @@ -127,6 +128,7 @@ const ( TPL_CREATE_ISSUE = `%s opened issue %s#%s
    user-avatar %s
    ` TPL_TRANSFER_REPO = `%s transfered repository %s to %s` + TPL_PUSH_TAG = `%s pushed tag %s at %s` ) type PushCommit struct { @@ -174,6 +176,8 @@ func ActionDesc(act Actioner) string { case 8: // Transfer repository. newRepoLink := content + "/" + repoName return fmt.Sprintf(TPL_TRANSFER_REPO, actUserName, actUserName, repoLink, newRepoLink, newRepoLink) + case 9: // Push tag. + return fmt.Sprintf(TPL_PUSH_TAG, actUserName, actUserName, repoLink, branch, branch, repoLink, repoLink) default: return "invalid type" } @@ -197,3 +201,19 @@ func DiffLineTypeToStr(diffType int) string { } return "same" } + +func Oauth2Icon(t int) string { + switch t { + case 1: + return "fa-github-square" + case 2: + return "fa-google-plus-square" + case 3: + return "fa-twitter-square" + case 4: + return "fa-linux" + case 5: + return "fa-weibo" + } + return "" +} diff --git a/modules/middleware/repo.go b/modules/middleware/repo.go index 1e79ce98..82c1c2db 100644 --- a/modules/middleware/repo.go +++ b/modules/middleware/repo.go @@ -123,6 +123,13 @@ func RepoAssignment(redirect bool, args ...bool) martini.Handler { ctx.Repo.GitRepo = gitRepo ctx.Repo.RepoLink = "/" + user.Name + "/" + repo.Name + tags, err := ctx.Repo.GitRepo.GetTags() + if err != nil { + ctx.Handle(500, "RepoAssignment(GetTags))", err) + return + } + ctx.Repo.Repository.NumTags = len(tags) + ctx.Data["Title"] = user.Name + "/" + repo.Name ctx.Data["Repository"] = repo ctx.Data["Owner"] = user diff --git a/modules/social/social.go b/modules/social/social.go index 230f478f..c2ee5417 100644 --- a/modules/social/social.go +++ b/modules/social/social.go @@ -48,7 +48,7 @@ func NewOauthService() { base.OauthService.OauthInfos = make(map[string]*base.OauthInfo) socialConfigs := make(map[string]*oauth.Config) - allOauthes := []string{"github", "google", "qq", "twitter"} + allOauthes := []string{"github", "google", "qq", "twitter", "weibo"} // Load all OAuth config data. for _, name := range allOauthes { base.OauthService.OauthInfos[name] = &base.OauthInfo{ @@ -98,6 +98,13 @@ func NewOauthService() { enabledOauths = append(enabledOauths, "Twitter") } + // Weibo. + if base.Cfg.MustBool("oauth.weibo", "ENABLED") { + base.OauthService.Weibo = true + newWeiboOauth(socialConfigs["weibo"]) + enabledOauths = append(enabledOauths, "Weibo") + } + log.Info("Oauth Service Enabled %s", enabledOauths) } @@ -331,3 +338,56 @@ func (s *SocialTwitter) UserInfo(token *oauth.Token, _ *url.URL) (*BasicUserInfo // }, nil return nil, nil } + +// __ __ ._____. +// / \ / \ ____ |__\_ |__ ____ +// \ \/\/ // __ \| || __ \ / _ \ +// \ /\ ___/| || \_\ ( <_> ) +// \__/\ / \___ >__||___ /\____/ +// \/ \/ \/ + +type SocialWeibo struct { + Token *oauth.Token + *oauth.Transport +} + +func (s *SocialWeibo) Type() int { + return models.OT_WEIBO +} + +func newWeiboOauth(config *oauth.Config) { + SocialMap["weibo"] = &SocialWeibo{ + Transport: &oauth.Transport{ + Config: config, + Transport: http.DefaultTransport, + }, + } +} + +func (s *SocialWeibo) SetRedirectUrl(url string) { + s.Transport.Config.RedirectURL = url +} + +func (s *SocialWeibo) UserInfo(token *oauth.Token, _ *url.URL) (*BasicUserInfo, error) { + transport := &oauth.Transport{Token: token} + var data struct { + Id string `json:"id"` + Name string `json:"name"` + } + var err error + + reqUrl := "https://api.weibo.com/2/users/show.json" + r, err := transport.Client().Get(reqUrl) + if err != nil { + return nil, err + } + defer r.Body.Close() + if err = json.NewDecoder(r.Body).Decode(&data); err != nil { + return nil, err + } + return &BasicUserInfo{ + Identity: data.Id, + Name: data.Name, + }, nil + return nil, nil +} diff --git a/routers/admin/admin.go b/routers/admin/admin.go index 18a43ff8..d0f737e6 100644 --- a/routers/admin/admin.go +++ b/routers/admin/admin.go @@ -153,6 +153,12 @@ func Config(ctx *middleware.Context) { ctx.Data["Mailer"] = base.MailService } + ctx.Data["OauthEnabled"] = false + if base.OauthService != nil { + ctx.Data["OauthEnabled"] = true + ctx.Data["Oauther"] = base.OauthService + } + ctx.Data["CacheAdapter"] = base.CacheAdapter ctx.Data["CacheConfig"] = base.CacheConfig diff --git a/routers/user/setting.go b/routers/user/setting.go index 7e66ad35..a8fdc116 100644 --- a/routers/user/setting.go +++ b/routers/user/setting.go @@ -69,6 +69,20 @@ func SettingPost(ctx *middleware.Context, form auth.UpdateProfileForm) { ctx.Redirect("/user/setting") } +func SettingSocial(ctx *middleware.Context) { + ctx.Data["Title"] = "Social Account" + ctx.Data["PageIsUserSetting"] = true + ctx.Data["IsUserPageSettingSocial"] = true + socials, err := models.GetOauthByUserId(ctx.User.Id) + if err != nil { + ctx.Handle(500, "user.SettingSocial", err) + return + } + + ctx.Data["Socials"] = socials + ctx.HTML(200, "user/social") +} + func SettingPassword(ctx *middleware.Context) { ctx.Data["Title"] = "Password" ctx.Data["PageIsUserSetting"] = true @@ -147,7 +161,7 @@ func SettingSSHKeys(ctx *middleware.Context, form auth.AddSSHKeyForm) { // Add new SSH key. if ctx.Req.Method == "POST" { - if hasErr, ok := ctx.Data["HasError"]; ok && hasErr.(bool) { + if ctx.HasError() { ctx.HTML(200, "user/publickey") return } @@ -162,11 +176,13 @@ func SettingSSHKeys(ctx *middleware.Context, form auth.AddSSHKeyForm) { ctx.RenderWithErr("Public key name has been used", "user/publickey", &form) return } - ctx.Handle(200, "ssh.AddPublicKey", err) - log.Trace("%s User SSH key added: %s", ctx.Req.RequestURI, ctx.User.LowerName) + ctx.Handle(500, "ssh.AddPublicKey", err) return } else { - ctx.Data["AddSSHKeySuccess"] = true + log.Trace("%s User SSH key added: %s", ctx.Req.RequestURI, ctx.User.LowerName) + ctx.Flash.Success("New SSH Key has been added!") + ctx.Redirect("/user/setting/ssh") + return } } diff --git a/templates/admin/config.tmpl b/templates/admin/config.tmpl index 31cfb77b..757a800c 100644 --- a/templates/admin/config.tmpl +++ b/templates/admin/config.tmpl @@ -88,12 +88,34 @@
    Enabled
    -
    Name
    + {{if .MailerEnabled}}
    Name
    {{.Mailer.Name}}
    Host
    {{.Mailer.Host}}
    User
    -
    {{.Mailer.User}}
    +
    {{.Mailer.User}}
    {{end}} +
    +
    +
    + +
    +
    + OAuth Configuration +
    + +
    +
    +
    Enabled
    +
    + {{if .OauthEnabled}}
    GitHub
    +
    +
    Google
    +
    +
    Tencent QQ
    +
    +
    Weibo
    +
    +
    {{.Mailer.User}}
    {{end}}
    diff --git a/templates/repo/toolbar.tmpl b/templates/repo/toolbar.tmpl index 9c137e51..bde5bc29 100644 --- a/templates/repo/toolbar.tmpl +++ b/templates/repo/toolbar.tmpl @@ -13,7 +13,7 @@
  • {{if .IsRepoToolbarIssuesList}} {{end}}
  • {{end}} -
  • {{if .Repository.NumReleases}}{{.Repository.NumReleases}} {{end}}Releases
  • +
  • {{if .Repository.NumTags}}{{.Repository.NumTags}} {{end}}Releases
  • {{if .IsRepoToolbarReleases}}
  • {{if not .IsRepoReleaseNew}}{{end}}
  • {{end}} diff --git a/templates/user/publickey.tmpl b/templates/user/publickey.tmpl index ecdeb035..29cfd8f0 100644 --- a/templates/user/publickey.tmpl +++ b/templates/user/publickey.tmpl @@ -4,8 +4,8 @@ {{template "user/setting_nav" .}}
    -

    SSH Keys

    {{if .AddSSHKeySuccess}} -

    New SSH Key has been added !

    {{else if .HasError}}

    {{.ErrorMsg}}

    {{end}} +

    SSH Keys

    + {{template "base/alert" .}}
    • SSH Key's name
    • {{range .Keys}} diff --git a/templates/user/setting_nav.tmpl b/templates/user/setting_nav.tmpl index c0f2ae03..9c7ae520 100644 --- a/templates/user/setting_nav.tmpl +++ b/templates/user/setting_nav.tmpl @@ -2,6 +2,7 @@

      Account Setting

      • Account Profile
      • +
      • Social Account
      • Password
      • SSH Keys
      • diff --git a/templates/user/signin.tmpl b/templates/user/signin.tmpl index d402c292..955c82f4 100644 --- a/templates/user/signin.tmpl +++ b/templates/user/signin.tmpl @@ -61,8 +61,9 @@ --> {{if .OauthService.GitHub}}GitHub{{end}} {{if .OauthService.Google}}Google{{end}} - {{if .OauthService.Tencent}}Twitter{{end}} - {{if .OauthService.Tencent}}QQ{{end}} + {{if .OauthService.Twitter}}Twitter{{end}} + {{if .OauthService.Tencent}}Tencent QQ{{end}} + {{if .OauthService.Weibo}}Weibo{{end}}
    {{end}}{{end}} diff --git a/templates/user/social.tmpl b/templates/user/social.tmpl new file mode 100644 index 00000000..f0b11323 --- /dev/null +++ b/templates/user/social.tmpl @@ -0,0 +1,17 @@ +{{template "base/head" .}} +{{template "base/navbar" .}} +
    + {{template "user/setting_nav" .}} +
    +
    +

    Social Account

    + {{template "base/alert" .}} +
      + {{range .Socials}} + + {{end}} +
    +
    +
    +
    +{{template "base/footer" .}} \ No newline at end of file diff --git a/web.go b/web.go index 8ae074ec..268d9e71 100644 --- a/web.go +++ b/web.go @@ -63,7 +63,7 @@ func runWeb(*cli.Context) { SignInRequire: base.Service.RequireSignInView, DisableCsrf: true, }) - + reqSignOut := middleware.Toggle(&middleware.ToggleOptions{SignOutRequire: true}) bindIgnErr := middleware.BindIgnErr @@ -108,6 +108,7 @@ func runWeb(*cli.Context) { r.Post("/forget_password", user.ForgotPasswdPost) }) m.Group("/user/setting", func(r martini.Router) { + r.Get("/social", user.SettingSocial) r.Get("/password", user.SettingPassword) r.Post("/password", bindIgnErr(auth.UpdatePasswdForm{}), user.SettingPasswordPost) r.Any("/ssh", bindIgnErr(auth.AddSSHKeyForm{}), user.SettingSSHKeys) -- cgit v1.2.3 From c36e7d322e74a55749ce2c2934c6fcfa82cff274 Mon Sep 17 00:00:00 2001 From: Unknown Date: Mon, 14 Apr 2014 04:11:33 -0400 Subject: Mirror updates --- models/models.go | 10 +++++++++- models/repo.go | 28 ++++++++++++++++------------ modules/base/conf.go | 6 +++--- routers/dashboard.go | 6 ++++++ templates/admin/dashboard.tmpl | 2 +- templates/base/head.tmpl | 1 + templates/home.tmpl | 19 +++++++++++++++++++ templates/user/profile.tmpl | 3 +-- 8 files changed, 56 insertions(+), 19 deletions(-) (limited to 'models/repo.go') diff --git a/models/models.go b/models/models.go index 0e20a1ab..d4854895 100644 --- a/models/models.go +++ b/models/models.go @@ -120,7 +120,10 @@ func NewEngine() (err error) { type Statistic struct { Counter struct { - User, PublicKey, Repo, Watch, Action, Access int64 + User, PublicKey, Repo, + Watch, Action, Access, + Issue, Comment, + Mirror, Oauth, Release int64 } } @@ -131,5 +134,10 @@ func GetStatistic() (stats Statistic) { stats.Counter.Watch, _ = orm.Count(new(Watch)) stats.Counter.Action, _ = orm.Count(new(Action)) stats.Counter.Access, _ = orm.Count(new(Access)) + stats.Counter.Issue, _ = orm.Count(new(Issue)) + stats.Counter.Comment, _ = orm.Count(new(Comment)) + stats.Counter.Mirror, _ = orm.Count(new(Mirror)) + stats.Counter.Oauth, _ = orm.Count(new(Oauth2)) + stats.Counter.Release, _ = orm.Count(new(Release)) return } diff --git a/models/repo.go b/models/repo.go index bb0c164e..6943d05e 100644 --- a/models/repo.go +++ b/models/repo.go @@ -66,6 +66,7 @@ func NewRepoContext() { type Repository struct { Id int64 OwnerId int64 `xorm:"unique(s)"` + Owner *User `xorm:"-"` ForkId int64 LowerName string `xorm:"unique(s) index not null"` Name string `xorm:"index not null"` @@ -364,24 +365,21 @@ func initRepoCommit(tmpPath string, sig *git.Signature) (err error) { var stderr string if _, stderr, err = com.ExecCmdDir(tmpPath, "git", "add", "--all"); err != nil { return err - } - if len(stderr) > 0 { - log.Trace("stderr(1): %s", stderr) + } else if strings.Contains(stderr, "fatal:") { + return errors.New("git add: " + stderr) } if _, stderr, err = com.ExecCmdDir(tmpPath, "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email), "-m", "Init commit"); err != nil { return err - } - if len(stderr) > 0 { - log.Trace("stderr(2): %s", stderr) + } else if strings.Contains(stderr, "fatal:") { + return errors.New("git commit: " + stderr) } if _, stderr, err = com.ExecCmdDir(tmpPath, "git", "push", "origin", "master"); err != nil { return err - } - if len(stderr) > 0 { - log.Trace("stderr(3): %s", stderr) + } else if strings.Contains(stderr, "fatal:") { + return errors.New("git push: " + stderr) } return nil } @@ -439,9 +437,8 @@ func initRepository(f string, user *User, repo *Repository, initReadme bool, rep _, stderr, err := com.ExecCmd("git", "clone", repoPath, tmpDir) if err != nil { return err - } - if len(stderr) > 0 { - log.Trace("repo.initRepository(git clone): %s", stderr) + } else if strings.Contains(stderr, "fatal:") { + return errors.New("git clone: " + stderr) } // README @@ -725,6 +722,13 @@ func GetRepositories(user *User, private bool) ([]Repository, error) { return repos, err } +// GetRecentUpdatedRepositories returns the list of repositories that are recently updated. +func GetRecentUpdatedRepositories() (repos []*Repository, err error) { + err = orm.Where("is_private=?", false).Limit(5).Desc("updated").Find(&repos) + return repos, err +} + +// GetRepositoryCount returns the total number of repositories of user. func GetRepositoryCount(user *User) (int64, error) { return orm.Count(&Repository{OwnerId: user.Id}) } diff --git a/modules/base/conf.go b/modules/base/conf.go index 957ec57b..c5d73bbc 100644 --- a/modules/base/conf.go +++ b/modules/base/conf.go @@ -37,9 +37,9 @@ type OauthInfo struct { // Oauther represents oauth service. type Oauther struct { - GitHub, Google, Tencent bool - Twitter, Weibo bool - OauthInfos map[string]*OauthInfo + GitHub, Google, Tencent, + Twitter, Weibo bool + OauthInfos map[string]*OauthInfo } var ( diff --git a/routers/dashboard.go b/routers/dashboard.go index 2c81cf23..71bdcc9f 100644 --- a/routers/dashboard.go +++ b/routers/dashboard.go @@ -5,6 +5,7 @@ package routers import ( + "github.com/gogits/gogs/models" "github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/middleware" "github.com/gogits/gogs/routers/user" @@ -23,6 +24,11 @@ func Home(ctx *middleware.Context) { return } + repos, _ := models.GetRecentUpdatedRepositories() + for _, repo := range repos { + repo.Owner, _ = models.GetUserById(repo.OwnerId) + } + ctx.Data["Repos"] = repos ctx.Data["PageIsHome"] = true ctx.HTML(200, "home") } diff --git a/templates/admin/dashboard.tmpl b/templates/admin/dashboard.tmpl index 2334c676..76539842 100644 --- a/templates/admin/dashboard.tmpl +++ b/templates/admin/dashboard.tmpl @@ -9,7 +9,7 @@
    - Gogs database has {{.Stats.Counter.User}} users, {{.Stats.Counter.PublicKey}} SSH keys, {{.Stats.Counter.Repo}} repositories, {{.Stats.Counter.Watch}} watches, {{.Stats.Counter.Action}} actions, and {{.Stats.Counter.Access}} accesses. + Gogs database has {{.Stats.Counter.User}} users, {{.Stats.Counter.PublicKey}} SSH keys, {{.Stats.Counter.Repo}} repositories, {{.Stats.Counter.Watch}} watches, {{.Stats.Counter.Action}} actions, {{.Stats.Counter.Access}} accesses, {{.Stats.Counter.Issue}} issues, {{.Stats.Counter.Comment}} comments, {{.Stats.Counter.Mirror}} mirrors, {{.Stats.Counter.Oauth}} oauthes, {{.Stats.Counter.Release}} releases.
    diff --git a/templates/base/head.tmpl b/templates/base/head.tmpl index 68231391..109ddd35 100644 --- a/templates/base/head.tmpl +++ b/templates/base/head.tmpl @@ -10,6 +10,7 @@ {{if .Repository.IsGoget}}{{end}} + {{if IsProdMode}} diff --git a/templates/home.tmpl b/templates/home.tmpl index d3a8c0c3..5827f618 100644 --- a/templates/home.tmpl +++ b/templates/home.tmpl @@ -1,8 +1,27 @@ {{template "base/head" .}} {{template "base/navbar" .}}
    + {{if not .Repos}}

    Hey there, welcome to the land of Gogs!

    If you just get your Gogs server running, go install guide page will help you setup things for your first-time run.

    + {{else}} +

    Hey there, welcome to the land of Gogs!

    +
    Here are some recent updated repositories:
    +
    +
      + {{range .Repos}} +
    • +
      {{.NumForks}}
      +

      + {{.Name}} +

      +

      {{.Description}}

      +
      Last updated {{.Updated|TimeSince}}
      +
    • + {{end}} +
    +
    + {{end}}
    {{template "base/footer" .}} diff --git a/templates/user/profile.tmpl b/templates/user/profile.tmpl index a336bfb2..e80b2394 100644 --- a/templates/user/profile.tmpl +++ b/templates/user/profile.tmpl @@ -58,14 +58,13 @@ {{else}} - {{$owner := .Owner}}
      {{range .Repos}}
    • {{.NumForks}}

      - {{.Name}}{{if .IsPrivate}} Private{{end}} + {{.Name}}{{if .IsPrivate}} Private{{end}}

      {{.Description}}

      Last updated {{.Updated|TimeSince}}
      -- cgit v1.2.3 From eda3f8b3b34f15d29bb2e6f1346e15616f508501 Mon Sep 17 00:00:00 2001 From: Unknown Date: Sat, 19 Apr 2014 06:00:08 -0400 Subject: Mirror updates --- .gopmfile | 23 +++++++++++------------ conf/app.ini | 2 ++ gogs.go | 2 +- models/repo.go | 2 +- modules/base/conf.go | 19 +++++++++++-------- routers/repo/repo.go | 1 + templates/repo/setting.tmpl | 7 +++++++ 7 files changed, 34 insertions(+), 22 deletions(-) (limited to 'models/repo.go') diff --git a/.gopmfile b/.gopmfile index 79f98e02..296d0236 100644 --- a/.gopmfile +++ b/.gopmfile @@ -2,24 +2,23 @@ path = github.com/gogits/gogs [deps] +github.com/Unknwon/cae = +github.com/Unknwon/com = +github.com/Unknwon/goconfig = github.com/codegangsta/cli = github.com/go-martini/martini = -github.com/nfnt/resize = -github.com/lunny/xorm = github.com/go-sql-driver/mysql = +github.com/go-xorm/xorm = +github.com/gogits/cache = +github.com/gogits/gfm = +github.com/gogits/git = +github.com/gogits/logs = +github.com/gogits/oauth2 = +github.com/gogits/session = github.com/lib/pq = +github.com/nfnt/resize = github.com/qiniu/log = github.com/robfig/cron = -github.com/Unknwon/com = -github.com/Unknwon/cae = -github.com/Unknwon/goconfig = -github.com/gogits/logs = -github.com/gogits/binding = -github.com/gogits/git = -github.com/gogits/gfm = -github.com/gogits/cache = -github.com/gogits/session = -github.com/gogits/oauth2 = [res] include = templates|public|conf diff --git a/conf/app.ini b/conf/app.ini index d805f822..eb3d635f 100644 --- a/conf/app.ini +++ b/conf/app.ini @@ -8,6 +8,7 @@ RUN_MODE = dev [repository] ROOT = +SCRIPT_TYPE = bash LANG_IGNS = Google Go|C|C++|Python|Ruby|C Sharp|Java|Objective-C LICENSES = Apache v2 License|GPL v2|MIT License|Affero GPL|Artistic License 2.0|BSD (3-Clause) License @@ -65,6 +66,7 @@ SEND_BUFFER_LEN = 10 SUBJECT = %(APP_NAME)s ; Mail server ; Gmail: smtp.gmail.com:587 +; QQ: smtp.qq.com:25 HOST = ; Mail from address FROM = diff --git a/gogs.go b/gogs.go index 65180754..bc807c46 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.3.0.0418 Alpha" +const APP_VER = "0.3.0.0419 Alpha" func init() { base.AppVer = APP_VER diff --git a/models/repo.go b/models/repo.go index 6943d05e..486720d2 100644 --- a/models/repo.go +++ b/models/repo.go @@ -413,7 +413,7 @@ func initRepository(f string, user *User, repo *Repository, initReadme bool, rep // hook/post-update if err := createHookUpdate(filepath.Join(repoPath, "hooks", "update"), - fmt.Sprintf("#!/usr/bin/env bash\n%s update $1 $2 $3\n", + fmt.Sprintf("#!/usr/bin/env %s\n%s update $1 $2 $3\n", base.ScriptType, strings.Replace(appPath, "\\", "/", -1))); err != nil { return err } diff --git a/modules/base/conf.go b/modules/base/conf.go index c5d73bbc..9dccc48f 100644 --- a/modules/base/conf.go +++ b/modules/base/conf.go @@ -43,15 +43,17 @@ type Oauther struct { } var ( - AppVer string - AppName string - AppLogo string - AppUrl string - IsProdMode bool - Domain string - SecretKey string - RunUser string + AppVer string + AppName string + AppLogo string + AppUrl string + IsProdMode bool + Domain string + SecretKey string + RunUser string + RepoRootPath string + ScriptType string InstallLock bool @@ -310,6 +312,7 @@ func NewConfigContext() { if err = os.MkdirAll(RepoRootPath, os.ModePerm); err != nil { qlog.Fatalf("Fail to create RepoRootPath(%s): %v\n", RepoRootPath, err) } + ScriptType = Cfg.MustValue("repository", "SCRIPT_TYPE", "bash") } func NewBaseServices() { diff --git a/routers/repo/repo.go b/routers/repo/repo.go index 6422f0a3..f733378b 100644 --- a/routers/repo/repo.go +++ b/routers/repo/repo.go @@ -340,6 +340,7 @@ func SettingPost(ctx *middleware.Context) { } ctx.Repo.Repository.Description = ctx.Query("desc") ctx.Repo.Repository.Website = ctx.Query("site") + ctx.Repo.Repository.IsPrivate = ctx.Query("private") == "on" ctx.Repo.Repository.IsGoget = ctx.Query("goget") == "on" if err := models.UpdateRepository(ctx.Repo.Repository); err != nil { ctx.Handle(404, "repo.SettingPost(update)", err) diff --git a/templates/repo/setting.tmpl b/templates/repo/setting.tmpl index 5572671c..61621fe0 100644 --- a/templates/repo/setting.tmpl +++ b/templates/repo/setting.tmpl @@ -65,6 +65,13 @@
      +
      + +
      +