From 4f2f3c285717eff7a2f4ae2b79fbb0809e786dc8 Mon Sep 17 00:00:00 2001 From: Unknown Date: Thu, 5 Jun 2014 22:07:35 -0400 Subject: Code convention --- cmd/web.go | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) (limited to 'cmd') diff --git a/cmd/web.go b/cmd/web.go index dc4daca0..30db037a 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -89,9 +89,11 @@ func runWeb(*cli.Context) { m.Get("/", ignSignIn, routers.Home) m.Get("/install", bindIgnErr(auth.InstallForm{}), routers.Install) m.Post("/install", bindIgnErr(auth.InstallForm{}), routers.InstallPost) - m.Get("/issues", reqSignIn, user.Issues) - m.Get("/pulls", reqSignIn, user.Pulls) - m.Get("/stars", reqSignIn, user.Stars) + m.Group("", func(r martini.Router) { + r.Get("/issues", user.Issues) + r.Get("/pulls", user.Pulls) + r.Get("/stars", user.Stars) + }, reqSignIn) m.Group("/api", func(r martini.Router) { m.Group("/v1", func(r martini.Router) { -- cgit v1.2.3 From 4fcbf553aa9b451bc461e09a98711966668e1889 Mon Sep 17 00:00:00 2001 From: FuXiaoHei Date: Sat, 7 Jun 2014 13:27:24 +0800 Subject: organisation main page ui --- cmd/web.go | 5 +++ public/css/gogs.css | 94 +++++++++++++++++++++++++++++++++++++++++++++++++- routers/org/org.go | 11 ++++++ templates/org/org.tmpl | 85 +++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 194 insertions(+), 1 deletion(-) create mode 100644 routers/org/org.go create mode 100644 templates/org/org.tmpl (limited to 'cmd') diff --git a/cmd/web.go b/cmd/web.go index 30db037a..2b14b077 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -27,6 +27,7 @@ import ( "github.com/gogits/gogs/routers/admin" "github.com/gogits/gogs/routers/api/v1" "github.com/gogits/gogs/routers/dev" + "github.com/gogits/gogs/routers/org" "github.com/gogits/gogs/routers/repo" "github.com/gogits/gogs/routers/user" ) @@ -186,6 +187,10 @@ func runWeb(*cli.Context) { reqOwner := middleware.RequireOwner() + m.Group("/o", func(r martini.Router) { + r.Get("/:org", org.Organization) + }) + m.Group("/:username/:reponame", func(r martini.Router) { r.Get("/settings", repo.Setting) r.Post("/settings", bindIgnErr(auth.RepoSettingForm{}), repo.SettingPost) diff --git a/public/css/gogs.css b/public/css/gogs.css index 79fd4bf9..09249811 100755 --- a/public/css/gogs.css +++ b/public/css/gogs.css @@ -1643,7 +1643,7 @@ html, body { vertical-align: top; } -#label-color-change-ipt2{ +#label-color-change-ipt2 { margin-top: 1px; } @@ -1814,4 +1814,96 @@ html, body { #release-preview { margin: 6px 0; +} + +/* organization */ + +#body-nav.org-nav { + height: 140px; + padding: 16px 0; +} + +.org-nav .org-logo { + margin-right: 16px; + width: 100px; + height: 100px; +} + +.org-nav .org-name { + margin-top: 0; +} + +.org-description { + font-size: 16px; +} + +.org-meta li, .org-meta li a, .org-repo-update, .org-repo-status, .org-team-meta { + color: #888; +} + +.org-meta li { + margin-right: 12px; +} + +.org-meta li a:hover { + text-decoration: underline; +} + +.org-meta .fa { + margin-left: 0; +} + +.org-sidebar { + margin-top: -100px; +} + +.org-panel .panel-heading { + font-size: 18px; +} + +.org-repo-status { + font-family: Verdana, Arial, Helvetica, sans-serif; +} + +.org-repo-item { + border-bottom: 1px solid #DDD; + padding-bottom: 18px; +} + +.org-member img { + width: 60px; + height: 60px; + border-radius: 4px; +} + +.org-member { + display: inline-block; + padding: 2px; +} + +.org-team-name { + font-size: 15px; + margin-bottom: 0; + color: #444; +} + +.org-team { + border-bottom: 1px solid #DDD; + margin-bottom: 12px; +} + +.org-team:last-child { + border: none; +} + +.org-team a { + display: block; +} + +.org-team a:hover { + text-decoration: none; +} + +.org-team a:hover .org-team-name { + color: #0079bc !important; } \ No newline at end of file diff --git a/routers/org/org.go b/routers/org/org.go new file mode 100644 index 00000000..1c02e773 --- /dev/null +++ b/routers/org/org.go @@ -0,0 +1,11 @@ +package org + +import ( + "github.com/go-martini/martini" + "github.com/gogits/gogs/modules/middleware" +) + +func Organization(ctx *middleware.Context, params martini.Params) { + ctx.Data["Title"] = "Organization Name" + params["org"] + ctx.HTML(200, "org/org") +} diff --git a/templates/org/org.tmpl b/templates/org/org.tmpl new file mode 100644 index 00000000..872e50be --- /dev/null +++ b/templates/org/org.tmpl @@ -0,0 +1,85 @@ +{{template "base/head" .}} +{{template "base/navbar" .}} +
+
+
+ +
+

Organization Name

+

Gogs(Go Git Service) is a Self Hosted Git Service in the Go Programming Language.

+ +
+
+
+
+
+
+
+
+ +
+
+
+
+
+
    +
  • Go
  • +
  • 6
  • +
  • 2
  • +
+
+

gogs

+

Gogs(Go Git Service) is a Self Hosted Git Service in the Go Programming Language.

+

Updated 17 hours ago

+
+
+
+
    +
  • Go
  • +
  • 6
  • +
  • 2
  • +
+
+

gogs

+

Gogs(Go Git Service) is a Self Hosted Git Service in the Go Programming Language.

+

Updated 17 hours ago

+
+
+
+ +
+
+{{template "base/footer" .}} -- cgit v1.2.3 From a3e1383cac3dfa2a71b04b47a295e9836fcb0d50 Mon Sep 17 00:00:00 2001 From: Unknown Date: Tue, 10 Jun 2014 19:11:53 -0400 Subject: Add gogs fix location command --- README.md | 2 +- README_ZH.md | 2 +- cmd/fix.go | 154 +++++++++++++++++++++++++++++++++++++++++---- cmd/serve.go | 1 - gogs.go | 6 +- models/models.go | 5 +- models/publickey.go | 14 ++--- models/repo.go | 6 +- modules/setting/setting.go | 11 +++- templates/VERSION | 2 +- 10 files changed, 171 insertions(+), 32 deletions(-) (limited to 'cmd') diff --git a/README.md b/README.md index 88870819..d34aa5a6 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.4.2 Alpha +##### Current version: 0.4.3 Alpha ### NOTICES diff --git a/README_ZH.md b/README_ZH.md index 84af15a6..ebffa33e 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.4.2 Alpha +##### 当前版本:0.4.3 Alpha ## 开发目的 diff --git a/cmd/fix.go b/cmd/fix.go index 3c2278ba..95ab3ae6 100644 --- a/cmd/fix.go +++ b/cmd/fix.go @@ -5,10 +5,16 @@ package cmd import ( + "bufio" "fmt" + "io" + "io/ioutil" "os" + "path" + "strings" "github.com/codegangsta/cli" + "github.com/gogits/gogs/models" "github.com/gogits/gogs/modules/setting" ) @@ -16,28 +22,152 @@ import ( var CmdFix = cli.Command{ Name: "fix", Usage: "This command for upgrade from old version", - Description: `Fix provide upgrade from old version`, Action: runFix, + Subcommands: fixCommands, Flags: []cli.Flag{}, } -func runFix(k *cli.Context) { - workDir, _ := setting.WorkDir() - newLogger(workDir) +func runFix(ctx *cli.Context) { +} - setting.NewConfigContext() - models.LoadModelsConfig() +var fixCommands = []cli.Command{ + { + Name: "location", + Usage: "Change Gogs app location", + Description: `Command location fixes location change of Gogs + +gogs fix location +`, + Action: runFixLocation, + }, +} + +// rewriteAuthorizedKeys replaces old Gogs path to the new one. +func rewriteAuthorizedKeys(sshPath, oldPath, newPath string) error { + fr, err := os.Open(sshPath) + if err != nil { + return err + } + defer fr.Close() + + tmpPath := sshPath + ".tmp" + fw, err := os.Create(tmpPath) + if err != nil { + return err + } + defer fw.Close() + + oldPath = "command=\"" + oldPath + " serv" + newPath = "command=\"" + newPath + " serv" + buf := bufio.NewReader(fr) + for { + line, errRead := buf.ReadString('\n') + line = strings.TrimSpace(line) + + if errRead != nil { + if errRead != io.EOF { + return errRead + } + + // Reached end of file, if nothing to read then break, + // otherwise handle the last line. + if len(line) == 0 { + break + } + } + + // Still finding the line, copy the line that currently read. + if _, err = fw.WriteString(strings.Replace(line, oldPath, newPath, 1) + "\n"); err != nil { + return err + } - if models.UseSQLite3 { - os.Chdir(workDir) + if errRead == io.EOF { + break + } } - models.SetEngine() + if err = os.Remove(sshPath); err != nil { + return err + } + return os.Rename(tmpPath, sshPath) +} + +func rewriteUpdateHook(path, appPath string) error { + rp := strings.NewReplacer("\\", "/", " ", "\\ ") + if err := ioutil.WriteFile(path, []byte(fmt.Sprintf(models.TPL_UPDATE_HOOK, + setting.ScriptType, rp.Replace(appPath))), os.ModePerm); err != nil { + return err + } + return nil +} - err := models.Fix() +func walkDir(rootPath, recPath, appPath string, depth int) error { + depth++ + if depth > 3 { + return nil + } else if depth == 3 { + if err := rewriteUpdateHook(path.Join(rootPath, "hooks/update"), appPath); err != nil { + return err + } + } + + dir, err := os.Open(rootPath) + if err != nil { + return err + } + defer dir.Close() + + fis, err := dir.Readdir(0) if err != nil { + return err + } + + for _, fi := range fis { + if strings.Contains(fi.Name(), ".DS_Store") { + continue + } + + relPath := path.Join(recPath, fi.Name()) + curPath := path.Join(rootPath, fi.Name()) + if fi.IsDir() { + if err = walkDir(curPath, relPath, appPath, depth); err != nil { + return err + } + } + } + return nil +} + +func runFixLocation(ctx *cli.Context) { + if len(ctx.Args()) != 1 { + fmt.Println("Incorrect arguments number, expect 1") + os.Exit(2) + } + + execPath, _ := setting.ExecPath() + + oldPath := ctx.Args().First() + fmt.Printf("Old location: %s\n", oldPath) + fmt.Println("This command should be executed in the new Gogs path") + fmt.Printf("Do you want to change Gogs app path from old location to:\n") + fmt.Printf("-> %s?\n", execPath) + fmt.Print("Press to continue, use to exit.") + fmt.Scanln() + + // Fix in authorized_keys file. + sshPath := path.Join(models.SshPath, "authorized_keys") + fmt.Printf("Fixing pathes in file: %s\n", sshPath) + if err := rewriteAuthorizedKeys(sshPath, oldPath, execPath); err != nil { + fmt.Println(err) + os.Exit(1) + } + + // Fix position in gogs-repositories. + setting.NewConfigContext() + fmt.Printf("Fixing pathes in repositories: %s\n", setting.RepoRootPath) + if err := walkDir(setting.RepoRootPath, "", execPath, 0); err != nil { fmt.Println(err) - } else { - fmt.Println("Fix successfully!") + os.Exit(1) } + fmt.Println("Fix position finished!") } diff --git a/cmd/serve.go b/cmd/serve.go index 302f8568..3a17bf9f 100644 --- a/cmd/serve.go +++ b/cmd/serve.go @@ -36,7 +36,6 @@ func newLogger(logPath string) { } qlog.SetOutput(f) - //qlog.SetOutputLevel(qlog.Ldebug) qlog.Info("Start logging serv...") } diff --git a/gogs.go b/gogs.go index 8a633a30..41a71c72 100644 --- a/gogs.go +++ b/gogs.go @@ -17,7 +17,7 @@ import ( "github.com/gogits/gogs/modules/setting" ) -const APP_VER = "0.4.2.0608 Alpha" +const APP_VER = "0.4.3.0610 Alpha" func init() { runtime.GOMAXPROCS(runtime.NumCPU()) @@ -31,10 +31,10 @@ func main() { app.Version = APP_VER app.Commands = []cli.Command{ cmd.CmdWeb, - // cmd.CmdFix, - cmd.CmdDump, cmd.CmdServ, cmd.CmdUpdate, + cmd.CmdFix, + cmd.CmdDump, } app.Flags = append(app.Flags, []cli.Flag{}...) app.Run(os.Args) diff --git a/models/models.go b/models/models.go index dca77e00..a59c0517 100644 --- a/models/models.go +++ b/models/models.go @@ -46,7 +46,9 @@ func LoadModelsConfig() { DbCfg.Host = setting.Cfg.MustValue("database", "HOST") DbCfg.Name = setting.Cfg.MustValue("database", "NAME") DbCfg.User = setting.Cfg.MustValue("database", "USER") - DbCfg.Pwd = setting.Cfg.MustValue("database", "PASSWD") + if len(DbCfg.Pwd) == 0 { + DbCfg.Pwd = setting.Cfg.MustValue("database", "PASSWD") + } DbCfg.SslMode = setting.Cfg.MustValue("database", "SSL_MODE") DbCfg.Path = setting.Cfg.MustValue("database", "PATH", "data/gogs.db") } @@ -67,7 +69,6 @@ func NewTestEngine(x *xorm.Engine) (err error) { } cnnstr := fmt.Sprintf("user=%s password=%s host=%s port=%s dbname=%s sslmode=%s", DbCfg.User, DbCfg.Pwd, host, port, DbCfg.Name, DbCfg.SslMode) - //fmt.Println(cnnstr) x, err = xorm.NewEngine("postgres", cnnstr) case "sqlite3": if !EnableSQLite3 { diff --git a/models/publickey.go b/models/publickey.go index 556db964..76dc0cc7 100644 --- a/models/publickey.go +++ b/models/publickey.go @@ -37,7 +37,7 @@ var ( var sshOpLocker = sync.Mutex{} var ( - sshPath string // SSH directory. + SshPath string // SSH directory. appPath string // Execution(binary) path. ) @@ -67,9 +67,9 @@ func init() { } // Determine and create .ssh path. - sshPath = filepath.Join(homeDir(), ".ssh") - if err = os.MkdirAll(sshPath, os.ModePerm); err != nil { - qlog.Fatalf("publickey.init(fail to create sshPath(%s)): %v\n", sshPath, err) + SshPath = filepath.Join(homeDir(), ".ssh") + if err = os.MkdirAll(SshPath, os.ModePerm); err != nil { + qlog.Fatalf("publickey.init(fail to create SshPath(%s)): %v\n", SshPath, err) } } @@ -94,7 +94,7 @@ func saveAuthorizedKeyFile(key *PublicKey) error { sshOpLocker.Lock() defer sshOpLocker.Unlock() - fpath := filepath.Join(sshPath, "authorized_keys") + fpath := filepath.Join(SshPath, "authorized_keys") f, err := os.OpenFile(fpath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600) if err != nil { return err @@ -216,8 +216,8 @@ func DeletePublicKey(key *PublicKey) error { return err } - fpath := filepath.Join(sshPath, "authorized_keys") - tmpPath := filepath.Join(sshPath, "authorized_keys.tmp") + fpath := filepath.Join(SshPath, "authorized_keys") + tmpPath := filepath.Join(SshPath, "authorized_keys.tmp") log.Trace("publickey.DeletePublicKey(authorized_keys): %s", fpath) if err = rewriteAuthorizedKeys(key, fpath, tmpPath); err != nil { diff --git a/models/repo.go b/models/repo.go index deb25b2a..3eca78c4 100644 --- a/models/repo.go +++ b/models/repo.go @@ -28,6 +28,10 @@ import ( "github.com/gogits/gogs/modules/setting" ) +const ( + TPL_UPDATE_HOOK = "#!/usr/bin/env %s\n%s update $1 $2 $3\n" +) + var ( ErrRepoAlreadyExist = errors.New("Repository already exist") ErrRepoNotExist = errors.New("Repository does not exist") @@ -450,7 +454,7 @@ func initRepository(f string, user *User, repo *Repository, initReadme bool, rep rp := strings.NewReplacer("\\", "/", " ", "\\ ") // hook/post-update if err := createHookUpdate(filepath.Join(repoPath, "hooks", "update"), - fmt.Sprintf("#!/usr/bin/env %s\n%s update $1 $2 $3\n", setting.ScriptType, + fmt.Sprintf(TPL_UPDATE_HOOK, setting.ScriptType, rp.Replace(appPath))); err != nil { return err } diff --git a/modules/setting/setting.go b/modules/setting/setting.go index 35c91651..73ec8ddd 100644 --- a/modules/setting/setting.go +++ b/modules/setting/setting.go @@ -90,8 +90,7 @@ var ( RunUser string ) -// WorkDir returns absolute path of work directory. -func WorkDir() (string, error) { +func ExecPath() (string, error) { file, err := exec.LookPath(os.Args[0]) if err != nil { return "", err @@ -100,7 +99,13 @@ func WorkDir() (string, error) { if err != nil { return "", err } - return path.Dir(strings.Replace(p, "\\", "/", -1)), nil + return p, nil +} + +// WorkDir returns absolute path of work directory. +func WorkDir() (string, error) { + execPath, err := ExecPath() + return path.Dir(strings.Replace(execPath, "\\", "/", -1)), err } // NewConfigContext initializes configuration context. diff --git a/templates/VERSION b/templates/VERSION index cf75962a..dc83da78 100644 --- a/templates/VERSION +++ b/templates/VERSION @@ -1 +1 @@ -0.4.2.0608 Alpha \ No newline at end of file +0.4.3.0610 Alpha \ No newline at end of file -- cgit v1.2.3 From e07674bff19dcc321a1611a3598d69c418ac8642 Mon Sep 17 00:00:00 2001 From: Unknown Date: Thu, 12 Jun 2014 17:47:23 -0400 Subject: Support edit release and save as draft --- README.md | 2 +- README_ZH.md | 2 +- cmd/web.go | 6 +- gogs.go | 2 +- models/release.go | 116 ++++++++++++++++++++++++++++--------- models/repo.go | 2 +- modules/auth/repo.go | 23 ++++++++ modules/middleware/repo.go | 8 +-- routers/repo/release.go | 136 +++++++++++++++++++++++++++++++------------- templates/VERSION | 2 +- templates/release/edit.tmpl | 70 +++++++++++++++++++++++ templates/release/list.tmpl | 12 +++- templates/release/new.tmpl | 2 +- 13 files changed, 299 insertions(+), 84 deletions(-) create mode 100644 templates/release/edit.tmpl (limited to 'cmd') diff --git a/README.md b/README.md index d34aa5a6..bd480090 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.4.3 Alpha +##### Current version: 0.4.4 Alpha ### NOTICES diff --git a/README_ZH.md b/README_ZH.md index ebffa33e..5f57d8a6 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.4.3 Alpha +##### 当前版本:0.4.4 Alpha ## 开发目的 diff --git a/cmd/web.go b/cmd/web.go index 2b14b077..27b3d8cf 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -228,11 +228,13 @@ func runWeb(*cli.Context) { }) r.Post("/comment/:action", repo.Comment) - r.Get("/releases/new", repo.ReleasesNew) + r.Get("/releases/new", repo.NewRelease) + r.Get("/releases/edit/:tagname", repo.EditRelease) }, reqSignIn, middleware.RepoAssignment(true)) m.Group("/:username/:reponame", func(r martini.Router) { - r.Post("/releases/new", bindIgnErr(auth.NewReleaseForm{}), repo.ReleasesNewPost) + r.Post("/releases/new", bindIgnErr(auth.NewReleaseForm{}), repo.NewReleasePost) + r.Post("/releases/edit/:tagname", bindIgnErr(auth.EditReleaseForm{}), repo.EditReleasePost) }, reqSignIn, middleware.RepoAssignment(true, true)) m.Group("/:username/:reponame", func(r martini.Router) { diff --git a/gogs.go b/gogs.go index ebb5f821..48202d14 100644 --- a/gogs.go +++ b/gogs.go @@ -17,7 +17,7 @@ import ( "github.com/gogits/gogs/modules/setting" ) -const APP_VER = "0.4.3.0612 Alpha" +const APP_VER = "0.4.4.0612 Alpha" func init() { runtime.GOMAXPROCS(runtime.NumCPU()) diff --git a/models/release.go b/models/release.go index e5e81b9b..32e8c92c 100644 --- a/models/release.go +++ b/models/release.go @@ -6,15 +6,16 @@ package models import ( "errors" + "sort" "strings" "time" - // "github.com/Unknwon/com" "github.com/gogits/git" ) var ( ErrReleaseAlreadyExist = errors.New("Release already exist") + ErrReleaseNotExist = errors.New("Release does not exist") ) // Release represents a release of repository. @@ -23,22 +24,17 @@ type Release struct { RepoId int64 PublisherId int64 Publisher *User `xorm:"-"` - Title string TagName string LowerTagName string Target string + Title string Sha1 string `xorm:"VARCHAR(40)"` NumCommits int NumCommitsBehind int `xorm:"-"` Note string `xorm:"TEXT"` + IsDraft bool `xorm:"NOT NULL DEFAULT false"` IsPrerelease bool - Created time.Time `xorm:"created"` -} - -// GetReleasesByRepoId returns a list of releases of repository. -func GetReleasesByRepoId(repoId int64) (rels []*Release, err error) { - err = orm.Desc("created").Find(&rels, Release{RepoId: repoId}) - return rels, err + Created time.Time `xorm:"CREATED"` } // IsReleaseExist returns true if release with given tag name already exists. @@ -50,6 +46,33 @@ func IsReleaseExist(repoId int64, tagName string) (bool, error) { return orm.Get(&Release{RepoId: repoId, LowerTagName: strings.ToLower(tagName)}) } +func createTag(gitRepo *git.Repository, rel *Release) error { + // Only actual create when publish. + if !rel.IsDraft { + if !gitRepo.IsTagExist(rel.TagName) { + commit, err := gitRepo.GetCommitOfBranch(rel.Target) + if err != nil { + return err + } + + if err = gitRepo.CreateTag(rel.TagName, commit.Id.String()); err != nil { + return err + } + } else { + commit, err := gitRepo.GetCommitOfTag(rel.TagName) + if err != nil { + return err + } + + rel.NumCommits, err = commit.CommitsCount() + if err != nil { + return err + } + } + } + return nil +} + // CreateRelease creates a new release of repository. func CreateRelease(gitRepo *git.Repository, rel *Release) error { isExist, err := IsReleaseExist(rel.RepoId, rel.TagName) @@ -59,28 +82,65 @@ func CreateRelease(gitRepo *git.Repository, rel *Release) error { return ErrReleaseAlreadyExist } - if !gitRepo.IsTagExist(rel.TagName) { - commit, err := gitRepo.GetCommitOfBranch(rel.Target) - if err != nil { - return err - } + if err = createTag(gitRepo, rel); err != nil { + return err + } + rel.LowerTagName = strings.ToLower(rel.TagName) + _, err = orm.InsertOne(rel) + return err +} - if err = gitRepo.CreateTag(rel.TagName, commit.Id.String()); err != nil { - return err - } - } else { - commit, err := gitRepo.GetCommitOfTag(rel.TagName) - if err != nil { - return err - } +// GetRelease returns release by given ID. +func GetRelease(repoId int64, tagName string) (*Release, error) { + isExist, err := IsReleaseExist(repoId, tagName) + if err != nil { + return nil, err + } else if !isExist { + return nil, ErrReleaseNotExist + } - rel.NumCommits, err = commit.CommitsCount() - if err != nil { - return err - } + rel := &Release{RepoId: repoId, LowerTagName: strings.ToLower(tagName)} + _, err = orm.Get(rel) + return rel, err +} + +// GetReleasesByRepoId returns a list of releases of repository. +func GetReleasesByRepoId(repoId int64) (rels []*Release, err error) { + err = orm.Desc("created").Find(&rels, Release{RepoId: repoId}) + return rels, err +} + +type ReleaseSorter struct { + rels []*Release +} + +func (rs *ReleaseSorter) Len() int { + return len(rs.rels) +} + +func (rs *ReleaseSorter) Less(i, j int) bool { + diffNum := rs.rels[i].NumCommits - rs.rels[j].NumCommits + if diffNum != 0 { + return diffNum > 0 } + return rs.rels[i].Created.After(rs.rels[j].Created) +} - rel.LowerTagName = strings.ToLower(rel.TagName) - _, err = orm.InsertOne(rel) +func (rs *ReleaseSorter) Swap(i, j int) { + rs.rels[i], rs.rels[j] = rs.rels[j], rs.rels[i] +} + +// SortReleases sorts releases by number of commits and created time. +func SortReleases(rels []*Release) { + sorter := &ReleaseSorter{rels: rels} + sort.Sort(sorter) +} + +// UpdateRelease updates information of a release. +func UpdateRelease(gitRepo *git.Repository, rel *Release) (err error) { + if err = createTag(gitRepo, rel); err != nil { + return err + } + _, err = orm.Id(rel.Id).AllCols().Update(rel) return err } diff --git a/models/repo.go b/models/repo.go index 7eab83c2..0f018135 100644 --- a/models/repo.go +++ b/models/repo.go @@ -835,7 +835,7 @@ func GetCollaborativeRepos(uname string) ([]*Repository, error) { if infos[0] == uname { continue } - + u, err := GetUserByName(infos[0]) if err != nil { return nil, err diff --git a/modules/auth/repo.go b/modules/auth/repo.go index 26ab7551..92ba64a2 100644 --- a/modules/auth/repo.go +++ b/modules/auth/repo.go @@ -208,6 +208,7 @@ type NewReleaseForm struct { Target string `form:"tag_target" binding:"Required"` Title string `form:"title" binding:"Required"` Content string `form:"content" binding:"Required"` + Draft string `form:"draft"` Prerelease bool `form:"prerelease"` } @@ -225,3 +226,25 @@ func (f *NewReleaseForm) Validate(errors *binding.Errors, req *http.Request, con data := context.Get(reflect.TypeOf(base.TmplData{})).Interface().(base.TmplData) validate(errors, data, f) } + +type EditReleaseForm struct { + Target string `form:"tag_target" binding:"Required"` + Title string `form:"title" binding:"Required"` + Content string `form:"content" binding:"Required"` + Draft string `form:"draft"` + Prerelease bool `form:"prerelease"` +} + +func (f *EditReleaseForm) Name(field string) string { + names := map[string]string{ + "Target": "Target", + "Title": "Release title", + "Content": "Release content", + } + return names[field] +} + +func (f *EditReleaseForm) Validate(errors *binding.Errors, req *http.Request, context martini.Context) { + data := context.Get(reflect.TypeOf(base.TmplData{})).Interface().(base.TmplData) + validate(errors, data, f) +} diff --git a/modules/middleware/repo.go b/modules/middleware/repo.go index c1acc827..6c77ed2a 100644 --- a/modules/middleware/repo.go +++ b/modules/middleware/repo.go @@ -21,21 +21,17 @@ import ( func RepoAssignment(redirect bool, args ...bool) martini.Handler { return func(ctx *Context, params martini.Params) { - log.Trace(fmt.Sprint(args)) // valid brachname var validBranch bool // display bare quick start if it is a bare repo var displayBare bool if len(args) >= 1 { - // Note: argument has wrong value in Go1.3 martini. - // validBranch = args[0] - validBranch = true + validBranch = args[0] } if len(args) >= 2 { - // displayBare = args[1] - displayBare = true + displayBare = args[1] } var ( diff --git a/routers/repo/release.go b/routers/repo/release.go index 27df3f6d..b6149b63 100644 --- a/routers/repo/release.go +++ b/routers/repo/release.go @@ -5,7 +5,7 @@ package repo import ( - "sort" + "github.com/go-martini/martini" "github.com/gogits/gogs/models" "github.com/gogits/gogs/modules/auth" @@ -14,27 +14,6 @@ import ( "github.com/gogits/gogs/modules/middleware" ) -type ReleaseSorter struct { - rels []*models.Release -} - -func (rs *ReleaseSorter) Len() int { - return len(rs.rels) -} - -func (rs *ReleaseSorter) Less(i, j int) bool { - diffNum := rs.rels[i].NumCommits - rs.rels[j].NumCommits - if diffNum != 0 { - return diffNum > 0 - } - - return rs.rels[i].Created.Second() > rs.rels[j].Created.Second() -} - -func (rs *ReleaseSorter) Swap(i, j int) { - rs.rels[i], rs.rels[j] = rs.rels[j], rs.rels[i] -} - func Releases(ctx *middleware.Context) { ctx.Data["Title"] = "Releases" ctx.Data["IsRepoToolbarReleases"] = true @@ -57,53 +36,76 @@ func Releases(ctx *middleware.Context) { return } - var tags ReleaseSorter - tags.rels = make([]*models.Release, len(rawTags)) + // Temproray cache commits count of used branches to speed up. + countCache := make(map[string]int) + + tags := make([]*models.Release, len(rawTags)) for i, rawTag := range rawTags { for _, rel := range rels { + if rel.IsDraft && !ctx.Repo.IsOwner { + continue + } if rel.TagName == rawTag { rel.Publisher, err = models.GetUserById(rel.PublisherId) if err != nil { ctx.Handle(500, "release.Releases(GetUserById)", err) return } - rel.NumCommitsBehind = commitsCount - rel.NumCommits + // Get corresponding target if it's not the current branch. + if ctx.Repo.BranchName != rel.Target { + // Get count if not exists. + if _, ok := countCache[rel.Target]; !ok { + commit, err := ctx.Repo.GitRepo.GetCommitOfTag(rel.TagName) + if err != nil { + ctx.Handle(500, "release.Releases(GetCommitOfTag)", err) + return + } + countCache[rel.Target], err = commit.CommitsCount() + if err != nil { + ctx.Handle(500, "release.Releases(CommitsCount2)", err) + return + } + } + rel.NumCommitsBehind = countCache[rel.Target] - rel.NumCommits + } else { + rel.NumCommitsBehind = commitsCount - rel.NumCommits + } + rel.Note = base.RenderMarkdownString(rel.Note, ctx.Repo.RepoLink) - tags.rels[i] = rel + tags[i] = rel break } } - if tags.rels[i] == nil { + if tags[i] == nil { commit, err := ctx.Repo.GitRepo.GetCommitOfTag(rawTag) if err != nil { - ctx.Handle(500, "release.Releases(GetCommitOfTag)", err) + ctx.Handle(500, "release.Releases(GetCommitOfTag2)", err) return } - tags.rels[i] = &models.Release{ + tags[i] = &models.Release{ Title: rawTag, TagName: rawTag, Sha1: commit.Id.String(), } - tags.rels[i].NumCommits, err = ctx.Repo.GitRepo.CommitsCount(commit.Id.String()) + + tags[i].NumCommits, err = ctx.Repo.GitRepo.CommitsCount(commit.Id.String()) if err != nil { ctx.Handle(500, "release.Releases(CommitsCount)", err) return } - tags.rels[i].NumCommitsBehind = commitsCount - tags.rels[i].NumCommits + tags[i].NumCommitsBehind = commitsCount - tags[i].NumCommits } } - - sort.Sort(&tags) - - ctx.Data["Releases"] = tags.rels + models.SortReleases(tags) + ctx.Data["Releases"] = tags ctx.HTML(200, "release/list") } -func ReleasesNew(ctx *middleware.Context) { +func NewRelease(ctx *middleware.Context) { if !ctx.Repo.IsOwner { - ctx.Handle(404, "release.ReleasesNew", nil) + ctx.Handle(403, "release.ReleasesNew", nil) return } @@ -113,9 +115,9 @@ func ReleasesNew(ctx *middleware.Context) { ctx.HTML(200, "release/new") } -func ReleasesNewPost(ctx *middleware.Context, form auth.NewReleaseForm) { +func NewReleasePost(ctx *middleware.Context, form auth.NewReleaseForm) { if !ctx.Repo.IsOwner { - ctx.Handle(404, "release.ReleasesNew", nil) + ctx.Handle(403, "release.ReleasesNew", nil) return } @@ -148,6 +150,7 @@ func ReleasesNewPost(ctx *middleware.Context, form auth.NewReleaseForm) { Sha1: ctx.Repo.Commit.Id.String(), NumCommits: commitsCount, Note: form.Content, + IsDraft: len(form.Draft) > 0, IsPrerelease: form.Prerelease, } @@ -163,3 +166,58 @@ func ReleasesNewPost(ctx *middleware.Context, form auth.NewReleaseForm) { ctx.Redirect(ctx.Repo.RepoLink + "/releases") } + +func EditRelease(ctx *middleware.Context, params martini.Params) { + if !ctx.Repo.IsOwner { + ctx.Handle(403, "release.ReleasesEdit", nil) + return + } + + tagName := params["tagname"] + rel, err := models.GetRelease(ctx.Repo.Repository.Id, tagName) + if err != nil { + if err == models.ErrReleaseNotExist { + ctx.Handle(404, "release.ReleasesEdit(GetRelease)", err) + } else { + ctx.Handle(500, "release.ReleasesEdit(GetRelease)", err) + } + return + } + ctx.Data["Release"] = rel + + ctx.Data["Title"] = "Edit Release" + ctx.Data["IsRepoToolbarReleases"] = true + ctx.HTML(200, "release/edit") +} + +func EditReleasePost(ctx *middleware.Context, params martini.Params, form auth.EditReleaseForm) { + if !ctx.Repo.IsOwner { + ctx.Handle(403, "release.EditReleasePost", nil) + return + } + + tagName := params["tagname"] + rel, err := models.GetRelease(ctx.Repo.Repository.Id, tagName) + if err != nil { + if err == models.ErrReleaseNotExist { + ctx.Handle(404, "release.EditReleasePost(GetRelease)", err) + } else { + ctx.Handle(500, "release.EditReleasePost(GetRelease)", err) + } + return + } + ctx.Data["Release"] = rel + + ctx.Data["Title"] = "Edit Release" + ctx.Data["IsRepoToolbarReleases"] = true + + rel.Title = form.Title + rel.Note = form.Content + rel.IsDraft = len(form.Draft) > 0 + rel.IsPrerelease = form.Prerelease + if err = models.UpdateRelease(ctx.Repo.GitRepo, rel); err != nil { + ctx.Handle(500, "release.EditReleasePost(UpdateRelease)", err) + return + } + ctx.Redirect(ctx.Repo.RepoLink + "/releases") +} diff --git a/templates/VERSION b/templates/VERSION index 1eb3e845..8e45ca59 100644 --- a/templates/VERSION +++ b/templates/VERSION @@ -1 +1 @@ -0.4.3.0612 Alpha \ No newline at end of file +0.4.4.0612 Alpha \ No newline at end of file diff --git a/templates/release/edit.tmpl b/templates/release/edit.tmpl new file mode 100644 index 00000000..e437092c --- /dev/null +++ b/templates/release/edit.tmpl @@ -0,0 +1,70 @@ +{{template "base/head" .}} +{{template "base/navbar" .}} +{{template "repo/nav" .}} +{{template "repo/toolbar" .}} +
+
+

Edit Release

+ {{template "base/alert" .}} +
+ {{.CsrfTokenHtml}} +
+ {{.Release.TagName}} + @ +
+ + + + +
+

Choose an existing tag, or create a new tag on publish

+
+
+ +
+
+
+ Content with Markdown +
+ +
+
+
+ +
+
+
loading...
+
+
+
+
+ +

We’ll point out that this release is identified as non-production ready.

+
+
+ + +
+
+
+
+{{template "base/footer" .}} \ No newline at end of file diff --git a/templates/release/list.tmpl b/templates/release/list.tmpl index 2607dfac..0f02508f 100644 --- a/templates/release/list.tmpl +++ b/templates/release/list.tmpl @@ -14,17 +14,23 @@
  • {{if .PublisherId}}
    - {{if .IsPrerelease}}Pre-Release{{else}}Stable{{end}} + {{if .IsDraft}} + Draft + {{else if .IsPrerelease}} + Pre-Release + {{else}} + Stable + {{end}} {{.TagName}} {{ShortSha .Sha1}}
    -

    {{.Title}}

    +

    {{.Title}} (edit)

       {{.Publisher.Name}} {{if .Created}}{{TimeSince .Created}}{{end}} - {{.NumCommitsBehind}} commits since this release + {{.NumCommitsBehind}} commits to {{.Target}} since this release

    {{str2html .Note}} diff --git a/templates/release/new.tmpl b/templates/release/new.tmpl index 06cb28c7..6c5cf40c 100644 --- a/templates/release/new.tmpl +++ b/templates/release/new.tmpl @@ -62,7 +62,7 @@
    - +
    -- cgit v1.2.3 From d952b4200c7c024ff5a809a3885bc79be9e4cce9 Mon Sep 17 00:00:00 2001 From: Unknown Date: Fri, 13 Jun 2014 13:01:52 -0400 Subject: Add corn rask monitor panel --- .gopmfile | 1 - cmd/web.go | 3 +- gogs.go | 2 +- modules/cron/constantdelay.go | 27 ++ modules/cron/constantdelay_test.go | 54 +++ modules/cron/cron.go | 212 ++++++++- modules/cron/cron_test.go | 255 ++++++++++ modules/cron/doc.go | 129 ++++++ modules/cron/manager.go | 24 + modules/cron/parser.go | 231 +++++++++ modules/cron/parser_test.go | 117 +++++ modules/cron/spec.go | 161 +++++++ modules/cron/spec_test.go | 173 +++++++ public/css/font-awesome.min.css | 4 +- public/fonts/FontAwesome.otf | Bin 62856 -> 75188 bytes public/fonts/fontawesome-webfont.eot | Bin 38205 -> 72449 bytes public/fonts/fontawesome-webfont.svg | 848 +++++++++++++++++++--------------- public/fonts/fontawesome-webfont.ttf | Bin 80652 -> 141564 bytes public/fonts/fontawesome-webfont.woff | Bin 44432 -> 83760 bytes routers/admin/admin.go | 17 + templates/VERSION | 2 +- templates/admin/monitor/cron.tmpl | 40 ++ templates/admin/nav.tmpl | 1 + templates/base/head.tmpl | 2 +- templates/user/signin.tmpl | 2 +- 25 files changed, 1908 insertions(+), 397 deletions(-) create mode 100644 modules/cron/constantdelay.go create mode 100644 modules/cron/constantdelay_test.go create mode 100644 modules/cron/cron_test.go create mode 100644 modules/cron/doc.go create mode 100644 modules/cron/manager.go create mode 100644 modules/cron/parser.go create mode 100644 modules/cron/parser_test.go create mode 100644 modules/cron/spec.go create mode 100644 modules/cron/spec_test.go create mode 100644 templates/admin/monitor/cron.tmpl (limited to 'cmd') diff --git a/.gopmfile b/.gopmfile index 5cfcc20c..3a0f3fc2 100644 --- a/.gopmfile +++ b/.gopmfile @@ -20,7 +20,6 @@ github.com/juju2013/goldap = `commit:f4a7f67` github.com/lib/pq = `commit:529edd9` github.com/nfnt/resize = `commit:8aee0d9` github.com/qiniu/log = `commit:891d1cb` -github.com/robfig/cron = `commit:b024fc5` [res] include = templates|public diff --git a/cmd/web.go b/cmd/web.go index 27b3d8cf..2fdfe433 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -162,8 +162,9 @@ func runWeb(*cli.Context) { m.Group("/admin", func(r martini.Router) { r.Get("/users", admin.Users) r.Get("/repos", admin.Repositories) - r.Get("/config", admin.Config) r.Get("/auths", admin.Auths) + r.Get("/config", admin.Config) + r.Get("/monitor", admin.Monitor) }, adminReq) m.Group("/admin/users", func(r martini.Router) { r.Get("/new", admin.NewUser) diff --git a/gogs.go b/gogs.go index 48202d14..b4129e90 100644 --- a/gogs.go +++ b/gogs.go @@ -17,7 +17,7 @@ import ( "github.com/gogits/gogs/modules/setting" ) -const APP_VER = "0.4.4.0612 Alpha" +const APP_VER = "0.4.4.0613 Alpha" func init() { runtime.GOMAXPROCS(runtime.NumCPU()) diff --git a/modules/cron/constantdelay.go b/modules/cron/constantdelay.go new file mode 100644 index 00000000..cd6e7b1b --- /dev/null +++ b/modules/cron/constantdelay.go @@ -0,0 +1,27 @@ +package cron + +import "time" + +// ConstantDelaySchedule represents a simple recurring duty cycle, e.g. "Every 5 minutes". +// It does not support jobs more frequent than once a second. +type ConstantDelaySchedule struct { + Delay time.Duration +} + +// Every returns a crontab Schedule that activates once every duration. +// Delays of less than a second are not supported (will round up to 1 second). +// Any fields less than a Second are truncated. +func Every(duration time.Duration) ConstantDelaySchedule { + if duration < time.Second { + duration = time.Second + } + return ConstantDelaySchedule{ + Delay: duration - time.Duration(duration.Nanoseconds())%time.Second, + } +} + +// Next returns the next time this should be run. +// This rounds so that the next activation time will be on the second. +func (schedule ConstantDelaySchedule) Next(t time.Time) time.Time { + return t.Add(schedule.Delay - time.Duration(t.Nanosecond())*time.Nanosecond) +} diff --git a/modules/cron/constantdelay_test.go b/modules/cron/constantdelay_test.go new file mode 100644 index 00000000..f43a58ad --- /dev/null +++ b/modules/cron/constantdelay_test.go @@ -0,0 +1,54 @@ +package cron + +import ( + "testing" + "time" +) + +func TestConstantDelayNext(t *testing.T) { + tests := []struct { + time string + delay time.Duration + expected string + }{ + // Simple cases + {"Mon Jul 9 14:45 2012", 15*time.Minute + 50*time.Nanosecond, "Mon Jul 9 15:00 2012"}, + {"Mon Jul 9 14:59 2012", 15 * time.Minute, "Mon Jul 9 15:14 2012"}, + {"Mon Jul 9 14:59:59 2012", 15 * time.Minute, "Mon Jul 9 15:14:59 2012"}, + + // Wrap around hours + {"Mon Jul 9 15:45 2012", 35 * time.Minute, "Mon Jul 9 16:20 2012"}, + + // Wrap around days + {"Mon Jul 9 23:46 2012", 14 * time.Minute, "Tue Jul 10 00:00 2012"}, + {"Mon Jul 9 23:45 2012", 35 * time.Minute, "Tue Jul 10 00:20 2012"}, + {"Mon Jul 9 23:35:51 2012", 44*time.Minute + 24*time.Second, "Tue Jul 10 00:20:15 2012"}, + {"Mon Jul 9 23:35:51 2012", 25*time.Hour + 44*time.Minute + 24*time.Second, "Thu Jul 11 01:20:15 2012"}, + + // Wrap around months + {"Mon Jul 9 23:35 2012", 91*24*time.Hour + 25*time.Minute, "Thu Oct 9 00:00 2012"}, + + // Wrap around minute, hour, day, month, and year + {"Mon Dec 31 23:59:45 2012", 15 * time.Second, "Tue Jan 1 00:00:00 2013"}, + + // Round to nearest second on the delay + {"Mon Jul 9 14:45 2012", 15*time.Minute + 50*time.Nanosecond, "Mon Jul 9 15:00 2012"}, + + // Round up to 1 second if the duration is less. + {"Mon Jul 9 14:45:00 2012", 15 * time.Millisecond, "Mon Jul 9 14:45:01 2012"}, + + // Round to nearest second when calculating the next time. + {"Mon Jul 9 14:45:00.005 2012", 15 * time.Minute, "Mon Jul 9 15:00 2012"}, + + // Round to nearest second for both. + {"Mon Jul 9 14:45:00.005 2012", 15*time.Minute + 50*time.Nanosecond, "Mon Jul 9 15:00 2012"}, + } + + for _, c := range tests { + actual := Every(c.delay).Next(getTime(c.time)) + expected := getTime(c.expected) + if actual != expected { + t.Errorf("%s, \"%s\": (expected) %v != %v (actual)", c.time, c.delay, expected, actual) + } + } +} diff --git a/modules/cron/cron.go b/modules/cron/cron.go index c06e649b..dbf0174b 100644 --- a/modules/cron/cron.go +++ b/modules/cron/cron.go @@ -1,3 +1,4 @@ +// Copyright 2012 Rob Figueiredo. All rights reserved. // Copyright 2014 The Gogs Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. @@ -5,17 +6,208 @@ package cron import ( - "fmt" + "sort" + "time" +) - "github.com/robfig/cron" +// Cron keeps track of any number of entries, invoking the associated func as +// specified by the schedule. It may be started, stopped, and the entries may +// be inspected while running. +type Cron struct { + entries []*Entry + stop chan struct{} + add chan *Entry + snapshot chan []*Entry + running bool +} - "github.com/gogits/gogs/models" - "github.com/gogits/gogs/modules/setting" -) +// Job is an interface for submitted cron jobs. +type Job interface { + Run() +} + +// The Schedule describes a job's duty cycle. +type Schedule interface { + // Return the next activation time, later than the given time. + // Next is invoked initially, and then each time the job is run. + Next(time.Time) time.Time +} + +// Entry consists of a schedule and the func to execute on that schedule. +type Entry struct { + Description string + Spec string + + // The schedule on which this job should be run. + Schedule Schedule + + // The next time the job will run. This is the zero time if Cron has not been + // started or this entry's schedule is unsatisfiable + Next time.Time + + // The last time this job was run. This is the zero time if the job has never + // been run. + Prev time.Time + + // The Job to run. + Job Job + + ExecTimes int // Execute times count. +} + +// byTime is a wrapper for sorting the entry array by time +// (with zero time at the end). +type byTime []*Entry + +func (s byTime) Len() int { return len(s) } +func (s byTime) Swap(i, j int) { s[i], s[j] = s[j], s[i] } +func (s byTime) Less(i, j int) bool { + // Two zero times should return false. + // Otherwise, zero is "greater" than any other time. + // (To sort it at the end of the list.) + if s[i].Next.IsZero() { + return false + } + if s[j].Next.IsZero() { + return true + } + return s[i].Next.Before(s[j].Next) +} + +// New returns a new Cron job runner. +func New() *Cron { + return &Cron{ + entries: nil, + add: make(chan *Entry), + stop: make(chan struct{}), + snapshot: make(chan []*Entry), + running: false, + } +} + +// A wrapper that turns a func() into a cron.Job +type FuncJob func() + +func (f FuncJob) Run() { f() } + +// AddFunc adds a func to the Cron to be run on the given schedule. +func (c *Cron) AddFunc(desc, spec string, cmd func()) error { + return c.AddJob(desc, spec, FuncJob(cmd)) +} + +// AddFunc adds a Job to the Cron to be run on the given schedule. +func (c *Cron) AddJob(desc, spec string, cmd Job) error { + schedule, err := Parse(spec) + if err != nil { + return err + } + c.Schedule(desc, spec, schedule, cmd) + return nil +} + +// Schedule adds a Job to the Cron to be run on the given schedule. +func (c *Cron) Schedule(desc, spec string, schedule Schedule, cmd Job) { + entry := &Entry{ + Description: desc, + Spec: spec, + Schedule: schedule, + Job: cmd, + } + if !c.running { + c.entries = append(c.entries, entry) + return + } + + c.add <- entry +} + +// Entries returns a snapshot of the cron entries. +func (c *Cron) Entries() []*Entry { + if c.running { + c.snapshot <- nil + x := <-c.snapshot + return x + } + return c.entrySnapshot() +} + +// Start the cron scheduler in its own go-routine. +func (c *Cron) Start() { + c.running = true + go c.run() +} + +// Run the scheduler.. this is private just due to the need to synchronize +// access to the 'running' state variable. +func (c *Cron) run() { + // Figure out the next activation times for each entry. + now := time.Now().Local() + for _, entry := range c.entries { + entry.Next = entry.Schedule.Next(now) + } + + for { + // Determine the next entry to run. + sort.Sort(byTime(c.entries)) + + var effective time.Time + if len(c.entries) == 0 || c.entries[0].Next.IsZero() { + // If there are no entries yet, just sleep - it still handles new entries + // and stop requests. + effective = now.AddDate(10, 0, 0) + } else { + effective = c.entries[0].Next + } + + select { + case now = <-time.After(effective.Sub(now)): + // Run every entry whose next time was this effective time. + for _, e := range c.entries { + if e.Next != effective { + break + } + go e.Job.Run() + e.ExecTimes++ + e.Prev = e.Next + e.Next = e.Schedule.Next(effective) + } + continue + + case newEntry := <-c.add: + c.entries = append(c.entries, newEntry) + newEntry.Next = newEntry.Schedule.Next(now) + + case <-c.snapshot: + c.snapshot <- c.entrySnapshot() + + case <-c.stop: + return + } + + // 'now' should be updated after newEntry and snapshot cases. + now = time.Now().Local() + } +} + +// Stop the cron scheduler. +func (c *Cron) Stop() { + c.stop <- struct{}{} + c.running = false +} -func NewCronContext() { - c := cron.New() - c.AddFunc("@every 1h", models.MirrorUpdate) - c.AddFunc(fmt.Sprintf("@every %dm", setting.WebhookTaskInterval), models.DeliverHooks) - c.Start() +// entrySnapshot returns a copy of the current cron entry list. +func (c *Cron) entrySnapshot() []*Entry { + entries := make([]*Entry, 0, len(c.entries)) + for _, e := range c.entries { + entries = append(entries, &Entry{ + Description: e.Description, + Spec: e.Spec, + Schedule: e.Schedule, + Next: e.Next, + Prev: e.Prev, + Job: e.Job, + ExecTimes: e.ExecTimes, + }) + } + return entries } diff --git a/modules/cron/cron_test.go b/modules/cron/cron_test.go new file mode 100644 index 00000000..9822e8ed --- /dev/null +++ b/modules/cron/cron_test.go @@ -0,0 +1,255 @@ +package cron + +import ( + "fmt" + "sync" + "testing" + "time" +) + +// Many tests schedule a job for every second, and then wait at most a second +// for it to run. This amount is just slightly larger than 1 second to +// compensate for a few milliseconds of runtime. +const ONE_SECOND = 1*time.Second + 10*time.Millisecond + +// Start and stop cron with no entries. +func TestNoEntries(t *testing.T) { + cron := New() + cron.Start() + + select { + case <-time.After(ONE_SECOND): + t.FailNow() + case <-stop(cron): + } +} + +// Start, stop, then add an entry. Verify entry doesn't run. +func TestStopCausesJobsToNotRun(t *testing.T) { + wg := &sync.WaitGroup{} + wg.Add(1) + + cron := New() + cron.Start() + cron.Stop() + cron.AddFunc("", "* * * * * ?", func() { wg.Done() }) + + select { + case <-time.After(ONE_SECOND): + // No job ran! + case <-wait(wg): + t.FailNow() + } +} + +// Add a job, start cron, expect it runs. +func TestAddBeforeRunning(t *testing.T) { + wg := &sync.WaitGroup{} + wg.Add(1) + + cron := New() + cron.AddFunc("", "* * * * * ?", func() { wg.Done() }) + cron.Start() + defer cron.Stop() + + // Give cron 2 seconds to run our job (which is always activated). + select { + case <-time.After(ONE_SECOND): + t.FailNow() + case <-wait(wg): + } +} + +// Start cron, add a job, expect it runs. +func TestAddWhileRunning(t *testing.T) { + wg := &sync.WaitGroup{} + wg.Add(1) + + cron := New() + cron.Start() + defer cron.Stop() + cron.AddFunc("", "* * * * * ?", func() { wg.Done() }) + + select { + case <-time.After(ONE_SECOND): + t.FailNow() + case <-wait(wg): + } +} + +// Test timing with Entries. +func TestSnapshotEntries(t *testing.T) { + wg := &sync.WaitGroup{} + wg.Add(1) + + cron := New() + cron.AddFunc("", "@every 2s", func() { wg.Done() }) + cron.Start() + defer cron.Stop() + + // Cron should fire in 2 seconds. After 1 second, call Entries. + select { + case <-time.After(ONE_SECOND): + cron.Entries() + } + + // Even though Entries was called, the cron should fire at the 2 second mark. + select { + case <-time.After(ONE_SECOND): + t.FailNow() + case <-wait(wg): + } + +} + +// Test that the entries are correctly sorted. +// Add a bunch of long-in-the-future entries, and an immediate entry, and ensure +// that the immediate entry runs immediately. +// Also: Test that multiple jobs run in the same instant. +func TestMultipleEntries(t *testing.T) { + wg := &sync.WaitGroup{} + wg.Add(2) + + cron := New() + cron.AddFunc("", "0 0 0 1 1 ?", func() {}) + cron.AddFunc("", "* * * * * ?", func() { wg.Done() }) + cron.AddFunc("", "0 0 0 31 12 ?", func() {}) + cron.AddFunc("", "* * * * * ?", func() { wg.Done() }) + + cron.Start() + defer cron.Stop() + + select { + case <-time.After(ONE_SECOND): + t.FailNow() + case <-wait(wg): + } +} + +// Test running the same job twice. +func TestRunningJobTwice(t *testing.T) { + wg := &sync.WaitGroup{} + wg.Add(2) + + cron := New() + cron.AddFunc("", "0 0 0 1 1 ?", func() {}) + cron.AddFunc("", "0 0 0 31 12 ?", func() {}) + cron.AddFunc("", "* * * * * ?", func() { wg.Done() }) + + cron.Start() + defer cron.Stop() + + select { + case <-time.After(2 * ONE_SECOND): + t.FailNow() + case <-wait(wg): + } +} + +func TestRunningMultipleSchedules(t *testing.T) { + wg := &sync.WaitGroup{} + wg.Add(2) + + cron := New() + cron.AddFunc("", "0 0 0 1 1 ?", func() {}) + cron.AddFunc("", "0 0 0 31 12 ?", func() {}) + cron.AddFunc("", "* * * * * ?", func() { wg.Done() }) + cron.Schedule("", Every(time.Minute), FuncJob(func() {})) + cron.Schedule("", Every(time.Second), FuncJob(func() { wg.Done() })) + cron.Schedule("", Every(time.Hour), FuncJob(func() {})) + + cron.Start() + defer cron.Stop() + + select { + case <-time.After(2 * ONE_SECOND): + t.FailNow() + case <-wait(wg): + } +} + +// Test that the cron is run in the local time zone (as opposed to UTC). +func TestLocalTimezone(t *testing.T) { + wg := &sync.WaitGroup{} + wg.Add(1) + + now := time.Now().Local() + spec := fmt.Sprintf("%d %d %d %d %d ?", + now.Second()+1, now.Minute(), now.Hour(), now.Day(), now.Month()) + + cron := New() + cron.AddFunc("", spec, func() { wg.Done() }) + cron.Start() + defer cron.Stop() + + select { + case <-time.After(ONE_SECOND): + t.FailNow() + case <-wait(wg): + } +} + +type testJob struct { + wg *sync.WaitGroup + name string +} + +func (t testJob) Run() { + t.wg.Done() +} + +// Simple test using Runnables. +func TestJob(t *testing.T) { + wg := &sync.WaitGroup{} + wg.Add(1) + + cron := New() + cron.AddJob("", "0 0 0 30 Feb ?", testJob{wg, "job0"}) + cron.AddJob("", "0 0 0 1 1 ?", testJob{wg, "job1"}) + cron.AddJob("", "* * * * * ?", testJob{wg, "job2"}) + cron.AddJob("", "1 0 0 1 1 ?", testJob{wg, "job3"}) + cron.Schedule("", Every(5*time.Second+5*time.Nanosecond), testJob{wg, "job4"}) + cron.Schedule("", Every(5*time.Minute), testJob{wg, "job5"}) + + cron.Start() + defer cron.Stop() + + select { + case <-time.After(ONE_SECOND): + t.FailNow() + case <-wait(wg): + } + + // Ensure the entries are in the right order. + expecteds := []string{"job2", "job4", "job5", "job1", "job3", "job0"} + + var actuals []string + for _, entry := range cron.Entries() { + actuals = append(actuals, entry.Job.(testJob).name) + } + + for i, expected := range expecteds { + if actuals[i] != expected { + t.Errorf("Jobs not in the right order. (expected) %s != %s (actual)", expecteds, actuals) + t.FailNow() + } + } +} + +func wait(wg *sync.WaitGroup) chan bool { + ch := make(chan bool) + go func() { + wg.Wait() + ch <- true + }() + return ch +} + +func stop(cron *Cron) chan bool { + ch := make(chan bool) + go func() { + cron.Stop() + ch <- true + }() + return ch +} diff --git a/modules/cron/doc.go b/modules/cron/doc.go new file mode 100644 index 00000000..dbdf5012 --- /dev/null +++ b/modules/cron/doc.go @@ -0,0 +1,129 @@ +/* +Package cron implements a cron spec parser and job runner. + +Usage + +Callers may register Funcs to be invoked on a given schedule. Cron will run +them in their own goroutines. + + c := cron.New() + c.AddFunc("0 30 * * * *", func() { fmt.Println("Every hour on the half hour") }) + c.AddFunc("@hourly", func() { fmt.Println("Every hour") }) + c.AddFunc("@every 1h30m", func() { fmt.Println("Every hour thirty") }) + c.Start() + .. + // Funcs are invoked in their own goroutine, asynchronously. + ... + // Funcs may also be added to a running Cron + c.AddFunc("@daily", func() { fmt.Println("Every day") }) + .. + // Inspect the cron job entries' next and previous run times. + inspect(c.Entries()) + .. + c.Stop() // Stop the scheduler (does not stop any jobs already running). + +CRON Expression Format + +A cron expression represents a set of times, using 6 space-separated fields. + + Field name | Mandatory? | Allowed values | Allowed special characters + ---------- | ---------- | -------------- | -------------------------- + Seconds | Yes | 0-59 | * / , - + Minutes | Yes | 0-59 | * / , - + Hours | Yes | 0-23 | * / , - + Day of month | Yes | 1-31 | * / , - ? + Month | Yes | 1-12 or JAN-DEC | * / , - + Day of week | Yes | 0-6 or SUN-SAT | * / , - ? + +Note: Month and Day-of-week field values are case insensitive. "SUN", "Sun", +and "sun" are equally accepted. + +Special Characters + +Asterisk ( * ) + +The asterisk indicates that the cron expression will match for all values of the +field; e.g., using an asterisk in the 5th field (month) would indicate every +month. + +Slash ( / ) + +Slashes are used to describe increments of ranges. For example 3-59/15 in the +1st field (minutes) would indicate the 3rd minute of the hour and every 15 +minutes thereafter. The form "*\/..." is equivalent to the form "first-last/...", +that is, an increment over the largest possible range of the field. The form +"N/..." is accepted as meaning "N-MAX/...", that is, starting at N, use the +increment until the end of that specific range. It does not wrap around. + +Comma ( , ) + +Commas are used to separate items of a list. For example, using "MON,WED,FRI" in +the 5th field (day of week) would mean Mondays, Wednesdays and Fridays. + +Hyphen ( - ) + +Hyphens are used to define ranges. For example, 9-17 would indicate every +hour between 9am and 5pm inclusive. + +Question mark ( ? ) + +Question mark may be used instead of '*' for leaving either day-of-month or +day-of-week blank. + +Predefined schedules + +You may use one of several pre-defined schedules in place of a cron expression. + + Entry | Description | Equivalent To + ----- | ----------- | ------------- + @yearly (or @annually) | Run once a year, midnight, Jan. 1st | 0 0 0 1 1 * + @monthly | Run once a month, midnight, first of month | 0 0 0 1 * * + @weekly | Run once a week, midnight on Sunday | 0 0 0 * * 0 + @daily (or @midnight) | Run once a day, midnight | 0 0 0 * * * + @hourly | Run once an hour, beginning of hour | 0 0 * * * * + +Intervals + +You may also schedule a job to execute at fixed intervals. This is supported by +formatting the cron spec like this: + + @every + +where "duration" is a string accepted by time.ParseDuration +(http://golang.org/pkg/time/#ParseDuration). + +For example, "@every 1h30m10s" would indicate a schedule that activates every +1 hour, 30 minutes, 10 seconds. + +Note: The interval does not take the job runtime into account. For example, +if a job takes 3 minutes to run, and it is scheduled to run every 5 minutes, +it will have only 2 minutes of idle time between each run. + +Time zones + +All interpretation and scheduling is done in the machine's local time zone (as +provided by the Go time package (http://www.golang.org/pkg/time). + +Be aware that jobs scheduled during daylight-savings leap-ahead transitions will +not be run! + +Thread safety + +Since the Cron service runs concurrently with the calling code, some amount of +care must be taken to ensure proper synchronization. + +All cron methods are designed to be correctly synchronized as long as the caller +ensures that invocations have a clear happens-before ordering between them. + +Implementation + +Cron entries are stored in an array, sorted by their next activation time. Cron +sleeps until the next job is due to be run. + +Upon waking: + - it runs each entry that is active on that second + - it calculates the next run times for the jobs that were run + - it re-sorts the array of entries by next activation time. + - it goes to sleep until the soonest job. +*/ +package cron diff --git a/modules/cron/manager.go b/modules/cron/manager.go new file mode 100644 index 00000000..563426fb --- /dev/null +++ b/modules/cron/manager.go @@ -0,0 +1,24 @@ +// Copyright 2014 The Gogs Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package cron + +import ( + "fmt" + + "github.com/gogits/gogs/models" + "github.com/gogits/gogs/modules/setting" +) + +var c = New() + +func NewCronContext() { + c.AddFunc("Update mirrors", "@every 1h", models.MirrorUpdate) + c.AddFunc("Deliver hooks", fmt.Sprintf("@every %dm", setting.WebhookTaskInterval), models.DeliverHooks) + c.Start() +} + +func ListEntries() []*Entry { + return c.Entries() +} diff --git a/modules/cron/parser.go b/modules/cron/parser.go new file mode 100644 index 00000000..4224fa93 --- /dev/null +++ b/modules/cron/parser.go @@ -0,0 +1,231 @@ +package cron + +import ( + "fmt" + "log" + "math" + "strconv" + "strings" + "time" +) + +// Parse returns a new crontab schedule representing the given spec. +// It returns a descriptive error if the spec is not valid. +// +// It accepts +// - Full crontab specs, e.g. "* * * * * ?" +// - Descriptors, e.g. "@midnight", "@every 1h30m" +func Parse(spec string) (_ Schedule, err error) { + // Convert panics into errors + defer func() { + if recovered := recover(); recovered != nil { + err = fmt.Errorf("%v", recovered) + } + }() + + if spec[0] == '@' { + return parseDescriptor(spec), nil + } + + // Split on whitespace. We require 5 or 6 fields. + // (second) (minute) (hour) (day of month) (month) (day of week, optional) + fields := strings.Fields(spec) + if len(fields) != 5 && len(fields) != 6 { + log.Panicf("Expected 5 or 6 fields, found %d: %s", len(fields), spec) + } + + // If a sixth field is not provided (DayOfWeek), then it is equivalent to star. + if len(fields) == 5 { + fields = append(fields, "*") + } + + schedule := &SpecSchedule{ + Second: getField(fields[0], seconds), + Minute: getField(fields[1], minutes), + Hour: getField(fields[2], hours), + Dom: getField(fields[3], dom), + Month: getField(fields[4], months), + Dow: getField(fields[5], dow), + } + + return schedule, nil +} + +// getField returns an Int with the bits set representing all of the times that +// the field represents. A "field" is a comma-separated list of "ranges". +func getField(field string, r bounds) uint64 { + // list = range {"," range} + var bits uint64 + ranges := strings.FieldsFunc(field, func(r rune) bool { return r == ',' }) + for _, expr := range ranges { + bits |= getRange(expr, r) + } + return bits +} + +// getRange returns the bits indicated by the given expression: +// number | number "-" number [ "/" number ] +func getRange(expr string, r bounds) uint64 { + + var ( + start, end, step uint + rangeAndStep = strings.Split(expr, "/") + lowAndHigh = strings.Split(rangeAndStep[0], "-") + singleDigit = len(lowAndHigh) == 1 + ) + + var extra_star uint64 + if lowAndHigh[0] == "*" || lowAndHigh[0] == "?" { + start = r.min + end = r.max + extra_star = starBit + } else { + start = parseIntOrName(lowAndHigh[0], r.names) + switch len(lowAndHigh) { + case 1: + end = start + case 2: + end = parseIntOrName(lowAndHigh[1], r.names) + default: + log.Panicf("Too many hyphens: %s", expr) + } + } + + switch len(rangeAndStep) { + case 1: + step = 1 + case 2: + step = mustParseInt(rangeAndStep[1]) + + // Special handling: "N/step" means "N-max/step". + if singleDigit { + end = r.max + } + default: + log.Panicf("Too many slashes: %s", expr) + } + + if start < r.min { + log.Panicf("Beginning of range (%d) below minimum (%d): %s", start, r.min, expr) + } + if end > r.max { + log.Panicf("End of range (%d) above maximum (%d): %s", end, r.max, expr) + } + if start > end { + log.Panicf("Beginning of range (%d) beyond end of range (%d): %s", start, end, expr) + } + + return getBits(start, end, step) | extra_star +} + +// parseIntOrName returns the (possibly-named) integer contained in expr. +func parseIntOrName(expr string, names map[string]uint) uint { + if names != nil { + if namedInt, ok := names[strings.ToLower(expr)]; ok { + return namedInt + } + } + return mustParseInt(expr) +} + +// mustParseInt parses the given expression as an int or panics. +func mustParseInt(expr string) uint { + num, err := strconv.Atoi(expr) + if err != nil { + log.Panicf("Failed to parse int from %s: %s", expr, err) + } + if num < 0 { + log.Panicf("Negative number (%d) not allowed: %s", num, expr) + } + + return uint(num) +} + +// getBits sets all bits in the range [min, max], modulo the given step size. +func getBits(min, max, step uint) uint64 { + var bits uint64 + + // If step is 1, use shifts. + if step == 1 { + return ^(math.MaxUint64 << (max + 1)) & (math.MaxUint64 << min) + } + + // Else, use a simple loop. + for i := min; i <= max; i += step { + bits |= 1 << i + } + return bits +} + +// all returns all bits within the given bounds. (plus the star bit) +func all(r bounds) uint64 { + return getBits(r.min, r.max, 1) | starBit +} + +// parseDescriptor returns a pre-defined schedule for the expression, or panics +// if none matches. +func parseDescriptor(spec string) Schedule { + switch spec { + case "@yearly", "@annually": + return &SpecSchedule{ + Second: 1 << seconds.min, + Minute: 1 << minutes.min, + Hour: 1 << hours.min, + Dom: 1 << dom.min, + Month: 1 << months.min, + Dow: all(dow), + } + + case "@monthly": + return &SpecSchedule{ + Second: 1 << seconds.min, + Minute: 1 << minutes.min, + Hour: 1 << hours.min, + Dom: 1 << dom.min, + Month: all(months), + Dow: all(dow), + } + + case "@weekly": + return &SpecSchedule{ + Second: 1 << seconds.min, + Minute: 1 << minutes.min, + Hour: 1 << hours.min, + Dom: all(dom), + Month: all(months), + Dow: 1 << dow.min, + } + + case "@daily", "@midnight": + return &SpecSchedule{ + Second: 1 << seconds.min, + Minute: 1 << minutes.min, + Hour: 1 << hours.min, + Dom: all(dom), + Month: all(months), + Dow: all(dow), + } + + case "@hourly": + return &SpecSchedule{ + Second: 1 << seconds.min, + Minute: 1 << minutes.min, + Hour: all(hours), + Dom: all(dom), + Month: all(months), + Dow: all(dow), + } + } + + const every = "@every " + if strings.HasPrefix(spec, every) { + duration, err := time.ParseDuration(spec[len(every):]) + if err != nil { + log.Panicf("Failed to parse duration %s: %s", spec, err) + } + return Every(duration) + } + + log.Panicf("Unrecognized descriptor: %s", spec) + return nil +} diff --git a/modules/cron/parser_test.go b/modules/cron/parser_test.go new file mode 100644 index 00000000..9050cf78 --- /dev/null +++ b/modules/cron/parser_test.go @@ -0,0 +1,117 @@ +package cron + +import ( + "reflect" + "testing" + "time" +) + +func TestRange(t *testing.T) { + ranges := []struct { + expr string + min, max uint + expected uint64 + }{ + {"5", 0, 7, 1 << 5}, + {"0", 0, 7, 1 << 0}, + {"7", 0, 7, 1 << 7}, + + {"5-5", 0, 7, 1 << 5}, + {"5-6", 0, 7, 1<<5 | 1<<6}, + {"5-7", 0, 7, 1<<5 | 1<<6 | 1<<7}, + + {"5-6/2", 0, 7, 1 << 5}, + {"5-7/2", 0, 7, 1<<5 | 1<<7}, + {"5-7/1", 0, 7, 1<<5 | 1<<6 | 1<<7}, + + {"*", 1, 3, 1<<1 | 1<<2 | 1<<3 | starBit}, + {"*/2", 1, 3, 1<<1 | 1<<3 | starBit}, + } + + for _, c := range ranges { + actual := getRange(c.expr, bounds{c.min, c.max, nil}) + if actual != c.expected { + t.Errorf("%s => (expected) %d != %d (actual)", c.expr, c.expected, actual) + } + } +} + +func TestField(t *testing.T) { + fields := []struct { + expr string + min, max uint + expected uint64 + }{ + {"5", 1, 7, 1 << 5}, + {"5,6", 1, 7, 1<<5 | 1<<6}, + {"5,6,7", 1, 7, 1<<5 | 1<<6 | 1<<7}, + {"1,5-7/2,3", 1, 7, 1<<1 | 1<<5 | 1<<7 | 1<<3}, + } + + for _, c := range fields { + actual := getField(c.expr, bounds{c.min, c.max, nil}) + if actual != c.expected { + t.Errorf("%s => (expected) %d != %d (actual)", c.expr, c.expected, actual) + } + } +} + +func TestBits(t *testing.T) { + allBits := []struct { + r bounds + expected uint64 + }{ + {minutes, 0xfffffffffffffff}, // 0-59: 60 ones + {hours, 0xffffff}, // 0-23: 24 ones + {dom, 0xfffffffe}, // 1-31: 31 ones, 1 zero + {months, 0x1ffe}, // 1-12: 12 ones, 1 zero + {dow, 0x7f}, // 0-6: 7 ones + } + + for _, c := range allBits { + actual := all(c.r) // all() adds the starBit, so compensate for that.. + if c.expected|starBit != actual { + t.Errorf("%d-%d/%d => (expected) %b != %b (actual)", + c.r.min, c.r.max, 1, c.expected|starBit, actual) + } + } + + bits := []struct { + min, max, step uint + expected uint64 + }{ + + {0, 0, 1, 0x1}, + {1, 1, 1, 0x2}, + {1, 5, 2, 0x2a}, // 101010 + {1, 4, 2, 0xa}, // 1010 + } + + for _, c := range bits { + actual := getBits(c.min, c.max, c.step) + if c.expected != actual { + t.Errorf("%d-%d/%d => (expected) %b != %b (actual)", + c.min, c.max, c.step, c.expected, actual) + } + } +} + +func TestSpecSchedule(t *testing.T) { + entries := []struct { + expr string + expected Schedule + }{ + {"* 5 * * * *", &SpecSchedule{all(seconds), 1 << 5, all(hours), all(dom), all(months), all(dow)}}, + {"@every 5m", ConstantDelaySchedule{time.Duration(5) * time.Minute}}, + } + + for _, c := range entries { + actual, err := Parse(c.expr) + if err != nil { + t.Error(err) + } + if !reflect.DeepEqual(actual, c.expected) { + t.Errorf("%s => (expected) %b != %b (actual)", c.expr, c.expected, actual) + } + } +} diff --git a/modules/cron/spec.go b/modules/cron/spec.go new file mode 100644 index 00000000..cb374332 --- /dev/null +++ b/modules/cron/spec.go @@ -0,0 +1,161 @@ +package cron + +import ( + "time" +) + +// SpecSchedule specifies a duty cycle (to the second granularity), based on a +// traditional crontab specification. It is computed initially and stored as bit sets. +type SpecSchedule struct { + Second, Minute, Hour, Dom, Month, Dow uint64 +} + +// bounds provides a range of acceptable values (plus a map of name to value). +type bounds struct { + min, max uint + names map[string]uint +} + +// The bounds for each field. +var ( + seconds = bounds{0, 59, nil} + minutes = bounds{0, 59, nil} + hours = bounds{0, 23, nil} + dom = bounds{1, 31, nil} + months = bounds{1, 12, map[string]uint{ + "jan": 1, + "feb": 2, + "mar": 3, + "apr": 4, + "may": 5, + "jun": 6, + "jul": 7, + "aug": 8, + "sep": 9, + "oct": 10, + "nov": 11, + "dec": 12, + }} + dow = bounds{0, 6, map[string]uint{ + "sun": 0, + "mon": 1, + "tue": 2, + "wed": 3, + "thu": 4, + "fri": 5, + "sat": 6, + }} +) + +const ( + // Set the top bit if a star was included in the expression. + starBit = 1 << 63 +) + +// Next returns the next time this schedule is activated, greater than the given +// time. If no time can be found to satisfy the schedule, return the zero time. +func (s *SpecSchedule) Next(t time.Time) time.Time { + // General approach: + // For Month, Day, Hour, Minute, Second: + // Check if the time value matches. If yes, continue to the next field. + // If the field doesn't match the schedule, then increment the field until it matches. + // While incrementing the field, a wrap-around brings it back to the beginning + // of the field list (since it is necessary to re-verify previous field + // values) + + // Start at the earliest possible time (the upcoming second). + t = t.Add(1*time.Second - time.Duration(t.Nanosecond())*time.Nanosecond) + + // This flag indicates whether a field has been incremented. + added := false + + // If no time is found within five years, return zero. + yearLimit := t.Year() + 5 + +WRAP: + if t.Year() > yearLimit { + return time.Time{} + } + + // Find the first applicable month. + // If it's this month, then do nothing. + for 1< 0 + dowMatch bool = 1< 0 + ) + + if s.Dom&starBit > 0 || s.Dow&starBit > 0 { + return domMatch && dowMatch + } + return domMatch || dowMatch +} diff --git a/modules/cron/spec_test.go b/modules/cron/spec_test.go new file mode 100644 index 00000000..855d7983 --- /dev/null +++ b/modules/cron/spec_test.go @@ -0,0 +1,173 @@ +package cron + +import ( + "testing" + "time" +) + +func TestActivation(t *testing.T) { + tests := []struct { + time, spec string + expected bool + }{ + // Every fifteen minutes. + {"Mon Jul 9 15:00 2012", "0 0/15 * * *", true}, + {"Mon Jul 9 15:45 2012", "0 0/15 * * *", true}, + {"Mon Jul 9 15:40 2012", "0 0/15 * * *", false}, + + // Every fifteen minutes, starting at 5 minutes. + {"Mon Jul 9 15:05 2012", "0 5/15 * * *", true}, + {"Mon Jul 9 15:20 2012", "0 5/15 * * *", true}, + {"Mon Jul 9 15:50 2012", "0 5/15 * * *", true}, + + // Named months + {"Sun Jul 15 15:00 2012", "0 0/15 * * Jul", true}, + {"Sun Jul 15 15:00 2012", "0 0/15 * * Jun", false}, + + // Everything set. + {"Sun Jul 15 08:30 2012", "0 30 08 ? Jul Sun", true}, + {"Sun Jul 15 08:30 2012", "0 30 08 15 Jul ?", true}, + {"Mon Jul 16 08:30 2012", "0 30 08 ? Jul Sun", false}, + {"Mon Jul 16 08:30 2012", "0 30 08 15 Jul ?", false}, + + // Predefined schedules + {"Mon Jul 9 15:00 2012", "@hourly", true}, + {"Mon Jul 9 15:04 2012", "@hourly", false}, + {"Mon Jul 9 15:00 2012", "@daily", false}, + {"Mon Jul 9 00:00 2012", "@daily", true}, + {"Mon Jul 9 00:00 2012", "@weekly", false}, + {"Sun Jul 8 00:00 2012", "@weekly", true}, + {"Sun Jul 8 01:00 2012", "@weekly", false}, + {"Sun Jul 8 00:00 2012", "@monthly", false}, + {"Sun Jul 1 00:00 2012", "@monthly", true}, + + // Test interaction of DOW and DOM. + // If both are specified, then only one needs to match. + {"Sun Jul 15 00:00 2012", "0 * * 1,15 * Sun", true}, + {"Fri Jun 15 00:00 2012", "0 * * 1,15 * Sun", true}, + {"Wed Aug 1 00:00 2012", "0 * * 1,15 * Sun", true}, + + // However, if one has a star, then both need to match. + {"Sun Jul 15 00:00 2012", "0 * * * * Mon", false}, + {"Sun Jul 15 00:00 2012", "0 * * */10 * Sun", false}, + {"Mon Jul 9 00:00 2012", "0 * * 1,15 * *", false}, + {"Sun Jul 15 00:00 2012", "0 * * 1,15 * *", true}, + {"Sun Jul 15 00:00 2012", "0 * * */2 * Sun", true}, + } + + for _, test := range tests { + sched, err := Parse(test.spec) + if err != nil { + t.Error(err) + continue + } + actual := sched.Next(getTime(test.time).Add(-1 * time.Second)) + expected := getTime(test.time) + if test.expected && expected != actual || !test.expected && expected == actual { + t.Errorf("Fail evaluating %s on %s: (expected) %s != %s (actual)", + test.spec, test.time, expected, actual) + } + } +} + +func TestNext(t *testing.T) { + runs := []struct { + time, spec string + expected string + }{ + // Simple cases + {"Mon Jul 9 14:45 2012", "0 0/15 * * *", "Mon Jul 9 15:00 2012"}, + {"Mon Jul 9 14:59 2012", "0 0/15 * * *", "Mon Jul 9 15:00 2012"}, + {"Mon Jul 9 14:59:59 2012", "0 0/15 * * *", "Mon Jul 9 15:00 2012"}, + + // Wrap around hours + {"Mon Jul 9 15:45 2012", "0 20-35/15 * * *", "Mon Jul 9 16:20 2012"}, + + // Wrap around days + {"Mon Jul 9 23:46 2012", "0 */15 * * *", "Tue Jul 10 00:00 2012"}, + {"Mon Jul 9 23:45 2012", "0 20-35/15 * * *", "Tue Jul 10 00:20 2012"}, + {"Mon Jul 9 23:35:51 2012", "15/35 20-35/15 * * *", "Tue Jul 10 00:20:15 2012"}, + {"Mon Jul 9 23:35:51 2012", "15/35 20-35/15 1/2 * *", "Tue Jul 10 01:20:15 2012"}, + {"Mon Jul 9 23:35:51 2012", "15/35 20-35/15 10-12 * *", "Tue Jul 10 10:20:15 2012"}, + + {"Mon Jul 9 23:35:51 2012", "15/35 20-35/15 1/2 */2 * *", "Thu Jul 11 01:20:15 2012"}, + {"Mon Jul 9 23:35:51 2012", "15/35 20-35/15 * 9-20 * *", "Wed Jul 10 00:20:15 2012"}, + {"Mon Jul 9 23:35:51 2012", "15/35 20-35/15 * 9-20 Jul *", "Wed Jul 10 00:20:15 2012"}, + + // Wrap around months + {"Mon Jul 9 23:35 2012", "0 0 0 9 Apr-Oct ?", "Thu Aug 9 00:00 2012"}, + {"Mon Jul 9 23:35 2012", "0 0 0 */5 Apr,Aug,Oct Mon", "Mon Aug 6 00:00 2012"}, + {"Mon Jul 9 23:35 2012", "0 0 0 */5 Oct Mon", "Mon Oct 1 00:00 2012"}, + + // Wrap around years + {"Mon Jul 9 23:35 2012", "0 0 0 * Feb Mon", "Mon Feb 4 00:00 2013"}, + {"Mon Jul 9 23:35 2012", "0 0 0 * Feb Mon/2", "Fri Feb 1 00:00 2013"}, + + // Wrap around minute, hour, day, month, and year + {"Mon Dec 31 23:59:45 2012", "0 * * * * *", "Tue Jan 1 00:00:00 2013"}, + + // Leap year + {"Mon Jul 9 23:35 2012", "0 0 0 29 Feb ?", "Mon Feb 29 00:00 2016"}, + + // Daylight savings time EST -> EDT + {"2012-03-11T00:00:00-0500", "0 30 2 11 Mar ?", "2013-03-11T02:30:00-0400"}, + + // Daylight savings time EDT -> EST + {"2012-11-04T00:00:00-0400", "0 30 2 04 Nov ?", "2012-11-04T02:30:00-0500"}, + {"2012-11-04T01:45:00-0400", "0 30 1 04 Nov ?", "2012-11-04T01:30:00-0500"}, + + // Unsatisfiable + {"Mon Jul 9 23:35 2012", "0 0 0 30 Feb ?", ""}, + {"Mon Jul 9 23:35 2012", "0 0 0 31 Apr ?", ""}, + } + + for _, c := range runs { + sched, err := Parse(c.spec) + if err != nil { + t.Error(err) + continue + } + actual := sched.Next(getTime(c.time)) + expected := getTime(c.expected) + if !actual.Equal(expected) { + t.Errorf("%s, \"%s\": (expected) %v != %v (actual)", c.time, c.spec, expected, actual) + } + } +} + +func TestErrors(t *testing.T) { + invalidSpecs := []string{ + "xyz", + "60 0 * * *", + "0 60 * * *", + "0 0 * * XYZ", + } + for _, spec := range invalidSpecs { + _, err := Parse(spec) + if err == nil { + t.Error("expected an error parsing: ", spec) + } + } +} + +func getTime(value string) time.Time { + if value == "" { + return time.Time{} + } + t, err := time.Parse("Mon Jan 2 15:04 2006", value) + if err != nil { + t, err = time.Parse("Mon Jan 2 15:04:05 2006", value) + if err != nil { + t, err = time.Parse("2006-01-02T15:04:05-0700", value) + if err != nil { + panic(err) + } + // Daylight savings time tests require location + if ny, err := time.LoadLocation("America/New_York"); err == nil { + t = t.In(ny) + } + } + } + + return t +} diff --git a/public/css/font-awesome.min.css b/public/css/font-awesome.min.css index 449d6ac5..3d920fc8 100644 --- a/public/css/font-awesome.min.css +++ b/public/css/font-awesome.min.css @@ -1,4 +1,4 @@ /*! - * Font Awesome 4.0.3 by @davegandy - http://fontawesome.io - @fontawesome + * Font Awesome 4.1.0 by @davegandy - http://fontawesome.io - @fontawesome * License - http://fontawesome.io/license (Font: SIL OFL 1.1, CSS: MIT License) - */@font-face{font-family:'FontAwesome';src:url('../fonts/fontawesome-webfont.eot?v=4.0.3');src:url('../fonts/fontawesome-webfont.eot?#iefix&v=4.0.3') format('embedded-opentype'),url('../fonts/fontawesome-webfont.woff?v=4.0.3') format('woff'),url('../fonts/fontawesome-webfont.ttf?v=4.0.3') format('truetype'),url('../fonts/fontawesome-webfont.svg?v=4.0.3#fontawesomeregular') format('svg');font-weight:normal;font-style:normal}.fa{display:inline-block;font-family:FontAwesome;font-style:normal;font-weight:normal;line-height:1;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.fa-lg{font-size:1.3333333333333333em;line-height:.75em;vertical-align:-15%}.fa-2x{font-size:2em}.fa-3x{font-size:3em}.fa-4x{font-size:4em}.fa-5x{font-size:5em}.fa-fw{width:1.2857142857142858em;text-align:center}.fa-ul{padding-left:0;margin-left:2.142857142857143em;list-style-type:none}.fa-ul>li{position:relative}.fa-li{position:absolute;left:-2.142857142857143em;width:2.142857142857143em;top:.14285714285714285em;text-align:center}.fa-li.fa-lg{left:-1.8571428571428572em}.fa-border{padding:.2em .25em .15em;border:solid .08em #eee;border-radius:.1em}.pull-right{float:right}.pull-left{float:left}.fa.pull-left{margin-right:.3em}.fa.pull-right{margin-left:.3em}.fa-spin{-webkit-animation:spin 2s infinite linear;-moz-animation:spin 2s infinite linear;-o-animation:spin 2s infinite linear;animation:spin 2s infinite linear}@-moz-keyframes spin{0%{-moz-transform:rotate(0deg)}100%{-moz-transform:rotate(359deg)}}@-webkit-keyframes spin{0%{-webkit-transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg)}}@-o-keyframes spin{0%{-o-transform:rotate(0deg)}100%{-o-transform:rotate(359deg)}}@-ms-keyframes spin{0%{-ms-transform:rotate(0deg)}100%{-ms-transform:rotate(359deg)}}@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(359deg)}}.fa-rotate-90{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=1);-webkit-transform:rotate(90deg);-moz-transform:rotate(90deg);-ms-transform:rotate(90deg);-o-transform:rotate(90deg);transform:rotate(90deg)}.fa-rotate-180{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=2);-webkit-transform:rotate(180deg);-moz-transform:rotate(180deg);-ms-transform:rotate(180deg);-o-transform:rotate(180deg);transform:rotate(180deg)}.fa-rotate-270{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=3);-webkit-transform:rotate(270deg);-moz-transform:rotate(270deg);-ms-transform:rotate(270deg);-o-transform:rotate(270deg);transform:rotate(270deg)}.fa-flip-horizontal{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=0,mirror=1);-webkit-transform:scale(-1,1);-moz-transform:scale(-1,1);-ms-transform:scale(-1,1);-o-transform:scale(-1,1);transform:scale(-1,1)}.fa-flip-vertical{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=2,mirror=1);-webkit-transform:scale(1,-1);-moz-transform:scale(1,-1);-ms-transform:scale(1,-1);-o-transform:scale(1,-1);transform:scale(1,-1)}.fa-stack{position:relative;display:inline-block;width:2em;height:2em;line-height:2em;vertical-align:middle}.fa-stack-1x,.fa-stack-2x{position:absolute;left:0;width:100%;text-align:center}.fa-stack-1x{line-height:inherit}.fa-stack-2x{font-size:2em}.fa-inverse{color:#fff}.fa-glass:before{content:"\f000"}.fa-music:before{content:"\f001"}.fa-search:before{content:"\f002"}.fa-envelope-o:before{content:"\f003"}.fa-heart:before{content:"\f004"}.fa-star:before{content:"\f005"}.fa-star-o:before{content:"\f006"}.fa-user:before{content:"\f007"}.fa-film:before{content:"\f008"}.fa-th-large:before{content:"\f009"}.fa-th:before{content:"\f00a"}.fa-th-list:before{content:"\f00b"}.fa-check:before{content:"\f00c"}.fa-times:before{content:"\f00d"}.fa-search-plus:before{content:"\f00e"}.fa-search-minus:before{content:"\f010"}.fa-power-off:before{content:"\f011"}.fa-signal:before{content:"\f012"}.fa-gear:before,.fa-cog:before{content:"\f013"}.fa-trash-o:before{content:"\f014"}.fa-home:before{content:"\f015"}.fa-file-o:before{content:"\f016"}.fa-clock-o:before{content:"\f017"}.fa-road:before{content:"\f018"}.fa-download:before{content:"\f019"}.fa-arrow-circle-o-down:before{content:"\f01a"}.fa-arrow-circle-o-up:before{content:"\f01b"}.fa-inbox:before{content:"\f01c"}.fa-play-circle-o:before{content:"\f01d"}.fa-rotate-right:before,.fa-repeat:before{content:"\f01e"}.fa-refresh:before{content:"\f021"}.fa-list-alt:before{content:"\f022"}.fa-lock:before{content:"\f023"}.fa-flag:before{content:"\f024"}.fa-headphones:before{content:"\f025"}.fa-volume-off:before{content:"\f026"}.fa-volume-down:before{content:"\f027"}.fa-volume-up:before{content:"\f028"}.fa-qrcode:before{content:"\f029"}.fa-barcode:before{content:"\f02a"}.fa-tag:before{content:"\f02b"}.fa-tags:before{content:"\f02c"}.fa-book:before{content:"\f02d"}.fa-bookmark:before{content:"\f02e"}.fa-print:before{content:"\f02f"}.fa-camera:before{content:"\f030"}.fa-font:before{content:"\f031"}.fa-bold:before{content:"\f032"}.fa-italic:before{content:"\f033"}.fa-text-height:before{content:"\f034"}.fa-text-width:before{content:"\f035"}.fa-align-left:before{content:"\f036"}.fa-align-center:before{content:"\f037"}.fa-align-right:before{content:"\f038"}.fa-align-justify:before{content:"\f039"}.fa-list:before{content:"\f03a"}.fa-dedent:before,.fa-outdent:before{content:"\f03b"}.fa-indent:before{content:"\f03c"}.fa-video-camera:before{content:"\f03d"}.fa-picture-o:before{content:"\f03e"}.fa-pencil:before{content:"\f040"}.fa-map-marker:before{content:"\f041"}.fa-adjust:before{content:"\f042"}.fa-tint:before{content:"\f043"}.fa-edit:before,.fa-pencil-square-o:before{content:"\f044"}.fa-share-square-o:before{content:"\f045"}.fa-check-square-o:before{content:"\f046"}.fa-arrows:before{content:"\f047"}.fa-step-backward:before{content:"\f048"}.fa-fast-backward:before{content:"\f049"}.fa-backward:before{content:"\f04a"}.fa-play:before{content:"\f04b"}.fa-pause:before{content:"\f04c"}.fa-stop:before{content:"\f04d"}.fa-forward:before{content:"\f04e"}.fa-fast-forward:before{content:"\f050"}.fa-step-forward:before{content:"\f051"}.fa-eject:before{content:"\f052"}.fa-chevron-left:before{content:"\f053"}.fa-chevron-right:before{content:"\f054"}.fa-plus-circle:before{content:"\f055"}.fa-minus-circle:before{content:"\f056"}.fa-times-circle:before{content:"\f057"}.fa-check-circle:before{content:"\f058"}.fa-question-circle:before{content:"\f059"}.fa-info-circle:before{content:"\f05a"}.fa-crosshairs:before{content:"\f05b"}.fa-times-circle-o:before{content:"\f05c"}.fa-check-circle-o:before{content:"\f05d"}.fa-ban:before{content:"\f05e"}.fa-arrow-left:before{content:"\f060"}.fa-arrow-right:before{content:"\f061"}.fa-arrow-up:before{content:"\f062"}.fa-arrow-down:before{content:"\f063"}.fa-mail-forward:before,.fa-share:before{content:"\f064"}.fa-expand:before{content:"\f065"}.fa-compress:before{content:"\f066"}.fa-plus:before{content:"\f067"}.fa-minus:before{content:"\f068"}.fa-asterisk:before{content:"\f069"}.fa-exclamation-circle:before{content:"\f06a"}.fa-gift:before{content:"\f06b"}.fa-leaf:before{content:"\f06c"}.fa-fire:before{content:"\f06d"}.fa-eye:before{content:"\f06e"}.fa-eye-slash:before{content:"\f070"}.fa-warning:before,.fa-exclamation-triangle:before{content:"\f071"}.fa-plane:before{content:"\f072"}.fa-calendar:before{content:"\f073"}.fa-random:before{content:"\f074"}.fa-comment:before{content:"\f075"}.fa-magnet:before{content:"\f076"}.fa-chevron-up:before{content:"\f077"}.fa-chevron-down:before{content:"\f078"}.fa-retweet:before{content:"\f079"}.fa-shopping-cart:before{content:"\f07a"}.fa-folder:before{content:"\f07b"}.fa-folder-open:before{content:"\f07c"}.fa-arrows-v:before{content:"\f07d"}.fa-arrows-h:before{content:"\f07e"}.fa-bar-chart-o:before{content:"\f080"}.fa-twitter-square:before{content:"\f081"}.fa-facebook-square:before{content:"\f082"}.fa-camera-retro:before{content:"\f083"}.fa-key:before{content:"\f084"}.fa-gears:before,.fa-cogs:before{content:"\f085"}.fa-comments:before{content:"\f086"}.fa-thumbs-o-up:before{content:"\f087"}.fa-thumbs-o-down:before{content:"\f088"}.fa-star-half:before{content:"\f089"}.fa-heart-o:before{content:"\f08a"}.fa-sign-out:before{content:"\f08b"}.fa-linkedin-square:before{content:"\f08c"}.fa-thumb-tack:before{content:"\f08d"}.fa-external-link:before{content:"\f08e"}.fa-sign-in:before{content:"\f090"}.fa-trophy:before{content:"\f091"}.fa-github-square:before{content:"\f092"}.fa-upload:before{content:"\f093"}.fa-lemon-o:before{content:"\f094"}.fa-phone:before{content:"\f095"}.fa-square-o:before{content:"\f096"}.fa-bookmark-o:before{content:"\f097"}.fa-phone-square:before{content:"\f098"}.fa-twitter:before{content:"\f099"}.fa-facebook:before{content:"\f09a"}.fa-github:before{content:"\f09b"}.fa-unlock:before{content:"\f09c"}.fa-credit-card:before{content:"\f09d"}.fa-rss:before{content:"\f09e"}.fa-hdd-o:before{content:"\f0a0"}.fa-bullhorn:before{content:"\f0a1"}.fa-bell:before{content:"\f0f3"}.fa-certificate:before{content:"\f0a3"}.fa-hand-o-right:before{content:"\f0a4"}.fa-hand-o-left:before{content:"\f0a5"}.fa-hand-o-up:before{content:"\f0a6"}.fa-hand-o-down:before{content:"\f0a7"}.fa-arrow-circle-left:before{content:"\f0a8"}.fa-arrow-circle-right:before{content:"\f0a9"}.fa-arrow-circle-up:before{content:"\f0aa"}.fa-arrow-circle-down:before{content:"\f0ab"}.fa-globe:before{content:"\f0ac"}.fa-wrench:before{content:"\f0ad"}.fa-tasks:before{content:"\f0ae"}.fa-filter:before{content:"\f0b0"}.fa-briefcase:before{content:"\f0b1"}.fa-arrows-alt:before{content:"\f0b2"}.fa-group:before,.fa-users:before{content:"\f0c0"}.fa-chain:before,.fa-link:before{content:"\f0c1"}.fa-cloud:before{content:"\f0c2"}.fa-flask:before{content:"\f0c3"}.fa-cut:before,.fa-scissors:before{content:"\f0c4"}.fa-copy:before,.fa-files-o:before{content:"\f0c5"}.fa-paperclip:before{content:"\f0c6"}.fa-save:before,.fa-floppy-o:before{content:"\f0c7"}.fa-square:before{content:"\f0c8"}.fa-bars:before{content:"\f0c9"}.fa-list-ul:before{content:"\f0ca"}.fa-list-ol:before{content:"\f0cb"}.fa-strikethrough:before{content:"\f0cc"}.fa-underline:before{content:"\f0cd"}.fa-table:before{content:"\f0ce"}.fa-magic:before{content:"\f0d0"}.fa-truck:before{content:"\f0d1"}.fa-pinterest:before{content:"\f0d2"}.fa-pinterest-square:before{content:"\f0d3"}.fa-google-plus-square:before{content:"\f0d4"}.fa-google-plus:before{content:"\f0d5"}.fa-money:before{content:"\f0d6"}.fa-caret-down:before{content:"\f0d7"}.fa-caret-up:before{content:"\f0d8"}.fa-caret-left:before{content:"\f0d9"}.fa-caret-right:before{content:"\f0da"}.fa-columns:before{content:"\f0db"}.fa-unsorted:before,.fa-sort:before{content:"\f0dc"}.fa-sort-down:before,.fa-sort-asc:before{content:"\f0dd"}.fa-sort-up:before,.fa-sort-desc:before{content:"\f0de"}.fa-envelope:before{content:"\f0e0"}.fa-linkedin:before{content:"\f0e1"}.fa-rotate-left:before,.fa-undo:before{content:"\f0e2"}.fa-legal:before,.fa-gavel:before{content:"\f0e3"}.fa-dashboard:before,.fa-tachometer:before{content:"\f0e4"}.fa-comment-o:before{content:"\f0e5"}.fa-comments-o:before{content:"\f0e6"}.fa-flash:before,.fa-bolt:before{content:"\f0e7"}.fa-sitemap:before{content:"\f0e8"}.fa-umbrella:before{content:"\f0e9"}.fa-paste:before,.fa-clipboard:before{content:"\f0ea"}.fa-lightbulb-o:before{content:"\f0eb"}.fa-exchange:before{content:"\f0ec"}.fa-cloud-download:before{content:"\f0ed"}.fa-cloud-upload:before{content:"\f0ee"}.fa-user-md:before{content:"\f0f0"}.fa-stethoscope:before{content:"\f0f1"}.fa-suitcase:before{content:"\f0f2"}.fa-bell-o:before{content:"\f0a2"}.fa-coffee:before{content:"\f0f4"}.fa-cutlery:before{content:"\f0f5"}.fa-file-text-o:before{content:"\f0f6"}.fa-building-o:before{content:"\f0f7"}.fa-hospital-o:before{content:"\f0f8"}.fa-ambulance:before{content:"\f0f9"}.fa-medkit:before{content:"\f0fa"}.fa-fighter-jet:before{content:"\f0fb"}.fa-beer:before{content:"\f0fc"}.fa-h-square:before{content:"\f0fd"}.fa-plus-square:before{content:"\f0fe"}.fa-angle-double-left:before{content:"\f100"}.fa-angle-double-right:before{content:"\f101"}.fa-angle-double-up:before{content:"\f102"}.fa-angle-double-down:before{content:"\f103"}.fa-angle-left:before{content:"\f104"}.fa-angle-right:before{content:"\f105"}.fa-angle-up:before{content:"\f106"}.fa-angle-down:before{content:"\f107"}.fa-desktop:before{content:"\f108"}.fa-laptop:before{content:"\f109"}.fa-tablet:before{content:"\f10a"}.fa-mobile-phone:before,.fa-mobile:before{content:"\f10b"}.fa-circle-o:before{content:"\f10c"}.fa-quote-left:before{content:"\f10d"}.fa-quote-right:before{content:"\f10e"}.fa-spinner:before{content:"\f110"}.fa-circle:before{content:"\f111"}.fa-mail-reply:before,.fa-reply:before{content:"\f112"}.fa-github-alt:before{content:"\f113"}.fa-folder-o:before{content:"\f114"}.fa-folder-open-o:before{content:"\f115"}.fa-smile-o:before{content:"\f118"}.fa-frown-o:before{content:"\f119"}.fa-meh-o:before{content:"\f11a"}.fa-gamepad:before{content:"\f11b"}.fa-keyboard-o:before{content:"\f11c"}.fa-flag-o:before{content:"\f11d"}.fa-flag-checkered:before{content:"\f11e"}.fa-terminal:before{content:"\f120"}.fa-code:before{content:"\f121"}.fa-reply-all:before{content:"\f122"}.fa-mail-reply-all:before{content:"\f122"}.fa-star-half-empty:before,.fa-star-half-full:before,.fa-star-half-o:before{content:"\f123"}.fa-location-arrow:before{content:"\f124"}.fa-crop:before{content:"\f125"}.fa-code-fork:before{content:"\f126"}.fa-unlink:before,.fa-chain-broken:before{content:"\f127"}.fa-question:before{content:"\f128"}.fa-info:before{content:"\f129"}.fa-exclamation:before{content:"\f12a"}.fa-superscript:before{content:"\f12b"}.fa-subscript:before{content:"\f12c"}.fa-eraser:before{content:"\f12d"}.fa-puzzle-piece:before{content:"\f12e"}.fa-microphone:before{content:"\f130"}.fa-microphone-slash:before{content:"\f131"}.fa-shield:before{content:"\f132"}.fa-calendar-o:before{content:"\f133"}.fa-fire-extinguisher:before{content:"\f134"}.fa-rocket:before{content:"\f135"}.fa-maxcdn:before{content:"\f136"}.fa-chevron-circle-left:before{content:"\f137"}.fa-chevron-circle-right:before{content:"\f138"}.fa-chevron-circle-up:before{content:"\f139"}.fa-chevron-circle-down:before{content:"\f13a"}.fa-html5:before{content:"\f13b"}.fa-css3:before{content:"\f13c"}.fa-anchor:before{content:"\f13d"}.fa-unlock-alt:before{content:"\f13e"}.fa-bullseye:before{content:"\f140"}.fa-ellipsis-h:before{content:"\f141"}.fa-ellipsis-v:before{content:"\f142"}.fa-rss-square:before{content:"\f143"}.fa-play-circle:before{content:"\f144"}.fa-ticket:before{content:"\f145"}.fa-minus-square:before{content:"\f146"}.fa-minus-square-o:before{content:"\f147"}.fa-level-up:before{content:"\f148"}.fa-level-down:before{content:"\f149"}.fa-check-square:before{content:"\f14a"}.fa-pencil-square:before{content:"\f14b"}.fa-external-link-square:before{content:"\f14c"}.fa-share-square:before{content:"\f14d"}.fa-compass:before{content:"\f14e"}.fa-toggle-down:before,.fa-caret-square-o-down:before{content:"\f150"}.fa-toggle-up:before,.fa-caret-square-o-up:before{content:"\f151"}.fa-toggle-right:before,.fa-caret-square-o-right:before{content:"\f152"}.fa-euro:before,.fa-eur:before{content:"\f153"}.fa-gbp:before{content:"\f154"}.fa-dollar:before,.fa-usd:before{content:"\f155"}.fa-rupee:before,.fa-inr:before{content:"\f156"}.fa-cny:before,.fa-rmb:before,.fa-yen:before,.fa-jpy:before{content:"\f157"}.fa-ruble:before,.fa-rouble:before,.fa-rub:before{content:"\f158"}.fa-won:before,.fa-krw:before{content:"\f159"}.fa-bitcoin:before,.fa-btc:before{content:"\f15a"}.fa-file:before{content:"\f15b"}.fa-file-text:before{content:"\f15c"}.fa-sort-alpha-asc:before{content:"\f15d"}.fa-sort-alpha-desc:before{content:"\f15e"}.fa-sort-amount-asc:before{content:"\f160"}.fa-sort-amount-desc:before{content:"\f161"}.fa-sort-numeric-asc:before{content:"\f162"}.fa-sort-numeric-desc:before{content:"\f163"}.fa-thumbs-up:before{content:"\f164"}.fa-thumbs-down:before{content:"\f165"}.fa-youtube-square:before{content:"\f166"}.fa-youtube:before{content:"\f167"}.fa-xing:before{content:"\f168"}.fa-xing-square:before{content:"\f169"}.fa-youtube-play:before{content:"\f16a"}.fa-dropbox:before{content:"\f16b"}.fa-stack-overflow:before{content:"\f16c"}.fa-instagram:before{content:"\f16d"}.fa-flickr:before{content:"\f16e"}.fa-adn:before{content:"\f170"}.fa-bitbucket:before{content:"\f171"}.fa-bitbucket-square:before{content:"\f172"}.fa-tumblr:before{content:"\f173"}.fa-tumblr-square:before{content:"\f174"}.fa-long-arrow-down:before{content:"\f175"}.fa-long-arrow-up:before{content:"\f176"}.fa-long-arrow-left:before{content:"\f177"}.fa-long-arrow-right:before{content:"\f178"}.fa-apple:before{content:"\f179"}.fa-windows:before{content:"\f17a"}.fa-android:before{content:"\f17b"}.fa-linux:before{content:"\f17c"}.fa-dribbble:before{content:"\f17d"}.fa-skype:before{content:"\f17e"}.fa-foursquare:before{content:"\f180"}.fa-trello:before{content:"\f181"}.fa-female:before{content:"\f182"}.fa-male:before{content:"\f183"}.fa-gittip:before{content:"\f184"}.fa-sun-o:before{content:"\f185"}.fa-moon-o:before{content:"\f186"}.fa-archive:before{content:"\f187"}.fa-bug:before{content:"\f188"}.fa-vk:before{content:"\f189"}.fa-weibo:before{content:"\f18a"}.fa-renren:before{content:"\f18b"}.fa-pagelines:before{content:"\f18c"}.fa-stack-exchange:before{content:"\f18d"}.fa-arrow-circle-o-right:before{content:"\f18e"}.fa-arrow-circle-o-left:before{content:"\f190"}.fa-toggle-left:before,.fa-caret-square-o-left:before{content:"\f191"}.fa-dot-circle-o:before{content:"\f192"}.fa-wheelchair:before{content:"\f193"}.fa-vimeo-square:before{content:"\f194"}.fa-turkish-lira:before,.fa-try:before{content:"\f195"}.fa-plus-square-o:before{content:"\f196"} \ No newline at end of file + */@font-face{font-family:'FontAwesome';src:url('../fonts/fontawesome-webfont.eot?v=4.1.0');src:url('../fonts/fontawesome-webfont.eot?#iefix&v=4.1.0') format('embedded-opentype'),url('../fonts/fontawesome-webfont.woff?v=4.1.0') format('woff'),url('../fonts/fontawesome-webfont.ttf?v=4.1.0') format('truetype'),url('../fonts/fontawesome-webfont.svg?v=4.1.0#fontawesomeregular') format('svg');font-weight:normal;font-style:normal}.fa{display:inline-block;font-family:FontAwesome;font-style:normal;font-weight:normal;line-height:1;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.fa-lg{font-size:1.33333333em;line-height:.75em;vertical-align:-15%}.fa-2x{font-size:2em}.fa-3x{font-size:3em}.fa-4x{font-size:4em}.fa-5x{font-size:5em}.fa-fw{width:1.28571429em;text-align:center}.fa-ul{padding-left:0;margin-left:2.14285714em;list-style-type:none}.fa-ul>li{position:relative}.fa-li{position:absolute;left:-2.14285714em;width:2.14285714em;top:.14285714em;text-align:center}.fa-li.fa-lg{left:-1.85714286em}.fa-border{padding:.2em .25em .15em;border:solid .08em #eee;border-radius:.1em}.pull-right{float:right}.pull-left{float:left}.fa.pull-left{margin-right:.3em}.fa.pull-right{margin-left:.3em}.fa-spin{-webkit-animation:spin 2s infinite linear;-moz-animation:spin 2s infinite linear;-o-animation:spin 2s infinite linear;animation:spin 2s infinite linear}@-moz-keyframes spin{0%{-moz-transform:rotate(0deg)}100%{-moz-transform:rotate(359deg)}}@-webkit-keyframes spin{0%{-webkit-transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg)}}@-o-keyframes spin{0%{-o-transform:rotate(0deg)}100%{-o-transform:rotate(359deg)}}@keyframes spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}.fa-rotate-90{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=1);-webkit-transform:rotate(90deg);-moz-transform:rotate(90deg);-ms-transform:rotate(90deg);-o-transform:rotate(90deg);transform:rotate(90deg)}.fa-rotate-180{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=2);-webkit-transform:rotate(180deg);-moz-transform:rotate(180deg);-ms-transform:rotate(180deg);-o-transform:rotate(180deg);transform:rotate(180deg)}.fa-rotate-270{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=3);-webkit-transform:rotate(270deg);-moz-transform:rotate(270deg);-ms-transform:rotate(270deg);-o-transform:rotate(270deg);transform:rotate(270deg)}.fa-flip-horizontal{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1);-webkit-transform:scale(-1, 1);-moz-transform:scale(-1, 1);-ms-transform:scale(-1, 1);-o-transform:scale(-1, 1);transform:scale(-1, 1)}.fa-flip-vertical{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1);-webkit-transform:scale(1, -1);-moz-transform:scale(1, -1);-ms-transform:scale(1, -1);-o-transform:scale(1, -1);transform:scale(1, -1)}.fa-stack{position:relative;display:inline-block;width:2em;height:2em;line-height:2em;vertical-align:middle}.fa-stack-1x,.fa-stack-2x{position:absolute;left:0;width:100%;text-align:center}.fa-stack-1x{line-height:inherit}.fa-stack-2x{font-size:2em}.fa-inverse{color:#fff}.fa-glass:before{content:"\f000"}.fa-music:before{content:"\f001"}.fa-search:before{content:"\f002"}.fa-envelope-o:before{content:"\f003"}.fa-heart:before{content:"\f004"}.fa-star:before{content:"\f005"}.fa-star-o:before{content:"\f006"}.fa-user:before{content:"\f007"}.fa-film:before{content:"\f008"}.fa-th-large:before{content:"\f009"}.fa-th:before{content:"\f00a"}.fa-th-list:before{content:"\f00b"}.fa-check:before{content:"\f00c"}.fa-times:before{content:"\f00d"}.fa-search-plus:before{content:"\f00e"}.fa-search-minus:before{content:"\f010"}.fa-power-off:before{content:"\f011"}.fa-signal:before{content:"\f012"}.fa-gear:before,.fa-cog:before{content:"\f013"}.fa-trash-o:before{content:"\f014"}.fa-home:before{content:"\f015"}.fa-file-o:before{content:"\f016"}.fa-clock-o:before{content:"\f017"}.fa-road:before{content:"\f018"}.fa-download:before{content:"\f019"}.fa-arrow-circle-o-down:before{content:"\f01a"}.fa-arrow-circle-o-up:before{content:"\f01b"}.fa-inbox:before{content:"\f01c"}.fa-play-circle-o:before{content:"\f01d"}.fa-rotate-right:before,.fa-repeat:before{content:"\f01e"}.fa-refresh:before{content:"\f021"}.fa-list-alt:before{content:"\f022"}.fa-lock:before{content:"\f023"}.fa-flag:before{content:"\f024"}.fa-headphones:before{content:"\f025"}.fa-volume-off:before{content:"\f026"}.fa-volume-down:before{content:"\f027"}.fa-volume-up:before{content:"\f028"}.fa-qrcode:before{content:"\f029"}.fa-barcode:before{content:"\f02a"}.fa-tag:before{content:"\f02b"}.fa-tags:before{content:"\f02c"}.fa-book:before{content:"\f02d"}.fa-bookmark:before{content:"\f02e"}.fa-print:before{content:"\f02f"}.fa-camera:before{content:"\f030"}.fa-font:before{content:"\f031"}.fa-bold:before{content:"\f032"}.fa-italic:before{content:"\f033"}.fa-text-height:before{content:"\f034"}.fa-text-width:before{content:"\f035"}.fa-align-left:before{content:"\f036"}.fa-align-center:before{content:"\f037"}.fa-align-right:before{content:"\f038"}.fa-align-justify:before{content:"\f039"}.fa-list:before{content:"\f03a"}.fa-dedent:before,.fa-outdent:before{content:"\f03b"}.fa-indent:before{content:"\f03c"}.fa-video-camera:before{content:"\f03d"}.fa-photo:before,.fa-image:before,.fa-picture-o:before{content:"\f03e"}.fa-pencil:before{content:"\f040"}.fa-map-marker:before{content:"\f041"}.fa-adjust:before{content:"\f042"}.fa-tint:before{content:"\f043"}.fa-edit:before,.fa-pencil-square-o:before{content:"\f044"}.fa-share-square-o:before{content:"\f045"}.fa-check-square-o:before{content:"\f046"}.fa-arrows:before{content:"\f047"}.fa-step-backward:before{content:"\f048"}.fa-fast-backward:before{content:"\f049"}.fa-backward:before{content:"\f04a"}.fa-play:before{content:"\f04b"}.fa-pause:before{content:"\f04c"}.fa-stop:before{content:"\f04d"}.fa-forward:before{content:"\f04e"}.fa-fast-forward:before{content:"\f050"}.fa-step-forward:before{content:"\f051"}.fa-eject:before{content:"\f052"}.fa-chevron-left:before{content:"\f053"}.fa-chevron-right:before{content:"\f054"}.fa-plus-circle:before{content:"\f055"}.fa-minus-circle:before{content:"\f056"}.fa-times-circle:before{content:"\f057"}.fa-check-circle:before{content:"\f058"}.fa-question-circle:before{content:"\f059"}.fa-info-circle:before{content:"\f05a"}.fa-crosshairs:before{content:"\f05b"}.fa-times-circle-o:before{content:"\f05c"}.fa-check-circle-o:before{content:"\f05d"}.fa-ban:before{content:"\f05e"}.fa-arrow-left:before{content:"\f060"}.fa-arrow-right:before{content:"\f061"}.fa-arrow-up:before{content:"\f062"}.fa-arrow-down:before{content:"\f063"}.fa-mail-forward:before,.fa-share:before{content:"\f064"}.fa-expand:before{content:"\f065"}.fa-compress:before{content:"\f066"}.fa-plus:before{content:"\f067"}.fa-minus:before{content:"\f068"}.fa-asterisk:before{content:"\f069"}.fa-exclamation-circle:before{content:"\f06a"}.fa-gift:before{content:"\f06b"}.fa-leaf:before{content:"\f06c"}.fa-fire:before{content:"\f06d"}.fa-eye:before{content:"\f06e"}.fa-eye-slash:before{content:"\f070"}.fa-warning:before,.fa-exclamation-triangle:before{content:"\f071"}.fa-plane:before{content:"\f072"}.fa-calendar:before{content:"\f073"}.fa-random:before{content:"\f074"}.fa-comment:before{content:"\f075"}.fa-magnet:before{content:"\f076"}.fa-chevron-up:before{content:"\f077"}.fa-chevron-down:before{content:"\f078"}.fa-retweet:before{content:"\f079"}.fa-shopping-cart:before{content:"\f07a"}.fa-folder:before{content:"\f07b"}.fa-folder-open:before{content:"\f07c"}.fa-arrows-v:before{content:"\f07d"}.fa-arrows-h:before{content:"\f07e"}.fa-bar-chart-o:before{content:"\f080"}.fa-twitter-square:before{content:"\f081"}.fa-facebook-square:before{content:"\f082"}.fa-camera-retro:before{content:"\f083"}.fa-key:before{content:"\f084"}.fa-gears:before,.fa-cogs:before{content:"\f085"}.fa-comments:before{content:"\f086"}.fa-thumbs-o-up:before{content:"\f087"}.fa-thumbs-o-down:before{content:"\f088"}.fa-star-half:before{content:"\f089"}.fa-heart-o:before{content:"\f08a"}.fa-sign-out:before{content:"\f08b"}.fa-linkedin-square:before{content:"\f08c"}.fa-thumb-tack:before{content:"\f08d"}.fa-external-link:before{content:"\f08e"}.fa-sign-in:before{content:"\f090"}.fa-trophy:before{content:"\f091"}.fa-github-square:before{content:"\f092"}.fa-upload:before{content:"\f093"}.fa-lemon-o:before{content:"\f094"}.fa-phone:before{content:"\f095"}.fa-square-o:before{content:"\f096"}.fa-bookmark-o:before{content:"\f097"}.fa-phone-square:before{content:"\f098"}.fa-twitter:before{content:"\f099"}.fa-facebook:before{content:"\f09a"}.fa-github:before{content:"\f09b"}.fa-unlock:before{content:"\f09c"}.fa-credit-card:before{content:"\f09d"}.fa-rss:before{content:"\f09e"}.fa-hdd-o:before{content:"\f0a0"}.fa-bullhorn:before{content:"\f0a1"}.fa-bell:before{content:"\f0f3"}.fa-certificate:before{content:"\f0a3"}.fa-hand-o-right:before{content:"\f0a4"}.fa-hand-o-left:before{content:"\f0a5"}.fa-hand-o-up:before{content:"\f0a6"}.fa-hand-o-down:before{content:"\f0a7"}.fa-arrow-circle-left:before{content:"\f0a8"}.fa-arrow-circle-right:before{content:"\f0a9"}.fa-arrow-circle-up:before{content:"\f0aa"}.fa-arrow-circle-down:before{content:"\f0ab"}.fa-globe:before{content:"\f0ac"}.fa-wrench:before{content:"\f0ad"}.fa-tasks:before{content:"\f0ae"}.fa-filter:before{content:"\f0b0"}.fa-briefcase:before{content:"\f0b1"}.fa-arrows-alt:before{content:"\f0b2"}.fa-group:before,.fa-users:before{content:"\f0c0"}.fa-chain:before,.fa-link:before{content:"\f0c1"}.fa-cloud:before{content:"\f0c2"}.fa-flask:before{content:"\f0c3"}.fa-cut:before,.fa-scissors:before{content:"\f0c4"}.fa-copy:before,.fa-files-o:before{content:"\f0c5"}.fa-paperclip:before{content:"\f0c6"}.fa-save:before,.fa-floppy-o:before{content:"\f0c7"}.fa-square:before{content:"\f0c8"}.fa-navicon:before,.fa-reorder:before,.fa-bars:before{content:"\f0c9"}.fa-list-ul:before{content:"\f0ca"}.fa-list-ol:before{content:"\f0cb"}.fa-strikethrough:before{content:"\f0cc"}.fa-underline:before{content:"\f0cd"}.fa-table:before{content:"\f0ce"}.fa-magic:before{content:"\f0d0"}.fa-truck:before{content:"\f0d1"}.fa-pinterest:before{content:"\f0d2"}.fa-pinterest-square:before{content:"\f0d3"}.fa-google-plus-square:before{content:"\f0d4"}.fa-google-plus:before{content:"\f0d5"}.fa-money:before{content:"\f0d6"}.fa-caret-down:before{content:"\f0d7"}.fa-caret-up:before{content:"\f0d8"}.fa-caret-left:before{content:"\f0d9"}.fa-caret-right:before{content:"\f0da"}.fa-columns:before{content:"\f0db"}.fa-unsorted:before,.fa-sort:before{content:"\f0dc"}.fa-sort-down:before,.fa-sort-desc:before{content:"\f0dd"}.fa-sort-up:before,.fa-sort-asc:before{content:"\f0de"}.fa-envelope:before{content:"\f0e0"}.fa-linkedin:before{content:"\f0e1"}.fa-rotate-left:before,.fa-undo:before{content:"\f0e2"}.fa-legal:before,.fa-gavel:before{content:"\f0e3"}.fa-dashboard:before,.fa-tachometer:before{content:"\f0e4"}.fa-comment-o:before{content:"\f0e5"}.fa-comments-o:before{content:"\f0e6"}.fa-flash:before,.fa-bolt:before{content:"\f0e7"}.fa-sitemap:before{content:"\f0e8"}.fa-umbrella:before{content:"\f0e9"}.fa-paste:before,.fa-clipboard:before{content:"\f0ea"}.fa-lightbulb-o:before{content:"\f0eb"}.fa-exchange:before{content:"\f0ec"}.fa-cloud-download:before{content:"\f0ed"}.fa-cloud-upload:before{content:"\f0ee"}.fa-user-md:before{content:"\f0f0"}.fa-stethoscope:before{content:"\f0f1"}.fa-suitcase:before{content:"\f0f2"}.fa-bell-o:before{content:"\f0a2"}.fa-coffee:before{content:"\f0f4"}.fa-cutlery:before{content:"\f0f5"}.fa-file-text-o:before{content:"\f0f6"}.fa-building-o:before{content:"\f0f7"}.fa-hospital-o:before{content:"\f0f8"}.fa-ambulance:before{content:"\f0f9"}.fa-medkit:before{content:"\f0fa"}.fa-fighter-jet:before{content:"\f0fb"}.fa-beer:before{content:"\f0fc"}.fa-h-square:before{content:"\f0fd"}.fa-plus-square:before{content:"\f0fe"}.fa-angle-double-left:before{content:"\f100"}.fa-angle-double-right:before{content:"\f101"}.fa-angle-double-up:before{content:"\f102"}.fa-angle-double-down:before{content:"\f103"}.fa-angle-left:before{content:"\f104"}.fa-angle-right:before{content:"\f105"}.fa-angle-up:before{content:"\f106"}.fa-angle-down:before{content:"\f107"}.fa-desktop:before{content:"\f108"}.fa-laptop:before{content:"\f109"}.fa-tablet:before{content:"\f10a"}.fa-mobile-phone:before,.fa-mobile:before{content:"\f10b"}.fa-circle-o:before{content:"\f10c"}.fa-quote-left:before{content:"\f10d"}.fa-quote-right:before{content:"\f10e"}.fa-spinner:before{content:"\f110"}.fa-circle:before{content:"\f111"}.fa-mail-reply:before,.fa-reply:before{content:"\f112"}.fa-github-alt:before{content:"\f113"}.fa-folder-o:before{content:"\f114"}.fa-folder-open-o:before{content:"\f115"}.fa-smile-o:before{content:"\f118"}.fa-frown-o:before{content:"\f119"}.fa-meh-o:before{content:"\f11a"}.fa-gamepad:before{content:"\f11b"}.fa-keyboard-o:before{content:"\f11c"}.fa-flag-o:before{content:"\f11d"}.fa-flag-checkered:before{content:"\f11e"}.fa-terminal:before{content:"\f120"}.fa-code:before{content:"\f121"}.fa-mail-reply-all:before,.fa-reply-all:before{content:"\f122"}.fa-star-half-empty:before,.fa-star-half-full:before,.fa-star-half-o:before{content:"\f123"}.fa-location-arrow:before{content:"\f124"}.fa-crop:before{content:"\f125"}.fa-code-fork:before{content:"\f126"}.fa-unlink:before,.fa-chain-broken:before{content:"\f127"}.fa-question:before{content:"\f128"}.fa-info:before{content:"\f129"}.fa-exclamation:before{content:"\f12a"}.fa-superscript:before{content:"\f12b"}.fa-subscript:before{content:"\f12c"}.fa-eraser:before{content:"\f12d"}.fa-puzzle-piece:before{content:"\f12e"}.fa-microphone:before{content:"\f130"}.fa-microphone-slash:before{content:"\f131"}.fa-shield:before{content:"\f132"}.fa-calendar-o:before{content:"\f133"}.fa-fire-extinguisher:before{content:"\f134"}.fa-rocket:before{content:"\f135"}.fa-maxcdn:before{content:"\f136"}.fa-chevron-circle-left:before{content:"\f137"}.fa-chevron-circle-right:before{content:"\f138"}.fa-chevron-circle-up:before{content:"\f139"}.fa-chevron-circle-down:before{content:"\f13a"}.fa-html5:before{content:"\f13b"}.fa-css3:before{content:"\f13c"}.fa-anchor:before{content:"\f13d"}.fa-unlock-alt:before{content:"\f13e"}.fa-bullseye:before{content:"\f140"}.fa-ellipsis-h:before{content:"\f141"}.fa-ellipsis-v:before{content:"\f142"}.fa-rss-square:before{content:"\f143"}.fa-play-circle:before{content:"\f144"}.fa-ticket:before{content:"\f145"}.fa-minus-square:before{content:"\f146"}.fa-minus-square-o:before{content:"\f147"}.fa-level-up:before{content:"\f148"}.fa-level-down:before{content:"\f149"}.fa-check-square:before{content:"\f14a"}.fa-pencil-square:before{content:"\f14b"}.fa-external-link-square:before{content:"\f14c"}.fa-share-square:before{content:"\f14d"}.fa-compass:before{content:"\f14e"}.fa-toggle-down:before,.fa-caret-square-o-down:before{content:"\f150"}.fa-toggle-up:before,.fa-caret-square-o-up:before{content:"\f151"}.fa-toggle-right:before,.fa-caret-square-o-right:before{content:"\f152"}.fa-euro:before,.fa-eur:before{content:"\f153"}.fa-gbp:before{content:"\f154"}.fa-dollar:before,.fa-usd:before{content:"\f155"}.fa-rupee:before,.fa-inr:before{content:"\f156"}.fa-cny:before,.fa-rmb:before,.fa-yen:before,.fa-jpy:before{content:"\f157"}.fa-ruble:before,.fa-rouble:before,.fa-rub:before{content:"\f158"}.fa-won:before,.fa-krw:before{content:"\f159"}.fa-bitcoin:before,.fa-btc:before{content:"\f15a"}.fa-file:before{content:"\f15b"}.fa-file-text:before{content:"\f15c"}.fa-sort-alpha-asc:before{content:"\f15d"}.fa-sort-alpha-desc:before{content:"\f15e"}.fa-sort-amount-asc:before{content:"\f160"}.fa-sort-amount-desc:before{content:"\f161"}.fa-sort-numeric-asc:before{content:"\f162"}.fa-sort-numeric-desc:before{content:"\f163"}.fa-thumbs-up:before{content:"\f164"}.fa-thumbs-down:before{content:"\f165"}.fa-youtube-square:before{content:"\f166"}.fa-youtube:before{content:"\f167"}.fa-xing:before{content:"\f168"}.fa-xing-square:before{content:"\f169"}.fa-youtube-play:before{content:"\f16a"}.fa-dropbox:before{content:"\f16b"}.fa-stack-overflow:before{content:"\f16c"}.fa-instagram:before{content:"\f16d"}.fa-flickr:before{content:"\f16e"}.fa-adn:before{content:"\f170"}.fa-bitbucket:before{content:"\f171"}.fa-bitbucket-square:before{content:"\f172"}.fa-tumblr:before{content:"\f173"}.fa-tumblr-square:before{content:"\f174"}.fa-long-arrow-down:before{content:"\f175"}.fa-long-arrow-up:before{content:"\f176"}.fa-long-arrow-left:before{content:"\f177"}.fa-long-arrow-right:before{content:"\f178"}.fa-apple:before{content:"\f179"}.fa-windows:before{content:"\f17a"}.fa-android:before{content:"\f17b"}.fa-linux:before{content:"\f17c"}.fa-dribbble:before{content:"\f17d"}.fa-skype:before{content:"\f17e"}.fa-foursquare:before{content:"\f180"}.fa-trello:before{content:"\f181"}.fa-female:before{content:"\f182"}.fa-male:before{content:"\f183"}.fa-gittip:before{content:"\f184"}.fa-sun-o:before{content:"\f185"}.fa-moon-o:before{content:"\f186"}.fa-archive:before{content:"\f187"}.fa-bug:before{content:"\f188"}.fa-vk:before{content:"\f189"}.fa-weibo:before{content:"\f18a"}.fa-renren:before{content:"\f18b"}.fa-pagelines:before{content:"\f18c"}.fa-stack-exchange:before{content:"\f18d"}.fa-arrow-circle-o-right:before{content:"\f18e"}.fa-arrow-circle-o-left:before{content:"\f190"}.fa-toggle-left:before,.fa-caret-square-o-left:before{content:"\f191"}.fa-dot-circle-o:before{content:"\f192"}.fa-wheelchair:before{content:"\f193"}.fa-vimeo-square:before{content:"\f194"}.fa-turkish-lira:before,.fa-try:before{content:"\f195"}.fa-plus-square-o:before{content:"\f196"}.fa-space-shuttle:before{content:"\f197"}.fa-slack:before{content:"\f198"}.fa-envelope-square:before{content:"\f199"}.fa-wordpress:before{content:"\f19a"}.fa-openid:before{content:"\f19b"}.fa-institution:before,.fa-bank:before,.fa-university:before{content:"\f19c"}.fa-mortar-board:before,.fa-graduation-cap:before{content:"\f19d"}.fa-yahoo:before{content:"\f19e"}.fa-google:before{content:"\f1a0"}.fa-reddit:before{content:"\f1a1"}.fa-reddit-square:before{content:"\f1a2"}.fa-stumbleupon-circle:before{content:"\f1a3"}.fa-stumbleupon:before{content:"\f1a4"}.fa-delicious:before{content:"\f1a5"}.fa-digg:before{content:"\f1a6"}.fa-pied-piper-square:before,.fa-pied-piper:before{content:"\f1a7"}.fa-pied-piper-alt:before{content:"\f1a8"}.fa-drupal:before{content:"\f1a9"}.fa-joomla:before{content:"\f1aa"}.fa-language:before{content:"\f1ab"}.fa-fax:before{content:"\f1ac"}.fa-building:before{content:"\f1ad"}.fa-child:before{content:"\f1ae"}.fa-paw:before{content:"\f1b0"}.fa-spoon:before{content:"\f1b1"}.fa-cube:before{content:"\f1b2"}.fa-cubes:before{content:"\f1b3"}.fa-behance:before{content:"\f1b4"}.fa-behance-square:before{content:"\f1b5"}.fa-steam:before{content:"\f1b6"}.fa-steam-square:before{content:"\f1b7"}.fa-recycle:before{content:"\f1b8"}.fa-automobile:before,.fa-car:before{content:"\f1b9"}.fa-cab:before,.fa-taxi:before{content:"\f1ba"}.fa-tree:before{content:"\f1bb"}.fa-spotify:before{content:"\f1bc"}.fa-deviantart:before{content:"\f1bd"}.fa-soundcloud:before{content:"\f1be"}.fa-database:before{content:"\f1c0"}.fa-file-pdf-o:before{content:"\f1c1"}.fa-file-word-o:before{content:"\f1c2"}.fa-file-excel-o:before{content:"\f1c3"}.fa-file-powerpoint-o:before{content:"\f1c4"}.fa-file-photo-o:before,.fa-file-picture-o:before,.fa-file-image-o:before{content:"\f1c5"}.fa-file-zip-o:before,.fa-file-archive-o:before{content:"\f1c6"}.fa-file-sound-o:before,.fa-file-audio-o:before{content:"\f1c7"}.fa-file-movie-o:before,.fa-file-video-o:before{content:"\f1c8"}.fa-file-code-o:before{content:"\f1c9"}.fa-vine:before{content:"\f1ca"}.fa-codepen:before{content:"\f1cb"}.fa-jsfiddle:before{content:"\f1cc"}.fa-life-bouy:before,.fa-life-saver:before,.fa-support:before,.fa-life-ring:before{content:"\f1cd"}.fa-circle-o-notch:before{content:"\f1ce"}.fa-ra:before,.fa-rebel:before{content:"\f1d0"}.fa-ge:before,.fa-empire:before{content:"\f1d1"}.fa-git-square:before{content:"\f1d2"}.fa-git:before{content:"\f1d3"}.fa-hacker-news:before{content:"\f1d4"}.fa-tencent-weibo:before{content:"\f1d5"}.fa-qq:before{content:"\f1d6"}.fa-wechat:before,.fa-weixin:before{content:"\f1d7"}.fa-send:before,.fa-paper-plane:before{content:"\f1d8"}.fa-send-o:before,.fa-paper-plane-o:before{content:"\f1d9"}.fa-history:before{content:"\f1da"}.fa-circle-thin:before{content:"\f1db"}.fa-header:before{content:"\f1dc"}.fa-paragraph:before{content:"\f1dd"}.fa-sliders:before{content:"\f1de"}.fa-share-alt:before{content:"\f1e0"}.fa-share-alt-square:before{content:"\f1e1"}.fa-bomb:before{content:"\f1e2"} \ No newline at end of file diff --git a/public/fonts/FontAwesome.otf b/public/fonts/FontAwesome.otf index 8b0f54e4..3461e3fc 100644 Binary files a/public/fonts/FontAwesome.otf and b/public/fonts/FontAwesome.otf differ diff --git a/public/fonts/fontawesome-webfont.eot b/public/fonts/fontawesome-webfont.eot index 7c79c6a6..6cfd5660 100755 Binary files a/public/fonts/fontawesome-webfont.eot and b/public/fonts/fontawesome-webfont.eot differ diff --git a/public/fonts/fontawesome-webfont.svg b/public/fonts/fontawesome-webfont.svg index 45fdf338..a9f84695 100755 --- a/public/fonts/fontawesome-webfont.svg +++ b/public/fonts/fontawesome-webfont.svg @@ -14,10 +14,11 @@ + - + - + @@ -30,385 +31,474 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/public/fonts/fontawesome-webfont.ttf b/public/fonts/fontawesome-webfont.ttf index e89738de..5cd6cff6 100755 Binary files a/public/fonts/fontawesome-webfont.ttf and b/public/fonts/fontawesome-webfont.ttf differ diff --git a/public/fonts/fontawesome-webfont.woff b/public/fonts/fontawesome-webfont.woff index 8c1748aa..9eaecb37 100755 Binary files a/public/fonts/fontawesome-webfont.woff and b/public/fonts/fontawesome-webfont.woff differ diff --git a/routers/admin/admin.go b/routers/admin/admin.go index 56eba88a..d4b49a9e 100644 --- a/routers/admin/admin.go +++ b/routers/admin/admin.go @@ -14,6 +14,7 @@ import ( "github.com/gogits/gogs/models" "github.com/gogits/gogs/modules/base" + "github.com/gogits/gogs/modules/cron" "github.com/gogits/gogs/modules/middleware" "github.com/gogits/gogs/modules/setting" ) @@ -228,3 +229,19 @@ func Config(ctx *middleware.Context) { ctx.HTML(200, "admin/config") } + +func Monitor(ctx *middleware.Context) { + ctx.Data["Title"] = "Monitoring Center" + ctx.Data["PageIsMonitor"] = true + + tab := ctx.Query("tab") + switch tab { + case "process": + ctx.Data["PageIsMonitorProcess"] = true + default: + ctx.Data["PageIsMonitorCron"] = true + ctx.Data["Entries"] = cron.ListEntries() + } + + ctx.HTML(200, "admin/monitor/cron") +} diff --git a/templates/VERSION b/templates/VERSION index 8e45ca59..c2606e90 100644 --- a/templates/VERSION +++ b/templates/VERSION @@ -1 +1 @@ -0.4.4.0612 Alpha \ No newline at end of file +0.4.4.0613 Alpha \ No newline at end of file diff --git a/templates/admin/monitor/cron.tmpl b/templates/admin/monitor/cron.tmpl new file mode 100644 index 00000000..a04c017e --- /dev/null +++ b/templates/admin/monitor/cron.tmpl @@ -0,0 +1,40 @@ +{{template "base/head" .}} +{{template "base/navbar" .}} +
    + {{template "admin/nav" .}} +
    + +
    +
    + {{if .PageIsMonitorCron}} + + + + + + + + + + + + {{range .Entries}} + + + + + + + + {{end}} + +
    NameScheduleNext TimePrevious TimeExecute Times
    {{.Description}}{{.Spec}}{{.Next}}{{.Prev}}{{.ExecTimes}}
    + {{end}} +
    +
    +
    +
    +{{template "base/footer" .}} \ No newline at end of file diff --git a/templates/admin/nav.tmpl b/templates/admin/nav.tmpl index 5ba44957..b78e0bd1 100644 --- a/templates/admin/nav.tmpl +++ b/templates/admin/nav.tmpl @@ -5,5 +5,6 @@
  • Repositories
  • Authentication
  • Configuration
  • +
  • Monitoring
  • \ No newline at end of file diff --git a/templates/base/head.tmpl b/templates/base/head.tmpl index e7759c29..a58299f8 100644 --- a/templates/base/head.tmpl +++ b/templates/base/head.tmpl @@ -14,7 +14,7 @@ {{if CdnMode}} - + diff --git a/templates/user/signin.tmpl b/templates/user/signin.tmpl index 09ce249f..9a8aa199 100644 --- a/templates/user/signin.tmpl +++ b/templates/user/signin.tmpl @@ -62,7 +62,7 @@ {{if .OauthService.GitHub}}GitHub{{end}} {{if .OauthService.Google}}Google{{end}} {{if .OauthService.Twitter}}Twitter{{end}} - {{if .OauthService.Tencent}}Tencent QQ{{end}} + {{if not .OauthService.Tencent}}Tencent QQ{{end}} {{if .OauthService.Weibo}}Weibo{{end}} {{end}}{{end}} -- cgit v1.2.3 From f147ad619a68440ef6c30d797a8217e687e8d51d Mon Sep 17 00:00:00 2001 From: Unknown Date: Thu, 19 Jun 2014 01:08:03 -0400 Subject: Basic process manager --- cmd/serve.go | 6 +- gogs.go | 2 +- models/fix.go | 6 - models/git_diff.go | 13 +- models/publickey.go | 3 +- models/repo.go | 268 +++++++++++++++++++---------------- modules/process/manager.go | 89 ++++++++++++ routers/admin/admin.go | 5 +- templates/VERSION | 2 +- templates/admin/monitor/process.tmpl | 38 +++++ 10 files changed, 289 insertions(+), 143 deletions(-) delete mode 100644 models/fix.go create mode 100644 modules/process/manager.go create mode 100644 templates/admin/monitor/process.tmpl (limited to 'cmd') diff --git a/cmd/serve.go b/cmd/serve.go index 3a17bf9f..a21500c7 100644 --- a/cmd/serve.go +++ b/cmd/serve.go @@ -32,7 +32,7 @@ func newLogger(logPath string) { f, err := os.OpenFile(logPath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, os.ModePerm) if err != nil { - qlog.Fatal(err) + qlog.Fatal("Fail to open log file(%s): %v", logPath, err) } qlog.SetOutput(f) @@ -185,8 +185,8 @@ func runServ(k *cli.Context) { gitcmd.Stdout = os.Stdout gitcmd.Stdin = os.Stdin gitcmd.Stderr = os.Stderr - - if err = gitcmd.Run(); err != nil { + err = gitcmd.Run() + if err != nil { println("Gogs: internal error:", err) qlog.Fatalf("Fail to execute git command: %v", err) } diff --git a/gogs.go b/gogs.go index b4129e90..7e1459e5 100644 --- a/gogs.go +++ b/gogs.go @@ -17,7 +17,7 @@ import ( "github.com/gogits/gogs/modules/setting" ) -const APP_VER = "0.4.4.0613 Alpha" +const APP_VER = "0.4.4.0619 Alpha" func init() { runtime.GOMAXPROCS(runtime.NumCPU()) diff --git a/models/fix.go b/models/fix.go deleted file mode 100644 index 9fc141bd..00000000 --- a/models/fix.go +++ /dev/null @@ -1,6 +0,0 @@ -package models - -func Fix() error { - _, err := orm.Exec("alter table repository drop column num_releases") - return err -} diff --git a/models/git_diff.go b/models/git_diff.go index 5b5a46a1..ed114b75 100644 --- a/models/git_diff.go +++ b/models/git_diff.go @@ -6,6 +6,7 @@ package models import ( "bufio" + "fmt" "io" "os" "os/exec" @@ -15,6 +16,7 @@ import ( "github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/log" + "github.com/gogits/gogs/modules/process" ) // Diff line types. @@ -67,7 +69,7 @@ func (diff *Diff) NumFiles() int { const DIFF_HEAD = "diff --git " -func ParsePatch(cmd *exec.Cmd, reader io.Reader) (*Diff, error) { +func ParsePatch(pid int64, cmd *exec.Cmd, reader io.Reader) (*Diff, error) { scanner := bufio.NewScanner(reader) var ( curFile *DiffFile @@ -169,11 +171,8 @@ func ParsePatch(cmd *exec.Cmd, reader io.Reader) (*Diff, error) { } // In case process became zombie. - if !cmd.ProcessState.Exited() { - log.Debug("git_diff.ParsePatch: process doesn't exit and now will be killed") - if err := cmd.Process.Kill(); err != nil { - log.Error("git_diff.ParsePatch: fail to kill zombie process: %v", err) - } + if err := process.Kill(pid); err != nil { + log.Error("git_diff.ParsePatch(Kill): %v", err) } return diff, nil } @@ -207,5 +206,5 @@ func GetDiff(repoPath, commitid string) (*Diff, error) { wr.Close() }() defer rd.Close() - return ParsePatch(cmd, rd) + return ParsePatch(process.Add(fmt.Sprintf("GetDiff(%s)", repoPath), cmd), cmd, rd) } diff --git a/models/publickey.go b/models/publickey.go index 76dc0cc7..72b45c5b 100644 --- a/models/publickey.go +++ b/models/publickey.go @@ -22,6 +22,7 @@ import ( qlog "github.com/qiniu/log" "github.com/gogits/gogs/modules/log" + "github.com/gogits/gogs/modules/process" ) const ( @@ -121,7 +122,7 @@ func AddPublicKey(key *PublicKey) (err error) { if err = ioutil.WriteFile(tmpPath, []byte(key.Content), os.ModePerm); err != nil { return err } - stdout, stderr, err := com.ExecCmd("ssh-keygen", "-l", "-f", tmpPath) + stdout, stderr, err := process.Exec("AddPublicKey", "ssh-keygen", "-l", "-f", tmpPath) if err != nil { return errors.New("ssh-keygen -l -f: " + stderr) } else if len(stdout) < 2 { diff --git a/models/repo.go b/models/repo.go index 0f018135..6b98d0e4 100644 --- a/models/repo.go +++ b/models/repo.go @@ -9,7 +9,6 @@ import ( "fmt" "io/ioutil" "os" - "os/exec" "path" "path/filepath" "sort" @@ -25,6 +24,7 @@ import ( "github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/bin" "github.com/gogits/gogs/modules/log" + "github.com/gogits/gogs/modules/process" "github.com/gogits/gogs/modules/setting" ) @@ -88,13 +88,13 @@ func NewRepoContext() { zip.Verbose = false // Check if server has basic git setting. - stdout, stderr, err := com.ExecCmd("git", "config", "--get", "user.name") + stdout, stderr, err := process.Exec("NewRepoContext(get setting)", "git", "config", "--get", "user.name") if strings.Contains(stderr, "fatal:") { log.Fatal("repo.NewRepoContext(fail to get git user.name): %s", stderr) } else if err != nil || len(strings.TrimSpace(stdout)) == 0 { - if _, stderr, err = com.ExecCmd("git", "config", "--global", "user.email", "gogitservice@gmail.com"); err != nil { + if _, stderr, err = process.Exec("NewRepoContext(set email)", "git", "config", "--global", "user.email", "gogitservice@gmail.com"); err != nil { log.Fatal("repo.NewRepoContext(fail to set git user.email): %s", stderr) - } else if _, stderr, err = com.ExecCmd("git", "config", "--global", "user.name", "Gogs"); err != nil { + } else if _, stderr, err = process.Exec("NewRepoContext(set name)", "git", "config", "--global", "user.name", "Gogs"); err != nil { log.Fatal("repo.NewRepoContext(fail to set git user.name): %s", stderr) } } @@ -190,7 +190,9 @@ type Mirror struct { // MirrorRepository creates a mirror repository from source. func MirrorRepository(repoId int64, userName, repoName, repoPath, url string) error { - _, stderr, err := com.ExecCmd("git", "clone", "--mirror", url, repoPath) + // TODO: need timeout. + _, stderr, err := process.Exec(fmt.Sprintf("MirrorRepository: %s/%s", userName, repoName), + "git", "clone", "--mirror", url, repoPath) if err != nil { return errors.New("git clone --mirror: " + stderr) } @@ -231,9 +233,11 @@ func MirrorUpdate() { return nil } + // TODO: need timeout. repoPath := filepath.Join(setting.RepoRootPath, m.RepoName+".git") - _, stderr, err := com.ExecCmdDir(repoPath, "git", "remote", "update") - if err != nil { + if _, stderr, err := process.ExecDir( + repoPath, fmt.Sprintf("MirrorUpdate: %s", repoPath), + "git", "remote", "update"); err != nil { return errors.New("git remote update: " + stderr) } else if err = git.UnpackRefs(repoPath); err != nil { return err @@ -268,133 +272,34 @@ func MigrateRepository(user *User, name, desc string, private, mirror bool, url return repo, UpdateRepository(repo) } + // TODO: need timeout. // Clone from local repository. - _, stderr, err := com.ExecCmd("git", "clone", repoPath, tmpDir) + _, stderr, err := process.Exec( + fmt.Sprintf("MigrateRepository(git clone): %s", repoPath), + "git", "clone", repoPath, tmpDir) if err != nil { return repo, errors.New("git clone: " + stderr) } + // TODO: need timeout. // Pull data from source. - _, stderr, err = com.ExecCmdDir(tmpDir, "git", "pull", url) - if err != nil { + if _, stderr, err = process.ExecDir( + tmpDir, fmt.Sprintf("MigrateRepository(git pull): %s", repoPath), + "git", "pull", url); err != nil { return repo, errors.New("git pull: " + stderr) } + // TODO: need timeout. // Push data to local repository. - if _, stderr, err = com.ExecCmdDir(tmpDir, "git", "push", "origin", "master"); err != nil { + if _, stderr, err = process.ExecDir( + tmpDir, fmt.Sprintf("MigrateRepository(git push): %s", repoPath), + "git", "push", "origin", "master"); err != nil { return repo, errors.New("git push: " + stderr) } return repo, UpdateRepository(repo) } -// CreateRepository creates a repository for given user or orgnaziation. -func CreateRepository(user *User, name, desc, lang, license string, private, mirror, initReadme bool) (*Repository, error) { - if !IsLegalName(name) { - return nil, ErrRepoNameIllegal - } - - isExist, err := IsRepositoryExist(user, name) - if err != nil { - return nil, err - } else if isExist { - return nil, ErrRepoAlreadyExist - } - - repo := &Repository{ - OwnerId: user.Id, - Name: name, - LowerName: strings.ToLower(name), - Description: desc, - IsPrivate: private, - IsBare: lang == "" && license == "" && !initReadme, - } - if !repo.IsBare { - repo.DefaultBranch = "master" - } - - repoPath := RepoPath(user.Name, repo.Name) - - sess := orm.NewSession() - defer sess.Close() - sess.Begin() - - if _, err = sess.Insert(repo); err != nil { - if err2 := os.RemoveAll(repoPath); err2 != nil { - log.Error("repo.CreateRepository(repo): %v", err) - return nil, errors.New(fmt.Sprintf( - "delete repo directory %s/%s failed(1): %v", user.Name, repo.Name, err2)) - } - sess.Rollback() - return nil, err - } - - mode := AU_WRITABLE - if mirror { - mode = AU_READABLE - } - access := Access{ - UserName: user.LowerName, - RepoName: strings.ToLower(path.Join(user.Name, repo.Name)), - Mode: mode, - } - if _, err = sess.Insert(&access); err != nil { - sess.Rollback() - if err2 := os.RemoveAll(repoPath); err2 != nil { - log.Error("repo.CreateRepository(access): %v", err) - return nil, errors.New(fmt.Sprintf( - "delete repo directory %s/%s failed(2): %v", user.Name, repo.Name, err2)) - } - return nil, err - } - - rawSql := "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?" - if _, err = sess.Exec(rawSql, user.Id); err != nil { - sess.Rollback() - if err2 := os.RemoveAll(repoPath); err2 != nil { - log.Error("repo.CreateRepository(repo count): %v", err) - return nil, errors.New(fmt.Sprintf( - "delete repo directory %s/%s failed(3): %v", user.Name, repo.Name, err2)) - } - return nil, err - } - - if err = sess.Commit(); err != nil { - sess.Rollback() - if err2 := os.RemoveAll(repoPath); err2 != nil { - log.Error("repo.CreateRepository(commit): %v", err) - return nil, errors.New(fmt.Sprintf( - "delete repo directory %s/%s failed(3): %v", user.Name, repo.Name, err2)) - } - return nil, err - } - - if err = WatchRepo(user.Id, repo.Id, true); err != nil { - log.Error("repo.CreateRepository(WatchRepo): %v", err) - } - - if err = NewRepoAction(user, repo); err != nil { - log.Error("repo.CreateRepository(NewRepoAction): %v", err) - } - - // No need for init for mirror. - if mirror { - return repo, nil - } - - if err = initRepository(repoPath, user, repo, initReadme, lang, license); err != nil { - return nil, err - } - - c := exec.Command("git", "update-server-info") - c.Dir = repoPath - if err = c.Run(); err != nil { - log.Error("repo.CreateRepository(exec update-server-info): %v", err) - } - - return repo, nil -} - // extractGitBareZip extracts git-bare.zip to repository path. func extractGitBareZip(repoPath string) error { z, err := zip.Open(path.Join(setting.RepoRootPath, "git-bare.zip")) @@ -409,15 +314,22 @@ func extractGitBareZip(repoPath string) error { // initRepoCommit temporarily changes with work directory. func initRepoCommit(tmpPath string, sig *git.Signature) (err error) { var stderr string - if _, stderr, err = com.ExecCmdDir(tmpPath, "git", "add", "--all"); err != nil { + if _, stderr, err = process.ExecDir( + tmpPath, fmt.Sprintf("initRepoCommit(git add): %s", tmpPath), + "git", "add", "--all"); err != nil { return errors.New("git add: " + stderr) } - if _, stderr, err = com.ExecCmdDir(tmpPath, "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email), + + if _, stderr, err = process.ExecDir( + tmpPath, fmt.Sprintf("initRepoCommit(git commit): %s", tmpPath), + "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email), "-m", "Init commit"); err != nil { return errors.New("git commit: " + stderr) } - if _, stderr, err = com.ExecCmdDir(tmpPath, "git", "push", "origin", "master"); err != nil { + if _, stderr, err = process.ExecDir( + tmpPath, fmt.Sprintf("initRepoCommit(git push): %s", tmpPath), + "git", "push", "origin", "master"); err != nil { return errors.New("git push: " + stderr) } return nil @@ -475,9 +387,11 @@ func initRepository(f string, user *User, repo *Repository, initReadme bool, rep tmpDir := filepath.Join(os.TempDir(), base.ToStr(time.Now().Nanosecond())) os.MkdirAll(tmpDir, os.ModePerm) - _, stderr, err := com.ExecCmd("git", "clone", repoPath, tmpDir) + _, stderr, err := process.Exec( + fmt.Sprintf("initRepository(git clone): %s", repoPath), + "git", "clone", repoPath, tmpDir) if err != nil { - return errors.New("git clone: " + stderr) + return errors.New("initRepository(git clone): " + stderr) } // README @@ -540,6 +454,114 @@ func initRepository(f string, user *User, repo *Repository, initReadme bool, rep return initRepoCommit(tmpDir, user.NewGitSig()) } +// CreateRepository creates a repository for given user or orgnaziation. +func CreateRepository(user *User, name, desc, lang, license string, private, mirror, initReadme bool) (*Repository, error) { + if !IsLegalName(name) { + return nil, ErrRepoNameIllegal + } + + isExist, err := IsRepositoryExist(user, name) + if err != nil { + return nil, err + } else if isExist { + return nil, ErrRepoAlreadyExist + } + + repo := &Repository{ + OwnerId: user.Id, + Name: name, + LowerName: strings.ToLower(name), + Description: desc, + IsPrivate: private, + IsBare: lang == "" && license == "" && !initReadme, + } + if !repo.IsBare { + repo.DefaultBranch = "master" + } + + repoPath := RepoPath(user.Name, repo.Name) + + sess := orm.NewSession() + defer sess.Close() + sess.Begin() + + if _, err = sess.Insert(repo); err != nil { + if err2 := os.RemoveAll(repoPath); err2 != nil { + log.Error("repo.CreateRepository(repo): %v", err) + return nil, errors.New(fmt.Sprintf( + "delete repo directory %s/%s failed(1): %v", user.Name, repo.Name, err2)) + } + sess.Rollback() + return nil, err + } + + mode := AU_WRITABLE + if mirror { + mode = AU_READABLE + } + access := Access{ + UserName: user.LowerName, + RepoName: strings.ToLower(path.Join(user.Name, repo.Name)), + Mode: mode, + } + if _, err = sess.Insert(&access); err != nil { + sess.Rollback() + if err2 := os.RemoveAll(repoPath); err2 != nil { + log.Error("repo.CreateRepository(access): %v", err) + return nil, errors.New(fmt.Sprintf( + "delete repo directory %s/%s failed(2): %v", user.Name, repo.Name, err2)) + } + return nil, err + } + + rawSql := "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?" + if _, err = sess.Exec(rawSql, user.Id); err != nil { + sess.Rollback() + if err2 := os.RemoveAll(repoPath); err2 != nil { + log.Error("repo.CreateRepository(repo count): %v", err) + return nil, errors.New(fmt.Sprintf( + "delete repo directory %s/%s failed(3): %v", user.Name, repo.Name, err2)) + } + return nil, err + } + + if err = sess.Commit(); err != nil { + sess.Rollback() + if err2 := os.RemoveAll(repoPath); err2 != nil { + log.Error("repo.CreateRepository(commit): %v", err) + return nil, errors.New(fmt.Sprintf( + "delete repo directory %s/%s failed(3): %v", user.Name, repo.Name, err2)) + } + return nil, err + } + + if err = WatchRepo(user.Id, repo.Id, true); err != nil { + log.Error("repo.CreateRepository(WatchRepo): %v", err) + } + + if err = NewRepoAction(user, repo); err != nil { + log.Error("repo.CreateRepository(NewRepoAction): %v", err) + } + + // No need for init for mirror. + if mirror { + return repo, nil + } + + if err = initRepository(repoPath, user, repo, initReadme, lang, license); err != nil { + return nil, err + } + + _, stderr, err := process.ExecDir( + repoPath, fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath), + "git", "update-server-info") + if err != nil { + return nil, errors.New("CreateRepository(git update-server-info): " + stderr) + } + + return repo, nil +} + // GetRepositoriesWithUsers returns given number of repository objects with offset. // It also auto-gets corresponding users. func GetRepositoriesWithUsers(num, offset int) ([]*Repository, error) { diff --git a/modules/process/manager.go b/modules/process/manager.go new file mode 100644 index 00000000..173b2aa4 --- /dev/null +++ b/modules/process/manager.go @@ -0,0 +1,89 @@ +// Copyright 2014 The Gogs Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package process + +import ( + "bytes" + "fmt" + "os/exec" + "time" + + "github.com/gogits/gogs/modules/log" +) + +// Process represents a working process inherit from Gogs. +type Process struct { + Pid int64 // Process ID, not system one. + Description string + Start time.Time + Cmd *exec.Cmd +} + +// List of existing processes. +var ( + curPid int64 = 1 + Processes []*Process +) + +// Add adds a existing process and returns its PID. +func Add(desc string, cmd *exec.Cmd) int64 { + pid := curPid + Processes = append(Processes, &Process{ + Pid: pid, + Description: desc, + Start: time.Now(), + Cmd: cmd, + }) + curPid++ + return pid +} + +func ExecDir(dir, desc, cmdName string, args ...string) (string, string, error) { + bufOut := new(bytes.Buffer) + bufErr := new(bytes.Buffer) + + cmd := exec.Command(cmdName, args...) + cmd.Dir = dir + cmd.Stdout = bufOut + cmd.Stderr = bufErr + + pid := Add(desc, cmd) + err := cmd.Run() + if errKill := Kill(pid); errKill != nil { + log.Error("Exec: %v", pid, desc, errKill) + } + return bufOut.String(), bufErr.String(), err +} + +// Exec starts executing a command and record its process. +func Exec(desc, cmdName string, args ...string) (string, string, error) { + return ExecDir("", desc, cmdName, args...) +} + +// Remove removes a process from list. +func Remove(pid int64) { + for i, proc := range Processes { + if proc.Pid == pid { + Processes = append(Processes[:i], Processes[i+1:]...) + return + } + } +} + +// Kill kills and removes a process from list. +func Kill(pid int64) error { + for i, proc := range Processes { + if proc.Pid == pid { + if proc.Cmd.Process != nil && proc.Cmd.ProcessState != nil && !proc.Cmd.ProcessState.Exited() { + if err := proc.Cmd.Process.Kill(); err != nil { + return fmt.Errorf("fail to kill process(%d/%s): %v", proc.Pid, proc.Description, err) + } + } + Processes = append(Processes[:i], Processes[i+1:]...) + return nil + } + } + return nil +} diff --git a/routers/admin/admin.go b/routers/admin/admin.go index d4b49a9e..a14ffae0 100644 --- a/routers/admin/admin.go +++ b/routers/admin/admin.go @@ -16,6 +16,7 @@ import ( "github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/cron" "github.com/gogits/gogs/modules/middleware" + "github.com/gogits/gogs/modules/process" "github.com/gogits/gogs/modules/setting" ) @@ -238,10 +239,12 @@ func Monitor(ctx *middleware.Context) { switch tab { case "process": ctx.Data["PageIsMonitorProcess"] = true + ctx.Data["Processes"] = process.Processes + ctx.HTML(200, "admin/monitor/process") default: ctx.Data["PageIsMonitorCron"] = true ctx.Data["Entries"] = cron.ListEntries() + ctx.HTML(200, "admin/monitor/cron") } - ctx.HTML(200, "admin/monitor/cron") } diff --git a/templates/VERSION b/templates/VERSION index c2606e90..d86ece15 100644 --- a/templates/VERSION +++ b/templates/VERSION @@ -1 +1 @@ -0.4.4.0613 Alpha \ No newline at end of file +0.4.4.0619 Alpha \ No newline at end of file diff --git a/templates/admin/monitor/process.tmpl b/templates/admin/monitor/process.tmpl new file mode 100644 index 00000000..2d60ff68 --- /dev/null +++ b/templates/admin/monitor/process.tmpl @@ -0,0 +1,38 @@ +{{template "base/head" .}} +{{template "base/navbar" .}} +
    + {{template "admin/nav" .}} +
    + +
    +
    + {{if .PageIsMonitorProcess}} + + + + + + + + + + + {{range .Processes}} + + + + + + + {{end}} + +
    PidDescriptionStart TimeExecution Time
    {{.Pid}}{{.Description}}{{.Start}}{{TimeSince .Start}}
    + {{end}} +
    +
    +
    +
    +{{template "base/footer" .}} \ No newline at end of file -- cgit v1.2.3 From 8bfa7ae7453e56191aa6f7de8067d5b6bb5a4a8b Mon Sep 17 00:00:00 2001 From: Unknown Date: Fri, 20 Jun 2014 01:14:54 -0400 Subject: Remove qiniu/log --- cmd/serve.go | 58 ++++++++++++++++------------------------------------ cmd/update.go | 20 ++++-------------- models/action.go | 3 +-- models/publickey.go | 7 +++---- models/update.go | 23 ++++++++++----------- modules/log/log.go | 11 +++++++++- routers/install.go | 1 + routers/repo/http.go | 16 +++++++-------- 8 files changed, 56 insertions(+), 83 deletions(-) (limited to 'cmd') diff --git a/cmd/serve.go b/cmd/serve.go index a21500c7..62e290d8 100644 --- a/cmd/serve.go +++ b/cmd/serve.go @@ -13,9 +13,9 @@ import ( "strings" "github.com/codegangsta/cli" - qlog "github.com/qiniu/log" "github.com/gogits/gogs/models" + "github.com/gogits/gogs/modules/log" "github.com/gogits/gogs/modules/setting" ) @@ -27,26 +27,13 @@ var CmdServ = cli.Command{ Flags: []cli.Flag{}, } -func newLogger(logPath string) { - os.MkdirAll(path.Dir(logPath), os.ModePerm) - - f, err := os.OpenFile(logPath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, os.ModePerm) - if err != nil { - qlog.Fatal("Fail to open log file(%s): %v", logPath, err) - } - - qlog.SetOutput(f) - qlog.Info("Start logging serv...") -} - func setup(logPath string) { - workDir, _ := setting.WorkDir() - newLogger(path.Join(workDir, logPath)) - setting.NewConfigContext() + log.NewGitLogger(path.Join(setting.LogRootPath, logPath)) models.LoadModelsConfig() if models.UseSQLite3 { + workDir, _ := setting.WorkDir() os.Chdir(workDir) } @@ -87,27 +74,27 @@ func In(b string, sl map[string]int) bool { } func runServ(k *cli.Context) { - setup(path.Join(setting.LogRootPath, "serv.log")) + setup("serv.log") keys := strings.Split(os.Args[2], "-") if len(keys) != 2 { println("Gogs: auth file format error") - qlog.Fatal("Invalid auth file format: %s", os.Args[2]) + log.GitLogger.Fatal("Invalid auth file format: %s", os.Args[2]) } keyId, err := strconv.ParseInt(keys[1], 10, 64) if err != nil { println("Gogs: auth file format error") - qlog.Fatalf("Invalid auth file format: %v", err) + log.GitLogger.Fatal("Invalid auth file format: %v", err) } user, err := models.GetUserByKeyId(keyId) if err != nil { if err == models.ErrUserNotKeyOwner { println("Gogs: you are not the owner of SSH key") - qlog.Fatalf("Invalid owner of SSH key: %d", keyId) + log.GitLogger.Fatal("Invalid owner of SSH key: %d", keyId) } println("Gogs: internal error:", err) - qlog.Fatalf("Fail to get user by key ID(%d): %v", keyId, err) + log.GitLogger.Fatal("Fail to get user by key ID(%d): %v", keyId, err) } cmd := os.Getenv("SSH_ORIGINAL_COMMAND") @@ -121,7 +108,7 @@ func runServ(k *cli.Context) { rr := strings.SplitN(repoPath, "/", 2) if len(rr) != 2 { println("Gogs: unavailable repository", args) - qlog.Fatalf("Unavailable repository: %v", args) + log.GitLogger.Fatal("Unavailable repository: %v", args) } repoUserName := rr[0] repoName := strings.TrimSuffix(rr[1], ".git") @@ -133,10 +120,10 @@ func runServ(k *cli.Context) { if err != nil { if err == models.ErrUserNotExist { println("Gogs: given repository owner are not registered") - qlog.Fatalf("Unregistered owner: %s", repoUserName) + log.GitLogger.Fatal("Unregistered owner: %s", repoUserName) } println("Gogs: internal error:", err) - qlog.Fatalf("Fail to get repository owner(%s): %v", repoUserName, err) + log.GitLogger.Fatal("Fail to get repository owner(%s): %v", repoUserName, err) } // Access check. @@ -145,20 +132,20 @@ func runServ(k *cli.Context) { has, err := models.HasAccess(user.Name, path.Join(repoUserName, repoName), models.AU_WRITABLE) if err != nil { println("Gogs: internal error:", err) - qlog.Fatal("Fail to check write access:", err) + log.GitLogger.Fatal("Fail to check write access:", err) } else if !has { println("You have no right to write this repository") - qlog.Fatalf("User %s has no right to write repository %s", user.Name, repoPath) + log.GitLogger.Fatal("User %s has no right to write repository %s", user.Name, repoPath) } case isRead: repo, err := models.GetRepositoryByName(repoUser.Id, repoName) if err != nil { if err == models.ErrRepoNotExist { println("Gogs: given repository does not exist") - qlog.Fatalf("Repository does not exist: %s/%s", repoUser.Name, repoName) + log.GitLogger.Fatal("Repository does not exist: %s/%s", repoUser.Name, repoName) } println("Gogs: internal error:", err) - qlog.Fatalf("Fail to get repository: %v", err) + log.GitLogger.Fatal("Fail to get repository: %v", err) } if !repo.IsPrivate { @@ -168,10 +155,10 @@ func runServ(k *cli.Context) { has, err := models.HasAccess(user.Name, path.Join(repoUserName, repoName), models.AU_READABLE) if err != nil { println("Gogs: internal error:", err) - qlog.Fatal("Fail to check read access:", err) + log.GitLogger.Fatal("Fail to check read access:", err) } else if !has { println("You have no right to access this repository") - qlog.Fatalf("User %s has no right to read repository %s", user.Name, repoPath) + log.GitLogger.Fatal("User %s has no right to read repository %s", user.Name, repoPath) } default: println("Unknown command") @@ -188,15 +175,6 @@ func runServ(k *cli.Context) { err = gitcmd.Run() if err != nil { println("Gogs: internal error:", err) - qlog.Fatalf("Fail to execute git command: %v", err) + log.GitLogger.Fatal("Fail to execute git command: %v", err) } - - //refName := os.Getenv("refName") - //oldCommitId := os.Getenv("oldCommitId") - //newCommitId := os.Getenv("newCommitId") - - //qlog.Error("get envs:", refName, oldCommitId, newCommitId) - - // update - //models.Update(refName, oldCommitId, newCommitId, repoUserName, repoName, user.Id) } diff --git a/cmd/update.go b/cmd/update.go index b8686a3e..d0e0acde 100644 --- a/cmd/update.go +++ b/cmd/update.go @@ -6,14 +6,12 @@ package cmd import ( "os" - "path" "strconv" "github.com/codegangsta/cli" - qlog "github.com/qiniu/log" "github.com/gogits/gogs/models" - "github.com/gogits/gogs/modules/setting" + "github.com/gogits/gogs/modules/log" ) var CmdUpdate = cli.Command{ @@ -24,33 +22,23 @@ var CmdUpdate = cli.Command{ Flags: []cli.Flag{}, } -func updateEnv(refName, oldCommitId, newCommitId string) { - os.Setenv("refName", refName) - os.Setenv("oldCommitId", oldCommitId) - os.Setenv("newCommitId", newCommitId) - qlog.Info("set envs:", refName, oldCommitId, newCommitId) -} - func runUpdate(c *cli.Context) { cmd := os.Getenv("SSH_ORIGINAL_COMMAND") if cmd == "" { return } - setup(path.Join(setting.LogRootPath, "update.log")) + setup("update.log") args := c.Args() if len(args) != 3 { - qlog.Fatal("received less 3 parameters") + log.GitLogger.Fatal("received less 3 parameters") } else if args[0] == "" { - qlog.Fatal("refName is empty, shouldn't use") + log.GitLogger.Fatal("refName is empty, shouldn't use") } - //updateEnv(args[0], args[1], args[2]) - userName := os.Getenv("userName") userId, _ := strconv.ParseInt(os.Getenv("userId"), 10, 64) - //repoId := os.Getenv("repoId") repoUserName := os.Getenv("repoUserName") repoName := os.Getenv("repoName") diff --git a/models/action.go b/models/action.go index e39b04a1..28468233 100644 --- a/models/action.go +++ b/models/action.go @@ -12,7 +12,6 @@ import ( "time" "github.com/gogits/git" - qlog "github.com/qiniu/log" "github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/log" @@ -115,7 +114,7 @@ func CommitRepoAction(userId, repoUserId int64, userName, actEmail string, return errors.New("action.CommitRepoAction(NotifyWatchers): " + err.Error()) } - qlog.Info("action.CommitRepoAction(end): %d/%s", repoUserId, repoName) + //qlog.Info("action.CommitRepoAction(end): %d/%s", repoUserId, repoName) // New push event hook. if err := repo.GetOwner(); err != nil { diff --git a/models/publickey.go b/models/publickey.go index 72b45c5b..b0021a68 100644 --- a/models/publickey.go +++ b/models/publickey.go @@ -19,7 +19,6 @@ import ( "time" "github.com/Unknwon/com" - qlog "github.com/qiniu/log" "github.com/gogits/gogs/modules/log" "github.com/gogits/gogs/modules/process" @@ -55,7 +54,7 @@ func exePath() (string, error) { func homeDir() string { home, err := com.HomeDir() if err != nil { - qlog.Fatalln(err) + log.Fatal("Fail to get home directory: %v", err) } return home } @@ -64,13 +63,13 @@ func init() { var err error if appPath, err = exePath(); err != nil { - qlog.Fatalf("publickey.init(fail to get app path): %v\n", err) + log.Fatal("publickey.init(fail to get app path): %v\n", err) } // Determine and create .ssh path. SshPath = filepath.Join(homeDir(), ".ssh") if err = os.MkdirAll(SshPath, os.ModePerm); err != nil { - qlog.Fatalf("publickey.init(fail to create SshPath(%s)): %v\n", SshPath, err) + log.Fatal("publickey.init(fail to create SshPath(%s)): %v\n", SshPath, err) } } diff --git a/models/update.go b/models/update.go index b7242cde..5675a94c 100644 --- a/models/update.go +++ b/models/update.go @@ -9,18 +9,17 @@ import ( "os/exec" "strings" - qlog "github.com/qiniu/log" - "github.com/gogits/git" "github.com/gogits/gogs/modules/base" + "github.com/gogits/gogs/modules/log" ) func Update(refName, oldCommitId, newCommitId, userName, repoUserName, repoName string, userId int64) { isNew := strings.HasPrefix(oldCommitId, "0000000") if isNew && strings.HasPrefix(newCommitId, "0000000") { - qlog.Fatal("old rev and new rev both 000000") + log.GitLogger.Fatal("old rev and new rev both 000000") } f := RepoPath(repoUserName, repoName) @@ -31,18 +30,18 @@ func Update(refName, oldCommitId, newCommitId, userName, repoUserName, repoName isDel := strings.HasPrefix(newCommitId, "0000000") if isDel { - qlog.Info("del rev", refName, "from", userName+"/"+repoName+".git", "by", userId) + log.GitLogger.Info("del rev", refName, "from", userName+"/"+repoName+".git", "by", userId) return } repo, err := git.OpenRepository(f) if err != nil { - qlog.Fatalf("runUpdate.Open repoId: %v", err) + log.GitLogger.Fatal("runUpdate.Open repoId: %v", err) } newCommit, err := repo.GetCommit(newCommitId) if err != nil { - qlog.Fatalf("runUpdate GetCommit of newCommitId: %v", err) + log.GitLogger.Fatal("runUpdate GetCommit of newCommitId: %v", err) return } @@ -51,28 +50,28 @@ func Update(refName, oldCommitId, newCommitId, userName, repoUserName, repoName if isNew { l, err = newCommit.CommitsBefore() if err != nil { - qlog.Fatalf("Find CommitsBefore erro: %v", err) + log.GitLogger.Fatal("Find CommitsBefore erro: %v", err) } } else { l, err = newCommit.CommitsBeforeUntil(oldCommitId) if err != nil { - qlog.Fatalf("Find CommitsBeforeUntil erro: %v", err) + log.GitLogger.Fatal("Find CommitsBeforeUntil erro: %v", err) return } } if err != nil { - qlog.Fatalf("runUpdate.Commit repoId: %v", err) + log.GitLogger.Fatal("runUpdate.Commit repoId: %v", err) } ru, err := GetUserByName(repoUserName) if err != nil { - qlog.Fatalf("runUpdate.GetUserByName: %v", err) + log.GitLogger.Fatal("runUpdate.GetUserByName: %v", err) } repos, err := GetRepositoryByName(ru.Id, repoName) if err != nil { - qlog.Fatalf("runUpdate.GetRepositoryByName userId: %v", err) + log.GitLogger.Fatal("runUpdate.GetRepositoryByName userId: %v", err) } commits := make([]*base.PushCommit, 0) @@ -96,6 +95,6 @@ func Update(refName, oldCommitId, newCommitId, userName, repoUserName, repoName //commits = append(commits, []string{lastCommit.Id().String(), lastCommit.Message()}) if err = CommitRepoAction(userId, ru.Id, userName, actEmail, repos.Id, repoUserName, repoName, refName, &base.PushCommits{l.Len(), commits}); err != nil { - qlog.Fatalf("runUpdate.models.CommitRepoAction: %s/%s:%v", repoUserName, repoName, err) + log.GitLogger.Fatal("runUpdate.models.CommitRepoAction: %s/%s:%v", repoUserName, repoName, err) } } diff --git a/modules/log/log.go b/modules/log/log.go index a62baad1..24f0442d 100644 --- a/modules/log/log.go +++ b/modules/log/log.go @@ -6,13 +6,16 @@ package log import ( + "fmt" "os" + "path" "github.com/gogits/logs" ) var ( - loggers []*logs.BeeLogger + loggers []*logs.BeeLogger + GitLogger *logs.BeeLogger ) func init() { @@ -38,6 +41,12 @@ func NewLogger(bufLen int64, mode, config string) { } } +func NewGitLogger(logPath string) { + os.MkdirAll(path.Dir(logPath), os.ModePerm) + GitLogger = logs.NewLogger(0) + GitLogger.SetLogger("file", fmt.Sprintf(`{"level":0,"filename":"%s","rotate":false}`, logPath)) +} + func Trace(format string, v ...interface{}) { for _, logger := range loggers { logger.Trace(format, v...) diff --git a/routers/install.go b/routers/install.go index eb0fc199..c2eee88a 100644 --- a/routers/install.go +++ b/routers/install.go @@ -60,6 +60,7 @@ func GlobalInit() { models.HasEngine = true cron.NewCronContext() + log.NewGitLogger(path.Join(setting.LogRootPath, "http.log")) } if models.EnableSQLite3 { log.Info("SQLite3 Enabled") diff --git a/routers/repo/http.go b/routers/repo/http.go index c5856d60..5915e876 100644 --- a/routers/repo/http.go +++ b/routers/repo/http.go @@ -9,7 +9,6 @@ import ( "fmt" "io" "io/ioutil" - "log" "net/http" "os" "os/exec" @@ -22,6 +21,7 @@ import ( "github.com/go-martini/martini" "github.com/gogits/gogs/models" + "github.com/gogits/gogs/modules/log" "github.com/gogits/gogs/modules/middleware" "github.com/gogits/gogs/modules/setting" ) @@ -190,7 +190,7 @@ var routes = []route{ // Request handling function func HttpBackend(config *Config) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - //log.Printf("%s %s %s %s", r.RemoteAddr, r.Method, r.URL.Path, r.Proto) + //log.GitLogger.Printf("%s %s %s %s", r.RemoteAddr, r.Method, r.URL.Path, r.Proto) for _, route := range routes { if m := route.cr.FindStringSubmatch(r.URL.Path); m != nil { if route.method != r.Method { @@ -202,7 +202,7 @@ func HttpBackend(config *Config) http.HandlerFunc { dir, err := getGitDir(config, m[1]) if err != nil { - log.Print(err) + log.GitLogger.Error(err.Error()) renderNotFound(w) return } @@ -246,19 +246,19 @@ func serviceRpc(rpc string, hr handler) { cmd.Dir = dir in, err := cmd.StdinPipe() if err != nil { - log.Print(err) + log.GitLogger.Error(err.Error()) return } stdout, err := cmd.StdoutPipe() if err != nil { - log.Print(err) + log.GitLogger.Error(err.Error()) return } err = cmd.Start() if err != nil { - log.Print(err) + log.GitLogger.Error(err.Error()) return } @@ -345,7 +345,7 @@ func getGitDir(config *Config, fPath string) (string, error) { cwd, err := os.Getwd() if err != nil { - log.Print(err) + log.GitLogger.Error(err.Error()) return "", err } @@ -422,7 +422,7 @@ func gitCommand(gitBinPath, dir string, args ...string) []byte { out, err := command.Output() if err != nil { - log.Print(err) + log.GitLogger.Error(err.Error()) } return out -- cgit v1.2.3 From bf703ef61761fc4b09e3cb95672869520eccbc39 Mon Sep 17 00:00:00 2001 From: fuxiaohei Date: Sun, 22 Jun 2014 14:10:12 +0800 Subject: add dashboard context switch button --- cmd/web.go | 2 +- public/css/gogs.css | 41 +++++++++++++++++++++++++++++++++++++++++ routers/dashboard.go | 2 +- templates/user/dashboard.tmpl | 14 ++++++++++++++ 4 files changed, 57 insertions(+), 2 deletions(-) (limited to 'cmd') diff --git a/cmd/web.go b/cmd/web.go index 2fdfe433..f62bc255 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -96,7 +96,7 @@ func runWeb(*cli.Context) { r.Get("/stars", user.Stars) }, reqSignIn) - m.Group("/api", func(r martini.Router) { + m.Group("/api", func(_ martini.Router) { m.Group("/v1", func(r martini.Router) { // Miscellaneous. r.Post("/markdown", bindIgnErr(apiv1.MarkdownForm{}), v1.Markdown) diff --git a/public/css/gogs.css b/public/css/gogs.css index 1e29eeba..67d1ebe5 100755 --- a/public/css/gogs.css +++ b/public/css/gogs.css @@ -638,6 +638,47 @@ html, body { margin: 0 .5em; } +#dashboard-switch .btn { + height: 40px; +} + +#dashboard-switch { + margin-top: 14px; + margin-right: 18px; +} + +#dashboard-switch .dropdown-menu { + padding: 0; +} + +#dashboard-switch-menu { + width: 180px; + margin-bottom: 0; + padding-bottom: 0; +} + +#dashboard-switch-menu > li > a { + display: block; + padding: .8em 1.2em; +} + +#dashboard-switch-menu > li { + border-bottom: 1px solid #eaeaea; +} + +#dashboard-switch-menu > li .fa { + opacity: 0; + margin-right: 16px; +} + +#dashboard-switch-menu > li.checked .fa { + opacity: 1; +} + +#dashboard-switch-menu > li:last-child { + border-bottom: none; +} + /* gogits repo single page */ #body-nav.repo-nav { diff --git a/routers/dashboard.go b/routers/dashboard.go index 438d0379..7daa0e7b 100644 --- a/routers/dashboard.go +++ b/routers/dashboard.go @@ -26,7 +26,7 @@ func Home(ctx *middleware.Context) { ctx.Data["PageIsHome"] = true - // Show recent updated repositoires for new visiters. + // Show recent updated repositories for new visitors. repos, err := models.GetRecentUpdatedRepositories() if err != nil { ctx.Handle(500, "dashboard.Home(GetRecentUpdatedRepositories)", err) diff --git a/templates/user/dashboard.tmpl b/templates/user/dashboard.tmpl index 5cda6722..c44ba362 100644 --- a/templates/user/dashboard.tmpl +++ b/templates/user/dashboard.tmpl @@ -2,6 +2,20 @@ {{template "base/navbar" .}}
    +
    + + + +
    -- cgit v1.2.3 From fb53cc4fa82bbbbba4b8b0281d5f5657b1a6fafc Mon Sep 17 00:00:00 2001 From: fuxiaohei Date: Mon, 23 Jun 2014 19:11:20 +0800 Subject: add organization setting page --- cmd/web.go | 1 + routers/org/org.go | 5 ++ templates/org/setting.tmpl | 151 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 157 insertions(+) create mode 100644 templates/org/setting.tmpl (limited to 'cmd') diff --git a/cmd/web.go b/cmd/web.go index 65ea6064..d29183a9 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -194,6 +194,7 @@ func runWeb(*cli.Context) { r.Get("/:org/dashboard", org.Dashboard) r.Get("/:org/members", org.Members) r.Get("/:org/teams", org.Teams) + r.Get("/:org/setting", org.Setting) }) m.Group("/:username/:reponame", func(r martini.Router) { diff --git a/routers/org/org.go b/routers/org/org.go index 8073d10b..ff97402e 100644 --- a/routers/org/org.go +++ b/routers/org/org.go @@ -29,3 +29,8 @@ func Dashboard(ctx *middleware.Context, params martini.Params) { ctx.Data["Title"] = "Dashboard" ctx.HTML(200, "org/dashboard") } + +func Setting(ctx *middleware.Context, param martini.Params) { + ctx.Data["Title"] = "Setting" + ctx.HTML(200, "org/setting") +} diff --git a/templates/org/setting.tmpl b/templates/org/setting.tmpl new file mode 100644 index 00000000..1be9707a --- /dev/null +++ b/templates/org/setting.tmpl @@ -0,0 +1,151 @@ +{{template "base/head" .}} +{{template "base/navbar" .}} +
    +
    +
    + + +
    + +
    +
    +
    +
    + +
    +
    + {{template "base/alert" .}} +
    +
    + Repository Options +
    + +
    +
    + {{.CsrfTokenHtml}} + + +
    + + +
    + +
    +
    + +
    + + +
    + +
    +
    + +
    + + +
    + +
    +
    + +
    + + +
    + +
    +
    + +
    + + +
    + +
    +
    + +
    +
    + +
    +
    +
    +
    +
    + +
    +
    + Danger Zone +
    +
    + +
    +
    Delete this organization
    +
    Once you delete this organization and all repositories in, there is no going back. Please be + certain. +
    + + + +
    +
    +
    +
    +{{template "base/footer" .}} -- cgit v1.2.3 From 47d29a1ee027734dcbbd1a6ed4d8ff3dde1a789b Mon Sep 17 00:00:00 2001 From: Unknown Date: Mon, 23 Jun 2014 16:22:34 -0400 Subject: Mirror fix on #248 --- cmd/update.go | 4 +++- gogs.go | 2 +- models/update.go | 26 +++++++++++++------------- routers/repo/http.go | 5 ++++- templates/VERSION | 2 +- 5 files changed, 22 insertions(+), 17 deletions(-) (limited to 'cmd') diff --git a/cmd/update.go b/cmd/update.go index d0e0acde..c030b6cf 100644 --- a/cmd/update.go +++ b/cmd/update.go @@ -42,5 +42,7 @@ func runUpdate(c *cli.Context) { repoUserName := os.Getenv("repoUserName") repoName := os.Getenv("repoName") - models.Update(args[0], args[1], args[2], userName, repoUserName, repoName, userId) + if err := models.Update(args[0], args[1], args[2], userName, repoUserName, repoName, userId); err != nil { + log.GitLogger.Fatal(err.Error()) + } } diff --git a/gogs.go b/gogs.go index 03c28601..a39d2d43 100644 --- a/gogs.go +++ b/gogs.go @@ -17,7 +17,7 @@ import ( "github.com/gogits/gogs/modules/setting" ) -const APP_VER = "0.4.5.0622 Alpha" +const APP_VER = "0.4.5.0623 Alpha" func init() { runtime.GOMAXPROCS(runtime.NumCPU()) diff --git a/models/update.go b/models/update.go index 5675a94c..3328f221 100644 --- a/models/update.go +++ b/models/update.go @@ -6,6 +6,7 @@ package models import ( "container/list" + "fmt" "os/exec" "strings" @@ -15,11 +16,11 @@ import ( "github.com/gogits/gogs/modules/log" ) -func Update(refName, oldCommitId, newCommitId, userName, repoUserName, repoName string, userId int64) { +func Update(refName, oldCommitId, newCommitId, userName, repoUserName, repoName string, userId int64) error { isNew := strings.HasPrefix(oldCommitId, "0000000") if isNew && strings.HasPrefix(newCommitId, "0000000") { - log.GitLogger.Fatal("old rev and new rev both 000000") + return fmt.Errorf("old rev and new rev both 000000") } f := RepoPath(repoUserName, repoName) @@ -31,18 +32,17 @@ func Update(refName, oldCommitId, newCommitId, userName, repoUserName, repoName isDel := strings.HasPrefix(newCommitId, "0000000") if isDel { log.GitLogger.Info("del rev", refName, "from", userName+"/"+repoName+".git", "by", userId) - return + return nil } repo, err := git.OpenRepository(f) if err != nil { - log.GitLogger.Fatal("runUpdate.Open repoId: %v", err) + return fmt.Errorf("runUpdate.Open repoId: %v", err) } newCommit, err := repo.GetCommit(newCommitId) if err != nil { - log.GitLogger.Fatal("runUpdate GetCommit of newCommitId: %v", err) - return + return fmt.Errorf("runUpdate GetCommit of newCommitId: %v", err) } var l *list.List @@ -50,28 +50,27 @@ func Update(refName, oldCommitId, newCommitId, userName, repoUserName, repoName if isNew { l, err = newCommit.CommitsBefore() if err != nil { - log.GitLogger.Fatal("Find CommitsBefore erro: %v", err) + return fmt.Errorf("Find CommitsBefore erro: %v", err) } } else { l, err = newCommit.CommitsBeforeUntil(oldCommitId) if err != nil { - log.GitLogger.Fatal("Find CommitsBeforeUntil erro: %v", err) - return + return fmt.Errorf("Find CommitsBeforeUntil erro: %v", err) } } if err != nil { - log.GitLogger.Fatal("runUpdate.Commit repoId: %v", err) + return fmt.Errorf("runUpdate.Commit repoId: %v", err) } ru, err := GetUserByName(repoUserName) if err != nil { - log.GitLogger.Fatal("runUpdate.GetUserByName: %v", err) + return fmt.Errorf("runUpdate.GetUserByName: %v", err) } repos, err := GetRepositoryByName(ru.Id, repoName) if err != nil { - log.GitLogger.Fatal("runUpdate.GetRepositoryByName userId: %v", err) + return fmt.Errorf("runUpdate.GetRepositoryByName userId: %v", err) } commits := make([]*base.PushCommit, 0) @@ -95,6 +94,7 @@ func Update(refName, oldCommitId, newCommitId, userName, repoUserName, repoName //commits = append(commits, []string{lastCommit.Id().String(), lastCommit.Message()}) if err = CommitRepoAction(userId, ru.Id, userName, actEmail, repos.Id, repoUserName, repoName, refName, &base.PushCommits{l.Len(), commits}); err != nil { - log.GitLogger.Fatal("runUpdate.models.CommitRepoAction: %s/%s:%v", repoUserName, repoName, err) + return fmt.Errorf("runUpdate.models.CommitRepoAction: %s/%s:%v", repoUserName, repoName, err) } + return nil } diff --git a/routers/repo/http.go b/routers/repo/http.go index 5915e876..d2bff299 100644 --- a/routers/repo/http.go +++ b/routers/repo/http.go @@ -141,7 +141,10 @@ func Http(ctx *middleware.Context, params martini.Params) { newCommitId := fields[1] refName := fields[2] - models.Update(refName, oldCommitId, newCommitId, authUsername, username, reponame, authUser.Id) + if err = models.Update(refName, oldCommitId, newCommitId, authUsername, username, reponame, authUser.Id); err != nil { + log.GitLogger.Error(err.Error()) + return + } } } } diff --git a/templates/VERSION b/templates/VERSION index 414dc2ef..ca3b3f1b 100644 --- a/templates/VERSION +++ b/templates/VERSION @@ -1 +1 @@ -0.4.5.0622 Alpha \ No newline at end of file +0.4.5.0623 Alpha \ No newline at end of file -- cgit v1.2.3 From e0f9c628c5ff7399167944b3d0730698487af498 Mon Sep 17 00:00:00 2001 From: Unknown Date: Wed, 25 Jun 2014 00:44:48 -0400 Subject: Add create organization --- cmd/serve.go | 20 ++--- cmd/web.go | 5 +- gogs.go | 2 +- models/access.go | 17 ++-- models/issue.go | 4 +- models/login.go | 4 +- models/models.go | 2 +- models/org.go | 69 ++++++++++++++++ models/repo.go | 10 ++- models/user.go | 186 +++++++++++++++++++++++++++++++++--------- modules/auth/org.go | 33 ++++++++ modules/middleware/repo.go | 4 +- routers/admin/user.go | 4 +- routers/install.go | 2 +- routers/org/org.go | 96 ++++++++++++++++++++-- routers/repo/http.go | 8 +- routers/repo/setting.go | 4 +- routers/user/home.go | 13 ++- routers/user/user.go | 7 +- templates/VERSION | 2 +- templates/org/dashboard.tmpl | 73 ----------------- templates/org/new.tmpl | 24 +----- templates/user/dashboard.tmpl | 39 ++++++--- templates/user/issues.tmpl | 3 +- 24 files changed, 436 insertions(+), 195 deletions(-) create mode 100644 models/org.go create mode 100644 modules/auth/org.go delete mode 100644 templates/org/dashboard.tmpl (limited to 'cmd') diff --git a/cmd/serve.go b/cmd/serve.go index 62e290d8..2a76da79 100644 --- a/cmd/serve.go +++ b/cmd/serve.go @@ -56,19 +56,19 @@ func parseCmd(cmd string) (string, string) { } var ( - COMMANDS_READONLY = map[string]int{ - "git-upload-pack": models.AU_WRITABLE, - "git upload-pack": models.AU_WRITABLE, - "git-upload-archive": models.AU_WRITABLE, + COMMANDS_READONLY = map[string]models.AccessType{ + "git-upload-pack": models.WRITABLE, + "git upload-pack": models.WRITABLE, + "git-upload-archive": models.WRITABLE, } - COMMANDS_WRITE = map[string]int{ - "git-receive-pack": models.AU_READABLE, - "git receive-pack": models.AU_READABLE, + COMMANDS_WRITE = map[string]models.AccessType{ + "git-receive-pack": models.READABLE, + "git receive-pack": models.READABLE, } ) -func In(b string, sl map[string]int) bool { +func In(b string, sl map[string]models.AccessType) bool { _, e := sl[b] return e } @@ -129,7 +129,7 @@ func runServ(k *cli.Context) { // Access check. switch { case isWrite: - has, err := models.HasAccess(user.Name, path.Join(repoUserName, repoName), models.AU_WRITABLE) + has, err := models.HasAccess(user.Name, path.Join(repoUserName, repoName), models.WRITABLE) if err != nil { println("Gogs: internal error:", err) log.GitLogger.Fatal("Fail to check write access:", err) @@ -152,7 +152,7 @@ func runServ(k *cli.Context) { break } - has, err := models.HasAccess(user.Name, path.Join(repoUserName, repoName), models.AU_READABLE) + has, err := models.HasAccess(user.Name, path.Join(repoUserName, repoName), models.READABLE) if err != nil { println("Gogs: internal error:", err) log.GitLogger.Fatal("Fail to check read access:", err) diff --git a/cmd/web.go b/cmd/web.go index d29183a9..878fdeac 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -188,14 +188,15 @@ func runWeb(*cli.Context) { reqOwner := middleware.RequireOwner() - m.Group("/o", func(r martini.Router) { + m.Group("/org", func(r martini.Router) { r.Get("/create", org.New) + r.Post("/create", bindIgnErr(auth.CreateOrganizationForm{}), org.NewPost) r.Get("/:org", org.Organization) r.Get("/:org/dashboard", org.Dashboard) r.Get("/:org/members", org.Members) r.Get("/:org/teams", org.Teams) r.Get("/:org/setting", org.Setting) - }) + }, reqSignIn) m.Group("/:username/:reponame", func(r martini.Router) { r.Get("/settings", repo.Setting) diff --git a/gogs.go b/gogs.go index 75d3eb4b..5c2c6ed9 100644 --- a/gogs.go +++ b/gogs.go @@ -17,7 +17,7 @@ import ( "github.com/gogits/gogs/modules/setting" ) -const APP_VER = "0.4.5.0624 Alpha" +const APP_VER = "0.4.5.0625 Alpha" func init() { runtime.GOMAXPROCS(runtime.NumCPU()) diff --git a/models/access.go b/models/access.go index cf31fc13..5238daba 100644 --- a/models/access.go +++ b/models/access.go @@ -11,19 +11,20 @@ import ( "github.com/go-xorm/xorm" ) -// Access types. +type AccessType int + const ( - AU_READABLE = iota + 1 - AU_WRITABLE + READABLE AccessType = iota + 1 + WRITABLE ) // Access represents the accessibility of user to repository. type Access struct { Id int64 - UserName string `xorm:"unique(s)"` - RepoName string `xorm:"unique(s)"` // / - Mode int `xorm:"unique(s)"` - Created time.Time `xorm:"created"` + UserName string `xorm:"unique(s)"` + RepoName string `xorm:"unique(s)"` // / + Mode AccessType `xorm:"unique(s)"` + Created time.Time `xorm:"created"` } // AddAccess adds new access record. @@ -59,7 +60,7 @@ func UpdateAccessWithSession(sess *xorm.Session, access *Access) error { // HasAccess returns true if someone can read or write to given repository. // The repoName should be in format /. -func HasAccess(uname, repoName string, mode int) (bool, error) { +func HasAccess(uname, repoName string, mode AccessType) (bool, error) { if len(repoName) == 0 { return false, nil } diff --git a/models/issue.go b/models/issue.go index 11f6dd4e..6d67a72b 100644 --- a/models/issue.go +++ b/models/issue.go @@ -213,9 +213,9 @@ func GetIssueCountByPoster(uid, rid int64, isClosed bool) int64 { // IssueUser represents an issue-user relation. type IssueUser struct { Id int64 - Uid int64 // User ID. + Uid int64 `xorm:"INDEX"` // User ID. IssueId int64 - RepoId int64 + RepoId int64 `xorm:"INDEX"` MilestoneId int64 IsRead bool IsAssigned bool diff --git a/models/login.go b/models/login.go index 98c5c64e..e99b61e7 100644 --- a/models/login.go +++ b/models/login.go @@ -255,7 +255,7 @@ func LoginUserLdapSource(user *User, name, passwd string, sourceId int64, cfg *L Email: mail, } - return RegisterUser(user) + return CreateUser(user) } type loginAuth struct { @@ -359,5 +359,5 @@ func LoginUserSMTPSource(user *User, name, passwd string, sourceId int64, cfg *S Passwd: passwd, Email: name, } - return RegisterUser(user) + return CreateUser(user) } diff --git a/models/models.go b/models/models.go index d6273d7f..4e65c00b 100644 --- a/models/models.go +++ b/models/models.go @@ -35,7 +35,7 @@ func init() { tables = append(tables, new(User), new(PublicKey), new(Repository), new(Watch), new(Action), new(Access), new(Issue), new(Comment), new(Oauth2), new(Follow), new(Mirror), new(Release), new(LoginSource), new(Webhook), new(IssueUser), - new(Milestone), new(Label), new(HookTask)) + new(Milestone), new(Label), new(HookTask), new(Team), new(OrgUser), new(TeamUser)) } func LoadModelsConfig() { diff --git a/models/org.go b/models/org.go new file mode 100644 index 00000000..1cfe1798 --- /dev/null +++ b/models/org.go @@ -0,0 +1,69 @@ +// Copyright 2014 The Gogs Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package models + +type AuthorizeType int + +const ( + ORG_READABLE AuthorizeType = iota + 1 + ORG_WRITABLE + ORG_ADMIN +) + +// Team represents a organization team. +type Team struct { + Id int64 + OrgId int64 `xorm:"INDEX"` + Name string + Description string + Authorize AuthorizeType + NumMembers int + NumRepos int +} + +// NewTeam creates a record of new team. +func NewTeam(t *Team) error { + _, err := x.Insert(t) + return err +} + +// ________ ____ ___ +// \_____ \_______ ____ | | \______ ___________ +// / | \_ __ \/ ___\| | / ___// __ \_ __ \ +// / | \ | \/ /_/ > | /\___ \\ ___/| | \/ +// \_______ /__| \___ /|______//____ >\___ >__| +// \/ /_____/ \/ \/ + +// OrgUser represents an organization-user relation. +type OrgUser struct { + Id int64 + Uid int64 `xorm:"INDEX"` + OrgId int64 `xorm:"INDEX"` + IsPublic bool + IsOwner bool + NumTeam int +} + +// GetOrgUsersByUserId returns all organization-user relations by user ID. +func GetOrgUsersByUserId(uid int64) ([]*OrgUser, error) { + ous := make([]*OrgUser, 0, 10) + err := x.Where("uid=?", uid).Find(&ous) + return ous, err +} + +// ___________ ____ ___ +// \__ ___/___ _____ _____ | | \______ ___________ +// | |_/ __ \\__ \ / \| | / ___// __ \_ __ \ +// | |\ ___/ / __ \| Y Y \ | /\___ \\ ___/| | \/ +// |____| \___ >____ /__|_| /______//____ >\___ >__| +// \/ \/ \/ \/ \/ + +// TeamUser represents an team-user relation. +type TeamUser struct { + Id int64 + Uid int64 + OrgId int64 `xorm:"INDEX"` + TeamId int64 +} diff --git a/models/repo.go b/models/repo.go index 4ccaccbf..f0e46c71 100644 --- a/models/repo.go +++ b/models/repo.go @@ -158,7 +158,7 @@ func IsRepositoryExist(u *User, repoName string) (bool, error) { } var ( - illegalEquals = []string{"raw", "install", "api", "avatar", "user", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin"} + illegalEquals = []string{"raw", "install", "api", "avatar", "user", "org", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin"} illegalSuffixs = []string{".git"} ) @@ -483,7 +483,9 @@ func CreateRepository(user *User, name, desc, lang, license string, private, mir sess := x.NewSession() defer sess.Close() - sess.Begin() + if err = sess.Begin(); err != nil { + return nil, err + } if _, err = sess.Insert(repo); err != nil { if err2 := os.RemoveAll(repoPath); err2 != nil { @@ -495,9 +497,9 @@ func CreateRepository(user *User, name, desc, lang, license string, private, mir return nil, err } - mode := AU_WRITABLE + mode := WRITABLE if mirror { - mode = AU_READABLE + mode = READABLE } access := Access{ UserName: user.LowerName, diff --git a/models/user.go b/models/user.go index 50d81c94..2388be9a 100644 --- a/models/user.go +++ b/models/user.go @@ -21,10 +21,11 @@ import ( "github.com/gogits/gogs/modules/setting" ) -// User types. +type UserType int + const ( - UT_INDIVIDUAL = iota + 1 - UT_ORGANIZATION + INDIVIDUAL UserType = iota // Historic reason to make it starts at 0. + ORGANIZATION ) var ( @@ -50,7 +51,8 @@ type User struct { LoginType LoginType LoginSource int64 `xorm:"not null default 0"` LoginName string - Type int + Type UserType + Orgs []*User `xorm:"-"` NumFollowers int NumFollowings int NumStars int @@ -65,36 +67,60 @@ type User struct { Salt string `xorm:"VARCHAR(10)"` Created time.Time `xorm:"created"` Updated time.Time `xorm:"updated"` + + // For organization. + NumTeams int + NumMembers int } // HomeLink returns the user home page link. -func (user *User) HomeLink() string { - return "/user/" + user.Name +func (u *User) HomeLink() string { + return "/user/" + u.Name } // AvatarLink returns user gravatar link. -func (user *User) AvatarLink() string { +func (u *User) AvatarLink() string { if setting.DisableGravatar { return "/img/avatar_default.jpg" } else if setting.Service.EnableCacheAvatar { - return "/avatar/" + user.Avatar + return "/avatar/" + u.Avatar } - return "//1.gravatar.com/avatar/" + user.Avatar + return "//1.gravatar.com/avatar/" + u.Avatar } // NewGitSig generates and returns the signature of given user. -func (user *User) NewGitSig() *git.Signature { +func (u *User) NewGitSig() *git.Signature { return &git.Signature{ - Name: user.Name, - Email: user.Email, + Name: u.Name, + Email: u.Email, When: time.Now(), } } // EncodePasswd encodes password to safe format. -func (user *User) EncodePasswd() { - newPasswd := base.PBKDF2([]byte(user.Passwd), []byte(user.Salt), 10000, 50, sha256.New) - user.Passwd = fmt.Sprintf("%x", newPasswd) +func (u *User) EncodePasswd() { + newPasswd := base.PBKDF2([]byte(u.Passwd), []byte(u.Salt), 10000, 50, sha256.New) + u.Passwd = fmt.Sprintf("%x", newPasswd) +} + +func (u *User) IsOrganization() bool { + return u.Type == ORGANIZATION +} + +func (u *User) GetOrganizations() error { + ous, err := GetOrgUsersByUserId(u.Id) + if err != nil { + return err + } + + u.Orgs = make([]*User, len(ous)) + for i, ou := range ous { + u.Orgs[i], err = GetUserById(ou.OrgId) + if err != nil { + return err + } + } + return nil } // Member represents user is member of organization. @@ -126,49 +152,135 @@ func GetUserSalt() string { return base.GetRandomString(10) } -// RegisterUser creates record of a new user. -func RegisterUser(user *User) (*User, error) { +// CreateUser creates record of a new user. +func CreateUser(u *User) (*User, error) { + if !IsLegalName(u.Name) { + return nil, ErrUserNameIllegal + } + + isExist, err := IsUserExist(u.Name) + if err != nil { + return nil, err + } else if isExist { + return nil, ErrUserAlreadyExist + } + + isExist, err = IsEmailUsed(u.Email) + if err != nil { + return nil, err + } else if isExist { + return nil, ErrEmailAlreadyUsed + } + + u.LowerName = strings.ToLower(u.Name) + u.Avatar = base.EncodeMd5(u.Email) + u.AvatarEmail = u.Email + u.Rands = GetUserSalt() + u.Salt = GetUserSalt() + u.EncodePasswd() + + sess := x.NewSession() + defer sess.Close() + if err = sess.Begin(); err != nil { + return nil, err + } - if !IsLegalName(user.Name) { + if _, err = sess.Insert(u); err != nil { + sess.Rollback() + return nil, err + } + + if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil { + sess.Rollback() + return nil, err + } + + if err = sess.Commit(); err != nil { + return nil, err + } + + // Auto-set admin for user whose ID is 1. + if u.Id == 1 { + u.IsAdmin = true + u.IsActive = true + _, err = x.Id(u.Id).UseBool().Update(u) + } + return u, err +} + +// CreateOrganization creates record of a new organization. +func CreateOrganization(org, owner *User) (*User, error) { + if !IsLegalName(org.Name) { return nil, ErrUserNameIllegal } - isExist, err := IsUserExist(user.Name) + isExist, err := IsUserExist(org.Name) if err != nil { return nil, err } else if isExist { return nil, ErrUserAlreadyExist } - isExist, err = IsEmailUsed(user.Email) + isExist, err = IsEmailUsed(org.Email) if err != nil { return nil, err } else if isExist { return nil, ErrEmailAlreadyUsed } - user.LowerName = strings.ToLower(user.Name) - user.Avatar = base.EncodeMd5(user.Email) - user.AvatarEmail = user.Email - user.Rands = GetUserSalt() - user.Salt = GetUserSalt() - user.EncodePasswd() - if _, err = x.Insert(user); err != nil { + org.LowerName = strings.ToLower(org.Name) + org.Avatar = base.EncodeMd5(org.Email) + org.AvatarEmail = org.Email + // No password for organization. + org.NumTeams = 1 + org.NumMembers = 1 + + sess := x.NewSession() + defer sess.Close() + if err = sess.Begin(); err != nil { + return nil, err + } + + if _, err = sess.Insert(org); err != nil { + sess.Rollback() return nil, err - } else if err = os.MkdirAll(UserPath(user.Name), os.ModePerm); err != nil { - if _, err := x.Id(user.Id).Delete(&User{}); err != nil { - return nil, errors.New(fmt.Sprintf( - "both create userpath %s and delete table record faild: %v", user.Name, err)) - } + } + + // Create default owner team. + t := &Team{ + OrgId: org.Id, + Name: "Owner", + Authorize: ORG_ADMIN, + NumMembers: 1, + } + if _, err = sess.Insert(t); err != nil { + sess.Rollback() return nil, err } - if user.Id == 1 { - user.IsAdmin = true - user.IsActive = true - _, err = x.Id(user.Id).UseBool().Update(user) + // Add initial creator to organization and owner team. + ou := &OrgUser{ + Uid: owner.Id, + OrgId: org.Id, + IsOwner: true, + NumTeam: 1, } - return user, err + if _, err = sess.Insert(ou); err != nil { + sess.Rollback() + return nil, err + } + + tu := &TeamUser{ + Uid: owner.Id, + OrgId: org.Id, + TeamId: t.Id, + } + if _, err = sess.Insert(tu); err != nil { + sess.Rollback() + return nil, err + } + + return org, sess.Commit() } // GetUsers returns given number of user objects with offset. diff --git a/modules/auth/org.go b/modules/auth/org.go new file mode 100644 index 00000000..a60fbb85 --- /dev/null +++ b/modules/auth/org.go @@ -0,0 +1,33 @@ +// Copyright 2014 The Gogs Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package auth + +import ( + "net/http" + "reflect" + + "github.com/go-martini/martini" + + "github.com/gogits/gogs/modules/base" + "github.com/gogits/gogs/modules/middleware/binding" +) + +type CreateOrganizationForm struct { + OrgName string `form:"orgname" binding:"Required;AlphaDashDot;MaxSize(30)"` + Email string `form:"email" binding:"Required;Email;MaxSize(50)"` +} + +func (f *CreateOrganizationForm) Name(field string) string { + names := map[string]string{ + "OrgName": "Organization name", + "Email": "E-mail address", + } + return names[field] +} + +func (f *CreateOrganizationForm) Validate(errs *binding.Errors, req *http.Request, ctx martini.Context) { + data := ctx.Get(reflect.TypeOf(base.TmplData{})).Interface().(base.TmplData) + validate(errs, data, f) +} diff --git a/modules/middleware/repo.go b/modules/middleware/repo.go index 6c77ed2a..43ba1e8c 100644 --- a/modules/middleware/repo.go +++ b/modules/middleware/repo.go @@ -46,7 +46,7 @@ func RepoAssignment(redirect bool, args ...bool) martini.Handler { // Collaborators who have write access can be seen as owners. if ctx.IsSigned { - ctx.Repo.IsOwner, err = models.HasAccess(ctx.User.Name, userName+"/"+repoName, models.AU_WRITABLE) + ctx.Repo.IsOwner, err = models.HasAccess(ctx.User.Name, userName+"/"+repoName, models.WRITABLE) if err != nil { ctx.Handle(500, "RepoAssignment(HasAccess)", err) return @@ -107,7 +107,7 @@ func RepoAssignment(redirect bool, args ...bool) martini.Handler { return } - hasAccess, err := models.HasAccess(ctx.User.Name, ctx.Repo.Owner.Name+"/"+repo.Name, models.AU_READABLE) + hasAccess, err := models.HasAccess(ctx.User.Name, ctx.Repo.Owner.Name+"/"+repo.Name, models.READABLE) if err != nil { ctx.Handle(500, "RepoAssignment(HasAccess)", err) return diff --git a/routers/admin/user.go b/routers/admin/user.go index d1bbb480..cf99db2b 100644 --- a/routers/admin/user.go +++ b/routers/admin/user.go @@ -67,7 +67,7 @@ func NewUserPost(ctx *middleware.Context, form auth.RegisterForm) { } var err error - if u, err = models.RegisterUser(u); err != nil { + if u, err = models.CreateUser(u); err != nil { switch err { case models.ErrUserAlreadyExist: ctx.RenderWithErr("Username has been already taken", USER_NEW, &form) @@ -76,7 +76,7 @@ func NewUserPost(ctx *middleware.Context, form auth.RegisterForm) { case models.ErrUserNameIllegal: ctx.RenderWithErr(models.ErrRepoNameIllegal.Error(), USER_NEW, &form) default: - ctx.Handle(500, "admin.user.NewUser(RegisterUser)", err) + ctx.Handle(500, "admin.user.NewUser(CreateUser)", err) } return } diff --git a/routers/install.go b/routers/install.go index 6ce7c980..bb3c16ea 100644 --- a/routers/install.go +++ b/routers/install.go @@ -227,7 +227,7 @@ func InstallPost(ctx *middleware.Context, form auth.InstallForm) { GlobalInit() // Create admin account. - if _, err := models.RegisterUser(&models.User{Name: form.AdminName, Email: form.AdminEmail, Passwd: form.AdminPasswd, + if _, err := models.CreateUser(&models.User{Name: form.AdminName, Email: form.AdminEmail, Passwd: form.AdminPasswd, IsAdmin: true, IsActive: true}); err != nil { if err != models.ErrUserAlreadyExist { setting.InstallLock = false diff --git a/routers/org/org.go b/routers/org/org.go index ff97402e..0595a81b 100644 --- a/routers/org/org.go +++ b/routers/org/org.go @@ -1,33 +1,117 @@ +// Copyright 2014 The Gogs Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + package org import ( "github.com/go-martini/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/middleware" + "github.com/gogits/gogs/routers/user" +) + +const ( + NEW base.TplName = "org/new" ) func Organization(ctx *middleware.Context, params martini.Params) { - ctx.Data["Title"] = "Organization "+params["org"] + ctx.Data["Title"] = "Organization " + params["org"] ctx.HTML(200, "org/org") } func Members(ctx *middleware.Context, params martini.Params) { - ctx.Data["Title"] = "Organization "+params["org"]+" Members" + ctx.Data["Title"] = "Organization " + params["org"] + " Members" ctx.HTML(200, "org/members") } func Teams(ctx *middleware.Context, params martini.Params) { - ctx.Data["Title"] = "Organization "+params["org"]+" Teams" + ctx.Data["Title"] = "Organization " + params["org"] + " Teams" ctx.HTML(200, "org/teams") } func New(ctx *middleware.Context) { - ctx.Data["Title"] = "Create an Organization" - ctx.HTML(200, "org/new") + ctx.Data["Title"] = "Create An Organization" + ctx.HTML(200, NEW) +} + +func NewPost(ctx *middleware.Context, form auth.CreateOrganizationForm) { + ctx.Data["Title"] = "Create An Organization" + + if ctx.HasError() { + ctx.HTML(200, NEW) + return + } + + org := &models.User{ + Name: form.OrgName, + Email: form.Email, + IsActive: true, // NOTE: may need to set false when require e-mail confirmation. + Type: models.ORGANIZATION, + } + + var err error + if org, err = models.CreateOrganization(org, ctx.User); err != nil { + switch err { + case models.ErrUserAlreadyExist: + ctx.Data["Err_OrgName"] = true + ctx.RenderWithErr("Organization name has been already taken", NEW, &form) + case models.ErrEmailAlreadyUsed: + ctx.Data["Err_Email"] = true + ctx.RenderWithErr("E-mail address has been already used", NEW, &form) + case models.ErrUserNameIllegal: + ctx.Data["Err_OrgName"] = true + ctx.RenderWithErr(models.ErrRepoNameIllegal.Error(), NEW, &form) + default: + ctx.Handle(500, "user.NewPost(CreateUser)", err) + } + return + } + log.Trace("%s Organization created: %s", ctx.Req.RequestURI, org.Name) + + ctx.Redirect("/org/" + form.OrgName + "/dashboard") } func Dashboard(ctx *middleware.Context, params martini.Params) { ctx.Data["Title"] = "Dashboard" - ctx.HTML(200, "org/dashboard") + ctx.Data["PageIsUserDashboard"] = true + ctx.Data["PageIsOrgDashboard"] = true + + org, err := models.GetUserByName(params["org"]) + if err != nil { + if err == models.ErrUserNotExist { + ctx.Handle(404, "org.Dashboard(GetUserByName)", err) + } else { + ctx.Handle(500, "org.Dashboard(GetUserByName)", err) + } + return + } + + if err := ctx.User.GetOrganizations(); err != nil { + ctx.Handle(500, "home.Dashboard(GetOrganizations)", err) + return + } + ctx.Data["Orgs"] = ctx.User.Orgs + ctx.Data["ContextUser"] = org + + ctx.Data["MyRepos"], err = models.GetRepositories(org.Id, true) + if err != nil { + ctx.Handle(500, "org.Dashboard(GetRepositories)", err) + return + } + + actions, err := models.GetFeeds(org.Id, 0, false) + if err != nil { + ctx.Handle(500, "org.Dashboard(GetFeeds)", err) + return + } + ctx.Data["Feeds"] = actions + + ctx.HTML(200, user.DASHBOARD) } func Setting(ctx *middleware.Context, param martini.Params) { diff --git a/routers/repo/http.go b/routers/repo/http.go index d2bff299..981266d5 100644 --- a/routers/repo/http.go +++ b/routers/repo/http.go @@ -107,9 +107,9 @@ func Http(ctx *middleware.Context, params martini.Params) { } if !isPublicPull { - var tp = models.AU_WRITABLE + var tp = models.WRITABLE if isPull { - tp = models.AU_READABLE + tp = models.READABLE } has, err := models.HasAccess(authUsername, username+"/"+reponame, tp) @@ -117,8 +117,8 @@ func Http(ctx *middleware.Context, params martini.Params) { ctx.Handle(401, "no basic auth and digit auth", nil) return } else if !has { - if tp == models.AU_READABLE { - has, err = models.HasAccess(authUsername, username+"/"+reponame, models.AU_WRITABLE) + if tp == models.READABLE { + has, err = models.HasAccess(authUsername, username+"/"+reponame, models.WRITABLE) if err != nil || !has { ctx.Handle(401, "no basic auth and digit auth", nil) return diff --git a/routers/repo/setting.go b/routers/repo/setting.go index 6479cb30..3d48e79c 100644 --- a/routers/repo/setting.go +++ b/routers/repo/setting.go @@ -175,7 +175,7 @@ func CollaborationPost(ctx *middleware.Context) { ctx.Redirect(ctx.Req.RequestURI) return } - has, err := models.HasAccess(name, repoLink, models.AU_WRITABLE) + has, err := models.HasAccess(name, repoLink, models.WRITABLE) if err != nil { ctx.Handle(500, "setting.CollaborationPost(HasAccess)", err) return @@ -196,7 +196,7 @@ func CollaborationPost(ctx *middleware.Context) { } if err = models.AddAccess(&models.Access{UserName: name, RepoName: repoLink, - Mode: models.AU_WRITABLE}); err != nil { + Mode: models.WRITABLE}); err != nil { ctx.Handle(500, "setting.CollaborationPost(AddAccess)", err) return } diff --git a/routers/user/home.go b/routers/user/home.go index 0f2cee25..86907b5a 100644 --- a/routers/user/home.go +++ b/routers/user/home.go @@ -20,7 +20,7 @@ import ( const ( DASHBOARD base.TplName = "user/dashboard" PROFILE base.TplName = "user/profile" - ISSUES base.TplName = "user/issue" + ISSUES base.TplName = "user/issues" PULLS base.TplName = "user/pulls" STARS base.TplName = "user/stars" ) @@ -29,6 +29,13 @@ func Dashboard(ctx *middleware.Context) { ctx.Data["Title"] = "Dashboard" ctx.Data["PageIsUserDashboard"] = true + if err := ctx.User.GetOrganizations(); err != nil { + ctx.Handle(500, "home.Dashboard(GetOrganizations)", err) + return + } + ctx.Data["Orgs"] = ctx.User.Orgs + ctx.Data["ContextUser"] = ctx.User + var err error ctx.Data["MyRepos"], err = models.GetRepositories(ctx.User.Id, true) if err != nil { @@ -53,7 +60,7 @@ func Dashboard(ctx *middleware.Context) { for _, act := range actions { if act.IsPrivate { if has, _ := models.HasAccess(ctx.User.Name, act.RepoUserName+"/"+act.RepoName, - models.AU_READABLE); !has { + models.READABLE); !has { continue } } @@ -131,7 +138,7 @@ func Feeds(ctx *middleware.Context, form auth.FeedsForm) { for _, act := range actions { if act.IsPrivate { if has, _ := models.HasAccess(ctx.User.Name, act.RepoUserName+"/"+act.RepoName, - models.AU_READABLE); !has { + models.READABLE); !has { continue } } diff --git a/routers/user/user.go b/routers/user/user.go index 8144730e..a50f126c 100644 --- a/routers/user/user.go +++ b/routers/user/user.go @@ -226,7 +226,7 @@ func SignUpPost(ctx *middleware.Context, form auth.RegisterForm) { } var err error - if u, err = models.RegisterUser(u); err != nil { + if u, err = models.CreateUser(u); err != nil { switch err { case models.ErrUserAlreadyExist: ctx.Data["Err_UserName"] = true @@ -235,13 +235,14 @@ func SignUpPost(ctx *middleware.Context, form auth.RegisterForm) { ctx.Data["Err_Email"] = true ctx.RenderWithErr("E-mail address has been already used", SIGNUP, &form) case models.ErrUserNameIllegal: + ctx.Data["Err_UserName"] = true ctx.RenderWithErr(models.ErrRepoNameIllegal.Error(), SIGNUP, &form) default: - ctx.Handle(500, "user.SignUpPost(RegisterUser)", err) + ctx.Handle(500, "user.SignUpPost(CreateUser)", err) } return } - log.Trace("%s User created: %s", ctx.Req.RequestURI, form.UserName) + log.Trace("%s User created: %s", ctx.Req.RequestURI, u.Name) // Bind social account. if isOauth { diff --git a/templates/VERSION b/templates/VERSION index 8c2be60b..b5cda695 100644 --- a/templates/VERSION +++ b/templates/VERSION @@ -1 +1 @@ -0.4.5.0624 Alpha \ No newline at end of file +0.4.5.0625 Alpha \ No newline at end of file diff --git a/templates/org/dashboard.tmpl b/templates/org/dashboard.tmpl deleted file mode 100644 index f86de1f4..00000000 --- a/templates/org/dashboard.tmpl +++ /dev/null @@ -1,73 +0,0 @@ -{{template "base/head" .}} -{{template "base/navbar" .}} -
    -
    -
    - - - -
    - -

    News Feed

    -
    -
    -
    - {{if .HasInfo}}
    {{.InfoMsg}}
    {{end}} -
    -
      - {{range .Feeds}} -
    • - -
      {{TimeSince .Created}}
      {{ActionDesc . | str2html}}
      - -
    • - {{else}} -
    • Oh. Looks like there isn't any activity here yet. Get Busy!
    • - {{end}} -
    -
    -
    -
    -
    Repositories -
    - - -
    -
    - -
    - -
    -
    -
    -
    -{{template "base/footer" .}} diff --git a/templates/org/new.tmpl b/templates/org/new.tmpl index baa9c9df..bb46db4a 100644 --- a/templates/org/new.tmpl +++ b/templates/org/new.tmpl @@ -1,22 +1,14 @@ {{template "base/head" .}} {{template "base/navbar" .}}
    -
    + {{.CsrfTokenHtml}}

    Create New Organization

    {{template "base/alert" .}} -
    - -
    -

    {{.SignedUserName}}

    - -
    -
    - -
    +
    - + Great organization names are short and memorable.
    @@ -24,18 +16,10 @@
    - + Organization's Email receives all notifications and confirmations.
    - -
    diff --git a/templates/user/dashboard.tmpl b/templates/user/dashboard.tmpl index 12018ad8..e1b43e15 100644 --- a/templates/user/dashboard.tmpl +++ b/templates/user/dashboard.tmpl @@ -4,29 +4,46 @@
    -

    News Feed

    +
    {{if .HasInfo}}
    {{.InfoMsg}}
    {{end}}
    @@ -44,7 +61,7 @@
    -
    Your Repositories +
    {{if not .PageIsOrgDashboard}}Your {{end}}Repositories
    - + + {{if not .PageIsOrgDashboard}}
    Collaborative Repositories
    @@ -78,6 +96,7 @@
    + {{end}}
    {{template "base/footer" .}} diff --git a/templates/user/issues.tmpl b/templates/user/issues.tmpl index d1c2bd99..c4ad64a4 100644 --- a/templates/user/issues.tmpl +++ b/templates/user/issues.tmpl @@ -3,7 +3,7 @@
    +
    {{if .HasInfo}}
    {{.InfoMsg}}
    {{end}}
    -- cgit v1.2.3 From 19e910428951135b9a341554dad54a6546d2ad50 Mon Sep 17 00:00:00 2001 From: Unknown Date: Fri, 27 Jun 2014 03:37:01 -0400 Subject: Organization settings page --- cmd/web.go | 5 +- gogs.go | 2 +- models/org.go | 86 +++++++++++++++++++++++++ models/repo.go | 2 +- models/user.go | 114 ++++++++------------------------- modules/auth/org.go | 30 ++++++++- modules/auth/repo.go | 2 +- modules/auth/user.go | 2 +- routers/org/org.go | 56 ++++++++++++++-- templates/VERSION | 2 +- templates/org/setting.tmpl | 151 -------------------------------------------- templates/org/settings.tmpl | 133 ++++++++++++++++++++++++++++++++++++++ 12 files changed, 331 insertions(+), 254 deletions(-) delete mode 100644 templates/org/setting.tmpl create mode 100644 templates/org/settings.tmpl (limited to 'cmd') diff --git a/cmd/web.go b/cmd/web.go index 878fdeac..729a1ba2 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -190,12 +190,13 @@ func runWeb(*cli.Context) { m.Group("/org", func(r martini.Router) { r.Get("/create", org.New) - r.Post("/create", bindIgnErr(auth.CreateOrganizationForm{}), org.NewPost) + r.Post("/create", bindIgnErr(auth.CreateOrgForm{}), org.NewPost) r.Get("/:org", org.Organization) r.Get("/:org/dashboard", org.Dashboard) r.Get("/:org/members", org.Members) r.Get("/:org/teams", org.Teams) - r.Get("/:org/setting", org.Setting) + r.Get("/:org/settings", org.Settings) + r.Post("/:org/settings", bindIgnErr(auth.OrgSettingForm{}), org.SettingsPost) }, reqSignIn) m.Group("/:username/:reponame", func(r martini.Router) { diff --git a/gogs.go b/gogs.go index 5c2c6ed9..d56760ab 100644 --- a/gogs.go +++ b/gogs.go @@ -17,7 +17,7 @@ import ( "github.com/gogits/gogs/modules/setting" ) -const APP_VER = "0.4.5.0625 Alpha" +const APP_VER = "0.4.5.0627 Alpha" func init() { runtime.GOMAXPROCS(runtime.NumCPU()) diff --git a/models/org.go b/models/org.go index 227151ab..553a46aa 100644 --- a/models/org.go +++ b/models/org.go @@ -4,6 +4,88 @@ package models +import ( + "strings" + + "github.com/gogits/gogs/modules/base" +) + +// CreateOrganization creates record of a new organization. +func CreateOrganization(org, owner *User) (*User, error) { + if !IsLegalName(org.Name) { + return nil, ErrUserNameIllegal + } + + isExist, err := IsUserExist(org.Name) + if err != nil { + return nil, err + } else if isExist { + return nil, ErrUserAlreadyExist + } + + isExist, err = IsEmailUsed(org.Email) + if err != nil { + return nil, err + } else if isExist { + return nil, ErrEmailAlreadyUsed + } + + org.LowerName = strings.ToLower(org.Name) + org.FullName = org.Name + org.Avatar = base.EncodeMd5(org.Email) + org.AvatarEmail = org.Email + // No password for organization. + org.NumTeams = 1 + org.NumMembers = 1 + + sess := x.NewSession() + defer sess.Close() + if err = sess.Begin(); err != nil { + return nil, err + } + + if _, err = sess.Insert(org); err != nil { + sess.Rollback() + return nil, err + } + + // Create default owner team. + t := &Team{ + OrgId: org.Id, + Name: OWNER_TEAM, + Authorize: ORG_ADMIN, + NumMembers: 1, + } + if _, err = sess.Insert(t); err != nil { + sess.Rollback() + return nil, err + } + + // Add initial creator to organization and owner team. + ou := &OrgUser{ + Uid: owner.Id, + OrgId: org.Id, + IsOwner: true, + NumTeam: 1, + } + if _, err = sess.Insert(ou); err != nil { + sess.Rollback() + return nil, err + } + + tu := &TeamUser{ + Uid: owner.Id, + OrgId: org.Id, + TeamId: t.Id, + } + if _, err = sess.Insert(tu); err != nil { + sess.Rollback() + return nil, err + } + + return org, sess.Commit() +} + type AuthorizeType int const ( @@ -72,6 +154,10 @@ func GetOrgUsersByOrgId(orgId int64) ([]*OrgUser, error) { return ous, err } +func GetOrganizationCount(u *User) (int64, error) { + return x.Where("uid=?", u.Id).Count(new(OrgUser)) +} + // ___________ ____ ___ // \__ ___/___ _____ _____ | | \______ ___________ // | |_/ __ \\__ \ / \| | / ___// __ \_ __ \ diff --git a/models/repo.go b/models/repo.go index 840529b9..85f2a913 100644 --- a/models/repo.go +++ b/models/repo.go @@ -240,7 +240,7 @@ func MirrorUpdate() { "git", "remote", "update"); err != nil { return errors.New("git remote update: " + stderr) } else if err = git.UnpackRefs(repoPath); err != nil { - return err + return errors.New("UnpackRefs: " + err.Error()) } m.NextUpdate = time.Now().Add(time.Duration(m.Interval) * time.Hour) diff --git a/models/user.go b/models/user.go index f67911ca..8ffad266 100644 --- a/models/user.go +++ b/models/user.go @@ -30,6 +30,7 @@ const ( var ( ErrUserOwnRepos = errors.New("User still have ownership of repositories") + ErrUserHasOrgs = errors.New("User still have membership of organization") ErrUserAlreadyExist = errors.New("User already exist") ErrUserNotExist = errors.New("User does not exist") ErrUserNotKeyOwner = errors.New("User does not the owner of public key") @@ -69,8 +70,9 @@ type User struct { Updated time.Time `xorm:"updated"` // For organization. - NumTeams int - NumMembers int + Description string + NumTeams int + NumMembers int } // HomeLink returns the user home page link. @@ -211,81 +213,6 @@ func CreateUser(u *User) (*User, error) { return u, err } -// CreateOrganization creates record of a new organization. -func CreateOrganization(org, owner *User) (*User, error) { - if !IsLegalName(org.Name) { - return nil, ErrUserNameIllegal - } - - isExist, err := IsUserExist(org.Name) - if err != nil { - return nil, err - } else if isExist { - return nil, ErrUserAlreadyExist - } - - isExist, err = IsEmailUsed(org.Email) - if err != nil { - return nil, err - } else if isExist { - return nil, ErrEmailAlreadyUsed - } - - org.LowerName = strings.ToLower(org.Name) - org.Avatar = base.EncodeMd5(org.Email) - org.AvatarEmail = org.Email - // No password for organization. - org.NumTeams = 1 - org.NumMembers = 1 - - sess := x.NewSession() - defer sess.Close() - if err = sess.Begin(); err != nil { - return nil, err - } - - if _, err = sess.Insert(org); err != nil { - sess.Rollback() - return nil, err - } - - // Create default owner team. - t := &Team{ - OrgId: org.Id, - Name: OWNER_TEAM, - Authorize: ORG_ADMIN, - NumMembers: 1, - } - if _, err = sess.Insert(t); err != nil { - sess.Rollback() - return nil, err - } - - // Add initial creator to organization and owner team. - ou := &OrgUser{ - Uid: owner.Id, - OrgId: org.Id, - IsOwner: true, - NumTeam: 1, - } - if _, err = sess.Insert(ou); err != nil { - sess.Rollback() - return nil, err - } - - tu := &TeamUser{ - Uid: owner.Id, - OrgId: org.Id, - TeamId: t.Id, - } - if _, err = sess.Insert(tu); err != nil { - sess.Rollback() - return nil, err - } - - return org, sess.Commit() -} - // GetUsers returns given number of user objects with offset. func GetUsers(num, offset int) ([]User, error) { users := make([]User, 0, num) @@ -392,51 +319,62 @@ func UpdateUser(u *User) (err error) { if len(u.Website) > 255 { u.Website = u.Website[:255] } + if len(u.Description) > 255 { + u.Description = u.Description[:255] + } _, err = x.Id(u.Id).AllCols().Update(u) return err } // DeleteUser completely deletes everything of the user. -func DeleteUser(user *User) error { +func DeleteUser(u *User) error { // Check ownership of repository. - count, err := GetRepositoryCount(user) + count, err := GetRepositoryCount(u) if err != nil { - return errors.New("modesl.GetRepositories: " + err.Error()) + return errors.New("modesl.GetRepositories(GetRepositoryCount): " + err.Error()) } else if count > 0 { return ErrUserOwnRepos } + // Check membership of organization. + count, err = GetOrganizationCount(u) + if err != nil { + return errors.New("modesl.GetRepositories(GetOrganizationCount): " + err.Error()) + } else if count > 0 { + return ErrUserHasOrgs + } + // TODO: check issues, other repos' commits // Delete all followers. - if _, err = x.Delete(&Follow{FollowId: user.Id}); err != nil { + if _, err = x.Delete(&Follow{FollowId: u.Id}); err != nil { return err } // Delete oauth2. - if _, err = x.Delete(&Oauth2{Uid: user.Id}); err != nil { + if _, err = x.Delete(&Oauth2{Uid: u.Id}); err != nil { return err } // Delete all feeds. - if _, err = x.Delete(&Action{UserId: user.Id}); err != nil { + if _, err = x.Delete(&Action{UserId: u.Id}); err != nil { return err } // Delete all watches. - if _, err = x.Delete(&Watch{UserId: user.Id}); err != nil { + if _, err = x.Delete(&Watch{UserId: u.Id}); err != nil { return err } // Delete all accesses. - if _, err = x.Delete(&Access{UserName: user.LowerName}); err != nil { + if _, err = x.Delete(&Access{UserName: u.LowerName}); err != nil { return err } // Delete all SSH keys. keys := make([]*PublicKey, 0, 10) - if err = x.Find(&keys, &PublicKey{OwnerId: user.Id}); err != nil { + if err = x.Find(&keys, &PublicKey{OwnerId: u.Id}); err != nil { return err } for _, key := range keys { @@ -446,11 +384,11 @@ func DeleteUser(user *User) error { } // Delete user directory. - if err = os.RemoveAll(UserPath(user.Name)); err != nil { + if err = os.RemoveAll(UserPath(u.Name)); err != nil { return err } - _, err = x.Delete(user) + _, err = x.Delete(u) return err } diff --git a/modules/auth/org.go b/modules/auth/org.go index a60fbb85..f87d10a7 100644 --- a/modules/auth/org.go +++ b/modules/auth/org.go @@ -14,12 +14,12 @@ import ( "github.com/gogits/gogs/modules/middleware/binding" ) -type CreateOrganizationForm struct { +type CreateOrgForm struct { OrgName string `form:"orgname" binding:"Required;AlphaDashDot;MaxSize(30)"` Email string `form:"email" binding:"Required;Email;MaxSize(50)"` } -func (f *CreateOrganizationForm) Name(field string) string { +func (f *CreateOrgForm) Name(field string) string { names := map[string]string{ "OrgName": "Organization name", "Email": "E-mail address", @@ -27,7 +27,31 @@ func (f *CreateOrganizationForm) Name(field string) string { return names[field] } -func (f *CreateOrganizationForm) Validate(errs *binding.Errors, req *http.Request, ctx martini.Context) { +func (f *CreateOrgForm) Validate(errs *binding.Errors, req *http.Request, ctx martini.Context) { data := ctx.Get(reflect.TypeOf(base.TmplData{})).Interface().(base.TmplData) validate(errs, data, f) } + +type OrgSettingForm struct { + DisplayName string `form:"display_name" binding:"Required;MaxSize(100)"` + Email string `form:"email" binding:"Required;Email;MaxSize(50)"` + Description string `form:"desc" binding:"MaxSize(255)"` + Website string `form:"site" binding:"Url;MaxSize(100)"` + Location string `form:"location" binding:"MaxSize(50)"` +} + +func (f *OrgSettingForm) Name(field string) string { + names := map[string]string{ + "DisplayName": "Display name", + "Email": "E-mail address", + "Description": "Description", + "Website": "Website address", + "Location": "Location", + } + return names[field] +} + +func (f *OrgSettingForm) Validate(errors *binding.Errors, req *http.Request, context martini.Context) { + data := context.Get(reflect.TypeOf(base.TmplData{})).Interface().(base.TmplData) + validate(errors, data, f) +} diff --git a/modules/auth/repo.go b/modules/auth/repo.go index db13743d..d3d21532 100644 --- a/modules/auth/repo.go +++ b/modules/auth/repo.go @@ -71,7 +71,7 @@ func (f *MigrateRepoForm) Validate(errors *binding.Errors, req *http.Request, co type RepoSettingForm struct { RepoName string `form:"name" binding:"Required;AlphaDash;MaxSize(100)"` - Description string `form:"desc" binding:"MaxSize(100)"` + Description string `form:"desc" binding:"MaxSize(255)"` Website string `form:"site" binding:"Url;MaxSize(100)"` Branch string `form:"branch"` Interval int `form:"interval"` diff --git a/modules/auth/user.go b/modules/auth/user.go index 20f99336..4a781acf 100644 --- a/modules/auth/user.go +++ b/modules/auth/user.go @@ -93,7 +93,7 @@ func (f *UpdateProfileForm) Name(field string) string { names := map[string]string{ "UserName": "Username", "Email": "E-mail address", - "Website": "Website", + "Website": "Website address", "Location": "Location", "Avatar": "Gravatar Email", } diff --git a/routers/org/org.go b/routers/org/org.go index 0595a81b..4f57b9a9 100644 --- a/routers/org/org.go +++ b/routers/org/org.go @@ -16,7 +16,8 @@ import ( ) const ( - NEW base.TplName = "org/new" + NEW base.TplName = "org/new" + SETTINGS base.TplName = "org/settings" ) func Organization(ctx *middleware.Context, params martini.Params) { @@ -39,7 +40,7 @@ func New(ctx *middleware.Context) { ctx.HTML(200, NEW) } -func NewPost(ctx *middleware.Context, form auth.CreateOrganizationForm) { +func NewPost(ctx *middleware.Context, form auth.CreateOrgForm) { ctx.Data["Title"] = "Create An Organization" if ctx.HasError() { @@ -114,7 +115,52 @@ func Dashboard(ctx *middleware.Context, params martini.Params) { ctx.HTML(200, user.DASHBOARD) } -func Setting(ctx *middleware.Context, param martini.Params) { - ctx.Data["Title"] = "Setting" - ctx.HTML(200, "org/setting") +func Settings(ctx *middleware.Context, params martini.Params) { + ctx.Data["Title"] = "Settings" + + org, err := models.GetUserByName(params["org"]) + if err != nil { + if err == models.ErrUserNotExist { + ctx.Handle(404, "org.Settings(GetUserByName)", err) + } else { + ctx.Handle(500, "org.Settings(GetUserByName)", err) + } + return + } + ctx.Data["Org"] = org + + ctx.HTML(200, SETTINGS) +} + +func SettingsPost(ctx *middleware.Context, params martini.Params, form auth.OrgSettingForm) { + ctx.Data["Title"] = "Settings" + + org, err := models.GetUserByName(params["org"]) + if err != nil { + if err == models.ErrUserNotExist { + ctx.Handle(404, "org.SettingsPost(GetUserByName)", err) + } else { + ctx.Handle(500, "org.SettingsPost(GetUserByName)", err) + } + return + } + ctx.Data["Org"] = org + + if ctx.HasError() { + ctx.HTML(200, SETTINGS) + return + } + + org.FullName = form.DisplayName + org.Email = form.Email + org.Description = form.Description + org.Website = form.Website + org.Location = form.Location + if err = models.UpdateUser(org); err != nil { + ctx.Handle(500, "org.SettingsPost(UpdateUser)", err) + return + } + log.Trace("%s Organization setting updated: %s", ctx.Req.RequestURI, org.LowerName) + ctx.Flash.Success("Organization profile has been successfully updated.") + ctx.Redirect("/org/" + org.Name + "/settings") } diff --git a/templates/VERSION b/templates/VERSION index b5cda695..be0ebee0 100644 --- a/templates/VERSION +++ b/templates/VERSION @@ -1 +1 @@ -0.4.5.0625 Alpha \ No newline at end of file +0.4.5.0627 Alpha \ No newline at end of file diff --git a/templates/org/setting.tmpl b/templates/org/setting.tmpl deleted file mode 100644 index 1be9707a..00000000 --- a/templates/org/setting.tmpl +++ /dev/null @@ -1,151 +0,0 @@ -{{template "base/head" .}} -{{template "base/navbar" .}} -
    -
    -
    - - -
    - -
    -
    -
    -
    - -
    -
    - {{template "base/alert" .}} -
    -
    - Repository Options -
    - -
    - - {{.CsrfTokenHtml}} - - -
    - - -
    - -
    -
    - -
    - - -
    - -
    -
    - -
    - - -
    - -
    -
    - -
    - - -
    - -
    -
    - -
    - - -
    - -
    -
    - -
    -
    - -
    -
    - -
    -
    - -
    -
    - Danger Zone -
    -
    - -
    -
    Delete this organization
    -
    Once you delete this organization and all repositories in, there is no going back. Please be - certain. -
    - - - -
    -
    -
    -
    -{{template "base/footer" .}} diff --git a/templates/org/settings.tmpl b/templates/org/settings.tmpl new file mode 100644 index 00000000..e19c027d --- /dev/null +++ b/templates/org/settings.tmpl @@ -0,0 +1,133 @@ +{{template "base/head" .}} +{{template "base/navbar" .}} +
    +
    +
    + +
    + +
    +
    + +
    +
    + +
    +
    + {{template "base/alert" .}} +
    +
    + Organization Options +
    + +
    +
    + {{.CsrfTokenHtml}} + + +
    + +
    + +
    +
    + +
    + +
    + +
    +
    + +
    + +
    + +
    +
    + +
    + +
    + +
    +
    + +
    + +
    + +
    +
    + +
    +
    + +
    +
    +
    +
    +
    + +
    +
    + Danger Zone +
    +
    + +
    +
    Delete this organization
    +
    Once you delete this organization and all repositories in, there is no going back. Please be + certain. +
    + + + +
    +
    +
    +
    +{{template "base/footer" .}} -- cgit v1.2.3 From b5ba2bd268b144ae0c878fe17257d8685d92f9cc Mon Sep 17 00:00:00 2001 From: fuxiaohei Date: Fri, 27 Jun 2014 21:33:49 +0800 Subject: add organization team-create page --- cmd/web.go | 3 ++ public/css/gogs.css | 2 +- routers/org/org.go | 4 --- routers/org/teams.go | 16 ++++++++++ templates/org/new_team.tmpl | 74 +++++++++++++++++++++++++++++++++++++++++++++ templates/org/teams.tmpl | 6 ++++ 6 files changed, 100 insertions(+), 5 deletions(-) create mode 100644 routers/org/teams.go create mode 100644 templates/org/new_team.tmpl (limited to 'cmd') diff --git a/cmd/web.go b/cmd/web.go index 729a1ba2..bf84d587 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -194,7 +194,10 @@ func runWeb(*cli.Context) { r.Get("/:org", org.Organization) r.Get("/:org/dashboard", org.Dashboard) r.Get("/:org/members", org.Members) + // organization teams + r.Get("/:org/teams/new",org.NewTeam) r.Get("/:org/teams", org.Teams) + r.Get("/:org/settings", org.Settings) r.Post("/:org/settings", bindIgnErr(auth.OrgSettingForm{}), org.SettingsPost) }, reqSignIn) diff --git a/public/css/gogs.css b/public/css/gogs.css index 960176f5..eb95a1d0 100755 --- a/public/css/gogs.css +++ b/public/css/gogs.css @@ -375,7 +375,7 @@ html, body { /* gogits repo create */ -#repo-create, #org-create { +#repo-create, #org-create, #org-teams-create { width: 800px; } diff --git a/routers/org/org.go b/routers/org/org.go index 4f57b9a9..c036a8e5 100644 --- a/routers/org/org.go +++ b/routers/org/org.go @@ -30,10 +30,6 @@ func Members(ctx *middleware.Context, params martini.Params) { ctx.HTML(200, "org/members") } -func Teams(ctx *middleware.Context, params martini.Params) { - ctx.Data["Title"] = "Organization " + params["org"] + " Teams" - ctx.HTML(200, "org/teams") -} func New(ctx *middleware.Context) { ctx.Data["Title"] = "Create An Organization" diff --git a/routers/org/teams.go b/routers/org/teams.go new file mode 100644 index 00000000..9585cb27 --- /dev/null +++ b/routers/org/teams.go @@ -0,0 +1,16 @@ +package org + +import ( + "github.com/go-martini/martini" + "github.com/gogits/gogs/modules/middleware" +) + +func Teams(ctx *middleware.Context, params martini.Params) { + ctx.Data["Title"] = "Organization "+params["org"]+" Teams" + ctx.HTML(200, "org/teams") +} + +func NewTeam(ctx *middleware.Context, params martini.Params) { + ctx.Data["Title"] = "Organization "+params["org"]+" New Team" + ctx.HTML(200, "org/new_team") +} diff --git a/templates/org/new_team.tmpl b/templates/org/new_team.tmpl new file mode 100644 index 00000000..752f37d2 --- /dev/null +++ b/templates/org/new_team.tmpl @@ -0,0 +1,74 @@ +{{template "base/head" .}} +{{template "base/navbar" .}} +
    +
    +
    + + +
    +

    Organization Name

    +
    +
    +
    +
    +
    +
    +
    +

    Create new team

    +
    + +
    + + You'll use this name to mention this team in conversations. +
    +
    +
    + +
    + +
    +
    +
    + +
    +
    + +

    This team will be able to view and clone its repositories.

    +
    +
    + +

    This team will be able to read its repositories, as well as push to them.

    +
    +
    + +

    This team will be able to push/pull to its repositories, as well as add other collaborators to them.

    +
    +
    +
    +
    +
    + +
    + +
    +
    +
    +
    +
    +{{template "base/footer" .}} diff --git a/templates/org/teams.tmpl b/templates/org/teams.tmpl index a8218812..90aab944 100644 --- a/templates/org/teams.tmpl +++ b/templates/org/teams.tmpl @@ -21,6 +21,12 @@
    +
    +
    + +
    +
    +

    Team Name

    -- cgit v1.2.3 From 1d55ecd29ce261cd3adf78649a44aaa30e4fd468 Mon Sep 17 00:00:00 2001 From: fuxiaohei Date: Fri, 27 Jun 2014 22:04:04 +0800 Subject: add organization team-create page --- cmd/web.go | 3 +- public/css/gogs.css | 2 +- routers/org/teams.go | 5 +++ templates/org/edit_team.tmpl | 75 ++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 83 insertions(+), 2 deletions(-) create mode 100644 templates/org/edit_team.tmpl (limited to 'cmd') diff --git a/cmd/web.go b/cmd/web.go index bf84d587..1668fae2 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -195,7 +195,8 @@ func runWeb(*cli.Context) { r.Get("/:org/dashboard", org.Dashboard) r.Get("/:org/members", org.Members) // organization teams - r.Get("/:org/teams/new",org.NewTeam) + r.Get("/:org/teams/:team/edit", org.EditTeam) + r.Get("/:org/teams/new", org.NewTeam) r.Get("/:org/teams", org.Teams) r.Get("/:org/settings", org.Settings) diff --git a/public/css/gogs.css b/public/css/gogs.css index eb95a1d0..98cb5ee1 100755 --- a/public/css/gogs.css +++ b/public/css/gogs.css @@ -375,7 +375,7 @@ html, body { /* gogits repo create */ -#repo-create, #org-create, #org-teams-create { +#repo-create, #org-create, #org-teams-create, #org-teams-edit { width: 800px; } diff --git a/routers/org/teams.go b/routers/org/teams.go index 9585cb27..9ca5185a 100644 --- a/routers/org/teams.go +++ b/routers/org/teams.go @@ -14,3 +14,8 @@ func NewTeam(ctx *middleware.Context, params martini.Params) { ctx.Data["Title"] = "Organization "+params["org"]+" New Team" ctx.HTML(200, "org/new_team") } + +func EditTeam(ctx *middleware.Context, params martini.Params){ + ctx.Data["Title"] = "Organization "+params["org"]+" Edit Team" + ctx.HTML(200,"org/edit_team") +} diff --git a/templates/org/edit_team.tmpl b/templates/org/edit_team.tmpl new file mode 100644 index 00000000..4292575c --- /dev/null +++ b/templates/org/edit_team.tmpl @@ -0,0 +1,75 @@ +{{template "base/head" .}} +{{template "base/navbar" .}} +
    +
    +
    + + +
    +

    Organization Name

    +
    +
    +
    +
    +
    +
    +
    +

    Edit team

    +
    + +
    + + You'll use this name to mention this team in conversations. +
    +
    +
    + +
    + +
    +
    +
    + +
    +
    + +

    This team will be able to view and clone its repositories.

    +
    +
    + +

    This team will be able to read its repositories, as well as push to them.

    +
    +
    + +

    This team will be able to push/pull to its repositories, as well as add other collaborators to them.

    +
    +
    +
    +
    +
    + +
    + + +
    +
    +
    +
    +
    +{{template "base/footer" .}} -- cgit v1.2.3 From 6e448b07145fbb090e0da6deb97f244c2bfd7ba7 Mon Sep 17 00:00:00 2001 From: Unknown Date: Sat, 28 Jun 2014 00:40:07 -0400 Subject: Finish delete organization --- cmd/web.go | 3 ++- gogs.go | 2 +- models/org.go | 44 ++++++++++++++++++++++++++++++++++++++++++ models/repo.go | 3 ++- models/user.go | 21 +++++--------------- modules/middleware/repo.go | 1 + routers/org/org.go | 45 ++++++++++++++++++++++++++++++++++++++++++- routers/repo/setting.go | 18 +++++++++++++---- routers/user/user.go | 2 +- templates/VERSION | 2 +- templates/user/dashboard.tmpl | 2 +- 11 files changed, 116 insertions(+), 27 deletions(-) (limited to 'cmd') diff --git a/cmd/web.go b/cmd/web.go index 1668fae2..7387d445 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -194,13 +194,14 @@ func runWeb(*cli.Context) { r.Get("/:org", org.Organization) r.Get("/:org/dashboard", org.Dashboard) r.Get("/:org/members", org.Members) - // organization teams + r.Get("/:org/teams/:team/edit", org.EditTeam) r.Get("/:org/teams/new", org.NewTeam) r.Get("/:org/teams", org.Teams) r.Get("/:org/settings", org.Settings) r.Post("/:org/settings", bindIgnErr(auth.OrgSettingForm{}), org.SettingsPost) + r.Post("/:org/settings/delete", org.DeletePost) }, reqSignIn) m.Group("/:username/:reponame", func(r martini.Router) { diff --git a/gogs.go b/gogs.go index d56760ab..3ad059bc 100644 --- a/gogs.go +++ b/gogs.go @@ -17,7 +17,7 @@ import ( "github.com/gogits/gogs/modules/setting" ) -const APP_VER = "0.4.5.0627 Alpha" +const APP_VER = "0.4.5.0628 Alpha" func init() { runtime.GOMAXPROCS(runtime.NumCPU()) diff --git a/models/org.go b/models/org.go index 553a46aa..025759b0 100644 --- a/models/org.go +++ b/models/org.go @@ -10,6 +10,16 @@ import ( "github.com/gogits/gogs/modules/base" ) +// GetOwnerTeam returns owner team of organization. +func (org *User) GetOwnerTeam() (*Team, error) { + t := &Team{ + OrgId: org.Id, + Name: OWNER_TEAM, + } + _, err := x.Get(t) + return t, err +} + // CreateOrganization creates record of a new organization. func CreateOrganization(org, owner *User) (*User, error) { if !IsLegalName(org.Name) { @@ -86,6 +96,34 @@ func CreateOrganization(org, owner *User) (*User, error) { return org, sess.Commit() } +// TODO: need some kind of mechanism to record failure. +// DeleteOrganization completely and permanently deletes everything of organization. +func DeleteOrganization(org *User) (err error) { + if err := DeleteUser(org); err != nil { + return err + } + + sess := x.NewSession() + defer sess.Close() + if err = sess.Begin(); err != nil { + return err + } + + if _, err = sess.Delete(&Team{OrgId: org.Id}); err != nil { + sess.Rollback() + return err + } + if _, err = sess.Delete(&OrgUser{OrgId: org.Id}); err != nil { + sess.Rollback() + return err + } + if _, err = sess.Delete(&TeamUser{OrgId: org.Id}); err != nil { + sess.Rollback() + return err + } + return sess.Commit() +} + type AuthorizeType int const ( @@ -158,6 +196,12 @@ func GetOrganizationCount(u *User) (int64, error) { return x.Where("uid=?", u.Id).Count(new(OrgUser)) } +// IsOrganizationOwner returns true if given user ID is in the owner team. +func IsOrganizationOwner(orgId, uid int64) bool { + has, _ := x.Where("is_owner=?", true).Get(&OrgUser{Uid: uid, OrgId: orgId}) + return has +} + // ___________ ____ ___ // \__ ___/___ _____ _____ | | \______ ___________ // | |_/ __ \\__ \ / \| | / ___// __ \_ __ \ diff --git a/models/repo.go b/models/repo.go index 85f2a913..3d38ed66 100644 --- a/models/repo.go +++ b/models/repo.go @@ -733,7 +733,7 @@ func UpdateRepository(repo *Repository) error { } // DeleteRepository deletes a repository for a user or orgnaztion. -func DeleteRepository(userId, repoId int64, userName string) (err error) { +func DeleteRepository(userId, repoId int64, userName string) error { repo := &Repository{Id: repoId, OwnerId: userId} has, err := x.Get(repo) if err != nil { @@ -747,6 +747,7 @@ func DeleteRepository(userId, repoId int64, userName string) (err error) { if err = sess.Begin(); err != nil { return err } + if _, err = sess.Delete(&Repository{Id: repoId}); err != nil { sess.Rollback() return err diff --git a/models/user.go b/models/user.go index 8ffad266..9b0bdebe 100644 --- a/models/user.go +++ b/models/user.go @@ -105,10 +105,12 @@ func (u *User) EncodePasswd() { u.Passwd = fmt.Sprintf("%x", newPasswd) } +// IsOrganization returns true if user is actually a organization. func (u *User) IsOrganization() bool { return u.Type == ORGANIZATION } +// GetOrganizations returns all organizations that user belongs to. func (u *User) GetOrganizations() error { ous, err := GetOrgUsersByUserId(u.Id) if err != nil { @@ -125,16 +127,6 @@ func (u *User) GetOrganizations() error { return nil } -// GetOwnerTeam returns owner team of organization. -func (org *User) GetOwnerTeam() (*Team, error) { - t := &Team{ - OrgId: org.Id, - Name: OWNER_TEAM, - } - _, err := x.Get(t) - return t, err -} - // IsUserExist checks if given user name exist, // the user name should be noncased unique. func IsUserExist(name string) (bool, error) { @@ -327,7 +319,8 @@ func UpdateUser(u *User) (err error) { return err } -// DeleteUser completely deletes everything of the user. +// TODO: need some kind of mechanism to record failure. +// DeleteUser completely and permanently deletes everything of user. func DeleteUser(u *User) error { // Check ownership of repository. count, err := GetRepositoryCount(u) @@ -346,32 +339,28 @@ func DeleteUser(u *User) error { } // TODO: check issues, other repos' commits + // TODO: roll backable in some point. // Delete all followers. if _, err = x.Delete(&Follow{FollowId: u.Id}); err != nil { return err } - // Delete oauth2. if _, err = x.Delete(&Oauth2{Uid: u.Id}); err != nil { return err } - // Delete all feeds. if _, err = x.Delete(&Action{UserId: u.Id}); err != nil { return err } - // Delete all watches. if _, err = x.Delete(&Watch{UserId: u.Id}); err != nil { return err } - // Delete all accesses. if _, err = x.Delete(&Access{UserName: u.LowerName}); err != nil { return err } - // Delete all SSH keys. keys := make([]*PublicKey, 0, 10) if err = x.Find(&keys, &PublicKey{OwnerId: u.Id}); err != nil { diff --git a/modules/middleware/repo.go b/modules/middleware/repo.go index 43ba1e8c..0c640275 100644 --- a/modules/middleware/repo.go +++ b/modules/middleware/repo.go @@ -44,6 +44,7 @@ func RepoAssignment(redirect bool, args ...bool) martini.Handler { repoName := params["reponame"] refName := params["branchname"] + // TODO: need more advanced onwership and access level check. // Collaborators who have write access can be seen as owners. if ctx.IsSigned { ctx.Repo.IsOwner, err = models.HasAccess(ctx.User.Name, userName+"/"+repoName, models.WRITABLE) diff --git a/routers/org/org.go b/routers/org/org.go index c036a8e5..7b2c4d73 100644 --- a/routers/org/org.go +++ b/routers/org/org.go @@ -30,7 +30,6 @@ func Members(ctx *middleware.Context, params martini.Params) { ctx.HTML(200, "org/members") } - func New(ctx *middleware.Context) { ctx.Data["Title"] = "Create An Organization" ctx.HTML(200, NEW) @@ -160,3 +159,47 @@ func SettingsPost(ctx *middleware.Context, params martini.Params, form auth.OrgS ctx.Flash.Success("Organization profile has been successfully updated.") ctx.Redirect("/org/" + org.Name + "/settings") } + +func DeletePost(ctx *middleware.Context, params martini.Params) { + ctx.Data["Title"] = "Settings" + + org, err := models.GetUserByName(params["org"]) + if err != nil { + if err == models.ErrUserNotExist { + ctx.Handle(404, "org.DeletePost(GetUserByName)", err) + } else { + ctx.Handle(500, "org.DeletePost(GetUserByName)", err) + } + return + } + ctx.Data["Org"] = org + + if !models.IsOrganizationOwner(org.Id, ctx.User.Id) { + ctx.Error(403) + return + } + + tmpUser := models.User{ + Passwd: ctx.Query("password"), + Salt: ctx.User.Salt, + } + tmpUser.EncodePasswd() + if tmpUser.Passwd != ctx.User.Passwd { + ctx.Flash.Error("Password is not correct. Make sure you are owner of this account.") + } else { + if err := models.DeleteOrganization(org); err != nil { + switch err { + case models.ErrUserOwnRepos: + ctx.Flash.Error("This organization still have ownership of repository, you have to delete or transfer them first.") + default: + ctx.Handle(500, "org.DeletePost(DeleteOrganization)", err) + return + } + } else { + ctx.Redirect("/") + return + } + } + + ctx.Redirect("/org/" + org.Name + "/settings") +} diff --git a/routers/repo/setting.go b/routers/repo/setting.go index 3d48e79c..e97eca12 100644 --- a/routers/repo/setting.go +++ b/routers/repo/setting.go @@ -122,13 +122,23 @@ func SettingPost(ctx *middleware.Context, form auth.RepoSettingForm) { return } - if err := models.DeleteRepository(ctx.User.Id, ctx.Repo.Repository.Id, ctx.User.LowerName); err != nil { - ctx.Handle(500, "setting.Delete", err) + if ctx.Repo.Owner.IsOrganization() && + !models.IsOrganizationOwner(ctx.Repo.Owner.Id, ctx.User.Id) { + ctx.Error(403) return } - log.Trace("%s Repository deleted: %s/%s", ctx.Req.RequestURI, ctx.User.LowerName, ctx.Repo.Repository.LowerName) - ctx.Redirect("/") + if err := models.DeleteRepository(ctx.Repo.Owner.Id, ctx.Repo.Repository.Id, ctx.Repo.Owner.Name); err != nil { + ctx.Handle(500, "setting.Delete(DeleteRepository)", err) + return + } + log.Trace("%s Repository deleted: %s/%s", ctx.Req.RequestURI, ctx.Repo.Owner.LowerName, ctx.Repo.Repository.LowerName) + + if ctx.Repo.Owner.IsOrganization() { + ctx.Redirect("/org/" + ctx.Repo.Owner.Name + "/dashboard") + } else { + ctx.Redirect("/") + } } } diff --git a/routers/user/user.go b/routers/user/user.go index a402744b..561fe1c1 100644 --- a/routers/user/user.go +++ b/routers/user/user.go @@ -296,7 +296,7 @@ func DeletePost(ctx *middleware.Context) { case models.ErrUserOwnRepos: ctx.Flash.Error("Your account still have ownership of repository, you have to delete or transfer them first.") default: - ctx.Handle(500, "user.Delete(DeleteUser)", err) + ctx.Handle(500, "user.DeletePost(DeleteUser)", err) return } } else { diff --git a/templates/VERSION b/templates/VERSION index be0ebee0..09c51980 100644 --- a/templates/VERSION +++ b/templates/VERSION @@ -1 +1 @@ -0.4.5.0627 Alpha \ No newline at end of file +0.4.5.0628 Alpha \ No newline at end of file diff --git a/templates/user/dashboard.tmpl b/templates/user/dashboard.tmpl index e1b43e15..2cb19cef 100644 --- a/templates/user/dashboard.tmpl +++ b/templates/user/dashboard.tmpl @@ -76,7 +76,7 @@