Skip to content

Commit 1773e88

Browse files
authored
Drop db operations from hook commands (#1514)
* move all database operations from hook command to web command and instead of internal routes * bug fixed * adjust the import path sequences * remove unused return value on hookSetup
1 parent 59f5bba commit 1773e88

File tree

8 files changed

+225
-60
lines changed

8 files changed

+225
-60
lines changed

cmd/hook.go

+21-39
Original file line numberDiff line numberDiff line change
@@ -7,20 +7,18 @@ package cmd
77
import (
88
"bufio"
99
"bytes"
10-
"crypto/tls"
1110
"fmt"
1211
"os"
12+
"path/filepath"
1313
"strconv"
1414
"strings"
1515

1616
"code.gitea.io/git"
1717
"code.gitea.io/gitea/models"
18-
"code.gitea.io/gitea/modules/base"
19-
"code.gitea.io/gitea/modules/httplib"
2018
"code.gitea.io/gitea/modules/log"
19+
"code.gitea.io/gitea/modules/private"
2120
"code.gitea.io/gitea/modules/setting"
2221

23-
"github.com/Unknwon/com"
2422
"github.com/urfave/cli"
2523
)
2624

@@ -64,6 +62,12 @@ var (
6462
}
6563
)
6664

65+
func hookSetup(logPath string) {
66+
setting.NewContext()
67+
log.NewGitLogger(filepath.Join(setting.LogRootPath, logPath))
68+
models.LoadConfigs()
69+
}
70+
6771
func runHookPreReceive(c *cli.Context) error {
6872
if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
6973
return nil
@@ -75,9 +79,7 @@ func runHookPreReceive(c *cli.Context) error {
7579
setting.CustomConf = c.GlobalString("config")
7680
}
7781

78-
if err := setup("hooks/pre-receive.log"); err != nil {
79-
fail("Hook pre-receive init failed", fmt.Sprintf("setup: %v", err))
80-
}
82+
hookSetup("hooks/pre-receive.log")
8183

8284
// the environment setted on serv command
8385
repoID, _ := strconv.ParseInt(os.Getenv(models.ProtectedBranchRepoID), 10, 64)
@@ -119,18 +121,20 @@ func runHookPreReceive(c *cli.Context) error {
119121
}*/
120122

121123
branchName := strings.TrimPrefix(refFullName, git.BranchPrefix)
122-
protectBranch, err := models.GetProtectedBranchBy(repoID, branchName)
124+
protectBranch, err := private.GetProtectedBranchBy(repoID, branchName)
123125
if err != nil {
124126
log.GitLogger.Fatal(2, "retrieve protected branches information failed")
125127
}
126128

127129
if protectBranch != nil {
128-
// check and deletion
129-
if newCommitID == git.EmptySHA {
130-
fail(fmt.Sprintf("branch %s is protected from deletion", branchName), "")
131-
} else {
132-
fail(fmt.Sprintf("protected branch %s can not be pushed to", branchName), "")
133-
//fail(fmt.Sprintf("branch %s is protected from force push", branchName), "")
130+
if !protectBranch.CanPush {
131+
// check and deletion
132+
if newCommitID == git.EmptySHA {
133+
fail(fmt.Sprintf("branch %s is protected from deletion", branchName), "")
134+
} else {
135+
fail(fmt.Sprintf("protected branch %s can not be pushed to", branchName), "")
136+
//fail(fmt.Sprintf("branch %s is protected from force push", branchName), "")
137+
}
134138
}
135139
}
136140
}
@@ -149,9 +153,7 @@ func runHookUpdate(c *cli.Context) error {
149153
setting.CustomConf = c.GlobalString("config")
150154
}
151155

152-
if err := setup("hooks/update.log"); err != nil {
153-
fail("Hook update init failed", fmt.Sprintf("setup: %v", err))
154-
}
156+
hookSetup("hooks/update.log")
155157

156158
return nil
157159
}
@@ -167,13 +169,10 @@ func runHookPostReceive(c *cli.Context) error {
167169
setting.CustomConf = c.GlobalString("config")
168170
}
169171

