diff --git a/.gitignore b/.gitignore index d201223ef..425f227c1 100644 --- a/.gitignore +++ b/.gitignore @@ -8,4 +8,5 @@ custom/ data/ .vendor/ .idea/ -*.iml \ No newline at end of file +*.iml +public/img/avatar/ \ No newline at end of file diff --git a/.gobuild.yml b/.gobuild.yml index d667c9308..78a38f2d3 100644 --- a/.gobuild.yml +++ b/.gobuild.yml @@ -4,4 +4,5 @@ filesets: - public - conf - LICENSE - - README.md \ No newline at end of file + - README.md + - README_ZH.md \ No newline at end of file diff --git a/.gopmfile b/.gopmfile index 6e6b59c62..bd641a17c 100644 --- a/.gopmfile +++ b/.gopmfile @@ -8,6 +8,7 @@ github.com/Unknwon/com= github.com/Unknwon/cae= github.com/Unknwon/goconfig= github.com/dchest/scrypt= +github.com/nfnt/resize= github.com/lunny/xorm= github.com/gogits/logs= github.com/gogits/binding= diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 08013d370..17a3ebe68 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,49 +1,31 @@ # Contributing to Gogs -Want to hack on Gogs? Awesome! Here are instructions to get you -started. They are probably not perfect, please let us know if anything -feels wrong or incomplete. +> Thanks [drone](https://github.com/drone/drone) because this guidelines sheet is forked from its [CONTRIBUTING.md](https://github.com/drone/drone/blob/master/CONTRIBUTING.md). + +**This document is pre^3 release, we're not ready for receiving contribution until v0.5.0 release.** + +Want to hack on Gogs? Awesome! Here are instructions to get you started. They are probably not perfect, please let us know if anything feels wrong or incomplete. ## Contribution guidelines ### Pull requests are always welcome -We are always thrilled to receive pull requests, and do our best to -process them as fast as possible. Not sure if that typo is worth a pull -request? Do it! We will appreciate it. +We are always thrilled to receive pull requests, and do our best to process them as fast as possible. Not sure if that typo is worth a pull request? Do it! We will appreciate it. -If your pull request is not accepted on the first try, don't be -discouraged! If there's a problem with the implementation, hopefully you -received feedback on what to improve. +If your pull request is not accepted on the first try, don't be discouraged! If there's a problem with the implementation, hopefully you received feedback on what to improve. -We're trying very hard to keep Gogs lean and focused. We don't want it -to do everything for everybody. This means that we might decide against -incorporating a new feature. +We're trying very hard to keep Gogs lean and focused. We don't want it to do everything for everybody. This means that we might decide against incorporating a new feature. ### Discuss your design on the mailing list -We recommend discussing your plans [on the mailing -list](https://groups.google.com/forum/#!forum/gogits) -before starting to code - especially for more ambitious contributions. -This gives other contributors a chance to point you in the right -direction, give feedback on your design, and maybe point out if someone -else is working on the same thing. +We recommend discussing your plans [on the mailing list](https://groups.google.com/forum/#!forum/gogits) before starting to code - especially for more ambitious contributions. This gives other contributors a chance to point you in the right direction, give feedback on your design, and maybe point out if someone else is working on the same thing. -We may close your pull request if not first discussed on the mailing -list. We aren't doing this to be jerks. We are doing this to prevent -people from spending large amounts of time on changes that may need -to be designed or architected in a specific way, or may not align with -the vision of the project. +We may close your pull request if not first discussed on the mailing list. We aren't doing this to be jerks. We are doing this to prevent people from spending large amounts of time on changes that may need to be designed or architected in a specific way, or may not align with the vision of the project. ### Create issues... -Any significant improvement should be documented as [a GitHub -issue](https://github.com/gogits/gogs/issues) before anybody -starts working on it. +Any significant improvement should be documented as [a GitHub issue](https://github.com/gogits/gogs/issues) before anybody starts working on it. ### ...but check for existing issues first! -Please take a moment to check that an issue doesn't already exist -documenting your bug report or improvement proposal. If it does, it -never hurts to add a quick "+1" or "I have this problem too". This will -help prioritize the most common problems and requests. \ No newline at end of file +Please take a moment to check that an issue doesn't already exist documenting your bug report or improvement proposal. If it does, it never hurts to add a quick "+1" or "I have this problem too". This will help prioritize the most common problems and requests. \ No newline at end of file diff --git a/README.md b/README.md index e947d7739..104b7eab5 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,11 @@ -Gogs - Go Git Service [![wercker status](https://app.wercker.com/status/ad0bdb0bc450ac6f09bc56b9640a50aa/s/ "wercker status")](https://app.wercker.com/project/bykey/ad0bdb0bc450ac6f09bc56b9640a50aa) [![Build Status](https://drone.io/github.com/gogits/gogs/status.png)](https://drone.io/github.com/gogits/gogs/latest) [![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/gogits/gogs/trend.png)](https://bitdeli.com/free "Bitdeli Badge") +Gogs - Go Git Service [![wercker status](https://app.wercker.com/status/ad0bdb0bc450ac6f09bc56b9640a50aa/s/ "wercker status")](https://app.wercker.com/project/bykey/ad0bdb0bc450ac6f09bc56b9640a50aa) [![Build Status](https://drone.io/github.com/gogits/gogs/status.png)](https://drone.io/github.com/gogits/gogs/latest) ===================== Gogs(Go Git Service) is a Self Hosted Git Service in the Go Programming Language. ![Demo](http://gowalker.org/public/gogs_demo.gif) -##### Current version: 0.1.6 Alpha +##### Current version: 0.1.7 Alpha #### Other language version @@ -27,7 +27,7 @@ More importantly, Gogs only needs one binary to setup your own project hosting o ## Features - Activity timeline -- SSH protocol support. +- SSH/HTTPS protocol support. - Register/delete account. - Create/delete/watch public repository. - User profile page. @@ -48,9 +48,11 @@ There are two ways to install Gogs: ## Acknowledgments -- Logo is inspired by [martini](https://github.com/martini-contrib). +- Logo is inspired by [martini-contrib](https://github.com/martini-contrib). +- Router and middleware mechanism of [martini](http://martini.codegangsta.io/). - Mail Service, modules design is inspired by [WeTalk](https://github.com/beego/wetalk). - System Monitor Status is inspired by [GoBlog](https://github.com/fuxiaohei/goblog). +- Usage and modification from [beego](http://beego.me) modules. ## Contributors diff --git a/README_ZH.md b/README_ZH.md index 78e26fada..838e30a0e 100644 --- a/README_ZH.md +++ b/README_ZH.md @@ -1,11 +1,11 @@ -Gogs - Go Git Service [![wercker status](https://app.wercker.com/status/ad0bdb0bc450ac6f09bc56b9640a50aa/s/ "wercker status")](https://app.wercker.com/project/bykey/ad0bdb0bc450ac6f09bc56b9640a50aa) [![Build Status](https://drone.io/github.com/gogits/gogs/status.png)](https://drone.io/github.com/gogits/gogs/latest) [![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/gogits/gogs/trend.png)](https://bitdeli.com/free "Bitdeli Badge") +Gogs - Go Git Service [![wercker status](https://app.wercker.com/status/ad0bdb0bc450ac6f09bc56b9640a50aa/s/ "wercker status")](https://app.wercker.com/project/bykey/ad0bdb0bc450ac6f09bc56b9640a50aa) [![Build Status](https://drone.io/github.com/gogits/gogs/status.png)](https://drone.io/github.com/gogits/gogs/latest) ===================== Gogs(Go Git Service) 是一个由 Go 语言编写的自助 Git 托管服务。 ![Demo](http://gowalker.org/public/gogs_demo.gif) -##### 当前版本:0.1.6 Alpha +##### 当前版本:0.1.7 Alpha ## 开发目的 @@ -23,7 +23,7 @@ Gogs 完全使用 Go 语言来实现对 Git 数据的操作,实现 **零** 依 ## 功能特性 - 活动时间线 -- SSH 协议支持 +- SSH/HTTPS 协议支持 - 注册/删除用户 - 创建/删除/关注公开仓库 - 用户个人信息页面 @@ -44,9 +44,11 @@ Gogs 完全使用 Go 语言来实现对 Git 数据的操作,实现 **零** 依 ## 特别鸣谢 -- Logo 基于 [martini](https://github.com/martini-contrib) 修改而来。 -- 邮件服务、模块设计基于 [WeTalk](https://github.com/beego/wetalk) 修改而来。 -- 系统监视状态基于 [GoBlog](https://github.com/fuxiaohei/goblog) 修改而来。 +- Logo 基于 [martini-contrib](https://github.com/martini-contrib) 修改而来。 +- 基于 [WeTalk](https://github.com/beego/wetalk) 修改的邮件服务和模块设计。 +- 基于 [GoBlog](https://github.com/fuxiaohei/goblog) 修改的系统监视状态。 +- [beego](http://beego.me) 模块的使用与修改。 +- [martini](http://martini.codegangsta.io/) 的路由与中间件机制。 ## 贡献成员 diff --git a/conf/app.ini b/conf/app.ini index b051557f4..809ea61c0 100644 --- a/conf/app.ini +++ b/conf/app.ini @@ -32,6 +32,8 @@ PATH = data/gogs.db [admin] [security] +; Use HTTPS to clone repository, otherwise use HTTP. +ENABLE_HTTPS_CLONE = false ; !!CHANGE THIS TO KEEP YOUR USER DATA SAFE!! SECRET_KEY = !#@FDEWREWR&*( ; Auto-login remember days @@ -50,6 +52,8 @@ DISENABLE_REGISTERATION = false REQUIRE_SIGNIN_VIEW = false ; Cache avatar as picture ENABLE_CACHE_AVATAR = false +; Mail notification +ENABLE_NOTIFY_MAIL = false [mailer] ENABLED = false @@ -103,8 +107,6 @@ SESSION_ID_HASHKEY = [picture] ; The place to picture data, either "server" or "qiniu", default is "server" SERVICE = server -; For "server" only, root path of picture data, default is "data/pictures" -PATH = data/pictures [log] ; Either "console", "file", "conn", "smtp" or "database", default is "console" diff --git a/conf/gitignore/C++ b/conf/gitignore/C++ index 5a1b6ec43..620d3dc8a 100644 --- a/conf/gitignore/C++ +++ b/conf/gitignore/C++ @@ -10,4 +10,4 @@ # Compiled Static libraries *.lai *.la -*.a \ No newline at end of file +*.a diff --git a/gogs.go b/gogs.go index 0bdbbc069..93b7231b7 100644 --- a/gogs.go +++ b/gogs.go @@ -20,7 +20,7 @@ import ( // Test that go1.2 tag above is included in builds. main.go refers to this definition. const go12tag = true -const APP_VER = "0.1.6.0323.1" +const APP_VER = "0.1.7.0324" func init() { base.AppVer = APP_VER diff --git a/models/action.go b/models/action.go index 117492935..44d7aea8c 100644 --- a/models/action.go +++ b/models/action.go @@ -59,14 +59,18 @@ func (a Action) GetContent() string { // CommitRepoAction records action for commit repository. func CommitRepoAction(userId int64, userName string, repoId int64, repoName string, refName string, commits *base.PushCommits) error { + log.Trace("action.CommitRepoAction: %d/%s", userId, repoName) + bs, err := json.Marshal(commits) if err != nil { + log.Error("action.CommitRepoAction(json): %d/%s", userId, repoName) return err } // Add feeds for user self and all watchers. watches, err := GetWatches(repoId) if err != nil { + log.Error("action.CommitRepoAction(get watches): %d/%s", userId, repoName) return err } watches = append(watches, Watch{UserId: userId}) @@ -86,20 +90,23 @@ func CommitRepoAction(userId int64, userName string, RepoName: repoName, RefName: refName, }) + if err != nil { + log.Error("action.CommitRepoAction(notify watches): %d/%s", userId, repoName) + } return err } // Update repository last update time. repo, err := GetRepositoryByName(userId, repoName) if err != nil { + log.Error("action.CommitRepoAction(GetRepositoryByName): %d/%s", userId, repoName) return err } repo.IsBare = false if err = UpdateRepository(repo); err != nil { + log.Error("action.CommitRepoAction(UpdateRepository): %d/%s", userId, repoName) return err } - - log.Trace("action.CommitRepoAction: %d/%s", userId, repo.LowerName) return nil } diff --git a/models/issue.go b/models/issue.go index 929567b1b..fe43a94b5 100644 --- a/models/issue.go +++ b/models/issue.go @@ -58,6 +58,7 @@ func CreateIssue(userId, repoId, milestoneId, assigneeId int64, name, labels, co Content: content, } _, err = orm.Insert(issue) + // TODO: newIssueAction return issue, err } @@ -67,9 +68,9 @@ func GetIssueCount(repoId int64) (int64, error) { } // GetIssueById returns issue object by given id. -func GetIssueById(id int64) (*Issue, error) { - issue := new(Issue) - has, err := orm.Id(id).Get(issue) +func GetIssueByIndex(repoId, index int64) (*Issue, error) { + issue := &Issue{RepoId: repoId, Index: index} + has, err := orm.Get(issue) if err != nil { return nil, err } else if !has { @@ -126,6 +127,18 @@ func GetIssues(userId, repoId, posterId, milestoneId int64, page int, isClosed, return issues, err } +// UpdateIssue updates information of issue. +func UpdateIssue(issue *Issue) error { + _, err := orm.Update(issue, &Issue{RepoId: issue.RepoId, Index: issue.Index}) + return err +} + +func CloseIssue() { +} + +func ReopenIssue() { +} + // Label represents a list of labels of repository for issues. type Label struct { Id int64 diff --git a/models/repo.go b/models/repo.go index 14bcfcca4..6cbfaf105 100644 --- a/models/repo.go +++ b/models/repo.go @@ -389,7 +389,7 @@ func UpdateRepository(repo *Repository) error { repo.Website = repo.Website[:255] } - _, err := orm.Id(repo.Id).UseBool().Cols("description", "website").Update(repo) + _, err := orm.Id(repo.Id).AllCols().Update(repo) return err } diff --git a/models/user.go b/models/user.go index 9333d1ee6..6ca16ec32 100644 --- a/models/user.go +++ b/models/user.go @@ -72,6 +72,9 @@ func (user *User) HomeLink() string { // AvatarLink returns the user gravatar link. func (user *User) AvatarLink() string { + if base.Service.EnableCacheAvatar { + return "/avatar/" + user.Avatar + } return "http://1.gravatar.com/avatar/" + user.Avatar } @@ -208,7 +211,7 @@ func UpdateUser(user *User) (err error) { user.Website = user.Website[:255] } - _, err = orm.Id(user.Id).UseBool().Cols("website", "location").Update(user) + _, err = orm.Id(user.Id).AllCols().Update(user) return err } diff --git a/modules/avatar/avatar.go b/modules/avatar/avatar.go new file mode 100644 index 000000000..0ba20294a --- /dev/null +++ b/modules/avatar/avatar.go @@ -0,0 +1,296 @@ +// 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. + +// for www.gravatar.com image cache + +/* +It is recommend to use this way + + cacheDir := "./cache" + defaultImg := "./default.jpg" + http.Handle("/avatar/", avatar.HttpHandler(cacheDir, defaultImg)) +*/ +package avatar + +import ( + "crypto/md5" + "encoding/hex" + "errors" + "fmt" + "image" + "image/jpeg" + "image/png" + "io" + "net/http" + "net/url" + "os" + "path/filepath" + "strings" + "sync" + "time" + + "github.com/gogits/gogs/modules/log" + "github.com/nfnt/resize" +) + +var ( + gravatar = "http://www.gravatar.com/avatar" +) + +// hash email to md5 string +// keep this func in order to make this package indenpent +func HashEmail(email string) string { + h := md5.New() + h.Write([]byte(strings.ToLower(email))) + return hex.EncodeToString(h.Sum(nil)) +} + +type Avatar struct { + Hash string + AlterImage string // image path + cacheDir string // image save dir + reqParams string + imagePath string + expireDuration time.Duration +} + +func New(hash string, cacheDir string) *Avatar { + return &Avatar{ + Hash: hash, + cacheDir: cacheDir, + expireDuration: time.Minute * 10, + reqParams: url.Values{ + "d": {"retro"}, + "size": {"200"}, + "r": {"pg"}}.Encode(), + imagePath: filepath.Join(cacheDir, hash+".image"), //maybe png or jpeg + } +} + +func (this *Avatar) HasCache() bool { + fileInfo, err := os.Stat(this.imagePath) + return err == nil && fileInfo.Mode().IsRegular() +} + +func (this *Avatar) Modtime() (modtime time.Time, err error) { + fileInfo, err := os.Stat(this.imagePath) + if err != nil { + return + } + return fileInfo.ModTime(), nil +} + +func (this *Avatar) Expired() bool { + modtime, err := this.Modtime() + return err != nil || time.Since(modtime) > this.expireDuration +} + +// default image format: jpeg +func (this *Avatar) Encode(wr io.Writer, size int) (err error) { + var img image.Image + decodeImageFile := func(file string) (img image.Image, err error) { + fd, err := os.Open(file) + if err != nil { + return + } + defer fd.Close() + img, err = jpeg.Decode(fd) + if err != nil { + fd.Seek(0, os.SEEK_SET) + img, err = png.Decode(fd) + } + return + } + imgPath := this.imagePath + if !this.HasCache() { + if this.AlterImage == "" { + return errors.New("request image failed, and no alt image offered") + } + imgPath = this.AlterImage + } + img, err = decodeImageFile(imgPath) + if err != nil { + return + } + m := resize.Resize(uint(size), 0, img, resize.Lanczos3) + return jpeg.Encode(wr, m, nil) +} + +// get image from gravatar.com +func (this *Avatar) Update() { + thunder.Fetch(gravatar+"/"+this.Hash+"?"+this.reqParams, + this.imagePath) +} + +func (this *Avatar) UpdateTimeout(timeout time.Duration) error { + var err error + select { + case <-time.After(timeout): + err = fmt.Errorf("get gravatar image %s timeout", this.Hash) + case err = <-thunder.GoFetch(gravatar+"/"+this.Hash+"?"+this.reqParams, + this.imagePath): + } + return err +} + +type avatarHandler struct { + cacheDir string + altImage string +} + +func (this *avatarHandler) mustInt(r *http.Request, defaultValue int, keys ...string) int { + var v int + for _, k := range keys { + if _, err := fmt.Sscanf(r.FormValue(k), "%d", &v); err == nil { + defaultValue = v + } + } + return defaultValue +} + +func (this *avatarHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + urlPath := r.URL.Path + hash := urlPath[strings.LastIndex(urlPath, "/")+1:] + size := this.mustInt(r, 80, "s", "size") // default size = 80*80 + + avatar := New(hash, this.cacheDir) + avatar.AlterImage = this.altImage + if avatar.Expired() { + err := avatar.UpdateTimeout(time.Millisecond * 500) + if err != nil { + log.Trace("avatar update error: %v", err) + } + } + if modtime, err := avatar.Modtime(); err == nil { + etag := fmt.Sprintf("size(%d)", size) + if t, err := time.Parse(http.TimeFormat, r.Header.Get("If-Modified-Since")); err == nil && modtime.Before(t.Add(1*time.Second)) && etag == r.Header.Get("If-None-Match") { + h := w.Header() + delete(h, "Content-Type") + delete(h, "Content-Length") + w.WriteHeader(http.StatusNotModified) + return + } + w.Header().Set("Last-Modified", modtime.UTC().Format(http.TimeFormat)) + w.Header().Set("ETag", etag) + } + w.Header().Set("Content-Type", "image/jpeg") + err := avatar.Encode(w, size) + if err != nil { + log.Warn("avatar encode error: %v", err) + w.WriteHeader(500) + } +} + +// http.Handle("/avatar/", avatar.HttpHandler("./cache")) +func HttpHandler(cacheDir string, defaultImgPath string) http.Handler { + return &avatarHandler{ + cacheDir: cacheDir, + altImage: defaultImgPath, + } +} + +// thunder downloader +var thunder = &Thunder{QueueSize: 10} + +type Thunder struct { + QueueSize int // download queue size + q chan *thunderTask + once sync.Once +} + +func (t *Thunder) init() { + if t.QueueSize < 1 { + t.QueueSize = 1 + } + t.q = make(chan *thunderTask, t.QueueSize) + for i := 0; i < t.QueueSize; i++ { + go func() { + for { + task := <-t.q + task.Fetch() + } + }() + } +} + +func (t *Thunder) Fetch(url string, saveFile string) error { + t.once.Do(t.init) + task := &thunderTask{ + Url: url, + SaveFile: saveFile, + } + task.Add(1) + t.q <- task + task.Wait() + return task.err +} + +func (t *Thunder) GoFetch(url, saveFile string) chan error { + c := make(chan error) + go func() { + c <- t.Fetch(url, saveFile) + }() + return c +} + +// thunder download +type thunderTask struct { + Url string + SaveFile string + sync.WaitGroup + err error +} + +func (this *thunderTask) Fetch() { + this.err = this.fetch() + this.Done() +} + +var client = &http.Client{} + +func (this *thunderTask) fetch() error { + req, _ := http.NewRequest("GET", this.Url, nil) + req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8") + req.Header.Set("Accept-Encoding", "gzip,deflate,sdch") + req.Header.Set("Accept-Language", "zh-CN,zh;q=0.8") + req.Header.Set("Cache-Control", "no-cache") + req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36") + resp, err := client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode != 200 { + return fmt.Errorf("status code: %d", resp.StatusCode) + } + + /* + log.Println("headers:", resp.Header) + switch resp.Header.Get("Content-Type") { + case "image/jpeg": + this.SaveFile += ".jpeg" + case "image/png": + this.SaveFile += ".png" + } + */ + /* + imgType := resp.Header.Get("Content-Type") + if imgType != "image/jpeg" && imgType != "image/png" { + return errors.New("not png or jpeg") + } + */ + + tmpFile := this.SaveFile + ".part" // mv to destination when finished + fd, err := os.Create(tmpFile) + if err != nil { + return err + } + _, err = io.Copy(fd, resp.Body) + fd.Close() + if err != nil { + os.Remove(tmpFile) + return err + } + return os.Rename(tmpFile, this.SaveFile) +} diff --git a/modules/avatar/avatar_test.go b/modules/avatar/avatar_test.go new file mode 100644 index 000000000..4656d6f0f --- /dev/null +++ b/modules/avatar/avatar_test.go @@ -0,0 +1,61 @@ +// 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 avatar_test + +import ( + "errors" + "os" + "strconv" + "testing" + "time" + + "github.com/gogits/gogs/modules/avatar" + "github.com/gogits/gogs/modules/log" +) + +const TMPDIR = "test-avatar" + +func TestFetch(t *testing.T) { + os.Mkdir(TMPDIR, 0755) + defer os.RemoveAll(TMPDIR) + + hash := avatar.HashEmail("ssx205@gmail.com") + a := avatar.New(hash, TMPDIR) + a.UpdateTimeout(time.Millisecond * 200) +} + +func TestFetchMany(t *testing.T) { + os.Mkdir(TMPDIR, 0755) + defer os.RemoveAll(TMPDIR) + + t.Log("start") + var n = 5 + ch := make(chan bool, n) + for i := 0; i < n; i++ { + go func(i int) { + hash := avatar.HashEmail(strconv.Itoa(i) + "ssx205@gmail.com") + a := avatar.New(hash, TMPDIR) + a.Update() + t.Log("finish", hash) + ch <- true + }(i) + } + for i := 0; i < n; i++ { + <-ch + } + t.Log("end") +} + +// cat +// wget http://www.artsjournal.com/artfulmanager/wp/wp-content/uploads/2013/12/200x200xmirror_cat.jpg.pagespeed.ic.GOZSv6v1_H.jpg -O default.jpg +/* +func TestHttp(t *testing.T) { + http.Handle("/", avatar.HttpHandler("./", "default.jpg")) + http.ListenAndServe(":8001", nil) +} +*/ + +func TestLogTrace(t *testing.T) { + log.Trace("%v", errors.New("console log test")) +} diff --git a/modules/base/conf.go b/modules/base/conf.go index 19f587077..b4e0de97b 100644 --- a/modules/base/conf.go +++ b/modules/base/conf.go @@ -38,6 +38,8 @@ var ( RunUser string RepoRootPath string + EnableHttpsClone bool + LogInRememberDays int CookieUserName string CookieRememberName string @@ -56,8 +58,7 @@ var ( SessionConfig *session.Config SessionManager *session.Manager - PictureService string - PictureRootPath string + PictureService string ) var Service struct { @@ -65,6 +66,7 @@ var Service struct { DisenableRegisteration bool RequireSignInView bool EnableCacheAvatar bool + NotifyMail bool ActiveCodeLives int ResetPwdCodeLives int } @@ -98,7 +100,7 @@ func newService() { Service.EnableCacheAvatar = Cfg.MustBool("service", "ENABLE_CACHE_AVATAR", false) } -func newLogService() { +func NewLogService() { // Get and check log mode. LogMode = Cfg.MustValue("log", "MODE", "console") modeSec := "log." + LogMode @@ -123,7 +125,7 @@ func newLogService() { logPath := Cfg.MustValue(modeSec, "FILE_NAME", "log/gogs.log") os.MkdirAll(path.Dir(logPath), os.ModePerm) LogConfig = fmt.Sprintf( - `{"level":%s,"filename":%s,"rotate":%v,"maxlines":%d,"maxsize",%d,"daily":%v,"maxdays":%d}`, level, + `{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`, level, logPath, Cfg.MustBool(modeSec, "LOG_ROTATE", true), Cfg.MustInt(modeSec, "MAX_LINES", 1000000), @@ -131,20 +133,20 @@ func newLogService() { Cfg.MustBool(modeSec, "DAILY_ROTATE", true), Cfg.MustInt(modeSec, "MAX_DAYS", 7)) case "conn": - LogConfig = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":%s,"addr":%s}`, level, + LogConfig = fmt.Sprintf(`{"level":"%s","reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level, Cfg.MustBool(modeSec, "RECONNECT_ON_MSG", false), Cfg.MustBool(modeSec, "RECONNECT", false), Cfg.MustValue(modeSec, "PROTOCOL", "tcp"), Cfg.MustValue(modeSec, "ADDR", ":7020")) case "smtp": - LogConfig = fmt.Sprintf(`{"level":%s,"username":%s,"password":%s,"host":%s,"sendTos":%s,"subject":%s}`, level, + LogConfig = fmt.Sprintf(`{"level":"%s","username":"%s","password":"%s","host":"%s","sendTos":"%s","subject":"%s"}`, level, Cfg.MustValue(modeSec, "USER", "example@example.com"), Cfg.MustValue(modeSec, "PASSWD", "******"), Cfg.MustValue(modeSec, "HOST", "127.0.0.1:25"), Cfg.MustValue(modeSec, "RECEIVERS", "[]"), Cfg.MustValue(modeSec, "SUBJECT", "Diagnostic message from serve")) case "database": - LogConfig = fmt.Sprintf(`{"level":%s,"driver":%s,"conn":%s}`, level, + LogConfig = fmt.Sprintf(`{"level":"%s","driver":"%s","conn":"%s"}`, level, Cfg.MustValue(modeSec, "Driver"), Cfg.MustValue(modeSec, "CONN")) } @@ -229,6 +231,17 @@ func newRegisterMailService() { log.Info("Register Mail Service Enabled") } +func newNotifyMailService() { + if !Cfg.MustBool("service", "ENABLE_NOTIFY_MAIL") { + return + } else if MailService == nil { + log.Warn("Notify Mail Service: Mail Service is not enabled") + return + } + Service.NotifyMail = true + log.Info("Notify Mail Service Enabled") +} + func NewConfigContext() { var err error workDir, err := exeDir() @@ -246,11 +259,16 @@ func NewConfigContext() { Cfg.BlockMode = false cfgPath = filepath.Join(workDir, "custom/conf/app.ini") - if com.IsFile(cfgPath) { - if err = Cfg.AppendFiles(cfgPath); err != nil { - fmt.Printf("Cannot load config file '%s'\n", cfgPath) - os.Exit(2) - } + if !com.IsFile(cfgPath) { + fmt.Println("Custom configuration not found(custom/conf/app.ini)\n" + + "Please create it and make your own configuration!") + os.Exit(2) + + } + + if err = Cfg.AppendFiles(cfgPath); err != nil { + fmt.Printf("Cannot load config file '%s'\n", cfgPath) + os.Exit(2) } AppName = Cfg.MustValue("", "APP_NAME", "Gogs: Go Git Service") @@ -260,12 +278,13 @@ func NewConfigContext() { SecretKey = Cfg.MustValue("security", "SECRET_KEY") RunUser = Cfg.MustValue("", "RUN_USER") + EnableHttpsClone = Cfg.MustBool("security", "ENABLE_HTTPS_CLONE", false) + LogInRememberDays = Cfg.MustInt("security", "LOGIN_REMEMBER_DAYS") CookieUserName = Cfg.MustValue("security", "COOKIE_USERNAME") CookieRememberName = Cfg.MustValue("security", "COOKIE_REMEMBER_NAME") PictureService = Cfg.MustValue("picture", "SERVICE") - PictureRootPath = Cfg.MustValue("picture", "PATH") // Determine and create root git reposiroty path. RepoRootPath = Cfg.MustValue("repository", "ROOT") @@ -277,9 +296,10 @@ func NewConfigContext() { func NewServices() { newService() - newLogService() + NewLogService() newCacheService() newSessionService() newMailService() newRegisterMailService() + newNotifyMailService() } diff --git a/modules/base/tool.go b/modules/base/tool.go index b48566f54..0dec7aa8d 100644 --- a/modules/base/tool.go +++ b/modules/base/tool.go @@ -102,7 +102,7 @@ func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string // AvatarLink returns avatar link by given e-mail. func AvatarLink(email string) string { - return "http://1.gravatar.com/avatar/" + EncodeMd5(email) + return "/avatar/" + EncodeMd5(email) } // Seconds-based time units @@ -519,7 +519,7 @@ func ActionDesc(act Actioner, avatarLink string) string { buf.WriteString(fmt.Sprintf(TPL_COMMIT_REPO_LI, avatarLink, actUserName, repoName, commit[0], commit[0][:7], commit[1]) + "\n") } if push.Len > 3 { - buf.WriteString(fmt.Sprintf(`
%d other commits >>
`, actUserName, repoName, push.Len)) + buf.WriteString(fmt.Sprintf(`
%d other commits >>
`, actUserName, repoName, branch, push.Len)) } return fmt.Sprintf(TPL_COMMIT_REPO, actUserName, actUserName, actUserName, repoName, branch, branch, actUserName, repoName, actUserName, repoName, buf.String()) diff --git a/modules/log/log.go b/modules/log/log.go index 29782fb2b..0c07c7c62 100644 --- a/modules/log/log.go +++ b/modules/log/log.go @@ -11,6 +11,11 @@ import ( var logger *logs.BeeLogger +func init() { + logger = logs.NewLogger(10000) + logger.SetLogger("console", `{"level": 0}`) +} + func NewLogger(bufLen int64, mode, config string) { logger = logs.NewLogger(bufLen) logger.SetLogger(mode, config) @@ -20,6 +25,10 @@ func Trace(format string, v ...interface{}) { logger.Trace(format, v...) } +func Debug(format string, v ...interface{}) { + logger.Debug(format, v...) +} + func Info(format string, v ...interface{}) { logger.Info(format, v...) } diff --git a/modules/middleware/auth.go b/modules/middleware/auth.go index 82c3367c4..64f75d75c 100644 --- a/modules/middleware/auth.go +++ b/modules/middleware/auth.go @@ -21,7 +21,7 @@ type ToggleOptions struct { func Toggle(options *ToggleOptions) martini.Handler { return func(ctx *Context) { - if options.SignOutRequire && ctx.IsSigned { + if options.SignOutRequire && ctx.IsSigned && ctx.Req.RequestURI != "/" { ctx.Redirect("/") return } diff --git a/modules/middleware/repo.go b/modules/middleware/repo.go index 3864caaf8..eea2570ca 100644 --- a/modules/middleware/repo.go +++ b/modules/middleware/repo.go @@ -69,8 +69,12 @@ func RepoAssignment(redirect bool) martini.Handler { ctx.Repo.IsWatching = models.IsWatching(ctx.User.Id, repo.Id) } ctx.Repo.Repository = repo + scheme := "http" + if base.EnableHttpsClone { + scheme = "https" + } ctx.Repo.CloneLink.SSH = fmt.Sprintf("git@%s:%s/%s.git", base.Domain, user.LowerName, repo.LowerName) - ctx.Repo.CloneLink.HTTPS = fmt.Sprintf("https://%s/%s/%s.git", base.Domain, user.LowerName, repo.LowerName) + ctx.Repo.CloneLink.HTTPS = fmt.Sprintf("%s://%s/%s/%s.git", scheme, base.Domain, user.LowerName, repo.LowerName) ctx.Data["IsRepositoryValid"] = true ctx.Data["Repository"] = repo diff --git a/public/css/gogs.css b/public/css/gogs.css index 65a6c03d7..434af0359 100755 --- a/public/css/gogs.css +++ b/public/css/gogs.css @@ -711,6 +711,12 @@ html, body { width: 1%; } +.file-content .file-body.file-code .lines-ellipsis { + background-color: #FAFAFA; + color: #999; + width: 1%; +} + .file-content .file-body.file-code .lines-num span { font-family: Menlo, Monaco, Consolas, "Courier New", monospace; line-height: 1.6; @@ -798,7 +804,7 @@ html, body { margin-left: .5em; } -.commit-box .avatar { +.commit-box .avatar, .diff-head-box .avatar { width: 20px; height: 20px; margin-right: 8px; @@ -831,10 +837,141 @@ html, body { background-color: #FFF; } -.guide-box { +.guide-box, .diff-head-box { margin-top: 20px; } +.diff-head-box h4 { + margin-top: 0; + margin-bottom: 0; + line-height: 26px; +} + +.diff-head-box p { + margin-bottom: 0; +} + +.diff-head-box .sha { + margin-left: 8px; +} + +.diff-head-box a.name { + color: #444; + margin-right: 8px; +} + +.diff-head-box span.time { + color: #888; +} + +.diff-detail-box { + margin-bottom: 16px; + line-height: 30px; +} + +.diff-detail-box span.status { + display: inline-block; + width: 12px; + height: 12px; + margin-right: 8px; + vertical-align: middle; +} + +.diff-detail-box ol { + padding-left: 0; + margin-bottom: 28px; +} + +.diff-detail-box li { + list-style: none; + padding-bottom: 4px; + margin-bottom: 4px; + border-bottom: 1px dashed #DDD; + padding-left: 6px; +} + +.diff-detail-box span.status.modify { + background-color: #f0db88; +} + +.diff-detail-box span.status.add { + background-color: #b4e2b4; +} + +.diff-detail-box span.status.del { + background-color: #e9aeae; +} + +.diff-detail-box span.status.rename { + background-color: #dad8ff; +} + +.diff-file-box .panel-heading { + padding: 10px 20px; + line-height: 26px; +} + +.diff-box .count { + margin-right: 12px; +} + +.diff-box .count .bar { + width: 40px; + display: inline-block; + margin: 2px 4px 0 4px; + vertical-align: text-top; +} + +.diff-box .file { + color: #888; +} + +#gogs-source .file-content.diff-file-box { + margin-bottom: 20px; +} + +.diff-box .count .bar .add { + background-color: #77c64a; + height: 12px; +} + +.diff-box .count .bar .del, .diff-box .count .bar { + background-color: #e75316; + height: 12px; +} + +.diff-file-box .file-body.file-code .lines-code > pre { + margin: 0; + padding: 3px; +} + +.diff-file-box .file-body.file-code .lines-num-old { + border-right: 1px solid #DDD; +} + +.diff-file-box .code-bin td { + padding: 20px; +} + +.diff-file-box .code-diff tbody tr.add-code td, .diff-file-box .code-diff tbody tr.add-code pre { + background-color: #d1ffd6 !important; + border-color: #b4e2b4 !important; +} + +.diff-file-box .code-diff tbody tr.del-code td, .diff-file-box .code-diff tbody tr.del-code pre { + background-color: #ffe2dd !important; + border-color: #e9aeae !important; +} + +.diff-file-box .code-diff tbody tr:hover td, .diff-file-box .code-diff tbody tr:hover pre { + background-color: #fff8d2 !important; + border-color: #f0db88 !important; +} + +.diff-file-box .ellipsis-code pre { + color: #AAA; +} + /* wrapper and footer */ #wrapper { diff --git a/public/css/markdown.css b/public/css/markdown.css index 9f4024ba8..d46fd9436 100644 --- a/public/css/markdown.css +++ b/public/css/markdown.css @@ -135,13 +135,12 @@ box-shadow: inset 40px 0 0 #f5f5f5, inset 41px 0 0 #ccc; } -.markdown > pre > code, -.markdown > pre > ol.linenums > li > code { +.markdown > pre > code { white-space: pre; word-wrap: normal; } -.markdown > pre > ol.linenums > li > code { +.markdown > pre > ol.linenums > li { padding: 0 10px; } diff --git a/public/img/avatar_default.jpg b/public/img/avatar_default.jpg new file mode 100644 index 000000000..728ec5af6 Binary files /dev/null and b/public/img/avatar_default.jpg differ diff --git a/public/js/app.js b/public/js/app.js index e0f92854f..9a58a6f2f 100644 --- a/public/js/app.js +++ b/public/js/app.js @@ -2,11 +2,11 @@ var Gogits = { "PageIsSignup": false }; -(function($){ +(function ($) { // extend jQuery ajax, set csrf token value var ajax = $.ajax; $.extend({ - ajax: function(url, options) { + ajax: function (url, options) { if (typeof url === 'object') { options = url; url = undefined; @@ -17,20 +17,37 @@ var Gogits = { var headers = options.headers || {}; var domain = document.domain.replace(/\./ig, '\\.'); if (!/^(http:|https:).*/.test(url) || eval('/^(http:|https:)\\/\\/(.+\\.)*' + domain + '.*/').test(url)) { - headers = $.extend(headers, {'X-Csrf-Token':csrftoken}); + headers = $.extend(headers, {'X-Csrf-Token': csrftoken}); } options.headers = headers; var callback = options.success; - options.success = function(data){ - if(data.once){ + options.success = function (data) { + if (data.once) { // change all _once value if ajax data.once exist $('[name=_once]').val(data.once); } - if(callback){ + if (callback) { callback.apply(this, arguments); } }; return ajax(url, options); + }, + + changeHash: function (hash) { + if (history.pushState) { + history.pushState(null, null, hash); + } + else { + location.hash = hash; + } + }, + + deSelect: function () { + if (window.getSelection) { + window.getSelection().removeAllRanges(); + } else { + document.selection.empty(); + } } }); }(jQuery)); @@ -97,8 +114,8 @@ var Gogits = { $tabs.find("li:eq(0) a").tab("show"); }; // fix dropdown inside click - Gogits.initDropDown = function(){ - $('.dropdown-menu.no-propagation').on('click',function(e){ + Gogits.initDropDown = function () { + $('.dropdown-menu.no-propagation').on('click', function (e) { e.stopPropagation(); }); }; @@ -110,25 +127,6 @@ var Gogits = { $pre.addClass('prettyprint linenums'); prettyPrint(); - var $lineNums = $pre.parent().siblings('.lines-num'); - if ($lineNums.length > 0) { - var nums = $pre.find('ol.linenums > li').length; - for (var i = 1; i <= nums; i++) { - $lineNums.append('' + i + ''); - } - - var last; - $(document).on('click', '.lines-num span', function () { - var $e = $(this); - if (last) { - last.removeClass('active'); - } - last = $e.parent().siblings('.lines-code').find('ol.linenums > ' + $e.attr('rel')); - last.addClass('active'); - window.location.href = '#' + $e.attr('id'); - }); - } - // Set anchor. var headers = {}; $md.find('h1, h2, h3, h4, h5, h6').each(function () { @@ -146,7 +144,70 @@ var Gogits = { node = node.wrap('
'); node.append(''); }); - } + }; + + Gogits.renderCodeView = function () { + function selectRange($list, $select, $from) { + $list.removeClass('active'); + if ($from) { + var a = parseInt($select.attr('rel').substr(1)); + var b = parseInt($from.attr('rel').substr(1)); + var c; + if (a != b) { + if (a > b) { + c = a; + a = b; + b = c; + } + var classes = []; + for (i = a; i <= b; i++) { + classes.push('.L' + i); + } + $list.filter(classes.join(',')).addClass('active'); + $.changeHash('#L' + a + '-' + 'L' + b); + return + } + } + $select.addClass('active'); + $.changeHash('#' + $select.attr('rel')); + } + + $(document).on('click', '.lines-num span', function (e) { + var $select = $(this); + var $list = $select.parent().siblings('.lines-code').find('ol.linenums > li'); + selectRange($list, $list.filter('[rel=' + $select.attr('rel') + ']'), (e.shiftKey ? $list.filter('.active').eq(0) : null)); + $.deSelect(); + }); + + $('.code-view .lines-code > pre').each(function () { + var $pre = $(this); + var $lineCode = $pre.parent(); + var $lineNums = $lineCode.siblings('.lines-num'); + if ($lineNums.length > 0) { + var nums = $pre.find('ol.linenums > li').length; + for (var i = 1; i <= nums; i++) { + $lineNums.append('' + i + ''); + } + } + }); + + $(window).on('hashchange',function (e) { + var m = window.location.hash.match(/^#(L\d+)\-(L\d+)$/); + var $list = $('.code-view ol.linenums > li'); + if (m) { + var $first = $list.filter('.' + m[1]); + selectRange($list, $first, $list.filter('.' + m[2])); + $("html, body").scrollTop($first.offset().top - 200); + return; + } + m = window.location.hash.match(/^#(L\d+)$/); + if (m) { + var $first = $list.filter('.' + m[1]); + selectRange($list, $first); + $("html, body").scrollTop($first.offset().top - 200); + } + }).trigger('hashchange'); + }; })(jQuery); @@ -177,6 +238,7 @@ function initCore() { Gogits.initModals(); Gogits.initDropDown(); Gogits.renderMarkdown(); + Gogits.renderCodeView(); } function initRegister() { @@ -272,6 +334,21 @@ function initRepository() { return false; }); })(); + + // repo diff counter + (function () { + var $counter = $('.diff-counter'); + if ($counter.length < 1) { + return; + } + $counter.each(function (i, item) { + var $item = $(item); + var addLine = $item.find('span[data-line].add').data("line"); + var delLine = $item.find('span[data-line].del').data("line"); + var addPercent = parseFloat(addLine) / (parseFloat(addLine) + parseFloat(delLine)) * 100; + $item.find(".bar .add").css("width", addPercent + "%"); + }); + }()); } (function ($) { diff --git a/public/js/lib.js b/public/js/lib.js index b5cc41c04..8735ac9c1 100644 --- a/public/js/lib.js +++ b/public/js/lib.js @@ -340,7 +340,7 @@ q,"'\"`"]):d.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(? s+")*(?:\\x5D|$))+/")+")")])}(b=a.types)&&g.push(["typ",b]);b=(""+a.keywords).replace(/^ | $/g,"");b.length&&g.push(["kwd",RegExp("^(?:"+b.replace(/[\s,]+/g,"|")+")\\b"),q]);d.push(["pln",/^\s+/,q," \r\n\t\u00a0"]);b="^.[^\\s\\w.$@'\"`/\\\\]*";a.regexLiterals&&(b+="(?!s*/)");g.push(["lit",/^@[$_a-z][\w$@]*/i,q],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],["pln",/^[$_a-z][\w$@]*/i,q],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,"0123456789"],["pln",/^\\[\S\s]?/, q],["pun",RegExp(b),q]);return C(d,g)}function J(a,d,g){function b(a){var c=a.nodeType;if(c==1&&!x.test(a.className))if("br"===a.nodeName)s(a),a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)b(a);else if((c==3||c==4)&&g){var d=a.nodeValue,i=d.match(m);if(i)c=d.substring(0,i.index),a.nodeValue=c,(d=d.substring(i.index+i[0].length))&&a.parentNode.insertBefore(j.createTextNode(d),a.nextSibling),s(a),c||a.parentNode.removeChild(a)}}function s(a){function b(a,c){var d= c?a.cloneNode(!1):a,e=a.parentNode;if(e){var e=b(e,1),g=a.nextSibling;e.appendChild(d);for(var i=g;i;i=g)g=i.nextSibling,e.appendChild(i)}return d}for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),d;(d=a.parentNode)&&d.nodeType===1;)a=d;c.push(a)}for(var x=/(?:^|\s)nocode(?:\s|$)/,m=/\r\n?|\n/,j=a.ownerDocument,k=j.createElement("li");a.firstChild;)k.appendChild(a.firstChild);for(var c=[k],i=0;i=0;){var b=d[g];F.hasOwnProperty(b)?D.console&&console.warn("cannot override language handler %s",b):F[b]=a}}function I(a,d){if(!a||!F.hasOwnProperty(a))a=/^\s*=0;){var b=d[g];F.hasOwnProperty(b)?D.console&&console.warn("cannot override language handler %s",b):F[b]=a}}function I(a,d){if(!a||!F.hasOwnProperty(a))a=/^\s*=l&&(b+=2);g>=B&&(r+=2)}}finally{if(f)f.style.display=h}}catch(u){D.console&&console.log(u&&u.stack||u)}}var D=window,y=["break,continue,do,else,for,if,return,while"],E=[[y,"auto,case,char,const,default,double,enum,extern,float,goto,inline,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"], "catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],M=[E,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,delegate,dynamic_cast,explicit,export,friend,generic,late_check,mutable,namespace,nullptr,property,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],N=[E,"abstract,assert,boolean,byte,extends,final,finally,implements,import,instanceof,interface,null,native,package,strictfp,super,synchronized,throws,transient"], diff --git a/routers/admin/admin.go b/routers/admin/admin.go index c0f39f715..0b5e3d8e7 100644 --- a/routers/admin/admin.go +++ b/routers/admin/admin.go @@ -141,6 +141,7 @@ func Config(ctx *middleware.Context) { ctx.Data["Domain"] = base.Domain ctx.Data["RunUser"] = base.RunUser ctx.Data["RunMode"] = strings.Title(martini.Env) + ctx.Data["EnableHttpsClone"] = base.EnableHttpsClone ctx.Data["RepoRootPath"] = base.RepoRootPath ctx.Data["Service"] = base.Service @@ -160,7 +161,6 @@ func Config(ctx *middleware.Context) { ctx.Data["SessionConfig"] = base.SessionConfig ctx.Data["PictureService"] = base.PictureService - ctx.Data["PictureRootPath"] = base.PictureRootPath ctx.Data["LogMode"] = base.LogMode ctx.Data["LogConfig"] = base.LogConfig diff --git a/routers/dashboard.go b/routers/dashboard.go index dafe9f31e..76ecc3f67 100644 --- a/routers/dashboard.go +++ b/routers/dashboard.go @@ -26,6 +26,6 @@ func Help(ctx *middleware.Context) { func NotFound(ctx *middleware.Context) { ctx.Data["PageIsNotFound"] = true - ctx.Data["Title"] = 404 + ctx.Data["Title"] = "Page Not Found" ctx.Handle(404, "home.NotFound", nil) } diff --git a/routers/repo/branch.go b/routers/repo/branch.go new file mode 100644 index 000000000..8c953f2ed --- /dev/null +++ b/routers/repo/branch.go @@ -0,0 +1,38 @@ +// 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 repo + +import ( + "github.com/codegangsta/martini" + "github.com/gogits/gogs/models" + "github.com/gogits/gogs/modules/middleware" +) + +func Branches(ctx *middleware.Context, params martini.Params) { + if !ctx.Repo.IsValid { + return + } + + brs, err := models.GetBranches(params["username"], params["reponame"]) + if err != nil { + ctx.Handle(200, "repo.Branches", err) + return + } else if len(brs) == 0 { + ctx.Handle(404, "repo.Branches", nil) + return + } + + ctx.Data["Username"] = params["username"] + ctx.Data["Reponame"] = params["reponame"] + + if len(params["branchname"]) == 0 { + params["branchname"] = "master" + } + ctx.Data["Branchname"] = params["branchname"] + ctx.Data["Branches"] = brs + ctx.Data["IsRepoToolbarBranches"] = true + + ctx.HTML(200, "repo/branches") +} diff --git a/routers/repo/commit.go b/routers/repo/commit.go new file mode 100644 index 000000000..e038998f9 --- /dev/null +++ b/routers/repo/commit.go @@ -0,0 +1,41 @@ +// 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 repo + +import ( + "github.com/codegangsta/martini" + "github.com/gogits/gogs/models" + "github.com/gogits/gogs/modules/middleware" +) + +func Commits(ctx *middleware.Context, params martini.Params) { + brs, err := models.GetBranches(params["username"], params["reponame"]) + if err != nil { + ctx.Handle(200, "repo.Commits", err) + return + } else if len(brs) == 0 { + ctx.Handle(404, "repo.Commits", nil) + return + } + + ctx.Data["IsRepoToolbarCommits"] = true + commits, err := models.GetCommits(params["username"], + params["reponame"], params["branchname"]) + if err != nil { + ctx.Handle(404, "repo.Commits", nil) + return + } + ctx.Data["Username"] = params["username"] + ctx.Data["Reponame"] = params["reponame"] + ctx.Data["CommitCount"] = commits.Len() + ctx.Data["Commits"] = commits + ctx.HTML(200, "repo/commits") +} + +func Diff(ctx *middleware.Context,params martini.Params){ + ctx.Data["Title"] = "commit-sha" + ctx.Data["IsRepoToolbarCommits"] = true + ctx.HTML(200,"repo/diff") +} diff --git a/routers/repo/issue.go b/routers/repo/issue.go index 78fe4b25d..e03f115e2 100644 --- a/routers/repo/issue.go +++ b/routers/repo/issue.go @@ -31,6 +31,10 @@ func Issues(ctx *middleware.Context, params martini.Params) { return } + if len(params["branchname"]) == 0 { + params["branchname"] = "master" + } + ctx.Data["Branchname"] = params["branchname"] ctx.HTML(200, "repo/issues") } @@ -63,13 +67,13 @@ func CreateIssue(ctx *middleware.Context, params martini.Params, form auth.Creat } func ViewIssue(ctx *middleware.Context, params martini.Params) { - issueid, err := base.StrTo(params["issueid"]).Int() + index, err := base.StrTo(params["index"]).Int() if err != nil { ctx.Handle(404, "issue.ViewIssue", err) return } - issue, err := models.GetIssueById(int64(issueid)) + issue, err := models.GetIssueByIndex(ctx.Repo.Repository.Id, int64(index)) if err != nil { if err == models.ErrIssueNotExist { ctx.Handle(404, "issue.ViewIssue", err) @@ -83,3 +87,39 @@ func ViewIssue(ctx *middleware.Context, params martini.Params) { ctx.Data["Issue"] = issue ctx.HTML(200, "issue/view") } + +func UpdateIssue(ctx *middleware.Context, params martini.Params, form auth.CreateIssueForm) { + if !ctx.Repo.IsOwner { + ctx.Handle(404, "issue.UpdateIssue", nil) + return + } + + index, err := base.StrTo(params["index"]).Int() + if err != nil { + ctx.Handle(404, "issue.UpdateIssue", err) + return + } + + issue, err := models.GetIssueByIndex(ctx.Repo.Repository.Id, int64(index)) + if err != nil { + if err == models.ErrIssueNotExist { + ctx.Handle(404, "issue.UpdateIssue", err) + } else { + ctx.Handle(200, "issue.UpdateIssue", err) + } + return + } + + issue.Name = form.IssueName + issue.MilestoneId = form.MilestoneId + issue.AssigneeId = form.AssigneeId + issue.Labels = form.Labels + issue.Content = form.Content + if err = models.UpdateIssue(issue); err != nil { + ctx.Handle(200, "issue.UpdateIssue", err) + return + } + + ctx.Data["Title"] = issue.Name + ctx.Data["Issue"] = issue +} diff --git a/routers/repo/pull.go b/routers/repo/pull.go new file mode 100644 index 000000000..16c60389d --- /dev/null +++ b/routers/repo/pull.go @@ -0,0 +1,21 @@ +// 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 repo + +import ( + "github.com/codegangsta/martini" + + "github.com/gogits/gogs/modules/middleware" +) + +func Pulls(ctx *middleware.Context, params martini.Params) { + ctx.Data["IsRepoToolbarPulls"] = true + if len(params["branchname"]) == 0 { + params["branchname"] = "master" + } + + ctx.Data["Branchname"] = params["branchname"] + ctx.HTML(200, "repo/pulls") +} diff --git a/routers/repo/repo.go b/routers/repo/repo.go index 82956098b..a055b416c 100644 --- a/routers/repo/repo.go +++ b/routers/repo/repo.go @@ -52,30 +52,6 @@ func Create(ctx *middleware.Context, form auth.CreateRepoForm) { ctx.Handle(200, "repo.Create", err) } -func Branches(ctx *middleware.Context, params martini.Params) { - if !ctx.Repo.IsValid { - return - } - - brs, err := models.GetBranches(params["username"], params["reponame"]) - if err != nil { - ctx.Handle(200, "repo.Branches", err) - return - } else if len(brs) == 0 { - ctx.Handle(404, "repo.Branches", nil) - return - } - - ctx.Data["Username"] = params["username"] - ctx.Data["Reponame"] = params["reponame"] - - ctx.Data["Branchname"] = brs[0] - ctx.Data["Branches"] = brs - ctx.Data["IsRepoToolbarBranches"] = true - - ctx.HTML(200, "repo/branches") -} - func Single(ctx *middleware.Context, params martini.Params) { if !ctx.Repo.IsValid { return @@ -276,7 +252,7 @@ func Setting(ctx *middleware.Context, params martini.Params) { ctx.HTML(200, "repo/setting") } -func SettingPost(ctx *middleware.Context, params martini.Params) { +func SettingPost(ctx *middleware.Context) { if !ctx.Repo.IsOwner { ctx.Error(404) return @@ -310,35 +286,6 @@ func SettingPost(ctx *middleware.Context, params martini.Params) { } } -func Commits(ctx *middleware.Context, params martini.Params) { - brs, err := models.GetBranches(params["username"], params["reponame"]) - if err != nil { - ctx.Handle(200, "repo.Commits", err) - return - } else if len(brs) == 0 { - ctx.Handle(404, "repo.Commits", nil) - return - } - - ctx.Data["IsRepoToolbarCommits"] = true - commits, err := models.GetCommits(params["username"], - params["reponame"], params["branchname"]) - if err != nil { - ctx.Handle(404, "repo.Commits", nil) - return - } - ctx.Data["Username"] = params["username"] - ctx.Data["Reponame"] = params["reponame"] - ctx.Data["CommitCount"] = commits.Len() - ctx.Data["Commits"] = commits - ctx.HTML(200, "repo/commits") -} - -func Pulls(ctx *middleware.Context) { - ctx.Data["IsRepoToolbarPulls"] = true - ctx.HTML(200, "repo/pulls") -} - func Action(ctx *middleware.Context, params martini.Params) { var err error switch params["action"] { diff --git a/serve.go b/serve.go index ca79973a6..06815b65d 100644 --- a/serve.go +++ b/serve.go @@ -72,6 +72,7 @@ func runServ(k *cli.Context) { base.NewConfigContext() models.LoadModelsConfig() models.NewEngine() + base.NewLogService() keys := strings.Split(os.Args[2], "-") if len(keys) != 2 { diff --git a/templates/admin/config.tmpl b/templates/admin/config.tmpl index 048740e61..1e2630460 100644 --- a/templates/admin/config.tmpl +++ b/templates/admin/config.tmpl @@ -17,6 +17,7 @@
Run User: {{.RunUser}}
Run Mode: {{.RunMode}}

+
Enable HTTPS Clone
Repository Root Path: {{.RepoRootPath}}
@@ -45,6 +46,7 @@
Register Email Confirmation:
Disenable Registeration:
Require Sign In View:
+
Mail Notification:
Enable Cache Avatar:

Active Code Lives: {{.Service.ActiveCodeLives}} minutes
@@ -103,7 +105,6 @@
Picture Service: {{.PictureService}}
-
Picture Root Path: {{.PictureRootPath}}
diff --git a/templates/repo/diff.tmpl b/templates/repo/diff.tmpl new file mode 100644 index 000000000..b0836127f --- /dev/null +++ b/templates/repo/diff.tmpl @@ -0,0 +1,448 @@ +{{template "base/head" .}} +{{template "base/navbar" .}} +{{template "repo/nav" .}} +{{template "repo/toolbar" .}} +
+
+
+
+ Browse Source +

bsongen: support for custom tags

+
+
+ + commit commit-sha + +

+ + author-name + times-ago +

+
+
+ +
+ Show Diff Files +

+ + 5 changed files with 25 additions and 9 deletions. +

+
    +
  1. +
    + 2 + + + + + 4 +
    + +   + gopmweb.go +
  2. +
  3. +
    + 666 + + + + + 44 +
    +   + static/img/favicon.png +
  4. +
  5. +   + static/img/favicon.png +
  6. +
  7. +   + static/img/favicon.png +
  8. +
+
+ +
+
+
+ BIN + + + + + +
+ View File + data/test/bson_test/simple_type.png +
+
+ + + + +
+
+
+ +
+
+
+ + 30 + + + + + - 4 +
+ View File + data/test/bson_test/simple_type.go +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ 1 + + 1 + +
	"github.com/youtube/vitess/go/bson"
+
+ 2 + + 2 + +
	"github.com/youtube/vitess/go/bson"
+
+ 3 + + 3 + +
	"github.com/youtube/vitess/go/bson"
+
+ + + + 4 + +
	"github.com/youtube/vitess/go/bson"
+
+ + + + 5 + +
	"github.com/youtube/vitess/go/bson"
+
+ 4 + + - + +
	"github.com/youtube/vitess/go/bson"
+
+ 5 + + - + +
	"github.com/youtube/vitess/go/bson"
+
+ 6 + + - + +
	"github.com/youtube/vitess/go/bson"
+
+ 7 + + - + +
	"github.com/youtube/vitess/go/bson"
+
+ 8 + + 6 + +
	"github.com/youtube/vitess/go/bson"
+
+ 9 + + 7 + +
	"github.com/youtube/vitess/go/bson"
+
+ 10 + + 8 + +
	"github.com/youtube/vitess/go/bson"
+
+
+
+ +
+
+
+ + 2 + + + + + - 4 +
+ View File + data/test/bson_test/simple_type.go +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ 1 + + 1 + +
	"github.com/youtube/vitess/go/bson"
+
+ 2 + + 2 + +
	"github.com/youtube/vitess/go/bson"
+
+ 3 + + 3 + +
	"github.com/youtube/vitess/go/bson"
+
+ + + + 4 + +
	"github.com/youtube/vitess/go/bson"
+
+ + + + 5 + +
	"github.com/youtube/vitess/go/bson"
+
+ 4 + + - + +
	"github.com/youtube/vitess/go/bson"
+
+ 5 + + - + +
	"github.com/youtube/vitess/go/bson"
+
+ 6 + + - + +
	"github.com/youtube/vitess/go/bson"
+
+ 7 + + - + +
	"github.com/youtube/vitess/go/bson"
+
+ 8 + + 6 + +
	"github.com/youtube/vitess/go/bson"
+
+ 9 + + 7 + +
	"github.com/youtube/vitess/go/bson"
+
+ 10 + + 8 + +
	"github.com/youtube/vitess/go/bson"
+
+ + +
	"github.com/youtube/vitess/go/bson"
+
+ 10 + + 8 + +
	"github.com/youtube/vitess/go/bson"
+
+ 10 + + 8 + +
	"github.com/youtube/vitess/go/bson"
+
+
+
+ +
+
+
+ BIN + + + + + +
+ View File + data/test/bson_test/simple_type.png +
+
+ + + + +
+
+
+
+
+{{template "base/footer" .}} \ No newline at end of file diff --git a/templates/repo/nav.tmpl b/templates/repo/nav.tmpl index a3358fd89..080cb72e5 100644 --- a/templates/repo/nav.tmpl +++ b/templates/repo/nav.tmpl @@ -53,9 +53,9 @@ -
+ {{end}}
 {{.Repository.NumForks}} diff --git a/templates/repo/single_file.tmpl b/templates/repo/single_file.tmpl index 7bca626aa..40ef44eb1 100644 --- a/templates/repo/single_file.tmpl +++ b/templates/repo/single_file.tmpl @@ -16,12 +16,12 @@ {{.FileContent|str2html}}
{{else}} -
+
- +
{{.FileContent}}
{{.FileContent}}
diff --git a/templates/repo/toolbar.tmpl b/templates/repo/toolbar.tmpl index b51768a3c..415023d17 100644 --- a/templates/repo/toolbar.tmpl +++ b/templates/repo/toolbar.tmpl @@ -6,27 +6,27 @@
  • Source
  • {{if not .IsBareRepo}}
  • Commits
  • -
  • Branches
  • -
  • Pull Requests
  • + +
  • Issues
  • -
    {{template "base/footer" .}} \ No newline at end of file diff --git a/templates/user/dashboard.tmpl b/templates/user/dashboard.tmpl index 72c31d3d8..ca5fecf26 100644 --- a/templates/user/dashboard.tmpl +++ b/templates/user/dashboard.tmpl @@ -5,8 +5,8 @@

    News Feed

    @@ -34,7 +34,7 @@
    diff --git a/templates/user/issues.tmpl b/templates/user/issues.tmpl index 94f668945..e28af5bec 100644 --- a/templates/user/issues.tmpl +++ b/templates/user/issues.tmpl @@ -5,8 +5,8 @@

    Issues

    diff --git a/templates/user/profile.tmpl b/templates/user/profile.tmpl index 2d76d9bf0..342236147 100644 --- a/templates/user/profile.tmpl +++ b/templates/user/profile.tmpl @@ -50,7 +50,7 @@
    \ No newline at end of file diff --git a/web.go b/web.go index 9d90851c9..9717c9384 100644 --- a/web.go +++ b/web.go @@ -17,6 +17,7 @@ import ( "github.com/gogits/gogs/models" "github.com/gogits/gogs/modules/auth" + "github.com/gogits/gogs/modules/avatar" "github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/log" "github.com/gogits/gogs/modules/mailer" @@ -30,9 +31,10 @@ import ( var CmdWeb = cli.Command{ Name: "web", - Usage: "just run", + Usage: "Gogs web server", Description: ` -gogs web`, +gogs web server is the only thing you need to run, +and it takes care of all the other things for you`, Action: runWeb, Flags: []cli.Flag{}, } @@ -87,12 +89,15 @@ func runWeb(*cli.Context) { reqSignOut := middleware.Toggle(&middleware.ToggleOptions{SignOutRequire: true}) // Routers. - m.Get("/", ignSignIn, routers.Home) + m.Get("/", reqSignIn, routers.Home) m.Get("/issues", reqSignIn, user.Issues) m.Get("/pulls", reqSignIn, user.Pulls) m.Get("/stars", reqSignIn, user.Stars) m.Get("/help", routers.Help) + avatarCache := avatar.HttpHandler("public/img/avatar/", "public/img/avatar_default.jpg") + m.Get("/avatar/:hash", avatarCache.ServeHTTP) + m.Group("/user", func(r martini.Router) { r.Any("/login", binding.BindIgnErr(auth.LogInForm{}), user.SignIn) r.Any("/sign_up", binding.BindIgnErr(auth.RegisterForm{}), user.SignUp) @@ -141,7 +146,8 @@ func runWeb(*cli.Context) { r.Get("/commits/:branchname", repo.Commits) r.Get("/issues", repo.Issues) r.Any("/issues/new", binding.BindIgnErr(auth.CreateIssueForm{}), repo.CreateIssue) - r.Get("/issues/:issueid", repo.ViewIssue) + r.Get("/issues/:index", repo.ViewIssue) + r.Post("/issues/:index", binding.BindIgnErr(auth.CreateIssueForm{}), repo.UpdateIssue) r.Get("/pulls", repo.Pulls) r.Get("/branches", repo.Branches) r.Get("/src/:branchname", repo.Single) @@ -151,8 +157,8 @@ func runWeb(*cli.Context) { }, ignSignIn, middleware.RepoAssignment(true)) // TODO: implement single commit page - // m.Get("/:username/:reponame/commit/:commitid/**", ignSignIn, middleware.RepoAssignment(true), repo.Single) - // m.Get("/:username/:reponame/commit/:commitid", ignSignIn, middleware.RepoAssignment(true), repo.Single) + m.Get("/:username/:reponame/commit/:commitid/**", ignSignIn, middleware.RepoAssignment(true), repo.Diff) + m.Get("/:username/:reponame/commit/:commitid", ignSignIn, middleware.RepoAssignment(true), repo.Diff) m.Group("/:username", func(r martini.Router) { r.Get("/:reponame", middleware.RepoAssignment(true), repo.Single)