Merge branch 'master' of github.com:gogits/gogs

Conflicts:
	models/repo.go
	modules/base/tool.go
	serve.go
This commit is contained in:
2014-03-26 14:38:14 +08:00
70 changed files with 1271 additions and 830 deletions
+3 -3
View File
@@ -2,7 +2,7 @@ Gogs(Go Git Service) is a Self Hosted Git Service in the Go Programming Language
![Demo](http://gowalker.org/public/gogs_demo.gif)
##### Current version: 0.1.7 Alpha
##### Current version: 0.1.8 Alpha
#### Other language version
@@ -17,7 +17,7 @@ More importantly, Gogs only needs one binary to setup your own project hosting o
## Overview
- Please see [Wiki](https://github.com/gogits/gogs/wiki) for project design, develop specification, change log and road map.
- See [Trello Broad](https://trello.com/b/uxAoeLUl/gogs-go-git-service) to follow the develop team.
- See [Trello Board](https://trello.com/b/uxAoeLUl/gogs-go-git-service) to follow the develop team.
- Try it before anything? Do it [online](http://try.gogits.org/Unknown/gogs) or go down to **Installation -> Install from binary** section!
- Having troubles? Get help from [Troubleshooting](https://github.com/gogits/gogs/wiki/Troubleshooting).
@@ -29,7 +29,7 @@ More importantly, Gogs only needs one binary to setup your own project hosting o
- Create/delete/watch public repository.
- User profile page.
- Repository viewer.
- Gravatar support.
- Gravatar and cache support.
- Mail service(register).
- Administration panel.
- Supports MySQL, PostgreSQL and SQLite3(binary release only).
+3 -3
View File
@@ -5,7 +5,7 @@ Gogs(Go Git Service) 是一个由 Go 语言编写的自助 Git 托管服务。
![Demo](http://gowalker.org/public/gogs_demo.gif)
##### 当前版本:0.1.7 Alpha
##### 当前版本:0.1.8 Alpha
## 开发目的
@@ -16,7 +16,7 @@ Gogs 完全使用 Go 语言来实现对 Git 数据的操作,实现 **零** 依
## 项目概览
- 有关项目设计、开发说明、变更日志和路线图,请通过 [Wiki](https://github.com/gogits/gogs/wiki) 查看。
- 您可以到 [Trello Broad](https://trello.com/b/uxAoeLUl/gogs-go-git-service) 跟随开发团队的脚步。
- 您可以到 [Trello Board](https://trello.com/b/uxAoeLUl/gogs-go-git-service) 跟随开发团队的脚步。
- 想要先睹为快?通过 [在线体验](http://try.gogits.org/Unknown/gogs) 或查看 **安装部署 -> 二进制安装** 小节。
- 使用过程中遇到问题?尝试从 [故障排查](https://github.com/gogits/gogs/wiki/Troubleshooting) 页面获取帮助。
@@ -28,7 +28,7 @@ Gogs 完全使用 Go 语言来实现对 Git 数据的操作,实现 **零** 依
- 创建/删除/关注公开仓库
- 用户个人信息页面
- 仓库浏览器
- Gravatar 支持
- Gravatar 以及缓存支持
- 邮件服务(注册)
- 管理员面板
- 支持 MySQL、PostgreSQL 以及 SQLite3(仅限二进制版本)
+3 -3
View File
@@ -1,8 +1,8 @@
; App name that shows on every page title
APP_NAME = Gogs: Go Git Service
APP_LOGO = img/favicon.png
; !!MUST CHANGE TO YOUR USER NAME!!
RUN_USER = lunny
; Change it if you run locally
RUN_USER = git
; Either "dev", "prod" or "test", default is "dev"
RUN_MODE = dev
@@ -164,4 +164,4 @@ RECEIVERS =
[log.database]
LEVEL =
Driver =
CONN =
CONN =
+137
View File
@@ -0,0 +1,137 @@
commit c1a3d4fefbbbf332cd1cedda66e93bf40cc9713d
Author: Unknown <joe2010xtmf@163.com>
Date: Tue Mar 25 21:37:18 2014 -0400
Add mail notify for creating issue
diff --git a/gogs.go b/gogs.go
index b62580f..f5a328a 100644
--- a/gogs.go
+++ b/gogs.go
@@ -19,7 +19,7 @@ import (
// Test that go1.2 tag above is included in builds. main.go refers to this definition.
const go12tag = true
-const APP_VER = "0.1.7.0325"
+const APP_VER = "0.1.8.0325"
func init() {
base.AppVer = APP_VER
diff --git a/models/issue.go b/models/issue.go
index 2bdd083..2de6568 100644
--- a/models/issue.go
+++ b/models/issue.go
@@ -59,7 +59,6 @@ func CreateIssue(userId, repoId, milestoneId, assigneeId int64, name, labels, co
Content: content,
}
_, err = orm.Insert(issue)
- // TODO: newIssueAction
return issue, err
}
diff --git a/modules/mailer/mail.go b/modules/mailer/mail.go
index 92acd20..d0decbe 100644
--- a/modules/mailer/mail.go
+++ b/modules/mailer/mail.go
@@ -6,6 +6,7 @@ package mailer
import (
"encoding/hex"
+ "errors"
"fmt"
"github.com/gogits/gogs/models"
@@ -15,12 +16,17 @@ import (
)
// Create New mail message use MailFrom and MailUser
-func NewMailMessage(To []string, subject, body string) Message {
- msg := NewHtmlMessage(To, base.MailService.User, subject, body)
+func NewMailMessageFrom(To []string, from, subject, body string) Message {
+ msg := NewHtmlMessage(To, from, subject, body)
msg.User = base.MailService.User
return msg
}
+// Create New mail message use MailFrom and MailUser
+func NewMailMessage(To []string, subject, body string) Message {
+ return NewMailMessageFrom(To, base.MailService.User, subject, body)
+}
+
func GetMailTmplData(user *models.User) map[interface{}]interface{} {
data := make(map[interface{}]interface{}, 10)
data["AppName"] = base.AppName
@@ -84,3 +90,33 @@ func SendActiveMail(r *middleware.Render, user *models.User) {
SendAsync(&msg)
}
+
+// SendNotifyMail sends mail notification of all watchers.
+func SendNotifyMail(userId, repoId int64, userName, repoName, subject, content string) error {
+ watches, err := models.GetWatches(repoId)
+ if err != nil {
+ return errors.New("mail.NotifyWatchers(get watches): " + err.Error())
+ }
+
+ tos := make([]string, 0, len(watches))
+ for i := range watches {
+ uid := watches[i].UserId
+ if userId == uid {
+ continue
+ }
+ u, err := models.GetUserById(uid)
+ if err != nil {
+ return errors.New("mail.NotifyWatchers(get user): " + err.Error())
+ }
+ tos = append(tos, u.Email)
+ }
+
+ if len(tos) == 0 {
+ return nil
+ }
+
+ msg := NewMailMessageFrom(tos, userName, subject, content)
+ msg.Info = fmt.Sprintf("Subject: %s, send notify emails", subject)
+ SendAsync(&msg)
+ return nil
+}
diff --git a/modules/mailer/mailer.go b/modules/mailer/mailer.go
index da63e01..63861d8 100644
--- a/modules/mailer/mailer.go
+++ b/modules/mailer/mailer.go
@@ -33,7 +33,7 @@ func (m Message) Content() string {
}
// create mail content
- content := "From: " + m.User + "<" + m.From +
+ content := "From: " + m.From + "<" + m.User +
">\r\nSubject: " + m.Subject + "\r\nContent-Type: " + contentType + "\r\n\r\n" + m.Body
return content
}
diff --git a/routers/repo/issue.go b/routers/repo/issue.go
index fc5bb98..242593f 100644
--- a/routers/repo/issue.go
+++ b/routers/repo/issue.go
@@ -13,6 +13,7 @@ import (
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/log"
+ "github.com/gogits/gogs/modules/mailer"
"github.com/gogits/gogs/modules/middleware"
)
@@ -86,6 +87,14 @@ func CreateIssue(ctx *middleware.Context, params martini.Params, form auth.Creat
return
}
+ // Mail watchers.
+ if base.Service.NotifyMail {
+ if err = mailer.SendNotifyMail(ctx.User.Id, ctx.Repo.Repository.Id, ctx.User.Name, ctx.Repo.Repository.Name, issue.Name, issue.Content); err != nil {
+ ctx.Handle(200, "issue.CreateIssue", err)
+ return
+ }
+ }
+
log.Trace("%d Issue created: %d", ctx.Repo.Repository.Id, issue.Id)
ctx.Redirect(fmt.Sprintf("/%s/%s/issues/%d", params["username"], params["reponame"], issue.Index))
}
+1 -16
View File
@@ -7,7 +7,6 @@ package main
import (
"os"
// "os/user"
"runtime"
"github.com/codegangsta/cli"
@@ -20,28 +19,14 @@ 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.7.0324"
const APP_VER = "0.1.8.0325"
func init() {
base.AppVer = APP_VER
runtime.GOMAXPROCS(runtime.NumCPU())
}
// func checkRunUser() bool {
// u, err := user.Current()
// if err != nil {
// // TODO: log
// return false
// }
// return u.Username == base.Cfg.MustValue("", "RUN_USER")
// }
func main() {
/*if !checkRunUser() {
println("The command should be run as", base.Cfg.MustValue("", "RUN_USER"))
return
}*/
app := cli.NewApp()
app.Name = "Gogs"
app.Usage = "Go Git Service"
+6 -27
View File
@@ -19,6 +19,7 @@ const (
OP_STAR_REPO
OP_FOLLOW_REPO
OP_COMMIT_REPO
OP_CREATE_ISSUE
OP_PULL_REQUEST
)
@@ -59,7 +60,7 @@ 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)
log.Trace("action.CommitRepoAction(start): %d/%s", userId, repoName)
bs, err := json.Marshal(commits)
if err != nil {
@@ -67,32 +68,8 @@ func CommitRepoAction(userId int64, userName string,
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})
for i := range watches {
if userId == watches[i].UserId && i > 0 {
continue // Do not add twice in case author watches his/her repository.
}
_, err = orm.InsertOne(&Action{
UserId: watches[i].UserId,
ActUserId: userId,
ActUserName: userName,
OpType: OP_COMMIT_REPO,
Content: string(bs),
RepoId: repoId,
RepoName: repoName,
RefName: refName,
})
if err != nil {
log.Error("action.CommitRepoAction(notify watches): %d/%s", userId, repoName)
}
if err = NotifyWatchers(userId, repoId, OP_COMMIT_REPO, userName, repoName, refName, string(bs)); err != nil {
log.Error("action.CommitRepoAction(notify watchers): %d/%s", userId, repoName)
return err
}
@@ -107,6 +84,8 @@ func CommitRepoAction(userId int64, userName string,
log.Error("action.CommitRepoAction(UpdateRepository): %d/%s", userId, repoName)
return err
}
log.Trace("action.CommitRepoAction(end): %d/%s", userId, repoName)
return nil
}
+274
View File
@@ -0,0 +1,274 @@
// 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
import (
"container/list"
"fmt"
"path"
"strings"
"github.com/Unknwon/com"
"github.com/gogits/git"
)
// RepoFile represents a file object in git repository.
type RepoFile struct {
*git.TreeEntry
Path string
Size int64
Repo *git.Repository
Commit *git.Commit
}
// LookupBlob returns the content of an object.
func (file *RepoFile) LookupBlob() (*git.Blob, error) {
if file.Repo == nil {
return nil, ErrRepoFileNotLoaded
}
return file.Repo.LookupBlob(file.Id)
}
// GetBranches returns all branches of given repository.
func GetBranches(userName, reposName string) ([]string, error) {
repo, err := git.OpenRepository(RepoPath(userName, reposName))
if err != nil {
return nil, err
}
refs, err := repo.AllReferences()
if err != nil {
return nil, err
}
brs := make([]string, len(refs))
for i, ref := range refs {
brs[i] = ref.Name
}
return brs, nil
}
func GetTargetFile(userName, reposName, branchName, commitId, rpath string) (*RepoFile, error) {
repo, err := git.OpenRepository(RepoPath(userName, reposName))
if err != nil {
return nil, err
}
commit, err := repo.GetCommit(branchName, commitId)
if err != nil {
return nil, err
}
parts := strings.Split(path.Clean(rpath), "/")
var entry *git.TreeEntry
tree := commit.Tree
for i, part := range parts {
if i == len(parts)-1 {
entry = tree.EntryByName(part)
if entry == nil {
return nil, ErrRepoFileNotExist
}
} else {
tree, err = repo.SubTree(tree, part)
if err != nil {
return nil, err
}
}
}
size, err := repo.ObjectSize(entry.Id)
if err != nil {
return nil, err
}
repoFile := &RepoFile{
entry,
rpath,
size,
repo,
commit,
}
return repoFile, nil
}
// GetReposFiles returns a list of file object in given directory of repository.
func GetReposFiles(userName, reposName, branchName, commitId, rpath string) ([]*RepoFile, error) {
repo, err := git.OpenRepository(RepoPath(userName, reposName))
if err != nil {
return nil, err
}
commit, err := repo.GetCommit(branchName, commitId)
if err != nil {
return nil, err
}
var repodirs []*RepoFile
var repofiles []*RepoFile
commit.Tree.Walk(func(dirname string, entry *git.TreeEntry) int {
if dirname == rpath {
// TODO: size get method shoule be improved
size, err := repo.ObjectSize(entry.Id)
if err != nil {
return 0
}
var cm = commit
var i int
for {
i = i + 1
//fmt.Println(".....", i, cm.Id(), cm.ParentCount())
if cm.ParentCount() == 0 {
break
} else if cm.ParentCount() == 1 {
pt, _ := repo.SubTree(cm.Parent(0).Tree, dirname)
if pt == nil {
break
}
pEntry := pt.EntryByName(entry.Name)
if pEntry == nil || !pEntry.Id.Equal(entry.Id) {
break
} else {
cm = cm.Parent(0)
}
} else {
var emptyCnt = 0
var sameIdcnt = 0
var lastSameCm *git.Commit
//fmt.Println(".....", cm.ParentCount())
for i := 0; i < cm.ParentCount(); i++ {
//fmt.Println("parent", i, cm.Parent(i).Id())
p := cm.Parent(i)
pt, _ := repo.SubTree(p.Tree, dirname)
var pEntry *git.TreeEntry
if pt != nil {
pEntry = pt.EntryByName(entry.Name)
}
//fmt.Println("pEntry", pEntry)
if pEntry == nil {
emptyCnt = emptyCnt + 1
if emptyCnt+sameIdcnt == cm.ParentCount() {
if lastSameCm == nil {
goto loop
} else {
cm = lastSameCm
break
}
}
} else {
//fmt.Println(i, "pEntry", pEntry.Id, "entry", entry.Id)
if !pEntry.Id.Equal(entry.Id) {
goto loop
} else {
lastSameCm = cm.Parent(i)
sameIdcnt = sameIdcnt + 1
if emptyCnt+sameIdcnt == cm.ParentCount() {
// TODO: now follow the first parent commit?
cm = lastSameCm
//fmt.Println("sameId...")
break
}
}
}
}
}
}
loop:
rp := &RepoFile{
entry,
path.Join(dirname, entry.Name),
size,
repo,
cm,
}
if entry.IsFile() {
repofiles = append(repofiles, rp)
} else if entry.IsDir() {
repodirs = append(repodirs, rp)
}
}
return 0
})
return append(repodirs, repofiles...), nil
}
func GetCommit(userName, repoName, branchname, commitid string) (*git.Commit, error) {
repo, err := git.OpenRepository(RepoPath(userName, repoName))
if err != nil {
return nil, err
}
return repo.GetCommit(branchname, commitid)
}
// GetCommits returns all commits of given branch of repository.
func GetCommits(userName, reposName, branchname string) (*list.List, error) {
repo, err := git.OpenRepository(RepoPath(userName, reposName))
if err != nil {
return nil, err
}
r, err := repo.LookupReference(fmt.Sprintf("refs/heads/%s", branchname))
if err != nil {
return nil, err
}
return r.AllCommits()
}
type DiffFile struct {
Name string
Addition, Deletion int
Type string
Content []string
}
type Diff struct {
NumFiles int // Number of file has been changed.
TotalAddition, TotalDeletion int
Files []*DiffFile
}
func GetDiff(repoPath, commitid string) (*Diff, error) {
stdout, _, err := com.ExecCmdDir(repoPath, "git", "show", commitid)
if err != nil {
return nil, err
}
// Sperate parts by file.
startIndex := strings.Index(stdout, "diff --git ") + 12
// First part is commit information.
// Check if it's a merge.
mergeIndex := strings.Index(stdout[:startIndex], "merge")
if mergeIndex > -1 {
mergeCommit := strings.SplitN(strings.Split(stdout[:startIndex], "\n")[1], "", 3)[2]
return GetDiff(repoPath, mergeCommit)
}
parts := strings.Split(stdout[startIndex:], "diff --git ")
diff := &Diff{NumFiles: len(parts)}
diff.Files = make([]*DiffFile, 0, diff.NumFiles)
for _, part := range parts {
infos := strings.SplitN(part, "\n", 6)
maxIndex := len(infos) - 1
infos[maxIndex] = strings.TrimSuffix(strings.TrimSuffix(infos[maxIndex], "\n"), "\n\\ No newline at end of file")
file := &DiffFile{
Name: strings.TrimPrefix(strings.Split(infos[0], " ")[0], "a/"),
Content: strings.Split(infos[maxIndex], "\n"),
}
diff.Files = append(diff.Files, file)
}
return diff, nil
}
+1 -1
View File
@@ -23,6 +23,7 @@ type Issue struct {
Name string
RepoId int64 `xorm:"index"`
PosterId int64
Poster *User `xorm:"-"`
MilestoneId int64
AssigneeId int64
IsPull bool // Indicates whether is a pull request or not.
@@ -58,7 +59,6 @@ func CreateIssue(userId, repoId, milestoneId, assigneeId int64, name, labels, co
Content: content,
}
_, err = orm.Insert(issue)
// TODO: newIssueAction
return issue, err
}
+38 -263
View File
File diff suppressed because it is too large Load Diff
+3 -6
View File
@@ -17,9 +17,8 @@ import (
)
type CreateIssueForm struct {
IssueName string `form:"name" binding:"Required;MaxSize(50)"`
RepoId int64 `form:"repoid" binding:"Required"`
MilestoneId int64 `form:"milestoneid" binding:"Required"`
IssueName string `form:"title" binding:"Required;MaxSize(50)"`
MilestoneId int64 `form:"milestoneid"`
AssigneeId int64 `form:"assigneeid"`
Labels string `form:"labels"`
Content string `form:"content"`
@@ -27,9 +26,7 @@ type CreateIssueForm struct {
func (f *CreateIssueForm) Name(field string) string {
names := map[string]string{
"IssueName": "Issue name",
"RepoId": "Repository ID",
"MilestoneId": "Milestone ID",
"IssueName": "Issue name",
}
return names[field]
}
+4 -3
View File
@@ -30,8 +30,9 @@ import (
"sync"
"time"
"github.com/gogits/gogs/modules/log"
"github.com/nfnt/resize"
"github.com/gogits/gogs/modules/log"
)
var (
@@ -251,8 +252,8 @@ 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", "text/html,application/xhtml+xml,application/xml;q=0.9,image/jpeg,image/png,*/*;q=0.8")
req.Header.Set("Accept-Encoding", "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")
+16 -12
View File
@@ -71,7 +71,7 @@ var Service struct {
ResetPwdCodeLives int
}
func exeDir() (string, error) {
func ExecDir() (string, error) {
file, err := exec.LookPath(os.Args[0])
if err != nil {
return "", err
@@ -244,7 +244,7 @@ func newNotifyMailService() {
func NewConfigContext() {
//var err error
workDir, err := exeDir()
workDir, err := ExecDir()
if err != nil {
fmt.Printf("Fail to get work directory: %s\n", err)
os.Exit(2)
@@ -259,16 +259,11 @@ func NewConfigContext() {
Cfg.BlockMode = false
cfgPath = filepath.Join(workDir, "custom/conf/app.ini")
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)
if com.IsFile(cfgPath) {
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")
@@ -276,7 +271,16 @@ func NewConfigContext() {
AppUrl = Cfg.MustValue("server", "ROOT_URL")
Domain = Cfg.MustValue("server", "DOMAIN")
SecretKey = Cfg.MustValue("security", "SECRET_KEY")
RunUser = Cfg.MustValue("", "RUN_USER")
curUser := os.Getenv("USERNAME")
if len(curUser) == 0 {
curUser = os.Getenv("USER")
}
if RunUser != curUser {
fmt.Printf("Expect user(%s) but current user is: %s\n", RunUser, curUser)
os.Exit(2)
}
EnableHttpsClone = Cfg.MustBool("security", "ENABLE_HTTPS_CLONE", false)
+19 -7
View File
@@ -102,7 +102,10 @@ func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string
// AvatarLink returns avatar link by given e-mail.
func AvatarLink(email string) string {
return "/avatar/" + EncodeMd5(email)
if Service.EnableCacheAvatar {
return "/avatar/" + EncodeMd5(email)
}
return "http://1.gravatar.com/avatar/" + EncodeMd5(email)
}
// Seconds-based time units
@@ -483,15 +486,19 @@ func ActionIcon(opType int) string {
return "plus-circle"
case 5: // Commit repository.
return "arrow-circle-o-right"
case 6: // Create issue.
return "exclamation-circle"
default:
return "invalid type"
}
}
const (
TPL_CREATE_REPO = `<a href="/user/%s">%s</a> created repository <a href="/%s/%s">%s</a>`
TPL_COMMIT_REPO = `<a href="/user/%s">%s</a> pushed to <a href="/%s/%s/src/%s">%s</a> at <a href="/%s/%s">%s/%s</a>%s`
TPL_COMMIT_REPO_LI = `<div><img id="gogs-user-avatar-commit" src="%s?s=16" alt="user-avatar" title="username"/> <a href="/%s/%s/commit/%s">%s</a> %s</div>`
TPL_CREATE_REPO = `<a href="/user/%s">%s</a> created repository <a href="/%s">%s</a>`
TPL_COMMIT_REPO = `<a href="/user/%s">%s</a> pushed to <a href="/%s/src/%s">%s</a> at <a href="/%s">%s</a>%s`
TPL_COMMIT_REPO_LI = `<div><img src="%s?s=16" alt="user-avatar"/> <a href="/%s/commit/%s">%s</a> %s</div>`
TPL_CREATE_Issue = `<a href="/user/%s">%s</a> opened issue <a href="/%s/issues/%s">%s#%s</a>
<div><img src="%s?s=16" alt="user-avatar"/> %s</div>`
)
type PushCommits struct {
@@ -504,11 +511,12 @@ type PushCommits struct {
func ActionDesc(act Actioner, avatarLink string) string {
actUserName := act.GetActUserName()
repoName := act.GetRepoName()
repoLink := actUserName + "/" + repoName
branch := act.GetBranch()
content := act.GetContent()
switch act.GetOpType() {
case 1: // Create repository.
return fmt.Sprintf(TPL_CREATE_REPO, actUserName, actUserName, actUserName, repoName, repoName)
return fmt.Sprintf(TPL_CREATE_REPO, actUserName, actUserName, repoLink, repoName)
case 5: // Commit repository.
var push *PushCommits
if err := json.Unmarshal([]byte(content), &push); err != nil {
@@ -516,13 +524,17 @@ func ActionDesc(act Actioner, avatarLink string) string {
}
buf := bytes.NewBuffer([]byte("\n"))
for _, commit := range push.Commits {
buf.WriteString(fmt.Sprintf(TPL_COMMIT_REPO_LI, avatarLink, actUserName, repoName, commit[0], commit[0][:7], commit[1]) + "\n")
buf.WriteString(fmt.Sprintf(TPL_COMMIT_REPO_LI, avatarLink, repoLink, commit[0], commit[0][:7], commit[1]) + "\n")
}
if push.Len > 3 {
buf.WriteString(fmt.Sprintf(`<div><a href="/%s/%s/commits/%s">%d other commits >></a></div>`, actUserName, repoName, branch, push.Len))
}
return fmt.Sprintf(TPL_COMMIT_REPO, actUserName, actUserName, actUserName, repoName, branch, branch, actUserName, repoName, actUserName, repoName,
return fmt.Sprintf(TPL_COMMIT_REPO, actUserName, actUserName, repoLink, branch, branch, repoLink, repoLink,
buf.String())
case 6: // Create issue.
infos := strings.SplitN(content, "|", 2)
return fmt.Sprintf(TPL_CREATE_Issue, actUserName, actUserName, repoLink, infos[0], repoLink, infos[0],
avatarLink, infos[1])
default:
return "invalid type"
}
+5 -1
View File
@@ -9,7 +9,10 @@ import (
"github.com/gogits/logs"
)
var logger *logs.BeeLogger
var (
logger *logs.BeeLogger
Mode, Config string
)
func init() {
logger = logs.NewLogger(10000)
@@ -17,6 +20,7 @@ func init() {
}
func NewLogger(bufLen int64, mode, config string) {
Mode, Config = mode, config
logger = logs.NewLogger(bufLen)
logger.SetLogger(mode, config)
}
+38 -2
View File
@@ -6,6 +6,7 @@ package mailer
import (
"encoding/hex"
"errors"
"fmt"
"github.com/gogits/gogs/models"
@@ -15,12 +16,17 @@ import (
)
// Create New mail message use MailFrom and MailUser
func NewMailMessage(To []string, subject, body string) Message {
msg := NewHtmlMessage(To, base.MailService.User, subject, body)
func NewMailMessageFrom(To []string, from, subject, body string) Message {
msg := NewHtmlMessage(To, from, subject, body)
msg.User = base.MailService.User
return msg
}
// Create New mail message use MailFrom and MailUser
func NewMailMessage(To []string, subject, body string) Message {
return NewMailMessageFrom(To, base.MailService.User, subject, body)
}
func GetMailTmplData(user *models.User) map[interface{}]interface{} {
data := make(map[interface{}]interface{}, 10)
data["AppName"] = base.AppName
@@ -84,3 +90,33 @@ func SendActiveMail(r *middleware.Render, user *models.User) {
SendAsync(&msg)
}
// SendNotifyMail sends mail notification of all watchers.
func SendNotifyMail(userId, repoId int64, userName, repoName, subject, content string) error {
watches, err := models.GetWatches(repoId)
if err != nil {
return errors.New("mail.NotifyWatchers(get watches): " + err.Error())
}
tos := make([]string, 0, len(watches))
for i := range watches {
uid := watches[i].UserId
if userId == uid {
continue
}
u, err := models.GetUserById(uid)
if err != nil {
return errors.New("mail.NotifyWatchers(get user): " + err.Error())
}
tos = append(tos, u.Email)
}
if len(tos) == 0 {
return nil
}
msg := NewMailMessageFrom(tos, userName, subject, content)
msg.Info = fmt.Sprintf("Subject: %s, send notify emails", subject)
SendAsync(&msg)
return nil
}
+1 -1
View File
@@ -33,7 +33,7 @@ func (m Message) Content() string {
}
// create mail content
content := "From: " + m.User + "<" + m.From +
content := "From: " + m.From + "<" + m.User +
">\r\nSubject: " + m.Subject + "\r\nContent-Type: " + contentType + "\r\n\r\n" + m.Body
return content
}
+6 -1
View File
@@ -73,9 +73,14 @@ func RepoAssignment(redirect bool) martini.Handler {
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.SSH = fmt.Sprintf("%s@%s:%s/%s.git", base.RunUser, base.Domain, user.LowerName, repo.LowerName)
ctx.Repo.CloneLink.HTTPS = fmt.Sprintf("%s://%s/%s/%s.git", scheme, base.Domain, user.LowerName, repo.LowerName)
if len(params["branchname"]) == 0 {
params["branchname"] = "master"
}
ctx.Data["Branchname"] = params["branchname"]
ctx.Data["IsRepositoryValid"] = true
ctx.Data["Repository"] = repo
ctx.Data["Owner"] = user
+208 -100
View File
File diff suppressed because it is too large Load Diff
+6 -5
View File
@@ -111,6 +111,7 @@ var Gogits = {
};
Gogits.initTabs = function () {
var $tabs = $('[data-init=tabs]');
$tabs.tab("show");
$tabs.find("li:eq(0) a").tab("show");
};
// fix dropdown inside click
@@ -243,7 +244,7 @@ function initCore() {
function initRegister() {
$.getScript("/js/jquery.validate.min.js", function () {
Gogits.validateForm("#gogs-login-card", {
Gogits.validateForm("#login-card", {
rules: {
"username": {
required: true,
@@ -268,7 +269,7 @@ function initRegister() {
}
function initUserSetting() {
$('#gogs-ssh-keys .delete').confirmation({
$('#ssh-keys .delete').confirmation({
singleton: true,
onConfirm: function (e, $this) {
Gogits.ajaxDelete("", {"id": $this.data("del")}, function (json) {
@@ -303,7 +304,7 @@ function initRepository() {
// watching script
(function () {
var $watch = $('#gogs-repo-watching'),
var $watch = $('#repo-watching'),
watchLink = $watch.data("watch"),
unwatchLink = $watch.data("unwatch");
$watch.on('click', '.to-watch',function () {
@@ -354,14 +355,14 @@ function initRepository() {
(function ($) {
$(function () {
initCore();
var body = $("#gogs-body");
var body = $("#body");
if (body.data("page") == "user-signup") {
initRegister();
}
if (body.data("page") == "user") {
initUserSetting();
}
if ($('.gogs-repo-nav').length) {
if ($('.repo-nav').length) {
initRepository();
}
});
-5
View File
@@ -26,11 +26,6 @@ func Branches(ctx *middleware.Context, params martini.Params) {
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
+19 -3
View File
@@ -34,8 +34,24 @@ func Commits(ctx *middleware.Context, params martini.Params) {
ctx.HTML(200, "repo/commits")
}
func Diff(ctx *middleware.Context,params martini.Params){
ctx.Data["Title"] = "commit-sha"
func Diff(ctx *middleware.Context, params martini.Params) {
commit, err := models.GetCommit(params["username"], params["reponame"], params["branchname"], params["commitid"])
if err != nil {
ctx.Handle(404, "repo.Diff", err)
return
}
diff, err := models.GetDiff(models.RepoPath(params["username"], params["reponame"]), params["commitid"])
if err != nil {
ctx.Handle(404, "repo.Diff", err)
return
}
shortSha := params["commitid"][:7]
ctx.Data["Title"] = commit.Message() + " · " + shortSha
ctx.Data["Commit"] = commit
ctx.Data["ShortSha"] = shortSha
ctx.Data["Diff"] = diff
ctx.Data["IsRepoToolbarCommits"] = true
ctx.HTML(200,"repo/diff")
ctx.HTML(200, "repo/diff")
}
+43 -11
View File
@@ -13,6 +13,7 @@ import (
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/mailer"
"github.com/gogits/gogs/modules/middleware"
)
@@ -23,19 +24,34 @@ func Issues(ctx *middleware.Context, params martini.Params) {
milestoneId, _ := base.StrTo(params["milestone"]).Int()
page, _ := base.StrTo(params["page"]).Int()
var err error
ctx.Data["Issues"], err = models.GetIssues(0, ctx.Repo.Repository.Id, 0,
// Get issues.
issues, err := models.GetIssues(0, ctx.Repo.Repository.Id, 0,
int64(milestoneId), page, params["state"] == "closed", false, params["labels"], params["sortType"])
if err != nil {
ctx.Handle(200, "issue.Issues: %v", err)
return
}
if len(params["branchname"]) == 0 {
params["branchname"] = "master"
var closedCount int
// Get posters.
for i := range issues {
u, err := models.GetUserById(issues[i].PosterId)
if err != nil {
ctx.Handle(200, "issue.Issues(get poster): %v", err)
return
}
if issues[i].IsClosed {
closedCount++
}
issues[i].Poster = u
}
ctx.Data["Branchname"] = params["branchname"]
ctx.HTML(200, "repo/issues")
ctx.Data["Issues"] = issues
ctx.Data["IssueCount"] = len(issues)
ctx.Data["OpenCount"] = len(issues) - closedCount
ctx.Data["ClosedCount"] = closedCount
ctx.HTML(200, "issue/list")
}
func CreateIssue(ctx *middleware.Context, params martini.Params, form auth.CreateIssueForm) {
@@ -57,14 +73,30 @@ func CreateIssue(ctx *middleware.Context, params martini.Params, form auth.Creat
return
}
issue, err := models.CreateIssue(ctx.User.Id, form.RepoId, form.MilestoneId, form.AssigneeId,
issue, err := models.CreateIssue(ctx.User.Id, ctx.Repo.Repository.Id, form.MilestoneId, form.AssigneeId,
form.IssueName, form.Labels, form.Content, false)
if err == nil {
log.Trace("%s Issue created: %d", form.RepoId, issue.Id)
ctx.Redirect(fmt.Sprintf("/%s/%s/issues/%d", params["username"], params["reponame"], issue.Index))
if err != nil {
ctx.Handle(200, "issue.CreateIssue", err)
return
}
ctx.Handle(200, "issue.CreateIssue", err)
// Notify watchers.
if err = models.NotifyWatchers(ctx.User.Id, ctx.Repo.Repository.Id, models.OP_CREATE_ISSUE,
ctx.User.Name, ctx.Repo.Repository.Name, "", fmt.Sprintf("%d|%s", issue.Index, issue.Name)); err != nil {
ctx.Handle(200, "issue.CreateIssue", err)
return
}
// Mail watchers.
if base.Service.NotifyMail {
if err = mailer.SendNotifyMail(ctx.User.Id, ctx.Repo.Repository.Id, ctx.User.Name, ctx.Repo.Repository.Name, issue.Name, issue.Content); err != nil {
ctx.Handle(200, "issue.CreateIssue", err)
return
}
}
log.Trace("%d Issue created: %d", ctx.Repo.Repository.Id, issue.Id)
ctx.Redirect(fmt.Sprintf("/%s/%s/issues/%d", params["username"], params["reponame"], issue.Index))
}
func ViewIssue(ctx *middleware.Context, params martini.Params) {
-5
View File
@@ -12,10 +12,5 @@ import (
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")
}
-14
View File
@@ -57,10 +57,6 @@ func Single(ctx *middleware.Context, params martini.Params) {
return
}
if len(params["branchname"]) == 0 {
params["branchname"] = "master"
}
// Get tree path
treename := params["_1"]
@@ -177,7 +173,6 @@ func Single(ctx *middleware.Context, params martini.Params) {
ctx.Data["Username"] = params["username"]
ctx.Data["Reponame"] = params["reponame"]
ctx.Data["Branchname"] = params["branchname"]
var treenames []string
Paths := make([]string, 0)
@@ -216,10 +211,6 @@ func SingleDownload(ctx *middleware.Context, params martini.Params) {
return
}
if len(params["branchname"]) == 0 {
params["branchname"] = "master"
}
// Get tree path
treename := params["_1"]
@@ -290,11 +281,6 @@ func Setting(ctx *middleware.Context, params martini.Params) {
title = t
}
if len(params["branchname"]) == 0 {
params["branchname"] = "master"
}
ctx.Data["Branchname"] = params["branchname"]
ctx.Data["Title"] = title + " - settings"
ctx.HTML(200, "repo/setting")
}
+2 -1
View File
@@ -285,7 +285,8 @@ func Feeds(ctx *middleware.Context, form auth.FeedsForm) {
}
func Issues(ctx *middleware.Context) {
ctx.HTML(200, "user/issues")
ctx.Data["Title"] = "Your Issues"
ctx.HTML(200, "issue/user")
}
func Pulls(ctx *middleware.Context) {
+22 -8
View File
@@ -9,6 +9,7 @@ import (
"fmt"
"os"
"os/exec"
"path"
"strconv"
"strings"
@@ -42,11 +43,12 @@ gogs serv provide access auth for repositories`,
Flags: []cli.Flag{},
}
func init() {
func newLogger(execDir string) {
level := "0"
os.MkdirAll("log", os.ModePerm)
log.NewLogger(10000, "file", fmt.Sprintf(`{"level":%s,"filename":"%s"}`, level, "log/serv.log"))
log.Info("start logging...")
logPath := execDir + "/log/serv.log"
os.MkdirAll(path.Dir(logPath), os.ModePerm)
log.NewLogger(10000, "file", fmt.Sprintf(`{"level":%s,"filename":"%s"}`, level, logPath))
log.Trace("start logging...")
}
func parseCmd(cmd string) (string, string) {
@@ -70,6 +72,10 @@ func In(b string, sl map[string]int) bool {
}
func runServ(k *cli.Context) {
execDir, _ := base.ExecDir()
newLogger(execDir)
log.Trace("new serv request " + log.Mode + ":" + log.Config)
base.NewConfigContext()
models.LoadModelsConfig()
models.NewEngine()
@@ -77,17 +83,20 @@ func runServ(k *cli.Context) {
keys := strings.Split(os.Args[2], "-")
if len(keys) != 2 {
fmt.Println("auth file format error")
log.Error("auth file format error")
return
}
keyId, err := strconv.ParseInt(keys[1], 10, 64)
if err != nil {
fmt.Println("auth file format error")
log.Error("auth file format error")
return
}
user, err := models.GetUserByKeyId(keyId)
if err != nil {
fmt.Println("You have no right to access")
log.Error("You have no right to access")
return
}
@@ -102,6 +111,7 @@ func runServ(k *cli.Context) {
rr := strings.SplitN(rRepo, "/", 2)
if len(rr) != 2 {
println("Unavilable repository", args)
log.Error("Unavilable repository %v", args)
return
}
repoName := rr[1]
@@ -112,21 +122,22 @@ func runServ(k *cli.Context) {
isWrite := In(verb, COMMANDS_WRITE)
isRead := In(verb, COMMANDS_READONLY)
//repo, err := models.GetRepositoryByName(user.Id, repoName)
/*//repo, err := models.GetRepositoryByName(user.Id, repoName)
//var isExist bool = true
if err != nil {
if err == models.ErrRepoNotExist {
//isExist = false
if isRead {
println("Repository", user.Name+"/"+repoName, "is not exist")
log.Error("Repository " + user.Name + "/" + repoName + " is not exist")
return
}
} else {
println("Get repository error:", err)
log.Error(err.Error())
log.Error("Get repository error: " + err.Error())
return
}
}
}*/
// access check
switch {
@@ -139,6 +150,7 @@ func runServ(k *cli.Context) {
}
if !has {
println("You have no right to write this repository")
log.Error("You have no right to access this repository")
return
}
case isRead:
@@ -158,10 +170,12 @@ func runServ(k *cli.Context) {
}
if !has {
println("You have no right to access this repository")
log.Error("You have no right to access this repository")
return
}
default:
println("Unknown command")
log.Error("Unknown command")
return
}
@@ -178,7 +192,7 @@ func runServ(k *cli.Context) {
if err = gitcmd.Run(); err != nil {
println("execute command error:", err.Error())
log.Error(err.Error())
log.Error("execute command error: " + err.Error())
return
}
}
+2 -2
View File
@@ -1,8 +1,8 @@
{{template "base/head" .}}
{{template "base/navbar" .}}
<div id="gogs-body" class="container" data-page="admin">
<div id="body" class="container" data-page="admin">
{{template "admin/nav" .}}
<div id="gogs-admin-container" class="col-md-9">
<div id="admin-container" class="col-md-9">
<div class="panel panel-default">
<div class="panel-heading">
Server Configuration
+2 -2
View File
@@ -1,8 +1,8 @@
{{template "base/head" .}}
{{template "base/navbar" .}}
<div id="gogs-body" class="container" data-page="admin">
<div id="body" class="container" data-page="admin">
{{template "admin/nav" .}}
<div id="gogs-admin-container" class="col-md-9">
<div id="admin-container" class="col-md-9">
<div class="panel panel-default">
<div class="panel-heading">
Statistic
+2 -2
View File
@@ -1,5 +1,5 @@
<div id="gogs-user-setting-nav" class="col-md-3 gogs-admin-nav">
<ul class="list-group" data-init="tabs">
<div id="user-setting-nav" class="col-md-3 admin-nav">
<ul class="list-group">
<li class="list-group-item{{if .PageIsDashboard}} active{{end}}"><a href="/admin"><i class="fa fa-tachometer fa-lg"></i> Dashboard</a></li>
<li class="list-group-item{{if .PageIsUsers}} active{{end}}"><a href="/admin/users"><i class="fa fa-users fa-lg"></i> Users</a></li>
<li class="list-group-item{{if .PageIsRepos}} active{{end}}"><a href="/admin/repos"><i class="fa fa-book fa-lg"></i> Repositories</a></li>
+2 -2
View File
@@ -1,8 +1,8 @@
{{template "base/head" .}}
{{template "base/navbar" .}}
<div id="gogs-body" class="container" data-page="admin">
<div id="body" class="container" data-page="admin">
{{template "admin/nav" .}}
<div id="gogs-admin-container" class="col-md-9">
<div id="admin-container" class="col-md-9">
<div class="panel panel-default">
<div class="panel-heading">
Repository Management

Some files were not shown because too many files have changed in this diff Show More