Browse Source

Linting, vet, misspell, also update drone ci

Dashie der otter 1 year ago
parent
commit
0f93bfd75f
Signed by: Dashie <dashie@sigpipe.me> GPG Key ID: C2D57B325840B755
47 changed files with 479 additions and 301 deletions
  1. 3
    0
      .drone.yml
  2. 21
    2
      Makefile
  3. 7
    6
      cmd/web.go
  4. 2
    0
      context/auth.go
  5. 41
    38
      context/context.go
  6. 4
    0
      context/repo.go
  7. 1
    0
      context/user.go
  8. 3
    3
      git.txt.go
  9. 42
    2
      models/error.go
  10. 3
    0
      models/errors/repo.go
  11. 9
    0
      models/errors/user.go
  12. 29
    22
      models/gitxt.go
  13. 19
    9
      models/models.go
  14. 9
    6
      models/sshkey.go
  15. 38
    27
      models/user.go
  16. 3
    2
      routers/admin/admin.go
  17. 35
    30
      routers/gitxt/gitxt.go
  18. 1
    0
      routers/hub.go
  19. 1
    0
      routers/repo/archive.go
  20. 22
    17
      routers/repo/repo.go
  21. 32
    27
      routers/user/auth.go
  22. 5
    3
      routers/user/setting.go
  23. 31
    16
      setting/setting.go
  24. 1
    0
      stuff/auth/auth.go
  25. 1
    0
      stuff/cron/cron.go
  26. 4
    2
      stuff/form/auth.go
  27. 6
    5
      stuff/form/form.go
  28. 6
    3
      stuff/form/gitxt.go
  29. 2
    1
      stuff/form/user.go
  30. 29
    25
      stuff/gite/gite.go
  31. 17
    10
      stuff/mailer/mail.go
  32. 8
    1
      stuff/mailer/mailer.go
  33. 3
    3
      stuff/markup/markdown.go
  34. 6
    12
      stuff/markup/markup.go
  35. 6
    5
      stuff/repository/repository.go
  36. 2
    1
      stuff/sanitize/sanitize.go
  37. 1
    1
      stuff/sanitize/sanitize_test.go
  38. 1
    0
      stuff/template/highlight/highlight.go
  39. 12
    11
      stuff/template/template.go
  40. 1
    0
      stuff/tool/file.go
  41. 4
    3
      stuff/tool/tool.go
  42. 1
    1
      vendor/github.com/go-macaron/binding/multipart_test.go
  43. 2
    2
      vendor/github.com/go-xorm/xorm/engine.go
  44. 1
    1
      vendor/golang.org/x/net/http2/server_test.go
  45. 2
    2
      vendor/golang.org/x/text/encoding/internal/identifier/mib.go
  46. 1
    1
      vendor/gopkg.in/libgit2/git2go.v25/note.go
  47. 1
    1
      vendor/gopkg.in/libgit2/git2go.v25/odb.go

+ 3
- 0
.drone.yml View File

@@ -18,6 +18,9 @@ pipeline:
18 18
       - go get -u github.com/golang/dep/cmd/dep
19 19
       - dep ensure
20 20
       - make clean
21
+      - make vet
22
+      - make lint
23
+      - make misspell-check
21 24
       - make build
22 25
     when:
23 26
       event: [ push, tag, pull_request ]

+ 21
- 2
Makefile View File

@@ -8,8 +8,10 @@ DATA_FILES := $(shell find conf | sed 's/ /\\ /g')
8 8
 BUILD_FLAGS:=-o git_txt -v
9 9
 TAGS=sqlite
10 10
 NOW=$(shell date -u '+%Y%m%d%I%M%S')
11
-GOVET=go tool vet -composites=false -methods=false -structtags=false
11
+GOVET=go vet
12
+GOLINT=golint -set_exit_status
12 13
 
14
+GOFILES := $(shell find . -name "*.go" -type f ! -path "./vendor/*" ! -path "*/bindata.go")
13 15
 PACKAGES ?= $(filter-out dev.sigpipe.me/dashie/git.txt/integrations,$(shell go list ./... | grep -v /vendor/))
14 16
 
15 17
 .PHONY: build clean
@@ -21,9 +23,12 @@ check: test
21 23
 web: build
22 24
 	./git_txt web
23 25
 
24
-govet:
26
+vet:
25 27
 	$(GOVET) git.txt.go
26 28
 
29
+lint:
30
+	$(GOLINT) $(PACKAGES)
31
+
27 32
 build:
28 33
 	go build $(BUILD_FLAGS) -ldflags '$(LDFLAGS)' -tags '$(TAGS)'
29 34
 
@@ -41,3 +46,17 @@ clean-mac: clean
41 46
 
42 47
 test:
43 48
 	go test -cover -v $(PACKAGES)
49
+
50
+.PHONY: misspell-check
51
+misspell-check:
52
+	@hash misspell > /dev/null 2>&1; if [ $$? -ne 0 ]; then \
53
+		go get -u github.com/client9/misspell/cmd/misspell; \
54
+	fi
55
+	misspell -error -i unknwon $(GOFILES)
56
+
57
+.PHONY: misspell
58
+misspell:
59
+	@hash misspell > /dev/null 2>&1; if [ $$? -ne 0 ]; then \
60
+		go get -u github.com/client9/misspell/cmd/misspell; \
61
+	fi
62
+	misspell -w -i unknwon $(GOFILES)

+ 7
- 6
cmd/web.go View File

@@ -31,6 +31,7 @@ import (
31 31
 	"dev.sigpipe.me/dashie/git.txt/stuff/mailer"
32 32
 )
33 33
 
