Code convention

release/v1.15
Unknown 2014-05-21 21:37:13 -04:00
parent 1331134316
commit 5e9a45f74a
7 changed files with 119 additions and 121 deletions

View File

@ -5,7 +5,6 @@
package cmd package cmd
import ( import (
//"container/list"
"fmt" "fmt"
"os" "os"
"os/exec" "os/exec"
@ -16,24 +15,10 @@ import (
"github.com/codegangsta/cli" "github.com/codegangsta/cli"
qlog "github.com/qiniu/log" qlog "github.com/qiniu/log"
//"github.com/gogits/git"
"github.com/gogits/gogs/models" "github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/base"
) )
var (
COMMANDS_READONLY = map[string]int{
"git-upload-pack": models.AU_WRITABLE,
"git upload-pack": models.AU_WRITABLE,
"git-upload-archive": models.AU_WRITABLE,
}
COMMANDS_WRITE = map[string]int{
"git-receive-pack": models.AU_READABLE,
"git receive-pack": models.AU_READABLE,
}
)
var CmdServ = cli.Command{ var CmdServ = cli.Command{
Name: "serv", Name: "serv",
Usage: "This command should only be called by SSH shell", Usage: "This command should only be called by SSH shell",
@ -42,8 +27,7 @@ var CmdServ = cli.Command{
Flags: []cli.Flag{}, Flags: []cli.Flag{},
} }
func newLogger(execDir string) { func newLogger(logPath string) {
logPath := execDir + "/log/serv.log"
os.MkdirAll(path.Dir(logPath), os.ModePerm) os.MkdirAll(path.Dir(logPath), os.ModePerm)
f, err := os.OpenFile(logPath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, os.ModePerm) f, err := os.OpenFile(logPath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, os.ModePerm)
@ -56,6 +40,20 @@ func newLogger(execDir string) {
qlog.Info("Start logging serv...") qlog.Info("Start logging serv...")
} }
func setup(logPath string) {
execDir, _ := base.ExecDir()
newLogger(path.Join(execDir, logPath))
base.NewConfigContext()
models.LoadModelsConfig()
if models.UseSQLite3 {
os.Chdir(execDir)
}
models.SetEngine()
}
func parseCmd(cmd string) (string, string) { func parseCmd(cmd string) (string, string) {
ss := strings.SplitN(cmd, " ", 2) ss := strings.SplitN(cmd, " ", 2)
if len(ss) != 2 { if len(ss) != 2 {
@ -71,39 +69,46 @@ func parseCmd(cmd string) (string, string) {
return verb, strings.Replace(args, "'/", "'", 1) return verb, strings.Replace(args, "'/", "'", 1)
} }
var (
COMMANDS_READONLY = map[string]int{
"git-upload-pack": models.AU_WRITABLE,
"git upload-pack": models.AU_WRITABLE,
"git-upload-archive": models.AU_WRITABLE,
}
COMMANDS_WRITE = map[string]int{
"git-receive-pack": models.AU_READABLE,
"git receive-pack": models.AU_READABLE,
}
)
func In(b string, sl map[string]int) bool { func In(b string, sl map[string]int) bool {
_, e := sl[b] _, e := sl[b]
return e return e
} }
func runServ(k *cli.Context) { func runServ(k *cli.Context) {
execDir, _ := base.ExecDir() setup("log/serv.log")
newLogger(execDir)
base.NewConfigContext()
models.LoadModelsConfig()
if models.UseSQLite3 {
os.Chdir(execDir)
}
models.SetEngine()
keys := strings.Split(os.Args[2], "-") keys := strings.Split(os.Args[2], "-")
if len(keys) != 2 { if len(keys) != 2 {
println("auth file format error") println("Gogs: auth file format error")
qlog.Fatal("auth file format error") qlog.Fatal("Invalid auth file format: %s", os.Args[2])
} }
keyId, err := strconv.ParseInt(keys[1], 10, 64) keyId, err := strconv.ParseInt(keys[1], 10, 64)
if err != nil { if err != nil {
println("auth file format error") println("Gogs: auth file format error")
qlog.Fatal("auth file format error", err) qlog.Fatalf("Invalid auth file format: %v", err)
} }
user, err := models.GetUserByKeyId(keyId) user, err := models.GetUserByKeyId(keyId)
if err != nil { if err != nil {
println("You have no right to access") if err == models.ErrUserNotKeyOwner {
qlog.Fatalf("SSH visit error: %v", err) println("Gogs: you are not the owner of SSH key")
qlog.Fatalf("Invalid owner of SSH key: %d", keyId)
}
println("Gogs: internal error:", err)
qlog.Fatalf("Fail to get user by key ID(%d): %v", keyId, err)
} }
cmd := os.Getenv("SSH_ORIGINAL_COMMAND") cmd := os.Getenv("SSH_ORIGINAL_COMMAND")
@ -116,8 +121,8 @@ func runServ(k *cli.Context) {
repoPath := strings.Trim(args, "'") repoPath := strings.Trim(args, "'")
rr := strings.SplitN(repoPath, "/", 2) rr := strings.SplitN(repoPath, "/", 2)
if len(rr) != 2 { if len(rr) != 2 {
println("Unavailable repository", args) println("Gogs: unavailable repository", args)
qlog.Fatalf("Unavailable repository %v", args) qlog.Fatalf("Unavailable repository: %v", args)
} }
repoUserName := rr[0] repoUserName := rr[0]
repoName := strings.TrimSuffix(rr[1], ".git") repoName := strings.TrimSuffix(rr[1], ".git")
@ -127,17 +132,21 @@ func runServ(k *cli.Context) {
repoUser, err := models.GetUserByName(repoUserName) repoUser, err := models.GetUserByName(repoUserName)
if err != nil { if err != nil {
println("You have no right to access") if err == models.ErrUserNotExist {
qlog.Fatalf("Get user failed: %v", err) println("Gogs: given repository owner are not registered")
qlog.Fatalf("Unregistered owner: %s", repoUserName)
}
println("Gogs: internal error:", err)
qlog.Fatalf("Fail to get repository owner(%s): %v", repoUserName, err)
} }
// access check // Access check.
switch { switch {
case isWrite: case isWrite:
has, err := models.HasAccess(user.LowerName, path.Join(repoUserName, repoName), models.AU_WRITABLE) has, err := models.HasAccess(user.Name, path.Join(repoUserName, repoName), models.AU_WRITABLE)
if err != nil { if err != nil {
println("Internal error:", err) println("Gogs: internal error:", err)
qlog.Fatal(err) qlog.Fatal("Fail to check write access:", err)
} else if !has { } else if !has {
println("You have no right to write this repository") println("You have no right to write this repository")
qlog.Fatalf("User %s has no right to write repository %s", user.Name, repoPath) qlog.Fatalf("User %s has no right to write repository %s", user.Name, repoPath)
@ -145,8 +154,12 @@ func runServ(k *cli.Context) {
case isRead: case isRead:
repo, err := models.GetRepositoryByName(repoUser.Id, repoName) repo, err := models.GetRepositoryByName(repoUser.Id, repoName)
if err != nil { if err != nil {
println("Get repository error:", err) if err == models.ErrRepoNotExist {
qlog.Fatal("Get repository error: " + err.Error()) println("Gogs: given repository does not exist")
qlog.Fatalf("Repository does not exist: %s/%s", repoUser.Name, repoName)
}
println("Gogs: internal error:", err)
qlog.Fatalf("Fail to get repository: %v", err)
} }
if !repo.IsPrivate { if !repo.IsPrivate {
@ -155,23 +168,15 @@ func runServ(k *cli.Context) {
has, err := models.HasAccess(user.Name, path.Join(repoUserName, repoName), models.AU_READABLE) has, err := models.HasAccess(user.Name, path.Join(repoUserName, repoName), models.AU_READABLE)
if err != nil { if err != nil {
println("Internal error") println("Gogs: internal error:", err)
qlog.Fatal(err) qlog.Fatal("Fail to check read access:", err)
} } else if !has {
if !has {
has, err = models.HasAccess(user.Name, path.Join(repoUserName, repoName), models.AU_WRITABLE)
if err != nil {
println("Internal error")
qlog.Fatal(err)
}
}
if !has {
println("You have no right to access this repository") println("You have no right to access this repository")
qlog.Fatal("You have no right to access this repository") qlog.Fatalf("User %s has no right to read repository %s", user.Name, repoPath)
} }
default: default:
println("Unknown command") println("Unknown command")
qlog.Fatal("Unknown command") return
} }
models.SetRepoEnvs(user.Id, user.Name, repoName, repoUserName) models.SetRepoEnvs(user.Id, user.Name, repoName, repoUserName)
@ -183,8 +188,8 @@ func runServ(k *cli.Context) {
gitcmd.Stderr = os.Stderr gitcmd.Stderr = os.Stderr
if err = gitcmd.Run(); err != nil { if err = gitcmd.Run(); err != nil {
println("execute command error:", err.Error()) println("Gogs: internal error:", err)
qlog.Fatal("execute command error: " + err.Error()) qlog.Fatalf("Fail to execute git command: %v", err)
} }
//refName := os.Getenv("refName") //refName := os.Getenv("refName")

View File

@ -6,14 +6,12 @@ package cmd
import ( import (
"os" "os"
"path"
"strconv" "strconv"
"github.com/codegangsta/cli" "github.com/codegangsta/cli"
qlog "github.com/qiniu/log" qlog "github.com/qiniu/log"
"github.com/gogits/gogs/models" "github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/base"
) )
var CmdUpdate = cli.Command{ var CmdUpdate = cli.Command{
@ -24,51 +22,25 @@ var CmdUpdate = cli.Command{
Flags: []cli.Flag{}, Flags: []cli.Flag{},
} }
func newUpdateLogger(execDir string) {
logPath := execDir + "/log/update.log"
os.MkdirAll(path.Dir(logPath), os.ModePerm)
f, err := os.OpenFile(logPath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, os.ModePerm)
if err != nil {
qlog.Fatal(err)
}
qlog.SetOutput(f)
qlog.Info("Start logging update...")
}
func updateEnv(refName, oldCommitId, newCommitId string) { func updateEnv(refName, oldCommitId, newCommitId string) {
os.Setenv("refName", refName) os.Setenv("refName", refName)
os.Setenv("oldCommitId", oldCommitId) os.Setenv("oldCommitId", oldCommitId)
os.Setenv("newCommitId", newCommitId) os.Setenv("newCommitId", newCommitId)
qlog.Error("set envs:", refName, oldCommitId, newCommitId) qlog.Info("set envs:", refName, oldCommitId, newCommitId)
} }
// for command: ./gogs update
func runUpdate(c *cli.Context) { func runUpdate(c *cli.Context) {
cmd := os.Getenv("SSH_ORIGINAL_COMMAND") cmd := os.Getenv("SSH_ORIGINAL_COMMAND")
if cmd == "" { if cmd == "" {
return return
} }
execDir, _ := base.ExecDir() setup("log/update.log")
newUpdateLogger(execDir)
base.NewConfigContext()
models.LoadModelsConfig()
if models.UseSQLite3 {
os.Chdir(execDir)
}
models.SetEngine()
args := c.Args() args := c.Args()
if len(args) != 3 { if len(args) != 3 {
qlog.Fatal("received less 3 parameters") qlog.Fatal("received less 3 parameters")
} } else if args[0] == "" {
if args[0] == "" {
qlog.Fatal("refName is empty, shouldn't use") qlog.Fatal("refName is empty, shouldn't use")
} }

View File

@ -78,7 +78,8 @@ func runWeb(*cli.Context) {
m.Get("/stars", reqSignIn, user.Stars) m.Get("/stars", reqSignIn, user.Stars)
m.Get("/help", routers.Help) m.Get("/help", routers.Help)
m.Group("/api/v1", func(r martini.Router) { m.Group("/api", func(r martini.Router) {
m.Group("/v1", func(r martini.Router) {
// Miscellaneous. // Miscellaneous.
r.Post("/markdown", bindIgnErr(apiv1.MarkdownForm{}), v1.Markdown) r.Post("/markdown", bindIgnErr(apiv1.MarkdownForm{}), v1.Markdown)
r.Post("/markdown/raw", v1.MarkdownRaw) r.Post("/markdown/raw", v1.MarkdownRaw)
@ -90,6 +91,7 @@ func runWeb(*cli.Context) {
ctx.JSON(404, &base.ApiJsonErr{"Not Found", v1.DOC_URL}) ctx.JSON(404, &base.ApiJsonErr{"Not Found", v1.DOC_URL})
}) })
}) })
})
avt := avatar.CacheServer("public/img/avatar/", "public/img/avatar_default.jpg") avt := avatar.CacheServer("public/img/avatar/", "public/img/avatar_default.jpg")
os.MkdirAll("public/img/avatar/", os.ModePerm) os.MkdirAll("public/img/avatar/", os.ModePerm)
@ -170,29 +172,36 @@ func runWeb(*cli.Context) {
m.Group("/:username/:reponame", func(r martini.Router) { m.Group("/:username/:reponame", func(r martini.Router) {
r.Get("/settings", repo.Setting) r.Get("/settings", repo.Setting)
r.Post("/settings", bindIgnErr(auth.RepoSettingForm{}), repo.SettingPost) r.Post("/settings", bindIgnErr(auth.RepoSettingForm{}), repo.SettingPost)
r.Get("/settings/collaboration", repo.Collaboration)
r.Post("/settings/collaboration", repo.CollaborationPost) m.Group("/settings", func(r martini.Router) {
r.Get("/settings/hooks", repo.WebHooks) r.Get("/collaboration", repo.Collaboration)
r.Get("/settings/hooks/add", repo.WebHooksAdd) r.Post("/collaboration", repo.CollaborationPost)
r.Post("/settings/hooks/add", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksAddPost) r.Get("/hooks", repo.WebHooks)
r.Get("/settings/hooks/:id", repo.WebHooksEdit) r.Get("/hooks/add", repo.WebHooksAdd)
r.Post("/settings/hooks/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost) r.Post("/hooks/add", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksAddPost)
r.Get("/hooks/:id", repo.WebHooksEdit)
r.Post("/hooks/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
})
}, reqSignIn, middleware.RepoAssignment(true), reqOwner) }, reqSignIn, middleware.RepoAssignment(true), reqOwner)
m.Group("/:username/:reponame", func(r martini.Router) { m.Group("/:username/:reponame", func(r martini.Router) {
r.Get("/action/:action", repo.Action) r.Get("/action/:action", repo.Action)
r.Get("/issues/new", repo.CreateIssue)
r.Post("/issues/new", bindIgnErr(auth.CreateIssueForm{}), repo.CreateIssuePost) m.Group("/issues", func(r martini.Router) {
r.Post("/issues/:index", bindIgnErr(auth.CreateIssueForm{}), repo.UpdateIssue) r.Get("/new", repo.CreateIssue)
r.Post("/issues/:index/assignee", repo.UpdateAssignee) r.Post("/new", bindIgnErr(auth.CreateIssueForm{}), repo.CreateIssuePost)
r.Post("/issues/:index/milestone", repo.UpdateIssueMilestone) r.Post("/:index", bindIgnErr(auth.CreateIssueForm{}), repo.UpdateIssue)
r.Post("/issues/labels/new", bindIgnErr(auth.CreateLabelForm{}), repo.NewLabel) r.Post("/:index/assignee", repo.UpdateAssignee)
r.Get("/issues/milestones", repo.Milestones) r.Post("/:index/milestone", repo.UpdateIssueMilestone)
r.Get("/issues/milestones/new", repo.NewMilestone) r.Post("/labels/new", bindIgnErr(auth.CreateLabelForm{}), repo.NewLabel)
r.Post("/issues/milestones/new", bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost) r.Get("/milestones", repo.Milestones)
r.Get("/issues/milestones/:index/edit", repo.UpdateMilestone) r.Get("/milestones/new", repo.NewMilestone)
r.Post("/issues/milestones/:index/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.UpdateMilestonePost) r.Post("/milestones/new", bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost)
r.Get("/issues/milestones/:index/:action", repo.UpdateMilestone) r.Get("/milestones/:index/edit", repo.UpdateMilestone)
r.Post("/milestones/:index/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.UpdateMilestonePost)
r.Get("/milestones/:index/:action", repo.UpdateMilestone)
})
r.Post("/comment/:action", repo.Comment) r.Post("/comment/:action", repo.Comment)
r.Get("/releases/new", repo.ReleasesNew) r.Get("/releases/new", repo.ReleasesNew)
}, reqSignIn, middleware.RepoAssignment(true)) }, reqSignIn, middleware.RepoAssignment(true))

View File

@ -17,7 +17,7 @@ import (
"github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/base"
) )
const APP_VER = "0.3.5.0518 Alpha" const APP_VER = "0.3.5.0521 Alpha"
func init() { func init() {
base.AppVer = APP_VER base.AppVer = APP_VER

View File

@ -30,6 +30,7 @@ var (
ErrUserOwnRepos = errors.New("User still have ownership of repositories") ErrUserOwnRepos = errors.New("User still have ownership of repositories")
ErrUserAlreadyExist = errors.New("User already exist") ErrUserAlreadyExist = errors.New("User already exist")
ErrUserNotExist = errors.New("User does not exist") ErrUserNotExist = errors.New("User does not exist")
ErrUserNotKeyOwner = errors.New("User does not the owner of public key")
ErrEmailAlreadyUsed = errors.New("E-mail already used") ErrEmailAlreadyUsed = errors.New("E-mail already used")
ErrUserNameIllegal = errors.New("User name contains illegal characters") ErrUserNameIllegal = errors.New("User name contains illegal characters")
ErrLoginSourceNotExist = errors.New("Login source does not exist") ErrLoginSourceNotExist = errors.New("Login source does not exist")
@ -349,8 +350,7 @@ func GetUserByKeyId(keyId int64) (*User, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
err = errors.New("not exist key owner") return nil, ErrUserNotKeyOwner
return nil, err
} }
return user, nil return user, nil
} }

View File

@ -10,6 +10,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"html/template" "html/template"
"runtime"
"strings" "strings"
"time" "time"
) )
@ -47,6 +48,9 @@ var mailDomains = map[string]string{
} }
var TemplateFuncs template.FuncMap = map[string]interface{}{ var TemplateFuncs template.FuncMap = map[string]interface{}{
"GoVer": func() string {
return runtime.Version()
},
"AppName": func() string { "AppName": func() string {
return AppName return AppName
}, },

View File

@ -15,7 +15,15 @@
</div> </div>
<div class="col-md-4"> <div class="col-md-4">
<p class="desc"><a href="http://gogs.io">Official Website</a></p> <p class="desc">
<a href="http://gogs.io">Official Website</a>
</p>
</div>
</div>
<div class="row">
<div class="col-md-6">
Go Version: {{GoVer}}
</div> </div>
</div> </div>
</div> </div>