Browse Source

Merge branch 'master' of https://gitote.in/gitote/gitote

Yoginth 7 years ago
parent
commit
ba6e060c4b
100 changed files with 1200 additions and 783 deletions
  1. 2 0
      .vscode/extensions.json
  2. 1 1
      .vscode/settings.json
  3. 16 0
      .vscode/tasks.json
  4. 6 4
      README.md
  5. 1 0
      cmd/admin.go
  6. 2 0
      cmd/cert_stub.go
  7. 19 18
      cmd/hook.go
  8. 2 1
      cmd/import.go
  9. 13 11
      cmd/serv.go
  10. 4 3
      cmd/web.go
  11. 2 0
      conf/app.ini
  12. 1 1
      gitote.go
  13. 23 17
      models/access.go
  14. 101 65
      models/action.go
  15. 8 4
      models/admin.go
  16. 6 4
      models/attachment.go
  17. 58 47
      models/comment.go
  18. 69 0
      models/error.go
  19. 8 0
      models/git_diff.go
  20. 89 74
      models/issue.go
  21. 4 3
      models/issue_label.go
  22. 27 23
      models/issue_mail.go
  23. 88 47
      models/login_source.go
  24. 9 3
      models/milestone.go
  25. 18 10
      models/mirror.go
  26. 2 2
      models/mirror_test.go
  27. 31 12
      models/models.go
  28. 17 16
      models/org.go
  29. 6 5
      models/org_team.go
  30. 66 57
      models/pull.go
  31. 5 2
      models/release.go
  32. 73 45
      models/repo.go
  33. 11 6
      models/repo_branch.go
  34. 12 8
      models/repo_collaboration.go
  35. 44 19
      models/repo_editor.go
  36. 36 0
      models/repo_editor_test.go
  37. 6 6
      models/repo_test.go
  38. 12 12
      models/ssh_key.go
  39. 1 1
      models/two_factor.go
  40. 1 0
      models/update.go
  41. 20 17
      models/user.go
  42. 6 1
      models/user_mail.go
  43. 30 29
      models/webhook.go
  44. 12 8
      models/webhook_discord.go
  45. 12 9
      models/webhook_slack.go
  46. 1 1
      models/wiki.go
  47. 1 1
      pkg/context/context.go
  48. 1 1
      pkg/context/org.go
  49. 6 6
      pkg/context/repo.go
  50. 1 1
      pkg/form/admin.go
  51. 1 1
      pkg/form/form.go
  52. 2 1
      pkg/form/repo.go
  53. 1 1
      pkg/form/user.go
  54. 9 1
      pkg/mailer/mailer.go
  55. 2 2
      pkg/markup/markdown.go
  56. 2 2
      pkg/markup/markdown_test.go
  57. 13 10
      pkg/markup/markup.go
  58. 2 2
      pkg/markup/markup_test.go
  59. 15 13
      pkg/setting/setting.go
  60. 1 1
      pkg/ssh/ssh.go
  61. 1 1
      pkg/sync/unique_queue.go
  62. 3 3
      pkg/template/template.go
  63. 5 6
      pkg/tool/path.go
  64. 14 10
      pkg/tool/path_test.go
  65. 4 4
      pkg/tool/tool.go
  66. 1 1
      public/css/gitote.min.css
  67. 10 0
      public/less/_dashboard.less
  68. 1 1
      public/less/_repository.less
  69. 1 1
      public/less/_user.less
  70. 21 21
      routes/admin/admin.go
  71. 16 16
      routes/admin/auths.go
  72. 2 2
      routes/admin/news.go
  73. 1 1
      routes/admin/notice.go
  74. 1 1
      routes/admin/orgs.go
  75. 4 4
      routes/admin/users.go
  76. 1 1
      routes/api/v1/admin/user.go
  77. 1 1
      routes/api/v1/api.go
  78. 1 1
      routes/api/v1/convert/convert.go
  79. 1 1
      routes/api/v1/org/org.go
  80. 17 17
      routes/api/v1/repo/hook.go
  81. 2 2
      routes/api/v1/repo/issue_comment.go
  82. 1 1
      routes/api/v1/repo/label.go
  83. 2 2
      routes/api/v1/repo/repo.go
  84. 2 2
      routes/api/v1/user/user.go
  85. 3 3
      routes/explore.go
  86. 1 1
      routes/install.go
  87. 1 1
      routes/org/members.go
  88. 1 1
      routes/org/org.go
  89. 4 4
      routes/org/teams.go
  90. 1 1
      routes/repo/branch.go
  91. 2 2
      routes/repo/http.go
  92. 12 12
      routes/repo/issue.go
  93. 2 2
      routes/repo/pull.go
  94. 1 1
      routes/repo/repo.go
  95. 3 2
      routes/repo/setting.go
  96. 2 2
      routes/repo/webhook.go
  97. 10 10
      routes/user/home.go
  98. 3 3
      routes/user/setting.go
  99. 3 3
      templates/admin/news/edit.tmpl
  100. 0 0
      templates/admin/user/edit.tmpl

+ 2 - 0
.vscode/extensions.json

@@ -4,5 +4,7 @@
         "michelemelluso.code-beautifier",
         "ms-vscode.go",
         "robertohuertasm.vscode-icons",
+        "joaoacdias.golang-tdd",
+        "valiantsin.operatormonodarktheme",
     ]
 }

+ 1 - 1
.vscode/settings.json