34
+// Web command
34 35
 var Web = cli.Command{
35 36
 	Name: "web",
36 37
 	Usage: "Start web server",
@@ -50,7 +51,7 @@ func newMacaron() *macaron.Macaron {
50 51
 
51 52
 	m.Use(macaron.Recovery())
52 53
 
53
-	if setting.Protocol == setting.SCHEME_FCGI {
54
+	if setting.Protocol == setting.SchemeFCGI {
54 55
 		m.SetURLPrefix(setting.AppSubURL)
55 56
 	}
56 57
 
@@ -212,7 +213,7 @@ func runWeb(ctx *cli.Context) error {
212 213
 	}
213 214
 
214 215
 	var listenAddr string
215
-	if setting.Protocol == setting.SCHEME_UNIX_SOCKET {
216
+	if setting.Protocol == setting.SchemeUnixSocket {
216 217
 		listenAddr = fmt.Sprintf("%s", setting.HTTPAddr)
217 218
 	} else {
218 219
 		listenAddr = fmt.Sprintf("%s:%s", setting.HTTPAddr, setting.HTTPPort)
@@ -221,13 +222,13 @@ func runWeb(ctx *cli.Context) error {
221 222
 
222 223
 	var err error
223 224
 	switch setting.Protocol {
224
-	case setting.SCHEME_HTTP:
225
+	case setting.SchemeHTTP:
225 226
 		err = http.ListenAndServe(listenAddr, m)
226
-	case setting.SCHEME_HTTPS:
227
+	case setting.SchemeHTTPS:
227 228
 		log.Fatal(2, "https not supported")
228
-	case setting.SCHEME_FCGI:
229
+	case setting.SchemeFCGI:
229 230
 		err = fcgi.Serve(nil, m)
230
-	case setting.SCHEME_UNIX_SOCKET:
231
+	case setting.SchemeUnixSocket:
231 232
 		os.Remove(listenAddr)
232 233
 
233 234
 		var listener *net.UnixListener

+ 2
- 0
context/auth.go View File

@@ -8,6 +8,7 @@ import (
8 8
 	log "gopkg.in/clog.v1"
9 9
 )
10 10
 
11
+// ToggleOptions struct
11 12
 type ToggleOptions struct {
12 13
 	SignInRequired  bool
13 14
 	SignOutRequired bool
@@ -16,6 +17,7 @@ type ToggleOptions struct {
16 17
 	AnonymousCreate bool
17 18
 }
18 19
 
20
+// Toggle options
19 21
 func Toggle(options *ToggleOptions) macaron.Handler {
20 22
 	return func(ctx *Context) {
21 23
 		// Redirect non-login pages from logged in user

+ 41
- 38
context/context.go View File

@@ -47,9 +47,9 @@ func (c *Context) PageIs(name string) {
47 47
 }
48 48
 
49 49
 // HTML responses template with given status.
50
-func (ctx *Context) HTML(status int, name string) {
50
+func (c *Context) HTML(status int, name string) {
51 51
 	log.Trace("Template: %s", name)
52
-	ctx.Context.HTML(status, name)
52
+	c.Context.HTML(status, name)
53 53
 }
54 54
 
55 55
 // Success responses template with status http.StatusOK.
@@ -63,45 +63,46 @@ func (c *Context) JSONSuccess(data interface{}) {
63 63
 }
64 64
 
65 65
 // HasError returns true if error occurs in form validation.
66
-func (ctx *Context) HasError() bool {
67
-	hasErr, ok := ctx.Data["HasError"]
66
+func (c *Context) HasError() bool {
67
+	hasErr, ok := c.Data["HasError"]
68 68
 	if !ok {
69 69
 		return false
70 70
 	}
71
-	ctx.Flash.ErrorMsg = ctx.Data["ErrorMsg"].(string)
72
-	ctx.Data["Flash"] = ctx.Flash
71
+	c.Flash.ErrorMsg = c.Data["ErrorMsg"].(string)
72
+	c.Data["Flash"] = c.Flash
73 73
 	return hasErr.(bool)
74 74
 }
75 75
 
76 76
 // RenderWithErr used for page has form validation but need to prompt error to users.
77
-func (ctx *Context) RenderWithErr(msg, tpl string, f interface{}) {
77
+func (c *Context) RenderWithErr(msg, tpl string, f interface{}) {
78 78
 	if f != nil {
79
-		form.Assign(f, ctx.Data)
79
+		form.Assign(f, c.Data)
80 80
 	}
81
-	ctx.Flash.ErrorMsg = msg
82
-	ctx.Data["Flash"] = ctx.Flash
83
-	ctx.HTML(http.StatusOK, tpl)
81
+	c.Flash.ErrorMsg = msg
82
+	c.Data["Flash"] = c.Flash
83
+	c.HTML(http.StatusOK, tpl)
84 84
 }
85 85
 
86 86
 // Handle handles and logs error by given status.
87
-func (ctx *Context) Handle(status int, title string, err error) {
87
+func (c *Context) Handle(status int, title string, err error) {
88 88
 	switch status {
89 89
 	case http.StatusNotFound:
90
-		ctx.Data["Title"] = ctx.Tr("error.page_not_found")
90
+		c.Data["Title"] = c.Tr("error.page_not_found")
91 91
 	case http.StatusInternalServerError:
92
-		ctx.Data["Title"] = ctx.Tr("internal_server_error")
92
+		c.Data["Title"] = c.Tr("internal_server_error")
93 93
 		log.Error(2, "%s: %v", title, err)
94 94
 	}
95
-	ctx.HTML(status, fmt.Sprintf("status/%d", status))
95
+	c.HTML(status, fmt.Sprintf("status/%d", status))
96 96
 }
97 97
 
98
-func (ctx *Context) HandleText(status int, title string) {
99
-	ctx.PlainText(status, []byte(title))
98
+// HandleText only
99
+func (c *Context) HandleText(status int, title string) {
100
+	c.PlainText(status, []byte(title))
100 101
 }
101 102
 
102 103
 // NotFound renders the 404 page.
103
-func (ctx *Context) NotFound() {
104
-	ctx.Handle(http.StatusNotFound, "", nil)
104
+func (c *Context) NotFound() {
105
+	c.Handle(http.StatusNotFound, "", nil)
105 106
 }
106 107
 
107 108
 // ServerError renders the 500 page.
@@ -109,7 +110,7 @@ func (c *Context) ServerError(title string, err error) {
109 110
 	c.Handle(http.StatusInternalServerError, title, err)
110 111
 }
111 112
 
112
-// SubURLRedirect responses redirection wtih given location and status.
113
+// SubURLRedirect responses redirection with given location and status.
113 114
 // It prepends setting.AppSubURL to the location string.
114 115
 func (c *Context) SubURLRedirect(location string, status ...int) {
115 116
 	c.Redirect(setting.AppSubURL + location)
@@ -126,7 +127,8 @@ func (c *Context) NotFoundOrServerError(title string, errck func(error) bool, er
126 127
 	c.ServerError(title, err)
127 128
 }
128 129
 
129
-func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{}) {
130
+// ServeContent headers
131
+func (c *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{}) {
130 132
 	modtime := time.Now()
131 133
 	for _, p := range params {
132 134
 		switch v := p.(type) {
@@ -134,17 +136,18 @@ func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interfa
134 136
 			modtime = v
135 137
 		}
136 138
 	}
137
-	ctx.Resp.Header().Set("Content-Description", "File Transfer")
138
-	ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
139
-	ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+name)
140
-	ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary")
141
-	ctx.Resp.Header().Set("Expires", "0")
142
-	ctx.Resp.Header().Set("Cache-Control", "must-revalidate")
143
-	ctx.Resp.Header().Set("Pragma", "public")
144
-	http.ServeContent(ctx.Resp, ctx.Req.Request, name, modtime, r)
145
-}
146
-
147
-func (ctx *Context) ServeContentNoDownload(name string, mime string, r io.ReadSeeker, params ...interface{}) {
139
+	c.Resp.Header().Set("Content-Description", "File Transfer")
140
+	c.Resp.Header().Set("Content-Type", "application/octet-stream")
141
+	c.Resp.Header().Set("Content-Disposition", "attachment; filename="+name)
142
+	c.Resp.Header().Set("Content-Transfer-Encoding", "binary")
143
+	c.Resp.Header().Set("Expires", "0")
144
+	c.Resp.Header().Set("Cache-Control", "must-revalidate")
145
+	c.Resp.Header().Set("Pragma", "public")
146
+	http.ServeContent(c.Resp, c.Req.Request, name, modtime, r)
147
+}
148
+
149
+// ServeContentNoDownload headers
150
+func (c *Context) ServeContentNoDownload(name string, mime string, r io.ReadSeeker, params ...interface{}) {
148 151
 	modtime := time.Now()
149 152
 	for _, p := range params {
150 153
 		switch v := p.(type) {
@@ -152,12 +155,12 @@ func (ctx *Context) ServeContentNoDownload(name string, mime string, r io.ReadSe
152 155
 			modtime = v
153 156
 		}
154 157
 	}
155
-	ctx.Resp.Header().Set("Content-Description", "File Content")
156
-	ctx.Resp.Header().Set("Content-Type", mime)
157
-	ctx.Resp.Header().Set("Expires", "0")
158
-	ctx.Resp.Header().Set("Cache-Control", "must-revalidate")
159
-	ctx.Resp.Header().Set("Pragma", "public")
160
-	http.ServeContent(ctx.Resp, ctx.Req.Request, name, modtime, r)
158
+	c.Resp.Header().Set("Content-Description", "File Content")
159
+	c.Resp.Header().Set("Content-Type", mime)
160
+	c.Resp.Header().Set("Expires", "0")
161
+	c.Resp.Header().Set("Cache-Control", "must-revalidate")
162
+	c.Resp.Header().Set("Pragma", "public")
163
+	http.ServeContent(c.Resp, c.Req.Request, name, modtime, r)
161 164
 }
162 165
 
163 166
 // Contexter initializes a classic context for a request.

+ 4
- 0
context/repo.go View File

@@ -10,6 +10,7 @@ import (
10 10
 	log "gopkg.in/clog.v1"
11 11
 )
12 12
 
13
+// Gitxt struct
13 14
 type Gitxt struct {
14 15
 	User	*models.User
15 16
 	Gitxt	*models.Gitxt
@@ -17,6 +18,7 @@ type Gitxt struct {
17 18
 	UserName	string
18 19
 }
19 20
 
21
+// AssignRepository to context
20 22
 func AssignRepository() macaron.Handler {
21 23
 	return func(ctx *Context) {
22 24
 		userName := ctx.Params("user")
@@ -41,6 +43,7 @@ func AssignRepository() macaron.Handler {
41 43
 	}
42 44
 }
43 45
 
46
+// GitUACheck User Agent check
44 47
 func GitUACheck() macaron.Handler {
45 48
 	return func(ctx *Context) {
46 49
 		if strings.HasPrefix(strings.Join(ctx.Req.Header["User-Agent"], ""), "git/") {
@@ -51,6 +54,7 @@ func GitUACheck() macaron.Handler {
51 54
 	}
52 55
 }
53 56
 
57
+// CheckRepoExpiry and handle
54 58
 func CheckRepoExpiry() macaron.Handler {
55 59
 	return func(ctx *Context) {
56 60
 		if ctx.Gitxt.Gitxt.ExpiryHours > 0 && ctx.Gitxt.Gitxt.ExpiryUnix <= time.Now().Unix() {

+ 1
- 0
context/user.go View File

@@ -6,6 +6,7 @@ import (
6 6
 	"dev.sigpipe.me/dashie/git.txt/models/errors"
7 7
 )
8 8
 
9
+// AssignUser to context
9 10
 func AssignUser() macaron.Handler {
10 11
 	return func(ctx *Context) {
11 12
 		userName := ctx.Params("user")

+ 3
- 3
git.txt.go View File

@@ -9,10 +9,10 @@ import (
9 9
 	"fmt"
10 10
 )
11 11
 
12
-const APP_VER = "0.2"
12
+const appVersion = "0.2"
13 13
 
14 14
 func init() {
15
-	setting.AppVer = APP_VER
15
+	setting.AppVer = appVersion
16 16
 	if os.Getenv("USE_RAVEN") == "true" {
17 17
 		raven.SetDSN(os.Getenv("RAVEN_DSN"))
18 18
 		fmt.Printf("Using Raven with DSN: %s\r\n", os.Getenv("RAVEN_DSN"))
@@ -25,7 +25,7 @@ func main() {
25 25
 	app := cli.NewApp()
26 26
 	app.Name = "git.txt"
27 27
 	app.Usage = "paste stuff to the interweb with git backend"
28
-	app.Version = APP_VER
28
+	app.Version = appVersion
29 29
 	app.Commands = []cli.Command{
30 30
 		cmd.Web,
31 31
 	}

+ 42
- 2
models/error.go View File

@@ -8,28 +8,34 @@ import (
8 8
 	"fmt"
9 9
 )
10 10
 
11
+// ErrNameReserved struct
11 12
 type ErrNameReserved struct {
12 13
 	Name string
13 14
 }
14 15
 
16
+// IsErrNameReserved func
15 17
 func IsErrNameReserved(err error) bool {
16 18
 	_, ok := err.(ErrNameReserved)
17 19
 	return ok
18 20
 }
19 21
 
22
+// Error func
20 23
 func (err ErrNameReserved) Error() string {
21 24
 	return fmt.Sprintf("name is reserved [name: %s]", err.Name)
22 25
 }
23 26
 
27
+// ErrNamePatternNotAllowed struct
24 28
 type ErrNamePatternNotAllowed struct {
25 29
 	Pattern string
26 30
 }
27 31
 
32
+// IsErrNamePatternNotAllowed func
28 33
 func IsErrNamePatternNotAllowed(err error) bool {
29 34
 	_, ok := err.(ErrNamePatternNotAllowed)
30 35
 	return ok
31 36
 }
32 37
 
38
+// Error func
33 39
 func (err ErrNamePatternNotAllowed) Error() string {
34 40
 	return fmt.Sprintf("name pattern is not allowed [pattern: %s]", err.Pattern)
35 41
 }
@@ -41,41 +47,50 @@ func (err ErrNamePatternNotAllowed) Error() string {
41 47
 // |______//____  >\___  >__|
42 48
 //              \/     \/
43 49
 
50
+// ErrUserAlreadyExist struct
44 51
 type ErrUserAlreadyExist struct {
45 52
 	Name string
46 53
 }
47 54
 
55
+// IsErrUserAlreadyExist func
48 56
 func IsErrUserAlreadyExist(err error) bool {
49 57
 	_, ok := err.(ErrUserAlreadyExist)
50 58
 	return ok
51 59
 }
52 60
 
61
+// Error func
53 62
 func (err ErrUserAlreadyExist) Error() string {
54 63
 	return fmt.Sprintf("user already exists [name: %s]", err.Name)
55 64
 }
56 65
 
66
+// ErrEmailAlreadyUsed struct
57 67
 type ErrEmailAlreadyUsed struct {
58 68
 	Email string
59 69
 }
60 70
 
71
+// IsErrEmailAlreadyUsed func
61 72
 func IsErrEmailAlreadyUsed(err error) bool {
62 73
 	_, ok := err.(ErrEmailAlreadyUsed)
63 74
 	return ok
64 75
 }
65 76
 
77
+// Error func
66 78
 func (err ErrEmailAlreadyUsed) Error() string {
67 79
 	return fmt.Sprintf("e-mail has been used [email: %s]", err.Email)
68 80
 }
69 81
 
82
+// ErrUserOwnRepos struct
70 83
 type ErrUserOwnRepos struct {
71 84
 	UID int64
72 85
 }
73 86
 
87
+// IsErrUserOwnRepos func
74 88
 func IsErrUserOwnRepos(err error) bool {
75 89
 	_, ok := err.(ErrUserOwnRepos)
76 90
 	return ok
77 91
 }
78 92
 
93
+// Error func
79 94
 func (err ErrUserOwnRepos) Error() string {
80 95
 	return fmt.Sprintf("user still has ownership of repositories [uid: %d]", err.UID)
81 96
 }
@@ -87,131 +102,156 @@ func (err ErrUserOwnRepos) Error() string {
87 102
 //  |____|   |____/|___  /____/__|\___  > |____|__ \___  > ____|
88 103
 //                     \/             \/          \/   \/\/
89 104
 
105
+// ErrKeyUnableVerify struct
90 106
 type ErrKeyUnableVerify struct {
91 107
 	Result string
92 108
 }
93 109
 
110
+// IsErrKeyUnableVerify func
94 111
 func IsErrKeyUnableVerify(err error) bool {
95 112
 	_, ok := err.(ErrKeyUnableVerify)
96 113
 	return ok
97 114
 }
98 115
 
116
+// Error func
99 117
 func (err ErrKeyUnableVerify) Error() string {
100 118
 	return fmt.Sprintf("Unable to verify key content [result: %s]", err.Result)
101 119
 }
102 120
 
121
+// ErrKeyNotExist struct
103 122
 type ErrKeyNotExist struct {
104 123
 	ID int64
105 124
 }
106 125
 
126
+// IsErrKeyNotExist func
107 127
 func IsErrKeyNotExist(err error) bool {
108 128
 	_, ok := err.(ErrKeyNotExist)
109 129
 	return ok
110 130
 }
111 131
 
132
+// Error func
112 133
 func (err ErrKeyNotExist) Error() string {
113 134
 	return fmt.Sprintf("public key does not exist [id: %d]", err.ID)
114 135
 }
115 136
 
137
+// ErrKeyAlreadyExist struct
116 138
 type ErrKeyAlreadyExist struct {
117 139
 	OwnerID int64
118 140
 	Content string
119 141
 }
120 142
 
143
+// IsErrKeyAlreadyExist func
121 144
 func IsErrKeyAlreadyExist(err error) bool {
122 145
 	_, ok := err.(ErrKeyAlreadyExist)
123 146
 	return ok
124 147
 }
125 148
 
149
+// Error func
126 150
 func (err ErrKeyAlreadyExist) Error() string {
127 151
 	return fmt.Sprintf("public key already exists [owner_id: %d, content: %s]", err.OwnerID, err.Content)
128 152
 }
129 153
 
154
+// ErrKeyNameAlreadyUsed struct
130 155
 type ErrKeyNameAlreadyUsed struct {
131 156
 	OwnerID int64
132 157
 	Name    string
133 158
 }
134 159
 
160
+// IsErrKeyNameAlreadyUsed func
135 161
 func IsErrKeyNameAlreadyUsed(err error) bool {
136 162
 	_, ok := err.(ErrKeyNameAlreadyUsed)
137 163
 	return ok
138 164
 }
139 165
 
166
+// Error func
140 167
 func (err ErrKeyNameAlreadyUsed) Error() string {
141 168
 	return fmt.Sprintf("public key already exists [owner_id: %d, name: %s]", err.OwnerID, err.Name)
142 169
 }
143 170
 
171
+// ErrKeyAccessDenied struct
144 172
 type ErrKeyAccessDenied struct {
145 173
 	UserID int64
146 174
 	KeyID  int64
147 175
 	Note   string
148 176
 }
149 177
 
178
+// IsErrKeyAccessDenied func
150 179
 func IsErrKeyAccessDenied(err error) bool {
151 180
 	_, ok := err.(ErrKeyAccessDenied)
152 181
 	return ok
153 182
 }
154 183
 
184
+// Error func
155 185
 func (err ErrKeyAccessDenied) Error() string {
156 186
 	return fmt.Sprintf("user does not have access to the key [user_id: %d, key_id: %d, note: %s]",
157 187
 		err.UserID, err.KeyID, err.Note)
158 188
 }
159 189
 
190
+// ErrDeployKeyNotExist struct
160 191
 type ErrDeployKeyNotExist struct {
161 192
 	ID     int64
162 193
 	KeyID  int64
163 194
 	RepoID int64
164 195
 }
165 196
 
197
+// IsErrDeployKeyNotExist func
166 198
 func IsErrDeployKeyNotExist(err error) bool {
167 199
 	_, ok := err.(ErrDeployKeyNotExist)
168 200
 	return ok
169 201
 }
170 202
 
203
+// Error func
171 204
 func (err ErrDeployKeyNotExist) Error() string {
172 205
 	return fmt.Sprintf("Deploy key does not exist [id: %d, key_id: %d, repo_id: %d]", err.ID, err.KeyID, err.RepoID)
173 206
 }
174 207
 
208
+// ErrDeployKeyAlreadyExist struct
175 209
 type ErrDeployKeyAlreadyExist struct {
176 210
 	KeyID  int64
177 211
 	RepoID int64
178 212
 }
179 213
 
214
+// IsErrDeployKeyAlreadyExist func
180 215
 func IsErrDeployKeyAlreadyExist(err error) bool {
181 216
 	_, ok := err.(ErrDeployKeyAlreadyExist)
182 217
 	return ok
183 218
 }
184 219
 
220
+// Error func
185 221
 func (err ErrDeployKeyAlreadyExist) Error() string {
186 222
 	return fmt.Sprintf("public key already exists [key_id: %d, repo_id: %d]", err.KeyID, err.RepoID)
187 223
 }
188 224
 
225
+// ErrDeployKeyNameAlreadyUsed struct
189 226
 type ErrDeployKeyNameAlreadyUsed struct {
190 227
 	RepoID int64
191 228
 	Name   string
192 229
 }
193 230
 
231
+// IsErrDeployKeyNameAlreadyUsed func
194 232
 func IsErrDeployKeyNameAlreadyUsed(err error) bool {
195 233
 	_, ok := err.(ErrDeployKeyNameAlreadyUsed)
196 234
 	return ok
197 235
 }
198 236
 
237
+// Error func
199 238
 func (err ErrDeployKeyNameAlreadyUsed) Error() string {
200 239
 	return fmt.Sprintf("public key already exists [repo_id: %d, name: %s]", err.RepoID, err.Name)
201 240
 }
202 241
 
203 242
 
204
-// Gitxt
243
+// ErrHashAlreadyExist struct
205 244
 type ErrHashAlreadyExist struct {
206 245
 	Hash string
207 246
 }
208 247
 
248
+// IsErrHashAlreadyExist func
209 249
 func IsErrHashAlreadyExist(err error) bool {
210 250
 	_, ok := err.(ErrHashAlreadyExist)
211 251
 	return ok
212 252
 }
213 253
 
214
-
254
+// Error func
215 255
 func (err ErrHashAlreadyExist) Error() string {
216 256
 	return fmt.Sprintf("hash already exists [hash: %s]", err.Hash)
217 257
 }

+ 3
- 0
models/errors/repo.go View File

@@ -2,17 +2,20 @@ package errors
2 2
 
3 3
 import "fmt"
4 4
 
5
+// RepoNotExist struct
5 6
 type RepoNotExist struct {
6 7
 	ID     int64
7 8
 	UserID   int64
8 9
 	Name   string
9 10
 }
10 11
 
12
+// IsRepoNotExist func
11 13
 func IsRepoNotExist(err error) bool {
12 14
 	_, ok := err.(RepoNotExist)
13 15
 	return ok
14 16
 }
15 17
 
18
+// Error func
16 19
 func (err RepoNotExist) Error() string {
17 20
 	return fmt.Sprintf("repository does not exist [id: %d, user_id: %d, name: %s]", err.ID, err.UserID, err.Name)
18 21
 }

+ 9
- 0
models/errors/user.go View File

@@ -6,40 +6,49 @@ package errors
6 6
 
7 7
 import "fmt"
8 8
 
9
+// EmptyName struct
9 10
 type EmptyName struct{}
10 11
 
12
+// IsEmptyName func
11 13
 func IsEmptyName(err error) bool {
12 14
 	_, ok := err.(EmptyName)
13 15
 	return ok
14 16
 }
15 17
 
18
+// Error func
16 19
 func (err EmptyName) Error() string {
17 20
 	return "empty name"
18 21
 }
19 22
 
23
+// UserNotExist struct
20 24
 type UserNotExist struct {
21 25
 	UserID int64
22 26
 	Name   string
23 27
 }
24 28
 
29
+// IsUserNotExist func
25 30
 func IsUserNotExist(err error) bool {
26 31
 	_, ok := err.(UserNotExist)
27 32
 	return ok
28 33
 }
29 34
 
35
+// Error func
30 36
 func (err UserNotExist) Error() string {
31 37
 	return fmt.Sprintf("user does not exist [user_id: %d, name: %s]", err.UserID, err.Name)
32 38
 }
33 39
 
40
+// UserNotKeyOwner struct
34 41
 type UserNotKeyOwner struct {
35 42
 	KeyID int64
36 43
 }
37 44
 
45
+// IsUserNotKeyOwner func
38 46
 func IsUserNotKeyOwner(err error) bool {
39 47
 	_, ok := err.(UserNotKeyOwner)
40 48
 	return ok
41 49
 }
42 50
 
51
+// Error func
43 52
 func (err UserNotKeyOwner) Error() string {
44 53
 	return fmt.Sprintf("user is not the owner of public key [key_id: %d]", err.KeyID)
45 54
 }

+ 29
- 22
models/gitxt.go View File

@@ -16,6 +16,7 @@ import (
16 16
 	"os/exec"
17 17
 )
18 18
 
19
+// Gitxt struct
19 20
 type Gitxt struct {
20 21
 	ID          int64        `xorm:"pk autoincr"`
21 22
 	Hash        string        `xorm:"UNIQUE NOT NULL"`
@@ -23,7 +24,7 @@ type Gitxt struct {
23 24
 	Anonymous   bool
24 25
 	Description string        `xorm:"TEXT"`
25 26
 
26
-	// Choosen expiry in hours
27
+	// Chosen expiry in hours
27 28
 	ExpiryHours		int64  `xorm:"INDEX"`
28 29
 	// Calculated expiry unix timestamp from the time of creation/update
29 30
 	ExpiryUnix	int64
@@ -41,26 +42,30 @@ type Gitxt struct {
41 42
 	// 	UserID
42 43
 }
43 44
 
45
+// BeforeInsert hooks
44 46
 func (gitxt *Gitxt) BeforeInsert() {
45 47
 	gitxt.CreatedUnix = time.Now().Unix()
46 48
 	gitxt.UpdatedUnix = gitxt.CreatedUnix
47 49
 }
48 50
 
51
+// BeforeUpdate hooks
49 52
 func (gitxt *Gitxt) BeforeUpdate() {
50 53
 	gitxt.UpdatedUnix = time.Now().Unix()
51 54
 }
52 55
 
53
-func (g *Gitxt) AfterSet(colName string, _ xorm.Cell) {
56
+// AfterSet hooks
57
+func (gitxt *Gitxt) AfterSet(colName string, _ xorm.Cell) {
54 58
 	switch colName {
55 59
 	case "created_unix":
56
-		g.Created = time.Unix(g.CreatedUnix, 0).Local()
60
+		gitxt.Created = time.Unix(gitxt.CreatedUnix, 0).Local()
57 61
 	case "updated_unix":
58
-		g.Updated = time.Unix(g.UpdatedUnix, 0).Local()
62
+		gitxt.Updated = time.Unix(gitxt.UpdatedUnix, 0).Local()
59 63
 	case "expiry_unix":
60
-		g.Expiry = time.Unix(g.ExpiryUnix, 0).Local()
64
+		gitxt.Expiry = time.Unix(gitxt.ExpiryUnix, 0).Local()
61 65
 	}
62 66
 }
63 67
 
68
+// GitxtWithUser struct
64 69
 type GitxtWithUser struct {
65 70
 	User        `xorm:"extends"`
66 71
 	Gitxt        `xorm:"extends"`
@@ -70,8 +75,8 @@ type GitxtWithUser struct {
70 75
 var taskStatusTable = sync.NewStatusTable()
71 76
 
72 77
 const (
73
-	_CLEAN_OLD_ARCHIVES = "clean_old_archives"
74
-	_DELETE_EXPIRED_REPOSITORIES = "delete_expired_repositories"
78
+	cleanOldArchives          = "clean_old_archives"
79
+	deleteExpiredRepositories = "delete_expired_repositories"
75 80
 )
76 81
 
77 82
 // IsHashUsed checks if given hash exist,
@@ -82,7 +87,7 @@ func IsHashUsed(uid int64, hash string) (bool, error) {
82 87
 	return x.Get(&Gitxt{Hash: hash})
83 88
 }
84 89
 
85
-// Create a new gitxt
90
+// CreateGitxt Create a new gitxt
86 91
 func CreateGitxt(g *Gitxt) (err error) {
87 92
 	isExist, err := IsHashUsed(0, g.Hash)
88 93
 	if err != nil {
@@ -131,6 +136,7 @@ func GetRepositoryByName(user string, name string) (*Gitxt, error) {
131 136
 	return repo, nil
132 137
 }
133 138
 
139
+// GitxtOptions struct
134 140
 type GitxtOptions struct {
135 141
 	UserID      int64
136 142
 	WithPrivate bool
@@ -139,7 +145,7 @@ type GitxtOptions struct {
139 145
 	PageSize    int
140 146
 }
141 147
 
142
-// Get gitxts
148
+// GetGitxts Get gitxts
143 149
 func GetGitxts(opts *GitxtOptions) (gitxts []*GitxtWithUser, _ int64, _ error) {
144 150
 	if opts.Page <= 0 {
145 151
 		opts.Page = 1
@@ -176,23 +182,24 @@ func updateGitxt(e Engine, u *Gitxt) error {
176 182
 	return err
177 183
 }
178 184
 
185
+// UpdateGitxt with infos
179 186
 func UpdateGitxt(u *Gitxt) error {
180 187
 	return updateGitxt(x, u)
181 188
 }
182 189
 
183
-// Delete expired
190
+// DeleteExpiredRepositories Delete expired
184 191
 func DeleteExpiredRepositories() {
185
-	if taskStatusTable.IsRunning(_DELETE_EXPIRED_REPOSITORIES) {
192
+	if taskStatusTable.IsRunning(deleteExpiredRepositories) {
186 193
 		return
187 194
 	}
188
-	taskStatusTable.Start(_DELETE_EXPIRED_REPOSITORIES)
189
-	defer taskStatusTable.Stop(_DELETE_EXPIRED_REPOSITORIES)
195
+	taskStatusTable.Start(deleteExpiredRepositories)
196
+	defer taskStatusTable.Stop(deleteExpiredRepositories)
190 197
 
191 198
 	log.Trace("Doing: DeleteExpiredRepositories")
192 199
 
193 200
 	type GitxtExpired struct {
194
-		userId int64
195
-		repoId int64
201
+		userID int64
202
+		repoID int64
196 203
 		hash   string
197 204
 	}
198 205
 	expired := []GitxtExpired{}
@@ -211,9 +218,9 @@ func DeleteExpiredRepositories() {
211 218
 	}
212 219
 
213 220
 	for _, tc := range expired {
214
-		err := DeleteRepository(tc.userId, tc.repoId)
221
+		err := DeleteRepository(tc.userID, tc.repoID)
215 222
 		if err != nil {
216
-			log.Warn("Error removing repository %i/%i: %v", tc.userId, tc.repoId, err)
223
+			log.Warn("Error removing repository %i/%i: %v", tc.userID, tc.repoID, err)
217 224
 		} else {
218 225
 			log.Trace("Deleted repository %s", tc.hash)
219 226
 		}
@@ -221,13 +228,13 @@ func DeleteExpiredRepositories() {
221 228
 	}
222 229
 }
223 230
 
224
-// Archive deletion
231
+// DeleteOldRepositoryArchives Archive deletion
225 232
 func DeleteOldRepositoryArchives() {
226
-	if taskStatusTable.IsRunning(_CLEAN_OLD_ARCHIVES) {
233
+	if taskStatusTable.IsRunning(cleanOldArchives) {
227 234
 		return
228 235
 	}
229
-	taskStatusTable.Start(_CLEAN_OLD_ARCHIVES)
230
-	defer taskStatusTable.Stop(_CLEAN_OLD_ARCHIVES)
236
+	taskStatusTable.Start(cleanOldArchives)
237
+	defer taskStatusTable.Stop(cleanOldArchives)
231 238
 
232 239
 	log.Trace("Doing: DeleteOldRepositoryArchives")
233 240
 
@@ -296,7 +303,7 @@ func removeRepository(path string) {
296 303
 	}
297 304
 }
298 305
 
299
-// Delete repository :'(
306
+// DeleteRepository Delete repository :'(
300 307
 func DeleteRepository(ownerID int64, repoID int64) error {
301 308
 	repo := &Gitxt{ID: repoID, UserID: ownerID}
302 309
 	has, err := x.Get(repo)

+ 19
- 9
models/models.go View File

@@ -1,8 +1,11 @@
1 1
 package models
2 2
 
3 3
 import (
4
+	// msssql
4 5
 	_ "github.com/denisenkom/go-mssqldb"
6
+	// mysql
5 7
 	_ "github.com/go-sql-driver/mysql"
8
+	// Postgresql
6 9
 	_ "github.com/lib/pq"
7 10
 	"github.com/go-xorm/xorm"
8 11
 	"database/sql"
@@ -33,6 +36,7 @@ type Engine interface {
33 36
 	Where(interface{}, ...interface{}) *xorm.Session
34 37
 }
35 38
 
39
+// Vars
36 40
 var (
37 41
 	x         *xorm.Engine
38 42
 	tables    []interface{}
@@ -47,7 +51,7 @@ var (
47 51
 
48 52
 func init() {
49 53
 	tables = append(tables,
50
-		new(User), new(SshKey), new(Gitxt))
54
+		new(User), new(SSHKey), new(Gitxt))
51 55
 
52 56
 	gonicNames := []string{"SSL"}
53 57
 	for _, name := range gonicNames {
@@ -55,6 +59,7 @@ func init() {
55 59
 	}
56 60
 }
57 61
 
62
+// LoadConfigs to init db
58 63
 func LoadConfigs() {
59 64
 	sec := setting.Cfg.Section("database")
60 65
 	DbCfg.Type = sec.Key("DB_TYPE").String()
@@ -109,7 +114,7 @@ func parseMSSQLHostPort(info string) (string, string) {
109 114
 
110 115
 func getEngine() (*xorm.Engine, error) {
111 116
 	connStr := ""
112
-	var Param string = "?"
117
+	var Param = "?"
113 118
 	if strings.Contains(DbCfg.Name, Param) {
114 119
 		Param = "&"
115 120
 	}
@@ -136,32 +141,34 @@ func getEngine() (*xorm.Engine, error) {
136 141
 		connStr = fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;", host, port, DbCfg.Name, DbCfg.User, DbCfg.Passwd)
137 142
 	case "sqlite3":
138 143
 		if !EnableSQLite3 {
139
-			return nil, errors.New("This binary version does not build support for SQLite3.")
144
+			return nil, errors.New("this binary version does not build support for SQLite3")
140 145
 		}
141 146
 		if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {
142
-			return nil, fmt.Errorf("Fail to create directories: %v", err)
147
+			return nil, fmt.Errorf("fail to create directories: %v", err)
143 148
 		}
144 149
 		connStr = "file:" + DbCfg.Path + "?cache=shared&mode=rwc"
145 150
 	default:
146
-		return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type)
151
+		return nil, fmt.Errorf("unknown database type: %s", DbCfg.Type)
147 152
 	}
148 153
 	return xorm.NewEngine(DbCfg.Type, connStr)
149 154
 }
150 155
 
156
+// NewTestEngine to test
151 157
 func NewTestEngine(x *xorm.Engine) (err error) {
152 158
 	x, err = getEngine()
153 159
 	if err != nil {
154
-		return fmt.Errorf("Connect to database: %v", err)
160
+		return fmt.Errorf("connect to database: %v", err)
155 161
 	}
156 162
 
157 163
 	x.SetMapper(core.GonicMapper{})
158 164
 	return x.StoreEngine("InnoDB").Sync2(tables...)
159 165
 }
160 166
 
167
+// SetEngine to use
161 168
 func SetEngine() (err error) {
162 169
 	x, err = getEngine()
163 170
 	if err != nil {
164
-		return fmt.Errorf("Fail to connect to database: %v", err)
171
+		return fmt.Errorf("fail to connect to database: %v", err)
165 172
 	}
166 173
 
167 174
 	x.SetMapper(core.GonicMapper{})
@@ -177,7 +184,7 @@ func SetEngine() (err error) {
177 184
 			MaxDays: sec.Key("MAX_DAYS").MustInt64(3),
178 185
 		})
179 186
 	if err != nil {
180
-		return fmt.Errorf("Fail to create 'xorm.log': %v", err)
187
+		return fmt.Errorf("fail to create 'xorm.log': %v", err)
181 188
 	}
182 189
 
183 190
 	x.SetLogger(xorm.NewSimpleLogger3(logger, xorm.DEFAULT_LOG_PREFIX, xorm.DEFAULT_LOG_FLAG, core.LOG_DEBUG))
@@ -185,6 +192,7 @@ func SetEngine() (err error) {
185 192
 	return nil
186 193
 }
187 194
 
195
+// NewEngine to use
188 196
 func NewEngine() (err error) {
189 197
 	if err = SetEngine(); err != nil {
190 198
 		return err
@@ -193,16 +201,18 @@ func NewEngine() (err error) {
193 201
 	// TODO: here do migrations if any
194 202
 
195 203
 	if err = x.StoreEngine("InnoDB").Sync2(tables...); err != nil {
196
-		return fmt.Errorf("sync database struct error: %v\n", err)
204
+		return fmt.Errorf("sync database struct error: %v", err)
197 205
 	}
198 206
 
199 207
 	return nil
200 208
 }
201 209
 
210
+// Ping pong
202 211
 func Ping() error {
203 212
 	return x.Ping()
204 213
 }
205 214
 
215
+// InitDb from config
206 216
 func InitDb() {
207 217
 	LoadConfigs()
208 218
 

+ 9
- 6
models/sshkey.go View File

@@ -4,7 +4,8 @@ import (
4 4
 	"time"
5 5
 )
6 6
 
7
-type SshKey struct {
7
+// SSHKey struct
8
+type SSHKey struct {
8 9
 	ID		int64	`xorm:"pk autoincr"`
9 10
 	UserID		int64	`xorm:"INDEX NOT NULL"`
10 11
 
@@ -23,11 +24,13 @@ type SshKey struct {
23 24
 	// 	UserID
24 25
 }
25 26
 
26
-func (ssh_key *SshKey) BeforeInsert() {
27
-	ssh_key.CreatedUnix = time.Now().Unix()
28
-	ssh_key.UpdatedUnix = ssh_key.CreatedUnix
27
+// BeforeInsert hooks
28
+func (sshKey *SSHKey) BeforeInsert() {
29
+	sshKey.CreatedUnix = time.Now().Unix()
30
+	sshKey.UpdatedUnix = sshKey.CreatedUnix
29 31
 }
30 32
 
31
-func (ssh_key *SshKey) BeforeUpdate() {
32
-	ssh_key.UpdatedUnix = time.Now().Unix()
33
+// BeforeUpdate hooks
34
+func (sshKey *SSHKey) BeforeUpdate() {
35
+	sshKey.UpdatedUnix = time.Now().Unix()
33 36
 }

+ 38
- 27
models/user.go View File

@@ -19,6 +19,7 @@ import (
19 19
 	"dev.sigpipe.me/dashie/git.txt/stuff/mailer"
20 20
 )
21 21
 
22
+// User struct
22 23
 type User struct {
23 24
 	ID		int64	`xorm:"pk autoincr"`
24 25
 	UserName	string	`xorm:"UNIQUE NOT NULL"`
@@ -43,11 +44,13 @@ type User struct {
43 44
 	// 	SshKeys
44 45
 }
45 46
 
47
+// BeforeInsert hooks
46 48
 func (user *User) BeforeInsert() {
47 49
 	user.CreatedUnix = time.Now().Unix()
48 50
 	user.UpdatedUnix = user.CreatedUnix
49 51
 }
50 52
 
53
+// BeforeUpdate hooks
51 54
 func (user *User) BeforeUpdate() {
52 55
 	user.UpdatedUnix = time.Now().Unix()
53 56
 }
@@ -153,21 +156,22 @@ func isUsableName(names, patterns []string, name string) error {
153 156
 	return nil
154 157
 }
155 158
 
159
+// IsUsableUsername or not
156 160
 func IsUsableUsername(name string) error {
157 161
 	return isUsableName(reservedUsernames, reservedUserPatterns, name)
158 162
 }
159 163
 
160 164
 // EncodePasswd encodes password to safe format.
161
-func (u *User) EncodePasswd() {
162
-	newPasswd := pbkdf2.Key([]byte(u.Password), []byte(u.Salt), 10000, 50, sha256.New)
163
-	u.Password = fmt.Sprintf("%x", newPasswd)
165
+func (user *User) EncodePasswd() {
166
+	newPasswd := pbkdf2.Key([]byte(user.Password), []byte(user.Salt), 10000, 50, sha256.New)
167
+	user.Password = fmt.Sprintf("%x", newPasswd)
164 168
 }
165 169
 
166 170
 // ValidatePassword checks if given password matches the one belongs to the user.
167
-func (u *User) ValidatePassword(passwd string) bool {
168
-	newUser := &User{Password: passwd, Salt: u.Salt}
171
+func (user *User) ValidatePassword(passwd string) bool {
172
+	newUser := &User{Password: passwd, Salt: user.Salt}
169 173
 	newUser.EncodePasswd()
170
-	return subtle.ConstantTimeCompare([]byte(u.Password), []byte(newUser.Password)) == 1
174
+	return subtle.ConstantTimeCompare([]byte(user.Password), []byte(newUser.Password)) == 1
171 175
 }
172 176
 
173 177
 // GetUserSalt returns a ramdom user salt token.
@@ -180,7 +184,7 @@ func UserPath(userName string) string {
180 184
 	return filepath.Join(setting.RepositoryRoot, strings.ToLower(userName))
181 185
 }
182 186
 
183
-// Create a new user and do some validation
187
+// CreateUser and do some validation
184 188
 func CreateUser(u *User) (err error) {
185 189
 	if err = IsUsableUsername(u.UserName); err != nil {
186 190
 		return err
@@ -227,11 +231,12 @@ func updateUser(e Engine, u *User) error {
227 231
 	return err
228 232
 }
229 233
 
234
+// UpdateUser with datas
230 235
 func UpdateUser(u *User) error {
231 236
 	return updateUser(x, u)
232 237
 }
233 238
 
234
-// Login validates user name and password.
239
+// UserLogin validates user name and password.
235 240
 func UserLogin(username, password string) (*User, error) {
236 241
 	var user *User
237 242
 	if strings.Contains(username, "@") {
@@ -258,12 +263,12 @@ func UserLogin(username, password string) (*User, error) {
258 263
 
259 264
 // get user by verify code
260 265
 func getVerifyUser(code string) (user *User) {
261
-	if len(code) <= tool.TIME_LIMIT_CODE_LENGTH {
266
+	if len(code) <= tool.TimeLimitCodeLength {
262 267
 		return nil
263 268
 	}
264 269
 
265 270
 	// use tail hex username query user
266
-	hexStr := code[tool.TIME_LIMIT_CODE_LENGTH:]
271
+	hexStr := code[tool.TimeLimitCodeLength:]
267 272
 	if b, err := hex.DecodeString(hexStr); err == nil {
268 273
 		if user, err = GetUserByName(string(b)); user != nil {
269 274
 			return user
@@ -275,14 +280,14 @@ func getVerifyUser(code string) (user *User) {
275 280
 	return nil
276 281
 }
277 282
 
278
-// verify active code when active account
283
+// VerifyUserActiveCode when active account
279 284
 func VerifyUserActiveCode(code string) (user *User) {
280 285
 	// HARDCODED
281 286
 	minutes := 180
282 287
 
283 288
 	if user = getVerifyUser(code); user != nil {
284 289
 		// time limit code
285
-		prefix := code[:tool.TIME_LIMIT_CODE_LENGTH]
290
+		prefix := code[:tool.TimeLimitCodeLength]
286 291
 		data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Password + user.Rands
287 292
 
288 293
 		if tool.VerifyTimeLimitCode(data, minutes, prefix) {
@@ -293,18 +298,18 @@ func VerifyUserActiveCode(code string) (user *User) {
293 298
 }
294 299
 
295 300
 // GenerateEmailActivateCode generates an activate code based on user information and given e-mail.
296
-func (u *User) GenerateEmailActivateCode(email string) string {
301
+func (user *User) GenerateEmailActivateCode(email string) string {
297 302
 	code := tool.CreateTimeLimitCode(
298
-		com.ToStr(u.ID)+email+u.LowerName+u.Password+u.Rands,180, nil)
303
+		com.ToStr(user.ID)+email+user.LowerName+user.Password+user.Rands,180, nil)
299 304
 
300 305
 	// Add tail hex username
301
-	code += hex.EncodeToString([]byte(u.LowerName))
306
+	code += hex.EncodeToString([]byte(user.LowerName))
302 307
 	return code
303 308
 }
304 309
 
305 310
 // GenerateActivateCode generates an activate code based on user information.
306
-func (u *User) GenerateActivateCode() string {
307
-	return u.GenerateEmailActivateCode(u.Email)
311
+func (user *User) GenerateActivateCode() string {
312
+	return user.GenerateEmailActivateCode(user.Email)
308 313
 }
309 314
 
310 315
 // mailerUser is a wrapper for satisfying mailer.User interface.
@@ -312,26 +317,32 @@ type mailerUser struct {
312 317
 	user *User
313 318
 }
314 319
 
315
-func (this mailerUser) ID() int64 {
316
-	return this.user.ID
320
+// ID id
321
+func (mUser mailerUser) ID() int64 {
322
+	return mUser.user.ID
317 323
 }
318 324
 
319
-func (this mailerUser) Email() string {
320
-	return this.user.Email
325
+// Email func
326
+func (mUser mailerUser) Email() string {
327
+	return mUser.user.Email
321 328
 }
322 329
 
323
-func (this mailerUser) DisplayName() string {
324
-	return this.user.UserName
330
+// DisplayName func
331
+func (mUser mailerUser) DisplayName() string {
332
+	return mUser.user.UserName
325 333
 }
326 334
 
327
-func (this mailerUser) GenerateActivateCode() string {
328
-	return this.user.GenerateActivateCode()
335
+// GenerateActivateCode func
336
+func (mUser mailerUser) GenerateActivateCode() string {
337
+	return mUser.user.GenerateActivateCode()
329 338
 }
330 339
 
331
-func (this mailerUser) GenerateEmailActivateCode(email string) string {
332
-	return this.user.GenerateEmailActivateCode(email)
340
+// GenerateEmailActivateCode func
341
+func (mUser mailerUser) GenerateEmailActivateCode(email string) string {
342
+	return mUser.user.GenerateEmailActivateCode(email)
333 343
 }
334 344
 
345
+// NewMailerUser mail user
335 346
 func NewMailerUser(u *User) mailer.User {
336 347
 	return mailerUser{u}
337 348
 }

+ 3
- 2
routers/admin/admin.go View File

@@ -10,7 +10,7 @@ import (
10 10
 )
11 11
 
12 12
 const (
13
-	DASHBOARD = "admin/dashboard"
13
+	tmplDashboard = "admin/dashboard"
14 14
 )
15 15
 
16 16
 var (
@@ -96,6 +96,7 @@ func updateSystemStatus() {
96 96
 	sysStatus.NumGC = m.NumGC
97 97
 }
98 98
 
99
+// Dashboard GET
99 100
 func Dashboard(ctx *context.Context) {
100 101
 	ctx.Title("admin.dashboard.title")
101 102
 	ctx.PageIs("AdminDashboard")
@@ -105,5 +106,5 @@ func Dashboard(ctx *context.Context) {
105 106
 	updateSystemStatus()
106 107
 	ctx.Data["SysStatus"] = sysStatus
107 108
 	ctx.Data["Entries"] = cron.ListTasks()
108
-	ctx.HTML(200, DASHBOARD)
109
+	ctx.HTML(200, tmplDashboard)
109 110
 }

+ 35
- 30
routers/gitxt/gitxt.go View File

@@ -23,12 +23,13 @@ import (
23 23
 )
24 24
 
25 25
 const (
26
-	NEW = "gitxt/new"
27
-	VIEW = "gitxt/view"
28
-	LIST = "gitxt/list"
29
-	EDIT = "gitxt/edit"
26
+	tmplNew  = "gitxt/new"
27
+	tmplView = "gitxt/view"
28
+	tmplList = "gitxt/list"
29
+	tmplEdit = "gitxt/edit"
30 30
 )
31 31
 
32
+// New GET
32 33
 func New(ctx *context.Context) {
33 34
 	ctx.Title("gitxt_new.title")
34 35
 	ctx.PageIs("GitxtNew")
@@ -40,9 +41,10 @@ func New(ctx *context.Context) {
40 41
 	// Initial expiry
41 42
 	ctx.Data["ExpiryHours"] = 0
42 43
 
43
-	ctx.Success(NEW)
44
+	ctx.Success(tmplNew)
44 45
 }
45 46
 
47
+// NewPost POST
46 48
 func NewPost(ctx *context.Context, f form.Gitxt) {
47 49
 	// Reject-redirect if not logged-in and anonymous create is deactivated
48 50
 	if !setting.AnonymousCreate && !ctx.IsLogged {
@@ -55,7 +57,7 @@ func NewPost(ctx *context.Context, f form.Gitxt) {
55 57
 
56 58
 	for i := range f.FilesFilename {
57 59
 		// For each filename sanitize it
58
-		f.FilesFilename[i] = sanitize.SanitizeFilename(f.FilesFilename[i])
60
+		f.FilesFilename[i] = sanitize.Filename(f.FilesFilename[i])
59 61
 		if len(f.FilesFilename[i]) == 0  || f.FilesFilename[i] == "." {
60 62
 			// If length is zero, use default filename
61 63
 			f.FilesFilename[i] = fmt.Sprintf("gitxt%d.txt", i)
@@ -81,7 +83,7 @@ func NewPost(ctx *context.Context, f form.Gitxt) {
81 83
 
82 84
 	// We got an error in the manual validation step, render with error
83 85
 	if ctx.HasError() {
84
-		ctx.Success(NEW)
86
+		ctx.Success(tmplNew)
85 87
 		return
86 88
 	}
87 89
 
@@ -113,7 +115,7 @@ func NewPost(ctx *context.Context, f form.Gitxt) {
113 115
 
114 116
 		log.Trace("Repository deleted: %s for %s", repositoryName, repositoryUser)
115 117
 
116
-		ctx.Success(NEW)
118
+		ctx.Success(tmplNew)
117 119
 		return
118 120
 	}
119 121
 
@@ -130,7 +132,7 @@ func NewPost(ctx *context.Context, f form.Gitxt) {
130 132
 			log.Warn("init_error_create_blob: %s", err)
131 133
 			ctx.Data["HasError"] = true
132 134
 			ctx.Data["ErrorMsg"] = ctx.Tr("gitxt_git.error_create_blob")
133
-			ctx.Success(NEW)
135
+			ctx.Success(tmplNew)
134 136
 			return
135 137
 		}
136 138
 		blobs = append(blobs, blob)
@@ -142,7 +144,7 @@ func NewPost(ctx *context.Context, f form.Gitxt) {
142 144
 		log.Warn("init_error_get_index: %s", err)
143 145
 		ctx.Data["HasError"] = true
144 146
 		ctx.Data["ErrorMsg"] = ctx.Tr("gitxt_git.error_get_index")
145
-		ctx.Success(NEW)
147
+		ctx.Success(tmplNew)
146 148
 		return
147 149
 	}
148 150
 
@@ -158,7 +160,7 @@ func NewPost(ctx *context.Context, f form.Gitxt) {
158 160
 			log.Warn("init_error_add_entry: %s", err)
159 161
 			ctx.Data["HasError"] = true
160 162
 			ctx.Data["ErrorMsg"] = ctx.Tr("gitxt_git.error_add_entry")
161
-			ctx.Success(NEW)
163
+			ctx.Success(tmplNew)
162 164
 			return
163 165
 		}
164 166
 	}
@@ -170,7 +172,7 @@ func NewPost(ctx *context.Context, f form.Gitxt) {
170 172
 		log.Warn("init_error_index_write_tree: %s", err)
171 173
 		ctx.Data["HasError"] = true
172 174
 		ctx.Data["ErrorMsg"] = ctx.Tr("gitxt_git.error_index_write_tree")
173
-		ctx.Success(NEW)
175
+		ctx.Success(tmplNew)
174 176
 		return
175 177
 
176 178
 	}
@@ -181,7 +183,7 @@ func NewPost(ctx *context.Context, f form.Gitxt) {
181 183
 		log.Warn("init_error_lookup_tree: %s", err)
182 184
 		ctx.Data["HasError"] = true
183 185
 		ctx.Data["ErrorMsg"] = ctx.Tr("gitxt_git.error_lookup_tree")
184
-		ctx.Success(NEW)
186
+		ctx.Success(tmplNew)
185 187
 		return
186 188
 
187 189
 	}
@@ -196,7 +198,7 @@ func NewPost(ctx *context.Context, f form.Gitxt) {
196 198
 		log.Warn("init_error_commit: %s", err)
197 199
 		ctx.Data["HasError"] = true
198 200
 		ctx.Data["ErrorMsg"] = ctx.Tr("gitxt_git.error_commit")
199
-		ctx.Success(NEW)
201
+		ctx.Success(tmplNew)
200 202
 		return
201 203
 
202 204
 	}
@@ -224,7 +226,7 @@ func NewPost(ctx *context.Context, f form.Gitxt) {
224 226
 		switch {
225 227
 		case models.IsErrHashAlreadyExist(err):
226 228
 			ctx.Data["Err_Hash"] = true
227
-			ctx.RenderWithErr(ctx.Tr("gitxt_new.hash_been_taken"), NEW, &f)
229
+			ctx.RenderWithErr(ctx.Tr("gitxt_new.hash_been_taken"), tmplNew, &f)
228 230
 		default:
229 231
 			ctx.Handle(500, "NewPost", err)
230 232
 		}
@@ -310,10 +312,10 @@ func View(ctx *context.Context) {
310 312
 		ctx.Data["IsOwner"] = false
311 313
 	}
312 314
 
313
-	ctx.Success(VIEW)
315
+	ctx.Success(tmplView)
314 316
 }
315 317
 
316
-
318
+// RawFile GET
317 319
 func RawFile(ctx *context.Context) {
318 320
 	file := ctx.Params("path")
319 321
 
@@ -356,7 +358,7 @@ func RawFile(ctx *context.Context) {
356 358
 	}
357 359
 }
358 360
 
359
-// List uploads, manage auth'ed user or not and from /:user too
361
+// ListUploads manage auth'ed user or not and from /:user too
360 362
 func ListUploads(ctx *context.Context) {
361 363
 	ctx.Title("gitxt_list.title")
362 364
 	ctx.PageIs("GitxtList")
@@ -409,9 +411,10 @@ func ListUploads(ctx *context.Context) {
409 411
 	ctx.Data["Total"] = gitxtsCount
410 412
 	ctx.Data["Page"] = paginater.New(int(gitxtsCount), opts.PageSize, page, 5)
411 413
 
412
-	ctx.Success(LIST)
414
+	ctx.Success(tmplList)
413 415
 }
414 416
 
417
+// DeletePost GET
415 418
 func DeletePost(ctx *context.Context, f form.GitxtDelete) {
416 419
 	if ctx.HasError() {
417 420
 		ctx.JSONSuccess(map[string]interface{}{
@@ -446,6 +449,7 @@ func DeletePost(ctx *context.Context, f form.GitxtDelete) {
446 449
 	return
447 450
 }
448 451
 
452
+// Edit git.txt
449 453
 func Edit(ctx *context.Context) {
450 454
 	ctx.Title("gitxt_edit.title")
451 455
 	ctx.PageIs("GitxtEdit")
@@ -514,9 +518,10 @@ func Edit(ctx *context.Context) {
514 518
 	ctx.Data["FilesFilename"] = FilesFilename
515 519
 	ctx.Data["FilesNotHandled"] = FilesNotHandled
516 520
 
517
-	ctx.Success(EDIT)
521
+	ctx.Success(tmplEdit)
518 522
 }
519 523
 
524
+// EditPost POST
520 525
 func EditPost(ctx *context.Context, f form.GitxtEdit) {
521 526
 	if !ctx.IsLogged {
522 527
 		ctx.Redirect(setting.AppSubURL + "/")
@@ -534,7 +539,7 @@ func EditPost(ctx *context.Context, f form.GitxtEdit) {
534 539
 
535 540
 	for i := range f.FilesFilename {
536 541
 		// For each filename sanitize it
537
-		f.FilesFilename[i] = sanitize.SanitizeFilename(f.FilesFilename[i])
542
+		f.FilesFilename[i] = sanitize.Filename(f.FilesFilename[i])
538 543
 		if len(f.FilesFilename[i]) == 0  || f.FilesFilename[i] == "." {
539 544
 			// If length is zero, use default filename
540 545
 			f.FilesFilename[i] = fmt.Sprintf("gitxt%d.txt", i)
@@ -561,7 +566,7 @@ func EditPost(ctx *context.Context, f form.GitxtEdit) {
561 566
 
562 567
 	// We got an error in the manual validation step, render with error
563 568
 	if ctx.HasError() {
564
-		ctx.Success(NEW)
569
+		ctx.Success(tmplNew)
565 570
 		return
566 571
 	}
567 572
 
@@ -604,7 +609,7 @@ func EditPost(ctx *context.Context, f form.GitxtEdit) {
604 609
 				log.Warn("init_error_create_blob: %s", err)
605 610
 				ctx.Data["HasError"] = true
606 611
 				ctx.Data["ErrorMsg"] = ctx.Tr("gitxt_git.error_create_blob")
607
-				ctx.Success(NEW)
612
+				ctx.Success(tmplNew)
608 613
 				return
609 614
 			}
610 615
 		}
@@ -617,7 +622,7 @@ func EditPost(ctx *context.Context, f form.GitxtEdit) {
617 622
 		log.Warn("init_error_get_index: %s", err)
618 623
 		ctx.Data["HasError"] = true
619 624
 		ctx.Data["ErrorMsg"] = ctx.Tr("gitxt_git.error_get_index")
620
-		ctx.Success(NEW)
625
+		ctx.Success(tmplNew)
621 626
 		return
622 627
 	}
623 628
 
@@ -635,7 +640,7 @@ func EditPost(ctx *context.Context, f form.GitxtEdit) {
635 640
 			log.Warn("init_error_add_entry: %s", err)
636 641
 			ctx.Data["HasError"] = true
637 642
 			ctx.Data["ErrorMsg"] = ctx.Tr("gitxt_git.error_add_entry")
638
-			ctx.Success(NEW)
643
+			ctx.Success(tmplNew)
639 644
 			return
640 645
 		}
641 646
 	}
@@ -647,7 +652,7 @@ func EditPost(ctx *context.Context, f form.GitxtEdit) {
647 652
 		log.Warn("init_error_index_write_tree: %s", err)
648 653
 		ctx.Data["HasError"] = true
649 654
 		ctx.Data["ErrorMsg"] = ctx.Tr("gitxt_git.error_index_write_tree")
650
-		ctx.Success(NEW)
655
+		ctx.Success(tmplNew)
651 656
 		return
652 657
 
653 658
 	}
@@ -658,7 +663,7 @@ func EditPost(ctx *context.Context, f form.GitxtEdit) {
658 663
 		log.Warn("init_error_lookup_tree: %s", err)
659 664
 		ctx.Data["HasError"] = true
660 665
 		ctx.Data["ErrorMsg"] = ctx.Tr("gitxt_git.error_lookup_tree")
661
-		ctx.Success(NEW)
666
+		ctx.Success(tmplNew)
662 667
 		return
663 668
 
664 669
 	}
@@ -669,7 +674,7 @@ func EditPost(ctx *context.Context, f form.GitxtEdit) {
669 674
 		log.Warn("git_error_get_head: %s", err)
670 675
 		ctx.Data["HasError"] = true
671 676
 		ctx.Data["ErrorMsg"] = ctx.Tr("gitxt_git.error_get_head")
672
-		ctx.Success(NEW)
677
+		ctx.Success(tmplNew)
673 678
 		return
674 679
 	}
675 680
 
@@ -679,7 +684,7 @@ func EditPost(ctx *context.Context, f form.GitxtEdit) {
679 684
 		log.Warn("git_error_get_head_commit: %s", err)
680 685
 		ctx.Data["HasError"] = true
681 686
 		ctx.Data["ErrorMsg"] = ctx.Tr("gitxt_git.error_get_head_commit")
682
-		ctx.Success(NEW)
687
+		ctx.Success(tmplNew)
683 688
 		return
684 689
 	}
685 690
 
@@ -693,7 +698,7 @@ func EditPost(ctx *context.Context, f form.GitxtEdit) {
693 698
 		log.Warn("init_error_commit: %s", err)
694 699
 		ctx.Data["HasError"] = true
695 700
 		ctx.Data["ErrorMsg"] = ctx.Tr("gitxt_git.error_commit")
696
-		ctx.Success(NEW)
701
+		ctx.Success(tmplNew)
697 702
 		return
698 703
 
699 704
 	}

+ 1
- 0
routers/hub.go View File

@@ -2,6 +2,7 @@ package routers
2 2
 
3 3
 import "dev.sigpipe.me/dashie/git.txt/context"
4 4
 
5
+// NotFound 404
5 6
 func NotFound(ctx *context.Context) {
6 7
 	ctx.Title(ctx.Tr("error.page_not_found"))
7 8
 	ctx.Handle(404, "home.NotFound", nil)

+ 1
- 0
routers/repo/archive.go View File

@@ -14,6 +14,7 @@ import (
14 14
 	"dev.sigpipe.me/dashie/git.txt/stuff/gite"
15 15
 )
16 16
 
17
+// DownloadArchive of repository
17 18
 func DownloadArchive(ctx *context.Context) {
18 19
 	var (
19 20
 		uri			= ctx.Params("*")

+ 22
- 17
routers/repo/repo.go View File

@@ -26,16 +26,17 @@ import (
26 26
 )
27 27
 
28 28
 const (
29
-	ENV_AUTH_USER_ID           = "GITXT_AUTH_USER_ID"
30
-	ENV_AUTH_USER_NAME         = "GITXT_AUTH_USER_NAME"
31
-	ENV_AUTH_USER_EMAIL        = "GITXT_AUTH_USER_EMAIL"
32
-	ENV_REPO_OWNER_NAME        = "GITXT_REPO_OWNER_NAME"
33
-	ENV_REPO_OWNER_SALT_MD5    = "GITXT_REPO_OWNER_SALT_MD5"
34
-	ENV_REPO_ID                = "GITXT_REPO_ID"
35
-	ENV_REPO_NAME              = "GITXT_REPO_NAME"
36
-	ENV_REPO_CUSTOM_HOOKS_PATH = "GITXT_REPO_CUSTOM_HOOKS_PATH"
29
+	envAuthUserID          = "GITXT_AUTH_USER_ID"
30
+	envAuthUserName        = "GITXT_AUTH_USER_NAME"
31
+	envAuthUserEmail       = "GITXT_AUTH_USER_EMAIL"
32
+	envRepoOwnerName       = "GITXT_REPO_OWNER_NAME"
33
+	envRepoOwnerSaltMd5    = "GITXT_REPO_OWNER_SALT_MD5"
34
+	envRepoID              = "GITXT_REPO_ID"
35
+	envRepoName            = "GITXT_REPO_NAME"
36
+	envRepoCustomHooksPath = "GITXT_REPO_CUSTOM_HOOKS_PATH"
37 37
 )
38 38
 
39
+// HTTPContext struct
39 40
 type HTTPContext struct {
40 41
 	*context.Context
41 42
 	OwnerName	string
@@ -51,6 +52,7 @@ func askCredentials(ctx *context.Context, status int, text string) {
51 52
 	ctx.HandleText(status, text)
52 53
 }
53 54
 
55
+// HTTPContexter magic
54 56
 func HTTPContexter() macaron.Handler {
55 57
 	return func(ctx *context.Context) {
56 58
 		ownerName := ctx.Params(":user")
@@ -181,6 +183,7 @@ func (h *serviceHandler) sendFile(contentType string) {
181 183
 	http.ServeFile(h.w, h.r, reqFile)
182 184
 }
183 185
 
186
+// ComposeHookEnvsOptions struct
184 187
 type ComposeHookEnvsOptions struct {
185 188
 	AuthUser  *models.User
186 189
 	OwnerName string
@@ -190,17 +193,18 @@ type ComposeHookEnvsOptions struct {
190 193
 	RepoPath  string
191 194
 }
192 195
 
196
+// ComposeHookEnvs magic
193 197
 func ComposeHookEnvs(opts ComposeHookEnvsOptions) []string {
194 198
 	envs := []string{
195 199
 		"SSH_ORIGINAL_COMMAND=1",
196
-		ENV_AUTH_USER_ID + "=" + com.ToStr(opts.AuthUser.ID),
197
-		ENV_AUTH_USER_NAME + "=" + opts.AuthUser.UserName,
198
-		ENV_AUTH_USER_EMAIL + "=" + opts.AuthUser.Email,
199
-		ENV_REPO_OWNER_NAME + "=" + opts.OwnerName,
200
-		ENV_REPO_OWNER_SALT_MD5 + "=" + tool.MD5(opts.OwnerSalt),
201
-		ENV_REPO_ID + "=" + com.ToStr(opts.RepoID),
202
-		ENV_REPO_NAME + "=" + opts.RepoName,
203
-		ENV_REPO_CUSTOM_HOOKS_PATH + "=" + path.Join(opts.RepoPath, "custom_hooks"),
200
+		envAuthUserID + "=" + com.ToStr(opts.AuthUser.ID),
201
+		envAuthUserName + "=" + opts.AuthUser.UserName,
202
+		envAuthUserEmail + "=" + opts.AuthUser.Email,
203
+		envRepoOwnerName + "=" + opts.OwnerName,
204
+		envRepoOwnerSaltMd5 + "=" + tool.MD5(opts.OwnerSalt),
205
+		envRepoID + "=" + com.ToStr(opts.RepoID),
206
+		envRepoName + "=" + opts.RepoName,
207
+		envRepoCustomHooksPath + "=" + path.Join(opts.RepoPath, "custom_hooks"),
204 208
 	}
205 209
 	return envs
206 210
 }
@@ -364,6 +368,7 @@ func getGitRepoPath(repoDir string) (string, error) {
364 368
 	return filename, nil
365 369
 }
366 370
 
371
+// HTTP Context
367 372
 func HTTP(ctx *HTTPContext) {
368 373
 	for _, route := range routes {
369 374
 		reqPath := strings.ToLower(ctx.Req.URL.Path)
@@ -375,7 +380,7 @@ func HTTP(ctx *HTTPContext) {
375 380
 		// We perform check here because routes matched in cmd/web.go is wider than needed,
376 381
 		// but we only want to output this message only if user is really trying to access
377 382
 		// Git HTTP endpoints.
378
-		if setting.DisableHttpGit {
383
+		if setting.DisableHTTPGit {
379 384
 			ctx.HandleText(http.StatusForbidden, "Interacting with repositories by HTTP protocol is not disabled")
380 385
 			return
381 386
 		}

+ 32
- 27
routers/user/auth.go View File

@@ -13,10 +13,10 @@ import (
13 13
 )
14 14
 
15 15
 const (
16
-	LOGIN	= "user/auth/login"
17
-	REGISTER = "user/auth/register"
18
-	FORGOT_PASSWORD = "user/auth/forgot_password"
19
-	RESET_PASSWORD = "user/auth/reset_password"
16
+	tmplLogin          = "user/auth/login"
17
+	tmplRegister       = "user/auth/register"
18
+	tmplForgotPassword = "user/auth/forgot_password"
19
+	tmplResetPassword  = "user/auth/reset_password"
20 20
 )
21 21
 
22 22
 // isValidRedirect returns false if the URL does not redirect to same site.
@@ -69,7 +69,7 @@ func AutoLogin(c *context.Context) (bool, error) {
69 69
 	return true, nil
70 70
 }
71 71
 
72
-// Login
72
+// Login GET
73 73
 func Login(ctx *context.Context) {
74 74
 	ctx.Title("login.title")
75 75
 
@@ -97,21 +97,22 @@ func Login(ctx *context.Context) {
97 97
 		return
98 98
 	}
99 99
 
100
-	ctx.HTML(200, LOGIN)
100
+	ctx.HTML(200, tmplLogin)
101 101
 }
102 102
 
103
+// LoginPost POST
103 104
 func LoginPost(ctx *context.Context, f form.Login) {
104 105
 	ctx.Title("login.title")
105 106
 
106 107
 	if ctx.HasError() {
107
-		ctx.Success(LOGIN)
108
+		ctx.Success(tmplLogin)
108 109
 		return
109 110
 	}
110 111
 
111 112
 	u, err := models.UserLogin(f.UserName, f.Password)
112 113
 	if err != nil {
113 114
 		if errors.IsUserNotExist(err) {
114
-			ctx.RenderWithErr(ctx.Tr("form.username_password_incorrect"), LOGIN, &f)
115
+			ctx.RenderWithErr(ctx.Tr("form.username_password_incorrect"), tmplLogin, &f)
115 116
 		} else {
116 117
 			ctx.ServerError("UserSignIn", err)
117 118
 		}
@@ -149,7 +150,7 @@ func afterLogin(ctx *context.Context, u *models.User, remember bool) {
149 150
 	ctx.Redirect(setting.AppSubURL + "/")
150 151
 }
151 152
 
152
-// Registration
153
+// Register GET
153 154
 func Register(ctx *context.Context) {
154 155
 	ctx.Title("register.title")
155 156
 	if ! setting.CanRegister {
@@ -158,9 +159,10 @@ func Register(ctx *context.Context) {
158 159
 		return
159 160
 	}
160 161
 
161
-	ctx.HTML(200, REGISTER)
162
+	ctx.HTML(200, tmplRegister)
162 163
 }
163 164
 
165
+// RegisterPost POST
164 166
 func RegisterPost(ctx *context.Context, f form.Register) {
165 167
 	ctx.Title("register.title")
166 168
 
@@ -171,14 +173,14 @@ func RegisterPost(ctx *context.Context, f form.Register) {
171 173
 	}
172 174
 
173 175
 	if ctx.HasError() {
174
-		ctx.HTML(200, REGISTER)
176
+		ctx.HTML(200, tmplRegister)
175 177
 		return
176 178
 	}
177 179
 
178 180
 	if f.Password != f.Repeat {
179 181
 		ctx.Data["Err_Password"] = true
180 182
 		ctx.Data["Err_Retype"] = true
181
-		ctx.RenderWithErr(ctx.Tr("form.password_not_match"), REGISTER, &f)
183
+		ctx.RenderWithErr(ctx.Tr("form.password_not_match"), tmplRegister, &f)
182 184
 		return
183 185
 	}
184 186
 
@@ -192,13 +194,13 @@ func RegisterPost(ctx *context.Context, f form.Register) {
192 194
 		switch {
193 195
 		case models.IsErrUserAlreadyExist(err):
194 196
 			ctx.Data["Err_UserName"] = true
195
-			ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), REGISTER, &f)
197
+			ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), tmplRegister, &f)
196 198
 		case models.IsErrNameReserved(err):
197 199
 			ctx.Data["Err_UserName"] = true
198
-			ctx.RenderWithErr(ctx.Tr("form.username_reserved"), REGISTER, &f)
200
+			ctx.RenderWithErr(ctx.Tr("form.username_reserved"), tmplRegister, &f)
199 201
 		case models.IsErrNamePatternNotAllowed(err):
200 202
 			ctx.Data["Err_UserName"] = true
201
-			ctx.RenderWithErr(ctx.Tr("form.username_pattern_not_allowed"), REGISTER, &f)
203
+			ctx.RenderWithErr(ctx.Tr("form.username_pattern_not_allowed"), tmplRegister, &f)
202 204
 		default:
203 205
 			ctx.Handle(500, "CreateUser", err)
204 206
 		}
@@ -222,7 +224,7 @@ func RegisterPost(ctx *context.Context, f form.Register) {
222 224
 	ctx.Redirect(setting.AppSubURL + "/user/login")
223 225
 }
224 226
 
225
-// Logout
227
+// Logout GET
226 228
 func Logout(ctx *context.Context) {
227 229
 	ctx.Session.Delete("uid")
228 230
 	ctx.Session.Delete("uname")
@@ -233,7 +235,7 @@ func Logout(ctx *context.Context) {
233 235
 }
234 236
 
235 237
 
236
-// ResetPassword
238
+// ResetPasswd GET
237 239
 func ResetPasswd(ctx *context.Context) {
238 240
 	ctx.Title("auth.reset_password")
239 241
 	code := ctx.Query("code")
@@ -243,9 +245,10 @@ func ResetPasswd(ctx *context.Context) {
243 245
 	}
244 246
 	ctx.Data["Code"] = code
245 247
 	ctx.Data["IsResetForm"] = true
246
-	ctx.HTML(200, RESET_PASSWORD)
248
+	ctx.HTML(200, tmplResetPassword)
247 249
 }
248 250
 
251
+// ResetPasswdPost POST
249 252
 func ResetPasswdPost(ctx *context.Context) {
250 253
 	ctx.Title("auth.reset_password")
251 254
 
@@ -262,7 +265,7 @@ func ResetPasswdPost(ctx *context.Context) {
262 265
 		if len(passwd) < 6 {
263 266
 			ctx.Data["IsResetForm"] = true
264 267
 			ctx.Data["Err_Password"] = true
265
-			ctx.RenderWithErr(ctx.Tr("auth.password_too_short"), RESET_PASSWORD, nil)
268
+			ctx.RenderWithErr(ctx.Tr("auth.password_too_short"), tmplResetPassword, nil)
266 269
 			return
267 270
 		}
268 271
 
@@ -287,23 +290,25 @@ func ResetPasswdPost(ctx *context.Context) {
287 290
 		return
288 291
 	}
289 292
 	ctx.Data["IsResetFailed"] = true
290
-	ctx.HTML(200, RESET_PASSWORD)
293
+	ctx.HTML(200, tmplResetPassword)
291 294
 }
292 295
 
296
+// ForgotPasswd GET
293 297
 func ForgotPasswd(ctx *context.Context) {
294 298
 	ctx.Title("auth.forgot_password")
295 299
 
296 300
 	if setting.MailService == nil {
297 301
 		ctx.Data["IsResetDisable"] = true
298
-		ctx.HTML(200, FORGOT_PASSWORD)
302
+		ctx.HTML(200, tmplForgotPassword)
299 303
 		return
300 304
 	}
301 305
 
302 306
 	ctx.Data["IsResetRequest"] = true
303 307
 
304
-	ctx.HTML(200, FORGOT_PASSWORD)
308
+	ctx.HTML(200, tmplForgotPassword)
305 309
 }
306 310
 
311
+// ForgotPasswdPost POST
307 312
 func ForgotPasswdPost(ctx *context.Context) {
308 313
 	ctx.Title("auth.forgot_password")
309 314
 
@@ -323,18 +328,18 @@ func ForgotPasswdPost(ctx *context.Context) {
323 328
 			ctx.Data["Hours"] = 180 / 60
324 329
 			ctx.Data["IsResetSent"] = true
325 330
 			log.Trace("User doesn't exists")
326
-			ctx.HTML(200, FORGOT_PASSWORD)
331
+			ctx.HTML(200, tmplForgotPassword)
327 332
 			return
328
-		} else {
329
-			ctx.Handle(500, "user.ResetPasswd(check existence)", err)
330 333
 		}
334
+
335
+		ctx.Handle(500, "user.ResetPasswd(check existence)", err)
331 336
 		return
332 337
 	}
333 338
 
334 339
 	if ctx.Cache.IsExist("MailResendLimit_" + u.LowerName) {
335 340
 		log.Trace("Mail Resend limited")
336 341
 		ctx.Data["ResendLimited"] = true
337
-		ctx.HTML(200, FORGOT_PASSWORD)
342
+		ctx.HTML(200, tmplForgotPassword)
338 343
 		return
339 344
 	}
340 345
 
@@ -346,5 +351,5 @@ func ForgotPasswdPost(ctx *context.Context) {
346 351
 	// HARDCODED
347 352
 	ctx.Data["Hours"] = 180 / 60
348 353
 	ctx.Data["IsResetSent"] = true
349
-	ctx.HTML(200, FORGOT_PASSWORD)
354
+	ctx.HTML(200, tmplForgotPassword)
350 355
 }

+ 5
- 3
routers/user/setting.go View File

@@ -7,23 +7,25 @@ import (
7 7
 )
8 8
 
9 9
 const (
10
-	SETTINGS_PROFILE = "user/settings/profile"
10
+	tmplSettingsProfile = "user/settings/profile"
11 11
 )
12 12
 
13
+// Settings GET
13 14
 func Settings(ctx *context.Context) {
14 15
 	ctx.Title("settings.title")
15 16
 	ctx.PageIs("SettingsProfile")
16 17
 	ctx.Data["email"] = ctx.User.Email
17
-	ctx.Success(SETTINGS_PROFILE)
18
+	ctx.Success(tmplSettingsProfile)
18 19
 }
19 20
 
21
+// SettingsPost POST
20 22
 func SettingsPost(ctx *context.Context, f form.UpdateSettingsProfile) {
21 23
 	ctx.Title("settings.title")
22 24
 	ctx.PageIs("SettingsProfile")
23 25
 	ctx.Data["origin_name"] = ctx.User.UserName
24 26
 
25 27
 	if ctx.HasError() {
26
-		ctx.Success(SETTINGS_PROFILE)
28
+		ctx.Success(tmplSettingsProfile)
27 29
 		return
28 30
 	}
29 31
 

+ 31
- 16
setting/setting.go View File

@@ -17,21 +17,26 @@ import (
17 17
 	"net/mail"
18 18
 )
19 19
 
20
+// Scheme type
20 21
 type Scheme string
21 22
 
23
+// Schemes
22 24
 const (
23
-	SCHEME_HTTP        Scheme = "http"
24
-	SCHEME_HTTPS       Scheme = "https"
25
-	SCHEME_FCGI        Scheme = "fcgi"
26
-	SCHEME_UNIX_SOCKET Scheme = "unix"
25
+	SchemeHTTP       Scheme = "http"
26
+	SchemeHTTPS      Scheme = "https"
27
+	SchemeFCGI       Scheme = "fcgi"
28
+	SchemeUnixSocket Scheme = "unix"
27 29
 )
28 30
 
31
+
32
+// Settings
29 33
 var (
30 34
 	// Build infos added by -ldflags
31 35
 	BuildTime	string
32 36
 	BuildGitHash 	string
33 37
 
34 38
 	// App Settings
39
+
35 40
 	AppVer		string
36 41
 	AppPath		string
37 42
 	AppName         string
@@ -53,6 +58,7 @@ var (
53 58
 	}
54 59
 
55 60
 	// Server settings
61
+
56 62
 	Protocol		Scheme
57 63
 	UnixSocketPermission	uint32
58 64
 	Domain			string
@@ -66,12 +72,14 @@ var (
66 72
 	}
67 73
 
68 74
 	// Database Settings
75
+
69 76
 	UseSQLite3	bool
70 77
 	UseMySQL	bool
71 78
 	UsePostgreSQL	bool
72 79
 	UseMSSQL	bool
73 80
 
74 81
 	// Global setting objects
82
+
75 83
 	CustomConf	string
76 84
 	IsWindows	bool
77 85
 	Cfg		*ini.File
@@ -79,20 +87,24 @@ var (
79 87
 	RobotsTxtPath	string
80 88
 
81 89
 	// Log settings
90
+
82 91
 	LogRootPath	string
83 92
 	LogModes	[]string
84 93
 	LogConfigs	[]interface{}
85 94
 
86 95
 	// Repository settings
87
-	RepositoryRoot	string
88
-	DisableHttpGit	bool
89
-	GitBinary	string
96
+
97
+	RepositoryRoot string
98
+	DisableHTTPGit bool
99
+	GitBinary      string
90 100
 
91 101
 	// Session settings
102
+
92 103
 	SessionConfig  session.Options
93 104
 	CSRFCookieName string
94 105
 
95 106
 	// Security settings
107
+
96 108
 	InstallLock             bool
97 109
 	SecretKey               string
98 110
 	LoginRememberDays       int
@@ -103,11 +115,12 @@ var (
103 115
 	LoginStatusCookieName string
104 116
 
105 117
 	// Cache settings
118
+
106 119
 	CacheAdapter  string
107 120
 	CacheInterval int
108 121
 	CacheConn string
109 122
 
110
-	// I18n settings
123
+	// Langs settings
111 124
 	Langs     []string
112 125
 	Names     []string
113 126
 	dateLangs map[string]string
@@ -128,7 +141,7 @@ var (
128 141
 	    AngledQuotes bool
129 142
 	}
130 143
 
131
-	// Static settings
144
+	// Bloby struct for static limitations
132 145
 	Bloby struct {
133 146
 		MaxSizeDisplay	int64
134 147
 		MaxPageDisplay  int64
@@ -188,6 +201,7 @@ func forcePathSeparator(path string) {
188 201
 	}
189 202
 }
190 203
 
204
+// InitConfig from file
191 205
 func InitConfig() {
192 206
 	workDir, err := WorkDir()
193 207
 	if err != nil {
@@ -221,27 +235,27 @@ func InitConfig() {
221 235
 	}
222 236
 
223 237
 	// Check if has app suburl.
224
-	appUrl, err := url.Parse(AppURL)
238
+	appURL, err := url.Parse(AppURL)
225 239
 	if err != nil {
226 240
 		log.Fatal(2, "Invalid ROOT_URL '%s': %s", AppURL, err)
227 241
 	}
228 242
 	// Suburl should start with '/' and end without '/', such as '/{subpath}'.
229 243
 	// This value is empty if site does not have sub-url.
230
-	AppSubURL = strings.TrimSuffix(appUrl.Path, "/")
244
+	AppSubURL = strings.TrimSuffix(appURL.Path, "/")
231 245
 	AppSubURLDepth = strings.Count(AppSubURL, "/")
232 246
 
233 247
 	CanRegister = Cfg.Section("").Key("CAN_REGISTER").MustBool(true)
234 248
 	AnonymousCreate = Cfg.Section("").Key("ANONYMOUS_CREATE").MustBool(true)
235 249
 
236
-	Protocol = SCHEME_HTTP
250
+	Protocol = SchemeHTTP
237 251
 	if sec.Key("PROTOCOL").String() == "https" {
238
-		Protocol = SCHEME_HTTPS
252
+		Protocol = SchemeHTTPS
239 253
 		log.Warn("https not supported")
240 254
 	} else if sec.Key("PROTOCOL").String() == "fcgi" {
241
-		Protocol = SCHEME_FCGI
255
+		Protocol = SchemeFCGI
242 256
 		log.Warn("fcgi not supported")
243 257
 	} else if sec.Key("PROTOCOL").String() == "unix" {
244
-		Protocol = SCHEME_UNIX_SOCKET
258
+		Protocol = SchemeUnixSocket
245 259
 		log.Warn("socket not supported")
246 260
 		UnixSocketPermissionRaw := sec.Key("UNIX_SOCKET_PERMISSION").MustString("666")
247 261
 		UnixSocketPermissionParsed, err := strconv.ParseUint(UnixSocketPermissionRaw, 8, 32)
@@ -258,7 +272,7 @@ func InitConfig() {
258 272
 
259 273
 	sec = Cfg.Section("repository")
260 274
 	RepositoryRoot = sec.Key("ROOT").MustString(path.Join(homeDir, "gitxt-repositories"))
261
-	DisableHttpGit = sec.Key("DISABLE_HTTP_GIT").MustBool(false)
275
+	DisableHTTPGit = sec.Key("DISABLE_HTTP_GIT").MustBool(false)
262 276
 	GitBinary = sec.Key("GIT_BINARY").MustString("git")
263 277
 
264 278
 	sec = Cfg.Section("security")
@@ -437,6 +451,7 @@ type Mailer struct {
437 451
 }
438 452
 
439 453
 var (
454
+	// MailService Mailer
440 455
 	MailService *Mailer
441 456
 )
442 457
 

+ 1
- 0
stuff/auth/auth.go View File

@@ -14,6 +14,7 @@ import (
14 14
 	"gopkg.in/macaron.v1"
15 15
 )
16 16
 
17
+// IsAPIPath or not ?
17 18
 func IsAPIPath(url string) bool {
18 19
 	return strings.HasPrefix(url, "/api/")
19 20
 }

+ 1
- 0
stuff/cron/cron.go View File

@@ -10,6 +10,7 @@ import (
10 10
 
11 11
 var c = cron.New()
12 12
 
13
+// NewContext initialize Cron stuff
13 14
 func NewContext() {
14 15
 	var (
15 16
 		entry	*cron.Entry

+ 4
- 2
stuff/form/auth.go View File

@@ -5,7 +5,7 @@ import (
5 5
 	"gopkg.in/macaron.v1"
6 6
 )
7 7
 
8
-// Register
8
+// Register form
9 9
 type Register struct {
10 10
 	UserName string `binding:"Required;AlphaDashDot;MaxSize(35)"`
11 11
 	Email    string `binding:"Required;Email;MaxSize(254)"`
@@ -13,17 +13,19 @@ type Register struct {
13 13
 	Repeat string
14 14
 }
15 15
 
16
+// Validate func
16 17
 func (f *Register) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
17 18
 	return validate(errs, ctx.Data, f, ctx.Locale)
18 19
 }
19 20
 
20
-// Login
21
+// Login form
21 22
 type Login struct {
22 23
 	UserName string `binding:"Required;MaxSize(254)"`
23 24
 	Password string `binding:"Required;MaxSize(255)"`
24 25
 	Remember bool
25 26
 }
26 27
 
28
+// Validate func
27 29
 func (f *Login) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
28 30
 	return validate(errs, ctx.Data, f, ctx.Locale)
29 31
 }

+ 6
- 5
stuff/form/form.go View File

@@ -11,9 +11,9 @@ import (
11 11
 	log "gopkg.in/clog.v1"
12 12
 )
13 13
 
14
-const ERR_ALPHA_DASH_DOT_SLASH = "AlphaDashDotSlashError"
14
+const errAlphaDashDotSlash = "AlphaDashDotSlashError"
15 15
 
16
-var AlphaDashDotSlashPattern = regexp.MustCompile("[^\\d\\w-_\\./]")
16
+var alphaDashDotSlashPattern = regexp.MustCompile("[^\\d\\w-_\\./]")
17 17
 
18 18
 func init() {
19 19
 	binding.SetNameMapper(com.ToSnakeCase)
@@ -22,8 +22,8 @@ func init() {
22 22
 			return rule == "AlphaDashDotSlash"
23 23
 		},
24 24
 		IsValid: func(errs binding.Errors, name string, v interface{}) (bool, binding.Errors) {
25
-			if AlphaDashDotSlashPattern.MatchString(fmt.Sprintf("%v", v)) {
26
-				errs.Add([]string{name}, ERR_ALPHA_DASH_DOT_SLASH, "AlphaDashDotSlash")
25
+			if alphaDashDotSlashPattern.MatchString(fmt.Sprintf("%v", v)) {
26
+				errs.Add([]string{name}, errAlphaDashDotSlash, "AlphaDashDotSlash")
27 27
 				return false, errs
28 28
 			}
29 29
 			return true, errs
@@ -31,6 +31,7 @@ func init() {
31 31
 	})
32 32
 }
33 33
 
34
+// Form interface
34 35
 type Form interface {
35 36
 	binding.Validator
36 37
 }
@@ -133,7 +134,7 @@ func validate(errs binding.Errors, data map[string]interface{}, f Form, l macaro
133 134
 				data["ErrorMsg"] = trName + l.Tr("form.alpha_dash_error")
134 135
 			case binding.ERR_ALPHA_DASH_DOT:
135 136
 				data["ErrorMsg"] = trName + l.Tr("form.alpha_dash_dot_error")
136
-			case ERR_ALPHA_DASH_DOT_SLASH:
137
+			case errAlphaDashDotSlash:
137 138
 				data["ErrorMsg"] = trName + l.Tr("form.alpha_dash_dot_slash_error")
138 139
 			case binding.ERR_SIZE:
139 140
 				data["ErrorMsg"] = trName + l.Tr("form.size_error", getSize(field))

+ 6
- 3
stuff/form/gitxt.go View File

@@ -5,7 +5,7 @@ import (
5 5
 	"github.com/go-macaron/binding"
6 6
 )
7 7
 
8
-/* New Gitxt */
8
+// Gitxt form struct
9 9
 type Gitxt struct {
10 10
 	Description string `binding:"MaxSize(255)"`
11 11
 	IsPublic    bool   `binding:"Default:1"`
@@ -18,21 +18,23 @@ type Gitxt struct {
18 18
 	ExpiryHours	int64	`binding:"In(0,1,4,24,48,72,96,120,144,168,730,8760);Default(0)"`
19 19
 }
20 20
 
21
+// Validate func
21 22
 func (f *Gitxt) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
22 23
 	return validate(errs, ctx.Data, f, ctx.Locale)
23 24
 }
24 25
 
25
-/* Delete Gitxt */
26
+// GitxtDelete form
26 27
 type GitxtDelete struct {
27 28
 	Hash    string   `binding:"Required"`
28 29
 	Owner    string   `binding:"Required"`
29 30
 }
30 31
 
32
+// Validate func
31 33
 func (f *GitxtDelete) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
32 34
 	return validate(errs, ctx.Data, f, ctx.Locale)
33 35
 }
34 36
 
35
-/* Edit Gitxt */
37
+// GitxtEdit form
36 38
 type GitxtEdit struct {
37 39
 	Description string `binding:"MaxSize(255)"`
38 40
 	// Validation builtin into Macaron/Binding doesn't validates theses slices
@@ -45,6 +47,7 @@ type GitxtEdit struct {
45 47
 	ExpiryHours	int64	`binding:"In(0,1,4,24,48,72,96,120,144,168,730,8760);Default(0)"`
46 48
 }
47 49
 
50
+// Validate struct
48 51
 func (f *GitxtEdit) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
49 52
 	return validate(errs, ctx.Data, f, ctx.Locale)
50 53
 }

+ 2
- 1
stuff/form/user.go View File

@@ -5,11 +5,12 @@ import (
5 5
 	"github.com/go-macaron/binding"
6 6
 )
7 7
 
8
-// Settings / Profile
8
+// UpdateSettingsProfile form struct
9 9
 type UpdateSettingsProfile struct {
10 10
 	Email string `binding:"Required;Email;MaxSize(254)"`
11 11
 }
12 12
 
13
+// Validate func
13 14
 func (f *UpdateSettingsProfile) Validate(ctx *macaron.Context, errs binding.Errors) binding.Errors {
14 15
 	return validate(errs, ctx.Data, f, ctx.Locale)
15 16
 }

+ 29
- 25
stuff/gite/gite.go View File

@@ -103,6 +103,7 @@ func getEntriesPaths(entries *[]TreeEntry, target string) git.TreeWalkCallback {
103 103
 		return 0
104 104
 	}
105 105
 }
106
+
106 107
 func getJustRawContent(repo *git.Repository, path string) (content []byte, size int64, err error) {
107 108
 	tree, err := getRepositoryTree(repo)
108 109
 	if err != nil {
@@ -116,6 +117,8 @@ func getJustRawContent(repo *git.Repository, path string) (content []byte, size
116 117
 	}
117 118
 	return blob.Contents(), blob.Size(), err
118 119
 }
120
+
121
+// WriteTarArchiveFromRepository because yes
119 122
 func WriteTarArchiveFromRepository(repo *git.Repository, archivePath string) (err error) {
120 123
 	archiveFile, err := os.Create(archivePath)
121 124
 	if err != nil {
@@ -157,6 +160,7 @@ func WriteTarArchiveFromRepository(repo *git.Repository, archivePath string) (er
157 160
 	return
158 161
 }
159 162
 
163
+// WriteZipArchiveFromRepository as said
160 164
 func WriteZipArchiveFromRepository(repo *git.Repository, archivePath string) (err error) {
161 165
 	archiveFile, err := os.Create(archivePath)
162 166
 	if err != nil {
@@ -194,31 +198,30 @@ func WriteZipArchiveFromRepository(repo *git.Repository, archivePath string) (er
194 198
 }
195 199
 
196 200
 
197
-// Get root tree without depth and contents
198
-
201
+// TreeFiles struct to get root tree without depth and contents
199 202
 type TreeFiles struct {
200
-	Id		string
201
-	Path		string
202
-	Content		string
203
-	ContentB	[]byte
204
-	ContentH	gotemplate.HTML
205
-	Size		int64	// bytes
206
-	OverSize	bool
207
-	IsBinary	bool
208
-	OverPageSize	bool
209
-	MimeType	string
210
-	LineNos		gotemplate.HTML
203
+	ID           string
204
+	Path         string
205
+	Content      string
206
+	ContentB     []byte
207
+	ContentH     gotemplate.HTML
208
+	Size         int64	// bytes
209
+	OverSize     bool
210
+	IsBinary     bool
211
+	OverPageSize bool
212
+	MimeType     string
213
+	LineNos      gotemplate.HTML
211 214
 }
212 215
 
213 216
 // Content helpers
214
-const RAW_CONTENT_CHECK_SIZE = 5000
217
+const rawContentCheckSize = 5000
215 218
 
216 219
 // isBinary returns true if data's format is binary.
217
-// This function will only check the first RAW_CONTENT_CHECK_SIZE bytes
220
+// This function will only check the first rawContentCheckSize bytes
218 221
 // so it may give false positives even if it is unlikely.
219 222
 func isBinary(data []byte) bool {
220
-	if len(data) > RAW_CONTENT_CHECK_SIZE {
221
-		data = data[:RAW_CONTENT_CHECK_SIZE]
223
+	if len(data) > rawContentCheckSize {
224
+		data = data[:rawContentCheckSize]
222 225
 	}
223 226
 	for _, b := range data {
224 227
 		if b == byte(0x0) {
@@ -244,8 +247,8 @@ func getTreeFile(repo *git.Repository, path string, curSize int64) (treeFile Tre
244 247
 
245 248
 	if len(blob.Contents()) <= 0 {
246 249
 		treeFile.MimeType = "text/plain"
247
-	} else if len(blob.Contents()) > RAW_CONTENT_CHECK_SIZE {
248
-		treeFile.MimeType, err = magicmime.TypeByBuffer(blob.Contents()[:RAW_CONTENT_CHECK_SIZE])
250
+	} else if len(blob.Contents()) > rawContentCheckSize {
251
+		treeFile.MimeType, err = magicmime.TypeByBuffer(blob.Contents()[:rawContentCheckSize])
249 252
 	} else {
250 253
 		treeFile.MimeType, err = magicmime.TypeByBuffer(blob.Contents()[:])
251 254
 	}
@@ -276,11 +279,12 @@ func getTreeFile(repo *git.Repository, path string, curSize int64) (treeFile Tre
276 279
 
277 280
 	treeFile.Size = blob.Size()
278 281
 	treeFile.Path = path
279
-	treeFile.Id = blob.Id().String()
282
+	treeFile.ID = blob.Id().String()
280 283
 
281 284
 	return treeFile, err
282 285
 }
283 286
 
287
+// GetTreeFileNoLimit yeah
284 288
 func GetTreeFileNoLimit(repo *git.Repository, path string) (treeFile TreeFiles, err error) {
285 289
 	tree, err := getRepositoryTree(repo)
286 290
 	if err != nil {
@@ -302,8 +306,8 @@ func GetTreeFileNoLimit(repo *git.Repository, path string) (treeFile TreeFiles,
302 306
 
303 307
 	treeFile.IsBinary = isBinary(blob.Contents())
304 308
 
305
-	if len(blob.Contents()) > RAW_CONTENT_CHECK_SIZE {
306
-		treeFile.MimeType, err = magicmime.TypeByBuffer(blob.Contents()[:RAW_CONTENT_CHECK_SIZE])
309
+	if len(blob.Contents()) > rawContentCheckSize {
310
+		treeFile.MimeType, err = magicmime.TypeByBuffer(blob.Contents()[:rawContentCheckSize])
307 311
 	} else {
308 312
 		treeFile.MimeType, err = magicmime.TypeByBuffer(blob.Contents()[:])
309 313
 	}
@@ -318,12 +322,12 @@ func GetTreeFileNoLimit(repo *git.Repository, path string) (treeFile TreeFiles,
318 322
 
319 323
 	treeFile.Size = blob.Size()
320 324
 	treeFile.Path = path
321
-	treeFile.Id = blob.Id().String()
325
+	treeFile.ID = blob.Id().String()
322 326
 
323 327
 	return treeFile, err
324 328
 }
325 329
 
326
-// TreeFiles.Content will be nil if size is too big
330
+// GetWalkTreeWithContent TreeFiles.Content will be nil if size is too big
327 331
 func GetWalkTreeWithContent(repo *git.Repository, path string) (finalEntries []TreeFiles, err error) {
328 332
 	tree, err := getRepositoryTree(repo)
329 333
 	if err != nil {
@@ -358,7 +362,7 @@ func GetWalkTreeWithContent(repo *git.Repository, path string) (finalEntries []T
358 362
 	return finalEntries, nil
359 363
 }
360 364
 
361
-// We just want the OID
365
+// GetTreeFileOid returns the OID of the Tree File
362 366
 func GetTreeFileOid(repo *git.Repository, path string) (oid *git.Oid, err error) {
363 367
 	tree, err := getRepositoryTree(repo)
364 368
 	if err != nil {

+ 17
- 10
stuff/mailer/mail.go View File

@@ -14,22 +14,24 @@ import (
14 14
 )
15 15
 
16 16
 const (
17
-	MAIL_AUTH_ACTIVATE        = "auth/activate"
18
-	MAIL_AUTH_ACTIVATE_EMAIL  = "auth/activate_email"
19
-	MAIL_AUTH_RESET_PASSWORD  = "auth/reset_passwd"
17
+	tmplMailAuthActivate      = "auth/activate"
18
+	tmplMailAuthActivateEmail = "auth/activate_email"
19
+	tmplMailAuthResetPassword = "auth/reset_passwd"
20 20
 )
21 21
 
22
+// MailRender the template
22 23
 type MailRender interface {
23 24
 	HTMLString(string, interface{}, ...macaron.HTMLOptions) (string, error)
24 25
 }
25 26
 
26 27
 var mailRender MailRender
27 28
 
29
+// InitMailRender templating system
28 30
 func InitMailRender(dir string, funcMap []template.FuncMap) {
29 31
 	opt := &macaron.RenderOptions{
30
-		Directory:         dir,
31
-		Funcs:             funcMap,
32
-		Extensions:        []string{".tmpl", ".html"},
32
+		Directory:  dir,
33
+		Funcs:      funcMap,
34
+		Extensions: []string{".tmpl", ".html"},
33 35
 	}
34 36
 	ts := macaron.NewTemplateSet()
35 37
 	ts.Set(macaron.DEFAULT_TPL_SET_NAME, opt)
@@ -40,6 +42,7 @@ func InitMailRender(dir string, funcMap []template.FuncMap) {
40 42
 	}
41 43
 }
42 44
 
45
+// SendTestMail as indicated
43 46
 func SendTestMail(email string) error {
44 47
 	return gomail.Send(&Sender{}, NewMessage([]string{email}, "git.txt Test Email!", "git.txt Test Email!").Message)
45 48
 }
@@ -48,6 +51,7 @@ func SendTestMail(email string) error {
48 51
 	Setup interfaces of used methods in mail to avoid cycle import.
49 52
 */
50 53
 
54
+// User is email user
51 55
 type User interface {
52 56
 	ID() int64
53 57
 	DisplayName() string
@@ -56,6 +60,7 @@ type User interface {
56 60
 	GenerateEmailActivateCode(string) string
57 61
 }
58 62
 
63
+// SendUserMail to the User
59 64
 func SendUserMail(c *macaron.Context, u User, tpl, code, subject, info string) {
60 65
 	data := map[string]interface{}{
61 66
 		"Username":          u.DisplayName(),
@@ -75,15 +80,17 @@ func SendUserMail(c *macaron.Context, u User, tpl, code, subject, info string) {
75 80
 	SendAsync(msg)
76 81
 }
77 82
 
83
+// SendActivateAccountMail when activating account
78 84
 func SendActivateAccountMail(c *macaron.Context, u User) {
79
-	SendUserMail(c, u, MAIL_AUTH_ACTIVATE, u.GenerateActivateCode(), c.Tr("mail.activate_account"), "activate account")
85
+	SendUserMail(c, u, tmplMailAuthActivate, u.GenerateActivateCode(), c.Tr("mail.activate_account"), "activate account")
80 86
 }
81 87
 
88
+// SendResetPasswordMail when resetting password
82 89
 func SendResetPasswordMail(c *macaron.Context, u User) {
83
-	SendUserMail(c, u, MAIL_AUTH_RESET_PASSWORD, u.GenerateActivateCode(), c.Tr("mail.reset_password"), "reset password")
90
+	SendUserMail(c, u, tmplMailAuthResetPassword, u.GenerateActivateCode(), c.Tr("mail.reset_password"), "reset password")
84 91
 }
85 92
 
86
-// SendActivateAccountMail sends confirmation email.
93
+// SendActivateEmailMail sends confirmation email.
87 94
 func SendActivateEmailMail(c *macaron.Context, u User, email string) {
88 95
 	data := map[string]interface{}{
89 96
 		"Username":        u.DisplayName(),
@@ -91,7 +98,7 @@ func SendActivateEmailMail(c *macaron.Context, u User, email string) {
91 98
 		"Code":            u.GenerateEmailActivateCode(email),
92 99
 		"Email":           email,
93 100
 	}
94
-	body, err := mailRender.HTMLString(string(MAIL_AUTH_ACTIVATE_EMAIL), data)
101
+	body, err := mailRender.HTMLString(string(tmplMailAuthActivateEmail), data)
95 102
 	if err != nil {
96 103
 		log.Error(3, "HTMLString: %v", err)
97 104
 		return

+ 8
- 1
stuff/mailer/mailer.go View File

@@ -21,6 +21,7 @@ import (
21 21
 	"dev.sigpipe.me/dashie/git.txt/setting"
22 22
 )
23 23
 
24
+// Message content
24 25
 type Message struct {
25 26
 	Info string // Message information for log purpose.
26 27
 	*gomail.Message
@@ -63,15 +64,17 @@ type loginAuth struct {
63 64
 	username, password string
64 65
 }
65 66
 
66
-// SMTP AUTH LOGIN Auth Handler
67
+// LoginAuth SMTP AUTH LOGIN Auth Handler
67 68
 func LoginAuth(username, password string) smtp.Auth {
68 69
 	return &loginAuth{username, password}
69 70
 }
70 71
 
72
+// Start the sending
71 73
 func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
72 74
 	return "LOGIN", []byte{}, nil
73 75
 }
74 76
 
77
+// Next switch to next action
75 78
 func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
76 79
 	if more {
77 80
 		switch string(fromServer) {
@@ -86,9 +89,11 @@ func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
86 89
 	return nil, nil
87 90
 }
88 91
 
92
+// Sender struct
89 93
 type Sender struct {
90 94
 }
91 95
 
96
+// Send the mail
92 97
 func (s *Sender) Send(from string, to []string, msg io.WriterTo) error {
93 98
 	opts := setting.MailService
94 99
 
@@ -210,6 +215,7 @@ func processMailQueue() {
210 215
 
211 216
 var mailQueue chan *Message
212 217
 
218
+// NewContext initiate the mailing process
213 219
 func NewContext() {
214 220
 	// Need to check if mailQueue is nil because in during reinstall (user had installed
215 221
 	// before but swithed install lock off), this function will be called again
@@ -222,6 +228,7 @@ func NewContext() {
222 228
 	go processMailQueue()
223 229
 }
224 230
 
231
+// SendAsync in the background
225 232
 func SendAsync(msg *Message) {
226 233
 	go func() {
227 234
 		mailQueue <- msg

+ 3
- 3
stuff/markup/markdown.go View File

@@ -62,7 +62,7 @@ func (r *MarkdownRenderer) AutoLink(out *bytes.Buffer, link []byte, kind int) {
62 62
 }
63 63
 
64 64
 // ListItem defines how list items should be processed to produce corresponding HTML elements.
65
-func (options *MarkdownRenderer) ListItem(out *bytes.Buffer, text []byte, flags int) {
65
+func (r *MarkdownRenderer) ListItem(out *bytes.Buffer, text []byte, flags int) {
66 66
 	// Detect procedures to draw checkboxes.
67 67
 	switch {
68 68
 	case bytes.HasPrefix(text, []byte("[ ] ")):
@@ -70,7 +70,7 @@ func (options *MarkdownRenderer) ListItem(out *bytes.Buffer, text []byte, flags
70 70
 	case bytes.HasPrefix(text, []byte("[x] ")):
71 71
 		text = append([]byte(`<input type="checkbox" disabled="" checked="" />`), text[3:]...)
72 72
 	}
73
-	options.Renderer.ListItem(out, text, flags)
73
+	r.Renderer.ListItem(out, text, flags)
74 74
 }
75 75
 
76 76
 // RawMarkdown renders Markdown to HTML without handling special links.
@@ -120,5 +120,5 @@ func RawMarkdown(body []byte, urlPrefix string) []byte {
120 120
 
121 121
 // Markdown takes a string or []byte and renders to HTML in Markdown syntax with special links.
122 122
 func Markdown(input interface{}, urlPrefix string) []byte {
123
-	return Render(MARKDOWN, input, urlPrefix)
123
+	return Render(typeMarkdown, input, urlPrefix)
124 124
 }

+ 6
- 12
stuff/markup/markup.go View File

@@ -23,11 +23,6 @@ func IsReadmeFile(name string) bool {
23 23
 	return strings.HasPrefix(strings.ToLower(name), "readme")
24 24
 }
25 25
 
26
-const (
27
-	ISSUE_NAME_STYLE_NUMERIC      = "numeric"
28
-	ISSUE_NAME_STYLE_ALPHANUMERIC = "alphanumeric"
29
-)
30
-
31 26
 var (
32 27
 	// MentionPattern matches string that mentions someone, e.g. @Unknwon
33 28
 	MentionPattern = regexp.MustCompile(`(\s|^|\W)@[0-9a-zA-Z-_\.]+`)
@@ -81,12 +76,10 @@ func cutoutVerbosePrefix(prefix string) string {
81 76
 	return prefix
82 77
 }
83 78
 
84
-
85 79
 // Note: this section is for purpose of increase performance and
86 80
 // reduce memory allocation at runtime since they are constant literals.
87 81
 var pound = []byte("#")
88 82
 
89
-
90 83
 // RenderSha1CurrentPattern renders SHA1 strings to corresponding links that assumes in the same repository.
91 84
 func RenderSha1CurrentPattern(rawBytes []byte, urlPrefix string) []byte {
92 85
 	return []byte(Sha1CurrentPattern.ReplaceAllStringFunc(string(rawBytes[:]), func(m string) string {
@@ -251,12 +244,13 @@ OUTER_LOOP:
251 244
 	return rawHTML
252 245
 }
253 246
 
247
+// Type of special text