Skip to content

Commit e573855

Browse files
committed
Fix #98, support web hook
1 parent 94bccbb commit e573855

File tree

13 files changed

+581
-23
lines changed

13 files changed

+581
-23
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ Gogs(Go Git Service) is a Self Hosted Git Service in the Go Programming Language
55

66
![Demo](http://gowalker.org/public/gogs_demo.gif)
77

8-
##### Current version: 0.3.2 Alpha
8+
##### Current version: 0.3.3 Alpha
99

1010
### NOTICES
1111

@@ -35,7 +35,7 @@ More importantly, Gogs only needs one binary to setup your own project hosting o
3535
- SSH/HTTP(S) protocol support.
3636
- Register/delete/rename account.
3737
- Create/migrate/mirror/delete/watch/rename/transfer public/private repository.
38-
- Repository viewer/release/issue tracker.
38+
- Repository viewer/release/issue tracker/webhooks.
3939
- Add/remove repository collaborators.
4040
- Gravatar and cache support.
4141
- Mail service(register, issue).

README_ZH.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ Gogs(Go Git Service) 是一个由 Go 语言编写的自助 Git 托管服务。
55

66
![Demo](http://gowalker.org/public/gogs_demo.gif)
77

8-
##### 当前版本:0.3.2 Alpha
8+
##### 当前版本:0.3.3 Alpha
99

1010
## 开发目的
1111

@@ -26,7 +26,7 @@ Gogs 完全使用 Go 语言来实现对 Git 数据的操作,实现 **零** 依
2626
- SSH/HTTP(S) 协议支持
2727
- 注册/删除/重命名用户
2828
- 创建/迁移/镜像/删除/关注/重命名/转移 公开/私有 仓库
29-
- 仓库 浏览器/发布/缺陷追踪
29+
- 仓库 浏览器/发布/缺陷管理/Web 钩子
3030
- 添加/删除 仓库协作者
3131
- Gravatar 以及缓存支持
3232
- 邮件服务(注册、Issue)

gogs.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import (
2020
// Test that go1.2 tag above is included in builds. main.go refers to this definition.
2121
const go12tag = true
2222

23-
const APP_VER = "0.3.2.0505 Alpha"
23+
const APP_VER = "0.3.3.0506 Alpha"
2424

2525
func init() {
2626
base.AppVer = APP_VER

models/action.go

Lines changed: 50 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,16 @@ package models
66

77
import (
88
"encoding/json"
9+
"errors"
10+
"fmt"
911
"strings"
1012
"time"
1113

1214
"github.com/gogits/git"
1315
qlog "github.com/qiniu/log"
1416

1517
"github.com/gogits/gogs/modules/base"
18+
"github.com/gogits/gogs/modules/hooks"
1619
"github.com/gogits/gogs/modules/log"
1720
)
1821

@@ -73,45 +76,80 @@ func (a Action) GetContent() string {
7376

7477
// CommitRepoAction adds new action for committing repository.
7578
func CommitRepoAction(userId, repoUserId int64, userName, actEmail string,
76-
repoId int64, repoUserName, repoName string, refName string, commit *base.PushCommits) error {
79+
repoId int64, repoUserName, repoName string, refFullName string, commit *base.PushCommits) error {
7780
// log.Trace("action.CommitRepoAction(start): %d/%s", userId, repoName)
7881

7982
opType := OP_COMMIT_REPO
8083
// Check it's tag push or branch.
81-
if strings.HasPrefix(refName, "refs/tags/") {
84+
if strings.HasPrefix(refFullName, "refs/tags/") {
8285
opType = OP_PUSH_TAG
8386
commit = &base.PushCommits{}
8487
}
8588

86-
refName = git.RefEndName(refName)
89+
refName := git.RefEndName(refFullName)
8790

8891
bs, err := json.Marshal(commit)
8992
if err != nil {
90-
qlog.Error("action.CommitRepoAction(json): %d/%s", repoUserId, repoName)
91-
return err
93+
return errors.New("action.CommitRepoAction(json): " + err.Error())
9294
}
9395

9496
// Change repository bare status and update last updated time.
9597
repo, err := GetRepositoryByName(repoUserId, repoName)
9698
if err != nil {
97-
qlog.Error("action.CommitRepoAction(GetRepositoryByName): %d/%s", repoUserId, repoName)
98-
return err
99+
return errors.New("action.CommitRepoAction(GetRepositoryByName): " + err.Error())
99100
}
100101
repo.IsBare = false
101102
if err = UpdateRepository(repo); err != nil {
102-
qlog.Error("action.CommitRepoAction(UpdateRepository): %d/%s", repoUserId, repoName)
103-
return err
103+
return errors.New("action.CommitRepoAction(UpdateRepository): " + err.Error())
104104
}
105105

106106
if err = NotifyWatchers(&Action{ActUserId: userId, ActUserName: userName, ActEmail: actEmail,
107107
OpType: opType, Content: string(bs), RepoId: repoId, RepoUserName: repoUserName,
108108
RepoName: repoName, RefName: refName,
109109
IsPrivate: repo.IsPrivate}); err != nil {
110-
qlog.Error("action.CommitRepoAction(notify watchers): %d/%s", userId, repoName)
111-
return err
112-
}
110+
return errors.New("action.CommitRepoAction(NotifyWatchers): " + err.Error())
113111

112+
}
114113
qlog.Info("action.CommitRepoAction(end): %d/%s", repoUserId, repoName)
114+
115+
// New push event hook.
116+
ws, err := GetActiveWebhooksByRepoId(repoId)
117+
if err != nil {
118+
return errors.New("action.CommitRepoAction(GetWebhooksByRepoId): " + err.Error())
119+
} else if len(ws) == 0 {
120+
return nil
121+
}
122+
123+
commits := make([]*hooks.PayloadCommit, len(commit.Commits))
124+
for i, cmt := range commit.Commits {
125+
commits[i] = &hooks.PayloadCommit{
126+
Id: cmt.Sha1,
127+
Message: cmt.Message,
128+
Url: fmt.Sprintf("%s%s/%s/commit/%s", base.AppUrl, repoUserName, repoName, cmt.Sha1),
129+
Author: &hooks.PayloadAuthor{
130+
Name: cmt.AuthorName,
131+
Email: cmt.AuthorEmail,
132+
},
133+
}
134+
}
135+
p := &hooks.Payload{
136+
Ref: refFullName,
137+
Commits: commits,
138+
Pusher: &hooks.PayloadAuthor{
139+
Name: userName,
140+
Email: actEmail,
141+
},
142+
}
143+
144+
for _, w := range ws {
145+
w.GetEvent()
146+
if !w.HasPushEvent() {
147+
continue
148+
}
149+
150+
p.Secret = w.Secret
151+
hooks.AddHookTask(&hooks.HookTask{hooks.HTT_WEBHOOK, w.Url, p, w.ContentType, w.IsSsl})
152+
}
115153
return nil
116154
}
117155

models/update.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,6 @@ func Update(refName, oldCommitId, newCommitId, userName, repoUserName, repoName
9696
//commits = append(commits, []string{lastCommit.Id().String(), lastCommit.Message()})
9797
if err = CommitRepoAction(userId, ru.Id, userName, actEmail,
9898
repos.Id, repoUserName, repoName, refName, &base.PushCommits{l.Len(), commits}); err != nil {
99-
qlog.Fatalf("runUpdate.models.CommitRepoAction: %v", err)
99+
qlog.Fatalf("runUpdate.models.CommitRepoAction: %s/%s:%v", repoUserName, repoName, err)
100100
}
101101
}

models/webhook.go

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ type HookEvent struct {
2828
type Webhook struct {
2929
Id int64
3030
RepoId int64
31-
Payload string `xorm:"TEXT"`
31+
Url string `xorm:"TEXT"`
3232
ContentType int
3333
Secret string `xorm:"TEXT"`
3434
Events string `xorm:"TEXT"`
@@ -50,6 +50,13 @@ func (w *Webhook) SaveEvent() error {
5050
return err
5151
}
5252

53+
func (w *Webhook) HasPushEvent() bool {
54+
if w.PushOnly {
55+
return true
56+
}
57+
return false
58+
}
59+
5360
// CreateWebhook creates new webhook.
5461
func CreateWebhook(w *Webhook) error {
5562
_, err := orm.Insert(w)
@@ -74,6 +81,12 @@ func GetWebhookById(hookId int64) (*Webhook, error) {
7481
return w, nil
7582
}
7683

84+
// GetActiveWebhooksByRepoId returns all active webhooks of repository.
85+
func GetActiveWebhooksByRepoId(repoId int64) (ws []*Webhook, err error) {
86+
err = orm.Find(&ws, &Webhook{RepoId: repoId, IsActive: true})
87+
return ws, err
88+
}
89+
7790
// GetWebhooksByRepoId returns all webhooks of repository.
7891
func GetWebhooksByRepoId(repoId int64) (ws []*Webhook, err error) {
7992
err = orm.Find(&ws, &Webhook{RepoId: repoId})

modules/hooks/hooks.go

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
// Copyright 2014 The Gogs Authors. All rights reserved.
2+
// Use of this source code is governed by a MIT-style
3+
// license that can be found in the LICENSE file.
4+
5+
package hooks
6+
7+
import (
8+
"encoding/json"
9+
"time"
10+
11+
"github.com/gogits/gogs/modules/httplib"
12+
"github.com/gogits/gogs/modules/log"
13+
)
14+
15+
// Hook task types.
16+
const (
17+
HTT_WEBHOOK = iota + 1
18+
HTT_SERVICE
19+
)
20+
21+
type PayloadAuthor struct {
22+
Name string `json:"name"`
23+
Email string `json:"email"`
24+
}
25+
26+
type PayloadCommit struct {
27+
Id string `json:"id"`
28+
Message string `json:"message"`
29+
Url string `json:"url"`
30+
Author *PayloadAuthor `json:"author"`
31+
}
32+
33+
// Payload represents payload information of hook.
34+
type Payload struct {
35+
Secret string `json:"secret"`
36+
Ref string `json:"ref"`
37+
Commits []*PayloadCommit `json:"commits"`
38+
Pusher *PayloadAuthor `json:"pusher"`
39+
}
40+
41+
// HookTask represents hook task.
42+
type HookTask struct {
43+
Type int
44+
Url string
45+
*Payload
46+
ContentType int
47+
IsSsl bool
48+
}
49+
50+
var (
51+
taskQueue = make(chan *HookTask, 1000)
52+
)
53+
54+
// AddHookTask adds new hook task to task queue.
55+
func AddHookTask(t *HookTask) {
56+
taskQueue <- t
57+
}
58+
59+
func init() {
60+
go handleQueue()
61+
}
62+
63+
func handleQueue() {
64+
for {
65+
select {
66+
case t := <-taskQueue:
67+
// Only support JSON now.
68+
data, err := json.MarshalIndent(t.Payload, "", "\t")
69+
if err != nil {
70+
log.Error("hooks.handleQueue(json): %v", err)
71+
continue
72+
}
73+
74+
_, err = httplib.Post(t.Url).SetTimeout(5*time.Second, 5*time.Second).
75+
Body(data).Response()
76+
if err != nil {
77+
log.Error("hooks.handleQueue: Fail to deliver hook: %v", err)
78+
continue
79+
}
80+
log.Info("Hook delivered")
81+
}
82+
}
83+
}

modules/httplib/README.md

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# httplib
2+
httplib is an libs help you to curl remote url.
3+
4+
# How to use?
5+
6+
## GET
7+
you can use Get to crawl data.
8+
9+
import "httplib"
10+
11+
str, err := httplib.Get("http://beego.me/").String()
12+
if err != nil {
13+
t.Fatal(err)
14+
}
15+
fmt.Println(str)
16+
17+
## POST
18+
POST data to remote url
19+
20+
b:=httplib.Post("http://beego.me/")
21+
b.Param("username","astaxie")
22+
b.Param("password","123456")
23+
str, err := b.String()
24+
if err != nil {
25+
t.Fatal(err)
26+
}
27+
fmt.Println(str)
28+
29+
## set timeout
30+
you can set timeout in request.default is 60 seconds.
31+
32+
set Get timeout:
33+
34+
httplib.Get("http://beego.me/").SetTimeout(100 * time.Second, 30 * time.Second)
35+
36+
set post timeout:
37+
38+
httplib.Post("http://beego.me/").SetTimeout(100 * time.Second, 30 * time.Second)
39+
40+
- first param is connectTimeout.
41+
- second param is readWriteTimeout
42+
43+
## debug
44+
if you want to debug the request info, set the debug on
45+
46+
httplib.Get("http://beego.me/").Debug(true)
47+
48+
## support HTTPS client
49+
if request url is https. You can set the client support TSL:
50+
51+
httplib.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
52+
53+
more info about the tls.Config please visit http://golang.org/pkg/crypto/tls/#Config
54+
55+
## set cookie
56+
some http request need setcookie. So set it like this:
57+
58+
cookie := &http.Cookie{}
59+
cookie.Name = "username"
60+
cookie.Value = "astaxie"
61+
httplib.Get("http://beego.me/").SetCookie(cookie)
62+

0 commit comments

Comments
 (0)