@@ -1,7 +1,7 @@
 {
     "files.autoSave": "afterDelay",
     "editor.fontSize": 14,
-    "editor.fontFamily": "'Droid Sans Mono', 'monospace', monospace, 'Droid Sans Fallback'",
+    "editor.fontFamily": "Operator Mono, Consolas, 'Courier New', monospace",
     "diffEditor.ignoreTrimWhitespace": true,
     "editor.autoClosingBrackets": "always",
     "editor.autoClosingQuotes": "always",

+ 16 - 0
.vscode/tasks.json

@@ -0,0 +1,16 @@
+{
+    // See https://go.microsoft.com/fwlink/?LinkId=733558
+    // for the documentation about the tasks.json format
+    "version": "2.0.0",
+    "tasks": [
+        {
+            "label": "Build Gitote",
+            "type": "shell",
+            "command": "go build",
+            "group": {
+                "kind": "build",
+                "isDefault": true
+            }
+        }
+    ]
+}

File diff suppressed because it is too large
+ 6 - 4
README.md


+ 1 - 0
cmd/admin.go

@@ -18,6 +18,7 @@ import (
 )
 
 var (
+	// Admin Initialize admin CLI
 	Admin = cli.Command{
 		Name:        "admin",
 		Usage:       "Perform admin operations on command line",

+ 2 - 0
cmd/cert_stub.go

@@ -15,6 +15,7 @@ import (
 	"github.com/urfave/cli"
 )
 
+// Cert Initialize cert CLI
 var Cert = cli.Command{
 	Name:        "cert",
 	Usage:       "Generate self-signed certificate",
@@ -22,6 +23,7 @@ var Cert = cli.Command{
 	Action:      runCert,
 }
 
+// runCert builds cert CLI
 func runCert(ctx *cli.Context) error {
 	fmt.Println("Command cert not available, please use build tags 'cert' to rebuild.")
 	os.Exit(1)

+ 19 - 18
cmd/hook.go

@@ -23,14 +23,15 @@ import (
 	"path/filepath"
 	"strings"
 
-	"github.com/Unknwon/com"
 	raven "github.com/getsentry/raven-go"
 	"github.com/urfave/cli"
+	"gitlab.com/gitote/com"
 	"gitlab.com/gitote/git-module"
 	log "gopkg.in/clog.v1"
 )
 
 var (
+	// Hook Initialize hook CLI
 	Hook = cli.Command{
 		Name:        "hook",
 		Usage:       "Delegate commands to corresponding Git hooks",
@@ -71,7 +72,7 @@ func runHookPreReceive(c *cli.Context) error {
 	}
 	setup(c, "hooks/pre-receive.log", true)
 
-	isWiki := strings.Contains(os.Getenv(models.ENV_REPO_CUSTOM_HOOKS_PATH), ".wiki.git/")
+	isWiki := strings.Contains(os.Getenv(models.EnvRepoCustomHookPath), ".wiki.git/")
 
 	buf := bytes.NewBuffer(nil)
 	scanner := bufio.NewScanner(os.Stdin)
@@ -92,7 +93,7 @@ func runHookPreReceive(c *cli.Context) error {
 		branchName := strings.TrimPrefix(string(fields[2]), git.BRANCH_PREFIX)
 
 		// Branch protection
-		repoID := com.StrTo(os.Getenv(models.ENV_REPO_ID)).MustInt64()
+		repoID := com.StrTo(os.Getenv(models.EnvRepoID)).MustInt64()
 		protectBranch, err := models.GetProtectBranchOfRepoByName(repoID, branchName)
 		if err != nil {
 			if errors.IsErrBranchNotExist(err) {
@@ -108,7 +109,7 @@ func runHookPreReceive(c *cli.Context) error {
 		bypassRequirePullRequest := false
 
 		// Check if user is in whitelist when enabled
-		userID := com.StrTo(os.Getenv(models.ENV_AUTH_USER_ID)).MustInt64()
+		userID := com.StrTo(os.Getenv(models.EnvAuthUserID)).MustInt64()
 		if protectBranch.EnableWhitelist {
 			if !models.IsUserInProtectBranchWhitelist(repoID, userID, branchName) {
 				fail(fmt.Sprintf("Branch '%s' is protected and you are not in the push whitelist", branchName), "")
@@ -129,7 +130,7 @@ func runHookPreReceive(c *cli.Context) error {
 
 		// Check force push
 		output, err := git.NewCommand("rev-list", "--max-count=1", oldCommitID, "^"+newCommitID).
-			RunInDir(models.RepoPath(os.Getenv(models.ENV_REPO_OWNER_NAME), os.Getenv(models.ENV_REPO_NAME)))
+			RunInDir(models.RepoPath(os.Getenv(models.EnvRepoOwnerName), os.Getenv(models.EnvRepoName)))
 		if err != nil {
 			fail("Internal error", "Fail to detect force push: %v", err)
 		} else if len(output) > 0 {
@@ -137,7 +138,7 @@ func runHookPreReceive(c *cli.Context) error {
 		}
 	}
 
-	customHooksPath := filepath.Join(os.Getenv(models.ENV_REPO_CUSTOM_HOOKS_PATH), "pre-receive")
+	customHooksPath := filepath.Join(os.Getenv(models.EnvRepoCustomHookPath), "pre-receive")
 	if !com.IsFile(customHooksPath) {
 		return nil
 	}
@@ -148,7 +149,7 @@ func runHookPreReceive(c *cli.Context) error {
 	} else {
 		hookCmd = exec.Command(customHooksPath)
 	}
-	hookCmd.Dir = models.RepoPath(os.Getenv(models.ENV_REPO_OWNER_NAME), os.Getenv(models.ENV_REPO_NAME))
+	hookCmd.Dir = models.RepoPath(os.Getenv(models.EnvRepoOwnerName), os.Getenv(models.EnvRepoName))
 	hookCmd.Stdout = os.Stdout
 	hookCmd.Stdin = buf
 	hookCmd.Stderr = os.Stderr
@@ -171,7 +172,7 @@ func runHookUpdate(c *cli.Context) error {
 		fail("First argument 'refName' is empty", "First argument 'refName' is empty")
 	}
 
-	customHooksPath := filepath.Join(os.Getenv(models.ENV_REPO_CUSTOM_HOOKS_PATH), "update")
+	customHooksPath := filepath.Join(os.Getenv(models.EnvRepoCustomHookPath), "update")
 	if !com.IsFile(customHooksPath) {
 		return nil
 	}
@@ -182,7 +183,7 @@ func runHookUpdate(c *cli.Context) error {
 	} else {
 		hookCmd = exec.Command(customHooksPath, args...)
 	}
-	hookCmd.Dir = models.RepoPath(os.Getenv(models.ENV_REPO_OWNER_NAME), os.Getenv(models.ENV_REPO_NAME))
+	hookCmd.Dir = models.RepoPath(os.Getenv(models.EnvRepoOwnerName), os.Getenv(models.EnvRepoName))
 	hookCmd.Stdout = os.Stdout
 	hookCmd.Stdin = os.Stdin
 	hookCmd.Stderr = os.Stderr
@@ -205,7 +206,7 @@ func runHookPostReceive(c *cli.Context) error {
 	mailer.InitMailRender(path.Join(setting.StaticRootPath, "templates/mail"),
 		path.Join(setting.CustomPath, "templates/mail"), template.NewFuncMap())
 
-	isWiki := strings.Contains(os.Getenv(models.ENV_REPO_CUSTOM_HOOKS_PATH), ".wiki.git/")
+	isWiki := strings.Contains(os.Getenv(models.EnvRepoCustomHookPath), ".wiki.git/")
 
 	buf := bytes.NewBuffer(nil)
 	scanner := bufio.NewScanner(os.Stdin)
@@ -227,10 +228,10 @@ func runHookPostReceive(c *cli.Context) error {
 			OldCommitID:  string(fields[0]),
 			NewCommitID:  string(fields[1]),
 			RefFullName:  string(fields[2]),
-			PusherID:     com.StrTo(os.Getenv(models.ENV_AUTH_USER_ID)).MustInt64(),
-			PusherName:   os.Getenv(models.ENV_AUTH_USER_NAME),
-			RepoUserName: os.Getenv(models.ENV_REPO_OWNER_NAME),
-			RepoName:     os.Getenv(models.ENV_REPO_NAME),
+			PusherID:     com.StrTo(os.Getenv(models.EnvAuthUserID)).MustInt64(),
+			PusherName:   os.Getenv(models.EnvAuthUsername),
+			RepoUserName: os.Getenv(models.EnvRepoOwnerName),
+			RepoName:     os.Getenv(models.EnvRepoName),
 		}
 		if err := models.PushUpdate(options); err != nil {
 			raven.CaptureErrorAndWait(err, nil)
@@ -240,8 +241,8 @@ func runHookPostReceive(c *cli.Context) error {
 		// Ask for running deliver hook and test pull request tasks
 		reqURL := setting.LocalURL + options.RepoUserName + "/" + options.RepoName + "/tasks/trigger?branch=" +
 			template.EscapePound(strings.TrimPrefix(options.RefFullName, git.BRANCH_PREFIX)) +
-			"&secret=" + os.Getenv(models.ENV_REPO_OWNER_SALT_MD5) +
-			"&pusher=" + os.Getenv(models.ENV_AUTH_USER_ID)
+			"&secret=" + os.Getenv(models.EnvRepoOwnerSlatMD5) +
+			"&pusher=" + os.Getenv(models.EnvAuthUserID)
 		log.Trace("Trigger task: %s", reqURL)
 
 		resp, err := httplib.Head(reqURL).SetTLSClientConfig(&tls.Config{
@@ -258,7 +259,7 @@ func runHookPostReceive(c *cli.Context) error {
 		}
 	}
 
-	customHooksPath := filepath.Join(os.Getenv(models.ENV_REPO_CUSTOM_HOOKS_PATH), "post-receive")
+	customHooksPath := filepath.Join(os.Getenv(models.EnvRepoCustomHookPath), "post-receive")
 	if !com.IsFile(customHooksPath) {
 		return nil
 	}
@@ -269,7 +270,7 @@ func runHookPostReceive(c *cli.Context) error {
 	} else {
 		hookCmd = exec.Command(customHooksPath)
 	}
-	hookCmd.Dir = models.RepoPath(os.Getenv(models.ENV_REPO_OWNER_NAME), os.Getenv(models.ENV_REPO_NAME))
+	hookCmd.Dir = models.RepoPath(os.Getenv(models.EnvRepoOwnerName), os.Getenv(models.EnvRepoName))
 	hookCmd.Stdout = os.Stdout
 	hookCmd.Stdin = buf
 	hookCmd.Stderr = os.Stderr

+ 2 - 1
cmd/import.go

@@ -15,11 +15,12 @@ import (
 	"path/filepath"
 	"time"
 
-	"github.com/Unknwon/com"
 	"github.com/urfave/cli"
+	"gitlab.com/gitote/com"
 )
 
 var (
+	// Import Initialize import CLI
 	Import = cli.Command{
 		Name:  "import",
 		Usage: "Import portable data as local Gitote data",

+ 13 - 11
cmd/serv.go

@@ -17,15 +17,17 @@ import (
 	"strings"
 	"time"
 
-	"github.com/Unknwon/com"
 	"github.com/urfave/cli"
+	"gitlab.com/gitote/com"
 	log "gopkg.in/clog.v1"
 )
 
 const (
-	_ACCESS_DENIED_MESSAGE = "Repository does not exist or you do not have access"
+	// AccessDeniedMessage Show Access Denied Message
+	AccessDeniedMessage = "Repository does not exist or you do not have access"
 )
 
+// Serv Initialize serv CLI
 var Serv = cli.Command{
 	Name:        "serv",
 	Usage:       "This command should only be called by SSH shell",
@@ -117,9 +119,9 @@ func checkDeployKey(key *models.PublicKey, repo *models.Repository) {
 
 var (
 	allowedCommands = map[string]models.AccessMode{
-		"git-upload-pack":    models.ACCESS_MODE_READ,
-		"git-upload-archive": models.ACCESS_MODE_READ,
-		"git-receive-pack":   models.ACCESS_MODE_WRITE,
+		"git-upload-pack":    models.AccessModeRead,
+		"git-upload-archive": models.AccessModeRead,
+		"git-receive-pack":   models.AccessModeWrite,
 	}
 )
 
@@ -163,7 +165,7 @@ func runServ(c *cli.Context) error {
 	repo, err := models.GetRepositoryByName(owner.ID, repoName)
 	if err != nil {
 		if errors.IsRepoNotExist(err) {
-			fail(_ACCESS_DENIED_MESSAGE, "Repository does not exist: %s/%s", owner.Name, repoName)
+			fail(AccessDeniedMessage, "Repository does not exist: %s/%s", owner.Name, repoName)
 		}
 		fail("Internal error", "Fail to get repository: %v", err)
 	}
@@ -175,7 +177,7 @@ func runServ(c *cli.Context) error {
 	}
 
 	// Prohibit push to mirror repositories.
-	if requestMode > models.ACCESS_MODE_READ && repo.IsMirror {
+	if requestMode > models.AccessModeRead && repo.IsMirror {
 		fail("Mirror repository is read-only", "")
 	}
 
@@ -187,7 +189,7 @@ func runServ(c *cli.Context) error {
 		fail("Invalid key ID", "Invalid key ID '%s': %v", c.Args()[0], err)
 	}
 
-	if requestMode == models.ACCESS_MODE_WRITE || repo.IsPrivate {
+	if requestMode == models.AccessModeWrite || repo.IsPrivate {
 		// Check deploy key or user key.
 		if key.IsDeployKey() {
 			if key.Mode < requestMode {
@@ -206,8 +208,8 @@ func runServ(c *cli.Context) error {
 			}
 
 			if mode < requestMode {
-				clientMessage := _ACCESS_DENIED_MESSAGE
-				if mode >= models.ACCESS_MODE_READ {
+				clientMessage := AccessDeniedMessage
+				if mode >= models.AccessModeRead {
 					clientMessage = "You do not have sufficient authorization for this action"
 				}
 				fail(clientMessage,
@@ -251,7 +253,7 @@ func runServ(c *cli.Context) error {
 	} else {
 		gitCmd = exec.Command(verb, repoFullName)
 	}
-	if requestMode == models.ACCESS_MODE_WRITE {
+	if requestMode == models.AccessModeWrite {
 		gitCmd.Env = append(os.Environ(), models.ComposeHookEnvs(models.ComposeHookEnvsOptions{
 			AuthUser:  user,
 			OwnerName: owner.Name,

+ 4 - 3
cmd/web.go

@@ -31,7 +31,7 @@ import (
 	"path"
 	"strings"
 
-	"github.com/Unknwon/com"
+	"gitlab.com/gitote/com"
 	raven "github.com/getsentry/raven-go"
 	"github.com/go-macaron/binding"
 	"github.com/go-macaron/cache"
@@ -47,6 +47,7 @@ import (
 	"gopkg.in/macaron.v1"
 )
 
+// Web Initialize web CLI
 var Web = cli.Command{
 	Name:  "web",
 	Usage: "Start web server",
@@ -81,14 +82,14 @@ func newMacaron() *macaron.Macaron {
 	m.Use(macaron.Static(
 		setting.AvatarUploadPath,
 		macaron.StaticOptions{
-			Prefix:      models.USER_AVATAR_URL_PREFIX,
+			Prefix:      models.UserAvatarURLPrefix,
 			SkipLogging: setting.DisableRouterLog,
 		},
 	))
 	m.Use(macaron.Static(
 		setting.RepositoryAvatarUploadPath,
 		macaron.StaticOptions{
-			Prefix:      models.REPO_AVATAR_URL_PREFIX,
+			Prefix:      models.RepoAvatarURLPrefix,
 			SkipLogging: setting.DisableRouterLog,
 		},
 	))

+ 2 - 0
conf/app.ini

@@ -243,6 +243,8 @@ USER =
 PASSWD =
 ; Use text/plain as format of content
 USE_PLAIN_TEXT = false
+; If sending html emails, then also attach a plaintext alternative to the MIME message, to support older mail clients and make spam filters happier.
+ADD_PLAIN_TEXT_ALT = false
 
 [cache]
 ; Either "memory", "redis", or "memcache", default is "memory"

+ 1 - 1
gitote.go

@@ -29,7 +29,7 @@ import (
 )
 
 // AppVer represents the version of Gitote
-const AppVer = "1.0.1-prod-rc.21"
+const AppVer = "1.0.1-prod-rc.25"
 
 // APIVer represents the API version of Gitote
 const APIVer = "v1"

+ 23 - 17
models/access.go

@@ -14,25 +14,31 @@ import (
 	log "gopkg.in/clog.v1"
 )
 
+// AccessMode specifies the users access mode
 type AccessMode int
 
 const (
-	ACCESS_MODE_NONE  AccessMode = iota // 0
-	ACCESS_MODE_READ                    // 1
-	ACCESS_MODE_WRITE                   // 2
-	ACCESS_MODE_ADMIN                   // 3
-	ACCESS_MODE_OWNER                   // 4
+	// AccessModeNone no access
+	AccessModeNone AccessMode = iota // 0
+	// AccessModeRead read access
+	AccessModeRead // 1
+	// AccessModeWrite write access
+	AccessModeWrite // 2
+	// AccessModeAdmin admin access
+	AccessModeAdmin // 3
+	// AccessModeOwner owner access
+	AccessModeOwner // 4
 )
 
 func (mode AccessMode) String() string {
 	switch mode {
-	case ACCESS_MODE_READ:
+	case AccessModeRead:
 		return "read"
-	case ACCESS_MODE_WRITE:
+	case AccessModeWrite:
 		return "write"
-	case ACCESS_MODE_ADMIN:
+	case AccessModeAdmin:
 		return "admin"
-	case ACCESS_MODE_OWNER:
+	case AccessModeOwner:
 		return "owner"
 	default:
 		return "none"
@@ -43,11 +49,11 @@ func (mode AccessMode) String() string {
 func ParseAccessMode(permission string) AccessMode {
 	switch permission {
 	case "write":
-		return ACCESS_MODE_WRITE
+		return AccessModeWrite
 	case "admin":
-		return ACCESS_MODE_ADMIN
+		return AccessModeAdmin
 	default:
-		return ACCESS_MODE_READ
+		return AccessModeRead
 	}
 }
 
@@ -62,10 +68,10 @@ type Access struct {
 }
 
 func accessLevel(e Engine, userID int64, repo *Repository) (AccessMode, error) {
-	mode := ACCESS_MODE_NONE
+	mode := AccessModeNone
 	// Everyone has read access to public repository
 	if !repo.IsPrivate {
-		mode = ACCESS_MODE_READ
+		mode = AccessModeRead
 	}
 
 	if userID <= 0 {
@@ -73,7 +79,7 @@ func accessLevel(e Engine, userID int64, repo *Repository) (AccessMode, error) {
 	}
 
 	if userID == repo.OwnerID {
-		return ACCESS_MODE_OWNER, nil
+		return AccessModeOwner, nil
 	}
 
 	access := &Access{
@@ -142,7 +148,7 @@ func (user *User) GetAccessibleRepositories(limit int) (repos []*Repository, _ e
 }
 
 func maxAccessMode(modes ...AccessMode) AccessMode {
-	max := ACCESS_MODE_NONE
+	max := AccessModeNone
 	for _, mode := range modes {
 		if mode > max {
 			max = mode
@@ -211,7 +217,7 @@ func (repo *Repository) recalculateTeamAccesses(e Engine, ignTeamID int64) (err
 		// Owner team gets owner access, and skip for teams that do not
 		// have relations with repository.
 		if t.IsOwnerTeam() {
-			t.Authorize = ACCESS_MODE_OWNER
+			t.Authorize = AccessModeOwner
 		} else if !t.hasRepository(e, repo.ID) {
 			continue
 		}

+ 101 - 65
models/action.go

@@ -17,50 +17,55 @@ import (
 	"time"
 	"unicode"
 
-	"github.com/Unknwon/com"
 	raven "github.com/getsentry/raven-go"
 	"github.com/go-xorm/xorm"
 	"github.com/json-iterator/go"
+	"gitlab.com/gitote/com"
 	"gitlab.com/gitote/git-module"
 	api "gitlab.com/gitote/go-gitote-client"
 	log "gopkg.in/clog.v1"
 )
 
+// ActionType represents the type of an action.
 type ActionType int
 
-// Note: To maintain backward compatibility only append to the end of list
+// Possible action types.
 const (
-	ACTION_CREATE_REPO         ActionType = iota + 1 // 1
-	ACTION_RENAME_REPO                               // 2
-	ACTION_STAR_REPO                                 // 3
-	ACTION_WATCH_REPO                                // 4
-	ACTION_COMMIT_REPO                               // 5
-	ACTION_CREATE_ISSUE                              // 6
-	ACTION_CREATE_PULL_REQUEST                       // 7
-	ACTION_TRANSFER_REPO                             // 8
-	ACTION_PUSH_TAG                                  // 9
-	ACTION_COMMENT_ISSUE                             // 10
-	ACTION_MERGE_PULL_REQUEST                        // 11
-	ACTION_CLOSE_ISSUE                               // 12
-	ACTION_REOPEN_ISSUE                              // 13
-	ACTION_CLOSE_PULL_REQUEST                        // 14
-	ACTION_REOPEN_PULL_REQUEST                       // 15
-	ACTION_CREATE_BRANCH                             // 16
-	ACTION_DELETE_BRANCH                             // 17
-	ACTION_DELETE_TAG                                // 18
-	ACTION_FORK_REPO                                 // 19
-	ACTION_MIRROR_SYNC_PUSH                          // 20
-	ACTION_MIRROR_SYNC_CREATE                        // 21
-	ACTION_MIRROR_SYNC_DELETE                        // 22
+	ActionCreateRepo        ActionType = iota + 1 // 1
+	ActionRenameRepo                              // 2
+	ActionStarRepo                                // 3
+	ActionWatchRepo                               // 4
+	ActionCommitRepo                              // 5
+	ActionCreateIssue                             // 6
+	ActionCreatePullRequest                       // 7
+	ActionTransferRepo                            // 8
+	ActionPushTag                                 // 9
+	ActionCommentIssue                            // 10
+	ActionMergePullRequest                        // 11
+	ActionCloseIssue                              // 12
+	ActionReopenIssue                             // 13
+	ActionClosePullRequest                        // 14
+	ActionReopenPullRequest                       // 15
+	ActionCreateBranch                            // 16
+	ActionDeleteBranch                            // 17
+	ActionDeleteTag                               // 18
+	ActionForkRepo                                // 19
+	ActionMirrorSyncPush                          // 20
+	ActionMirrorSyncCreate                        // 21
+	ActionMirrorSyncDelete                        // 22
 )
 
 var (
-	// Same as Github. See https://help.github.com/articles/closing-issues-via-commit-messages
-	IssueCloseKeywords  = []string{"close", "closes", "closed", "fix", "fixes", "fixed", "resolve", "resolves", "resolved"}
+	// IssueCloseKeywords Same as Github.
+	// See https://help.github.com/articles/closing-issues-via-commit-messages
+	IssueCloseKeywords = []string{"close", "closes", "closed", "fix", "fixes", "fixed", "resolve", "resolves", "resolved"}
+	// IssueReopenKeywords Same as Github.
 	IssueReopenKeywords = []string{"reopen", "reopens", "reopened"}
-
-	IssueCloseKeywordsPat     = regexp.MustCompile(assembleKeywordsPattern(IssueCloseKeywords))
-	IssueReopenKeywordsPat    = regexp.MustCompile(assembleKeywordsPattern(IssueReopenKeywords))
+	// IssueCloseKeywordsPat close keyword pattern
+	IssueCloseKeywordsPat = regexp.MustCompile(assembleKeywordsPattern(IssueCloseKeywords))
+	// IssueReopenKeywordsPat reopen keyword pattern
+	IssueReopenKeywordsPat = regexp.MustCompile(assembleKeywordsPattern(IssueReopenKeywords))
+	// IssueReferenceKeywordsPat reference keyword pattern
 	IssueReferenceKeywordsPat = regexp.MustCompile(`(?i)(?:)(^| )\S+`)
 )
 
@@ -87,10 +92,12 @@ type Action struct {
 	CreatedUnix  int64
 }
 
+// BeforeInsert will be invoked by XORM before inserting a record
 func (a *Action) BeforeInsert() {
 	a.CreatedUnix = time.Now().Unix()
 }
 
+// AfterSet is invoked from XORM after setting the values of all fields of this object.
 func (a *Action) AfterSet(colName string, _ xorm.Cell) {
 	switch colName {
 	case "created_unix":
@@ -98,42 +105,56 @@ func (a *Action) AfterSet(colName string, _ xorm.Cell) {
 	}
 }
 
+// GetOpType gets the ActionType of this action.
 func (a *Action) GetOpType() int {
 	return int(a.OpType)
 }
 
+// GetActUserName gets the action's user name.
 func (a *Action) GetActUserName() string {
 	return a.ActUserName
 }
 
+// ShortActUserName gets the action's user name trimmed to max 20
+// chars.
 func (a *Action) ShortActUserName() string {
 	return tool.EllipsisString(a.ActUserName, 20)
 }
 
+// GetRepoUserName returns the name of the action repository owner.
 func (a *Action) GetRepoUserName() string {
 	return a.RepoUserName
 }
 
+// ShortRepoUserName returns the name of the action repository owner
+// trimmed to max 20 chars.
 func (a *Action) ShortRepoUserName() string {
 	return tool.EllipsisString(a.RepoUserName, 20)
 }
 
+// GetRepoName returns the name of the action repository.
 func (a *Action) GetRepoName() string {
 	return a.RepoName
 }
 
+// ShortRepoName returns the name of the action repository
+// trimmed to max 33 chars.
 func (a *Action) ShortRepoName() string {
 	return tool.EllipsisString(a.RepoName, 33)
 }
 
+// GetRepoPath returns the virtual path to the action repository.
 func (a *Action) GetRepoPath() string {
 	return path.Join(a.RepoUserName, a.RepoName)
 }
 
+// ShortRepoPath returns the virtual path to the action repository
+// trimmed to max 20 + 1 + 33 chars.
 func (a *Action) ShortRepoPath() string {
 	return path.Join(a.ShortRepoUserName(), a.ShortRepoName())
 }
 
+// GetRepoLink returns relative link to action repository.
 func (a *Action) GetRepoLink() string {
 	if len(setting.AppSubURL) > 0 {
 		return path.Join(setting.AppSubURL, a.GetRepoPath())
@@ -141,22 +162,29 @@ func (a *Action) GetRepoLink() string {
 	return "/" + a.GetRepoPath()
 }
 
+// GetBranch returns the action's repository branch.
 func (a *Action) GetBranch() string {
 	return a.RefName
 }
 
+// GetContent returns the action's content.
 func (a *Action) GetContent() string {
 	return a.Content
 }
 
+// GetCreate returns the action creation time.
 func (a *Action) GetCreate() time.Time {
 	return a.Created
 }
 
+// GetIssueInfos returns a list of issues associated with
+// the action.
 func (a *Action) GetIssueInfos() []string {
 	return strings.SplitN(a.Content, "|", 2)
 }
 
+// GetIssueTitle returns the title of first issue associated
+// with the action.
 func (a *Action) GetIssueTitle() string {
 	index := com.StrTo(a.GetIssueInfos()[0]).MustInt64()
 	issue, err := GetIssueByIndex(a.RepoID, index)
@@ -168,6 +196,8 @@ func (a *Action) GetIssueTitle() string {
 	return issue.Title
 }
 
+// GetIssueContent returns the content of first issue associated with
+// this action.
 func (a *Action) GetIssueContent() string {
 	index := com.StrTo(a.GetIssueInfos()[0]).MustInt64()
 	issue, err := GetIssueByIndex(a.RepoID, index)
@@ -180,9 +210,9 @@ func (a *Action) GetIssueContent() string {
 }
 
 func newRepoAction(e Engine, doer, owner *User, repo *Repository) (err error) {
-	opType := ACTION_CREATE_REPO
+	opType := ActionCreateRepo
 	if repo.IsFork {
-		opType = ACTION_FORK_REPO
+		opType = ActionForkRepo
 	}
 
 	return notifyWatchers(e, &Action{
@@ -205,7 +235,7 @@ func renameRepoAction(e Engine, actUser *User, oldRepoName string, repo *Reposit
 	if err = notifyWatchers(e, &Action{
 		ActUserID:    actUser.ID,
 		ActUserName:  actUser.Name,
-		OpType:       ACTION_RENAME_REPO,
+		OpType:       ActionRenameRepo,
 		RepoID:       repo.ID,
 		RepoUserName: repo.Owner.Name,
 		RepoName:     repo.Name,
@@ -228,6 +258,7 @@ func issueIndexTrimRight(c rune) bool {
 	return !unicode.IsDigit(c)
 }
 
+// PushCommit represents a commit in a push operation.
 type PushCommit struct {
 	Sha1           string
 	Message        string
@@ -238,21 +269,24 @@ type PushCommit struct {
 	Timestamp      time.Time
 }
 
+// PushCommits represents list of commits in a push operation.
 type PushCommits struct {
 	Len        int
 	Commits    []*PushCommit
 	CompareURL string
-
-	avatars map[string]string
+	avatars    map[string]string
 }
 
+// NewPushCommits returns new push commits
 func NewPushCommits() *PushCommits {
 	return &PushCommits{
 		avatars: make(map[string]string),
 	}
 }
 
-func (pc *PushCommits) ToApiPayloadCommits(repoPath, repoURL string) ([]*api.PayloadCommit, error) {
+// ToAPIPayloadCommits converts a PushCommits object to
+// api.PayloadCommit format.
+func (pc *PushCommits) ToAPIPayloadCommits(repoPath, repoURL string) ([]*api.PayloadCommit, error) {
 	commits := make([]*api.PayloadCommit, len(pc.Commits))
 	for i, commit := range pc.Commits {
 		authorUsername := ""
@@ -301,22 +335,22 @@ func (pc *PushCommits) ToApiPayloadCommits(repoPath, repoURL string) ([]*api.Pay
 
 // AvatarLink tries to match user in database with e-mail
 // in order to show custom avatar, and falls back to general avatar link.
-func (push *PushCommits) AvatarLink(email string) string {
-	_, ok := push.avatars[email]
+func (pc *PushCommits) AvatarLink(email string) string {
+	_, ok := pc.avatars[email]
 	if !ok {
 		u, err := GetUserByEmail(email)
 		if err != nil {
-			push.avatars[email] = tool.AvatarLink(email)
+			pc.avatars[email] = tool.AvatarLink(email)
 			if !errors.IsUserNotExist(err) {
 				raven.CaptureErrorAndWait(err, nil)
 				log.Error(4, "GetUserByEmail: %v", err)
 			}
 		} else {
-			push.avatars[email] = u.RelAvatarLink()
+			pc.avatars[email] = u.RelAvatarLink()
 		}
 	}
 
-	return push.avatars[email]
+	return pc.avatars[email]
 }
 
 // UpdateIssuesCommit checks if issues are manipulated by commit message.
@@ -450,6 +484,7 @@ func UpdateIssuesCommit(doer *User, repo *Repository, commits []*PushCommit) err
 	return nil
 }
 
+// CommitRepoActionOptions represent options of a new commit action.
 type CommitRepoActionOptions struct {
 	PusherName  string
 	RepoOwnerID int64
@@ -481,10 +516,10 @@ func CommitRepoAction(opts CommitRepoActionOptions) error {
 	isNewRef := opts.OldCommitID == git.EMPTY_SHA
 	isDelRef := opts.NewCommitID == git.EMPTY_SHA
 
-	opType := ACTION_COMMIT_REPO
+	opType := ActionCommitRepo
 	// Check if it's tag push or branch.
 	if strings.HasPrefix(opts.RefFullName, git.TAG_PREFIX) {
-		opType = ACTION_PUSH_TAG
+		opType = ActionPushTag
 	} else {
 		// if not the first commit, set the compare URL.
 		if !isNewRef && !isDelRef {
@@ -523,9 +558,9 @@ func CommitRepoAction(opts CommitRepoActionOptions) error {
 	apiRepo := repo.APIFormat(nil)
 	apiPusher := pusher.APIFormat()
 	switch opType {
-	case ACTION_COMMIT_REPO: // Push
+	case ActionCommitRepo: // Push
 		if isDelRef {
-			if err = PrepareWebhooks(repo, HOOK_EVENT_DELETE, &api.DeletePayload{
+			if err = PrepareWebhooks(repo, HookEventDelete, &api.DeletePayload{
 				Ref:        refName,
 				RefType:    "branch",
 				PusherType: api.PUSHER_TYPE_USER,
@@ -535,7 +570,7 @@ func CommitRepoAction(opts CommitRepoActionOptions) error {
 				return fmt.Errorf("PrepareWebhooks.(delete branch): %v", err)
 			}
 
-			action.OpType = ACTION_DELETE_BRANCH
+			action.OpType = ActionDeleteBranch
 			if err = NotifyWatchers(action); err != nil {
 				return fmt.Errorf("NotifyWatchers.(delete branch): %v", err)
 			}
@@ -547,7 +582,7 @@ func CommitRepoAction(opts CommitRepoActionOptions) error {
 		compareURL := setting.AppURL + opts.Commits.CompareURL
 		if isNewRef {
 			compareURL = ""
-			if err = PrepareWebhooks(repo, HOOK_EVENT_CREATE, &api.CreatePayload{
+			if err = PrepareWebhooks(repo, HookEventCreate, &api.CreatePayload{
 				Ref:           refName,
 				RefType:       "branch",
 				DefaultBranch: repo.DefaultBranch,
@@ -557,18 +592,18 @@ func CommitRepoAction(opts CommitRepoActionOptions) error {
 				return fmt.Errorf("PrepareWebhooks.(new branch): %v", err)
 			}
 
-			action.OpType = ACTION_CREATE_BRANCH
+			action.OpType = ActionCreateBranch
 			if err = NotifyWatchers(action); err != nil {
 				return fmt.Errorf("NotifyWatchers.(new branch): %v", err)
 			}
 		}
 
-		commits, err := opts.Commits.ToApiPayloadCommits(repo.RepoPath(), repo.HTMLURL())
+		commits, err := opts.Commits.ToAPIPayloadCommits(repo.RepoPath(), repo.HTMLURL())
 		if err != nil {
-			return fmt.Errorf("ToApiPayloadCommits: %v", err)
+			return fmt.Errorf("ToAPIPayloadCommits: %v", err)
 		}
 
-		if err = PrepareWebhooks(repo, HOOK_EVENT_PUSH, &api.PushPayload{
+		if err = PrepareWebhooks(repo, HookEventPush, &api.PushPayload{
 			Ref:        opts.RefFullName,
 			Before:     opts.OldCommitID,
 			After:      opts.NewCommitID,
@@ -581,14 +616,14 @@ func CommitRepoAction(opts CommitRepoActionOptions) error {
 			return fmt.Errorf("PrepareWebhooks.(new commit): %v", err)
 		}
 
-		action.OpType = ACTION_COMMIT_REPO
+		action.OpType = ActionCommitRepo
 		if err = NotifyWatchers(action); err != nil {
 			return fmt.Errorf("NotifyWatchers.(new commit): %v", err)
 		}
 
-	case ACTION_PUSH_TAG: // Tag
+	case ActionPushTag: // Tag
 		if isDelRef {
-			if err = PrepareWebhooks(repo, HOOK_EVENT_DELETE, &api.DeletePayload{
+			if err = PrepareWebhooks(repo, HookEventDelete, &api.DeletePayload{
 				Ref:        refName,
 				RefType:    "tag",
 				PusherType: api.PUSHER_TYPE_USER,
@@ -598,14 +633,14 @@ func CommitRepoAction(opts CommitRepoActionOptions) error {
 				return fmt.Errorf("PrepareWebhooks.(delete tag): %v", err)
 			}
 
-			action.OpType = ACTION_DELETE_TAG
+			action.OpType = ActionDeleteTag
 			if err = NotifyWatchers(action); err != nil {
 				return fmt.Errorf("NotifyWatchers.(delete tag): %v", err)
 			}
 			return nil
 		}
 
-		if err = PrepareWebhooks(repo, HOOK_EVENT_CREATE, &api.CreatePayload{
+		if err = PrepareWebhooks(repo, HookEventCreate, &api.CreatePayload{
 			Ref:           refName,
 			RefType:       "tag",
 			DefaultBranch: repo.DefaultBranch,
@@ -615,7 +650,7 @@ func CommitRepoAction(opts CommitRepoActionOptions) error {
 			return fmt.Errorf("PrepareWebhooks.(new tag): %v", err)
 		}
 
-		action.OpType = ACTION_PUSH_TAG
+		action.OpType = ActionPushTag
 		if err = NotifyWatchers(action); err != nil {
 			return fmt.Errorf("NotifyWatchers.(new tag): %v", err)
 		}
@@ -628,7 +663,7 @@ func transferRepoAction(e Engine, doer, oldOwner *User, repo *Repository) (err e
 	if err = notifyWatchers(e, &Action{
 		ActUserID:    doer.ID,
 		ActUserName:  doer.Name,
-		OpType:       ACTION_TRANSFER_REPO,
+		OpType:       ActionTransferRepo,
 		RepoID:       repo.ID,
 		RepoUserName: repo.Owner.Name,
 		RepoName:     repo.Name,
@@ -658,7 +693,7 @@ func mergePullRequestAction(e Engine, doer *User, repo *Repository, issue *Issue
 	return notifyWatchers(e, &Action{
 		ActUserID:    doer.ID,
 		ActUserName:  doer.Name,
-		OpType:       ACTION_MERGE_PULL_REQUEST,
+		OpType:       ActionMergePullRequest,
 		Content:      fmt.Sprintf("%d|%s", issue.Index, issue.Title),
 		RepoID:       repo.ID,
 		RepoUserName: repo.Owner.Name,
@@ -686,6 +721,7 @@ func mirrorSyncAction(opType ActionType, repo *Repository, refName string, data
 	})
 }
 
+// MirrorSyncPushActionOptions mirror synchronization action options.
 type MirrorSyncPushActionOptions struct {
 	RefName     string
 	OldCommitID string
@@ -699,14 +735,14 @@ func MirrorSyncPushAction(repo *Repository, opts MirrorSyncPushActionOptions) er
 		opts.Commits.Commits = opts.Commits.Commits[:setting.UI.FeedMaxCommitNum]
 	}
 
-	apiCommits, err := opts.Commits.ToApiPayloadCommits(repo.RepoPath(), repo.HTMLURL())
+	apiCommits, err := opts.Commits.ToAPIPayloadCommits(repo.RepoPath(), repo.HTMLURL())
 	if err != nil {
-		return fmt.Errorf("ToApiPayloadCommits: %v", err)
+		return fmt.Errorf("ToAPIPayloadCommits: %v", err)
 	}
 
 	opts.Commits.CompareURL = repo.ComposeCompareURL(opts.OldCommitID, opts.NewCommitID)
 	apiPusher := repo.MustOwner().APIFormat()
-	if err := PrepareWebhooks(repo, HOOK_EVENT_PUSH, &api.PushPayload{
+	if err := PrepareWebhooks(repo, HookEventPush, &api.PushPayload{
 		Ref:        opts.RefName,
 		Before:     opts.OldCommitID,
 		After:      opts.NewCommitID,
@@ -724,17 +760,17 @@ func MirrorSyncPushAction(repo *Repository, opts MirrorSyncPushActionOptions) er
 		return err
 	}
 
-	return mirrorSyncAction(ACTION_MIRROR_SYNC_PUSH, repo, opts.RefName, data)
+	return mirrorSyncAction(ActionMirrorSyncPush, repo, opts.RefName, data)
 }
 
 // MirrorSyncCreateAction adds new action for mirror synchronization of new reference.
 func MirrorSyncCreateAction(repo *Repository, refName string) error {
-	return mirrorSyncAction(ACTION_MIRROR_SYNC_CREATE, repo, refName, nil)
+	return mirrorSyncAction(ActionMirrorSyncCreate, repo, refName, nil)
 }
 
-// MirrorSyncCreateAction adds new action for mirror synchronization of delete reference.
+// MirrorSyncDeleteAction deletes action for mirror synchronization of delete reference.
 func MirrorSyncDeleteAction(repo *Repository, refName string) error {
-	return mirrorSyncAction(ACTION_MIRROR_SYNC_DELETE, repo, refName, nil)
+	return mirrorSyncAction(ActionMirrorSyncDelete, repo, refName, nil)
 }
 
 // GetFeeds returns action list of given user in given context.

+ 8 - 4
models/admin.go

@@ -13,16 +13,18 @@ import (
 	"strings"
 	"time"
 
-	"github.com/Unknwon/com"
 	raven "github.com/getsentry/raven-go"
 	"github.com/go-xorm/xorm"
+	"gitlab.com/gitote/com"
 	log "gopkg.in/clog.v1"
 )
 
+//NoticeType describes the notice type
 type NoticeType int
 
 const (
-	NOTICE_REPOSITORY NoticeType = iota + 1
+	//NoticeRepository type
+	NoticeRepository NoticeType = iota + 1
 )
 
 // Notice represents a system notice for admin.
@@ -34,10 +36,12 @@ type Notice struct {
 	CreatedUnix int64
 }
 
+// BeforeInsert will be invoked by XORM before inserting a record
 func (n *Notice) BeforeInsert() {
 	n.CreatedUnix = time.Now().Unix()
 }
 
+// AfterSet is invoked from XORM after setting the values of all fields of this object.
 func (n *Notice) AfterSet(colName string, _ xorm.Cell) {
 	switch colName {
 	case "created_unix":
@@ -65,9 +69,9 @@ func CreateNotice(tp NoticeType, desc string) error {
 	return err
 }
 
-// CreateRepositoryNotice creates new system notice with type NOTICE_REPOSITORY.
+// CreateRepositoryNotice creates new system notice with type NoticeRepository.
 func CreateRepositoryNotice(desc string) error {
-	return CreateNotice(NOTICE_REPOSITORY, desc)
+	return CreateNotice(NoticeRepository, desc)
 }
 
 // RemoveAllWithNotice removes all directories in given path and

+ 6 - 4
models/attachment.go

@@ -32,10 +32,12 @@ type Attachment struct {
 	CreatedUnix int64
 }
 
+// BeforeInsert will be invoked by XORM before inserting a record
 func (a *Attachment) BeforeInsert() {
 	a.CreatedUnix = time.Now().Unix()
 }
 
+// AfterSet is invoked from XORM after setting the values of all fields of this object.
 func (a *Attachment) AfterSet(colName string, _ xorm.Cell) {
 	switch colName {
 	case "created_unix":
@@ -164,8 +166,8 @@ func DeleteAttachments(attachments []*Attachment, remove bool) (int, error) {
 }
 
 // DeleteAttachmentsByIssue deletes all attachments associated with the given issue.
-func DeleteAttachmentsByIssue(issueId int64, remove bool) (int, error) {
-	attachments, err := GetAttachmentsByIssueID(issueId)
+func DeleteAttachmentsByIssue(issueID int64, remove bool) (int, error) {
+	attachments, err := GetAttachmentsByIssueID(issueID)
 	if err != nil {
 		return 0, err
 	}
@@ -174,8 +176,8 @@ func DeleteAttachmentsByIssue(issueId int64, remove bool) (int, error) {
 }
 
 // DeleteAttachmentsByComment deletes all attachments associated with the given comment.
-func DeleteAttachmentsByComment(commentId int64, remove bool) (int, error) {
-	attachments, err := GetAttachmentsByCommentID(commentId)
+func DeleteAttachmentsByComment(commentID int64, remove bool) (int, error) {
+	attachments, err := GetAttachmentsByCommentID(commentID)
 	if err != nil {
 		return 0, err
 	}

+ 58 - 47
models/comment.go

@@ -13,39 +13,44 @@ import (
 	"strings"
 	"time"
 
-	"github.com/Unknwon/com"
 	raven "github.com/getsentry/raven-go"
 	"github.com/go-xorm/xorm"
+	"gitlab.com/gitote/com"
 	api "gitlab.com/gitote/go-gitote-client"
 	log "gopkg.in/clog.v1"
 )
 
-// CommentType defines whether a comment is just a simple comment, an action (like close) or a reference.
+// CommentType defines whether a comment is just a simple comment,
+// an action (like close) or a reference.
 type CommentType int
 
 const (
-	// Plain comment, can be associated with a commit (CommitID > 0) and a line (LineNum > 0)
-	COMMENT_TYPE_COMMENT CommentType = iota
-	COMMENT_TYPE_REOPEN
-	COMMENT_TYPE_CLOSE
-
-	// References.
-	COMMENT_TYPE_ISSUE_REF
-	// Reference from a commit (not part of a pull request)
-	COMMENT_TYPE_COMMIT_REF
-	// Reference from a comment
-	COMMENT_TYPE_COMMENT_REF
-	// Reference from a pull request
-	COMMENT_TYPE_PULL_REF
+	// CommentTypeComment Plain comment, can be associated with a commit
+	// (CommitID > 0) and a line (LineNum > 0)
+	CommentTypeComment CommentType = iota
+	// CommentTypeReopen Reopen.
+	CommentTypeReopen
+	// CommentTypeClose Closes.
+	CommentTypeClose
+	// CommentTypeIssueRef References.
+	CommentTypeIssueRef
+	// CommentTypeCommitRef Reference from a commit (not part of a pull request)
+	CommentTypeCommitRef
+	// CommentTypeCommentRef Reference from a comment
+	CommentTypeCommentRef
+	// CommentTypePullRef Reference from a pull request
+	CommentTypePullRef
 )
 
+// CommentTag defines comment tag type
 type CommentTag int
 
+// Enumerate all the comment tag types
 const (
-	COMMENT_TAG_NONE CommentTag = iota
-	COMMENT_TAG_POSTER
-	COMMENT_TAG_WRITER
-	COMMENT_TAG_OWNER
+	CommentTagNone CommentTag = iota
+	CommentTagPoster
+	CommentTagWriter
+	CommentTagOwner
 )
 
 // Comment represents a comment in commit and issue page.
@@ -75,15 +80,18 @@ type Comment struct {
 	ShowTag CommentTag `xorm:"-" json:"-"`
 }
 
+// BeforeInsert will be invoked by XORM before inserting a record
 func (c *Comment) BeforeInsert() {
 	c.CreatedUnix = time.Now().Unix()
 	c.UpdatedUnix = c.CreatedUnix
 }
 
+// BeforeUpdate is invoked from XORM before updating this object.
 func (c *Comment) BeforeUpdate() {
 	c.UpdatedUnix = time.Now().Unix()
 }
 
+// AfterSet is invoked from XORM after setting the values of all fields of this object.
 func (c *Comment) AfterSet(colName string, _ xorm.Cell) {
 	switch colName {
 	case "created_unix":
@@ -129,16 +137,17 @@ func (c *Comment) loadAttributes(e Engine) (err error) {
 	return nil
 }
 
+// LoadAttributes loads all attributes
 func (c *Comment) LoadAttributes() error {
 	return c.loadAttributes(x)
 }
 
+// HTMLURL formats a URL-string to the issue-comment
 func (c *Comment) HTMLURL() string {
 	return fmt.Sprintf("%s#issuecomment-%d", c.Issue.HTMLURL(), c.ID)
 }
 
-// This method assumes following fields have been assigned with valid values:
-// Required - Poster, Issue
+// APIFormat converts a Comment to the api.Comment format
 func (c *Comment) APIFormat() *api.Comment {
 	return &api.Comment{
 		ID:      c.ID,
@@ -150,6 +159,7 @@ func (c *Comment) APIFormat() *api.Comment {
 	}
 }
 
+// CommentHashTag returns issue comment with hash
 func CommentHashTag(id int64) string {
 	return "issuecomment-" + com.ToStr(id)
 }
@@ -166,21 +176,21 @@ func (c *Comment) EventTag() string {
 
 // mailParticipants sends new comment emails to repository watchers
 // and mentioned people.
-func (cmt *Comment) mailParticipants(e Engine, opType ActionType, issue *Issue) (err error) {
-	mentions := markup.FindAllMentions(cmt.Content)
-	if err = updateIssueMentions(e, cmt.IssueID, mentions); err != nil {
-		return fmt.Errorf("UpdateIssueMentions [%d]: %v", cmt.IssueID, err)
+func (c *Comment) mailParticipants(e Engine, opType ActionType, issue *Issue) (err error) {
+	mentions := markup.FindAllMentions(c.Content)
+	if err = updateIssueMentions(e, c.IssueID, mentions); err != nil {
+		return fmt.Errorf("UpdateIssueMentions [%d]: %v", c.IssueID, err)
 	}
 
 	switch opType {
-	case ACTION_COMMENT_ISSUE:
-		issue.Content = cmt.Content
-	case ACTION_CLOSE_ISSUE:
+	case ActionCommentIssue:
+		issue.Content = c.Content
+	case ActionCloseIssue:
 		issue.Content = fmt.Sprintf("Closed #%d", issue.Index)
-	case ACTION_REOPEN_ISSUE:
+	case ActionReopenIssue:
 		issue.Content = fmt.Sprintf("Reopened #%d", issue.Index)
 	}
-	if err = mailIssueCommentToParticipants(issue, cmt.Poster, mentions); err != nil {
+	if err = mailIssueCommentToParticipants(issue, c.Poster, mentions); err != nil {
 		raven.CaptureErrorAndWait(err, nil)
 		log.Error(2, "mailIssueCommentToParticipants: %v", err)
 	}
@@ -217,8 +227,8 @@ func createComment(e *xorm.Session, opts *CreateCommentOptions) (_ *Comment, err
 
 	// Check comment type.
 	switch opts.Type {
-	case COMMENT_TYPE_COMMENT:
-		act.OpType = ACTION_COMMENT_ISSUE
+	case CommentTypeComment:
+		act.OpType = ActionCommentIssue
 
 		if _, err = e.Exec("UPDATE `issue` SET num_comments=num_comments+1 WHERE id=?", opts.Issue.ID); err != nil {
 			return nil, err
@@ -246,10 +256,10 @@ func createComment(e *xorm.Session, opts *CreateCommentOptions) (_ *Comment, err
 			}
 		}
 
-	case COMMENT_TYPE_REOPEN:
-		act.OpType = ACTION_REOPEN_ISSUE
+	case CommentTypeReopen:
+		act.OpType = ActionReopenIssue
 		if opts.Issue.IsPull {
-			act.OpType = ACTION_REOPEN_PULL_REQUEST
+			act.OpType = ActionReopenPullRequest
 		}
 
 		if opts.Issue.IsPull {
@@ -261,10 +271,10 @@ func createComment(e *xorm.Session, opts *CreateCommentOptions) (_ *Comment, err
 			return nil, err
 		}
 
-	case COMMENT_TYPE_CLOSE:
-		act.OpType = ACTION_CLOSE_ISSUE
+	case CommentTypeClose:
+		act.OpType = ActionCloseIssue
 		if opts.Issue.IsPull {
-			act.OpType = ACTION_CLOSE_PULL_REQUEST
+			act.OpType = ActionClosePullRequest
 		}
 
 		if opts.Issue.IsPull {
@@ -297,9 +307,9 @@ func createComment(e *xorm.Session, opts *CreateCommentOptions) (_ *Comment, err
 }
 
 func createStatusComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue) (*Comment, error) {
-	cmtType := COMMENT_TYPE_CLOSE
+	cmtType := CommentTypeClose
 	if !issue.IsClosed {
-		cmtType = COMMENT_TYPE_REOPEN
+		cmtType = CommentTypeReopen
 	}
 	return createComment(e, &CreateCommentOptions{
 		Type:  cmtType,
@@ -309,6 +319,7 @@ func createStatusComment(e *xorm.Session, doer *User, repo *Repository, issue *I
 	})
 }
 
+// CreateCommentOptions defines options for creating comment
 type CreateCommentOptions struct {
 	Type  CommentType
 	Doer  *User
@@ -341,7 +352,7 @@ func CreateComment(opts *CreateCommentOptions) (comment *Comment, err error) {
 // CreateIssueComment creates a plain issue comment.
 func CreateIssueComment(doer *User, repo *Repository, issue *Issue, content string, attachments []string) (*Comment, error) {
 	comment, err := CreateComment(&CreateCommentOptions{
-		Type:        COMMENT_TYPE_COMMENT,
+		Type:        CommentTypeComment,
 		Doer:        doer,
 		Repo:        repo,
 		Issue:       issue,
@@ -353,7 +364,7 @@ func CreateIssueComment(doer *User, repo *Repository, issue *Issue, content stri
 	}
 
 	comment.Issue = issue
-	if err = PrepareWebhooks(repo, HOOK_EVENT_ISSUE_COMMENT, &api.IssueCommentPayload{
+	if err = PrepareWebhooks(repo, HookEventIssueComment, &api.IssueCommentPayload{
 		Action:     api.HOOK_ISSUE_COMMENT_CREATED,
 		Issue:      issue.APIFormat(),
 		Comment:    comment.APIFormat(),
@@ -375,7 +386,7 @@ func CreateRefComment(doer *User, repo *Repository, issue *Issue, content, commi
 
 	// Check if same reference from same commit has already existed.
 	has, err := x.Get(&Comment{
-		Type:      COMMENT_TYPE_COMMIT_REF,
+		Type:      CommentTypeCommitRef,
 		IssueID:   issue.ID,
 		CommitSHA: commitSHA,
 	})
@@ -386,7 +397,7 @@ func CreateRefComment(doer *User, repo *Repository, issue *Issue, content, commi
 	}
 
 	_, err = CreateComment(&CreateCommentOptions{
-		Type:      COMMENT_TYPE_COMMIT_REF,
+		Type:      CommentTypeCommitRef,
 		Doer:      doer,
 		Repo:      repo,
 		Issue:     issue,
@@ -472,7 +483,7 @@ func UpdateComment(doer *User, c *Comment, oldContent string) (err error) {
 	if err = c.Issue.LoadAttributes(); err != nil {
 		raven.CaptureErrorAndWait(err, nil)
 		log.Error(2, "Issue.LoadAttributes [issue_id: %d]: %v", c.IssueID, err)
-	} else if err = PrepareWebhooks(c.Issue.Repo, HOOK_EVENT_ISSUE_COMMENT, &api.IssueCommentPayload{
+	} else if err = PrepareWebhooks(c.Issue.Repo, HookEventIssueComment, &api.IssueCommentPayload{
 		Action:  api.HOOK_ISSUE_COMMENT_EDITED,
 		Issue:   c.Issue.APIFormat(),
 		Comment: c.APIFormat(),
@@ -511,7 +522,7 @@ func DeleteCommentByID(doer *User, id int64) error {
 		return err
 	}
 
-	if comment.Type == COMMENT_TYPE_COMMENT {
+	if comment.Type == CommentTypeComment {
 		if _, err = sess.Exec("UPDATE `issue` SET num_comments = num_comments - 1 WHERE id = ?", comment.IssueID); err != nil {
 			return err
 		}
@@ -530,7 +541,7 @@ func DeleteCommentByID(doer *User, id int64) error {
 	if err = comment.Issue.LoadAttributes(); err != nil {
 		raven.CaptureErrorAndWait(err, nil)
 		log.Error(2, "Issue.LoadAttributes [issue_id: %d]: %v", comment.IssueID, err)
-	} else if err = PrepareWebhooks(comment.Issue.Repo, HOOK_EVENT_ISSUE_COMMENT, &api.IssueCommentPayload{
+	} else if err = PrepareWebhooks(comment.Issue.Repo, HookEventIssueComment, &api.IssueCommentPayload{
 		Action:     api.HOOK_ISSUE_COMMENT_DELETED,
 		Issue:      comment.Issue.APIFormat(),
 		Comment:    comment.APIFormat(),

+ 69 - 0
models/error.go

@@ -10,10 +10,12 @@ import (
 	"fmt"
 )
 
+// ErrNameReserved represents a "reserved name" error.
 type ErrNameReserved struct {
 	Name string
 }
 
+// IsErrNameReserved checks if an error is a ErrNameReserved.
 func IsErrNameReserved(err error) bool {
 	_, ok := err.(ErrNameReserved)
 	return ok
@@ -23,10 +25,13 @@ func (err ErrNameReserved) Error() string {
 	return fmt.Sprintf("name is reserved [name: %s]", err.Name)
 }
 
+// ErrNamePatternNotAllowed represents a "pattern not allowed" error.
 type ErrNamePatternNotAllowed struct {
 	Pattern string
 }
 
+// IsErrNamePatternNotAllowed checks if an error is an
+// ErrNamePatternNotAllowed.
 func IsErrNamePatternNotAllowed(err error) bool {
 	_, ok := err.(ErrNamePatternNotAllowed)
 	return ok
@@ -36,10 +41,12 @@ func (err ErrNamePatternNotAllowed) Error() string {
 	return fmt.Sprintf("name pattern is not allowed [pattern: %s]", err.Pattern)
 }
 
+// ErrUserAlreadyExist represents a "user already exists" error.
 type ErrUserAlreadyExist struct {
 	Name string
 }
 
+// IsErrUserAlreadyExist checks if an error is a ErrUserAlreadyExists.
 func IsErrUserAlreadyExist(err error) bool {
 	_, ok := err.(ErrUserAlreadyExist)
 	return ok
@@ -49,10 +56,12 @@ func (err ErrUserAlreadyExist) Error() string {
 	return fmt.Sprintf("user already exists [name: %s]", err.Name)
 }
 
+// ErrEmailAlreadyUsed represents a "EmailAlreadyUsed" kind of error.
 type ErrEmailAlreadyUsed struct {
 	Email string
 }
 
+// IsErrEmailAlreadyUsed checks if an error is a ErrEmailAlreadyUsed.
 func IsErrEmailAlreadyUsed(err error) bool {
 	_, ok := err.(ErrEmailAlreadyUsed)
 	return ok
@@ -62,10 +71,12 @@ func (err ErrEmailAlreadyUsed) Error() string {
 	return fmt.Sprintf("e-mail has been used [email: %s]", err.Email)
 }
 
+// ErrUserOwnRepos represents a "UserOwnRepos" kind of error.
 type ErrUserOwnRepos struct {
 	UID int64
 }
 
+// IsErrUserOwnRepos checks if an error is a ErrUserOwnRepos.
 func IsErrUserOwnRepos(err error) bool {
 	_, ok := err.(ErrUserOwnRepos)
 	return ok
@@ -75,10 +86,12 @@ func (err ErrUserOwnRepos) Error() string {
 	return fmt.Sprintf("user still has ownership of repositories [uid: %d]", err.UID)
 }
 
+// ErrUserHasOrgs represents a "UserHasOrgs" kind of error.
 type ErrUserHasOrgs struct {
 	UID int64
 }
 
+// IsErrUserHasOrgs checks if an error is a ErrUserHasOrgs.
 func IsErrUserHasOrgs(err error) bool {
 	_, ok := err.(ErrUserHasOrgs)
 	return ok
@@ -88,10 +101,12 @@ func (err ErrUserHasOrgs) Error() string {
 	return fmt.Sprintf("user still has membership of organizations [uid: %d]", err.UID)
 }
 
+// ErrWikiAlreadyExist represents a "WikiAlreadyExist" kind of error.
 type ErrWikiAlreadyExist struct {
 	Title string
 }
 
+// IsErrWikiAlreadyExist checks if an error is an ErrWikiAlreadyExist.
 func IsErrWikiAlreadyExist(err error) bool {
 	_, ok := err.(ErrWikiAlreadyExist)
 	return ok
@@ -101,10 +116,12 @@ func (err ErrWikiAlreadyExist) Error() string {
 	return fmt.Sprintf("wiki page already exists [title: %s]", err.Title)
 }
 
+// ErrKeyUnableVerify represents a "KeyUnableVerify" kind of error.
 type ErrKeyUnableVerify struct {
 	Result string
 }
 
+// IsErrKeyUnableVerify checks if an error is a ErrKeyUnableVerify.
 func IsErrKeyUnableVerify(err error) bool {
 	_, ok := err.(ErrKeyUnableVerify)
 	return ok
@@ -114,10 +131,12 @@ func (err ErrKeyUnableVerify) Error() string {
 	return fmt.Sprintf("Unable to verify key content [result: %s]", err.Result)
 }
 
+// ErrKeyNotExist represents a "KeyNotExist" kind of error.
 type ErrKeyNotExist struct {
 	ID int64
 }
 
+// IsErrKeyNotExist checks if an error is a ErrKeyNotExist.
 func IsErrKeyNotExist(err error) bool {
 	_, ok := err.(ErrKeyNotExist)
 	return ok
@@ -127,11 +146,13 @@ func (err ErrKeyNotExist) Error() string {
 	return fmt.Sprintf("public key does not exist [id: %d]", err.ID)
 }
 
+// ErrKeyAlreadyExist represents a "KeyAlreadyExist" kind of error.
 type ErrKeyAlreadyExist struct {
 	OwnerID int64
 	Content string
 }
 
+// IsErrKeyAlreadyExist checks if an error is a ErrKeyAlreadyExist.
 func IsErrKeyAlreadyExist(err error) bool {
 	_, ok := err.(ErrKeyAlreadyExist)
 	return ok
@@ -141,11 +162,13 @@ func (err ErrKeyAlreadyExist) Error() string {
 	return fmt.Sprintf("public key already exists [owner_id: %d, content: %s]", err.OwnerID, err.Content)
 }
 
+// ErrKeyNameAlreadyUsed represents a "KeyNameAlreadyUsed" kind of error.
 type ErrKeyNameAlreadyUsed struct {
 	OwnerID int64
 	Name    string
 }
 
+// IsErrKeyNameAlreadyUsed checks if an error is a ErrKeyNameAlreadyUsed.
 func IsErrKeyNameAlreadyUsed(err error) bool {
 	_, ok := err.(ErrKeyNameAlreadyUsed)
 	return ok
@@ -155,12 +178,14 @@ func (err ErrKeyNameAlreadyUsed) Error() string {
 	return fmt.Sprintf("public key already exists [owner_id: %d, name: %s]", err.OwnerID, err.Name)
 }
 
+// ErrKeyAccessDenied represents a "KeyAccessDenied" kind of error.
 type ErrKeyAccessDenied struct {
 	UserID int64
 	KeyID  int64
 	Note   string
 }
 
+// IsErrKeyAccessDenied checks if an error is a ErrKeyAccessDenied.
 func IsErrKeyAccessDenied(err error) bool {
 	_, ok := err.(ErrKeyAccessDenied)
 	return ok
@@ -171,12 +196,14 @@ func (err ErrKeyAccessDenied) Error() string {
 		err.UserID, err.KeyID, err.Note)
 }
 
+// ErrDeployKeyNotExist represents a "DeployKeyNotExist" kind of error.
 type ErrDeployKeyNotExist struct {
 	ID     int64
 	KeyID  int64
 	RepoID int64
 }
 
+// IsErrDeployKeyNotExist checks if an error is a ErrDeployKeyNotExist.
 func IsErrDeployKeyNotExist(err error) bool {
 	_, ok := err.(ErrDeployKeyNotExist)
 	return ok
@@ -186,11 +213,13 @@ func (err ErrDeployKeyNotExist) Error() string {
 	return fmt.Sprintf("Deploy key does not exist [id: %d, key_id: %d, repo_id: %d]", err.ID, err.KeyID, err.RepoID)
 }
 
+// ErrDeployKeyAlreadyExist represents a "DeployKeyAlreadyExist" kind of error.
 type ErrDeployKeyAlreadyExist struct {
 	KeyID  int64
 	RepoID int64
 }
 
+// IsErrDeployKeyAlreadyExist checks if an error is a ErrDeployKeyAlreadyExist.
 func IsErrDeployKeyAlreadyExist(err error) bool {
 	_, ok := err.(ErrDeployKeyAlreadyExist)
 	return ok
@@ -200,11 +229,13 @@ func (err ErrDeployKeyAlreadyExist) Error() string {
 	return fmt.Sprintf("public key already exists [key_id: %d, repo_id: %d]", err.KeyID, err.RepoID)
 }
 
+// ErrDeployKeyNameAlreadyUsed represents a "DeployKeyNameAlreadyUsed" kind of error.
 type ErrDeployKeyNameAlreadyUsed struct {
 	RepoID int64
 	Name   string
 }
 
+// IsErrDeployKeyNameAlreadyUsed checks if an error is a ErrDeployKeyNameAlreadyUsed.
 func IsErrDeployKeyNameAlreadyUsed(err error) bool {
 	_, ok := err.(ErrDeployKeyNameAlreadyUsed)
 	return ok
@@ -214,10 +245,12 @@ func (err ErrDeployKeyNameAlreadyUsed) Error() string {
 	return fmt.Sprintf("public key already exists [repo_id: %d, name: %s]", err.RepoID, err.Name)
 }
 
+// ErrAccessTokenNotExist represents a "AccessTokenNotExist" kind of error.
 type ErrAccessTokenNotExist struct {
 	SHA string
 }
 
+// IsErrAccessTokenNotExist checks if an error is a ErrAccessTokenNotExist.
 func IsErrAccessTokenNotExist(err error) bool {
 	_, ok := err.(ErrAccessTokenNotExist)
 	return ok
@@ -227,9 +260,11 @@ func (err ErrAccessTokenNotExist) Error() string {
 	return fmt.Sprintf("access token does not exist [sha: %s]", err.SHA)
 }
 
+// ErrAccessTokenEmpty represents a "AccessTokenEmpty" kind of error.
 type ErrAccessTokenEmpty struct {
 }
 
+// IsErrAccessTokenEmpty checks if an error is a ErrAccessTokenEmpty.
 func IsErrAccessTokenEmpty(err error) bool {
 	_, ok := err.(ErrAccessTokenEmpty)
 	return ok
@@ -239,10 +274,12 @@ func (err ErrAccessTokenEmpty) Error() string {
 	return fmt.Sprintf("access token is empty")
 }
 
+// ErrLastOrgOwner represents a "LastOrgOwner" kind of error.
 type ErrLastOrgOwner struct {
 	UID int64
 }
 
+// IsErrLastOrgOwner checks if an error is a ErrLastOrgOwner.
 func IsErrLastOrgOwner(err error) bool {
 	_, ok := err.(ErrLastOrgOwner)
 	return ok
@@ -252,11 +289,13 @@ func (err ErrLastOrgOwner) Error() string {
 	return fmt.Sprintf("user is the last member of owner team [uid: %d]", err.UID)
 }
 
+// ErrRepoAlreadyExist represents a "RepoAlreadyExist" kind of error.
 type ErrRepoAlreadyExist struct {
 	Uname string
 	Name  string
 }
 
+// IsErrRepoAlreadyExist checks if an error is a ErrRepoAlreadyExist.
 func IsErrRepoAlreadyExist(err error) bool {
 	_, ok := err.(ErrRepoAlreadyExist)
 	return ok
@@ -266,12 +305,14 @@ func (err ErrRepoAlreadyExist) Error() string {
 	return fmt.Sprintf("repository already exists [uname: %s, name: %s]", err.Uname, err.Name)
 }
 
+// ErrInvalidCloneAddr represents a "InvalidCloneAddr" kind of error.
 type ErrInvalidCloneAddr struct {
 	IsURLError         bool
 	IsInvalidPath      bool
 	IsPermissionDenied bool
 }
 
+// IsErrInvalidCloneAddr checks if an error is a ErrInvalidCloneAddr.
 func IsErrInvalidCloneAddr(err error) bool {
 	_, ok := err.(ErrInvalidCloneAddr)
 	return ok
@@ -282,10 +323,12 @@ func (err ErrInvalidCloneAddr) Error() string {
 		err.IsURLError, err.IsInvalidPath, err.IsPermissionDenied)
 }
 
+// ErrUpdateTaskNotExist represents a "UpdateTaskNotExist" kind of error.
 type ErrUpdateTaskNotExist struct {
 	UUID string
 }
 
+// IsErrUpdateTaskNotExist checks if an error is a ErrUpdateTaskNotExist.
 func IsErrUpdateTaskNotExist(err error) bool {
 	_, ok := err.(ErrUpdateTaskNotExist)
 	return ok
@@ -295,10 +338,12 @@ func (err ErrUpdateTaskNotExist) Error() string {
 	return fmt.Sprintf("update task does not exist [uuid: %s]", err.UUID)
 }
 
+// ErrReleaseAlreadyExist represents a "ReleaseAlreadyExist" kind of error.
 type ErrReleaseAlreadyExist struct {
 	TagName string
 }
 
+// IsErrReleaseAlreadyExist checks if an error is a ErrReleaseAlreadyExist.
 func IsErrReleaseAlreadyExist(err error) bool {
 	_, ok := err.(ErrReleaseAlreadyExist)
 	return ok
@@ -308,11 +353,13 @@ func (err ErrReleaseAlreadyExist) Error() string {
 	return fmt.Sprintf("release tag already exist [tag_name: %s]", err.TagName)
 }
 
+// ErrReleaseNotExist represents a "ReleaseNotExist" kind of error.
 type ErrReleaseNotExist struct {
 	ID      int64
 	TagName string
 }
 
+// IsErrReleaseNotExist checks if an error is a ErrReleaseNotExist.
 func IsErrReleaseNotExist(err error) bool {
 	_, ok := err.(ErrReleaseNotExist)
 	return ok
@@ -322,10 +369,12 @@ func (err ErrReleaseNotExist) Error() string {
 	return fmt.Sprintf("release tag does not exist [id: %d, tag_name: %s]", err.ID, err.TagName)
 }
 
+// ErrInvalidTagName represents a "InvalidTagName" kind of error.
 type ErrInvalidTagName struct {
 	TagName string
 }
 
+// IsErrInvalidTagName checks if an error is a ErrInvalidTagName.
 func IsErrInvalidTagName(err error) bool {
 	_, ok := err.(ErrInvalidTagName)
 	return ok
@@ -335,10 +384,12 @@ func (err ErrInvalidTagName) Error() string {
 	return fmt.Sprintf("release tag name is not valid [tag_name: %s]", err.TagName)
 }
 
+// ErrRepoFileAlreadyExist represents a "RepoFileAlreadyExist" kind of error.
 type ErrRepoFileAlreadyExist struct {
 	FileName string
 }
 
+// IsErrRepoFileAlreadyExist checks if an error is a ErrRepoFileAlreadyExist.
 func IsErrRepoFileAlreadyExist(err error) bool {
 	_, ok := err.(ErrRepoFileAlreadyExist)
 	return ok
@@ -348,6 +399,7 @@ func (err ErrRepoFileAlreadyExist) Error() string {
 	return fmt.Sprintf("repository file already exists [file_name: %s]", err.FileName)
 }
 
+// ErrPullRequestNotExist represents a "PullRequestNotExist" kind of error.
 type ErrPullRequestNotExist struct {
 	ID         int64
 	IssueID    int64
@@ -357,6 +409,7 @@ type ErrPullRequestNotExist struct {
 	BaseBranch string
 }
 
+// IsErrPullRequestNotExist checks if an error is a ErrPullRequestNotExist.
 func IsErrPullRequestNotExist(err error) bool {
 	_, ok := err.(ErrPullRequestNotExist)
 	return ok
@@ -367,11 +420,13 @@ func (err ErrPullRequestNotExist) Error() string {
 		err.ID, err.IssueID, err.HeadRepoID, err.BaseRepoID, err.HeadBarcnh, err.BaseBranch)
 }
 
+// ErrCommentNotExist represents a "CommentNotExist" kind of error.
 type ErrCommentNotExist struct {
 	ID      int64
 	IssueID int64
 }
 
+// IsErrCommentNotExist checks if an error is a ErrCommentNotExist.
 func IsErrCommentNotExist(err error) bool {
 	_, ok := err.(ErrCommentNotExist)
 	return ok
@@ -381,11 +436,13 @@ func (err ErrCommentNotExist) Error() string {
 	return fmt.Sprintf("comment does not exist [id: %d, issue_id: %d]", err.ID, err.IssueID)
 }
 
+// ErrLabelNotExist represents a "LabelNotExist" kind of error.
 type ErrLabelNotExist struct {
 	LabelID int64
 	RepoID  int64
 }
 
+// IsErrLabelNotExist checks if an error is a ErrLabelNotExist.
 func IsErrLabelNotExist(err error) bool {
 	_, ok := err.(ErrLabelNotExist)
 	return ok
@@ -395,11 +452,13 @@ func (err ErrLabelNotExist) Error() string {
 	return fmt.Sprintf("label does not exist [label_id: %d, repo_id: %d]", err.LabelID, err.RepoID)
 }
 
+// ErrMilestoneNotExist represents a "MilestoneNotExist" kind of error.
 type ErrMilestoneNotExist struct {
 	ID     int64
 	RepoID int64
 }
 
+// IsErrMilestoneNotExist checks if an error is a ErrMilestoneNotExist.
 func IsErrMilestoneNotExist(err error) bool {
 	_, ok := err.(ErrMilestoneNotExist)
 	return ok
@@ -409,11 +468,13 @@ func (err ErrMilestoneNotExist) Error() string {
 	return fmt.Sprintf("milestone does not exist [id: %d, repo_id: %d]", err.ID, err.RepoID)
 }
 
+// ErrAttachmentNotExist represents a "AttachmentNotExist" kind of error.
 type ErrAttachmentNotExist struct {
 	ID   int64
 	UUID string
 }
 
+// IsErrAttachmentNotExist checks if an error is a ErrAttachmentNotExist.
 func IsErrAttachmentNotExist(err error) bool {
 	_, ok := err.(ErrAttachmentNotExist)
 	return ok
@@ -423,10 +484,12 @@ func (err ErrAttachmentNotExist) Error() string {
 	return fmt.Sprintf("attachment does not exist [id: %d, uuid: %s]", err.ID, err.UUID)
 }
 
+// ErrLoginSourceAlreadyExist represents a "LoginSourceAlreadyExist" kind of error.
 type ErrLoginSourceAlreadyExist struct {
 	Name string
 }
 
+// IsErrLoginSourceAlreadyExist checks if an error is a ErrLoginSourceAlreadyExist.
 func IsErrLoginSourceAlreadyExist(err error) bool {
 	_, ok := err.(ErrLoginSourceAlreadyExist)
 	return ok
@@ -436,10 +499,12 @@ func (err ErrLoginSourceAlreadyExist) Error() string {
 	return fmt.Sprintf("login source already exists [name: %s]", err.Name)
 }
 
+// ErrLoginSourceInUse represents a "LoginSourceInUse" kind of error.
 type ErrLoginSourceInUse struct {
 	ID int64
 }
 
+// IsErrLoginSourceInUse checks if an error is a ErrLoginSourceInUse.
 func IsErrLoginSourceInUse(err error) bool {
 	_, ok := err.(ErrLoginSourceInUse)
 	return ok
@@ -449,11 +514,13 @@ func (err ErrLoginSourceInUse) Error() string {
 	return fmt.Sprintf("login source is still used by some users [id: %d]", err.ID)
 }
 
+// ErrTeamAlreadyExist represents a "TeamAlreadyExist" kind of error.
 type ErrTeamAlreadyExist struct {
 	OrgID int64
 	Name  string
 }
 
+// IsErrTeamAlreadyExist checks if an error is a ErrTeamAlreadyExist.
 func IsErrTeamAlreadyExist(err error) bool {
 	_, ok := err.(ErrTeamAlreadyExist)
 	return ok
@@ -463,11 +530,13 @@ func (err ErrTeamAlreadyExist) Error() string {
 	return fmt.Sprintf("team already exists [org_id: %d, name: %s]", err.OrgID, err.Name)
 }
 
+// ErrUploadNotExist represents a "UploadNotExist" kind of error.
 type ErrUploadNotExist struct {
 	ID   int64
 	UUID string
 }
 
+// IsErrUploadNotExist checks if an error is a ErrUploadNotExist.
 func IsErrUploadNotExist(err error) bool {
 	_, ok := err.(ErrAttachmentNotExist)
 	return ok

+ 8 - 0
models/git_diff.go

@@ -22,6 +22,7 @@ import (
 	"golang.org/x/text/transform"
 )
 
+// DiffSection represents a section of a DiffFile.
 type DiffSection struct {
 	*git.DiffSection
 }
@@ -104,20 +105,24 @@ func (diffSection *DiffSection) ComputedInlineDiffFor(diffLine *git.DiffLine) te
 	return diffToHTML(diffRecord, diffLine.Type)
 }
 
+// DiffFile represents a file diff.
 type DiffFile struct {
 	*git.DiffFile
 	Sections []*DiffSection
 }
 
+// HighlightClass returns highlight class for a filename.
 func (diffFile *DiffFile) HighlightClass() string {
 	return highlight.FileNameToHighlightClass(diffFile.Name)
 }
 
+// Diff represents a difference between two git trees.
 type Diff struct {
 	*git.Diff
 	Files []*DiffFile
 }
 
+// NewDiff creates new diff
 func NewDiff(gitDiff *git.Diff) *Diff {
 	diff := &Diff{
 		Diff:  gitDiff,
@@ -164,6 +169,7 @@ func NewDiff(gitDiff *git.Diff) *Diff {
 	return diff
 }
 
+// ParsePatch builds a Diff object from a io.Reader and some
 func ParsePatch(maxLines, maxLineCharacteres, maxFiles int, reader io.Reader) (*Diff, error) {
 	done := make(chan error)
 	var gitDiff *git.Diff
@@ -177,6 +183,7 @@ func ParsePatch(maxLines, maxLineCharacteres, maxFiles int, reader io.Reader) (*
 	return NewDiff(gitDiff), nil
 }
 
+// GetDiffRange builds a Diff between two commits of a repository.
 func GetDiffRange(repoPath, beforeCommitID, afterCommitID string, maxLines, maxLineCharacteres, maxFiles int) (*Diff, error) {
 	gitDiff, err := git.GetDiffRange(repoPath, beforeCommitID, afterCommitID, maxLines, maxLineCharacteres, maxFiles)
 	if err != nil {
@@ -185,6 +192,7 @@ func GetDiffRange(repoPath, beforeCommitID, afterCommitID string, maxLines, maxL
 	return NewDiff(gitDiff), nil
 }
 
+// GetDiffCommit builds a Diff representing the given commitID.
 func GetDiffCommit(repoPath, commitID string, maxLines, maxLineCharacteres, maxFiles int) (*Diff, error) {
 	gitDiff, err := git.GetDiffCommit(repoPath, commitID, maxLines, maxLineCharacteres, maxFiles)
 	if err != nil {

+ 89 - 74
models/issue.go

@@ -14,14 +14,15 @@ import (
 	"strings"
 	"time"
 
-	"github.com/Unknwon/com"
 	raven "github.com/getsentry/raven-go"
 	"github.com/go-xorm/xorm"
+	"gitlab.com/gitote/com"
 	api "gitlab.com/gitote/go-gitote-client"
 	log "gopkg.in/clog.v1"
 )
 
 var (
+	// ErrMissingIssueNumber display error
 	ErrMissingIssueNumber = errors.New("No issue number specified")
 )
 
@@ -47,28 +48,29 @@ type Issue struct {
 	IsPull          bool         // Indicates whether is a pull request or not.
 	PullRequest     *PullRequest `xorm:"-" json:"-"`
 	NumComments     int
-
-	Deadline     time.Time `xorm:"-" json:"-"`
-	DeadlineUnix int64
-	Created      time.Time `xorm:"-" json:"-"`
-	CreatedUnix  int64
-	Updated      time.Time `xorm:"-" json:"-"`
-	UpdatedUnix  int64
-
-	Attachments []*Attachment `xorm:"-" json:"-"`
-	Comments    []*Comment    `xorm:"-" json:"-"`
+	Deadline        time.Time `xorm:"-" json:"-"`
+	DeadlineUnix    int64
+	Created         time.Time `xorm:"-" json:"-"`
+	CreatedUnix     int64
+	Updated         time.Time `xorm:"-" json:"-"`
+	UpdatedUnix     int64
+	Attachments     []*Attachment `xorm:"-" json:"-"`
+	Comments        []*Comment    `xorm:"-" json:"-"`
 }
 
+// BeforeInsert will be invoked by XORM before inserting a record
 func (issue *Issue) BeforeInsert() {
 	issue.CreatedUnix = time.Now().Unix()
 	issue.UpdatedUnix = issue.CreatedUnix
 }
 
+// BeforeUpdate is invoked from XORM before updating this object.
 func (issue *Issue) BeforeUpdate() {
 	issue.UpdatedUnix = time.Now().Unix()
 	issue.DeadlineUnix = issue.Deadline.Unix()
 }
 
+// AfterSet is invoked from XORM after setting the values of all fields of this object.
 func (issue *Issue) AfterSet(colName string, _ xorm.Cell) {
 	switch colName {
 	case "deadline_unix":
@@ -146,10 +148,12 @@ func (issue *Issue) loadAttributes(e Engine) (err error) {
 	return nil
 }
 
+// LoadAttributes loads the attribute of this issue.
 func (issue *Issue) LoadAttributes() error {
 	return issue.loadAttributes(x)
 }
 
+// HTMLURL returns the absolute URL to this issue.
 func (issue *Issue) HTMLURL() string {
 	var path string
 	if issue.IsPull {
@@ -161,14 +165,14 @@ func (issue *Issue) HTMLURL() string {
 }
 
 // State returns string representation of issue status.
-func (i *Issue) State() api.StateType {
-	if i.IsClosed {
+func (issue *Issue) State() api.StateType {
+	if issue.IsClosed {
 		return api.STATE_CLOSED
 	}
 	return api.STATE_OPEN
 }
 
-// This method assumes some fields assigned with values:
+// APIFormat This method assumes some fields assigned with values:
 // Required - Poster, Labels,
 // Optional - Milestone, Assignee, PullRequest
 func (issue *Issue) APIFormat() *api.Issue {
@@ -209,22 +213,22 @@ func (issue *Issue) APIFormat() *api.Issue {
 }
 
 // HashTag returns unique hash tag for issue.
-func (i *Issue) HashTag() string {
-	return "issue-" + com.ToStr(i.ID)
+func (issue *Issue) HashTag() string {
+	return "issue-" + com.ToStr(issue.ID)
 }
 
 // IsPoster returns true if given user by ID is the poster.
-func (i *Issue) IsPoster(uid int64) bool {
-	return i.PosterID == uid
+func (issue *Issue) IsPoster(uid int64) bool {
+	return issue.PosterID == uid
 }
 
-func (i *Issue) hasLabel(e Engine, labelID int64) bool {
-	return hasIssueLabel(e, i.ID, labelID)
+func (issue *Issue) hasLabel(e Engine, labelID int64) bool {
+	return hasIssueLabel(e, issue.ID, labelID)
 }
 
 // HasLabel returns true if issue has been labeled by given ID.
-func (i *Issue) HasLabel(labelID int64) bool {
-	return i.hasLabel(x, labelID)
+func (issue *Issue) HasLabel(labelID int64) bool {
+	return issue.hasLabel(x, labelID)
 }
 
 func (issue *Issue) sendLabelUpdatedWebhook(doer *User) {
@@ -236,7 +240,7 @@ func (issue *Issue) sendLabelUpdatedWebhook(doer *User) {
 			log.Error(2, "LoadIssue: %v", err)
 			return
 		}
-		err = PrepareWebhooks(issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{
+		err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
 			Action:      api.HOOK_ISSUE_LABEL_UPDATED,
 			Index:       issue.Index,
 			PullRequest: issue.PullRequest.APIFormat(),
@@ -244,7 +248,7 @@ func (issue *Issue) sendLabelUpdatedWebhook(doer *User) {
 			Sender:      doer.APIFormat(),
 		})
 	} else {
-		err = PrepareWebhooks(issue.Repo, HOOK_EVENT_ISSUES, &api.IssuesPayload{
+		err = PrepareWebhooks(issue.Repo, HookEventIssues, &api.IssuesPayload{
 			Action:     api.HOOK_ISSUE_LABEL_UPDATED,
 			Index:      issue.Index,
 			Issue:      issue.APIFormat(),
@@ -258,8 +262,8 @@ func (issue *Issue) sendLabelUpdatedWebhook(doer *User) {
 	}
 }
 
-func (i *Issue) addLabel(e *xorm.Session, label *Label) error {
-	return newIssueLabel(e, i, label)
+func (issue *Issue) addLabel(e *xorm.Session, label *Label) error {
+	return newIssueLabel(e, issue, label)
 }
 
 // AddLabel adds a new label to the issue.
@@ -331,6 +335,8 @@ func (issue *Issue) clearLabels(e *xorm.Session) (err error) {
 	return nil
 }
 
+// ClearLabels removes all issue labels as the given user.
+// Triggers appropriate WebHooks, if any.
 func (issue *Issue) ClearLabels(doer *User) (err error) {
 	sess := x.NewSession()
 	defer sess.Close()
@@ -353,7 +359,7 @@ func (issue *Issue) ClearLabels(doer *User) (err error) {
 			log.Error(2, "LoadIssue: %v", err)
 			return
 		}
-		err = PrepareWebhooks(issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{
+		err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
 			Action:      api.HOOK_ISSUE_LABEL_CLEARED,
 			Index:       issue.Index,
 			PullRequest: issue.PullRequest.APIFormat(),
@@ -361,7 +367,7 @@ func (issue *Issue) ClearLabels(doer *User) (err error) {
 			Sender:      doer.APIFormat(),
 		})
 	} else {
-		err = PrepareWebhooks(issue.Repo, HOOK_EVENT_ISSUES, &api.IssuesPayload{
+		err = PrepareWebhooks(issue.Repo, HookEventIssues, &api.IssuesPayload{
 			Action:     api.HOOK_ISSUE_LABEL_CLEARED,
 			Index:      issue.Index,
 			Issue:      issue.APIFormat(),
@@ -394,12 +400,13 @@ func (issue *Issue) ReplaceLabels(labels []*Label) (err error) {
 	return sess.Commit()
 }
 
-func (i *Issue) GetAssignee() (err error) {
-	if i.AssigneeID == 0 || i.Assignee != nil {
+// GetAssignee get the assignee of the issue.
+func (issue *Issue) GetAssignee() (err error) {
+	if issue.AssigneeID == 0 || issue.Assignee != nil {
 		return nil
 	}
 
-	i.Assignee, err = GetUserByID(i.AssigneeID)
+	issue.Assignee, err = GetUserByID(issue.AssigneeID)
 	if errors.IsUserNotExist(err) {
 		return nil
 	}
@@ -407,8 +414,8 @@ func (i *Issue) GetAssignee() (err error) {
 }
 
 // ReadBy sets issue to be read by given user.
-func (i *Issue) ReadBy(uid int64) error {
-	return UpdateIssueUserByRead(uid, i.ID)
+func (issue *Issue) ReadBy(uid int64) error {
+	return UpdateIssueUserByRead(uid, issue.ID)
 }
 
 func updateIssueCols(e Engine, issue *Issue, cols ...string) error {
@@ -421,41 +428,41 @@ func UpdateIssueCols(issue *Issue, cols ...string) error {
 	return updateIssueCols(x, issue, cols...)
 }
 
-func (i *Issue) changeStatus(e *xorm.Session, doer *User, repo *Repository, isClosed bool) (err error) {
+func (issue *Issue) changeStatus(e *xorm.Session, doer *User, repo *Repository, isClosed bool) (err error) {
 	// Nothing should be performed if current status is same as target status
-	if i.IsClosed == isClosed {
+	if issue.IsClosed == isClosed {
 		return nil
 	}
-	i.IsClosed = isClosed
+	issue.IsClosed = isClosed
 
-	if err = updateIssueCols(e, i, "is_closed"); err != nil {
+	if err = updateIssueCols(e, issue, "is_closed"); err != nil {
 		return err
-	} else if err = updateIssueUsersByStatus(e, i.ID, isClosed); err != nil {
+	} else if err = updateIssueUsersByStatus(e, issue.ID, isClosed); err != nil {
 		return err
 	}
 
 	// Update issue count of labels
-	if err = i.getLabels(e); err != nil {
+	if err = issue.getLabels(e); err != nil {
 		return err
 	}
-	for idx := range i.Labels {
-		if i.IsClosed {
-			i.Labels[idx].NumClosedIssues++
+	for idx := range issue.Labels {
+		if issue.IsClosed {
+			issue.Labels[idx].NumClosedIssues++
 		} else {
-			i.Labels[idx].NumClosedIssues--
+			issue.Labels[idx].NumClosedIssues--
 		}
-		if err = updateLabel(e, i.Labels[idx]); err != nil {
+		if err = updateLabel(e, issue.Labels[idx]); err != nil {
 			return err
 		}
 	}
 
 	// Update issue count of milestone
-	if err = changeMilestoneIssueStats(e, i); err != nil {
+	if err = changeMilestoneIssueStats(e, issue); err != nil {
 		return err
 	}
 
 	// New action comment
-	if _, err = createStatusComment(e, doer, repo, i); err != nil {
+	if _, err = createStatusComment(e, doer, repo, issue); err != nil {
 		return err
 	}
 
@@ -492,7 +499,7 @@ func (issue *Issue) ChangeStatus(doer *User, repo *Repository, isClosed bool) (e
 		} else {
 			apiPullRequest.Action = api.HOOK_ISSUE_REOPENED
 		}
-		err = PrepareWebhooks(repo, HOOK_EVENT_PULL_REQUEST, apiPullRequest)
+		err = PrepareWebhooks(repo, HookEventPullRequest, apiPullRequest)
 	} else {
 		apiIssues := &api.IssuesPayload{
 			Index:      issue.Index,
@@ -505,7 +512,7 @@ func (issue *Issue) ChangeStatus(doer *User, repo *Repository, isClosed bool) (e
 		} else {
 			apiIssues.Action = api.HOOK_ISSUE_REOPENED
 		}
-		err = PrepareWebhooks(repo, HOOK_EVENT_ISSUES, apiIssues)
+		err = PrepareWebhooks(repo, HookEventIssues, apiIssues)
 	}
 	if err != nil {
 		raven.CaptureErrorAndWait(err, nil)
@@ -515,6 +522,7 @@ func (issue *Issue) ChangeStatus(doer *User, repo *Repository, isClosed bool) (e
 	return nil
 }
 
+// ChangeTitle changes the title of this issue, as the given user.
 func (issue *Issue) ChangeTitle(doer *User, title string) (err error) {
 	oldTitle := issue.Title
 	issue.Title = title
@@ -524,7 +532,7 @@ func (issue *Issue) ChangeTitle(doer *User, title string) (err error) {
 
 	if issue.IsPull {
 		issue.PullRequest.Issue = issue
-		err = PrepareWebhooks(issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{
+		err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
 			Action:      api.HOOK_ISSUE_EDITED,
 			Index:       issue.Index,
 			PullRequest: issue.PullRequest.APIFormat(),
@@ -537,7 +545,7 @@ func (issue *Issue) ChangeTitle(doer *User, title string) (err error) {
 			Sender:     doer.APIFormat(),
 		})
 	} else {
-		err = PrepareWebhooks(issue.Repo, HOOK_EVENT_ISSUES, &api.IssuesPayload{
+		err = PrepareWebhooks(issue.Repo, HookEventIssues, &api.IssuesPayload{
 			Action: api.HOOK_ISSUE_EDITED,
 			Index:  issue.Index,
 			Issue:  issue.APIFormat(),
@@ -558,6 +566,7 @@ func (issue *Issue) ChangeTitle(doer *User, title string) (err error) {
 	return nil
 }
 
+// ChangeContent changes issue content, as the given user.
 func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
 	oldContent := issue.Content
 	issue.Content = content
@@ -567,7 +576,7 @@ func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
 
 	if issue.IsPull {
 		issue.PullRequest.Issue = issue
-		err = PrepareWebhooks(issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{
+		err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
 			Action:      api.HOOK_ISSUE_EDITED,
 			Index:       issue.Index,
 			PullRequest: issue.PullRequest.APIFormat(),
@@ -580,7 +589,7 @@ func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
 			Sender:     doer.APIFormat(),
 		})
 	} else {
-		err = PrepareWebhooks(issue.Repo, HOOK_EVENT_ISSUES, &api.IssuesPayload{
+		err = PrepareWebhooks(issue.Repo, HookEventIssues, &api.IssuesPayload{
 			Action: api.HOOK_ISSUE_EDITED,
 			Index:  issue.Index,
 			Issue:  issue.APIFormat(),
@@ -601,6 +610,7 @@ func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
 	return nil
 }
 
+// ChangeAssignee changes issue assignee.
 func (issue *Issue) ChangeAssignee(doer *User, assigneeID int64) (err error) {
 	issue.AssigneeID = assigneeID
 	if err = UpdateIssueUserByAssignee(issue); err != nil {
@@ -629,7 +639,7 @@ func (issue *Issue) ChangeAssignee(doer *User, assigneeID int64) (err error) {
 		} else {
 			apiPullRequest.Action = api.HOOK_ISSUE_ASSIGNED
 		}
-		err = PrepareWebhooks(issue.Repo, HOOK_EVENT_PULL_REQUEST, apiPullRequest)
+		err = PrepareWebhooks(issue.Repo, HookEventPullRequest, apiPullRequest)
 	} else {
 		apiIssues := &api.IssuesPayload{
 			Index:      issue.Index,
@@ -642,7 +652,7 @@ func (issue *Issue) ChangeAssignee(doer *User, assigneeID int64) (err error) {
 		} else {
 			apiIssues.Action = api.HOOK_ISSUE_ASSIGNED
 		}
-		err = PrepareWebhooks(issue.Repo, HOOK_EVENT_ISSUES, apiIssues)
+		err = PrepareWebhooks(issue.Repo, HookEventIssues, apiIssues)
 	}
 	if err != nil {
 		raven.CaptureErrorAndWait(err, nil)
@@ -652,6 +662,7 @@ func (issue *Issue) ChangeAssignee(doer *User, assigneeID int64) (err error) {
 	return nil
 }
 
+// NewIssueOptions represents the options of a new issue.
 type NewIssueOptions struct {
 	Repo        *Repository
 	Issue       *Issue
@@ -690,7 +701,7 @@ func newIssue(e *xorm.Session, opts NewIssueOptions) (err error) {
 		// Assume assignee is invalid and drop silently.
 		opts.Issue.AssigneeID = 0
 		if assignee != nil {
-			valid, err := hasAccess(e, assignee.ID, opts.Repo, ACCESS_MODE_READ)
+			valid, err := hasAccess(e, assignee.ID, opts.Repo, AccessModeRead)
 			if err != nil {
 				return fmt.Errorf("hasAccess [user_id: %d, repo_id: %d]: %v", assignee.ID, opts.Repo.ID, err)
 			}
@@ -780,7 +791,7 @@ func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string)
 	if err = NotifyWatchers(&Action{
 		ActUserID:    issue.Poster.ID,
 		ActUserName:  issue.Poster.Name,
-		OpType:       ACTION_CREATE_ISSUE,
+		OpType:       ActionCreateIssue,
 		Content:      fmt.Sprintf("%d|%s", issue.Index, issue.Title),
 		RepoID:       repo.ID,
 		RepoUserName: repo.Owner.Name,
@@ -795,7 +806,7 @@ func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string)
 		log.Error(2, "MailParticipants: %v", err)
 	}
 
-	if err = PrepareWebhooks(repo, HOOK_EVENT_ISSUES, &api.IssuesPayload{
+	if err = PrepareWebhooks(repo, HookEventIssues, &api.IssuesPayload{
 		Action:     api.HOOK_ISSUE_OPENED,
 		Index:      issue.Index,
 		Issue:      issue.APIFormat(),
@@ -835,7 +846,7 @@ func GetIssueByRef(ref string) (*Issue, error) {
 	return issue, issue.LoadAttributes()
 }
 
-// GetIssueByIndex returns raw issue without loading attributes by index in a repository.
+// GetRawIssueByIndex returns raw issue without loading attributes by index in a repository.
 func GetRawIssueByIndex(repoID, index int64) (*Issue, error) {
 	issue := &Issue{
 		RepoID: repoID,
@@ -883,6 +894,7 @@ func GetIssueByID(id int64) (*Issue, error) {
 	return getIssueByID(x, id)
 }
 
+// IssuesOptions represents options of an issue.
 type IssuesOptions struct {
 	UserID      int64
 	AssigneeID  int64
@@ -1091,9 +1103,9 @@ func NewIssueUsers(repo *Repository, issue *Issue) (err error) {
 }
 
 // PairsContains returns true when pairs list contains given issue.
-func PairsContains(ius []*IssueUser, issueId, uid int64) int {
+func PairsContains(ius []*IssueUser, issueID, uid int64) int {
 	for i := range ius {
-		if ius[i].IssueID == issueId &&
+		if ius[i].IssueID == issueID &&
 			ius[i].UID == uid {
 			return i
 		}
@@ -1129,9 +1141,9 @@ func GetIssueUserPairsByMode(userID, repoID int64, filterMode FilterMode, isClos
 	}
 
 	switch filterMode {
-	case FILTER_MODE_ASSIGN:
+	case FilterModeAssign:
 		sess.And("is_assigned=?", true)
-	case FILTER_MODE_CREATE:
+	case FilterModeCreate:
 		sess.And("is_poster=?", true)
 	default:
 		return ius, nil
@@ -1192,13 +1204,15 @@ type IssueStats struct {
 	MentionCount           int64
 }
 
+// FilterMode represents an mode.
 type FilterMode string
 
+// Filter modes.
 const (
-	FILTER_MODE_YOUR_REPOS FilterMode = "your_repositories"
-	FILTER_MODE_ASSIGN     FilterMode = "assigned"
-	FILTER_MODE_CREATE     FilterMode = "created_by"
-	FILTER_MODE_MENTION    FilterMode = "mentioned"
+	FilterModeYourRepos FilterMode = "your_repositories"
+	FilterModeAssign    FilterMode = "assigned"
+	FilterModeCreate    FilterMode = "created_by"
+	FilterModeMention   FilterMode = "mentioned"
 )
 
 func parseCountResult(results []map[string][]byte) int64 {
@@ -1211,6 +1225,7 @@ func parseCountResult(results []map[string][]byte) int64 {
 	return 0
 }
 
+// IssueStatsOptions contains parameters accepted by GetIssueStats.
 type IssueStatsOptions struct {
 	RepoID      int64
 	UserID      int64
@@ -1252,7 +1267,7 @@ func GetIssueStats(opts *IssueStatsOptions) *IssueStats {
 	}
 
 	switch opts.FilterMode {
-	case FILTER_MODE_YOUR_REPOS, FILTER_MODE_ASSIGN:
+	case FilterModeYourRepos, FilterModeAssign:
 		stats.OpenCount, _ = countSession(opts).
 			And("is_closed = ?", false).
 			Count(new(Issue))
@@ -1260,7 +1275,7 @@ func GetIssueStats(opts *IssueStatsOptions) *IssueStats {
 		stats.ClosedCount, _ = countSession(opts).
 			And("is_closed = ?", true).
 			Count(new(Issue))
-	case FILTER_MODE_CREATE:
+	case FilterModeCreate:
 		stats.OpenCount, _ = countSession(opts).
 			And("poster_id = ?", opts.UserID).
 			And("is_closed = ?", false).
@@ -1270,7 +1285,7 @@ func GetIssueStats(opts *IssueStatsOptions) *IssueStats {
 			And("poster_id = ?", opts.UserID).
 			And("is_closed = ?", true).
 			Count(new(Issue))
-	case FILTER_MODE_MENTION:
+	case FilterModeMention:
 		stats.OpenCount, _ = countSession(opts).
 			Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
 			And("issue_user.uid = ?", opts.UserID).
@@ -1318,7 +1333,7 @@ func GetUserIssueStats(repoID, userID int64, repoIDs []int64, filterMode FilterM
 	}
 
 	switch filterMode {
-	case FILTER_MODE_YOUR_REPOS:
+	case FilterModeYourRepos:
 		if !hasAnyRepo {
 			break
 		}
@@ -1327,14 +1342,14 @@ func GetUserIssueStats(repoID, userID int64, repoIDs []int64, filterMode FilterM
 			Count(new(Issue))
 		stats.ClosedCount, _ = countSession(true, isPull, repoID, repoIDs).
 			Count(new(Issue))
-	case FILTER_MODE_ASSIGN:
+	case FilterModeAssign:
 		stats.OpenCount, _ = countSession(false, isPull, repoID, nil).
 			And("assignee_id = ?", userID).
 			Count(new(Issue))
 		stats.ClosedCount, _ = countSession(true, isPull, repoID, nil).
 			And("assignee_id = ?", userID).
 			Count(new(Issue))
-	case FILTER_MODE_CREATE:
+	case FilterModeCreate:
 		stats.OpenCount, _ = countSession(false, isPull, repoID, nil).
 			And("poster_id = ?", userID).
 			Count(new(Issue))
@@ -1360,10 +1375,10 @@ func GetRepoIssueStats(repoID, userID int64, filterMode FilterMode, isPull bool)
 	closedCountSession := countSession(true, isPull, repoID)
 
 	switch filterMode {
-	case FILTER_MODE_ASSIGN:
+	case FilterModeAssign:
 		openCountSession.And("assignee_id = ?", userID)
 		closedCountSession.And("assignee_id = ?", userID)
-	case FILTER_MODE_CREATE:
+	case FilterModeCreate:
 		openCountSession.And("poster_id = ?", userID)
 		closedCountSession.And("poster_id = ?", userID)
 	}

+ 4 - 3
models/issue_label.go

@@ -64,6 +64,7 @@ type Label struct {
 	IsChecked       bool `xorm:"-" json:"-"`
 }
 
+// APIFormat converts a Label to the api.Label format
 func (label *Label) APIFormat() *api.Label {
 	return &api.Label{
 		ID:    label.ID,
@@ -79,9 +80,9 @@ func (label *Label) CalOpenIssues() {
 
 // ForegroundColor calculates the text color for labels based
 // on their background color.
-func (l *Label) ForegroundColor() template.CSS {
-	if strings.HasPrefix(l.Color, "#") {
-		if color, err := strconv.ParseUint(l.Color[1:], 16, 64); err == nil {
+func (label *Label) ForegroundColor() template.CSS {
+	if strings.HasPrefix(label.Color, "#") {
+		if color, err := strconv.ParseUint(label.Color[1:], 16, 64); err == nil {
 			r := float32(0xFF & (color >> 16))
 			g := float32(0xFF & (color >> 8))
 			b := float32(0xFF & color)

+ 27 - 23
models/issue_mail.go

@@ -12,11 +12,12 @@ import (
 	"gitote/gitote/pkg/markup"
 	"gitote/gitote/pkg/setting"
 
-	"github.com/Unknwon/com"
 	raven "github.com/getsentry/raven-go"
+	"gitlab.com/gitote/com"
 	log "gopkg.in/clog.v1"
 )
 
+// MailSubject returns subject of mail.
 func (issue *Issue) MailSubject() string {
 	return fmt.Sprintf("[%s] %s (#%d)", issue.Repo.Name, issue.Title, issue.Index)
 }
@@ -26,26 +27,27 @@ type mailerUser struct {
 	user *User
 }
 
-func (this mailerUser) ID() int64 {
-	return this.user.ID
+func (t mailerUser) ID() int64 {
+	return t.user.ID
 }
 
-func (this mailerUser) DisplayName() string {
-	return this.user.DisplayName()
+func (t mailerUser) DisplayName() string {
+	return t.user.DisplayName()
 }
 
-func (this mailerUser) Email() string {
-	return this.user.Email
+func (t mailerUser) Email() string {
+	return t.user.Email
 }
 
-func (this mailerUser) GenerateActivateCode() string {
-	return this.user.GenerateActivateCode()
+func (t mailerUser) GenerateActivateCode() string {
+	return t.user.GenerateActivateCode()
 }
 
-func (this mailerUser) GenerateEmailActivateCode(email string) string {
-	return this.user.GenerateEmailActivateCode(email)
+func (t mailerUser) GenerateEmailActivateCode(email string) string {
+	return t.user.GenerateEmailActivateCode(email)
 }
 
+// NewMailerUser returns mailerUser
 func NewMailerUser(u *User) mailer.User {
 	return mailerUser{u}
 }
@@ -55,18 +57,19 @@ type mailerRepo struct {
 	repo *Repository
 }
 
-func (this mailerRepo) FullName() string {
-	return this.repo.FullName()
+func (t mailerRepo) FullName() string {
+	return t.repo.FullName()
 }
 
-func (this mailerRepo) HTMLURL() string {
-	return this.repo.HTMLURL()
+func (t mailerRepo) HTMLURL() string {
+	return t.repo.HTMLURL()
 }
 
-func (this mailerRepo) ComposeMetas() map[string]string {
-	return this.repo.ComposeMetas()
+func (t mailerRepo) ComposeMetas() map[string]string {
+	return t.repo.ComposeMetas()
 }
 
+// NewMailerRepo returns mailerRepo
 func NewMailerRepo(repo *Repository) mailer.Repository {
 	return mailerRepo{repo}
 }
@@ -76,18 +79,19 @@ type mailerIssue struct {
 	issue *Issue
 }
 
-func (this mailerIssue) MailSubject() string {
-	return this.issue.MailSubject()
+func (t mailerIssue) MailSubject() string {
+	return t.issue.MailSubject()
 }
 
-func (this mailerIssue) Content() string {
-	return this.issue.Content
+func (t mailerIssue) Content() string {
+	return t.issue.Content
 }
 
-func (this mailerIssue) HTMLURL() string {
-	return this.issue.HTMLURL()
+func (t mailerIssue) HTMLURL() string {
+	return t.issue.HTMLURL()
 }
 
+// NewMailerIssue returns mailerIssue
 func NewMailerIssue(issue *Issue) mailer.Issue {
 	return mailerIssue{issue}
 }

+ 88 - 47
models/login_source.go

@@ -4,7 +4,6 @@
 // This source code is licensed under the MIT license found in the
 // LICENSE file in the root directory of this source tree.
 
-// FIXME: Put this file into its own package and separate into different files based on login sources.
 package models
 
 import (
@@ -23,37 +22,40 @@ import (
 	"sync"
 	"time"
 
-	"github.com/Unknwon/com"
 	raven "github.com/getsentry/raven-go"
 	"github.com/go-macaron/binding"
 	"github.com/go-xorm/core"
 	"github.com/go-xorm/xorm"
 	"github.com/json-iterator/go"
+	"gitlab.com/gitote/com"
 	log "gopkg.in/clog.v1"
 	"gopkg.in/ini.v1"
 )
 
+// LoginType represents an login type.
 type LoginType int
 
 // Note: new type must append to the end of list to maintain compatibility.
 const (
-	LOGIN_NOTYPE LoginType = iota
-	LOGIN_PLAIN            // 1
-	LOGIN_LDAP             // 2
-	LOGIN_SMTP             // 3
-	LOGIN_PAM              // 4
-	LOGIN_DLDAP            // 5
-	LOGIN_GITHUB           // 6
+	LoginNotype LoginType = iota
+	LoginPlain            // 1
+	LoginLDAP             // 2
+	LoginSMTP             // 3
+	LoginPAM              // 4
+	LoginDLDAP            // 5
+	LoginGitHub           // 6
 )
 
+// LoginNames contains the name of LoginType values.
 var LoginNames = map[LoginType]string{
-	LOGIN_LDAP:   "LDAP (via BindDN)",
-	LOGIN_DLDAP:  "LDAP (simple auth)", // Via direct bind
-	LOGIN_SMTP:   "SMTP",
-	LOGIN_PAM:    "PAM",
-	LOGIN_GITHUB: "GitHub",
+	LoginLDAP:   "LDAP (via BindDN)",
+	LoginDLDAP:  "LDAP (simple auth)", // Via direct bind
+	LoginSMTP:   "SMTP",
+	LoginPAM:    "PAM",
+	LoginGitHub: "GitHub",
 }
 
+// SecurityProtocolNames contains the name of SecurityProtocol values.
 var SecurityProtocolNames = map[ldap.SecurityProtocol]string{
 	ldap.SECURITY_PROTOCOL_UNENCRYPTED: "Unencrypted",
 	ldap.SECURITY_PROTOCOL_LDAPS:       "LDAPS",
@@ -68,34 +70,43 @@ var (
 	_ core.Conversion = &GitHubConfig{}
 )
 
+// LDAPConfig holds configuration for LDAP login source.
 type LDAPConfig struct {
 	*ldap.Source `ini:"config"`
 }
 
+// FromDB fills up a LDAPConfig from serialized format.
 func (cfg *LDAPConfig) FromDB(bs []byte) error {
 	return jsoniter.Unmarshal(bs, &cfg)
 }
 
+// ToDB exports a LDAPConfig to a serialized format.
 func (cfg *LDAPConfig) ToDB() ([]byte, error) {
 	return jsoniter.Marshal(cfg)
 }
 
+// GitHubConfig holds configuration for GitHub login source.
 type GitHubConfig struct {
 	APIEndpoint string // GitHub service (e.g. https://api.github.com/)
 }
 
+// FromDB fills up a GitHubConfig from serialized format.
 func (cfg *GitHubConfig) FromDB(bs []byte) error {
 	return jsoniter.Unmarshal(bs, &cfg)
 }
 
+// ToDB exports a GitHubConfig to a serialized format.
 func (cfg *GitHubConfig) ToDB() ([]byte, error) {
 	return jsoniter.Marshal(cfg)
 }
 
+// SecurityProtocolName returns the name of configured security
+// protocol.
 func (cfg *LDAPConfig) SecurityProtocolName() string {
 	return SecurityProtocolNames[cfg.SecurityProtocol]
 }
 
+// SMTPConfig holds configuration for the SMTP login source.
 type SMTPConfig struct {
 	Auth           string
 	Host           string
@@ -105,22 +116,27 @@ type SMTPConfig struct {
 	SkipVerify     bool
 }
 
+// FromDB fills up an SMTPConfig from serialized format.
 func (cfg *SMTPConfig) FromDB(bs []byte) error {
 	return jsoniter.Unmarshal(bs, cfg)
 }
 
+// ToDB exports an SMTPConfig to a serialized format.
 func (cfg *SMTPConfig) ToDB() ([]byte, error) {
 	return jsoniter.Marshal(cfg)
 }
 
+// PAMConfig holds configuration for the PAM login source.
 type PAMConfig struct {
 	ServiceName string // PAM service (e.g. system-auth)
 }
 
+// FromDB fills up a PAMConfig from serialized format.
 func (cfg *PAMConfig) FromDB(bs []byte) error {
 	return jsoniter.Unmarshal(bs, &cfg)
 }
 
+// ToDB exports a PAMConfig to a serialized format.
 func (cfg *PAMConfig) ToDB() ([]byte, error) {
 	return jsoniter.Marshal(cfg)
 }
@@ -163,11 +179,13 @@ type LoginSource struct {
 	LocalFile *AuthSourceFile `xorm:"-" json:"-"`
 }
 
+// BeforeInsert will be invoked by XORM before inserting a record
 func (s *LoginSource) BeforeInsert() {
 	s.CreatedUnix = time.Now().Unix()
 	s.UpdatedUnix = s.CreatedUnix
 }
 
+// BeforeUpdate is invoked from XORM before updating this object.
 func (s *LoginSource) BeforeUpdate() {
 	s.UpdatedUnix = time.Now().Unix()
 }
@@ -183,17 +201,18 @@ func Cell2Int64(val xorm.Cell) int64 {
 	return (*val).(int64)
 }
 
+// BeforeSet is invoked from XORM before setting the value of a field of this object.
 func (s *LoginSource) BeforeSet(colName string, val xorm.Cell) {
 	switch colName {
 	case "type":
 		switch LoginType(Cell2Int64(val)) {
-		case LOGIN_LDAP, LOGIN_DLDAP:
+		case LoginLDAP, LoginDLDAP:
 			s.Cfg = new(LDAPConfig)
-		case LOGIN_SMTP:
+		case LoginSMTP:
 			s.Cfg = new(SMTPConfig)
-		case LOGIN_PAM:
+		case LoginPAM:
 			s.Cfg = new(PAMConfig)
-		case LOGIN_GITHUB:
+		case LoginGitHub:
 			s.Cfg = new(GitHubConfig)
 		default:
 			panic("unrecognized login source type: " + com.ToStr(*val))
@@ -201,6 +220,7 @@ func (s *LoginSource) BeforeSet(colName string, val xorm.Cell) {
 	}
 }
 
+// AfterSet is invoked from XORM after setting the values of all fields of this object.
 func (s *LoginSource) AfterSet(colName string, _ xorm.Cell) {
 	switch colName {
 	case "created_unix":
@@ -210,74 +230,89 @@ func (s *LoginSource) AfterSet(colName string, _ xorm.Cell) {
 	}
 }
 
+// TypeName return name of this login source type.
 func (s *LoginSource) TypeName() string {
 	return LoginNames[s.Type]
 }
 
+// IsLDAP returns true of this source is of the LDAP type.
 func (s *LoginSource) IsLDAP() bool {
-	return s.Type == LOGIN_LDAP
+	return s.Type == LoginLDAP
 }
 
+// IsDLDAP returns true of this source is of the DLDAP type.
 func (s *LoginSource) IsDLDAP() bool {
-	return s.Type == LOGIN_DLDAP
+	return s.Type == LoginDLDAP
 }
 
+// IsSMTP returns true of this source is of the SMTP type.
 func (s *LoginSource) IsSMTP() bool {
-	return s.Type == LOGIN_SMTP
+	return s.Type == LoginSMTP
 }
 
+// IsPAM returns true of this source is of the PAM type.
 func (s *LoginSource) IsPAM() bool {
-	return s.Type == LOGIN_PAM
+	return s.Type == LoginPAM
 }
 
+// IsGitHub returns true of this source is of the GitHub type.
 func (s *LoginSource) IsGitHub() bool {
-	return s.Type == LOGIN_GITHUB
+	return s.Type == LoginGitHub
 }
 
+// HasTLS returns true of this source supports TLS.
 func (s *LoginSource) HasTLS() bool {
 	return ((s.IsLDAP() || s.IsDLDAP()) &&
 		s.LDAP().SecurityProtocol > ldap.SECURITY_PROTOCOL_UNENCRYPTED) ||
 		s.IsSMTP()
 }
 
+// UseTLS returns true of this source is configured to use TLS.
 func (s *LoginSource) UseTLS() bool {
 	switch s.Type {
-	case LOGIN_LDAP, LOGIN_DLDAP:
+	case LoginLDAP, LoginDLDAP:
 		return s.LDAP().SecurityProtocol != ldap.SECURITY_PROTOCOL_UNENCRYPTED
-	case LOGIN_SMTP:
+	case LoginSMTP:
 		return s.SMTP().TLS
 	}
 
 	return false
 }
 
+// SkipVerify returns true if this source is configured to skip SSL
+// verification.
 func (s *LoginSource) SkipVerify() bool {
 	switch s.Type {
-	case LOGIN_LDAP, LOGIN_DLDAP:
+	case LoginLDAP, LoginDLDAP:
 		return s.LDAP().SkipVerify
-	case LOGIN_SMTP:
+	case LoginSMTP:
 		return s.SMTP().SkipVerify
 	}
 
 	return false
 }
 
+// LDAP returns LDAPConfig for this source, if of LDAP type.
 func (s *LoginSource) LDAP() *LDAPConfig {
 	return s.Cfg.(*LDAPConfig)
 }
 
+// SMTP returns SMTPConfig for this source, if of SMTP type.
 func (s *LoginSource) SMTP() *SMTPConfig {
 	return s.Cfg.(*SMTPConfig)
 }
 
+// PAM returns PAMConfig for this source, if of PAM type.
 func (s *LoginSource) PAM() *PAMConfig {
 	return s.Cfg.(*PAMConfig)
 }
 
+// GitHub returns GitHubConfig for this source, if of GitHubConfig type.
 func (s *LoginSource) GitHub() *GitHubConfig {
 	return s.Cfg.(*GitHubConfig)
 }
 
+// CreateLoginSource inserts a LoginSource in the DB if not already existing with the given name.
 func CreateLoginSource(source *LoginSource) error {
 	has, err := x.Get(&LoginSource{Name: source.Name})
 	if err != nil {
@@ -370,6 +405,7 @@ func UpdateLoginSource(source *LoginSource) error {
 	return ResetNonDefaultLoginSources(source)
 }
 
+// DeleteSource deletes a LoginSource record in DB.
 func DeleteSource(source *LoginSource) error {
 	count, err := x.Count(&User{LoginSource: source.ID})
 	if err != nil {
@@ -394,6 +430,7 @@ type LocalLoginSources struct {
 	sources []*LoginSource
 }
 
+// Len returns length of local login sources.
 func (s *LocalLoginSources) Len() int {
 	return len(s.sources)
 }
@@ -509,19 +546,19 @@ func LoadAuthSources() {
 		authType := s.Key("type").String()
 		switch authType {
 		case "ldap_bind_dn":
-			loginSource.Type = LOGIN_LDAP
+			loginSource.Type = LoginLDAP
 			loginSource.Cfg = &LDAPConfig{}
 		case "ldap_simple_auth":
-			loginSource.Type = LOGIN_DLDAP
+			loginSource.Type = LoginDLDAP
 			loginSource.Cfg = &LDAPConfig{}
 		case "smtp":
-			loginSource.Type = LOGIN_SMTP
+			loginSource.Type = LoginSMTP
 			loginSource.Cfg = &SMTPConfig{}
 		case "pam":
-			loginSource.Type = LOGIN_PAM
+			loginSource.Type = LoginPAM
 			loginSource.Cfg = &PAMConfig{}
 		case "github":
-			loginSource.Type = LOGIN_GITHUB
+			loginSource.Type = LoginGitHub
 			loginSource.Cfg = &GitHubConfig{}
 		default:
 			raven.CaptureErrorAndWait(err, nil)
@@ -553,7 +590,7 @@ func composeFullName(firstname, surname, username string) string {
 // LoginViaLDAP queries if login/password is valid against the LDAP directory pool,
 // and create a local user if success when enabled.
 func LoginViaLDAP(user *User, login, password string, source *LoginSource, autoRegister bool) (*User, error) {
-	username, fn, sn, mail, isAdmin, succeed := source.Cfg.(*LDAPConfig).SearchEntry(login, password, source.Type == LOGIN_DLDAP)
+	username, fn, sn, mail, isAdmin, succeed := source.Cfg.(*LDAPConfig).SearchEntry(login, password, source.Type == LoginDLDAP)
 	if !succeed {
 		// User not in LDAP, do nothing
 		return nil, errors.UserNotExist{0, login}
@@ -620,13 +657,16 @@ func (auth *smtpLoginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
 	return nil, nil
 }
 
+// SMTP authentication type names.
 const (
-	SMTP_PLAIN = "PLAIN"
-	SMTP_LOGIN = "LOGIN"
+	SMTPPlain = "PLAIN"
+	SMTPLogin = "LOGIN"
 )
 
-var SMTPAuths = []string{SMTP_PLAIN, SMTP_LOGIN}
+// SMTPAuths contains available SMTP authentication type names.
+var SMTPAuths = []string{SMTPPlain, SMTPLogin}
 
+// SMTPAuth contains available SMTP authentication type names.
 func SMTPAuth(a smtp.Auth, cfg *SMTPConfig) error {
 	c, err := smtp.Dial(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port))
 	if err != nil {
@@ -674,9 +714,9 @@ func LoginViaSMTP(user *User, login, password string, sourceID int64, cfg *SMTPC
 	}
 
 	var auth smtp.Auth
-	if cfg.Auth == SMTP_PLAIN {
+	if cfg.Auth == SMTPPlain {
 		auth = smtp.PlainAuth("", login, password, cfg.Host)
-	} else if cfg.Auth == SMTP_LOGIN {
+	} else if cfg.Auth == SMTPLogin {
 		auth = &smtpLoginAuth{login, password}
 	} else {
 		return nil, errors.New("Unsupported SMTP authentication type")
@@ -708,7 +748,7 @@ func LoginViaSMTP(user *User, login, password string, sourceID int64, cfg *SMTPC
 		Name:        strings.ToLower(username),
 		Email:       login,
 		Passwd:      password,
-		LoginType:   LOGIN_SMTP,
+		LoginType:   LoginSMTP,
 		LoginSource: sourceID,
 		LoginName:   login,
 		IsActive:    true,
@@ -735,7 +775,7 @@ func LoginViaPAM(user *User, login, password string, sourceID int64, cfg *PAMCon
 		Name:        login,
 		Email:       login,
 		Passwd:      password,
-		LoginType:   LOGIN_PAM,
+		LoginType:   LoginPAM,
 		LoginSource: sourceID,
 		LoginName:   login,
 		IsActive:    true,
@@ -743,6 +783,7 @@ func LoginViaPAM(user *User, login, password string, sourceID int64, cfg *PAMCon
 	return user, CreateUser(user)
 }
 
+// LoginViaGitHub contains available GitHub authentication type names.
 func LoginViaGitHub(user *User, login, password string, sourceID int64, cfg *GitHubConfig, autoRegister bool) (*User, error) {
 	fullname, email, url, location, err := github.Authenticate(cfg.APIEndpoint, login, password)
 	if err != nil {
@@ -762,7 +803,7 @@ func LoginViaGitHub(user *User, login, password string, sourceID int64, cfg *Git
 		Email:       email,
 		Website:     url,
 		Passwd:      password,
-		LoginType:   LOGIN_GITHUB,
+		LoginType:   LoginGitHub,
 		LoginSource: sourceID,
 		LoginName:   login,
 		IsActive:    true,
@@ -777,13 +818,13 @@ func remoteUserLogin(user *User, login, password string, source *LoginSource, au
 	}
 
 	switch source.Type {
-	case LOGIN_LDAP, LOGIN_DLDAP:
+	case LoginLDAP, LoginDLDAP:
 		return LoginViaLDAP(user, login, password, source, autoRegister)
-	case LOGIN_SMTP:
+	case LoginSMTP:
 		return LoginViaSMTP(user, login, password, source.ID, source.Cfg.(*SMTPConfig), autoRegister)
-	case LOGIN_PAM:
+	case LoginPAM:
 		return LoginViaPAM(user, login, password, source.ID, source.Cfg.(*PAMConfig), autoRegister)
-	case LOGIN_GITHUB:
+	case LoginGitHub:
 		return LoginViaGitHub(user, login, password, source.ID, source.Cfg.(*GitHubConfig), autoRegister)
 	}
 
@@ -813,8 +854,8 @@ func UserLogin(username, password string, loginSourceID int64) (*User, error) {
 		}
 
 		// Validate password hash fetched from database for local accounts
-		if user.LoginType == LOGIN_NOTYPE ||
-			user.LoginType == LOGIN_PLAIN {
+		if user.LoginType == LoginNotype ||
+			user.LoginType == LoginPlain {
 			if user.ValidatePassword(password) {
 				return user, nil
 			}

+ 9 - 3
models/milestone.go

@@ -38,10 +38,12 @@ type Milestone struct {
 	ClosedDateUnix int64
 }
 
+// BeforeInsert will be invoked by XORM before inserting a record
 func (m *Milestone) BeforeInsert() {
 	m.DeadlineUnix = m.Deadline.Unix()
 }
 
+// BeforeUpdate is invoked from XORM before updating this object.
 func (m *Milestone) BeforeUpdate() {
 	if m.NumIssues > 0 {
 		m.Completeness = m.NumClosedIssues * 100 / m.NumIssues
@@ -53,6 +55,7 @@ func (m *Milestone) BeforeUpdate() {
 	m.ClosedDateUnix = m.ClosedDate.Unix()
 }
 
+// AfterSet is invoked from XORM after setting the values of all fields of this object.
 func (m *Milestone) AfterSet(colName string, _ xorm.Cell) {
 	switch colName {
 	case "num_closed_issues":
@@ -82,10 +85,12 @@ func (m *Milestone) State() api.StateType {
 	return api.STATE_OPEN
 }
 
+// ChangeStatus changes milestone status to open or closed.
 func (m *Milestone) ChangeStatus(isClosed bool) error {
 	return ChangeMilestoneStatus(m, isClosed)
 }
 
+// APIFormat returns this Milestone in API format.
 func (m *Milestone) APIFormat() *api.Milestone {
 	apiMilestone := &api.Milestone{
 		ID:           m.ID,
@@ -104,6 +109,7 @@ func (m *Milestone) APIFormat() *api.Milestone {
 	return apiMilestone
 }
 
+// CountIssues counts issues in milestone.
 func (m *Milestone) CountIssues(isClosed, includePulls bool) int64 {
 	sess := x.Where("milestone_id = ?", m.ID).And("is_closed = ?", isClosed)
 	if !includePulls {
@@ -145,7 +151,7 @@ func getMilestoneByRepoID(e Engine, repoID, id int64) (*Milestone, error) {
 	return m, nil
 }
 
-// GetWebhookByRepoID returns the milestone in a repository.
+// GetMilestoneByRepoID returns the milestone in a repository.
 func GetMilestoneByRepoID(repoID, id int64) (*Milestone, error) {
 	return getMilestoneByRepoID(x, repoID, id)
 }
@@ -341,7 +347,7 @@ func ChangeMilestoneAssign(doer *User, issue *Issue, oldMilestoneID int64) (err
 			log.Error(2, "LoadIssue: %v", err)
 			return
 		}
-		err = PrepareWebhooks(issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{
+		err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
 			Action:      hookAction,
 			Index:       issue.Index,
 			PullRequest: issue.PullRequest.APIFormat(),
@@ -349,7 +355,7 @@ func ChangeMilestoneAssign(doer *User, issue *Issue, oldMilestoneID int64) (err
 			Sender:      doer.APIFormat(),
 		})
 	} else {
-		err = PrepareWebhooks(issue.Repo, HOOK_EVENT_ISSUES, &api.IssuesPayload{
+		err = PrepareWebhooks(issue.Repo, HookEventIssues, &api.IssuesPayload{
 			Action:     hookAction,
 			Index:      issue.Index,
 			Issue:      issue.APIFormat(),

+ 18 - 10
models/mirror.go

@@ -17,14 +17,15 @@ import (
 	"strings"
 	"time"
 
-	"github.com/Unknwon/com"
 	raven "github.com/getsentry/raven-go"
 	"github.com/go-xorm/xorm"
+	"gitlab.com/gitote/com"
 	"gitlab.com/gitote/git-module"
 	log "gopkg.in/clog.v1"
 	"gopkg.in/ini.v1"
 )
 
+// MirrorQueue holds an UniqueQueue object of the mirror
 var MirrorQueue = sync.NewUniqueQueue(setting.Repository.MirrorQueueLength)
 
 // Mirror represents mirror information of a repository.
@@ -44,15 +45,18 @@ type Mirror struct {
 	address string `xorm:"-" json:"-"`
 }
 
+// BeforeInsert will be invoked by XORM before inserting a record
 func (m *Mirror) BeforeInsert() {
 	m.NextSyncUnix = m.NextSync.Unix()
 }
 
+// BeforeUpdate is invoked from XORM before updating this object.
 func (m *Mirror) BeforeUpdate() {
 	m.LastSyncUnix = m.LastSync.Unix()
 	m.NextSyncUnix = m.NextSync.Unix()
 }
 
+// AfterSet is invoked from XORM after setting the values of all fields of this object.
 func (m *Mirror) AfterSet(colName string, _ xorm.Cell) {
 	var err error
 	switch colName {
@@ -94,7 +98,7 @@ func findPasswordInMirrorAddress(addr string) (start int, end int, found bool) {
 	if delim == -1 {
 		return -1, -1, false
 	}
-	delim += 1
+	delim++
 
 	if start+delim >= end {
 		return -1, -1, false // No password portion presented
@@ -192,7 +196,8 @@ func (m *Mirror) SaveAddress(addr string) error {
 	return cfg.SaveToIndent(configPath, "\t")
 }
 
-const GIT_SHORT_EMPTY_SHA = "0000000"
+// GitShortEmptySHA Git short empty SHA
+const GitShortEmptySHA = "0000000"
 
 // mirrorSyncResult contains information of a updated reference.
 // If the oldCommitID is "0000000", it means a new reference, the value of newCommitID is empty.
@@ -220,12 +225,12 @@ func parseRemoteUpdateOutput(output string) []*mirrorSyncResult {
 		case strings.HasPrefix(lines[i], " * "): // New reference
 			results = append(results, &mirrorSyncResult{
 				refName:     refName,
-				oldCommitID: GIT_SHORT_EMPTY_SHA,
+				oldCommitID: GitShortEmptySHA,
 			})
 		case strings.HasPrefix(lines[i], " - "): // Delete reference
 			results = append(results, &mirrorSyncResult{
 				refName:     refName,
-				newCommitID: GIT_SHORT_EMPTY_SHA,
+				newCommitID: GitShortEmptySHA,
 			})
 		case strings.HasPrefix(lines[i], "   "): // New commits of a reference
 			delimIdx := strings.Index(lines[i][3:], " ")
@@ -333,10 +338,12 @@ func updateMirror(e Engine, m *Mirror) error {
 	return err
 }
 
+// UpdateMirror returns updateMirror
 func UpdateMirror(m *Mirror) error {
 	return updateMirror(x, m)
 }
 
+// DeleteMirrorByRepoID delted repo by ID
 func DeleteMirrorByRepoID(repoID int64) error {
 	_, err := x.Delete(&Mirror{RepoID: repoID})
 	return err
@@ -344,11 +351,11 @@ func DeleteMirrorByRepoID(repoID int64) error {
 
 // MirrorUpdate checks and updates mirror repositories.
 func MirrorUpdate() {
-	if taskStatusTable.IsRunning(_MIRROR_UPDATE) {
+	if taskStatusTable.IsRunning(_MirrorUpdate) {
 		return
 	}
-	taskStatusTable.Start(_MIRROR_UPDATE)
-	defer taskStatusTable.Stop(_MIRROR_UPDATE)
+	taskStatusTable.Start(_MirrorUpdate)
+	defer taskStatusTable.Stop(_MirrorUpdate)
 
 	log.Trace("Doing: MirrorUpdate")
 
@@ -417,7 +424,7 @@ func SyncMirrors() {
 			}
 
 			// Delete reference
-			if result.newCommitID == GIT_SHORT_EMPTY_SHA {
+			if result.newCommitID == GitShortEmptySHA {
 				if err = MirrorSyncDeleteAction(m.Repo, result.refName); err != nil {
 					raven.CaptureErrorAndWait(err, nil)
 					log.Error(2, "MirrorSyncDeleteAction [repo_id: %d]: %v", m.RepoID, err)
@@ -427,7 +434,7 @@ func SyncMirrors() {
 
 			// New reference
 			isNewRef := false
-			if result.oldCommitID == GIT_SHORT_EMPTY_SHA {
+			if result.oldCommitID == GitShortEmptySHA {
 				if err = MirrorSyncCreateAction(m.Repo, result.refName); err != nil {
 					raven.CaptureErrorAndWait(err, nil)
 					log.Error(2, "MirrorSyncCreateAction [repo_id: %d]: %v", m.RepoID, err)
@@ -517,6 +524,7 @@ func SyncMirrors() {
 	}
 }
 
+// InitSyncMirrors will init sync mirrors
 func InitSyncMirrors() {
 	go SyncMirrors()
 }

+ 2 - 2
models/mirror_test.go

@@ -26,9 +26,9 @@ From https://gitlab.com/yoginth/upsteam
  - [deleted]         (none)     -> bugfix
 `,
 				[]*mirrorSyncResult{
-					{"develop", GIT_SHORT_EMPTY_SHA, ""},
+					{"develop", GitShortEmptySHA, ""},
 					{"master", "b0bb24f", "1d85a4f"},
-					{"bugfix", "", GIT_SHORT_EMPTY_SHA},
+					{"bugfix", "", GitShortEmptySHA},
 				},
 			},
 		}

+ 31 - 12
models/models.go

@@ -17,14 +17,19 @@ import (
 	"path"
 	"strings"
 
-	"github.com/Unknwon/com"
+	// Needed for the MSSSQL driver
 	_ "github.com/denisenkom/go-mssqldb"
 	raven "github.com/getsentry/raven-go"
+
+	// Needed for the MySSQL driver
 	_ "github.com/go-sql-driver/mysql"
 	"github.com/go-xorm/core"
 	"github.com/go-xorm/xorm"
 	"github.com/json-iterator/go"
+
+	// Needed for the PostgreSQL driver
 	_ "github.com/lib/pq"
+	"gitlab.com/gitote/com"
 	log "gopkg.in/clog.v1"
 )
 
@@ -45,14 +50,18 @@ type Engine interface {
 }
 
 var (
-	x         *xorm.Engine
-	tables    []interface{}
+	x      *xorm.Engine
+	tables []interface{}
+
+	// HasEngine specifies if we have a xorm.Engine
 	HasEngine bool
 
+	// DbCfg holds the database settings
 	DbCfg struct {
 		Type, Host, Name, User, Passwd, Path, SSLMode string
 	}
 
+	// EnableSQLite3 use SQLite3
 	EnableSQLite3 bool
 )
 
@@ -74,6 +83,7 @@ func init() {
 	}
 }
 
+// LoadConfigs loads the database settings
 func LoadConfigs() {
 	sec := setting.Cfg.Section("database")
 	DbCfg.Type = sec.Key("DB_TYPE").String()
@@ -128,7 +138,7 @@ func parseMSSQLHostPort(info string) (string, string) {
 
 func getEngine() (*xorm.Engine, error) {
 	connStr := ""
-	var Param string = "?"
+	var Param = "?"
 	if strings.Contains(DbCfg.Name, Param) {
 		Param = "&"
 	}
@@ -157,7 +167,7 @@ func getEngine() (*xorm.Engine, error) {
 		connStr = fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;", host, port, DbCfg.Name, DbCfg.User, DbCfg.Passwd)
 	case "sqlite3":
 		if !EnableSQLite3 {
-			return nil, errors.New("This binary version does not build support for SQLite3.")
+			return nil, errors.New("this binary version does not build support for sqlite3")
 		}
 		if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {
 			return nil, fmt.Errorf("Fail to create directories: %v", err)
@@ -169,6 +179,7 @@ func getEngine() (*xorm.Engine, error) {
 	return xorm.NewEngine(DbCfg.Type, connStr)
 }
 
+// NewTestEngine sets a new test xorm.Engine
 func NewTestEngine(x *xorm.Engine) (err error) {
 	x, err = getEngine()
 	if err != nil {
@@ -179,6 +190,7 @@ func NewTestEngine(x *xorm.Engine) (err error) {
 	return x.StoreEngine("InnoDB").Sync2(tables...)
 }
 
+// SetEngine sets the xorm.Engine
 func SetEngine() (err error) {
 	x, err = getEngine()
 	if err != nil {
@@ -210,18 +222,20 @@ func SetEngine() (err error) {
 	return nil
 }
 
+// NewEngine initializes a new xorm.Engine
 func NewEngine() (err error) {
 	if err = SetEngine(); err != nil {
 		return err
 	}
 
 	if err = x.StoreEngine("InnoDB").Sync2(tables...); err != nil {
-		return fmt.Errorf("sync database struct error: %v\n", err)
+		return fmt.Errorf("sync database struct error: %v", err)
 	}
 
 	return nil
 }
 
+// Statistic contains the database statistics
 type Statistic struct {
 	Counter struct {
 		User, Org, PublicKey,
@@ -233,6 +247,7 @@ type Statistic struct {
 	}
 }
 
+// GetStatistic returns the database statistics
 func GetStatistic() (stats Statistic) {
 	stats.Counter.User = CountUsers()
 	stats.Counter.Org = CountOrganizations()
@@ -258,11 +273,15 @@ func GetStatistic() (stats Statistic) {
 	return
 }
 
+// Ping tests if database is alive
 func Ping() error {
-	return x.Ping()
+	if x != nil {
+		return x.Ping()
+	}
+	return errors.New("database not configured")
 }
 
-// The version table. Should have only one row with id==1
+// Version The version table. Should have only one row with id==1
 type Version struct {
 	ID      int64
 	Version int64
@@ -337,13 +356,13 @@ func ImportDatabase(dirPath string, verbose bool) (err error) {
 
 				tp := LoginType(com.StrTo(com.ToStr(meta["Type"])).MustInt64())
 				switch tp {
-				case LOGIN_LDAP, LOGIN_DLDAP:
+				case LoginLDAP, LoginDLDAP:
 					bean.Cfg = new(LDAPConfig)
-				case LOGIN_SMTP:
+				case LoginSMTP:
 					bean.Cfg = new(SMTPConfig)
-				case LOGIN_PAM:
+				case LoginPAM:
 					bean.Cfg = new(PAMConfig)
-				case LOGIN_GITHUB:
+				case LoginGitHub:
 					bean.Cfg = new(GitHubConfig)
 				default:
 					return fmt.Errorf("unrecognized login source type:: %v", tp)

+ 17 - 16
models/org.go

@@ -17,6 +17,7 @@ import (
 )
 
 var (
+	// ErrOrgNotExist displays error.
 	ErrOrgNotExist = errors.New("Organization does not exist")
 )
 
@@ -34,13 +35,13 @@ func (org *User) getTeam(e Engine, name string) (*Team, error) {
 	return getTeamOfOrgByName(e, org.ID, name)
 }
 
-// GetTeamOfOrgByName returns named team of organization.
+// GetTeam returns named team of organization.
 func (org *User) GetTeam(name string) (*Team, error) {
 	return org.getTeam(x, name)
 }
 
 func (org *User) getOwnerTeam(e Engine) (*Team, error) {
-	return org.getTeam(e, OWNER_TEAM)
+	return org.getTeam(e, ownerTeamName)
 }
 
 // GetOwnerTeam returns owner team of organization.
@@ -72,7 +73,7 @@ func (org *User) GetMembers() error {
 
 	org.Members = make([]*User, len(ous))
 	for i, ou := range ous {
-		org.Members[i], err = GetUserByID(ou.Uid)
+		org.Members[i], err = GetUserByID(ou.UID)
 		if err != nil {
 			return err
 		}
@@ -137,7 +138,7 @@ func CreateOrganization(org, owner *User) (err error) {
 
 	// Add initial creator to organization and owner team.
 	if _, err = sess.Insert(&OrgUser{
-		Uid:      owner.ID,
+		UID:      owner.ID,
 		OrgID:    org.ID,
 		IsOwner:  true,
 		NumTeams: 1,
@@ -148,9 +149,9 @@ func CreateOrganization(org, owner *User) (err error) {
 	// Create default owner team.
 	t := &Team{
 		OrgID:      org.ID,
-		LowerName:  strings.ToLower(OWNER_TEAM),
-		Name:       OWNER_TEAM,
-		Authorize:  ACCESS_MODE_OWNER,
+		LowerName:  strings.ToLower(ownerTeamName),
+		Name:       ownerTeamName,
+		Authorize:  AccessModeOwner,
 		NumMembers: 1,
 	}
 	if _, err = sess.Insert(t); err != nil {
@@ -179,7 +180,7 @@ func GetOrgByName(name string) (*User, error) {
 	}
 	u := &User{
 		LowerName: strings.ToLower(name),
-		Type:      USER_TYPE_ORGANIZATION,
+		Type:      UserTypeOrganization,
 	}
 	has, err := x.Get(u)
 	if err != nil {
@@ -232,7 +233,7 @@ func DeleteOrganization(org *User) (err error) {
 // OrgUser represents an organization-user relation.
 type OrgUser struct {
 	ID       int64
-	Uid      int64 `xorm:"INDEX UNIQUE(s)"`
+	UID      int64 `xorm:"INDEX UNIQUE(s)"`
 	OrgID    int64 `xorm:"INDEX UNIQUE(s)"`
 	IsPublic bool
 	IsOwner  bool
@@ -246,14 +247,14 @@ func IsOrganizationOwner(orgID, userID int64) bool {
 }
 
 // IsOrganizationMember returns true if given user is member of organization.
-func IsOrganizationMember(orgId, uid int64) bool {
-	has, _ := x.Where("uid=?", uid).And("org_id=?", orgId).Get(new(OrgUser))
+func IsOrganizationMember(orgID, uid int64) bool {
+	has, _ := x.Where("uid=?", uid).And("org_id=?", orgID).Get(new(OrgUser))
 	return has
 }
 
 // IsPublicMembership returns true if given user public his/her membership.
-func IsPublicMembership(orgId, uid int64) bool {
-	has, _ := x.Where("uid=?", uid).And("org_id=?", orgId).And("is_public=?", true).Get(new(OrgUser))
+func IsPublicMembership(orgID, uid int64) bool {
+	has, _ := x.Where("uid=?", uid).And("org_id=?", orgID).And("is_public=?", true).Get(new(OrgUser))
 	return has
 }
 
@@ -290,7 +291,7 @@ func GetOwnedOrgsByUserID(userID int64) ([]*User, error) {
 	return getOwnedOrgsByUserID(sess, userID)
 }
 
-// GetOwnedOrganizationsByUserIDDesc returns a list of organizations are owned by
+// GetOwnedOrgsByUserIDDesc returns a list of organizations are owned by
 // given user ID, ordered descending by the given condition.
 func GetOwnedOrgsByUserIDDesc(userID int64, desc string) ([]*User, error) {
 	sess := x.NewSession()
@@ -346,7 +347,7 @@ func AddOrgUser(orgID, uid int64) error {
 	}
 
 	ou := &OrgUser{
-		Uid:   uid,
+		UID:   uid,
 		OrgID: orgID,
 	}
 
@@ -474,7 +475,7 @@ func (org *User) GetUserTeamIDs(userID int64) ([]int64, error) {
 	return teamIDs, nil
 }
 
-// GetTeams returns all teams that belong to organization,
+// GetUserTeams returns all teams that belong to organization,
 // and that the user has joined.
 func (org *User) GetUserTeams(userID int64) ([]*Team, error) {
 	return org.getUserTeams(x, userID)

+ 6 - 5
models/org_team.go

@@ -14,7 +14,7 @@ import (
 	"github.com/go-xorm/xorm"
 )
 
-const OWNER_TEAM = "Owners"
+const ownerTeamName = "Owners"
 
 // Team represents a organization team.
 type Team struct {
@@ -30,6 +30,7 @@ type Team struct {
 	NumMembers  int
 }
 
+// AfterSet is invoked from XORM after setting the values of all fields of this object.
 func (t *Team) AfterSet(colName string, _ xorm.Cell) {
 	switch colName {
 	case "num_repos":
@@ -41,15 +42,15 @@ func (t *Team) AfterSet(colName string, _ xorm.Cell) {
 
 // IsOwnerTeam returns true if team is owner team.
 func (t *Team) IsOwnerTeam() bool {
-	return t.Name == OWNER_TEAM
+	return t.Name == ownerTeamName
 }
 
 // HasWriteAccess returns true if team has at least write level access mode.
 func (t *Team) HasWriteAccess() bool {
-	return t.Authorize >= ACCESS_MODE_WRITE
+	return t.Authorize >= AccessModeWrite
 }
 
-// IsTeamMember returns true if given user is a member of team.
+// IsMember returns true if given user is a member of team.
 func (t *Team) IsMember(userID int64) bool {
 	return IsTeamMember(t.OrgID, t.ID, userID)
 }
@@ -173,7 +174,7 @@ func (t *Team) removeRepository(e Engine, repo *Repository, recalculate bool) (e
 		return fmt.Errorf("get team members: %v", err)
 	}
 	for _, member := range t.Members {
-		has, err := hasAccess(e, member.ID, repo, ACCESS_MODE_READ)
+		has, err := hasAccess(e, member.ID, repo, AccessModeRead)
 		if err != nil {
 			return err
 		} else if has {

+ 66 - 57
models/pull.go

@@ -17,50 +17,50 @@ import (
 	"strings"
 	"time"
 
-	"github.com/Unknwon/com"
 	raven "github.com/getsentry/raven-go"
 	"github.com/go-xorm/xorm"
+	"gitlab.com/gitote/com"
 	"gitlab.com/gitote/git-module"
 	api "gitlab.com/gitote/go-gitote-client"
 	log "gopkg.in/clog.v1"
 )
 
-var PullRequestQueue = sync.NewUniqueQueue(setting.Repository.PullRequestQueueLength)
+var pullRequestQueue = sync.NewUniqueQueue(setting.Repository.PullRequestQueueLength)
 
+// PullRequestType defines pull request type
 type PullRequestType int
 
+// Enumerate all the pull request types
 const (
-	PULL_REQUEST_GITOTE PullRequestType = iota
-	PLLL_ERQUEST_GIT
+	PullRequestGitote PullRequestType = iota
 )
 
+// PullRequestStatus defines pull request status
 type PullRequestStatus int
 
+// Enumerate all the pull request status
 const (
-	PULL_REQUEST_STATUS_CONFLICT PullRequestStatus = iota
-	PULL_REQUEST_STATUS_CHECKING
-	PULL_REQUEST_STATUS_MERGEABLE
+	PullRequestStatusConflict PullRequestStatus = iota
+	PullRequestStatusChecking
+	PullRequestStatusMergeable
 )
 
 // PullRequest represents relation between pull request and repositories.
 type PullRequest struct {
-	ID     int64
-	Type   PullRequestType
-	Status PullRequestStatus
-
-	IssueID int64  `xorm:"INDEX"`
-	Issue   *Issue `xorm:"-" json:"-"`
-	Index   int64
-
-	HeadRepoID   int64
-	HeadRepo     *Repository `xorm:"-" json:"-"`
-	BaseRepoID   int64
-	BaseRepo     *Repository `xorm:"-" json:"-"`
-	HeadUserName string
-	HeadBranch   string
-	BaseBranch   string
-	MergeBase    string `xorm:"VARCHAR(40)"`
-
+	ID             int64
+	Type           PullRequestType
+	Status         PullRequestStatus
+	IssueID        int64  `xorm:"INDEX"`
+	Issue          *Issue `xorm:"-" json:"-"`
+	Index          int64
+	HeadRepoID     int64
+	HeadRepo       *Repository `xorm:"-" json:"-"`
+	BaseRepoID     int64
+	BaseRepo       *Repository `xorm:"-" json:"-"`
+	HeadUserName   string
+	HeadBranch     string
+	BaseBranch     string
+	MergeBase      string `xorm:"VARCHAR(40)"`
 	HasMerged      bool
 	MergedCommitID string `xorm:"VARCHAR(40)"`
 	MergerID       int64
@@ -69,11 +69,12 @@ type PullRequest struct {
 	MergedUnix     int64
 }
 
+// BeforeUpdate is invoked from XORM before updating this object.
 func (pr *PullRequest) BeforeUpdate() {
 	pr.MergedUnix = pr.Merged.Unix()
 }
 
-// Note: don't try to get Issue because will end up recursive querying.
+// AfterSet is invoked from XORM after setting the values of all fields of this object.
 func (pr *PullRequest) AfterSet(colName string, _ xorm.Cell) {
 	switch colName {
 	case "merged_unix":
@@ -114,10 +115,12 @@ func (pr *PullRequest) loadAttributes(e Engine) (err error) {
 	return nil
 }
 
+// LoadAttributes loads pull request attributes from database
 func (pr *PullRequest) LoadAttributes() error {
 	return pr.loadAttributes(x)
 }
 
+// LoadIssue loads issue information from database
 func (pr *PullRequest) LoadIssue() (err error) {
 	if pr.Issue != nil {
 		return nil
@@ -127,7 +130,7 @@ func (pr *PullRequest) LoadIssue() (err error) {
 	return err
 }
 
-// This method assumes following fields have been assigned with valid values:
+// APIFormat This method assumes following fields have been assigned with valid values:
 // Required - Issue, BaseRepo
 // Optional - HeadRepo, Merger
 func (pr *PullRequest) APIFormat() *api.PullRequest {
@@ -161,8 +164,8 @@ func (pr *PullRequest) APIFormat() *api.PullRequest {
 		HasMerged:  pr.HasMerged,
 	}
 
-	if pr.Status != PULL_REQUEST_STATUS_CHECKING {
-		mergeable := pr.Status != PULL_REQUEST_STATUS_CONFLICT
+	if pr.Status != PullRequestStatusChecking {
+		mergeable := pr.Status != PullRequestStatusConflict
 		apiPullRequest.Mergeable = &mergeable
 	}
 	if pr.HasMerged {
@@ -176,20 +179,22 @@ func (pr *PullRequest) APIFormat() *api.PullRequest {
 
 // IsChecking returns true if this pull request is still checking conflict.
 func (pr *PullRequest) IsChecking() bool {
-	return pr.Status == PULL_REQUEST_STATUS_CHECKING
+	return pr.Status == PullRequestStatusChecking
 }
 
 // CanAutoMerge returns true if this pull request can be merged automatically.
 func (pr *PullRequest) CanAutoMerge() bool {
-	return pr.Status == PULL_REQUEST_STATUS_MERGEABLE
+	return pr.Status == PullRequestStatusMergeable
 }
 
 // MergeStyle represents the approach to merge commits into base branch.
 type MergeStyle string
 
 const (
-	MERGE_STYLE_REGULAR MergeStyle = "create_merge_commit"
-	MERGE_STYLE_REBASE  MergeStyle = "rebase_before_merging"
+	// MergeStyleRegular create merge commit
+	MergeStyleRegular MergeStyle = "create_merge_commit"
+	// MergeStyleRebase rebase before merging
+	MergeStyleRebase MergeStyle = "rebase_before_merging"
 )
 
 // Merge merges pull request to base repository.
@@ -248,12 +253,12 @@ func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository, mergeStyle
 	remoteHeadBranch := "head_repo/" + pr.HeadBranch
 
 	// Check if merge style is allowed, reset to default style if not
-	if mergeStyle == MERGE_STYLE_REBASE && !pr.BaseRepo.PullsAllowRebase {
-		mergeStyle = MERGE_STYLE_REGULAR
+	if mergeStyle == MergeStyleRebase && !pr.BaseRepo.PullsAllowRebase {
+		mergeStyle = MergeStyleRegular
 	}
 
 	switch mergeStyle {
-	case MERGE_STYLE_REGULAR: // Create merge commit
+	case MergeStyleRegular: // Create merge commit
 
 		// Merge changes from head branch.
 		if _, stderr, err = process.ExecDir(-1, tmpBasePath,
@@ -272,7 +277,7 @@ func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository, mergeStyle
 			return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, stderr)
 		}
 
-	case MERGE_STYLE_REBASE: // Rebase before merging
+	case MergeStyleRebase: // Rebase before merging
 
 		// Rebase head branch based on base branch, this creates a non-branch commit state.
 		if _, stderr, err = process.ExecDir(-1, tmpBasePath,
@@ -341,7 +346,7 @@ func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository, mergeStyle
 		log.Error(2, "LoadAttributes: %v", err)
 		return nil
 	}
-	if err = PrepareWebhooks(pr.Issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{
+	if err = PrepareWebhooks(pr.Issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
 		Action:      api.HOOK_ISSUE_CLOSED,
 		Index:       pr.Index,
 		PullRequest: pr.APIFormat(),
@@ -369,14 +374,14 @@ func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository, mergeStyle
 		log.Error(2, "GetBranchCommit: %v", err)
 		return nil
 	}
-	if mergeStyle == MERGE_STYLE_REGULAR {
+	if mergeStyle == MergeStyleRegular {
 		l.PushFront(mergeCommit)
 	}
 
-	commits, err := ListToPushCommits(l).ToApiPayloadCommits(pr.BaseRepo.RepoPath(), pr.BaseRepo.HTMLURL())
+	commits, err := ListToPushCommits(l).ToAPIPayloadCommits(pr.BaseRepo.RepoPath(), pr.BaseRepo.HTMLURL())
 	if err != nil {
 		raven.CaptureErrorAndWait(err, nil)
-		log.Error(2, "ToApiPayloadCommits: %v", err)
+		log.Error(2, "ToAPIPayloadCommits: %v", err)
 		return nil
 	}
 
@@ -390,7 +395,7 @@ func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository, mergeStyle
 		Pusher:     pr.HeadRepo.MustOwner().APIFormat(),
 		Sender:     doer.APIFormat(),
 	}
-	if err = PrepareWebhooks(pr.BaseRepo, HOOK_EVENT_PUSH, p); err != nil {
+	if err = PrepareWebhooks(pr.BaseRepo, HookEventPush, p); err != nil {
 		raven.CaptureErrorAndWait(err, nil)
 		log.Error(2, "PrepareWebhooks: %v", err)
 		return nil
@@ -434,13 +439,13 @@ func (pr *PullRequest) testPatch() (err error) {
 	}
 	args = append(args, patchPath)
 
-	pr.Status = PULL_REQUEST_STATUS_CHECKING
+	pr.Status = PullRequestStatusChecking
 	_, stderr, err := process.ExecDir(-1, pr.BaseRepo.LocalCopyPath(),
 		fmt.Sprintf("testPatch (git apply --check): %d", pr.BaseRepo.ID),
 		"git", args...)
 	if err != nil {
 		log.Trace("PullRequest[%d].testPatch (apply): has conflict\n%s", pr.ID, stderr)
-		pr.Status = PULL_REQUEST_STATUS_CONFLICT
+		pr.Status = PullRequestStatusConflict
 		return nil
 	}
 	return nil
@@ -474,8 +479,8 @@ func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []str
 		return fmt.Errorf("testPatch: %v", err)
 	}
 	// No conflict appears after test means mergeable.
-	if pr.Status == PULL_REQUEST_STATUS_CHECKING {
-		pr.Status = PULL_REQUEST_STATUS_MERGEABLE
+	if pr.Status == PullRequestStatusChecking {
+		pr.Status = PullRequestStatusMergeable
 	}
 
 	pr.IssueID = pull.ID
@@ -490,7 +495,7 @@ func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []str
 	if err = NotifyWatchers(&Action{
 		ActUserID:    pull.Poster.ID,
 		ActUserName:  pull.Poster.Name,
-		OpType:       ACTION_CREATE_PULL_REQUEST,
+		OpType:       ActionCreatePullRequest,
 		Content:      fmt.Sprintf("%d|%s", pull.Index, pull.Title),
 		RepoID:       repo.ID,
 		RepoUserName: repo.Owner.Name,
@@ -507,7 +512,7 @@ func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []str
 
 	pr.Issue = pull
 	pull.PullRequest = pr
-	if err = PrepareWebhooks(repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{
+	if err = PrepareWebhooks(repo, HookEventPullRequest, &api.PullRequestPayload{
 		Action:      api.HOOK_ISSUE_OPENED,
 		Index:       pull.Index,
 		PullRequest: pr.APIFormat(),
@@ -595,7 +600,7 @@ func (pr *PullRequest) Update() error {
 	return err
 }
 
-// Update updates specific fields of pull request.
+// UpdateCols updates specific fields of pull request.
 func (pr *PullRequest) UpdateCols(cols ...string) error {
 	_, err := x.Id(pr.ID).Cols(cols...).Update(pr)
 	return err
@@ -674,8 +679,8 @@ func (pr *PullRequest) PushToBaseRepo() (err error) {
 
 // AddToTaskQueue adds itself to pull request test task queue.
 func (pr *PullRequest) AddToTaskQueue() {
-	go PullRequestQueue.AddFunc(pr.ID, func() {
-		pr.Status = PULL_REQUEST_STATUS_CHECKING
+	go pullRequestQueue.AddFunc(pr.ID, func() {
+		pr.Status = PullRequestStatusChecking
 		if err := pr.UpdateCols("status"); err != nil {
 			raven.CaptureErrorAndWait(err, nil)
 			log.Error(3, "AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
@@ -683,6 +688,7 @@ func (pr *PullRequest) AddToTaskQueue() {
 	})
 }
 
+// PullRequestList defines a list of pull requests
 type PullRequestList []*PullRequest
 
 func (prs PullRequestList) loadAttributes(e Engine) (err error) {
@@ -720,6 +726,7 @@ func (prs PullRequestList) loadAttributes(e Engine) (err error) {
 	return nil
 }
 
+// LoadAttributes load all the prs attributes
 func (prs PullRequestList) LoadAttributes() error {
 	return prs.loadAttributes(x)
 }
@@ -766,7 +773,7 @@ func AddTestPullRequestTask(doer *User, repoID int64, branch string, isSync bool
 					log.Error(2, "LoadAttributes: %v", err)
 					continue
 				}
-				if err = PrepareWebhooks(pr.Issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{
+				if err = PrepareWebhooks(pr.Issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
 					Action:      api.HOOK_ISSUE_SYNCHRONIZED,
 					Index:       pr.Issue.Index,
 					PullRequest: pr.Issue.PullRequest.APIFormat(),
@@ -795,6 +802,7 @@ func AddTestPullRequestTask(doer *User, repoID int64, branch string, isSync bool
 	}
 }
 
+// ChangeUsernameInPullRequests changes the name of head_user_name
 func ChangeUsernameInPullRequests(oldUserName, newUserName string) error {
 	pr := PullRequest{
 		HeadUserName: strings.ToLower(newUserName),
@@ -807,12 +815,12 @@ func ChangeUsernameInPullRequests(oldUserName, newUserName string) error {
 // and set to be either conflict or mergeable.
 func (pr *PullRequest) checkAndUpdateStatus() {
 	// Status is not changed to conflict means mergeable.
-	if pr.Status == PULL_REQUEST_STATUS_CHECKING {
-		pr.Status = PULL_REQUEST_STATUS_MERGEABLE
+	if pr.Status == PullRequestStatusChecking {
+		pr.Status = PullRequestStatusMergeable
 	}
 
 	// Make sure there is no waiting test to process before levaing the checking status.
-	if !PullRequestQueue.Exist(pr.ID) {
+	if !pullRequestQueue.Exist(pr.ID) {
 		if err := pr.UpdateCols("status"); err != nil {
 			raven.CaptureErrorAndWait(err, nil)
 			log.Error(4, "Update[%d]: %v", pr.ID, err)
@@ -825,7 +833,7 @@ func (pr *PullRequest) checkAndUpdateStatus() {
 func TestPullRequests() {
 	prs := make([]*PullRequest, 0, 10)
 	x.Iterate(PullRequest{
-		Status: PULL_REQUEST_STATUS_CHECKING,
+		Status: PullRequestStatusChecking,
 	},
 		func(idx int, bean interface{}) error {
 			pr := bean.(*PullRequest)
@@ -851,9 +859,9 @@ func TestPullRequests() {
 	}
 
 	// Start listening on new test requests.
-	for prID := range PullRequestQueue.Queue() {
+	for prID := range pullRequestQueue.Queue() {
 		log.Trace("TestPullRequests[%v]: processing test task", prID)
-		PullRequestQueue.Remove(prID)
+		pullRequestQueue.Remove(prID)
 
 		pr, err := GetPullRequestByID(com.StrTo(prID).MustInt64())
 		if err != nil {
@@ -870,6 +878,7 @@ func TestPullRequests() {
 	}
 }
 
+// InitTestPullRequests runs the task to test all the checking status pull requests
 func InitTestPullRequests() {
 	go TestPullRequests()
 }

+ 5 - 2
models/release.go

@@ -45,12 +45,14 @@ type Release struct {
 	Attachments []*Attachment `xorm:"-" json:"-"`
 }
 
+// BeforeInsert will be invoked by XORM before inserting a record
 func (r *Release) BeforeInsert() {
 	if r.CreatedUnix == 0 {
 		r.CreatedUnix = time.Now().Unix()
 	}
 }
 
+// AfterSet is invoked from XORM after setting the values of all fields of this object.
 func (r *Release) AfterSet(colName string, _ xorm.Cell) {
 	switch colName {
 	case "created_unix":
@@ -88,11 +90,12 @@ func (r *Release) loadAttributes(e Engine) (err error) {
 	return nil
 }
 
+// LoadAttributes load repo and publisher attributes for a release
 func (r *Release) LoadAttributes() error {
 	return r.loadAttributes(x)
 }
 
-// This method assumes some fields assigned with values:
+// APIFormat This method assumes some fields assigned with values:
 // Required - Publisher
 func (r *Release) APIFormat() *api.Release {
 	return &api.Release{
@@ -151,7 +154,7 @@ func createTag(gitRepo *git.Repository, r *Release) error {
 }
 
 func (r *Release) preparePublishWebhooks() {
-	if err := PrepareWebhooks(r.Repo, HOOK_EVENT_RELEASE, &api.ReleasePayload{
+	if err := PrepareWebhooks(r.Repo, HookEventRelease, &api.ReleasePayload{
 		Action:     api.HOOK_RELEASE_PUBLISHED,
 		Release:    r.APIFormat(),
 		Repository: r.Repo.APIFormat(nil),

+ 73 - 45
models/repo.go

@@ -28,11 +28,11 @@ import (
 	"strings"
 	"time"
 
-	"github.com/Unknwon/com"
 	raven "github.com/getsentry/raven-go"
 	"github.com/go-xorm/xorm"
 	"github.com/mcuadros/go-version"
 	"github.com/nfnt/resize"
+	"gitlab.com/gitote/com"
 	git "gitlab.com/gitote/git-module"
 	api "gitlab.com/gitote/go-gitote-client"
 	"gitlab.com/yoginth/cae/zip"
@@ -40,18 +40,29 @@ import (
 	"gopkg.in/ini.v1"
 )
 
-// REPO_AVATAR_URL_PREFIX is used to identify a URL is to access repository avatar.
-const REPO_AVATAR_URL_PREFIX = "repo-avatars"
+// RepoAvatarURLPrefix is used to identify a URL is to access repository avatar.
+const RepoAvatarURLPrefix = "repo-avatars"
 
 var repoWorkingPool = sync.NewExclusivePool()
 
 var (
-	Gitignores, Licenses, Readmes, LabelTemplates []string
+	// Gitignores contains the gitiginore files
+	Gitignores []string
 
-	// Maximum items per page in forks, watchers and stars of a repo
+	// Licenses contains the license files
+	Licenses []string
+
+	// Readmes contains the readme files
+	Readmes []string
+
+	// LabelTemplates contains the label template files
+	LabelTemplates []string
+
+	// ItemsPerPage maximum items per page in forks, watchers and stars of a repo
 	ItemsPerPage = 39
 )
 
+// LoadRepoConfig loads the repository config
 func LoadRepoConfig() {
 	// Load .gitignore and license files and readme templates.
 	types := []string{"gitignore", "license", "readme", "label"}
@@ -103,6 +114,7 @@ func LoadRepoConfig() {
 	Licenses = sortedLicenses
 }
 
+// NewRepoContext creates a new repository context
 func NewRepoContext() {
 	zip.Verbose = false
 
@@ -170,6 +182,7 @@ type Repository struct {
 	DefaultBranch   string
 	Size            int64 `xorm:"NOT NULL DEFAULT 0"`
 	UseCustomAvatar bool
+	IsVerified      bool
 
 	// Counters
 	NumWatches          int
@@ -218,15 +231,18 @@ type Repository struct {
 	UpdatedUnix int64
 }
 
+// BeforeInsert will be invoked by XORM before inserting a record
 func (repo *Repository) BeforeInsert() {
 	repo.CreatedUnix = time.Now().Unix()
 	repo.UpdatedUnix = repo.CreatedUnix
 }
 
+// BeforeUpdate is invoked from XORM before updating this object.
 func (repo *Repository) BeforeUpdate() {
 	repo.UpdatedUnix = time.Now().Unix()
 }
 
+// AfterSet is invoked from XORM after setting the values of all fields of this object.
 func (repo *Repository) AfterSet(colName string, _ xorm.Cell) {
 	switch colName {
 	case "default_branch":
@@ -242,7 +258,7 @@ func (repo *Repository) AfterSet(colName string, _ xorm.Cell) {
 		repo.NumOpenMilestones = repo.NumMilestones - repo.NumClosedMilestones
 	case "external_tracker_style":
 		if len(repo.ExternalTrackerStyle) == 0 {
-			repo.ExternalTrackerStyle = markup.ISSUE_NAME_STYLE_NUMERIC
+			repo.ExternalTrackerStyle = markup.IssueNameStyleNumeric
 		}
 	case "created_unix":
 		repo.Created = time.Unix(repo.CreatedUnix, 0).Local()
@@ -274,6 +290,7 @@ func (repo *Repository) loadAttributes(e Engine) (err error) {
 	return nil
 }
 
+// LoadAttributes loads attributes from database
 func (repo *Repository) LoadAttributes() error {
 	return repo.loadAttributes(x)
 }
@@ -283,10 +300,12 @@ func (repo *Repository) IsPartialPublic() bool {
 	return !repo.IsPrivate || repo.AllowPublicWiki || repo.AllowPublicIssues
 }
 
+// CanGuestViewWiki returns true if wiki is public or allow public access to wiki or issues.
 func (repo *Repository) CanGuestViewWiki() bool {
 	return repo.EnableWiki && !repo.EnableExternalWiki && repo.AllowPublicWiki
 }
 
+// CanGuestViewIssues returns true if issues is public or allow public access to wiki or issues.
 func (repo *Repository) CanGuestViewIssues() bool {
 	return repo.EnableIssues && !repo.EnableExternalTracker && repo.AllowPublicIssues
 }
@@ -297,10 +316,12 @@ func (repo *Repository) MustOwner() *User {
 	return repo.mustOwner(x)
 }
 
+// FullName returns the repository full name
 func (repo *Repository) FullName() string {
 	return repo.MustOwner().Name + "/" + repo.Name
 }
 
+// HTMLURL returns the repository HTML URL
 func (repo *Repository) HTMLURL() string {
 	return setting.AppURL + repo.FullName()
 }
@@ -314,11 +335,11 @@ func (repo *Repository) CustomAvatarPath() string {
 // which includes app sub-url as prefix.
 // Since Gravatar support not needed here - just check for image path.
 func (repo *Repository) RelAvatarLink() string {
-	defaultImgUrl := ""
+	defaultImgURL := ""
 	if !com.IsExist(repo.CustomAvatarPath()) {
-		return defaultImgUrl
+		return defaultImgURL
 	}
-	return fmt.Sprintf("%s/%s/%d", setting.AppSubURL, REPO_AVATAR_URL_PREFIX, repo.ID)
+	return fmt.Sprintf("%s/%s/%d", setting.AppSubURL, RepoAvatarURLPrefix, repo.ID)
 }
 
 // AvatarLink returns repository avatar absolute link.
@@ -364,7 +385,7 @@ func (repo *Repository) DeleteAvatar() error {
 	return UpdateRepository(repo, false)
 }
 
-// This method assumes following fields have been assigned with valid values:
+// APIFormat This method assumes following fields have been assigned with valid values:
 // Required - BaseRepo (if fork)
 // Arguments that are allowed to be nil: permission
 func (repo *Repository) APIFormat(permission *api.Permission, user ...*User) *api.Repository {
@@ -415,6 +436,7 @@ func (repo *Repository) getOwner(e Engine) (err error) {
 	return err
 }
 
+// GetOwner returns the repository owner
 func (repo *Repository) GetOwner() error {
 	return repo.getOwner(x)
 }
@@ -430,6 +452,7 @@ func (repo *Repository) mustOwner(e Engine) *User {
 	return repo.Owner
 }
 
+// UpdateSize updates the repository size, calculating it using git.GetRepoSize
 func (repo *Repository) UpdateSize() error {
 	countObject, err := git.GetRepoSize(repo.RepoPath())
 	if err != nil {
@@ -454,10 +477,10 @@ func (repo *Repository) ComposeMetas() map[string]string {
 			"repo":   repo.Name,
 		}
 		switch repo.ExternalTrackerStyle {
-		case markup.ISSUE_NAME_STYLE_ALPHANUMERIC:
-			repo.ExternalMetas["style"] = markup.ISSUE_NAME_STYLE_ALPHANUMERIC
+		case markup.IssueNameStyleAlphaNumeric:
+			repo.ExternalMetas["style"] = markup.IssueNameStyleAlphaNumeric
 		default:
-			repo.ExternalMetas["style"] = markup.ISSUE_NAME_STYLE_NUMERIC
+			repo.ExternalMetas["style"] = markup.IssueNameStyleNumeric
 		}
 
 	}
@@ -505,7 +528,7 @@ func (repo *Repository) getUsersWithAccesMode(e Engine, mode AccessMode) (_ []*U
 
 // getAssignees returns a list of users who can be assigned to issues in this repository.
 func (repo *Repository) getAssignees(e Engine) (_ []*User, err error) {
-	return repo.getUsersWithAccesMode(e, ACCESS_MODE_READ)
+	return repo.getUsersWithAccesMode(e, AccessModeRead)
 }
 
 // GetAssignees returns all users that have read access and can be assigned to issues
@@ -521,7 +544,7 @@ func (repo *Repository) GetAssigneeByID(userID int64) (*User, error) {
 
 // GetWriters returns all users that have write access to the repository.
 func (repo *Repository) GetWriters() (_ []*User, err error) {
-	return repo.getUsersWithAccesMode(x, ACCESS_MODE_WRITE)
+	return repo.getUsersWithAccesMode(x, AccessModeWrite)
 }
 
 // GetMilestoneByID returns the milestone belongs to repository by given ID.
@@ -534,6 +557,7 @@ func (repo *Repository) IssueStats(userID int64, filterMode FilterMode, isPull b
 	return GetRepoIssueStats(repo.ID, userID, filterMode, isPull)
 }
 
+// GetMirror sets the repository mirror, returns an error upon failure
 func (repo *Repository) GetMirror() (err error) {
 	repo.Mirror, err = GetMirrorByRepoID(repo.ID)
 	return err
@@ -543,28 +567,33 @@ func (repo *Repository) repoPath(e Engine) string {
 	return RepoPath(repo.mustOwner(e).Name, repo.Name)
 }
 
+// RepoPath returns the repository path
 func (repo *Repository) RepoPath() string {
 	return repo.repoPath(x)
 }
 
+// GitConfigPath returns the path to a repository's git config/ directory
 func (repo *Repository) GitConfigPath() string {
 	return filepath.Join(repo.RepoPath(), "config")
 }
 
+// RelLink returns the repository relative link
 func (repo *Repository) RelLink() string {
 	return "/" + repo.FullName()
 }
 
+// Link returns the repository link
 func (repo *Repository) Link() string {
 	return setting.AppSubURL + "/" + repo.FullName()
 }
 
+// ComposeCompareURL returns the repository comparison URL
 func (repo *Repository) ComposeCompareURL(oldCommitID, newCommitID string) string {
 	return fmt.Sprintf("%s/%s/compare/%s...%s", repo.MustOwner().Name, repo.Name, oldCommitID, newCommitID)
 }
 
 func (repo *Repository) HasAccess(userID int64) bool {
-	has, _ := HasAccess(userID, repo, ACCESS_MODE_READ)
+	has, _ := HasAccess(userID, repo, AccessModeRead)
 	return has
 }
 
@@ -606,7 +635,7 @@ func (repo *Repository) LocalCopyPath() string {
 	return path.Join(setting.AppDataPath, "tmp/local-repo", com.ToStr(repo.ID))
 }
 
-// UpdateLocalCopy fetches latest changes of given branch from repoPath to localPath.
+// UpdateLocalCopyBranch fetches latest changes of given branch from repoPath to localPath.
 // It creates a new clone if local copy does not exist, but does not checks out to a
 // specific branch if the local copy belongs to a wiki.
 // For existing local copy, it checks out to target branch by default, and safe to
@@ -877,7 +906,8 @@ func createDelegateHooks(repoPath string) (err error) {
 	return nil
 }
 
-// Finish migrating repository and/or wiki with things that don't need to be done for mirrors.
+// CleanUpMigrateInfo Finish migrating repository and/or wiki with things that don't
+// need to be done for mirrors.
 func CleanUpMigrateInfo(repo *Repository) (*Repository, error) {
 	repoPath := repo.RepoPath()
 	if err := createDelegateHooks(repoPath); err != nil {
@@ -1194,6 +1224,7 @@ func CountUserRepositories(userID int64, private bool) int64 {
 	return countRepositories(userID, private)
 }
 
+// Repositories returns repos in given page.
 func Repositories(page, pageSize int) (_ []*Repository, err error) {
 	repos := make([]*Repository, 0, pageSize)
 	return repos, x.Limit(pageSize, (page-1)*pageSize).Asc("id").Find(&repos)
@@ -1478,6 +1509,7 @@ func updateRepository(e Engine, repo *Repository, visibilityChanged bool) (err e
 	return nil
 }
 
+// UpdateRepository updates a repository
 func UpdateRepository(repo *Repository, visibilityChanged bool) (err error) {
 	sess := x.NewSession()
 	defer sess.Close()
@@ -1683,7 +1715,7 @@ func GetUserRepositories(opts *UserRepoOptions) ([]*Repository, error) {
 	return repos, sess.Find(&repos)
 }
 
-// GetUserRepositories returns a list of mirror repositories of given user.
+// GetUserMirrorRepositories returns a list of mirror repositories of given user.
 func GetUserMirrorRepositories(userID int64) ([]*Repository, error) {
 	repos := make([]*Repository, 0, 10)
 	return repos, x.Where("owner_id = ?", userID).And("is_mirror = ?", true).Find(&repos)
@@ -1771,12 +1803,13 @@ func SearchRepositoryByName(opts *SearchRepoOptions) (repos []*Repository, count
 	return repos, count, sess.Distinct("repo.*").Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).Find(&repos)
 }
 
+// DeleteOldRepositoryArchives deletes old repository archives.
 func DeleteOldRepositoryArchives() {
-	if taskStatusTable.IsRunning(_CLEAN_OLD_ARCHIVES) {
+	if taskStatusTable.IsRunning(_CleanOldArchives) {
 		return
 	}
-	taskStatusTable.Start(_CLEAN_OLD_ARCHIVES)
-	defer taskStatusTable.Stop(_CLEAN_OLD_ARCHIVES)
+	taskStatusTable.Start(_CleanOldArchives)
+	defer taskStatusTable.Stop(_CleanOldArchives)
 
 	log.Trace("Doing: DeleteOldRepositoryArchives")
 
@@ -1833,11 +1866,11 @@ func DeleteOldRepositoryArchives() {
 
 // DeleteRepositoryArchives deletes all repositories' archives.
 func DeleteRepositoryArchives() error {
-	if taskStatusTable.IsRunning(_CLEAN_OLD_ARCHIVES) {
+	if taskStatusTable.IsRunning(_CleanOldArchives) {
 		return nil
 	}
-	taskStatusTable.Start(_CLEAN_OLD_ARCHIVES)
-	defer taskStatusTable.Stop(_CLEAN_OLD_ARCHIVES)
+	taskStatusTable.Start(_CleanOldArchives)
+	defer taskStatusTable.Stop(_CleanOldArchives)
 
 	return x.Where("id > 0").Iterate(new(Repository),
 		func(idx int, bean interface{}) error {
@@ -1928,19 +1961,19 @@ func SyncRepositoryHooks() error {
 var taskStatusTable = sync.NewStatusTable()
 
 const (
-	_MIRROR_UPDATE      = "mirror_update"
-	_GIT_FSCK           = "git_fsck"
-	_CHECK_REPO_STATS   = "check_repos_stats"
-	_CLEAN_OLD_ARCHIVES = "clean_old_archives"
+	_MirrorUpdate     = "mirror_update"
+	_GitFSCK          = "git_fsck"
+	_CheckRepoStats   = "check_repos_stats"
+	_CleanOldArchives = "clean_old_archives"
 )
 
 // GitFsck calls 'git fsck' to check repository health.
 func GitFsck() {
-	if taskStatusTable.IsRunning(_GIT_FSCK) {
+	if taskStatusTable.IsRunning(_GitFSCK) {
 		return
 	}
-	taskStatusTable.Start(_GIT_FSCK)
-	defer taskStatusTable.Stop(_GIT_FSCK)
+	taskStatusTable.Start(_GitFSCK)
+	defer taskStatusTable.Stop(_GitFSCK)
 
 	log.Trace("Doing: GitFsck")
 
@@ -1963,6 +1996,7 @@ func GitFsck() {
 	}
 }
 
+// GitGcRepos calls 'git gc' to remove unnecessary files and optimize the local repository
 func GitGcRepos() error {
 	args := append([]string{"gc"}, setting.Git.GCArgs...)
 	return x.Where("id > 0").Iterate(new(Repository),
@@ -2005,12 +2039,13 @@ func repoStatsCheck(checker *repoChecker) {
 	}
 }
 
+// CheckRepoStats checks the repository stats
 func CheckRepoStats() {
-	if taskStatusTable.IsRunning(_CHECK_REPO_STATS) {
+	if taskStatusTable.IsRunning(_CheckRepoStats) {
 		return
 	}
-	taskStatusTable.Start(_CHECK_REPO_STATS)
-	defer taskStatusTable.Stop(_CHECK_REPO_STATS)
+	taskStatusTable.Start(_CheckRepoStats)
+	defer taskStatusTable.Stop(_CheckRepoStats)
 
 	log.Trace("Doing: CheckRepoStats")
 
@@ -2236,7 +2271,7 @@ func watchRepo(e Engine, userID, repoID int64, watch bool) (err error) {
 	return err
 }
 
-// Watch or unwatch repository.
+// WatchRepo Watch or unwatch repository.
 func WatchRepo(userID, repoID int64, watch bool) (err error) {
 	return watchRepo(x, userID, repoID, watch)
 }
@@ -2298,20 +2333,13 @@ func NotifyWatchers(act *Action) error {
 	return notifyWatchers(x, act)
 }
 
-//   _________ __
-//  /   _____//  |______ _______
-//  \_____  \\   __\__  \\_  __ \
-//  /        \|  |  / __ \|  | \/
-// /_______  /|__| (____  /__|
-//         \/           \/
-
 type Star struct {
 	ID     int64
 	UID    int64 `xorm:"UNIQUE(s)"`
 	RepoID int64 `xorm:"UNIQUE(s)"`
 }
 
-// Star or unstar repository.
+// StarRepo Star or unstar repository.
 func StarRepo(userID, repoID int64, star bool) (err error) {
 	if star {
 		if IsStaring(userID, repoID) {
@@ -2433,7 +2461,7 @@ func ForkRepository(doer, owner *User, baseRepo *Repository, name, desc string)
 		raven.CaptureErrorAndWait(err, nil)
 		log.Error(2, "UpdateSize [repo_id: %d]: %v", repo.ID, err)
 	}
-	if err = PrepareWebhooks(baseRepo, HOOK_EVENT_FORK, &api.ForkPayload{
+	if err = PrepareWebhooks(baseRepo, HookEventFork, &api.ForkPayload{
 		Forkee: repo.APIFormat(nil),
 		Repo:   baseRepo.APIFormat(nil),
 		Sender: doer.APIFormat(),

+ 11 - 6
models/repo_branch.go

@@ -12,18 +12,19 @@ import (
 	"gitote/gitote/pkg/tool"
 	"strings"
 
-	"github.com/Unknwon/com"
+	"gitlab.com/gitote/com"
 	"gitlab.com/gitote/git-module"
 )
 
+// Branch holds the branch information
 type Branch struct {
-	RepoPath string
-	Name     string
-
+	RepoPath    string
+	Name        string
 	IsProtected bool
 	Commit      *git.Commit
 }
 
+// GetBranchesByPath returns a branch by it's path
 func GetBranchesByPath(path string) ([]*Branch, error) {
 	gitRepo, err := git.OpenRepository(path)
 	if err != nil {
@@ -45,6 +46,7 @@ func GetBranchesByPath(path string) ([]*Branch, error) {
 	return branches, nil
 }
 
+// GetBranch returns a branch by it's name
 func (repo *Repository) GetBranch(br string) (*Branch, error) {
 	if !git.IsBranchExist(repo.RepoPath(), br) {
 		return nil, errors.ErrBranchNotExist{br}
@@ -55,10 +57,12 @@ func (repo *Repository) GetBranch(br string) (*Branch, error) {
 	}, nil
 }
 
+// GetBranches returns all the branches of a repository
 func (repo *Repository) GetBranches() ([]*Branch, error) {
 	return GetBranchesByPath(repo.RepoPath())
 }
 
+// GetCommit returns all the commits of a branch
 func (br *Branch) GetCommit() (*git.Commit, error) {
 	gitRepo, err := git.OpenRepository(br.RepoPath)
 	if err != nil {
@@ -67,6 +71,7 @@ func (br *Branch) GetCommit() (*git.Commit, error) {
 	return gitRepo.GetBranchCommit(br.Name)
 }
 
+// ProtectBranchWhitelist holds protect information.
 type ProtectBranchWhitelist struct {
 	ID              int64
 	ProtectBranchID int64
@@ -157,7 +162,7 @@ func UpdateOrgProtectBranch(repo *Repository, protectBranch *ProtectBranch, whit
 		userIDs := tool.StringsToInt64s(strings.Split(whitelistUserIDs, ","))
 		validUserIDs = make([]int64, 0, len(userIDs))
 		for _, userID := range userIDs {
-			has, err := HasAccess(userID, repo, ACCESS_MODE_WRITE)
+			has, err := HasAccess(userID, repo, AccessModeWrite)
 			if err != nil {
 				return fmt.Errorf("HasAccess [user_id: %d, repo_id: %d]: %v", userID, protectBranch.RepoID, err)
 			} else if !has {
@@ -175,7 +180,7 @@ func UpdateOrgProtectBranch(repo *Repository, protectBranch *ProtectBranch, whit
 	if protectBranch.WhitelistTeamIDs != whitelistTeamIDs {
 		hasTeamsChanged = true
 		teamIDs := tool.StringsToInt64s(strings.Split(whitelistTeamIDs, ","))
-		teams, err := GetTeamsHaveAccessToRepo(repo.OwnerID, repo.ID, ACCESS_MODE_WRITE)
+		teams, err := GetTeamsHaveAccessToRepo(repo.OwnerID, repo.ID, AccessModeWrite)
 		if err != nil {
 			return fmt.Errorf("GetTeamsHaveAccessToRepo [org_id: %d, repo_id: %d]: %v", repo.OwnerID, repo.ID, err)
 		}

+ 12 - 8
models/repo_collaboration.go

@@ -22,13 +22,14 @@ type Collaboration struct {
 	Mode   AccessMode `xorm:"DEFAULT 2 NOT NULL"`
 }
 
+// ModeI18nKey returns the collaboration mode I18n Key
 func (c *Collaboration) ModeI18nKey() string {
 	switch c.Mode {
-	case ACCESS_MODE_READ:
+	case AccessModeRead:
 		return "repo.settings.collaboration.read"
-	case ACCESS_MODE_WRITE:
+	case AccessModeWrite:
 		return "repo.settings.collaboration.write"
-	case ACCESS_MODE_ADMIN:
+	case AccessModeAdmin:
 		return "repo.settings.collaboration.admin"
 	default:
 		return "repo.settings.collaboration.undefined"
@@ -50,6 +51,7 @@ func IsCollaborator(repoID, userID int64) bool {
 	return has
 }
 
+// IsCollaborator check if a user is a collaborator of a repository
 func (repo *Repository) IsCollaborator(userID int64) bool {
 	return IsCollaborator(repo.ID, userID)
 }
@@ -67,7 +69,7 @@ func (repo *Repository) AddCollaborator(u *User) error {
 	} else if has {
 		return nil
 	}
-	collaboration.Mode = ACCESS_MODE_WRITE
+	collaboration.Mode = AccessModeWrite
 
 	sess := x.NewSession()
 	defer sess.Close()
@@ -95,13 +97,14 @@ type Collaborator struct {
 	Collaboration *Collaboration
 }
 
+// APIFormat for colloborator
 func (c *Collaborator) APIFormat() *api.Collaborator {
 	return &api.Collaborator{
 		User: c.User.APIFormat(),
 		Permissions: api.Permission{
-			Admin: c.Collaboration.Mode >= ACCESS_MODE_ADMIN,
-			Push:  c.Collaboration.Mode >= ACCESS_MODE_WRITE,
-			Pull:  c.Collaboration.Mode >= ACCESS_MODE_READ,
+			Admin: c.Collaboration.Mode >= AccessModeAdmin,
+			Push:  c.Collaboration.Mode >= AccessModeWrite,
+			Pull:  c.Collaboration.Mode >= AccessModeRead,
 		},
 	}
 }
@@ -134,7 +137,7 @@ func (repo *Repository) GetCollaborators() ([]*Collaborator, error) {
 // ChangeCollaborationAccessMode sets new access mode for the collaboration.
 func (repo *Repository) ChangeCollaborationAccessMode(userID int64, mode AccessMode) error {
 	// Discard invalid input
-	if mode <= ACCESS_MODE_NONE || mode > ACCESS_MODE_OWNER {
+	if mode <= AccessModeNone || mode > AccessModeOwner {
 		return nil
 	}
 
@@ -224,6 +227,7 @@ func DeleteCollaboration(repo *Repository, userID int64) (err error) {
 	return sess.Commit()
 }
 
+// DeleteCollaboration removes collaboration relation between the user and repository.
 func (repo *Repository) DeleteCollaboration(userID int64) error {
 	return DeleteCollaboration(repo, userID)
 }

+ 44 - 19
models/repo_editor.go

@@ -22,22 +22,24 @@ import (
 	"strings"
 	"time"
 
-	"github.com/Unknwon/com"
 	gouuid "github.com/satori/go.uuid"
+	"gitlab.com/gitote/com"
 	"gitlab.com/gitote/git-module"
 )
 
+// Enumerate all the env variable.
 const (
-	ENV_AUTH_USER_ID           = "GITOTE_AUTH_USER_ID"
-	ENV_AUTH_USER_NAME         = "GITOTE_AUTH_USER_NAME"
-	ENV_AUTH_USER_EMAIL        = "GITOTE_AUTH_USER_EMAIL"
-	ENV_REPO_OWNER_NAME        = "GITOTE_REPO_OWNER_NAME"
-	ENV_REPO_OWNER_SALT_MD5    = "GITOTE_REPO_OWNER_SALT_MD5"
-	ENV_REPO_ID                = "GITOTE_REPO_ID"
-	ENV_REPO_NAME              = "GITOTE_REPO_NAME"
-	ENV_REPO_CUSTOM_HOOKS_PATH = "GITOTE_REPO_CUSTOM_HOOKS_PATH"
+	EnvAuthUserID         = "GITOTE_AUTH_USER_ID"
+	EnvAuthUsername       = "GITOTE_AUTH_USER_NAME"
+	EnvAuthUserEmail      = "GITOTE_AUTH_USER_EMAIL"
+	EnvRepoOwnerName      = "GITOTE_REPO_OWNER_NAME"
+	EnvRepoOwnerSlatMD5   = "GITOTE_REPO_OWNER_SALT_MD5"
+	EnvRepoID             = "GITOTE_REPO_ID"
+	EnvRepoName           = "GITOTE_REPO_NAME"
+	EnvRepoCustomHookPath = "GITOTE_REPO_CUSTOM_HOOKS_PATH"
 )
 
+// ComposeHookEnvsOptions holds hook envs.
 type ComposeHookEnvsOptions struct {
 	AuthUser  *User
 	OwnerName string
@@ -47,17 +49,18 @@ type ComposeHookEnvsOptions struct {
 	RepoPath  string
 }
 
+// ComposeHookEnvs returns the envs
 func ComposeHookEnvs(opts ComposeHookEnvsOptions) []string {
 	envs := []string{
 		"SSH_ORIGINAL_COMMAND=1",
-		ENV_AUTH_USER_ID + "=" + com.ToStr(opts.AuthUser.ID),
-		ENV_AUTH_USER_NAME + "=" + opts.AuthUser.Name,
-		ENV_AUTH_USER_EMAIL + "=" + opts.AuthUser.Email,
-		ENV_REPO_OWNER_NAME + "=" + opts.OwnerName,
-		ENV_REPO_OWNER_SALT_MD5 + "=" + tool.MD5(opts.OwnerSalt),
-		ENV_REPO_ID + "=" + com.ToStr(opts.RepoID),
-		ENV_REPO_NAME + "=" + opts.RepoName,
-		ENV_REPO_CUSTOM_HOOKS_PATH + "=" + path.Join(opts.RepoPath, "custom_hooks"),
+		EnvAuthUserID + "=" + com.ToStr(opts.AuthUser.ID),
+		EnvAuthUsername + "=" + opts.AuthUser.Name,
+		EnvAuthUserEmail + "=" + opts.AuthUser.Email,
+		EnvRepoOwnerName + "=" + opts.OwnerName,
+		EnvRepoOwnerSlatMD5 + "=" + tool.MD5(opts.OwnerSalt),
+		EnvRepoID + "=" + com.ToStr(opts.RepoID),
+		EnvRepoName + "=" + opts.RepoName,
+		EnvRepoCustomHookPath + "=" + path.Join(opts.RepoPath, "custom_hooks"),
 	}
 	return envs
 }
@@ -80,6 +83,8 @@ func discardLocalRepoBranchChanges(localPath, branch string) error {
 	return nil
 }
 
+// DiscardLocalRepoBranchChanges discards local commits/changes of
+// given branch to make sure it is even to remote branch.
 func (repo *Repository) DiscardLocalRepoBranchChanges(branch string) error {
 	return discardLocalRepoBranchChanges(repo.LocalCopyPath(), branch)
 }
@@ -96,10 +101,12 @@ func checkoutNewBranch(repoPath, localPath, oldBranch, newBranch string) error {
 	return nil
 }
 
+// CheckoutNewBranch checks out a new branch
 func (repo *Repository) CheckoutNewBranch(oldBranch, newBranch string) error {
 	return checkoutNewBranch(repo.RepoPath(), repo.LocalCopyPath(), oldBranch, newBranch)
 }
 
+// UpdateRepoFileOptions holds the repository file update options
 type UpdateRepoFileOptions struct {
 	LastCommitID string
 	OldBranch    string
@@ -235,6 +242,7 @@ func (repo *Repository) GetDiffPreview(branch, treePath, content string) (diff *
 	return diff, nil
 }
 
+// DeleteRepoFileOptions holds the repository delete file options
 type DeleteRepoFileOptions struct {
 	LastCommitID string
 	OldBranch    string
@@ -243,6 +251,7 @@ type DeleteRepoFileOptions struct {
 	Message      string
 }
 
+// DeleteRepoFile deletes a repository file
 func (repo *Repository) DeleteRepoFile(doer *User, opts DeleteRepoFileOptions) (err error) {
 	repoWorkingPool.CheckIn(com.ToStr(repo.ID))
 	defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
@@ -304,9 +313,13 @@ func (upload *Upload) LocalPath() string {
 
 // NewUpload creates a new upload object.
 func NewUpload(name string, buf []byte, file multipart.File) (_ *Upload, err error) {
+	if tool.IsMaliciousPath(name) {
+		return nil, fmt.Errorf("malicious path detected: %s", name)
+	}
+
 	upload := &Upload{
 		UUID: gouuid.NewV4().String(),
-		Name: tool.SanitizePath(name),
+		Name: name,
 	}
 
 	localPath := upload.LocalPath()
@@ -333,6 +346,7 @@ func NewUpload(name string, buf []byte, file multipart.File) (_ *Upload, err err
 	return upload, nil
 }
 
+// GetUploadByUUID returns the Upload by UUID
 func GetUploadByUUID(uuid string) (*Upload, error) {
 	upload := &Upload{UUID: uuid}
 	has, err := x.Get(upload)
@@ -344,6 +358,7 @@ func GetUploadByUUID(uuid string) (*Upload, error) {
 	return upload, nil
 }
 
+// GetUploadsByUUIDs returns multiple uploads by UUIDS
 func GetUploadsByUUIDs(uuids []string) ([]*Upload, error) {
 	if len(uuids) == 0 {
 		return []*Upload{}, nil
@@ -354,6 +369,7 @@ func GetUploadsByUUIDs(uuids []string) ([]*Upload, error) {
 	return uploads, x.In("uuid", uuids).Find(&uploads)
 }
 
+// DeleteUploads deletes multiple uploads
 func DeleteUploads(uploads ...*Upload) (err error) {
 	if len(uploads) == 0 {
 		return nil
@@ -387,10 +403,12 @@ func DeleteUploads(uploads ...*Upload) (err error) {
 	return sess.Commit()
 }
 
+// DeleteUpload delete a upload
 func DeleteUpload(u *Upload) error {
 	return DeleteUploads(u)
 }
 
+// DeleteUploadByUUID deletes a upload by UUID
 func DeleteUploadByUUID(uuid string) error {
 	upload, err := GetUploadByUUID(uuid)
 	if err != nil {
@@ -407,6 +425,7 @@ func DeleteUploadByUUID(uuid string) error {
 	return nil
 }
 
+// UploadRepoFileOptions contains the uploaded repository file options
 type UploadRepoFileOptions struct {
 	LastCommitID string
 	OldBranch    string
@@ -416,6 +435,12 @@ type UploadRepoFileOptions struct {
 	Files        []string // In UUID format
 }
 
+// isRepositoryGitPath returns true if given path is or resides inside ".git" path of the repository.
+func isRepositoryGitPath(path string) bool {
+	return strings.HasSuffix(path, ".git") || strings.Contains(path, ".git"+string(os.PathSeparator))
+}
+
+// UploadRepoFiles uploads files to a repository
 func (repo *Repository) UploadRepoFiles(doer *User, opts UploadRepoFileOptions) (err error) {
 	if len(opts.Files) == 0 {
 		return nil
@@ -453,7 +478,7 @@ func (repo *Repository) UploadRepoFiles(doer *User, opts UploadRepoFileOptions)
 		}
 
 		// Prevent copying files into .git directory
-		if strings.HasPrefix(upload.Name, ".git/") {
+		if isRepositoryGitPath(upload.Name) {
 			continue
 		}
 

+ 36 - 0
models/repo_editor_test.go

@@ -0,0 +1,36 @@
+// Copyright 2015 The Gogs Authors. All rights reserved.
+// Copyright 2018 Gitote. All rights reserved.
+//
+// This source code is licensed under the MIT license found in the
+// LICENSE file in the root directory of this source tree.
+
+package models
+
+import (
+	"os"
+	"testing"
+
+	. "github.com/smartystreets/goconvey/convey"
+)
+
+func Test_isRepositoryGitPath(t *testing.T) {
+	Convey("Check if path is or resides inside '.git'", t, func() {
+		sep := string(os.PathSeparator)
+		testCases := []struct {
+			path   string
+			expect bool
+		}{
+			{"." + sep + ".git", true},
+			{"." + sep + ".git" + sep + "", true},
+			{"." + sep + ".git" + sep + "hooks" + sep + "pre-commit", true},
+			{".git" + sep + "hooks", true},
+			{"dir" + sep + ".git", true},
+
+			{".gitignore", false},
+			{"dir" + sep + ".gitkeep", false},
+		}
+		for _, tc := range testCases {
+			So(isRepositoryGitPath(tc.path), ShouldEqual, tc.expect)
+		}
+	})
+}

+ 6 - 6
models/repo_test.go

@@ -30,7 +30,7 @@ func TestRepo(t *testing.T) {
 			Convey("It should be nil even if other settings are present", func() {
 				repo.EnableExternalTracker = false
 				repo.ExternalTrackerFormat = "http://gitlab.com/{user}/{repo}/{issue}"
-				repo.ExternalTrackerStyle = markup.ISSUE_NAME_STYLE_NUMERIC
+				repo.ExternalTrackerStyle = markup.IssueNameStyleNumeric
 				So(repo.ComposeMetas(), ShouldEqual, map[string]string(nil))
 			})
 		})
@@ -39,17 +39,17 @@ func TestRepo(t *testing.T) {
 			repo.EnableExternalTracker = true
 			Convey("It should default to numeric issue style", func() {
 				metas := repo.ComposeMetas()
-				So(metas["style"], ShouldEqual, markup.ISSUE_NAME_STYLE_NUMERIC)
+				So(metas["style"], ShouldEqual, markup.IssueNameStyleNumeric)
 			})
 			Convey("It should pass through numeric issue style setting", func() {
-				repo.ExternalTrackerStyle = markup.ISSUE_NAME_STYLE_NUMERIC
+				repo.ExternalTrackerStyle = markup.IssueNameStyleNumeric
 				metas := repo.ComposeMetas()
-				So(metas["style"], ShouldEqual, markup.ISSUE_NAME_STYLE_NUMERIC)
+				So(metas["style"], ShouldEqual, markup.IssueNameStyleNumeric)
 			})
 			Convey("It should pass through alphanumeric issue style setting", func() {
-				repo.ExternalTrackerStyle = markup.ISSUE_NAME_STYLE_ALPHANUMERIC
+				repo.ExternalTrackerStyle = markup.IssueNameStyleAlphaNumeric
 				metas := repo.ComposeMetas()
-				So(metas["style"], ShouldEqual, markup.ISSUE_NAME_STYLE_ALPHANUMERIC)
+				So(metas["style"], ShouldEqual, markup.IssueNameStyleAlphaNumeric)
 			})
 			Convey("It should contain the user name", func() {
 				metas := repo.ComposeMetas()

+ 12 - 12
models/ssh_key.go

@@ -22,15 +22,15 @@ import (
 	"sync"
 	"time"
 
-	"github.com/Unknwon/com"
 	raven "github.com/getsentry/raven-go"
 	"github.com/go-xorm/xorm"
+	"gitlab.com/gitote/com"
 	"golang.org/x/crypto/ssh"
 	log "gopkg.in/clog.v1"
 )
 
 const (
-	_TPL_PUBLICK_KEY = `command="%s serv key-%d --config='%s'",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty %s` + "\n"
+	TPLPublicKey = `command="%s serv key-%d --config='%s'",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty %s` + "\n"
 )
 
 var sshOpLocker sync.Mutex
@@ -38,8 +38,8 @@ var sshOpLocker sync.Mutex
 type KeyType int
 
 const (
-	KEY_TYPE_USER = iota + 1
-	KEY_TYPE_DEPLOY
+	KeyTypeUser = iota + 1
+	KeyTypeDeploy
 )
 
 // PublicKey represents a user or deploy SSH public key.
@@ -86,12 +86,12 @@ func (k *PublicKey) OmitEmail() string {
 
 // AuthorizedString returns formatted public key string for authorized_keys file.
 func (k *PublicKey) AuthorizedString() string {
-	return fmt.Sprintf(_TPL_PUBLICK_KEY, setting.AppPath, k.ID, setting.CustomConf, k.Content)
+	return fmt.Sprintf(TPLPublicKey, setting.AppPath, k.ID, setting.CustomConf, k.Content)
 }
 
 // IsDeployKey returns true if the public key is used as deploy key.
 func (k *PublicKey) IsDeployKey() bool {
-	return k.Type == KEY_TYPE_DEPLOY
+	return k.Type == KeyTypeDeploy
 }
 
 func extractTypeFromBase64Key(key string) (string, error) {
@@ -364,7 +364,7 @@ func appendAuthorizedKeysToFile(keys ...*PublicKey) error {
 func checkKeyContent(content string) error {
 	has, err := x.Get(&PublicKey{
 		Content: content,
-		Type:    KEY_TYPE_USER,
+		Type:    KeyTypeUser,
 	})
 	if err != nil {
 		return err
@@ -428,8 +428,8 @@ func AddPublicKey(ownerID int64, name, content string) (*PublicKey, error) {
 		OwnerID: ownerID,
 		Name:    name,
 		Content: content,
-		Mode:    ACCESS_MODE_WRITE,
-		Type:    KEY_TYPE_USER,
+		Mode:    AccessModeWrite,
+		Type:    KeyTypeUser,
 	}
 	if err = addKey(sess, key); err != nil {
 		return nil, fmt.Errorf("addKey: %v", err)
@@ -651,8 +651,8 @@ func AddDeployKey(repoID int64, name, content string) (*DeployKey, error) {
 
 	pkey := &PublicKey{
 		Content: content,
-		Mode:    ACCESS_MODE_READ,
-		Type:    KEY_TYPE_DEPLOY,
+		Mode:    AccessModeRead,
+		Type:    KeyTypeDeploy,
 	}
 	has, err := x.Get(pkey)
 	if err != nil {
@@ -729,7 +729,7 @@ func DeleteDeployKey(doer *User, id int64) error {
 		if err != nil {
 			return fmt.Errorf("GetRepositoryByID: %v", err)
 		}
-		yes, err := HasAccess(doer.ID, repo, ACCESS_MODE_ADMIN)
+		yes, err := HasAccess(doer.ID, repo, AccessModeAdmin)
 		if err != nil {
 			return fmt.Errorf("HasAccess: %v", err)
 		} else if !yes {

+ 1 - 1
models/two_factor.go

@@ -15,9 +15,9 @@ import (
 	"strings"
 	"time"
 
-	"github.com/Unknwon/com"
 	"github.com/go-xorm/xorm"
 	"github.com/pquerna/otp/totp"
+	"gitlab.com/gitote/com"
 	log "gopkg.in/clog.v1"
 )
 

+ 1 - 0
models/update.go

@@ -28,6 +28,7 @@ func CommitToPushCommit(commit *git.Commit) *PushCommit {
 	}
 }
 
+// ListToPushCommits transforms a list.List to PushCommits type.
 func ListToPushCommits(l *list.List) *PushCommits {
 	if l == nil {
 		return &PushCommits{}

+ 20 - 17
models/user.go

@@ -26,24 +26,24 @@ import (
 	"time"
 	"unicode/utf8"
 
-	"github.com/Unknwon/com"
 	raven "github.com/getsentry/raven-go"
 	"github.com/go-xorm/xorm"
 	"github.com/nfnt/resize"
+	"gitlab.com/gitote/com"
 	"gitlab.com/gitote/git-module"
 	api "gitlab.com/gitote/go-gitote-client"
 	"golang.org/x/crypto/pbkdf2"
 	log "gopkg.in/clog.v1"
 )
 
-// USER_AVATAR_URL_PREFIX is used to identify a URL is to access user avatar.
-const USER_AVATAR_URL_PREFIX = "avatars"
+// UserAvatarURLPrefix is used to identify a URL is to access user avatar.
+const UserAvatarURLPrefix = "avatars"
 
 type UserType int
 
 const (
-	USER_TYPE_INDIVIDUAL UserType = iota // Historic reason to make it starts at 0.
-	USER_TYPE_ORGANIZATION
+	UserTypeIndividual UserType = iota // Historic reason to make it starts at 0.
+	UserTypeOrganization
 )
 
 // User represents the object of individual and member of organization.
@@ -102,7 +102,7 @@ type User struct {
 	Twitter       string
 	Linkedin      string
 	Github        string
-	Devto         string
+	Makerlog      string
 	Stackoverflow string
 	Reddit        string
 	Telegram      string
@@ -185,9 +185,9 @@ func (u *User) APIFormat() *api.User {
 	}
 }
 
-// returns true if user login type is LOGIN_PLAIN.
+// returns true if user login type is LoginPlain.
 func (u *User) IsLocal() bool {
-	return u.LoginType <= LOGIN_PLAIN
+	return u.LoginType <= LoginPlain
 }
 
 // HasForkedRepo checks if user has already forked a repository with given ID.
@@ -307,7 +307,7 @@ func (u *User) RelAvatarLink() string {
 		if !com.IsExist(u.CustomAvatarPath()) {
 			return defaultImgUrl
 		}
-		return fmt.Sprintf("%s/%s/%d", setting.AppSubURL, USER_AVATAR_URL_PREFIX, u.ID)
+		return fmt.Sprintf("%s/%s/%d", setting.AppSubURL, UserAvatarURLPrefix, u.ID)
 	case setting.DisableGravatar, setting.OfflineMode:
 		if !com.IsExist(u.CustomAvatarPath()) {
 			if err := u.GenerateRandomAvatar(); err != nil {
@@ -316,7 +316,7 @@ func (u *User) RelAvatarLink() string {
 			}
 		}
 
-		return fmt.Sprintf("%s/%s/%d", setting.AppSubURL, USER_AVATAR_URL_PREFIX, u.ID)
+		return fmt.Sprintf("%s/%s/%d", setting.AppSubURL, UserAvatarURLPrefix, u.ID)
 	}
 	return tool.AvatarLink(u.AvatarEmail)
 }
@@ -416,7 +416,7 @@ func (u *User) DeleteAvatar() error {
 
 // IsAdminOfRepo returns true if user has admin or higher access of repository.
 func (u *User) IsAdminOfRepo(repo *Repository) bool {
-	has, err := HasAccess(u.ID, repo, ACCESS_MODE_ADMIN)
+	has, err := HasAccess(u.ID, repo, AccessModeAdmin)
 	if err != nil {
 		raven.CaptureErrorAndWait(err, nil)
 		log.Error(2, "HasAccess: %v", err)
@@ -426,7 +426,7 @@ func (u *User) IsAdminOfRepo(repo *Repository) bool {
 
 // IsWriterOfRepo returns true if user has write access to given repository.
 func (u *User) IsWriterOfRepo(repo *Repository) bool {
-	has, err := HasAccess(u.ID, repo, ACCESS_MODE_WRITE)
+	has, err := HasAccess(u.ID, repo, AccessModeWrite)
 	if err != nil {
 		raven.CaptureErrorAndWait(err, nil)
 		log.Error(2, "HasAccess: %v", err)
@@ -436,7 +436,7 @@ func (u *User) IsWriterOfRepo(repo *Repository) bool {
 
 // IsOrganization returns true if user is actually a organization.
 func (u *User) IsOrganization() bool {
-	return u.Type == USER_TYPE_ORGANIZATION
+	return u.Type == UserTypeOrganization
 }
 
 // IsUserOrgOwner returns true if user is in the owner team of given organization.
@@ -496,7 +496,7 @@ func (u *User) GetOrganizations(showPrivate bool) error {
 	}
 
 	u.Orgs = make([]*User, 0, len(orgIDs))
-	if err = x.Where("type = ?", USER_TYPE_ORGANIZATION).In("id", orgIDs).Find(&u.Orgs); err != nil {
+	if err = x.Where("type = ?", UserTypeOrganization).In("id", orgIDs).Find(&u.Orgs); err != nil {
 		return err
 	}
 	return nil
@@ -576,6 +576,7 @@ func isUsableName(names, patterns []string, name string) error {
 	return nil
 }
 
+// IsUsableUsername returns an error when a username is reserved
 func IsUsableUsername(name string) error {
 	return isUsableName(reservedUsernames, reservedUserPatterns, name)
 }
@@ -665,7 +666,7 @@ func parseUserFromCode(code string) (user *User) {
 	return nil
 }
 
-// verify active code when active account
+// VerifyUserActiveCode verify active code when active account
 func VerifyUserActiveCode(code string) (user *User) {
 	minutes := setting.Service.ActiveCodeLives
 
@@ -681,7 +682,7 @@ func VerifyUserActiveCode(code string) (user *User) {
 	return nil
 }
 
-// verify active code when active account
+// VerifyActiveEmailCode verify active code when active account
 func VerifyActiveEmailCode(code, email string) *EmailAddress {
 	minutes := setting.Service.ActiveCodeLives
 
@@ -910,6 +911,7 @@ func UserPath(userName string) string {
 	return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
 }
 
+// GetUserByKeyID get user information by user's public key id
 func GetUserByKeyID(keyID int64) (*User, error) {
 	user := new(User)
 	has, err := x.SQL("SELECT a.* FROM `user` AS a, public_key AS b WHERE a.id = b.owner_id AND b.id=?", keyID).Get(user)
@@ -939,7 +941,7 @@ func GetUserByID(id int64) (*User, error) {
 
 // GetAssigneeByID returns the user with write access of repository by given ID.
 func GetAssigneeByID(repo *Repository, userID int64) (*User, error) {
-	has, err := HasAccess(userID, repo, ACCESS_MODE_READ)
+	has, err := HasAccess(userID, repo, AccessModeRead)
 	if err != nil {
 		return nil, err
 	} else if !has {
@@ -1113,6 +1115,7 @@ type Follow struct {
 	FollowID int64 `xorm:"UNIQUE(follow)"`
 }
 
+// IsFollowing returns true if user is following followID.
 func IsFollowing(userID, followID int64) bool {
 	has, _ := x.Get(&Follow{UserID: userID, FollowID: followID})
 	return has

+ 6 - 1
models/user_mail.go

@@ -69,7 +69,7 @@ func isEmailUsed(e Engine, email string) (bool, error) {
 	}
 
 	// We need to check primary email of users as well.
-	return e.Where("type=?", USER_TYPE_INDIVIDUAL).And("email=?", email).Get(new(User))
+	return e.Where("type=?", UserTypeIndividual).And("email=?", email).Get(new(User))
 }
 
 // IsEmailUsed returns true if the email has been used.
@@ -90,10 +90,12 @@ func addEmailAddress(e Engine, email *EmailAddress) error {
 	return err
 }
 
+// AddEmailAddress adds an email address to given user.
 func AddEmailAddress(email *EmailAddress) error {
 	return addEmailAddress(x, email)
 }
 
+// AddEmailAddresses adds an email address to given user.
 func AddEmailAddresses(emails []*EmailAddress) error {
 	if len(emails) == 0 {
 		return nil
@@ -142,6 +144,7 @@ func (email *EmailAddress) Activate() error {
 	return sess.Commit()
 }
 
+// DeleteEmailAddress deletes an email address of given user.
 func DeleteEmailAddress(email *EmailAddress) (err error) {
 	if email.ID > 0 {
 		_, err = x.Id(email.ID).Delete(new(EmailAddress))
@@ -151,6 +154,7 @@ func DeleteEmailAddress(email *EmailAddress) (err error) {
 	return err
 }
 
+// DeleteEmailAddresses deletes multiple email addresses
 func DeleteEmailAddresses(emails []*EmailAddress) (err error) {
 	for i := range emails {
 		if err = DeleteEmailAddress(emails[i]); err != nil {
@@ -161,6 +165,7 @@ func DeleteEmailAddresses(emails []*EmailAddress) (err error) {
 	return nil
 }
 
+// MakeEmailPrimary sets primary email address of given user.
 func MakeEmailPrimary(email *EmailAddress) error {
 	has, err := x.Get(email)
 	if err != nil {

+ 30 - 29
models/webhook.go

@@ -86,9 +86,9 @@ type HookEvent struct {
 type HookStatus int
 
 const (
-	HOOK_STATUS_NONE = iota
-	HOOK_STATUS_SUCCEED
-	HOOK_STATUS_FAILED
+	HookStatusNone = iota
+	HookStatusSucceed
+	HookStatusFailed
 )
 
 // Webhook represents a web hook object.
@@ -215,14 +215,14 @@ type eventChecker struct {
 func (w *Webhook) EventsArray() []string {
 	events := make([]string, 0, 8)
 	eventCheckers := []eventChecker{
-		{w.HasCreateEvent, HOOK_EVENT_CREATE},
-		{w.HasDeleteEvent, HOOK_EVENT_DELETE},
-		{w.HasForkEvent, HOOK_EVENT_FORK},
-		{w.HasPushEvent, HOOK_EVENT_PUSH},
-		{w.HasIssuesEvent, HOOK_EVENT_ISSUES},
-		{w.HasPullRequestEvent, HOOK_EVENT_PULL_REQUEST},
-		{w.HasIssueCommentEvent, HOOK_EVENT_ISSUE_COMMENT},
-		{w.HasReleaseEvent, HOOK_EVENT_RELEASE},
+		{w.HasCreateEvent, HookEventCreate},
+		{w.HasDeleteEvent, HookEventDelete},
+		{w.HasForkEvent, HookEventFork},
+		{w.HasPushEvent, HookEventPush},
+		{w.HasIssuesEvent, HookEventIssues},
+		{w.HasPullRequestEvent, HookEventPullRequest},
+		{w.HasIssueCommentEvent, HookEventIssueComment},
+		{w.HasReleaseEvent, HookEventRelease},
 	}
 	for _, c := range eventCheckers {
 		if c.checker() {
@@ -379,14 +379,14 @@ func IsValidHookTaskType(name string) bool {
 type HookEventType string
 
 const (
-	HOOK_EVENT_CREATE        HookEventType = "create"
-	HOOK_EVENT_DELETE        HookEventType = "delete"
-	HOOK_EVENT_FORK          HookEventType = "fork"
-	HOOK_EVENT_PUSH          HookEventType = "push"
-	HOOK_EVENT_ISSUES        HookEventType = "issues"
-	HOOK_EVENT_PULL_REQUEST  HookEventType = "pull_request"
-	HOOK_EVENT_ISSUE_COMMENT HookEventType = "issue_comment"
-	HOOK_EVENT_RELEASE       HookEventType = "release"
+	HookEventCreate       HookEventType = "create"
+	HookEventDelete       HookEventType = "delete"
+	HookEventFork         HookEventType = "fork"
+	HookEventPush         HookEventType = "push"
+	HookEventIssues       HookEventType = "issues"
+	HookEventPullRequest  HookEventType = "pull_request"
+	HookEventIssueComment HookEventType = "issue_comment"
+	HookEventRelease      HookEventType = "release"
 )
 
 // HookRequest represents hook task request information.
@@ -524,35 +524,35 @@ func prepareHookTasks(e Engine, repo *Repository, event HookEventType, p api.Pay
 	var payloader api.Payloader
 	for _, w := range webhooks {
 		switch event {
-		case HOOK_EVENT_CREATE:
+		case HookEventCreate:
 			if !w.HasCreateEvent() {
 				continue
 			}
-		case HOOK_EVENT_DELETE:
+		case HookEventDelete:
 			if !w.HasDeleteEvent() {
 				continue
 			}
-		case HOOK_EVENT_FORK:
+		case HookEventFork:
 			if !w.HasForkEvent() {
 				continue
 			}
-		case HOOK_EVENT_PUSH:
+		case HookEventPush:
 			if !w.HasPushEvent() {
 				continue
 			}
-		case HOOK_EVENT_ISSUES:
+		case HookEventIssues:
 			if !w.HasIssuesEvent() {
 				continue
 			}
-		case HOOK_EVENT_PULL_REQUEST:
+		case HookEventPullRequest:
 			if !w.HasPullRequestEvent() {
 				continue
 			}
-		case HOOK_EVENT_ISSUE_COMMENT:
+		case HookEventIssueComment:
 			if !w.HasIssueCommentEvent() {
 				continue
 			}
-		case HOOK_EVENT_RELEASE:
+		case HookEventRelease:
 			if !w.HasReleaseEvent() {
 				continue
 			}
@@ -687,9 +687,9 @@ func (t *HookTask) deliver() {
 			return
 		}
 		if t.IsSucceed {
-			w.LastStatus = HOOK_STATUS_SUCCEED
+			w.LastStatus = HookStatusSucceed
 		} else {
-			w.LastStatus = HOOK_STATUS_FAILED
+			w.LastStatus = HookStatusFailed
 		}
 		if err = UpdateWebhook(w); err != nil {
 			raven.CaptureErrorAndWait(err, nil)
@@ -762,6 +762,7 @@ func DeliverHooks() {
 	}
 }
 
+// InitDeliverHooks starts the hooks delivery thread
 func InitDeliverHooks() {
 	go DeliverHooks()
 }

+ 12 - 8
models/webhook_discord.go

@@ -57,14 +57,17 @@ func (p *DiscordPayload) JSONPayload() ([]byte, error) {
 	return data, nil
 }
 
+// DiscordTextFormatter formats text
 func DiscordTextFormatter(s string) string {
 	return strings.Split(s, "\n")[0]
 }
 
+// DiscordLinkFormatter formats link
 func DiscordLinkFormatter(url string, text string) string {
 	return fmt.Sprintf("[%s](%s)", text, url)
 }
 
+// DiscordSHALinkFormatter formats SHA text
 func DiscordSHALinkFormatter(url string, text string) string {
 	return fmt.Sprintf("[`%s`](%s)", text, url)
 }
@@ -370,6 +373,7 @@ func getDiscordReleasePayload(p *api.ReleasePayload) (*DiscordPayload, error) {
 	}, nil
 }
 
+// GetDiscordPayload converts a discord webhook into a DiscordPayload
 func GetDiscordPayload(p api.Payloader, event HookEventType, meta string) (payload *DiscordPayload, err error) {
 	slack := &SlackMeta{}
 	if err := jsoniter.Unmarshal([]byte(meta), &slack); err != nil {
@@ -377,21 +381,21 @@ func GetDiscordPayload(p api.Payloader, event HookEventType, meta string) (paylo
 	}
 
 	switch event {
-	case HOOK_EVENT_CREATE:
+	case HookEventCreate:
 		payload, err = getDiscordCreatePayload(p.(*api.CreatePayload))
-	case HOOK_EVENT_DELETE:
+	case HookEventDelete:
 		payload, err = getDiscordDeletePayload(p.(*api.DeletePayload))
-	case HOOK_EVENT_FORK:
+	case HookEventFork:
 		payload, err = getDiscordForkPayload(p.(*api.ForkPayload))
-	case HOOK_EVENT_PUSH:
+	case HookEventPush:
 		payload, err = getDiscordPushPayload(p.(*api.PushPayload), slack)
-	case HOOK_EVENT_ISSUES:
+	case HookEventIssues:
 		payload, err = getDiscordIssuesPayload(p.(*api.IssuesPayload), slack)
-	case HOOK_EVENT_ISSUE_COMMENT:
+	case HookEventIssueComment:
 		payload, err = getDiscordIssueCommentPayload(p.(*api.IssueCommentPayload), slack)
-	case HOOK_EVENT_PULL_REQUEST:
+	case HookEventPullRequest:
 		payload, err = getDiscordPullRequestPayload(p.(*api.PullRequestPayload), slack)
-	case HOOK_EVENT_RELEASE:
+	case HookEventRelease:
 		payload, err = getDiscordReleasePayload(p.(*api.ReleasePayload))
 	}
 	if err != nil {

+ 12 - 9
models/webhook_slack.go

@@ -48,7 +48,7 @@ func (p *SlackPayload) JSONPayload() ([]byte, error) {
 	return data, nil
 }
 
-// see: https://api.slack.com/docs/formatting
+// SlackTextFormatter formats text see: https://api.slack.com/docs/formatting
 func SlackTextFormatter(s string) string {
 	// replace & < >
 	s = strings.Replace(s, "&", "&amp;", -1)
@@ -57,6 +57,7 @@ func SlackTextFormatter(s string) string {
 	return s
 }
 
+// SlackShortTextFormatter formats short text
 func SlackShortTextFormatter(s string) string {
 	s = strings.Split(s, "\n")[0]
 	// replace & < >
@@ -66,6 +67,7 @@ func SlackShortTextFormatter(s string) string {
 	return s
 }
 
+// SlackLinkFormatter formats link
 func SlackLinkFormatter(url string, text string) string {
 	return fmt.Sprintf("<%s|%s>", url, SlackTextFormatter(text))
 }
@@ -287,6 +289,7 @@ func getSlackReleasePayload(p *api.ReleasePayload) (*SlackPayload, error) {
 	}, nil
 }
 
+// GetSlackPayload converts a slack webhook into a SlackPayload
 func GetSlackPayload(p api.Payloader, event HookEventType, meta string) (payload *SlackPayload, err error) {
 	slack := &SlackMeta{}
 	if err := jsoniter.Unmarshal([]byte(meta), &slack); err != nil {
@@ -294,21 +297,21 @@ func GetSlackPayload(p api.Payloader, event HookEventType, meta string) (payload
 	}
 
 	switch event {
-	case HOOK_EVENT_CREATE:
+	case HookEventCreate:
 		payload, err = getSlackCreatePayload(p.(*api.CreatePayload))
-	case HOOK_EVENT_DELETE:
+	case HookEventDelete:
 		payload, err = getSlackDeletePayload(p.(*api.DeletePayload))
-	case HOOK_EVENT_FORK:
+	case HookEventFork:
 		payload, err = getSlackForkPayload(p.(*api.ForkPayload))
-	case HOOK_EVENT_PUSH:
+	case HookEventPush:
 		payload, err = getSlackPushPayload(p.(*api.PushPayload), slack)
-	case HOOK_EVENT_ISSUES:
+	case HookEventIssues:
 		payload, err = getSlackIssuesPayload(p.(*api.IssuesPayload), slack)
-	case HOOK_EVENT_ISSUE_COMMENT:
+	case HookEventIssueComment:
 		payload, err = getSlackIssueCommentPayload(p.(*api.IssueCommentPayload), slack)
-	case HOOK_EVENT_PULL_REQUEST:
+	case HookEventPullRequest:
 		payload, err = getSlackPullRequestPayload(p.(*api.PullRequestPayload), slack)
-	case HOOK_EVENT_RELEASE:
+	case HookEventRelease:
 		payload, err = getSlackReleasePayload(p.(*api.ReleasePayload))
 	}
 	if err != nil {

+ 1 - 1
models/wiki.go

@@ -17,7 +17,7 @@ import (
 	"path/filepath"
 	"strings"
 
-	"github.com/Unknwon/com"
+	"gitlab.com/gitote/com"
 	"gitlab.com/gitote/git-module"
 )
 

+ 1 - 1
pkg/context/context.go

@@ -20,12 +20,12 @@ import (
 	"strings"
 	"time"
 
-	"github.com/Unknwon/com"
 	raven "github.com/getsentry/raven-go"
 	"github.com/go-macaron/cache"
 	"github.com/go-macaron/csrf"
 	"github.com/go-macaron/i18n"
 	"github.com/go-macaron/session"
+	"gitlab.com/gitote/com"
 	log "gopkg.in/clog.v1"
 	"gopkg.in/macaron.v1"
 )

+ 1 - 1
pkg/context/org.go

@@ -135,7 +135,7 @@ func HandleOrgAssignment(c *Context, args ...bool) {
 			return
 		}
 
-		c.Org.IsTeamAdmin = c.Org.Team.IsOwnerTeam() || c.Org.Team.Authorize >= models.ACCESS_MODE_ADMIN
+		c.Org.IsTeamAdmin = c.Org.Team.IsOwnerTeam() || c.Org.Team.Authorize >= models.AccessModeAdmin
 		c.Data["IsTeamAdmin"] = c.Org.IsTeamAdmin
 		if requireTeamAdmin && !c.Org.IsTeamAdmin {
 			c.Handle(404, "OrgAssignment", err)

+ 6 - 6
pkg/context/repo.go

@@ -51,22 +51,22 @@ type Repository struct {
 
 // IsOwner returns true if current user is the owner of repository.
 func (r *Repository) IsOwner() bool {
-	return r.AccessMode >= models.ACCESS_MODE_OWNER
+	return r.AccessMode >= models.AccessModeOwner
 }
 
 // IsAdmin returns true if current user has admin or higher access of repository.
 func (r *Repository) IsAdmin() bool {
-	return r.AccessMode >= models.ACCESS_MODE_ADMIN
+	return r.AccessMode >= models.AccessModeAdmin
 }
 
 // IsWriter returns true if current user has write or higher access of repository.
 func (r *Repository) IsWriter() bool {
-	return r.AccessMode >= models.ACCESS_MODE_WRITE
+	return r.AccessMode >= models.AccessModeWrite
 }
 
 // HasAccess returns true if the current user has at least read access for this repository
 func (r *Repository) HasAccess() bool {
-	return r.AccessMode >= models.ACCESS_MODE_READ
+	return r.AccessMode >= models.AccessModeRead
 }
 
 // CanEnableEditor returns true if repository is editable and user has proper access level.
@@ -158,7 +158,7 @@ func RepoAssignment(pages ...bool) macaron.Handler {
 
 		// Admin has super access.
 		if c.IsLogged && c.User.IsAdmin {
-			c.Repo.AccessMode = models.ACCESS_MODE_OWNER
+			c.Repo.AccessMode = models.AccessModeOwner
 		} else {
 			mode, err := models.AccessLevel(c.UserID(), repo)
 			if err != nil {
@@ -169,7 +169,7 @@ func RepoAssignment(pages ...bool) macaron.Handler {
 		}
 
 		// Check access
-		if c.Repo.AccessMode == models.ACCESS_MODE_NONE {
+		if c.Repo.AccessMode == models.AccessModeNone {
 			// Redirect to any accessible page if not yet on it
 			if repo.IsPartialPublic() &&
 				(!(isIssuesPage || isWikiPage) ||

+ 1 - 1
pkg/form/admin.go

@@ -40,7 +40,7 @@ type AdminEditUser struct {
 	Twitter          string `binding:"MaxSize(50)"`
 	Linkedin         string `binding:"MaxSize(50)"`
 	Github           string `binding:"MaxSize(50)"`
-	Devto            string `binding:"MaxSize(50)"`
+	Makerlog         string `binding:"MaxSize(50)"`
 	Stackoverflow    string `binding:"MaxSize(50)"`
 	Reddit           string `binding:"MaxSize(50)"`
 	Telegram         string `binding:"MaxSize(50)"`

+ 1 - 1
pkg/form/form.go

@@ -12,8 +12,8 @@ import (
 	"regexp"
 	"strings"
 
-	"github.com/Unknwon/com"
 	"github.com/go-macaron/binding"
+	"gitlab.com/gitote/com"
 	"gopkg.in/macaron.v1"
 )
 

+ 2 - 1
pkg/form/repo.go

@@ -11,8 +11,8 @@ import (
 	"net/url"
 	"strings"
 
-	"github.com/Unknwon/com"
 	"github.com/go-macaron/binding"
+	"gitlab.com/gitote/com"
 	"gopkg.in/macaron.v1"
 )
 
@@ -85,6 +85,7 @@ type RepoSetting struct {
 	MirrorAddress string
 	Private       bool
 	EnablePrune   bool
+	IsVerified    bool
 
 	// Advanced settings
 	EnableWiki            bool

+ 1 - 1
pkg/form/user.go

@@ -98,7 +98,7 @@ type UpdateSocial struct {
 	Twitter       string `binding:"MaxSize(50)"`
 	Linkedin      string `binding:"MaxSize(50)"`
 	Github        string `binding:"MaxSize(50)"`
-	Devto         string `binding:"MaxSize(50)"`
+	Makerlog      string `binding:"MaxSize(50)"`
 	Stackoverflow string `binding:"MaxSize(50)"`
 	Reddit        string `binding:"MaxSize(50)"`
 	Telegram      string `binding:"MaxSize(50)"`

+ 9 - 1
pkg/mailer/mailer.go

@@ -41,7 +41,8 @@ func NewMessageFrom(to []string, from, subject, htmlBody string) *Message {
 
 	contentType := "text/html"
 	body := htmlBody
-	if setting.MailService.UsePlainText {
+	switchedToPlaintext := false
+	if setting.MailService.UsePlainText || setting.MailService.AddPlainTextAlt {
 		plainBody, err := html2text.FromString(htmlBody)
 		if err != nil {
 			raven.CaptureErrorAndWait(err, nil)
@@ -49,9 +50,16 @@ func NewMessageFrom(to []string, from, subject, htmlBody string) *Message {
 		} else {
 			contentType = "text/plain"
 			body = plainBody
+			switchedToPlaintext = true
 		}
 	}
 	msg.SetBody(contentType, body)
+	if switchedToPlaintext && setting.MailService.AddPlainTextAlt && !setting.MailService.UsePlainText {
+		// The AddAlternative method name is confusing - adding html as an "alternative" will actually cause mail
+		// clients to show it as first priority, and the text "main body" is the 2nd priority fallback.
+		// See: https://godoc.org/gopkg.in/gomail.v2#Message.AddAlternative
+		msg.AddAlternative("text/html", htmlBody)
+	}
 	return &Message{
 		Message:     msg,
 		confirmChan: make(chan struct{}),

+ 2 - 2
pkg/markup/markdown.go

@@ -106,7 +106,7 @@ func (r *MarkdownRenderer) AutoLink(out *bytes.Buffer, link []byte, kind int) {
 }
 
 // ListItem defines how list items should be processed to produce corresponding HTML elements.
-func (options *MarkdownRenderer) ListItem(out *bytes.Buffer, text []byte, flags int) {
+func (r *MarkdownRenderer) ListItem(out *bytes.Buffer, text []byte, flags int) {
 	// Detect procedures to draw checkboxes.
 	switch {
 	case bytes.HasPrefix(text, []byte("[ ] ")):
@@ -114,7 +114,7 @@ func (options *MarkdownRenderer) ListItem(out *bytes.Buffer, text []byte, flags
 	case bytes.HasPrefix(text, []byte("[x] ")):
 		text = append([]byte(`<input type="checkbox" disabled="" checked="" />`), text[3:]...)
 	}
-	options.Renderer.ListItem(out, text, flags)
+	r.Renderer.ListItem(out, text, flags)
 }
 
 // RawMarkdown renders content in Markdown syntax to HTML without handling special links.

+ 2 - 2
pkg/markup/markdown_test.go

@@ -94,8 +94,8 @@ func Test_Markdown(t *testing.T) {
 		Convey("To the internal issue tracker", func() {
 			Convey("It should correctly convert URLs", func() {
 				testCases := []string{
-					"http://localhost:3000/user/project/commit/d8a994ef243349f321568f9e36d5c3f444b99cae", " <code><a href=\"http://localhost:3000/user/project/commit/d8a994ef243349f321568f9e36d5c3f444b99cae\">d8a994ef24</a></code>",
-					"http://localhost:3000/user/project/commit/d8a994ef243349f321568f9e36d5c3f444b99cae#diff-2", " <code><a href=\"http://localhost:3000/user/project/commit/d8a994ef243349f321568f9e36d5c3f444b99cae#diff-2\">d8a994ef24</a></code>",
+					"http://localhost:3000/user/project/commit/d8a994ef243349f321568f9e36d5c3f444b99cae", " <code><a href=\"http://localhost:3000/user/project/commit/d8a994ef243349f321568f9e36d5c3f444b99cae\">d8a994e</a></code>",
+					"http://localhost:3000/user/project/commit/d8a994ef243349f321568f9e36d5c3f444b99cae#diff-2", " <code><a href=\"http://localhost:3000/user/project/commit/d8a994ef243349f321568f9e36d5c3f444b99cae#diff-2\">d8a994e</a></code>",
 					"https://external-link.gitote/gitote/commit/d8a994ef243349f321568f9e36d5c3f444b99cae#diff-2", "<a href=\"https://external-link.gitote/gitote/commit/d8a994ef243349f321568f9e36d5c3f444b99cae#diff-2\">https://external-link.gitote/gitote/commit/d8a994ef243349f321568f9e36d5c3f444b99cae#diff-2</a>",
 					"https://commit/d8a994ef243349f321568f9e36d5c3f444b99cae", "<a href=\"https://commit/d8a994ef243349f321568f9e36d5c3f444b99cae\">https://commit/d8a994ef243349f321568f9e36d5c3f444b99cae</a>",
 				}

+ 13 - 10
pkg/markup/markup.go

@@ -15,7 +15,7 @@ import (
 	"regexp"
 	"strings"
 
-	"github.com/Unknwon/com"
+	"gitlab.com/gitote/com"
 	"golang.org/x/net/html"
 )
 
@@ -29,15 +29,18 @@ func IsIPythonNotebook(name string) bool {
 	return strings.HasSuffix(name, ".ipynb")
 }
 
+// Issue name style
 const (
-	ISSUE_NAME_STYLE_NUMERIC      = "numeric"
-	ISSUE_NAME_STYLE_ALPHANUMERIC = "alphanumeric"
+	IssueNameStyleNumeric      = "numeric"
+	IssueNameStyleAlphaNumeric = "alphanumeric"
 )
 
 var (
 	// MentionPattern matches string that mentions someone, e.g. @yoginth
-	MentionPattern   = regexp.MustCompile(`(\s|^|\W)@[0-9a-zA-Z-_\.]+`)
-	CommitPattern    = regexp.MustCompile(`(\s|^)https?.*commit/[0-9a-zA-Z]+(#+[0-9a-zA-Z-]*)?`)
+	MentionPattern = regexp.MustCompile(`(\s|^|\W)@[0-9a-zA-Z-_\.]+`)
+	// CommitPattern matches string that commits
+	CommitPattern = regexp.MustCompile(`(\s|^)https?.*commit/[0-9a-zA-Z]+(#+[0-9a-zA-Z-]*)?`)
+	// IssueFullPattern matches string that issue
 	IssueFullPattern = regexp.MustCompile(`(\s|^)https?.*issues/[0-9]+(#+[0-9a-zA-Z-]*)?`)
 	// IssueNumericPattern matches string that references to a numeric issue, e.g. #505
 	IssueNumericPattern = regexp.MustCompile(`( |^|\(|\[)#[0-9]+\b`)
@@ -46,9 +49,7 @@ var (
 	// CrossReferenceIssueNumericPattern matches string that references a numeric issue in a difference repository
 	// e.g. gitote/gitote#12345
 	CrossReferenceIssueNumericPattern = regexp.MustCompile(`( |^)[0-9a-zA-Z-_\.]+/[0-9a-zA-Z-_\.]+#[0-9]+\b`)
-
-	// FIXME: this pattern matches pure numbers as well, right now we do a hack to check in RenderSha1CurrentPattern by converting string to a number.
-	// by converting string to a number.
+	// Sha1CurrentPattern by converting string to a number.
 	Sha1CurrentPattern = regexp.MustCompile(`\b[0-9a-f]{7,40}\b`)
 )
 
@@ -85,7 +86,7 @@ func RenderIssueIndexPattern(rawBytes []byte, urlPrefix string, metas map[string
 	urlPrefix = cutoutVerbosePrefix(urlPrefix)
 
 	pattern := IssueNumericPattern
-	if metas["style"] == ISSUE_NAME_STYLE_ALPHANUMERIC {
+	if metas["style"] == IssueNameStyleAlphaNumeric {
 		pattern = IssueAlphanumericPattern
 	}
 
@@ -100,7 +101,7 @@ func RenderIssueIndexPattern(rawBytes []byte, urlPrefix string, metas map[string
 			link = fmt.Sprintf(`<a href="%s/issues/%s">%s</a>`, urlPrefix, m[1:], m)
 		} else {
 			// Support for external issue tracker
-			if metas["style"] == ISSUE_NAME_STYLE_ALPHANUMERIC {
+			if metas["style"] == IssueNameStyleAlphaNumeric {
 				metas["index"] = string(m)
 			} else {
 				metas["index"] = string(m[1:])
@@ -306,8 +307,10 @@ OUTER_LOOP:
 	return rawHTML
 }
 
+// Type holds type
 type Type string
 
+// Markup
 const (
 	UNRECOGNIZED     Type = "unrecognized"
 	MARKDOWN         Type = "markdown"

+ 2 - 2
pkg/markup/markup_test.go

@@ -155,7 +155,7 @@ func Test_RenderIssueIndexPattern(t *testing.T) {
 			metas["format"] = "https://someurl.com/{user}/{repo}/{index}"
 			metas["user"] = "someuser"
 			metas["repo"] = "somerepo"
-			metas["style"] = ISSUE_NAME_STYLE_NUMERIC
+			metas["style"] = IssueNameStyleNumeric
 
 			Convey("should not render anything when there are no mentions", func() {
 				testCases := []string{
@@ -227,7 +227,7 @@ func Test_RenderIssueIndexPattern(t *testing.T) {
 			metas["format"] = "https://someurl.com/{user}/{repo}/?b={index}"
 			metas["user"] = "someuser"
 			metas["repo"] = "somerepo"
-			metas["style"] = ISSUE_NAME_STYLE_ALPHANUMERIC
+			metas["style"] = IssueNameStyleAlphaNumeric
 			Convey("It should not render anything when there are no mentions", func() {
 				testCases := []string{
 					"",

+ 15 - 13
pkg/setting/setting.go

@@ -21,13 +21,13 @@ import (
 	"strings"
 	"time"
 
-	"github.com/Unknwon/com"
 	raven "github.com/getsentry/raven-go"
 	_ "github.com/go-macaron/cache/memcache"
 	_ "github.com/go-macaron/cache/redis"
 	"github.com/go-macaron/session"
 	_ "github.com/go-macaron/session/redis"
 	"github.com/mcuadros/go-version"
+	"gitlab.com/gitote/com"
 	"gitlab.com/gitote/go-libravatar"
 	log "gopkg.in/clog.v1"
 	"gopkg.in/ini.v1"
@@ -882,6 +882,7 @@ type Mailer struct {
 	UseCertificate    bool
 	CertFile, KeyFile string
 	UsePlainText      bool
+	AddPlainTextAlt   bool
 }
 
 var (
@@ -897,18 +898,19 @@ func newMailService() {
 	}
 
 	MailService = &Mailer{
-		QueueLength:    sec.Key("SEND_BUFFER_LEN").MustInt(100),
-		SubjectPrefix:  sec.Key("SUBJECT_PREFIX").MustString("[" + "Gitote" + "] "),
-		Host:           sec.Key("HOST").String(),
-		User:           sec.Key("USER").String(),
-		Passwd:         sec.Key("PASSWD").String(),
-		DisableHelo:    sec.Key("DISABLE_HELO").MustBool(),
-		HeloHostname:   sec.Key("HELO_HOSTNAME").String(),
-		SkipVerify:     sec.Key("SKIP_VERIFY").MustBool(),
-		UseCertificate: sec.Key("USE_CERTIFICATE").MustBool(),
-		CertFile:       sec.Key("CERT_FILE").String(),
-		KeyFile:        sec.Key("KEY_FILE").String(),
-		UsePlainText:   sec.Key("USE_PLAIN_TEXT").MustBool(),
+		QueueLength:     sec.Key("SEND_BUFFER_LEN").MustInt(100),
+		SubjectPrefix:   sec.Key("SUBJECT_PREFIX").MustString("[" + "Gitote" + "] "),
+		Host:            sec.Key("HOST").String(),
+		User:            sec.Key("USER").String(),
+		Passwd:          sec.Key("PASSWD").String(),
+		DisableHelo:     sec.Key("DISABLE_HELO").MustBool(),
+		HeloHostname:    sec.Key("HELO_HOSTNAME").String(),
+		SkipVerify:      sec.Key("SKIP_VERIFY").MustBool(),
+		UseCertificate:  sec.Key("USE_CERTIFICATE").MustBool(),
+		CertFile:        sec.Key("CERT_FILE").String(),
+		KeyFile:         sec.Key("KEY_FILE").String(),
+		UsePlainText:    sec.Key("USE_PLAIN_TEXT").MustBool(),
+		AddPlainTextAlt: sec.Key("ADD_PLAIN_TEXT_ALT").MustBool(),
 	}
 	MailService.From = sec.Key("FROM").MustString(MailService.User)
 

+ 1 - 1
pkg/ssh/ssh.go

@@ -18,8 +18,8 @@ import (
 	"path/filepath"
 	"strings"
 
-	"github.com/Unknwon/com"
 	raven "github.com/getsentry/raven-go"
+	"gitlab.com/gitote/com"
 	"golang.org/x/crypto/ssh"
 	log "gopkg.in/clog.v1"
 )

+ 1 - 1
pkg/sync/unique_queue.go

@@ -7,7 +7,7 @@
 package sync
 
 import (
-	"github.com/Unknwon/com"
+	"gitlab.com/gitote/com"
 )
 
 // UniqueQueue is a queue which guarantees only one instance of same

+ 3 - 3
pkg/template/template.go

@@ -248,9 +248,9 @@ type Actioner interface {
 func ActionIcon(opType int) string {
 	switch opType {
 	case 1, 8: // Create and transfer repository
-		return "repo"
-	case 5: // Commit repository
-		return "git-commit"
+		return "rocket"
+	case 5: // Push repository
+		return "repo-push"
 	case 6: // Create issue
 		return "issue-opened"
 	case 7: // New pull request

+ 5 - 6
pkg/tool/path.go

@@ -7,6 +7,7 @@
 package tool
 
 import (
+	"path/filepath"
 	"strings"
 )
 
@@ -18,10 +19,8 @@ func IsSameSiteURLPath(url string) bool {
 	return len(url) >= 2 && url[0] == '/' && url[1] != '/' && url[1] != '\\'
 }
 
-// SanitizePath sanitizes user-defined file paths to prevent remote code execution.
-func SanitizePath(path string) string {
-	path = strings.TrimLeft(path, "/")
-	path = strings.Replace(path, "../", "", -1)
-	path = strings.Replace(path, "..\\", "", -1)
-	return path
+// IsMaliciousPath returns true if given path is an absolute path or contains malicious content
+// which has potential to traverse upper level directories.
+func IsMaliciousPath(path string) bool {
+	return filepath.IsAbs(path) || strings.Contains(path, "..")
 }

+ 14 - 10
pkg/tool/path_test.go

@@ -22,30 +22,34 @@ func Test_IsSameSiteURLPath(t *testing.T) {
 			{"http://github.com", false},
 			{"https://github.com", false},
 			{"/\\github.com", false},
+
 			{"/admin", true},
 			{"/user/repo", true},
 		}
+
 		for _, tc := range testCases {
 			So(IsSameSiteURLPath(tc.url), ShouldEqual, tc.expect)
 		}
 	})
 }
 
-func Test_SanitizePath(t *testing.T) {
-	Convey("Sanitize malicious user-defined path", t, func() {
+func Test_IsMaliciousPath(t *testing.T) {
+	Convey("Detects malicious path", t, func() {
 		testCases := []struct {
 			path   string
-			expect string
+			expect bool
 		}{
-			{"../../../../../../../../../data/gitote/data/sessions/a/9/a9f0ab6c3ef63dd8", "data/gitote/data/sessions/a/9/a9f0ab6c3ef63dd8"},
-			{"data/gitote/../../../../../../../../../data/sessions/a/9/a9f0ab6c3ef63dd8", "data/gitote/data/sessions/a/9/a9f0ab6c3ef63dd8"},
-			{"..\\..\\..\\..\\..\\..\\..\\..\\..\\data\\gitote\\data\\sessions\\a\\9\\a9f0ab6c3ef63dd8", "data\\gitote\\data\\sessions\\a\\9\\a9f0ab6c3ef63dd8"},
-			{"data\\gitote\\..\\..\\..\\..\\..\\..\\..\\..\\..\\data\\sessions\\a\\9\\a9f0ab6c3ef63dd8", "data\\gitote\\data\\sessions\\a\\9\\a9f0ab6c3ef63dd8"},
-			{"data/sessions/a/9/a9f0ab6c3ef63dd8", "data/sessions/a/9/a9f0ab6c3ef63dd8"},
-			{"data\\sessions\\a\\9\\a9f0ab6c3ef63dd8", "data\\sessions\\a\\9\\a9f0ab6c3ef63dd8"},
+			{"../../../../../../../../../data/gitote/data/sessions/a/9/a9f0ab6c3ef63dd8", true},
+			{"..\\/..\\/../data/gitote/data/sessions/a/9/a9f0ab6c3ef63dd8", true},
+			{"data/gitote/../../../../../../../../../data/sessions/a/9/a9f0ab6c3ef63dd8", true},
+			{"..\\..\\..\\..\\..\\..\\..\\..\\..\\data\\gitote\\data\\sessions\\a\\9\\a9f0ab6c3ef63dd8", true},
+			{"data\\gitote\\..\\..\\..\\..\\..\\..\\..\\..\\..\\data\\sessions\\a\\9\\a9f0ab6c3ef63dd8", true},
+
+			{"data/sessions/a/9/a9f0ab6c3ef63dd8", false},
+			{"data\\sessions\\a\\9\\a9f0ab6c3ef63dd8", false},
 		}
 		for _, tc := range testCases {
-			So(SanitizePath(tc.path), ShouldEqual, tc.expect)
+			So(IsMaliciousPath(tc.path), ShouldEqual, tc.expect)
 		}
 	})
 }

+ 4 - 4
pkg/tool/tool.go

@@ -21,9 +21,9 @@ import (
 	"unicode"
 	"unicode/utf8"
 
-	"github.com/Unknwon/com"
-	"github.com/Unknwon/i18n"
 	"gitlab.com/gitote/chardet"
+	"gitlab.com/gitote/com"
+	"gitlab.com/gitote/i18n"
 	log "gopkg.in/clog.v1"
 )
 
@@ -48,8 +48,8 @@ func SHA1(str string) string {
 
 // ShortSHA1 truncates SHA1 string length to at most 10.
 func ShortSHA1(sha1 string) string {
-	if len(sha1) > 10 {
-		return sha1[:10]
+	if len(sha1) > 7 {
+		return sha1[:7]
 	}
 	return sha1
 }

File diff suppressed because it is too large
+ 1 - 1
public/css/gitote.min.css


+ 10 - 0
public/less/_dashboard.less

@@ -249,6 +249,16 @@
 		overflow-wrap: break-word !important;
 		font-size: 13px !important;
 	}
+
+	.icons {
+		background: #e6ebf1;
+		padding: 7px;
+		font-size: 15px;
+		border-radius: 50%;
+		height: 28px;
+		width: 28px;
+		margin-left: -10px;
+	}
 }
 
 .ui.grid > [class*="fifteen wide"].column {

+ 1 - 1
public/less/_repository.less

@@ -140,7 +140,7 @@
 	#clone-panel {
 		margin-top: -8px;
 		margin-left: @5;
-		width: 360px;
+		width: auto;
 
 		input {
 			border-radius: 0;

+ 1 - 1
public/less/_user.less

@@ -150,7 +150,7 @@
 
 .verified {
 	font-size: 16px;
-	color: #328a46;
+	color: #328a46 !important;
 	margin-right: 3px;
 
 	&.v-explore {

+ 21 - 21
routes/admin/admin.go

@@ -19,8 +19,8 @@ import (
 	"strings"
 	"time"
 
-	"github.com/Unknwon/com"
 	"github.com/json-iterator/go"
+	"gitlab.com/gitote/com"
 	"gopkg.in/macaron.v1"
 )
 
@@ -125,26 +125,26 @@ func updateSystemStatus() {
 type AdminOperation int
 
 const (
-	// CLEAN_INACTIVATE_USER operation value
-	CLEAN_INACTIVATE_USER AdminOperation = iota + 1
+	// CleanInactiveUser operation value
+	CleanInactiveUser AdminOperation = iota + 1
 
-	// CLEAN_REPO_ARCHIVES operation value
-	CLEAN_REPO_ARCHIVES
+	// CleanRepoArchives operation value
+	CleanRepoArchives
 
-	// CLEAN_MISSING_REPOS operation value
-	CLEAN_MISSING_REPOS
+	// CleanMissingRepos operation value
+	CleanMissingRepos
 
-	// GIT_GC_REPOS operation value
-	GIT_GC_REPOS
+	// GitGCRepos operation value
+	GitGCRepos
 
-	// SYNC_SSH_AUTHORIZED_KEY operation value
-	SYNC_SSH_AUTHORIZED_KEY
+	// SyncSSHAuthorizedKey operation value
+	SyncSSHAuthorizedKey
 
-	// SYNC_REPOSITORY_HOOKS operation value
-	SYNC_REPOSITORY_HOOKS
+	// SyncRepositoryHooks operation value
+	SyncRepositoryHooks
 
-	// REINIT_MISSING_REPOSITORY operation value
-	REINIT_MISSING_REPOSITORY
+	// ReinitMissingRepository operation value
+	ReinitMissingRepository
 )
 
 // Dashboard shows dashboard page
@@ -160,22 +160,22 @@ func Dashboard(c *context.Context) {
 		var success string
 
 		switch AdminOperation(op) {
-		case CLEAN_REPO_ARCHIVES:
+		case CleanRepoArchives:
 			success = "All repositories archives have been deleted successfully."
 			err = models.DeleteRepositoryArchives()
-		case CLEAN_MISSING_REPOS:
+		case CleanMissingRepos:
 			success = "All repository records that lost Git files have been deleted successfully."
 			err = models.DeleteMissingRepositories()
-		case GIT_GC_REPOS:
+		case GitGCRepos:
 			success = "All repositories have done garbage collection successfully."
 			err = models.GitGcRepos()
-		case SYNC_SSH_AUTHORIZED_KEY:
+		case SyncSSHAuthorizedKey:
 			success = "All public keys have been rewritten successfully."
 			err = models.RewriteAuthorizedKeys()
-		case SYNC_REPOSITORY_HOOKS:
+		case SyncRepositoryHooks:
 			success = "All repositories' pre-receive, update and post-receive hooks have been resynced successfully."
 			err = models.SyncRepositoryHooks()
-		case REINIT_MISSING_REPOSITORY:
+		case ReinitMissingRepository:
 			success = "All repository records that lost Git files have been reinitialized successfully."
 			err = models.ReinitMissingRepositories()
 		}

+ 16 - 16
routes/admin/auths.go

@@ -16,8 +16,8 @@ import (
 	"net/http"
 	"strings"
 
-	"github.com/Unknwon/com"
 	"github.com/go-xorm/core"
+	"gitlab.com/gitote/com"
 	log "gopkg.in/clog.v1"
 )
 
@@ -56,11 +56,11 @@ type dropdownItem struct {
 
 var (
 	authSources = []dropdownItem{
-		{models.LoginNames[models.LOGIN_LDAP], models.LOGIN_LDAP},
-		{models.LoginNames[models.LOGIN_DLDAP], models.LOGIN_DLDAP},
-		{models.LoginNames[models.LOGIN_SMTP], models.LOGIN_SMTP},
-		{models.LoginNames[models.LOGIN_PAM], models.LOGIN_PAM},
-		{models.LoginNames[models.LOGIN_GITHUB], models.LOGIN_GITHUB},
+		{models.LoginNames[models.LoginLDAP], models.LoginLDAP},
+		{models.LoginNames[models.LoginDLDAP], models.LoginDLDAP},
+		{models.LoginNames[models.LoginSMTP], models.LoginSMTP},
+		{models.LoginNames[models.LoginPAM], models.LoginPAM},
+		{models.LoginNames[models.LoginGitHub], models.LoginGitHub},
 	}
 	securityProtocols = []dropdownItem{
 		{models.SecurityProtocolNames[ldap.SECURITY_PROTOCOL_UNENCRYPTED], ldap.SECURITY_PROTOCOL_UNENCRYPTED},
@@ -75,8 +75,8 @@ func NewAuthSource(c *context.Context) {
 	c.PageIs("Admin")
 	c.PageIs("AdminAuthentications")
 
-	c.Data["type"] = models.LOGIN_LDAP
-	c.Data["CurrentTypeName"] = models.LoginNames[models.LOGIN_LDAP]
+	c.Data["type"] = models.LoginLDAP
+	c.Data["CurrentTypeName"] = models.LoginNames[models.LoginLDAP]
 	c.Data["CurrentSecurityProtocol"] = models.SecurityProtocolNames[ldap.SECURITY_PROTOCOL_UNENCRYPTED]
 	c.Data["smtp_auth"] = "PLAIN"
 	c.Data["is_active"] = true
@@ -140,17 +140,17 @@ func NewAuthSourcePost(c *context.Context, f form.Authentication) {
 	hasTLS := false
 	var config core.Conversion
 	switch models.LoginType(f.Type) {
-	case models.LOGIN_LDAP, models.LOGIN_DLDAP:
+	case models.LoginLDAP, models.LoginDLDAP:
 		config = parseLDAPConfig(f)
 		hasTLS = ldap.SecurityProtocol(f.SecurityProtocol) > ldap.SECURITY_PROTOCOL_UNENCRYPTED
-	case models.LOGIN_SMTP:
+	case models.LoginSMTP:
 		config = parseSMTPConfig(f)
 		hasTLS = true
-	case models.LOGIN_PAM:
+	case models.LoginPAM:
 		config = &models.PAMConfig{
 			ServiceName: f.PAMServiceName,
 		}
-	case models.LOGIN_GITHUB:
+	case models.LoginGitHub:
 		config = &models.GitHubConfig{
 			APIEndpoint: strings.TrimSuffix(f.GitHubAPIEndpoint, "/") + "/",
 		}
@@ -230,15 +230,15 @@ func EditAuthSourcePost(c *context.Context, f form.Authentication) {
 
 	var config core.Conversion
 	switch models.LoginType(f.Type) {
-	case models.LOGIN_LDAP, models.LOGIN_DLDAP:
+	case models.LoginLDAP, models.LoginDLDAP:
 		config = parseLDAPConfig(f)
-	case models.LOGIN_SMTP:
+	case models.LoginSMTP:
 		config = parseSMTPConfig(f)
-	case models.LOGIN_PAM:
+	case models.LoginPAM:
 		config = &models.PAMConfig{
 			ServiceName: f.PAMServiceName,
 		}
-	case models.LOGIN_GITHUB:
+	case models.LoginGitHub:
 		config = &models.GitHubConfig{
 			APIEndpoint: strings.TrimSuffix(f.GitHubAPIEndpoint, "/") + "/",
 		}

+ 2 - 2
routes/admin/news.go

@@ -28,14 +28,14 @@ func News(c *context.Context) {
 	c.HTML(200, NewsTPL)
 }
 
-// News shows news page
+// NewsNew shows new news page
 func NewsNew(c *context.Context) {
 	c.Data["Title"] = "News"
 	c.Data["PageIsAdminNews"] = true
 	c.HTML(200, NewsNewTPL)
 }
 
-// News shows news page
+// NewsEdit shows edit news page
 func NewsEdit(c *context.Context) {
 	c.Data["Title"] = "News"
 	c.Data["PageIsAdminNews"] = true

+ 1 - 1
routes/admin/notice.go

@@ -11,7 +11,7 @@ import (
 	"gitote/gitote/pkg/context"
 	"gitote/gitote/pkg/setting"
 
-	"github.com/Unknwon/com"
+	"gitlab.com/gitote/com"
 	"gitlab.com/yoginth/paginater"
 	log "gopkg.in/clog.v1"
 )

+ 1 - 1
routes/admin/orgs.go

@@ -25,7 +25,7 @@ func Organizations(c *context.Context) {
 	c.Data["PageIsAdminOrganizations"] = true
 
 	routes.RenderUserSearch(c, &routes.UserSearchOptions{
-		Type:     models.USER_TYPE_ORGANIZATION,
+		Type:     models.UserTypeOrganization,
 		Counter:  models.CountOrganizations,
 		Ranger:   models.Organizations,
 		PageSize: setting.UI.Admin.OrgPagingNum,

+ 4 - 4
routes/admin/users.go

@@ -15,7 +15,7 @@ import (
 	"gitote/gitote/routes"
 	"strings"
 
-	"github.com/Unknwon/com"
+	"gitlab.com/gitote/com"
 	log "gopkg.in/clog.v1"
 )
 
@@ -37,7 +37,7 @@ func Users(c *context.Context) {
 	c.Data["PageIsAdminUsers"] = true
 
 	routes.RenderUserSearch(c, &routes.UserSearchOptions{
-		Type:     models.USER_TYPE_INDIVIDUAL,
+		Type:     models.UserTypeIndividual,
 		Counter:  models.CountUsers,
 		Ranger:   models.Users,
 		PageSize: setting.UI.Admin.UserPagingNum,
@@ -92,7 +92,7 @@ func NewUserPost(c *context.Context, f form.AdminCrateUser) {
 		ThemeColor: "#161616",
 		IsActive:   true,
 		ShowAds:    true,
-		LoginType:  models.LOGIN_PLAIN,
+		LoginType:  models.LoginPlain,
 	}
 
 	if len(f.LoginType) > 0 {
@@ -242,7 +242,7 @@ func EditUserPost(c *context.Context, f form.AdminEditUser) {
 	u.Twitter = f.Twitter
 	u.Linkedin = f.Linkedin
 	u.Github = f.Github
-	u.Devto = f.Devto
+	u.Makerlog = f.Makerlog
 	u.Stackoverflow = f.Stackoverflow
 	u.Reddit = f.Reddit
 	u.Telegram = f.Telegram

+ 1 - 1
routes/api/v1/admin/user.go

@@ -45,7 +45,7 @@ func CreateUser(c *context.APIContext, form api.CreateUserOption) {
 		Email:     form.Email,
 		Passwd:    form.Password,
 		IsActive:  true,
-		LoginType: models.LOGIN_PLAIN,
+		LoginType: models.LoginPlain,
 	}
 
 	parseLoginSource(c, u, form.SourceID, form.LoginName)

+ 1 - 1
routes/api/v1/api.go

@@ -56,7 +56,7 @@ func repoAssignment() macaron.Handler {
 		}
 
 		if c.IsTokenAuth && c.User.IsAdmin {
-			c.Repo.AccessMode = models.ACCESS_MODE_OWNER
+			c.Repo.AccessMode = models.AccessModeOwner
 		} else {
 			mode, err := models.AccessLevel(c.UserID(), repo)
 			if err != nil {

+ 1 - 1
routes/api/v1/convert/convert.go

@@ -10,7 +10,7 @@ import (
 	"fmt"
 	"gitote/gitote/models"
 
-	"github.com/Unknwon/com"
+	"gitlab.com/gitote/com"
 	"gitlab.com/gitote/git-module"
 	api "gitlab.com/gitote/go-gitote-client"
 )

+ 1 - 1
routes/api/v1/org/org.go

@@ -27,7 +27,7 @@ func CreateOrgForUser(c *context.APIContext, apiForm api.CreateOrgOption, user *
 		Website:     apiForm.Website,
 		Location:    apiForm.Location,
 		IsActive:    true,
-		Type:        models.USER_TYPE_ORGANIZATION,
+		Type:        models.UserTypeOrganization,
 	}
 	if err := models.CreateOrganization(org, user); err != nil {
 		if models.IsErrUserAlreadyExist(err) ||

+ 17 - 17
routes/api/v1/repo/hook.go

@@ -12,8 +12,8 @@ import (
 	"gitote/gitote/pkg/context"
 	"gitote/gitote/routes/api/v1/convert"
 
-	"github.com/Unknwon/com"
 	"github.com/json-iterator/go"
+	"gitlab.com/gitote/com"
 	api "gitlab.com/gitote/go-gitote-client"
 )
 
@@ -58,14 +58,14 @@ func CreateHook(c *context.APIContext, form api.CreateHookOption) {
 		HookEvent: &models.HookEvent{
 			ChooseEvents: true,
 			HookEvents: models.HookEvents{
-				Create:       com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_CREATE)),
-				Delete:       com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_DELETE)),
-				Fork:         com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_FORK)),
-				Push:         com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_PUSH)),
-				Issues:       com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_ISSUES)),
-				IssueComment: com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_ISSUE_COMMENT)),
-				PullRequest:  com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_PULL_REQUEST)),
-				Release:      com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_RELEASE)),
+				Create:       com.IsSliceContainsStr(form.Events, string(models.HookEventCreate)),
+				Delete:       com.IsSliceContainsStr(form.Events, string(models.HookEventDelete)),
+				Fork:         com.IsSliceContainsStr(form.Events, string(models.HookEventFork)),
+				Push:         com.IsSliceContainsStr(form.Events, string(models.HookEventPush)),
+				Issues:       com.IsSliceContainsStr(form.Events, string(models.HookEventIssues)),
+				IssueComment: com.IsSliceContainsStr(form.Events, string(models.HookEventIssueComment)),
+				PullRequest:  com.IsSliceContainsStr(form.Events, string(models.HookEventPullRequest)),
+				Release:      com.IsSliceContainsStr(form.Events, string(models.HookEventRelease)),
 			},
 		},
 		IsActive:     form.Active,
@@ -148,14 +148,14 @@ func EditHook(c *context.APIContext, form api.EditHookOption) {
 	w.PushOnly = false
 	w.SendEverything = false
 	w.ChooseEvents = true
-	w.Create = com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_CREATE))
-	w.Delete = com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_DELETE))
-	w.Fork = com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_FORK))
-	w.Push = com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_PUSH))
-	w.Issues = com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_ISSUES))
-	w.IssueComment = com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_ISSUE_COMMENT))
-	w.PullRequest = com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_PULL_REQUEST))
-	w.Release = com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_RELEASE))
+	w.Create = com.IsSliceContainsStr(form.Events, string(models.HookEventCreate))
+	w.Delete = com.IsSliceContainsStr(form.Events, string(models.HookEventDelete))
+	w.Fork = com.IsSliceContainsStr(form.Events, string(models.HookEventFork))
+	w.Push = com.IsSliceContainsStr(form.Events, string(models.HookEventPush))
+	w.Issues = com.IsSliceContainsStr(form.Events, string(models.HookEventIssues))
+	w.IssueComment = com.IsSliceContainsStr(form.Events, string(models.HookEventIssueComment))
+	w.PullRequest = com.IsSliceContainsStr(form.Events, string(models.HookEventPullRequest))
+	w.Release = com.IsSliceContainsStr(form.Events, string(models.HookEventRelease))
 	if err = w.UpdateEvent(); err != nil {
 		c.Error(500, "UpdateEvent", err)
 		return

+ 2 - 2
routes/api/v1/repo/issue_comment.go

@@ -99,7 +99,7 @@ func EditIssueComment(c *context.APIContext, form api.EditIssueCommentOption) {
 	if c.User.ID != comment.PosterID && !c.Repo.IsAdmin() {
 		c.Status(403)
 		return
-	} else if comment.Type != models.COMMENT_TYPE_COMMENT {
+	} else if comment.Type != models.CommentTypeComment {
 		c.Status(204)
 		return
 	}
@@ -127,7 +127,7 @@ func DeleteIssueComment(c *context.APIContext) {
 	if c.User.ID != comment.PosterID && !c.Repo.IsAdmin() {
 		c.Status(403)
 		return
-	} else if comment.Type != models.COMMENT_TYPE_COMMENT {
+	} else if comment.Type != models.CommentTypeComment {
 		c.Status(204)
 		return
 	}

+ 1 - 1
routes/api/v1/repo/label.go

@@ -10,7 +10,7 @@ import (
 	"gitote/gitote/models"
 	"gitote/gitote/pkg/context"
 
-	"github.com/Unknwon/com"
+	"gitlab.com/gitote/com"
 	api "gitlab.com/gitote/go-gitote-client"
 )
 

+ 2 - 2
routes/api/v1/repo/repo.go

@@ -132,8 +132,8 @@ func listUserRepositories(c *context.APIContext, username string) {
 	i := numOwnRepos
 	for repo, access := range accessibleRepos {
 		repos[i] = repo.APIFormat(&api.Permission{
-			Admin: access >= models.ACCESS_MODE_ADMIN,
-			Push:  access >= models.ACCESS_MODE_WRITE,
+			Admin: access >= models.AccessModeAdmin,
+			Push:  access >= models.AccessModeWrite,
 			Pull:  true,
 		})
 		i++

+ 2 - 2
routes/api/v1/user/user.go

@@ -12,14 +12,14 @@ import (
 	"gitote/gitote/pkg/context"
 	"gitote/gitote/pkg/markup"
 
-	"github.com/Unknwon/com"
+	"gitlab.com/gitote/com"
 	api "gitlab.com/gitote/go-gitote-client"
 )
 
 func Search(c *context.APIContext) {
 	opts := &models.SearchUserOptions{
 		Keyword:  c.Query("q"),
-		Type:     models.USER_TYPE_INDIVIDUAL,
+		Type:     models.UserTypeIndividual,
 		PageSize: com.StrTo(c.Query("limit")).MustInt(),
 	}
 	if opts.PageSize == 0 {

+ 3 - 3
routes/explore.go

@@ -31,7 +31,7 @@ const (
 	ExploreOrganizationsTPL = "explore/organizations"
 )
 
-// ExploreHome shows explore page
+// Explore shows explore page
 func Explore(c *context.Context) {
 	c.Data["Title"] = c.Tr("explore")
 	c.Data["PageIsExplore"] = true
@@ -178,7 +178,7 @@ func ExploreUsers(c *context.Context) {
 	c.Data["PageIsExploreUsers"] = true
 
 	RenderUserSearch(c, &UserSearchOptions{
-		Type:     models.USER_TYPE_INDIVIDUAL,
+		Type:     models.UserTypeIndividual,
 		Counter:  models.CountUsers,
 		Ranger:   models.Users,
 		PageSize: setting.UI.ExplorePagingNum,
@@ -194,7 +194,7 @@ func ExploreOrganizations(c *context.Context) {
 	c.Data["PageIsExploreOrganizations"] = true
 
 	RenderUserSearch(c, &UserSearchOptions{
-		Type:     models.USER_TYPE_ORGANIZATION,
+		Type:     models.UserTypeOrganization,
 		Counter:  models.CountOrganizations,
 		Ranger:   models.Organizations,
 		PageSize: setting.UI.ExplorePagingNum,

+ 1 - 1
routes/install.go

@@ -24,9 +24,9 @@ import (
 	"path/filepath"
 	"strings"
 
-	"github.com/Unknwon/com"
 	raven "github.com/getsentry/raven-go"
 	"github.com/go-xorm/xorm"
+	"gitlab.com/gitote/com"
 	"gitlab.com/gitote/git-module"
 	log "gopkg.in/clog.v1"
 	"gopkg.in/ini.v1"

+ 1 - 1
routes/org/members.go

@@ -12,8 +12,8 @@ import (
 	"gitote/gitote/pkg/context"
 	"gitote/gitote/pkg/setting"
 
-	"github.com/Unknwon/com"
 	raven "github.com/getsentry/raven-go"
+	"gitlab.com/gitote/com"
 	log "gopkg.in/clog.v1"
 )
 

+ 1 - 1
routes/org/org.go

@@ -38,7 +38,7 @@ func CreatePost(c *context.Context, f form.CreateOrg) {
 	org := &models.User{
 		Name:     f.OrgName,
 		IsActive: true,
-		Type:     models.USER_TYPE_ORGANIZATION,
+		Type:     models.UserTypeOrganization,
 	}
 
 	// Create organization

+ 4 - 4
routes/org/teams.go

@@ -13,8 +13,8 @@ import (
 	"gitote/gitote/pkg/form"
 	"path"
 
-	"github.com/Unknwon/com"
 	raven "github.com/getsentry/raven-go"
+	"gitlab.com/gitote/com"
 	log "gopkg.in/clog.v1"
 )
 
@@ -255,11 +255,11 @@ func EditTeamPost(c *context.Context, f form.CreateTeam) {
 		var auth models.AccessMode
 		switch f.Permission {
 		case "read":
-			auth = models.ACCESS_MODE_READ
+			auth = models.AccessModeRead
 		case "write":
-			auth = models.ACCESS_MODE_WRITE
+			auth = models.AccessModeWrite
 		case "admin":
-			auth = models.ACCESS_MODE_ADMIN
+			auth = models.AccessModeAdmin
 		default:
 			c.Error(401)
 			return

+ 1 - 1
routes/repo/branch.go

@@ -152,7 +152,7 @@ func DeleteBranchPost(c *context.Context) {
 		return
 	}
 
-	if err := models.PrepareWebhooks(c.Repo.Repository, models.HOOK_EVENT_DELETE, &api.DeletePayload{
+	if err := models.PrepareWebhooks(c.Repo.Repository, models.HookEventDelete, &api.DeletePayload{
 		Ref:        branchName,
 		RefType:    "branch",
 		PusherType: api.PUSHER_TYPE_USER,

+ 2 - 2
routes/repo/http.go

@@ -149,9 +149,9 @@ Please create and use personal access token on user settings page`)
 
 		log.Trace("HTTPGit - Authenticated user: %s", authUser.Name)
 
-		mode := models.ACCESS_MODE_WRITE
+		mode := models.AccessModeWrite
 		if isPull {
-			mode = models.ACCESS_MODE_READ
+			mode = models.AccessModeRead
 		}
 		has, err := models.HasAccess(authUser.ID, repo, mode)
 		if err != nil {

+ 12 - 12
routes/repo/issue.go

@@ -23,8 +23,8 @@ import (
 	"strings"
 	"time"
 
-	"github.com/Unknwon/com"
 	raven "github.com/getsentry/raven-go"
+	"gitlab.com/gitote/com"
 	"gitlab.com/yoginth/paginater"
 	log "gopkg.in/clog.v1"
 )
@@ -141,16 +141,16 @@ func issues(c *context.Context, isPullList bool) {
 		assigneeID = c.QueryInt64("assignee")
 		posterID   int64
 	)
-	filterMode := models.FILTER_MODE_YOUR_REPOS
+	filterMode := models.FilterModeYourRepos
 	switch viewType {
 	case "assigned":
-		filterMode = models.FILTER_MODE_ASSIGN
+		filterMode = models.FilterModeAssign
 		assigneeID = c.User.ID
 	case "created_by":
-		filterMode = models.FILTER_MODE_CREATE
+		filterMode = models.FilterModeCreate
 		posterID = c.User.ID
 	case "mentioned":
-		filterMode = models.FILTER_MODE_MENTION
+		filterMode = models.FilterModeMention
 	}
 
 	var uid int64 = -1
@@ -195,7 +195,7 @@ func issues(c *context.Context, isPullList bool) {
 		MilestoneID: milestoneID,
 		Page:        pager.Current(),
 		IsClosed:    isShowClosed,
-		IsMention:   filterMode == models.FILTER_MODE_MENTION,
+		IsMention:   filterMode == models.FilterModeMention,
 		IsPull:      isPullList,
 		Labels:      selectLabels,
 		SortType:    sortType,
@@ -627,7 +627,7 @@ func viewIssue(c *context.Context, isPullList bool) {
 	// Render comments and and fetch participants.
 	participants[0] = issue.Poster
 	for _, comment = range issue.Comments {
-		if comment.Type == models.COMMENT_TYPE_COMMENT {
+		if comment.Type == models.CommentTypeComment {
 			comment.RenderedContent = string(markup.Markdown(comment.Content, c.Repo.RepoLink, c.Repo.Repository.ComposeMetas()))
 
 			// Check tag.
@@ -639,11 +639,11 @@ func viewIssue(c *context.Context, isPullList bool) {
 
 			if repo.IsOwnedBy(comment.PosterID) ||
 				(repo.Owner.IsOrganization() && repo.Owner.IsOwnedBy(comment.PosterID)) {
-				comment.ShowTag = models.COMMENT_TAG_OWNER
+				comment.ShowTag = models.CommentTagOwner
 			} else if comment.Poster.IsWriterOfRepo(repo) {
-				comment.ShowTag = models.COMMENT_TAG_WRITER
+				comment.ShowTag = models.CommentTagWriter
 			} else if comment.PosterID == issue.PosterID {
-				comment.ShowTag = models.COMMENT_TAG_POSTER
+				comment.ShowTag = models.CommentTagPoster
 			}
 
 			marked[comment.PosterID] = comment.ShowTag
@@ -953,7 +953,7 @@ func UpdateCommentContent(c *context.Context) {
 	if c.UserID() != comment.PosterID && !c.Repo.IsAdmin() {
 		c.Error(404)
 		return
-	} else if comment.Type != models.COMMENT_TYPE_COMMENT {
+	} else if comment.Type != models.CommentTypeComment {
 		c.Error(204)
 		return
 	}
@@ -986,7 +986,7 @@ func DeleteComment(c *context.Context) {
 	if c.UserID() != comment.PosterID && !c.Repo.IsAdmin() {
 		c.Error(404)
 		return
-	} else if comment.Type != models.COMMENT_TYPE_COMMENT {
+	} else if comment.Type != models.CommentTypeComment {
 		c.Error(204)
 		return
 	}

+ 2 - 2
routes/repo/pull.go

@@ -17,7 +17,7 @@ import (
 	"path"
 	"strings"
 
-	"github.com/Unknwon/com"
+	"gitlab.com/gitote/com"
 	"gitlab.com/gitote/git-module"
 	log "gopkg.in/clog.v1"
 )
@@ -716,7 +716,7 @@ func CompareAndPullRequestPost(c *context.Context, f form.NewIssue) {
 		HeadRepo:     headRepo,
 		BaseRepo:     repo,
 		MergeBase:    prInfo.MergeBase,
-		Type:         models.PULL_REQUEST_GITOTE,
+		Type:         models.PullRequestGitote,
 	}
 	// FIXME: check error in the case two people send pull request at almost same time, give nice error prompt
 	// instead of 500.

+ 1 - 1
routes/repo/repo.go

@@ -18,8 +18,8 @@ import (
 	"path"
 	"strings"
 
-	"github.com/Unknwon/com"
 	raven "github.com/getsentry/raven-go"
+	"gitlab.com/gitote/com"
 	"gitlab.com/gitote/git-module"
 	log "gopkg.in/clog.v1"
 )

+ 3 - 2
routes/repo/setting.go

@@ -19,8 +19,8 @@ import (
 	"strings"
 	"time"
 
-	"github.com/Unknwon/com"
 	raven "github.com/getsentry/raven-go"
+	"gitlab.com/gitote/com"
 	"gitlab.com/gitote/git-module"
 	log "gopkg.in/clog.v1"
 )
@@ -104,6 +104,7 @@ func SettingsPost(c *context.Context, f form.RepoSetting) {
 		repo.Website = f.Website
 		repo.DonateURL = f.DonateURL
 		repo.DonateBadge = f.DonateBadge
+		repo.IsVerified = f.IsVerified
 
 		// Visibility of forked repository is forced sync with base repository.
 		if repo.IsFork {
@@ -539,7 +540,7 @@ func SettingsProtectedBranch(c *context.Context) {
 		c.Data["Users"] = users
 		c.Data["whitelist_users"] = protectBranch.WhitelistUserIDs
 
-		teams, err := c.Repo.Owner.TeamsHaveAccessToRepo(c.Repo.Repository.ID, models.ACCESS_MODE_WRITE)
+		teams, err := c.Repo.Owner.TeamsHaveAccessToRepo(c.Repo.Repository.ID, models.AccessModeWrite)
 		if err != nil {
 			c.Handle(500, "Repo.Owner.TeamsHaveAccessToRepo", err)
 			return

+ 2 - 2
routes/repo/webhook.go

@@ -15,8 +15,8 @@ import (
 	"gitote/gitote/pkg/setting"
 	"strings"
 
-	"github.com/Unknwon/com"
 	"github.com/json-iterator/go"
+	"gitlab.com/gitote/com"
 	git "gitlab.com/gitote/git-module"
 	api "gitlab.com/gitote/go-gitote-client"
 )
@@ -524,7 +524,7 @@ func TestWebhook(c *context.Context) {
 		Pusher: apiUser,
 		Sender: apiUser,
 	}
-	if err := models.TestWebhook(c.Repo.Repository, models.HOOK_EVENT_PUSH, p, c.ParamsInt64("id")); err != nil {
+	if err := models.TestWebhook(c.Repo.Repository, models.HookEventPush, p, c.ParamsInt64("id")); err != nil {
 		c.Handle(500, "TestWebhook", err)
 	} else {
 		c.Flash.Info(c.Tr("repo.settings.webhook.test_delivery_success"))

+ 10 - 10
routes/user/home.go

@@ -14,7 +14,7 @@ import (
 	"gitote/gitote/pkg/context"
 	"gitote/gitote/pkg/setting"
 
-	"github.com/Unknwon/com"
+	"gitlab.com/gitote/com"
 	"gitlab.com/yoginth/paginater"
 )
 
@@ -194,19 +194,19 @@ func Issues(c *context.Context) {
 
 	var (
 		sortType   = c.Query("sort")
-		filterMode = models.FILTER_MODE_YOUR_REPOS
+		filterMode = models.FilterModeYourRepos
 	)
 
 	// Note: Organization does not have view type and filter mode.
 	if !ctxUser.IsOrganization() {
 		viewType := c.Query("type")
 		types := []string{
-			string(models.FILTER_MODE_YOUR_REPOS),
-			string(models.FILTER_MODE_ASSIGN),
-			string(models.FILTER_MODE_CREATE),
+			string(models.FilterModeYourRepos),
+			string(models.FilterModeAssign),
+			string(models.FilterModeCreate),
 		}
 		if !com.IsSliceContainsStr(types, viewType) {
-			viewType = string(models.FILTER_MODE_YOUR_REPOS)
+			viewType = string(models.FilterModeYourRepos)
 		}
 		filterMode = models.FilterMode(viewType)
 	}
@@ -244,7 +244,7 @@ func Issues(c *context.Context) {
 	for _, repo := range repos {
 		userRepoIDs = append(userRepoIDs, repo.ID)
 
-		if filterMode != models.FILTER_MODE_YOUR_REPOS {
+		if filterMode != models.FilterModeYourRepos {
 			continue
 		}
 
@@ -281,7 +281,7 @@ func Issues(c *context.Context) {
 		SortType: sortType,
 	}
 	switch filterMode {
-	case models.FILTER_MODE_YOUR_REPOS:
+	case models.FilterModeYourRepos:
 		// Get all issues from repositories from this user.
 		if userRepoIDs == nil {
 			issueOptions.RepoIDs = []int64{-1}
@@ -289,11 +289,11 @@ func Issues(c *context.Context) {
 			issueOptions.RepoIDs = userRepoIDs
 		}
 
-	case models.FILTER_MODE_ASSIGN:
+	case models.FilterModeAssign:
 		// Get all issues assigned to this user.
 		issueOptions.AssigneeID = ctxUser.ID
 
-	case models.FILTER_MODE_CREATE:
+	case models.FilterModeCreate:
 		// Get all issues created by this user.
 		issueOptions.PosterID = ctxUser.ID
 	}

+ 3 - 3
routes/user/setting.go

@@ -22,10 +22,10 @@ import (
 	"io/ioutil"
 	"strings"
 
-	"github.com/Unknwon/com"
 	raven "github.com/getsentry/raven-go"
 	"github.com/pquerna/otp"
 	"github.com/pquerna/otp/totp"
+	"gitlab.com/gitote/com"
 	log "gopkg.in/clog.v1"
 )
 
@@ -182,7 +182,7 @@ func SettingsSocial(c *context.Context) {
 	c.Data["twitter"] = c.User.Twitter
 	c.Data["linkedin"] = c.User.Linkedin
 	c.Data["github"] = c.User.Github
-	c.Data["devto"] = c.User.Devto
+	c.Data["makerlog"] = c.User.Makerlog
 	c.Data["stackoverflow"] = c.User.Stackoverflow
 	c.Data["reddit"] = c.User.Reddit
 	c.Data["telegram"] = c.User.Telegram
@@ -205,7 +205,7 @@ func SettingsSocialPost(c *context.Context, f form.UpdateSocial) {
 	c.User.Twitter = f.Twitter
 	c.User.Linkedin = f.Linkedin
 	c.User.Github = f.Github
-	c.User.Devto = f.Devto
+	c.User.Makerlog = f.Makerlog
 	c.User.Stackoverflow = f.Stackoverflow
 	c.User.Reddit = f.Reddit
 	c.User.Telegram = f.Telegram

+ 3 - 3
templates/admin/news/edit.tmpl

@@ -88,9 +88,9 @@
 							<label for="gitlab">GitLab</label>
 							<input id="gitlab" name="gitlab" value="{{.User.Gitlab}}">
 						</div>
-						<div class="field {{if .Err_Devto}}error{{end}}">
-							<label for="devto">Dev.to</label>
-							<input id="devto" name="devto" value="{{.User.Devto}}">
+						<div class="field {{if .Err_MakerLog}}error{{end}}">
+							<label for="makerlog">MakerLog</label>
+							<input id="makerlog" name="makerlog" value="{{.User.Makerlog}}">
 						</div>
 						<div class="field {{if .Err_Stackoverflow}}error{{end}}">
 							<label for="stackoverflow">Stackoverflow</label>

+ 0 - 0
templates/admin/user/edit.tmpl


Some files were not shown because too many files changed in this diff