summaryrefslogtreecommitdiffstats
path: root/cmd
diff options
context:
space:
mode:
authorLunny Xiao <xiaolunwen@gmail.com>2017-02-25 22:54:40 +0800
committerGitHub <noreply@github.com>2017-02-25 22:54:40 +0800
commitcd1821a7e292b05e04fcc2a969b42d06ab512849 (patch)
tree084f97bfb24a37ec3028d15fdacb51e86cfcc368 /cmd
parente8e56da9ac321aacb3c06968997a45c2f133cd4e (diff)
downloadgitea-cd1821a7e292b05e04fcc2a969b42d06ab512849.tar.gz
gitea-cd1821a7e292b05e04fcc2a969b42d06ab512849.zip
Move push update to post-receive and protected branch check to pre-receive (#1030)
* move all push update to git hook post-receive and protected branch check to git hook pre-receive * add SSH_ORIGINAL_COMMAND check back * remove all unused codes * fix the import
Diffstat (limited to 'cmd')
-rw-r--r--cmd/hook.go135
-rw-r--r--cmd/serv.go76
-rw-r--r--cmd/update.go83
3 files changed, 131 insertions, 163 deletions
diff --git a/cmd/hook.go b/cmd/hook.go
index 15ad74f8e0..a89c3741bf 100644
--- a/cmd/hook.go
+++ b/cmd/hook.go
@@ -5,11 +5,22 @@
package cmd
import (
+ "bufio"
+ "bytes"
+ "crypto/tls"
"fmt"
"os"
+ "strconv"
+ "strings"
+ "code.gitea.io/git"
"code.gitea.io/gitea/models"
+ "code.gitea.io/gitea/modules/base"
+ "code.gitea.io/gitea/modules/httplib"
+ "code.gitea.io/gitea/modules/log"
+ "code.gitea.io/gitea/modules/setting"
+ "github.com/Unknwon/com"
"github.com/urfave/cli"
)
@@ -57,10 +68,59 @@ func runHookPreReceive(c *cli.Context) error {
if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
return nil
}
+
if err := setup("hooks/pre-receive.log"); err != nil {
fail("Hook pre-receive init failed", fmt.Sprintf("setup: %v", err))
}
+ // the environment setted on serv command
+ repoID, _ := strconv.ParseInt(os.Getenv(models.ProtectedBranchRepoID), 10, 64)
+ isWiki := (os.Getenv(models.EnvRepoIsWiki) == "true")
+
+ buf := bytes.NewBuffer(nil)
+ scanner := bufio.NewScanner(os.Stdin)
+ for scanner.Scan() {
+ buf.Write(scanner.Bytes())
+ buf.WriteByte('\n')
+
+ // TODO: support news feeds for wiki
+ if isWiki {
+ continue
+ }
+
+ fields := bytes.Fields(scanner.Bytes())
+ if len(fields) != 3 {
+ continue
+ }
+
+ oldCommitID := string(fields[0])
+ newCommitID := string(fields[1])
+ refFullName := string(fields[2])
+
+ branchName := strings.TrimPrefix(refFullName, git.BranchPrefix)
+ protectBranch, err := models.GetProtectedBranchBy(repoID, branchName)
+ if err != nil {
+ log.GitLogger.Fatal(2, "retrieve protected branches information failed")
+ }
+
+ if protectBranch != nil {
+ fail(fmt.Sprintf("protected branch %s can not be pushed to", branchName), "")
+ }
+
+ // check and deletion
+ if newCommitID == git.EmptySHA {
+ fail(fmt.Sprintf("Branch '%s' is protected from deletion", branchName), "")
+ }
+
+ // Check force push
+ output, err := git.NewCommand("rev-list", oldCommitID, "^"+newCommitID).Run()
+ if err != nil {
+ fail("Internal error", "Fail to detect force push: %v", err)
+ } else if len(output) > 0 {
+ fail(fmt.Sprintf("Branch '%s' is protected from force push", branchName), "")
+ }
+ }
+
return nil
}
@@ -73,23 +133,6 @@ func runHookUpdate(c *cli.Context) error {
fail("Hook update init failed", fmt.Sprintf("setup: %v", err))
}
- args := c.Args()
- if len(args) != 3 {
- fail("Arguments received are not equal to three", "Arguments received are not equal to three")
- } else if len(args[0]) == 0 {
- fail("First argument 'refName' is empty", "First argument 'refName' is empty")
- }
-
- uuid := os.Getenv(envUpdateTaskUUID)
- if err := models.AddUpdateTask(&models.UpdateTask{
- UUID: uuid,
- RefName: args[0],
- OldCommitID: args[1],
- NewCommitID: args[2],
- }); err != nil {
- fail("Internal error", "Fail to add update task '%s': %v", uuid, err)
- }
-
return nil
}
@@ -102,5 +145,63 @@ func runHookPostReceive(c *cli.Context) error {
fail("Hook post-receive init failed", fmt.Sprintf("setup: %v", err))
}
+ // the environment setted on serv command
+ repoUser := os.Getenv(models.EnvRepoUsername)
+ repoUserSalt := os.Getenv(models.EnvRepoUserSalt)
+ isWiki := (os.Getenv(models.EnvRepoIsWiki) == "true")
+ repoName := os.Getenv(models.EnvRepoName)
+ pusherID, _ := strconv.ParseInt(os.Getenv(models.EnvPusherID), 10, 64)
+ pusherName := os.Getenv(models.EnvPusherName)
+
+ buf := bytes.NewBuffer(nil)
+ scanner := bufio.NewScanner(os.Stdin)
+ for scanner.Scan() {
+ buf.Write(scanner.Bytes())
+ buf.WriteByte('\n')
+
+ // TODO: support news feeds for wiki
+ if isWiki {
+ continue
+ }
+
+ fields := bytes.Fields(scanner.Bytes())
+ if len(fields) != 3 {
+ continue
+ }
+
+ oldCommitID := string(fields[0])
+ newCommitID := string(fields[1])
+ refFullName := string(fields[2])
+
+ if err := models.PushUpdate(models.PushUpdateOptions{
+ RefFullName: refFullName,
+ OldCommitID: oldCommitID,
+ NewCommitID: newCommitID,
+ PusherID: pusherID,
+ PusherName: pusherName,
+ RepoUserName: repoUser,
+ RepoName: repoName,
+ }); err != nil {
+ log.GitLogger.Error(2, "Update: %v", err)
+ }
+
+ // Ask for running deliver hook and test pull request tasks.
+ reqURL := setting.LocalURL + repoUser + "/" + repoName + "/tasks/trigger?branch=" +
+ strings.TrimPrefix(refFullName, git.BranchPrefix) + "&secret=" + base.EncodeMD5(repoUserSalt) + "&pusher=" + com.ToStr(pusherID)
+ log.GitLogger.Trace("Trigger task: %s", reqURL)
+
+ resp, err := httplib.Head(reqURL).SetTLSClientConfig(&tls.Config{
+ InsecureSkipVerify: true,
+ }).Response()
+ if err == nil {
+ resp.Body.Close()
+ if resp.StatusCode/100 != 2 {
+ log.GitLogger.Error(2, "Failed to trigger task: not 2xx response code")
+ }
+ } else {
+ log.GitLogger.Error(2, "Failed to trigger task: %v", err)
+ }
+ }
+
return nil
}
diff --git a/cmd/serv.go b/cmd/serv.go
index 141a58a2ac..5b1caf4d34 100644
--- a/cmd/serv.go
+++ b/cmd/serv.go
@@ -6,7 +6,6 @@
package cmd
import (
- "crypto/tls"
"encoding/json"
"fmt"
"os"
@@ -15,22 +14,17 @@ import (
"strings"
"time"
- "code.gitea.io/git"
"code.gitea.io/gitea/models"
- "code.gitea.io/gitea/modules/base"
- "code.gitea.io/gitea/modules/httplib"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
"github.com/Unknwon/com"
"github.com/dgrijalva/jwt-go"
- gouuid "github.com/satori/go.uuid"
"github.com/urfave/cli"
)
const (
accessDenied = "Repository does not exist or you do not have access"
lfsAuthenticateVerb = "git-lfs-authenticate"
- envUpdateTaskUUID = "GITEA_UUID"
)
// CmdServ represents the available serv sub-command.
@@ -96,52 +90,6 @@ func fail(userMessage, logMessage string, args ...interface{}) {
os.Exit(1)
}
-func handleUpdateTask(uuid string, user, repoUser *models.User, reponame string, isWiki bool) {
- task, err := models.GetUpdateTaskByUUID(uuid)
- if err != nil {
- if models.IsErrUpdateTaskNotExist(err) {
- log.GitLogger.Trace("No update task is presented: %s", uuid)
- return
- }
- log.GitLogger.Fatal(2, "GetUpdateTaskByUUID: %v", err)
- } else if err = models.DeleteUpdateTaskByUUID(uuid); err != nil {
- log.GitLogger.Fatal(2, "DeleteUpdateTaskByUUID: %v", err)
- }
-
- if isWiki {
- return
- }
-
- if err = models.PushUpdate(models.PushUpdateOptions{
- RefFullName: task.RefName,
- OldCommitID: task.OldCommitID,
- NewCommitID: task.NewCommitID,
- PusherID: user.ID,
- PusherName: user.Name,
- RepoUserName: repoUser.Name,
- RepoName: reponame,
- }); err != nil {
- log.GitLogger.Error(2, "Update: %v", err)
- }
-
- // Ask for running deliver hook and test pull request tasks.
- reqURL := setting.LocalURL + repoUser.Name + "/" + reponame + "/tasks/trigger?branch=" +
- strings.TrimPrefix(task.RefName, git.BranchPrefix) + "&secret=" + base.EncodeMD5(repoUser.Salt) + "&pusher=" + com.ToStr(user.ID)
- log.GitLogger.Trace("Trigger task: %s", reqURL)
-
- resp, err := httplib.Head(reqURL).SetTLSClientConfig(&tls.Config{
- InsecureSkipVerify: true,
- }).Response()
- if err == nil {
- resp.Body.Close()
- if resp.StatusCode/100 != 2 {
- log.GitLogger.Error(2, "Failed to trigger task: not 2xx response code")
- }
- } else {
- log.GitLogger.Error(2, "Failed to trigger task: %v", err)
- }
-}
-
func runServ(c *cli.Context) error {
if c.IsSet("config") {
setting.CustomConf = c.String("config")
@@ -187,6 +135,7 @@ func runServ(c *cli.Context) error {
if len(rr) != 2 {
fail("Invalid repository path", "Invalid repository path: %v", args)
}
+
username := strings.ToLower(rr[0])
reponame := strings.ToLower(strings.TrimSuffix(rr[1], ".git"))
@@ -196,6 +145,14 @@ func runServ(c *cli.Context) error {
reponame = reponame[:len(reponame)-5]
}
+ os.Setenv(models.EnvRepoUsername, username)
+ if isWiki {
+ os.Setenv(models.EnvRepoIsWiki, "true")
+ } else {
+ os.Setenv(models.EnvRepoIsWiki, "false")
+ }
+ os.Setenv(models.EnvRepoName, reponame)
+
repoUser, err := models.GetUserByName(username)
if err != nil {
if models.IsErrUserNotExist(err) {
@@ -204,6 +161,8 @@ func runServ(c *cli.Context) error {
fail("Internal error", "Failed to get repository owner (%s): %v", username, err)
}
+ os.Setenv(models.EnvRepoUserSalt, repoUser.Salt)
+
repo, err := models.GetRepositoryByName(repoUser.ID, reponame)
if err != nil {
if models.IsErrRepoNotExist(err) {
@@ -286,7 +245,8 @@ func runServ(c *cli.Context) error {
user.Name, requestedMode, repoPath)
}
- os.Setenv("GITEA_PUSHER_NAME", user.Name)
+ os.Setenv(models.EnvPusherName, user.Name)
+ os.Setenv(models.EnvPusherID, fmt.Sprintf("%d", user.ID))
}
}
@@ -323,11 +283,6 @@ func runServ(c *cli.Context) error {
return nil
}
- uuid := gouuid.NewV4().String()
- os.Setenv(envUpdateTaskUUID, uuid)
- // Keep the old env variable name for backward compability
- os.Setenv("uuid", uuid)
-
// Special handle for Windows.
if setting.IsWindows {
verb = strings.Replace(verb, "-", " ", 1)
@@ -341,7 +296,6 @@ func runServ(c *cli.Context) error {
gitcmd = exec.Command(verb, repoPath)
}
- os.Setenv(models.ProtectedBranchAccessMode, requestedMode.String())
os.Setenv(models.ProtectedBranchRepoID, fmt.Sprintf("%d", repo.ID))
gitcmd.Dir = setting.RepoRootPath
@@ -352,10 +306,6 @@ func runServ(c *cli.Context) error {
fail("Internal error", "Failed to execute git command: %v", err)
}
- if requestedMode == models.AccessModeWrite {
- handleUpdateTask(uuid, user, repoUser, reponame, isWiki)
- }
-
// Update user key activity.
if keyID > 0 {
key, err := models.GetPublicKeyByID(keyID)
diff --git a/cmd/update.go b/cmd/update.go
deleted file mode 100644
index 58e60493d0..0000000000
--- a/cmd/update.go
+++ /dev/null
@@ -1,83 +0,0 @@
-// 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 cmd
-
-import (
- "os"
- "strconv"
- "strings"
-
- "github.com/urfave/cli"
-
- "code.gitea.io/git"
- "code.gitea.io/gitea/models"
- "code.gitea.io/gitea/modules/log"
- "code.gitea.io/gitea/modules/setting"
-)
-
-// CmdUpdate represents the available update sub-command.
-var CmdUpdate = cli.Command{
- Name: "update",
- Usage: "This command should only be called by Git hook",
- Description: `Update get pushed info and insert into database`,
- Action: runUpdate,
- Flags: []cli.Flag{
- cli.StringFlag{
- Name: "config, c",
- Value: "custom/conf/app.ini",
- Usage: "Custom configuration file path",
- },
- },
-}
-
-func runUpdate(c *cli.Context) error {
- if c.IsSet("config") {
- setting.CustomConf = c.String("config")
- }
-
- setup("update.log")
-
- if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
- log.GitLogger.Trace("SSH_ORIGINAL_COMMAND is empty")
- return nil
- }
-
- args := c.Args()
- if len(args) != 3 {
- log.GitLogger.Fatal(2, "Arguments received are not equal to three")
- } else if len(args[0]) == 0 {
- log.GitLogger.Fatal(2, "First argument 'refName' is empty, shouldn't use")
- }
-
- // protected branch check
- branchName := strings.TrimPrefix(args[0], git.BranchPrefix)
- repoID, _ := strconv.ParseInt(os.Getenv(models.ProtectedBranchRepoID), 10, 64)
- log.GitLogger.Trace("pushing to %d %v", repoID, branchName)
- accessMode := models.ParseAccessMode(os.Getenv(models.ProtectedBranchAccessMode))
- // skip admin or owner AccessMode
- if accessMode == models.AccessModeWrite {
- protectBranch, err := models.GetProtectedBranchBy(repoID, branchName)
- if err != nil {
- log.GitLogger.Fatal(2, "retrieve protected branches information failed")
- }
-
- if protectBranch != nil {
- log.GitLogger.Fatal(2, "protected branches can not be pushed to")
- }
- }
-
- task := models.UpdateTask{
- UUID: os.Getenv("GITEA_UUID"),
- RefName: args[0],
- OldCommitID: args[1],
- NewCommitID: args[2],
- }
-
- if err := models.AddUpdateTask(&task); err != nil {
- log.GitLogger.Fatal(2, "AddUpdateTask: %v", err)
- }
-
- return nil
-}