From a55941ff833155cba88dbcc957b15c0ddcf07cb4 Mon Sep 17 00:00:00 2001 From: Unknown Date: Fri, 28 Mar 2014 17:34:07 -0400 Subject: Add auto-detect home directory --- modules/base/conf.go | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) (limited to 'modules') diff --git a/modules/base/conf.go b/modules/base/conf.go index b3a987e6..fd77cfd3 100644 --- a/modules/base/conf.go +++ b/modules/base/conf.go @@ -291,9 +291,14 @@ func NewConfigContext() { PictureService = Cfg.MustValue("picture", "SERVICE") // Determine and create root git reposiroty path. - RepoRootPath = Cfg.MustValue("repository", "ROOT") + homeDir, err := com.HomeDir() + if err != nil { + fmt.Printf("Fail to get home directory): %v\n", err) + os.Exit(2) + } + RepoRootPath = Cfg.MustValue("repository", "ROOT", filepath.Join(homeDir, "git/gogs-repositories")) if err = os.MkdirAll(RepoRootPath, os.ModePerm); err != nil { - fmt.Printf("models.init(fail to create RepoRootPath(%s)): %v\n", RepoRootPath, err) + fmt.Printf("Fail to create RepoRootPath(%s): %v\n", RepoRootPath, err) os.Exit(2) } } -- cgit v1.2.3 From 6e376bb85c7a154c7567fd4be8cabc9627c8c6e7 Mon Sep 17 00:00:00 2001 From: Unknown Date: Fri, 28 Mar 2014 18:40:31 -0400 Subject: Working on install page --- modules/auth/auth.go | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ routers/install.go | 3 ++- templates/install.tmpl | 8 ++++---- web.go | 2 +- 4 files changed, 57 insertions(+), 6 deletions(-) (limited to 'modules') diff --git a/modules/auth/auth.go b/modules/auth/auth.go index 2e0555f6..ac03a8f1 100644 --- a/modules/auth/auth.go +++ b/modules/auth/auth.go @@ -161,3 +161,53 @@ func AssignForm(form interface{}, data base.TmplData) { data[fieldName] = val.Field(i).Interface() } } + +type InstallForm struct { + Database string `form:"database" binding:"Required"` + Host string `form:"host"` + User string `form:"user"` + Passwd string `form:"passwd"` + DatabaseName string `form:"database_name"` + SslMode string `form:"ssl_mode"` + DatabasePath string `form:"database_path"` + RepoRootPath string `form:"repo_path"` + RunUser string `form:"run_user"` + AppUrl string `form:"app_url"` + AdminName string `form:"admin_name" binding:"Required"` + AdminPasswd string `form:"admin_pwd" binding:"Required;MinSize(6);MaxSize(30)"` + AdminEmail string `form:"admin_email" binding:"Required;Email;MaxSize(50)"` + SmtpHost string `form:"smtp_host"` + SmtpEmail string `form:"mailer_user"` + SmtpPasswd string `form:"mailer_pwd"` + RegisterConfirm string `form:"register_confirm"` + MailNotify string `form:"mail_notify"` +} + +func (f *InstallForm) Name(field string) string { + names := map[string]string{ + "Database": "Database name", + "AdminName": "Admin user name", + "AdminPasswd": "Admin password", + "AdminEmail": "Admin e-maill address", + } + return names[field] +} + +func (f *InstallForm) Validate(errors *binding.Errors, req *http.Request, context martini.Context) { + if req.Method == "GET" || errors.Count() == 0 { + return + } + + data := context.Get(reflect.TypeOf(base.TmplData{})).Interface().(base.TmplData) + data["HasError"] = true + AssignForm(f, data) + + if len(errors.Overall) > 0 { + for _, err := range errors.Overall { + log.Error("InstallForm.Validate: %v", err) + } + return + } + + validate(errors, data, f) +} diff --git a/routers/install.go b/routers/install.go index e0ac92f1..b5c3a936 100644 --- a/routers/install.go +++ b/routers/install.go @@ -8,11 +8,12 @@ import ( "errors" "github.com/gogits/gogs/models" + "github.com/gogits/gogs/modules/auth" "github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/middleware" ) -func Install(ctx *middleware.Context) { +func Install(ctx *middleware.Context, form auth.InstallForm) { if base.InstallLock { ctx.Handle(404, "install.Install", errors.New("Installation is prohibited")) return diff --git a/templates/install.tmpl b/templates/install.tmpl index 872982a0..d8f05fca 100644 --- a/templates/install.tmpl +++ b/templates/install.tmpl @@ -43,7 +43,7 @@
- +

Recommend use INNODB engine with utf8_general_ci charset.

@@ -64,7 +64,7 @@
- +

The file path of SQLite3 database.

@@ -78,7 +78,7 @@
- +

The git copy of each repository is saved in this directory.

@@ -88,7 +88,7 @@
- +

The user has access to visit and run Gogs.

diff --git a/web.go b/web.go index 4ed273ea..35695f0b 100644 --- a/web.go +++ b/web.go @@ -90,7 +90,7 @@ func runWeb(*cli.Context) { // Routers. m.Get("/", ignSignIn, routers.Home) - m.Get("/install", routers.Install) + m.Any("/install", routers.Install) m.Get("/issues", reqSignIn, user.Issues) m.Get("/pulls", reqSignIn, user.Pulls) m.Get("/stars", reqSignIn, user.Stars) -- cgit v1.2.3 From a726c125b572bc1ff0b445990821280e304db9ff Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Sat, 29 Mar 2014 19:29:52 +0800 Subject: Add PushCommit --- modules/base/tool.go | 11 +++++++++-- routers/repo/repo.go | 8 +++----- update.go | 8 ++++++-- 3 files changed, 18 insertions(+), 9 deletions(-) (limited to 'modules') diff --git a/modules/base/tool.go b/modules/base/tool.go index 9ddb90f7..d005ffe3 100644 --- a/modules/base/tool.go +++ b/modules/base/tool.go @@ -506,9 +506,16 @@ const (
user-avatar %s
` ) +type PushCommit struct { + Sha1 string + Message string + AuthorEmail string + AuthorName string +} + type PushCommits struct { Len int - Commits [][]string + Commits []*PushCommit } // ActionDesc accepts int that represents action operation type @@ -529,7 +536,7 @@ func ActionDesc(act Actioner, avatarLink string) string { } buf := bytes.NewBuffer([]byte("\n")) for _, commit := range push.Commits { - buf.WriteString(fmt.Sprintf(TPL_COMMIT_REPO_LI, avatarLink, repoLink, commit[0], commit[0][:7], commit[1]) + "\n") + buf.WriteString(fmt.Sprintf(TPL_COMMIT_REPO_LI, avatarLink, repoLink, commit.Sha1, commit.Sha1[:7], commit.Message) + "\n") } if push.Len > 3 { buf.WriteString(fmt.Sprintf(`
%d other commits >>
`, actUserName, repoName, branch, push.Len)) diff --git a/routers/repo/repo.go b/routers/repo/repo.go index e7107ad1..b9ac1f1c 100644 --- a/routers/repo/repo.go +++ b/routers/repo/repo.go @@ -276,11 +276,9 @@ func Http(ctx *middleware.Context, params martini.Params) { } prefix := path.Join("/", username, params["reponame"]) - server := &webdav.Server{ - Fs: webdav.Dir(models.RepoPath(username, reponame)), - TrimPrefix: prefix, - Listings: true, - } + server := webdav.NewServer( + models.RepoPath(username, reponame), + prefix, true) server.ServeHTTP(ctx.ResponseWriter, ctx.Req) } diff --git a/update.go b/update.go index faec0029..9743dcc4 100644 --- a/update.go +++ b/update.go @@ -130,11 +130,15 @@ func runUpdate(c *cli.Context) { return } - commits := make([][]string, 0) + commits := make([]*base.PushCommit, 0) var maxCommits = 3 for e := l.Front(); e != nil; e = e.Next() { commit := e.Value.(*git.Commit) - commits = append(commits, []string{commit.Id().String(), commit.Message()}) + commits = append(commits, + &base.PushCommit{commit.Id().String(), + commit.Message(), + commit.Author.Email, + commit.Author.Name}) if len(commits) >= maxCommits { break } -- cgit v1.2.3 From 828282882066aa4e8bd8fb0c083c530607bc34bb Mon Sep 17 00:00:00 2001 From: Unknown Date: Sat, 29 Mar 2014 07:50:25 -0400 Subject: Fix action email bug --- models/action.go | 13 +++++++++---- modules/base/tool.go | 8 +++++--- routers/repo/issue.go | 2 +- routers/user/user.go | 2 +- templates/user/dashboard.tmpl | 2 +- templates/user/profile.tmpl | 2 +- 6 files changed, 18 insertions(+), 11 deletions(-) (limited to 'modules') diff --git a/models/action.go b/models/action.go index 9d99df85..89485578 100644 --- a/models/action.go +++ b/models/action.go @@ -31,6 +31,7 @@ type Action struct { OpType int // Operations: CREATE DELETE STAR ... ActUserId int64 // Action user id. ActUserName string // Action user name. + ActEmail string RepoId int64 RepoName string RefName string @@ -46,6 +47,10 @@ func (a Action) GetActUserName() string { return a.ActUserName } +func (a Action) GetActEmail() string { + return a.ActEmail +} + func (a Action) GetRepoName() string { return a.RepoName } @@ -69,8 +74,8 @@ func CommitRepoAction(userId int64, userName string, return err } - if err = NotifyWatchers(&Action{ActUserId: userId, ActUserName: userName, OpType: OP_COMMIT_REPO, - Content: string(bs), RepoId: repoId, RepoName: repoName, RefName: refName}); err != nil { + if err = NotifyWatchers(&Action{ActUserId: userId, ActUserName: userName, ActEmail: "", + OpType: OP_COMMIT_REPO, Content: string(bs), RepoId: repoId, RepoName: repoName, RefName: refName}); err != nil { log.Error("action.CommitRepoAction(notify watchers): %d/%s", userId, repoName) return err } @@ -93,8 +98,8 @@ func CommitRepoAction(userId int64, userName string, // NewRepoAction adds new action for creating repository. func NewRepoAction(user *User, repo *Repository) (err error) { - if err = NotifyWatchers(&Action{ActUserId: user.Id, ActUserName: user.Name, OpType: OP_CREATE_REPO, - RepoId: repo.Id, RepoName: repo.Name}); err != nil { + if err = NotifyWatchers(&Action{ActUserId: user.Id, ActUserName: user.Name, ActEmail: user.Email, + OpType: OP_CREATE_REPO, RepoId: repo.Id, RepoName: repo.Name}); err != nil { log.Error("action.NewRepoAction(notify watchers): %d/%s", user.Id, repo.Name) return err } diff --git a/modules/base/tool.go b/modules/base/tool.go index d005ffe3..6876da76 100644 --- a/modules/base/tool.go +++ b/modules/base/tool.go @@ -478,6 +478,7 @@ func (a argInt) Get(i int, args ...int) (r int) { type Actioner interface { GetOpType() int GetActUserName() string + GetActEmail() string GetRepoName() string GetBranch() string GetContent() string @@ -520,8 +521,9 @@ type PushCommits struct { // ActionDesc accepts int that represents action operation type // and returns the description. -func ActionDesc(act Actioner, avatarLink string) string { +func ActionDesc(act Actioner) string { actUserName := act.GetActUserName() + email := act.GetActEmail() repoName := act.GetRepoName() repoLink := actUserName + "/" + repoName branch := act.GetBranch() @@ -536,7 +538,7 @@ func ActionDesc(act Actioner, avatarLink string) string { } buf := bytes.NewBuffer([]byte("\n")) for _, commit := range push.Commits { - buf.WriteString(fmt.Sprintf(TPL_COMMIT_REPO_LI, avatarLink, repoLink, commit.Sha1, commit.Sha1[:7], commit.Message) + "\n") + 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(`
%d other commits >>
`, actUserName, repoName, branch, push.Len)) @@ -546,7 +548,7 @@ func ActionDesc(act Actioner, avatarLink string) 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, infos[1]) + AvatarLink(email), infos[1]) default: return "invalid type" } diff --git a/routers/repo/issue.go b/routers/repo/issue.go index 14876e18..c89c8b56 100644 --- a/routers/repo/issue.go +++ b/routers/repo/issue.go @@ -105,7 +105,7 @@ func CreateIssue(ctx *middleware.Context, params martini.Params, form auth.Creat } // Notify watchers. - if err = models.NotifyWatchers(&models.Action{ActUserId: ctx.User.Id, ActUserName: ctx.User.Name, + if err = models.NotifyWatchers(&models.Action{ActUserId: ctx.User.Id, ActUserName: ctx.User.Name, ActEmail: ctx.User.Email, OpType: models.OP_CREATE_ISSUE, Content: fmt.Sprintf("%d|%s", issue.Index, issue.Name), RepoId: ctx.Repo.Repository.Id, RepoName: ctx.Repo.Repository.Name, RefName: ""}); err != nil { ctx.Handle(200, "issue.CreateIssue", err) diff --git a/routers/user/user.go b/routers/user/user.go index b0fc5839..114169e6 100644 --- a/routers/user/user.go +++ b/routers/user/user.go @@ -279,7 +279,7 @@ func Feeds(ctx *middleware.Context, form auth.FeedsForm) { feeds := make([]string, len(actions)) for i := range actions { feeds[i] = fmt.Sprintf(TPL_FEED, base.ActionIcon(actions[i].OpType), - base.TimeSince(actions[i].Created), base.ActionDesc(actions[i], ctx.User.AvatarLink())) + base.TimeSince(actions[i].Created), base.ActionDesc(actions[i])) } ctx.JSON(200, &feeds) } diff --git a/templates/user/dashboard.tmpl b/templates/user/dashboard.tmpl index 6064095b..bc0853fb 100644 --- a/templates/user/dashboard.tmpl +++ b/templates/user/dashboard.tmpl @@ -18,7 +18,7 @@ {{range .Feeds}}
  • -
    {{TimeSince .Created}}
    {{ActionDesc . $.SignedUser.AvatarLink | str2html}}
    +
    {{TimeSince .Created}}
    {{ActionDesc . | str2html}}
  • {{else}} diff --git a/templates/user/profile.tmpl b/templates/user/profile.tmpl index 5ac8121f..97549d48 100644 --- a/templates/user/profile.tmpl +++ b/templates/user/profile.tmpl @@ -35,7 +35,7 @@ {{range .Feeds}}
  • -
    {{TimeSince .Created}}
    {{ActionDesc . $.Owner.AvatarLink | str2html}}
    +
    {{TimeSince .Created}}
    {{ActionDesc . | str2html}}
  • {{else}} -- cgit v1.2.3 From 107a1eadac72e610a9bcb68498751ca51ec8f51a Mon Sep 17 00:00:00 2001 From: Unknown Date: Sat, 29 Mar 2014 17:50:51 -0400 Subject: Finish close and reopen issue, install page, ready going to test stage of v0.2.0 --- README.md | 2 +- README_ZH.md | 2 +- gogs.go | 2 +- models/issue.go | 36 ++++++++++-- models/models.go | 24 ++++---- models/repo.go | 25 ++++---- modules/auth/auth.go | 1 + modules/base/conf.go | 7 ++- public/css/gogs.css | 6 +- routers/install.go | 141 ++++++++++++++++++++++++++++++++++++++++++++-- routers/repo/issue.go | 62 +++++++++++++------- routers/user/user.go | 14 ++--- templates/install.tmpl | 59 ++++++++++--------- templates/issue/view.tmpl | 65 +++++++++++---------- web.go | 28 +-------- 15 files changed, 314 insertions(+), 160 deletions(-) (limited to 'modules') diff --git a/README.md b/README.md index e88a2477..1d3aaf3e 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.1.9 Alpha +##### Current version: 0.2.0 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. diff --git a/README_ZH.md b/README_ZH.md index 8e187c73..4590e36b 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.1.9 Alpha +##### 当前版本:0.2.0 Alpha ## 开发目的 diff --git a/gogs.go b/gogs.go index f1372f0c..2ef35ca4 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.1.9.0329 Alpha" +const APP_VER = "0.2.0.0329 Alpha" func init() { base.AppVer = APP_VER diff --git a/models/issue.go b/models/issue.go index 9fd1b905..f14030df 100644 --- a/models/issue.go +++ b/models/issue.go @@ -170,9 +170,17 @@ type Milestone struct { Created time.Time `xorm:"created"` } +// Issue types. +const ( + IT_PLAIN = iota // Pure comment. + IT_REOPEN // Issue reopen status change prompt. + IT_CLOSE // Issue close status change prompt. +) + // Comment represents a comment in commit and issue page. type Comment struct { Id int64 + Type int PosterId int64 Poster *User `xorm:"-"` IssueId int64 @@ -183,21 +191,37 @@ type Comment struct { } // CreateComment creates comment of issue or commit. -func CreateComment(userId, issueId, commitId, line int64, content string) error { +func CreateComment(userId, repoId, issueId, commitId, line int64, cmtType int, content string) error { sess := orm.NewSession() defer sess.Close() sess.Begin() - if _, err := orm.Insert(&Comment{PosterId: userId, IssueId: issueId, + if _, err := orm.Insert(&Comment{PosterId: userId, Type: cmtType, IssueId: issueId, CommitId: commitId, Line: line, Content: content}); err != nil { sess.Rollback() return err } - rawSql := "UPDATE `issue` SET num_comments = num_comments + 1 WHERE id = ?" - if _, err := sess.Exec(rawSql, issueId); err != nil { - sess.Rollback() - return err + // Check comment type. + switch cmtType { + case IT_PLAIN: + rawSql := "UPDATE `issue` SET num_comments = num_comments + 1 WHERE id = ?" + if _, err := sess.Exec(rawSql, issueId); err != nil { + sess.Rollback() + return err + } + case IT_REOPEN: + rawSql := "UPDATE `repository` SET num_closed_issues = num_closed_issues - 1 WHERE id = ?" + if _, err := sess.Exec(rawSql, repoId); err != nil { + sess.Rollback() + return err + } + case IT_CLOSE: + rawSql := "UPDATE `repository` SET num_closed_issues = num_closed_issues + 1 WHERE id = ?" + if _, err := sess.Exec(rawSql, repoId); err != nil { + sess.Rollback() + return err + } } return sess.Commit() } diff --git a/models/models.go b/models/models.go index bafa1747..825730c5 100644 --- a/models/models.go +++ b/models/models.go @@ -34,8 +34,7 @@ func LoadModelsConfig() { DbCfg.Path = base.Cfg.MustValue("database", "PATH", "data/gogs.db") } -func SetEngine() { - var err error +func SetEngine() (err error) { switch DbCfg.Type { case "mysql": orm, err = xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8", @@ -47,12 +46,10 @@ func SetEngine() { os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm) orm, err = xorm.NewEngine("sqlite3", DbCfg.Path) default: - fmt.Printf("Unknown database type: %s\n", DbCfg.Type) - os.Exit(2) + return fmt.Errorf("Unknown database type: %s\n", DbCfg.Type) } if err != nil { - fmt.Printf("models.init(fail to conntect database): %v\n", err) - os.Exit(2) + return fmt.Errorf("models.init(fail to conntect database): %v\n", err) } // WARNNING: for serv command, MUST remove the output to os.stdout, @@ -62,20 +59,21 @@ func SetEngine() { //orm.ShowErr = true f, err := os.Create("xorm.log") if err != nil { - fmt.Printf("models.init(fail to create xorm.log): %v\n", err) - os.Exit(2) + return fmt.Errorf("models.init(fail to create xorm.log): %v\n", err) } orm.Logger = f orm.ShowSQL = true + return nil } -func NewEngine() { - SetEngine() - if err := orm.Sync(new(User), new(PublicKey), new(Repository), new(Watch), +func NewEngine() (err error) { + if err = SetEngine(); err != nil { + return err + } else if err = orm.Sync(new(User), new(PublicKey), new(Repository), new(Watch), new(Action), new(Access), new(Issue), new(Comment)); err != nil { - fmt.Printf("sync database struct error: %v\n", err) - os.Exit(2) + return fmt.Errorf("sync database struct error: %v\n", err) } + return nil } type Statistic struct { diff --git a/models/repo.go b/models/repo.go index a848694d..0b2bbe48 100644 --- a/models/repo.go +++ b/models/repo.go @@ -11,7 +11,6 @@ import ( "os" "os/exec" "path/filepath" - "regexp" "strings" "time" "unicode/utf8" @@ -59,15 +58,6 @@ func NewRepoContext() { os.Exit(2) } } - - // Initialize illegal patterns. - for i := range illegalPatterns[1:] { - pattern := "" - for j := range illegalPatterns[i+1] { - pattern += "[" + string(illegalPatterns[i+1][j]-32) + string(illegalPatterns[i+1][j]) + "]" - } - illegalPatterns[i+1] = pattern - } } // Repository represents a git repository. @@ -105,15 +95,20 @@ func IsRepositoryExist(user *User, repoName string) (bool, error) { } var ( - // Define as all lower case!! - illegalPatterns = []string{"[.][Gg][Ii][Tt]", "raw", "user", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin"} + illegalEquals = []string{"raw", "install", "api", "avatar", "user", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin"} + illegalSuffixs = []string{".git"} ) // IsLegalName returns false if name contains illegal characters. func IsLegalName(repoName string) bool { - for _, pattern := range illegalPatterns { - has, _ := regexp.MatchString(pattern, repoName) - if has { + repoName = strings.ToLower(repoName) + for _, char := range illegalEquals { + if repoName == char { + return false + } + } + for _, char := range illegalSuffixs { + if strings.HasSuffix(repoName, char) { return false } } diff --git a/modules/auth/auth.go b/modules/auth/auth.go index ac03a8f1..361f55b2 100644 --- a/modules/auth/auth.go +++ b/modules/auth/auth.go @@ -172,6 +172,7 @@ type InstallForm struct { DatabasePath string `form:"database_path"` RepoRootPath string `form:"repo_path"` RunUser string `form:"run_user"` + Domain string `form:"domain"` AppUrl string `form:"app_url"` AdminName string `form:"admin_name" binding:"Required"` AdminPasswd string `form:"admin_pwd" binding:"Required;MinSize(6);MaxSize(30)"` diff --git a/modules/base/conf.go b/modules/base/conf.go index fd77cfd3..f696d083 100644 --- a/modules/base/conf.go +++ b/modules/base/conf.go @@ -272,18 +272,19 @@ func NewConfigContext() { Domain = Cfg.MustValue("server", "DOMAIN") SecretKey = Cfg.MustValue("security", "SECRET_KEY") + InstallLock = Cfg.MustBool("security", "INSTALL_LOCK", false) + RunUser = Cfg.MustValue("", "RUN_USER") curUser := os.Getenv("USERNAME") if len(curUser) == 0 { curUser = os.Getenv("USER") } - if RunUser != curUser { + // 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) } - InstallLock = Cfg.MustBool("security", "INSTALL_LOCK", false) - LogInRememberDays = Cfg.MustInt("security", "LOGIN_REMEMBER_DAYS") CookieUserName = Cfg.MustValue("security", "COOKIE_USERNAME") CookieRememberName = Cfg.MustValue("security", "COOKIE_REMEMBER_NAME") diff --git a/public/css/gogs.css b/public/css/gogs.css index d6c117c8..965c9096 100755 --- a/public/css/gogs.css +++ b/public/css/gogs.css @@ -1197,13 +1197,13 @@ html, body { line-height: 42px; } -#issue .issue-closed{ - border-bottom: 3px solid #CCC; +#issue .issue-closed, #issue .issue-opened { + border-bottom: 2px solid #CCC; margin-bottom: 24px; padding-bottom: 24px; } -#issue .issue-closed .btn-danger,#issue .issue-opened .btn-success{ +#issue .issue-closed .label-danger,#issue .issue-opened .label-success{ margin: 0 .8em; } diff --git a/routers/install.go b/routers/install.go index b5c3a936..407705b7 100644 --- a/routers/install.go +++ b/routers/install.go @@ -6,13 +6,46 @@ package routers import ( "errors" + "os" + "strings" + + "github.com/Unknwon/goconfig" + "github.com/codegangsta/martini" "github.com/gogits/gogs/models" "github.com/gogits/gogs/modules/auth" "github.com/gogits/gogs/modules/base" + "github.com/gogits/gogs/modules/log" + "github.com/gogits/gogs/modules/mailer" "github.com/gogits/gogs/modules/middleware" ) +// Check run mode(Default of martini is Dev). +func checkRunMode() { + switch base.Cfg.MustValue("", "RUN_MODE") { + case "prod": + martini.Env = martini.Prod + case "test": + martini.Env = martini.Test + } + log.Info("Run Mode: %s", strings.Title(martini.Env)) +} + +// GlobalInit is for global configuration reload-able. +func GlobalInit() { + base.NewConfigContext() + mailer.NewMailerContext() + models.LoadModelsConfig() + models.LoadRepoConfig() + models.NewRepoContext() + if err := models.NewEngine(); err != nil && base.InstallLock { + log.Error("%v", err) + os.Exit(2) + } + base.NewServices() + checkRunMode() +} + func Install(ctx *middleware.Context, form auth.InstallForm) { if base.InstallLock { ctx.Handle(404, "install.Install", errors.New("Installation is prohibited")) @@ -20,14 +53,114 @@ func Install(ctx *middleware.Context, form auth.InstallForm) { } ctx.Data["Title"] = "Install" - ctx.Data["DbCfg"] = models.DbCfg - ctx.Data["RepoRootPath"] = base.RepoRootPath - ctx.Data["RunUser"] = base.RunUser - ctx.Data["AppUrl"] = base.AppUrl ctx.Data["PageIsInstall"] = true + // Get and assign value to install form. + if len(form.Host) == 0 { + form.Host = models.DbCfg.Host + } + if len(form.User) == 0 { + form.User = models.DbCfg.User + } + if len(form.Passwd) == 0 { + form.Passwd = models.DbCfg.Pwd + } + if len(form.DatabaseName) == 0 { + form.DatabaseName = models.DbCfg.Name + } + if len(form.DatabasePath) == 0 { + form.DatabasePath = models.DbCfg.Path + } + + if len(form.RepoRootPath) == 0 { + form.RepoRootPath = base.RepoRootPath + } + if len(form.RunUser) == 0 { + form.RunUser = base.RunUser + } + if len(form.Domain) == 0 { + form.Domain = base.Domain + } + if len(form.AppUrl) == 0 { + form.AppUrl = base.AppUrl + } + + auth.AssignForm(form, ctx.Data) + if ctx.Req.Method == "GET" { ctx.HTML(200, "install") return } + + if ctx.HasError() { + ctx.HTML(200, "install") + return + } + + // Pass basic check, now test configuration. + // Test database setting. + dbTypes := map[string]string{"mysql": "mysql", "pgsql": "postgres", "sqlite": "sqlite3"} + models.DbCfg.Type = dbTypes[form.Database] + models.DbCfg.Host = form.Host + models.DbCfg.User = form.User + models.DbCfg.Pwd = form.Passwd + models.DbCfg.Name = form.DatabaseName + models.DbCfg.SslMode = form.SslMode + models.DbCfg.Path = form.DatabasePath + + if err := models.NewEngine(); err != nil { + ctx.RenderWithErr("Database setting is not correct: "+err.Error(), "install", &form) + return + } + + // Test repository root path. + if err := os.MkdirAll(form.RepoRootPath, os.ModePerm); err != nil { + ctx.RenderWithErr("Repository root path is invalid: "+err.Error(), "install", &form) + return + } + + // Create admin account. + if _, err := models.RegisterUser(&models.User{Name: form.AdminName, Email: form.AdminEmail, Passwd: form.AdminPasswd, + IsAdmin: true, IsActive: true}); err != nil { + if err != models.ErrUserAlreadyExist { + ctx.RenderWithErr("Admin account setting is invalid: "+err.Error(), "install", &form) + return + } + } + + // Save settings. + base.Cfg.SetValue("database", "DB_TYPE", models.DbCfg.Type) + base.Cfg.SetValue("database", "HOST", models.DbCfg.Host) + base.Cfg.SetValue("database", "NAME", models.DbCfg.Name) + base.Cfg.SetValue("database", "USER", models.DbCfg.User) + base.Cfg.SetValue("database", "PASSWD", models.DbCfg.Pwd) + base.Cfg.SetValue("database", "SSL_MODE", models.DbCfg.SslMode) + base.Cfg.SetValue("database", "PATH", models.DbCfg.Path) + + base.Cfg.SetValue("repository", "ROOT", form.RepoRootPath) + base.Cfg.SetValue("", "RUN_USER", form.RunUser) + base.Cfg.SetValue("server", "DOMAIN", form.Domain) + base.Cfg.SetValue("server", "ROOT_URL", form.AppUrl) + + if len(form.Host) > 0 { + base.Cfg.SetValue("mailer", "ENABLED", "true") + base.Cfg.SetValue("mailer", "HOST", form.SmtpHost) + base.Cfg.SetValue("mailer", "USER", form.SmtpEmail) + base.Cfg.SetValue("mailer", "PASSWD", form.SmtpPasswd) + + base.Cfg.SetValue("service", "REGISTER_EMAIL_CONFIRM", base.ToStr(form.RegisterConfirm == "on")) + base.Cfg.SetValue("service", "ENABLE_NOTIFY_MAIL", base.ToStr(form.MailNotify == "on")) + } + + base.Cfg.SetValue("security", "INSTALL_LOCK", "true") + + if err := goconfig.SaveConfigFile(base.Cfg, "custom/conf/app.ini"); err != nil { + ctx.RenderWithErr("Fail to save configuration: "+err.Error(), "install", &form) + return + } + + GlobalInit() + + log.Info("First-time run install finished!") + ctx.Redirect("/user/login") } diff --git a/routers/repo/issue.go b/routers/repo/issue.go index 337bd4bf..3506e901 100644 --- a/routers/repo/issue.go +++ b/routers/repo/issue.go @@ -7,6 +7,7 @@ package repo import ( "fmt" "net/url" + "strings" "github.com/codegangsta/martini" @@ -175,7 +176,7 @@ func ViewIssue(ctx *middleware.Context, params martini.Params) { ctx.Data["Title"] = issue.Name ctx.Data["Issue"] = issue ctx.Data["Comments"] = comments - ctx.Data["IsIssueOwner"] = issue.PosterId == ctx.User.Id + ctx.Data["IsIssueOwner"] = ctx.Repo.IsOwner || issue.PosterId == ctx.User.Id ctx.Data["IsRepoToolbarIssues"] = true ctx.Data["IsRepoToolbarIssuesList"] = false ctx.HTML(200, "issue/view") @@ -225,24 +226,17 @@ func UpdateIssue(ctx *middleware.Context, params martini.Params, form auth.Creat } func Comment(ctx *middleware.Context, params martini.Params) { - fmt.Println(ctx.Query("change_status")) if !ctx.Repo.IsValid { ctx.Handle(404, "issue.Comment(invalid repo):", nil) } - index, err := base.StrTo(ctx.Query("issueIndex")).Int() + index, err := base.StrTo(ctx.Query("issueIndex")).Int64() if err != nil { - ctx.Handle(404, "issue.Comment", err) + ctx.Handle(404, "issue.Comment(get index)", err) return } - content := ctx.Query("content") - if len(content) == 0 { - ctx.Redirect(fmt.Sprintf("/%s/%s/issues/%d", ctx.User.Name, ctx.Repo.Repository.Name, index)) - return - } - - issue, err := models.GetIssueByIndex(ctx.Repo.Repository.Id, int64(index)) + issue, err := models.GetIssueByIndex(ctx.Repo.Repository.Id, index) if err != nil { if err == models.ErrIssueNotExist { ctx.Handle(404, "issue.Comment", err) @@ -252,16 +246,46 @@ func Comment(ctx *middleware.Context, params martini.Params) { return } - switch params["action"] { - case "new": - if err = models.CreateComment(ctx.User.Id, issue.Id, 0, 0, content); err != nil { - ctx.Handle(500, "issue.Comment(create comment)", err) + // Check if issue owner changes the status of issue. + var newStatus string + if ctx.Repo.IsOwner || issue.PosterId == ctx.User.Id { + newStatus = ctx.Query("change_status") + } + if len(newStatus) > 0 { + if (strings.Contains(newStatus, "Reopen") && issue.IsClosed) || + (strings.Contains(newStatus, "Close") && !issue.IsClosed) { + issue.IsClosed = !issue.IsClosed + if err = models.UpdateIssue(issue); err != nil { + ctx.Handle(200, "issue.Comment(update issue status)", err) + return + } + + cmtType := models.IT_CLOSE + if !issue.IsClosed { + cmtType = models.IT_REOPEN + } + + if err = models.CreateComment(ctx.User.Id, ctx.Repo.Repository.Id, issue.Id, 0, 0, cmtType, ""); err != nil { + ctx.Handle(200, "issue.Comment(create status change comment)", err) + return + } + log.Trace("%s Issue(%d) status changed: %v", ctx.Req.RequestURI, issue.Id, !issue.IsClosed) + } + } + + content := ctx.Query("content") + if len(content) > 0 { + switch params["action"] { + case "new": + if err = models.CreateComment(ctx.User.Id, ctx.Repo.Repository.Id, issue.Id, 0, 0, models.IT_PLAIN, content); err != nil { + ctx.Handle(500, "issue.Comment(create comment)", err) + return + } + log.Trace("%s Comment created: %d", ctx.Req.RequestURI, issue.Id) + default: + ctx.Handle(404, "issue.Comment", err) return } - log.Trace("%s Comment created: %d", ctx.Req.RequestURI, issue.Id) - default: - ctx.Handle(404, "issue.Comment", err) - return } ctx.Redirect(fmt.Sprintf("/%s/%s/issues/%d", ctx.User.Name, ctx.Repo.Repository.Name, index)) diff --git a/routers/user/user.go b/routers/user/user.go index 114169e6..aeaf91c9 100644 --- a/routers/user/user.go +++ b/routers/user/user.go @@ -120,7 +120,7 @@ func SignIn(ctx *middleware.Context, form auth.LogInForm) { return } - if hasErr, ok := ctx.Data["HasError"]; ok && hasErr.(bool) { + if ctx.HasError() { ctx.HTML(200, "user/signin") return } @@ -308,17 +308,19 @@ func Issues(ctx *middleware.Context) { showRepos := make([]models.Repository, 0, len(repos)) - var closedIssueCount, createdByCount int + isShowClosed := ctx.Query("state") == "closed" + var closedIssueCount, createdByCount, allIssueCount int // Get all issues. allIssues := make([]models.Issue, 0, 5*len(repos)) for i, repo := range repos { - issues, err := models.GetIssues(0, repo.Id, posterId, 0, page, false, false, "", "") + issues, err := models.GetIssues(0, repo.Id, posterId, 0, page, isShowClosed, false, "", "") if err != nil { ctx.Handle(200, "user.Issues(get issues)", err) return } + allIssueCount += repo.NumIssues closedIssueCount += repo.NumClosedIssues // Set repository information to issues. @@ -330,12 +332,10 @@ func Issues(ctx *middleware.Context) { repos[i].NumOpenIssues = repo.NumIssues - repo.NumClosedIssues if repos[i].NumOpenIssues > 0 { showRepos = append(showRepos, repos[i]) - } } showIssues := make([]models.Issue, 0, len(allIssues)) - isShowClosed := ctx.Query("state") == "closed" ctx.Data["IsShowClosed"] = isShowClosed // Get posters and filter issues. @@ -361,9 +361,9 @@ func Issues(ctx *middleware.Context) { ctx.Data["Repos"] = showRepos ctx.Data["Issues"] = showIssues - ctx.Data["AllIssueCount"] = len(allIssues) + ctx.Data["AllIssueCount"] = allIssueCount ctx.Data["ClosedIssueCount"] = closedIssueCount - ctx.Data["OpenIssueCount"] = len(allIssues) - closedIssueCount + ctx.Data["OpenIssueCount"] = allIssueCount - closedIssueCount ctx.Data["CreatedByCount"] = createdByCount ctx.HTML(200, "issue/user") } diff --git a/templates/install.tmpl b/templates/install.tmpl index a456ac5f..20bd502d 100644 --- a/templates/install.tmpl +++ b/templates/install.tmpl @@ -3,9 +3,8 @@
    {{.CsrfTokenHtml}}

    Install Steps For First-time Run

    -
    {{.ErrorMsg}}
    -

    Gogs requires MySQL or PostgreSQL based on your choice

    +

    Gogs requires MySQL or PostgreSQL, SQLite3 only available for official binary version

    @@ -16,26 +15,28 @@
    +
    -
    - +
    +
    - +
    +
    - +
    @@ -43,7 +44,7 @@
    - +

    Recommend use INNODB engine with utf8_general_ci charset.

    @@ -59,12 +60,13 @@ +
    - +

    The file path of SQLite3 database.

    @@ -73,12 +75,11 @@

    General Settings of Gogs

    -
    - +

    The git copy of each repository is saved in this directory.

    @@ -88,16 +89,25 @@
    - +

    The user has access to visit and run Gogs.

    +
    + + +
    + +

    This affects SSH clone URL.

    +
    +
    +
    - +

    This affects HTTP/HTTPS clone URL and somewhere in e-mail.

    @@ -105,35 +115,30 @@

    Admin Account Settings

    -
    -
    - +
    -
    +
    -
    - +
    -
    +
    -
    - +

    -
    - +
    - +

    @@ -175,7 +180,7 @@
    @@ -186,7 +191,7 @@
    diff --git a/templates/issue/view.tmpl b/templates/issue/view.tmpl index 0481a33b..91e5250c 100644 --- a/templates/issue/view.tmpl +++ b/templates/issue/view.tmpl @@ -30,37 +30,37 @@
    {{range .Comments}} -
    - -
    -
    - {{.Poster.Name}} commented {{TimeSince .Created}} - - Owner -
    -
    - {{str2html .Content}} -
    -
    -
    - {{end}} - + Owner +
    +
    + {{str2html .Content}} +
    +
    +
    + {{else if eq .Type 1}} +
    + +
    + {{.Poster.Name}} Reopened this issue {{TimeSince .Created}} +
    +
    + {{else if eq .Type 2}} +
    +
    - {user.name} - Closed this - {close.time} + {{.Poster.Name}} Closed this issue {{TimeSince .Created}}
    -
    -
    - -
    - {user.name} - Reopened this - {close.time} -
    -
    --> + + {{end}} + {{end}}
    {{if .SignedUser}}
    @@ -68,8 +68,7 @@ {{.CsrfTokenHtml}}
    -
    - Content with Markdown +
    Content with Markdown
    -
    loading...
    +
    Loading...
    {{if .Issue.IsClosed}} - {{else}} + {{else}} {{end}}  
    diff --git a/web.go b/web.go index 7098717a..6aabc0e9 100644 --- a/web.go +++ b/web.go @@ -8,19 +8,16 @@ import ( "fmt" "html/template" "net/http" - "strings" "github.com/codegangsta/cli" "github.com/codegangsta/martini" "github.com/gogits/binding" - "github.com/gogits/gogs/models" "github.com/gogits/gogs/modules/auth" "github.com/gogits/gogs/modules/avatar" "github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/log" - "github.com/gogits/gogs/modules/mailer" "github.com/gogits/gogs/modules/middleware" "github.com/gogits/gogs/routers" "github.com/gogits/gogs/routers/admin" @@ -40,27 +37,6 @@ and it takes care of all the other things for you`, Flags: []cli.Flag{}, } -// globalInit is for global configuration reload-able. -func globalInit() { - base.NewConfigContext() - mailer.NewMailerContext() - models.LoadModelsConfig() - models.LoadRepoConfig() - models.NewRepoContext() - models.NewEngine() -} - -// Check run mode(Default of martini is Dev). -func checkRunMode() { - switch base.Cfg.MustValue("", "RUN_MODE") { - case "prod": - martini.Env = martini.Prod - case "test": - martini.Env = martini.Test - } - log.Info("Run Mode: %s", strings.Title(martini.Env)) -} - func newMartini() *martini.ClassicMartini { r := martini.NewRouter() m := martini.New() @@ -74,9 +50,7 @@ func newMartini() *martini.ClassicMartini { func runWeb(*cli.Context) { fmt.Println("Server is running...") - globalInit() - base.NewServices() - checkRunMode() + routers.GlobalInit() log.Info("%s %s", base.AppName, base.AppVer) m := newMartini() -- cgit v1.2.3 From 3f657607393e35c96a3519ac589778cb021b8b95 Mon Sep 17 00:00:00 2001 From: slene Date: Sun, 30 Mar 2014 10:05:39 +0800 Subject: NewLogger set to display line number --- modules/log/log.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'modules') diff --git a/modules/log/log.go b/modules/log/log.go index e1bab8ae..f0067548 100644 --- a/modules/log/log.go +++ b/modules/log/log.go @@ -15,13 +15,14 @@ var ( ) func init() { - logger = logs.NewLogger(10000) - logger.SetLogger("console", `{"level": 0}`) + NewLogger(10000, "console", `{"level": 0}`) } 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) } -- cgit v1.2.3 From 66b697a51345bfed8cc472cb894a6edc7845397f Mon Sep 17 00:00:00 2001 From: slene Date: Sun, 30 Mar 2014 10:05:54 +0800 Subject: add ShortSha template func --- modules/base/template.go | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'modules') diff --git a/modules/base/template.go b/modules/base/template.go index dca76faf..dfcae931 100644 --- a/modules/base/template.go +++ b/modules/base/template.go @@ -33,6 +33,13 @@ func List(l *list.List) chan interface{} { return c } +func ShortSha(sha1 string) string { + if len(sha1) == 40 { + return sha1[:10] + } + return sha1 +} + var mailDomains = map[string]string{ "gmail.com": "gmail.com", } @@ -72,4 +79,5 @@ var TemplateFuncs template.FuncMap = map[string]interface{}{ }, "DiffTypeToStr": DiffTypeToStr, "DiffLineTypeToStr": DiffLineTypeToStr, + "ShortSha": ShortSha, } -- cgit v1.2.3 From 105f97e61ce3d9f2bc8ce178d0ffcbf531bd91b3 Mon Sep 17 00:00:00 2001 From: slene Date: Sun, 30 Mar 2014 10:09:59 +0800 Subject: remove Context.IsValid & verify repo in middleware repo.go --- modules/middleware/context.go | 14 +++++++- modules/middleware/repo.go | 74 ++++++++++++++++++++++++++++++++++--------- 2 files changed, 72 insertions(+), 16 deletions(-) (limited to 'modules') diff --git a/modules/middleware/context.go b/modules/middleware/context.go index d81ab999..a6aa58ee 100644 --- a/modules/middleware/context.go +++ b/modules/middleware/context.go @@ -18,6 +18,7 @@ import ( "github.com/codegangsta/martini" "github.com/gogits/cache" + "github.com/gogits/git" "github.com/gogits/session" "github.com/gogits/gogs/models" @@ -41,11 +42,18 @@ type Context struct { csrfToken string Repo struct { - IsValid bool IsOwner bool IsWatching bool + IsBranch bool + IsTag bool + IsCommit bool Repository *models.Repository Owner *models.User + Commit *git.Commit + GitRepo *git.Repository + BranchName string + CommitId string + RepoLink string CloneLink struct { SSH string HTTPS string @@ -98,6 +106,10 @@ func (ctx *Context) Handle(status int, title string, err error) { ctx.HTML(status, fmt.Sprintf("status/%d", status)) } +func (ctx *Context) Debug(msg string, args ...interface{}) { + log.Debug(msg, args...) +} + func (ctx *Context) GetCookie(name string) string { cookie, err := ctx.Req.Cookie(name) if err != nil { diff --git a/modules/middleware/repo.go b/modules/middleware/repo.go index 54b735af..d1b68b05 100644 --- a/modules/middleware/repo.go +++ b/modules/middleware/repo.go @@ -11,6 +11,8 @@ import ( "github.com/codegangsta/martini" + "github.com/gogits/git" + "github.com/gogits/gogs/models" "github.com/gogits/gogs/modules/base" ) @@ -25,8 +27,12 @@ func RepoAssignment(redirect bool) martini.Handler { err error ) + userName := params["username"] + repoName := params["reponame"] + branchName := params["branchname"] + // get repository owner - ctx.Repo.IsOwner = ctx.IsSigned && ctx.User.LowerName == strings.ToLower(params["username"]) + ctx.Repo.IsOwner = ctx.IsSigned && ctx.User.LowerName == strings.ToLower(userName) if !ctx.Repo.IsOwner { user, err = models.GetUserByName(params["username"]) @@ -51,10 +57,8 @@ func RepoAssignment(redirect bool) martini.Handler { return } - ctx.Repo.Owner = user - // get repository - repo, err := models.GetRepositoryByName(user.Id, params["reponame"]) + repo, err := models.GetRepositoryByName(user.Id, repoName) if err != nil { if err == models.ErrRepoNotExist { ctx.Handle(404, "RepoAssignment", err) @@ -62,29 +66,69 @@ func RepoAssignment(redirect bool) martini.Handler { ctx.Redirect("/") return } - ctx.Handle(200, "RepoAssignment", err) + ctx.Handle(404, "RepoAssignment", err) + return + } + ctx.Repo.Repository = repo + + gitRepo, err := git.OpenRepository(models.RepoPath(userName, repoName)) + if err != nil { + ctx.Handle(404, "RepoAssignment Invalid repo", err) return } + ctx.Repo.GitRepo = gitRepo + + detect: + if len(branchName) > 0 { + // TODO check tag + if models.IsBranchExist(user.Name, repoName, branchName) { + ctx.Repo.IsBranch = true + ctx.Repo.BranchName = branchName + + ctx.Repo.Commit, err = gitRepo.GetCommitOfBranch(branchName) + if err != nil { + ctx.Handle(404, "RepoAssignment invalid branch", nil) + return + } + + ctx.Repo.CommitId = ctx.Repo.Commit.Oid.String() + + } else if len(branchName) == 40 { + ctx.Repo.IsCommit = true + ctx.Repo.CommitId = branchName + ctx.Repo.BranchName = branchName + + ctx.Repo.Commit, err = gitRepo.GetCommit(branchName) + if err != nil { + ctx.Handle(404, "RepoAssignment invalid commit", nil) + return + } + } else { + ctx.Handle(404, "RepoAssignment invalid repo", nil) + return + } + + } else { + branchName = "master" + goto detect + } - ctx.Repo.IsValid = true - if ctx.User != nil { + if ctx.IsSigned { ctx.Repo.IsWatching = models.IsWatching(ctx.User.Id, repo.Id) } - ctx.Repo.Repository = repo + + ctx.Repo.Owner = user ctx.Repo.CloneLink.SSH = fmt.Sprintf("%s@%s:%s/%s.git", base.RunUser, base.Domain, user.LowerName, repo.LowerName) ctx.Repo.CloneLink.HTTPS = fmt.Sprintf("%s%s/%s.git", base.AppUrl, user.LowerName, repo.LowerName) + ctx.Repo.RepoLink = "/" + user.Name + "/" + repo.Name - if len(params["branchname"]) == 0 { - params["branchname"] = "master" - } - ctx.Data["Branchname"] = params["branchname"] - - ctx.Data["IsRepositoryValid"] = true + ctx.Data["BranchName"] = ctx.Repo.BranchName + ctx.Data["CommitId"] = ctx.Repo.CommitId ctx.Data["Repository"] = repo ctx.Data["Owner"] = user ctx.Data["Title"] = user.Name + "/" + repo.Name ctx.Data["CloneLink"] = ctx.Repo.CloneLink - ctx.Data["RepositoryLink"] = ctx.Data["Title"] + ctx.Data["RepoLink"] = ctx.Repo.RepoLink ctx.Data["IsRepositoryOwner"] = ctx.Repo.IsOwner ctx.Data["IsRepositoryWatching"] = ctx.Repo.IsWatching } -- cgit v1.2.3 From 578d981d7e196728dc0685f62a211383d4c808fa Mon Sep 17 00:00:00 2001 From: slene Date: Sun, 30 Mar 2014 11:38:41 +0800 Subject: display bare repo page --- modules/middleware/repo.go | 32 ++++++++++++-------- routers/repo/repo.go | 10 ------- templates/repo/single.tmpl | 4 --- templates/repo/single_bare.tmpl | 66 +++++++++++++++++++++++------------------ 4 files changed, 57 insertions(+), 55 deletions(-) (limited to 'modules') diff --git a/modules/middleware/repo.go b/modules/middleware/repo.go index d1b68b05..deb28286 100644 --- a/modules/middleware/repo.go +++ b/modules/middleware/repo.go @@ -73,11 +73,30 @@ func RepoAssignment(redirect bool) martini.Handler { gitRepo, err := git.OpenRepository(models.RepoPath(userName, repoName)) if err != nil { - ctx.Handle(404, "RepoAssignment Invalid repo", err) + ctx.Handle(404, "RepoAssignment Invalid repo "+models.RepoPath(userName, repoName), err) return } ctx.Repo.GitRepo = gitRepo + ctx.Repo.Owner = user + ctx.Repo.RepoLink = "/" + user.Name + "/" + repo.Name + + ctx.Data["Title"] = user.Name + "/" + repo.Name + ctx.Data["Repository"] = repo + ctx.Data["Owner"] = user + ctx.Data["RepoLink"] = ctx.Repo.RepoLink + ctx.Data["IsRepositoryOwner"] = ctx.Repo.IsOwner + + ctx.Repo.CloneLink.SSH = fmt.Sprintf("%s@%s:%s/%s.git", base.RunUser, base.Domain, user.LowerName, repo.LowerName) + ctx.Repo.CloneLink.HTTPS = fmt.Sprintf("%s%s/%s.git", base.AppUrl, user.LowerName, repo.LowerName) + ctx.Data["CloneLink"] = ctx.Repo.CloneLink + + if repo.IsBare { + ctx.Data["IsBareRepo"] = true + ctx.HTML(200, "repo/single_bare") + return + } + detect: if len(branchName) > 0 { // TODO check tag @@ -117,19 +136,8 @@ func RepoAssignment(redirect bool) martini.Handler { ctx.Repo.IsWatching = models.IsWatching(ctx.User.Id, repo.Id) } - ctx.Repo.Owner = user - ctx.Repo.CloneLink.SSH = fmt.Sprintf("%s@%s:%s/%s.git", base.RunUser, base.Domain, user.LowerName, repo.LowerName) - ctx.Repo.CloneLink.HTTPS = fmt.Sprintf("%s%s/%s.git", base.AppUrl, user.LowerName, repo.LowerName) - ctx.Repo.RepoLink = "/" + user.Name + "/" + repo.Name - ctx.Data["BranchName"] = ctx.Repo.BranchName ctx.Data["CommitId"] = ctx.Repo.CommitId - ctx.Data["Repository"] = repo - ctx.Data["Owner"] = user - ctx.Data["Title"] = user.Name + "/" + repo.Name - ctx.Data["CloneLink"] = ctx.Repo.CloneLink - ctx.Data["RepoLink"] = ctx.Repo.RepoLink - ctx.Data["IsRepositoryOwner"] = ctx.Repo.IsOwner ctx.Data["IsRepositoryWatching"] = ctx.Repo.IsWatching } } diff --git a/routers/repo/repo.go b/routers/repo/repo.go index c9c9af1e..27c806a3 100644 --- a/routers/repo/repo.go +++ b/routers/repo/repo.go @@ -77,10 +77,6 @@ func Single(ctx *middleware.Context, params martini.Params) { if err != nil { ctx.Handle(404, "repo.Single(GetBranches)", err) return - } else if ctx.Repo.Repository.IsBare { - ctx.Data["IsBareRepo"] = true - ctx.HTML(200, "repo/single") - return } ctx.Data["Branches"] = brs @@ -264,12 +260,6 @@ func Setting(ctx *middleware.Context, params martini.Params) { ctx.Data["IsRepoToolbarSetting"] = true - if ctx.Repo.Repository.IsBare { - ctx.Data["IsBareRepo"] = true - ctx.HTML(200, "repo/setting") - return - } - var title string if t, ok := ctx.Data["Title"].(string); ok { title = t diff --git a/templates/repo/single.tmpl b/templates/repo/single.tmpl index abaa4e89..0bf7b0aa 100644 --- a/templates/repo/single.tmpl +++ b/templates/repo/single.tmpl @@ -4,9 +4,6 @@ {{template "repo/toolbar" .}}
    - {{if .IsBareRepo}} - {{template "repo/single_bare" .}} - {{else}}
    {{ $n := len .Treenames}} {{if not .IsFile}}{{end}} @@ -38,7 +35,6 @@ {{else}} {{template "repo/single_list" .}} {{end}} - {{end}}
    {{template "base/footer" .}} diff --git a/templates/repo/single_bare.tmpl b/templates/repo/single_bare.tmpl index ed182ad2..fe0e3aa3 100644 --- a/templates/repo/single_bare.tmpl +++ b/templates/repo/single_bare.tmpl @@ -1,31 +1,39 @@ -
    -
    -

    Quick Guide

    -
    -
    -

    Clone this repository

    -
    - - - - - - - - +{{template "base/head" .}} +{{template "base/navbar" .}} +{{template "repo/nav" .}} +
    +
    +
    +
    +

    Quick Guide

    +
    +
    +

    Clone this repository

    +
    + + + + + + + + +
    +

    We recommend every repository include a README, LICENSE, and .gitignore.

    +
    +

    Create a new repository on the command line

    +
    touch README.md
    +        git init
    +        git add README.md
    +        git commit -m "first commit"
    +        git remote add origin 
    +        git push -u origin master
    +
    +

    Push an existing repository from the command line

    +
    git remote add origin 
    +        git push -u origin master
    +
    -

    We recommend every repository include a README, LICENSE, and .gitignore.

    -
    -

    Create a new repository on the command line

    -
    touch README.md
    -git init
    -git add README.md
    -git commit -m "first commit"
    -git remote add origin 
    -git push -u origin master
    -
    -

    Push an existing repository from the command line

    -
    git remote add origin 
    -git push -u origin master
    -
    \ No newline at end of file +
    +{{template "base/footer" .}} -- cgit v1.2.3 From d6c9e3413a982fd64a74e774d4a2b8157f39f299 Mon Sep 17 00:00:00 2001 From: slene Date: Sun, 30 Mar 2014 13:30:17 +0800 Subject: fix display bare repo --- modules/middleware/repo.go | 88 ++++++++++++++++++++++++----------------- routers/repo/repo.go | 1 + templates/repo/single_bare.tmpl | 13 +++--- templates/repo/toolbar.tmpl | 2 +- web.go | 13 +++--- 5 files changed, 68 insertions(+), 49 deletions(-) (limited to 'modules') diff --git a/modules/middleware/repo.go b/modules/middleware/repo.go index deb28286..559e90c0 100644 --- a/modules/middleware/repo.go +++ b/modules/middleware/repo.go @@ -17,10 +17,20 @@ import ( "github.com/gogits/gogs/modules/base" ) -func RepoAssignment(redirect bool) martini.Handler { +func RepoAssignment(redirect bool, args ...bool) martini.Handler { return func(ctx *Context, params martini.Params) { - // assign false first - ctx.Data["IsRepositoryValid"] = false + // valid brachname + var validBranch bool + // display bare quick start if it is a bare repo + var displayBare bool + + if len(args) >= 1 { + validBranch = args[0] + } + + if len(args) >= 2 { + displayBare = args[1] + } var ( user *models.User @@ -71,6 +81,8 @@ func RepoAssignment(redirect bool) martini.Handler { } ctx.Repo.Repository = repo + ctx.Data["IsBareRepo"] = ctx.Repo.Repository.IsBare + gitRepo, err := git.OpenRepository(models.RepoPath(userName, repoName)) if err != nil { ctx.Handle(404, "RepoAssignment Invalid repo "+models.RepoPath(userName, repoName), err) @@ -86,50 +98,54 @@ func RepoAssignment(redirect bool) martini.Handler { ctx.Data["Owner"] = user ctx.Data["RepoLink"] = ctx.Repo.RepoLink ctx.Data["IsRepositoryOwner"] = ctx.Repo.IsOwner + ctx.Data["BranchName"] = "" ctx.Repo.CloneLink.SSH = fmt.Sprintf("%s@%s:%s/%s.git", base.RunUser, base.Domain, user.LowerName, repo.LowerName) ctx.Repo.CloneLink.HTTPS = fmt.Sprintf("%s%s/%s.git", base.AppUrl, user.LowerName, repo.LowerName) ctx.Data["CloneLink"] = ctx.Repo.CloneLink - if repo.IsBare { - ctx.Data["IsBareRepo"] = true - ctx.HTML(200, "repo/single_bare") - return - } - - detect: - if len(branchName) > 0 { - // TODO check tag - if models.IsBranchExist(user.Name, repoName, branchName) { - ctx.Repo.IsBranch = true - ctx.Repo.BranchName = branchName - - ctx.Repo.Commit, err = gitRepo.GetCommitOfBranch(branchName) - if err != nil { - ctx.Handle(404, "RepoAssignment invalid branch", nil) + // when repo is bare, not valid branch + if !ctx.Repo.Repository.IsBare && validBranch { + detect: + if len(branchName) > 0 { + // TODO check tag + if models.IsBranchExist(user.Name, repoName, branchName) { + ctx.Repo.IsBranch = true + ctx.Repo.BranchName = branchName + + ctx.Repo.Commit, err = gitRepo.GetCommitOfBranch(branchName) + if err != nil { + ctx.Handle(404, "RepoAssignment invalid branch", nil) + return + } + + ctx.Repo.CommitId = ctx.Repo.Commit.Oid.String() + + } else if len(branchName) == 40 { + ctx.Repo.IsCommit = true + ctx.Repo.CommitId = branchName + ctx.Repo.BranchName = branchName + + ctx.Repo.Commit, err = gitRepo.GetCommit(branchName) + if err != nil { + ctx.Handle(404, "RepoAssignment invalid commit", nil) + return + } + } else { + ctx.Handle(404, "RepoAssignment invalid repo", nil) return } - ctx.Repo.CommitId = ctx.Repo.Commit.Oid.String() - - } else if len(branchName) == 40 { - ctx.Repo.IsCommit = true - ctx.Repo.CommitId = branchName - ctx.Repo.BranchName = branchName - - ctx.Repo.Commit, err = gitRepo.GetCommit(branchName) - if err != nil { - ctx.Handle(404, "RepoAssignment invalid commit", nil) - return - } } else { - ctx.Handle(404, "RepoAssignment invalid repo", nil) - return + branchName = "master" + goto detect } + } - } else { - branchName = "master" - goto detect + // repo is bare and display enable + if displayBare && ctx.Repo.Repository.IsBare { + ctx.HTML(200, "repo/single_bare") + return } if ctx.IsSigned { diff --git a/routers/repo/repo.go b/routers/repo/repo.go index 27c806a3..5b0a165d 100644 --- a/routers/repo/repo.go +++ b/routers/repo/repo.go @@ -78,6 +78,7 @@ func Single(ctx *middleware.Context, params martini.Params) { ctx.Handle(404, "repo.Single(GetBranches)", err) return } + ctx.Data["Branches"] = brs isViewBranch := ctx.Repo.IsBranch diff --git a/templates/repo/single_bare.tmpl b/templates/repo/single_bare.tmpl index fe0e3aa3..035e78e8 100644 --- a/templates/repo/single_bare.tmpl +++ b/templates/repo/single_bare.tmpl @@ -1,6 +1,7 @@ {{template "base/head" .}} {{template "base/navbar" .}} {{template "repo/nav" .}} +{{template "repo/toolbar" .}}
    @@ -23,15 +24,15 @@

    Create a new repository on the command line

    touch README.md
    -        git init
    -        git add README.md
    -        git commit -m "first commit"
    -        git remote add origin 
    -        git push -u origin master
    +git init +git add README.md +git commit -m "first commit" +git remote add origin +git push -u origin master

    Push an existing repository from the command line

    git remote add origin 
    -        git push -u origin master
    +git push -u origin master
    diff --git a/templates/repo/toolbar.tmpl b/templates/repo/toolbar.tmpl index 3c7c8a50..542f8fd8 100644 --- a/templates/repo/toolbar.tmpl +++ b/templates/repo/toolbar.tmpl @@ -3,7 +3,7 @@
    -{{template "base/footer" .}} \ No newline at end of file +{{template "base/footer" .}} -- cgit v1.2.3 From b1627672f9b45047976f498fe618995361e9ff35 Mon Sep 17 00:00:00 2001 From: slene Date: Sun, 30 Mar 2014 17:09:19 +0800 Subject: fix link --- modules/middleware/repo.go | 3 +++ templates/repo/single.tmpl | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) (limited to 'modules') diff --git a/modules/middleware/repo.go b/modules/middleware/repo.go index 559e90c0..6912cd83 100644 --- a/modules/middleware/repo.go +++ b/modules/middleware/repo.go @@ -140,6 +140,9 @@ func RepoAssignment(redirect bool, args ...bool) martini.Handler { branchName = "master" goto detect } + + ctx.Data["IsBranch"] = ctx.Repo.IsBranch + ctx.Data["IsCommit"] = ctx.Repo.IsCommit } // repo is bare and display enable diff --git a/templates/repo/single.tmpl b/templates/repo/single.tmpl index 0bf7b0aa..7ee6b0ca 100644 --- a/templates/repo/single.tmpl +++ b/templates/repo/single.tmpl @@ -8,7 +8,7 @@ {{ $n := len .Treenames}} {{if not .IsFile}}{{end}}