170-
if err := setup("hooks/post-receive.log"); err != nil {
171-
fail("Hook post-receive init failed", fmt.Sprintf("setup: %v", err))
172-
}
172+
hookSetup("hooks/post-receive.log")
173173

174174
// the environment setted on serv command
175175
repoUser := os.Getenv(models.EnvRepoUsername)
176-
repoUserSalt := os.Getenv(models.EnvRepoUserSalt)
177176
isWiki := (os.Getenv(models.EnvRepoIsWiki) == "true")
178177
repoName := os.Getenv(models.EnvRepoName)
179178
pusherID, _ := strconv.ParseInt(os.Getenv(models.EnvPusherID), 10, 64)
@@ -199,7 +198,7 @@ func runHookPostReceive(c *cli.Context) error {
199198
newCommitID := string(fields[1])
200199
refFullName := string(fields[2])
201200

202-
if err := models.PushUpdate(models.PushUpdateOptions{
201+
if err := private.PushUpdate(models.PushUpdateOptions{
203202
RefFullName: refFullName,
204203
OldCommitID: oldCommitID,
205204
NewCommitID: newCommitID,
@@ -210,23 +209,6 @@ func runHookPostReceive(c *cli.Context) error {
210209
}); err != nil {
211210
log.GitLogger.Error(2, "Update: %v", err)
212211
}
213-
214-
// Ask for running deliver hook and test pull request tasks.
215-
reqURL := setting.LocalURL + repoUser + "/" + repoName + "/tasks/trigger?branch=" +
216-
strings.TrimPrefix(refFullName, git.BranchPrefix) + "&secret=" + base.EncodeMD5(repoUserSalt) + "&pusher=" + com.ToStr(pusherID)
217-
log.GitLogger.Trace("Trigger task: %s", reqURL)
218-
219-
resp, err := httplib.Head(reqURL).SetTLSClientConfig(&tls.Config{
220-
InsecureSkipVerify: true,
221-
}).Response()
222-
if err == nil {
223-
resp.Body.Close()
224-
if resp.StatusCode/100 != 2 {
225-
log.GitLogger.Error(2, "Failed to trigger task: not 2xx response code")
226-
}
227-
} else {
228-
log.GitLogger.Error(2, "Failed to trigger task: %v", err)
229-
}
230212
}
231213

232214
return nil

models/update.go

+21-21
Original file line numberDiff line numberDiff line change
@@ -65,40 +65,40 @@ type PushUpdateOptions struct {
6565

6666
// PushUpdate must be called for any push actions in order to
6767
// generates necessary push action history feeds.
68-
func PushUpdate(opts PushUpdateOptions) (err error) {
68+
func PushUpdate(opts PushUpdateOptions) (repo *Repository, err error) {
6969
isNewRef := opts.OldCommitID == git.EmptySHA
7070
isDelRef := opts.NewCommitID == git.EmptySHA
7171
if isNewRef && isDelRef {
72-
return fmt.Errorf("Old and new revisions are both %s", git.EmptySHA)
72+
return nil, fmt.Errorf("Old and new revisions are both %s", git.EmptySHA)
7373
}
7474

7575
repoPath := RepoPath(opts.RepoUserName, opts.RepoName)
7676

7777
gitUpdate := exec.Command("git", "update-server-info")
7878
gitUpdate.Dir = repoPath
7979
if err = gitUpdate.Run(); err != nil {
80-
return fmt.Errorf("Failed to call 'git update-server-info': %v", err)
80+
return nil, fmt.Errorf("Failed to call 'git update-server-info': %v", err)
8181
}
8282

83-
if isDelRef {
84-
log.GitLogger.Info("Reference '%s' has been deleted from '%s/%s' by %s",
85-
opts.RefFullName, opts.RepoUserName, opts.RepoName, opts.PusherName)
86-
return nil
83+
owner, err := GetUserByName(opts.RepoUserName)
84+
if err != nil {
85+
return nil, fmt.Errorf("GetUserByName: %v", err)
8786
}
8887

89-
gitRepo, err := git.OpenRepository(repoPath)
88+
repo, err = GetRepositoryByName(owner.ID, opts.RepoName)
9089
if err != nil {
91-
return fmt.Errorf("OpenRepository: %v", err)
90+
return nil, fmt.Errorf("GetRepositoryByName: %v", err)
9291
}
9392

94-
owner, err := GetUserByName(opts.RepoUserName)
95-
if err != nil {
96-
return fmt.Errorf("GetUserByName: %v", err)
93+
if isDelRef {
94+
log.GitLogger.Info("Reference '%s' has been deleted from '%s/%s' by %s",
95+
opts.RefFullName, opts.RepoUserName, opts.RepoName, opts.PusherName)
96+
return repo, nil
9797
}
9898

99-
repo, err := GetRepositoryByName(owner.ID, opts.RepoName)
99+
gitRepo, err := git.OpenRepository(repoPath)
100100
if err != nil {
101-
return fmt.Errorf("GetRepositoryByName: %v", err)
101+
return nil, fmt.Errorf("OpenRepository: %v", err)
102102
}
103103

104104
if err = repo.UpdateSize(); err != nil {
@@ -116,27 +116,27 @@ func PushUpdate(opts PushUpdateOptions) (err error) {
116116
NewCommitID: opts.NewCommitID,
117117
Commits: &PushCommits{},
118118
}); err != nil {
119-
return fmt.Errorf("CommitRepoAction (tag): %v", err)
119+
return nil, fmt.Errorf("CommitRepoAction (tag): %v", err)
120120
}
121-
return nil
121+
return repo, nil
122122
}
123123

124124
newCommit, err := gitRepo.GetCommit(opts.NewCommitID)
125125
if err != nil {
126-
return fmt.Errorf("gitRepo.GetCommit: %v", err)
126+
return nil, fmt.Errorf("gitRepo.GetCommit: %v", err)
127127
}
128128

129129
// Push new branch.
130130
var l *list.List
131131
if isNewRef {
132132
l, err = newCommit.CommitsBeforeLimit(10)
133133
if err != nil {
134-
return fmt.Errorf("newCommit.CommitsBeforeLimit: %v", err)
134+
return nil, fmt.Errorf("newCommit.CommitsBeforeLimit: %v", err)
135135
}
136136
} else {
137137
l, err = newCommit.CommitsBeforeUntil(opts.OldCommitID)
138138
if err != nil {
139-
return fmt.Errorf("newCommit.CommitsBeforeUntil: %v", err)
139+
return nil, fmt.Errorf("newCommit.CommitsBeforeUntil: %v", err)
140140
}
141141
}
142142

@@ -149,7 +149,7 @@ func PushUpdate(opts PushUpdateOptions) (err error) {
149149
NewCommitID: opts.NewCommitID,
150150
Commits: ListToPushCommits(l),
151151
}); err != nil {
152-
return fmt.Errorf("CommitRepoAction (branch): %v", err)
152+
return nil, fmt.Errorf("CommitRepoAction (branch): %v", err)
153153
}
154-
return nil
154+
return repo, nil
155155
}

modules/private/branch.go

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// Copyright 2017 The Gitea 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 private
6+
7+
import (
8+
"crypto/tls"
9+
"encoding/json"
10+
"fmt"
11+
12+
"code.gitea.io/gitea/models"
13+
"code.gitea.io/gitea/modules/log"
14+
"code.gitea.io/gitea/modules/setting"
15+
)
16+
17+
// GetProtectedBranchBy get protected branch information
18+
func GetProtectedBranchBy(repoID int64, branchName string) (*models.ProtectedBranch, error) {
19+
// Ask for running deliver hook and test pull request tasks.
20+
reqURL := setting.LocalURL + fmt.Sprintf("api/internal/branch/%d/%s", repoID, branchName)
21+
log.GitLogger.Trace("GetProtectedBranchBy: %s", reqURL)
22+
23+
resp, err := newRequest(reqURL, "GET").SetTLSClientConfig(&tls.Config{
24+
InsecureSkipVerify: true,
25+
}).Response()
26+
if err != nil {
27+
return nil, err
28+
}
29+
30+
var branch models.ProtectedBranch
31+
if err := json.NewDecoder(resp.Body).Decode(&branch); err != nil {
32+
return nil, err
33+
}
34+
35+
defer resp.Body.Close()
36+
37+
// All 2XX status codes are accepted and others will return an error
38+
if resp.StatusCode/100 != 2 {
39+
return nil, fmt.Errorf("Failed to update public key: %s", decodeJSONError(resp).Err)
40+
}
41+
42+
return &branch, nil
43+
}

modules/private/internal.go

+4
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
// Copyright 2017 The Gitea 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+
15
package private
26

37
import (

modules/private/push_update.go

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// Copyright 2017 The Gitea 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 private
6+
7+
import (
8+
"crypto/tls"
9+
"encoding/json"
10+
"fmt"
11+
12+
"code.gitea.io/gitea/models"
13+
"code.gitea.io/gitea/modules/log"
14+
"code.gitea.io/gitea/modules/setting"
15+
)
16+
17+
// PushUpdate update publick key updates
18+
func PushUpdate(opt models.PushUpdateOptions) error {
19+
// Ask for running deliver hook and test pull request tasks.
20+
reqURL := setting.LocalURL + "api/internal/push/update"
21+
log.GitLogger.Trace("PushUpdate: %s", reqURL)
22+
23+
body, err := json.Marshal(&opt)
24+
if err != nil {
25+
return err
26+
}
27+
28+
resp, err := newRequest(reqURL, "POST").Body(body).SetTLSClientConfig(&tls.Config{
29+
InsecureSkipVerify: true,
30+
}).Response()
31+
if err != nil {
32+
return err
33+
}
34+
35+
defer resp.Body.Close()
36+
37+
// All 2XX status codes are accepted and others will return an error
38+
if resp.StatusCode/100 != 2 {
39+
return fmt.Errorf("Failed to update public key: %s", decodeJSONError(resp).Err)
40+
}
41+
42+
return nil
43+
}

routers/private/branch.go

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// Copyright 2017 The Gitea 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 private
6+
7+
import (
8+
"code.gitea.io/gitea/models"
9+
10+
macaron "gopkg.in/macaron.v1"
11+
)
12+
13+
// GetProtectedBranchBy get protected branch information
14+
func GetProtectedBranchBy(ctx *macaron.Context) {
15+
repoID := ctx.ParamsInt64(":id")
16+
branchName := ctx.Params(":branch")
17+
protectBranch, err := models.GetProtectedBranchBy(repoID, branchName)
18+
if err != nil {
19+
ctx.JSON(500, map[string]interface{}{
20+
"err": err.Error(),
21+
})
22+
return
23+
} else if protectBranch != nil {
24+
ctx.JSON(200, protectBranch)
25+
} else {
26+
ctx.JSON(200, &models.ProtectedBranch{
27+
CanPush: true,
28+
})
29+
}
30+
}

routers/private/internal.go

+3
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import (
1010

1111
"code.gitea.io/gitea/models"
1212
"code.gitea.io/gitea/modules/setting"
13+
1314
macaron "gopkg.in/macaron.v1"
1415
)
1516

@@ -40,5 +41,7 @@ func UpdatePublicKey(ctx *macaron.Context) {
4041
func RegisterRoutes(m *macaron.Macaron) {
4142
m.Group("/", func() {
4243
m.Post("/ssh/:id/update", UpdatePublicKey)
44+
m.Post("/push/update", PushUpdate)
45+
m.Get("/branch/:id/:branch", GetProtectedBranchBy)
4346
}, CheckInternalToken)
4447
}

0 commit comments

Comments
 (0)