Merge pull request #110 from strk/MixedCaseConst

Use MixedCase constant names
This commit is contained in:
Sandro Santilli 2016-11-07 19:22:21 +01:00 committed by GitHub
commit 01a7674b5c
47 changed files with 398 additions and 398 deletions

View file

@ -64,9 +64,9 @@ func parseCmd(cmd string) (string, string) {
var ( var (
allowedCommands = map[string]models.AccessMode{ allowedCommands = map[string]models.AccessMode{
"git-upload-pack": models.ACCESS_MODE_READ, "git-upload-pack": models.AccessModeRead,
"git-upload-archive": models.ACCESS_MODE_READ, "git-upload-archive": models.AccessModeRead,
"git-receive-pack": models.ACCESS_MODE_WRITE, "git-receive-pack": models.AccessModeWrite,
} }
) )
@ -191,7 +191,7 @@ func runServ(c *cli.Context) error {
} }
// Prohibit push to mirror repositories. // Prohibit push to mirror repositories.
if requestedMode > models.ACCESS_MODE_READ && repo.IsMirror { if requestedMode > models.AccessModeRead && repo.IsMirror {
fail("mirror repository is read-only", "") fail("mirror repository is read-only", "")
} }
@ -200,7 +200,7 @@ func runServ(c *cli.Context) error {
keyID int64 keyID int64
user *models.User user *models.User
) )
if requestedMode == models.ACCESS_MODE_WRITE || repo.IsPrivate { if requestedMode == models.AccessModeWrite || repo.IsPrivate {
keys := strings.Split(c.Args()[0], "-") keys := strings.Split(c.Args()[0], "-")
if len(keys) != 2 { if len(keys) != 2 {
fail("Key ID format error", "Invalid key argument: %s", c.Args()[0]) fail("Key ID format error", "Invalid key argument: %s", c.Args()[0])
@ -213,7 +213,7 @@ func runServ(c *cli.Context) error {
keyID = key.ID keyID = key.ID
// Check deploy key or user key. // Check deploy key or user key.
if key.Type == models.KEY_TYPE_DEPLOY { if key.Type == models.KeyTypeDeploy {
if key.Mode < requestedMode { if key.Mode < requestedMode {
fail("Key permission denied", "Cannot push with deployment key: %d", key.ID) fail("Key permission denied", "Cannot push with deployment key: %d", key.ID)
} }
@ -243,7 +243,7 @@ func runServ(c *cli.Context) error {
fail("Internal error", "Fail to check access: %v", err) fail("Internal error", "Fail to check access: %v", err)
} else if mode < requestedMode { } else if mode < requestedMode {
clientMessage := accessDenied clientMessage := accessDenied
if mode >= models.ACCESS_MODE_READ { if mode >= models.AccessModeRead {
clientMessage = "You do not have sufficient authorization for this action" clientMessage = "You do not have sufficient authorization for this action"
} }
fail(clientMessage, fail(clientMessage,
@ -276,7 +276,7 @@ func runServ(c *cli.Context) error {
fail("Internal error", "Failed to execute git command: %v", err) fail("Internal error", "Failed to execute git command: %v", err)
} }
if requestedMode == models.ACCESS_MODE_WRITE { if requestedMode == models.AccessModeWrite {
handleUpdateTask(uuid, user, repoUser, reponame, isWiki) handleUpdateTask(uuid, user, repoUser, reponame, isWiki)
} }

View file

@ -13,22 +13,22 @@ import (
type AccessMode int type AccessMode int
const ( const (
ACCESS_MODE_NONE AccessMode = iota // 0 AccessModeNone AccessMode = iota // 0
ACCESS_MODE_READ // 1 AccessModeRead // 1
ACCESS_MODE_WRITE // 2 AccessModeWrite // 2
ACCESS_MODE_ADMIN // 3 AccessModeAdmin // 3
ACCESS_MODE_OWNER // 4 AccessModeOwner // 4
) )
func (mode AccessMode) String() string { func (mode AccessMode) String() string {
switch mode { switch mode {
case ACCESS_MODE_READ: case AccessModeRead:
return "read" return "read"
case ACCESS_MODE_WRITE: case AccessModeWrite:
return "write" return "write"
case ACCESS_MODE_ADMIN: case AccessModeAdmin:
return "admin" return "admin"
case ACCESS_MODE_OWNER: case AccessModeOwner:
return "owner" return "owner"
default: default:
return "none" return "none"
@ -39,11 +39,11 @@ func (mode AccessMode) String() string {
func ParseAccessMode(permission string) AccessMode { func ParseAccessMode(permission string) AccessMode {
switch permission { switch permission {
case "write": case "write":
return ACCESS_MODE_WRITE return AccessModeWrite
case "admin": case "admin":
return ACCESS_MODE_ADMIN return AccessModeAdmin
default: default:
return ACCESS_MODE_READ return AccessModeRead
} }
} }
@ -58,9 +58,9 @@ type Access struct {
} }
func accessLevel(e Engine, u *User, repo *Repository) (AccessMode, error) { func accessLevel(e Engine, u *User, repo *Repository) (AccessMode, error) {
mode := ACCESS_MODE_NONE mode := AccessModeNone
if !repo.IsPrivate { if !repo.IsPrivate {
mode = ACCESS_MODE_READ mode = AccessModeRead
} }
if u == nil { if u == nil {
@ -68,7 +68,7 @@ func accessLevel(e Engine, u *User, repo *Repository) (AccessMode, error) {
} }
if u.ID == repo.OwnerID { if u.ID == repo.OwnerID {
return ACCESS_MODE_OWNER, nil return AccessModeOwner, nil
} }
a := &Access{UserID: u.ID, RepoID: repo.ID} a := &Access{UserID: u.ID, RepoID: repo.ID}
@ -135,7 +135,7 @@ func (user *User) GetAccessibleRepositories(limit int) (repos []*Repository, _ e
} }
func maxAccessMode(modes ...AccessMode) AccessMode { func maxAccessMode(modes ...AccessMode) AccessMode {
max := ACCESS_MODE_NONE max := AccessModeNone
for _, mode := range modes { for _, mode := range modes {
if mode > max { if mode > max {
max = mode max = mode
@ -146,9 +146,9 @@ func maxAccessMode(modes ...AccessMode) AccessMode {
// FIXME: do corss-comparison so reduce deletions and additions to the minimum? // FIXME: do corss-comparison so reduce deletions and additions to the minimum?
func (repo *Repository) refreshAccesses(e Engine, accessMap map[int64]AccessMode) (err error) { func (repo *Repository) refreshAccesses(e Engine, accessMap map[int64]AccessMode) (err error) {
minMode := ACCESS_MODE_READ minMode := AccessModeRead
if !repo.IsPrivate { if !repo.IsPrivate {
minMode = ACCESS_MODE_WRITE minMode = AccessModeWrite
} }
newAccesses := make([]Access, 0, len(accessMap)) newAccesses := make([]Access, 0, len(accessMap))
@ -212,7 +212,7 @@ func (repo *Repository) recalculateTeamAccesses(e Engine, ignTeamID int64) (err
// Owner team gets owner access, and skip for teams that do not // Owner team gets owner access, and skip for teams that do not
// have relations with repository. // have relations with repository.
if t.IsOwnerTeam() { if t.IsOwnerTeam() {
t.Authorize = ACCESS_MODE_OWNER t.Authorize = AccessModeOwner
} else if !t.hasRepository(e, repo.ID) { } else if !t.hasRepository(e, repo.ID) {
continue continue
} }

View file

@ -27,21 +27,21 @@ import (
type ActionType int type ActionType int
const ( const (
ACTION_CREATE_REPO ActionType = iota + 1 // 1 ActionCreateRepo ActionType = iota + 1 // 1
ACTION_RENAME_REPO // 2 ActionRenameRepo // 2
ACTION_STAR_REPO // 3 ActionStarRepo // 3
ACTION_WATCH_REPO // 4 ActionWatchRepo // 4
ACTION_COMMIT_REPO // 5 ActionCommitRepo // 5
ACTION_CREATE_ISSUE // 6 ActionCreateIssue // 6
ACTION_CREATE_PULL_REQUEST // 7 ActionCreatePullRequest // 7
ACTION_TRANSFER_REPO // 8 ActionTransferRepo // 8
ACTION_PUSH_TAG // 9 ActionPushTag // 9
ACTION_COMMENT_ISSUE // 10 ActionCommentIssue // 10
ACTION_MERGE_PULL_REQUEST // 11 ActionMergePullRequest // 11
ACTION_CLOSE_ISSUE // 12 ActionCloseIssue // 12
ACTION_REOPEN_ISSUE // 13 ActionReopenIssue // 13
ACTION_CLOSE_PULL_REQUEST // 14 ActionClosePullRequest // 14
ACTION_REOPEN_PULL_REQUEST // 15 ActionReopenPullRequest // 15
) )
var ( var (
@ -176,7 +176,7 @@ func newRepoAction(e Engine, u *User, repo *Repository) (err error) {
if err = notifyWatchers(e, &Action{ if err = notifyWatchers(e, &Action{
ActUserID: u.ID, ActUserID: u.ID,
ActUserName: u.Name, ActUserName: u.Name,
OpType: ACTION_CREATE_REPO, OpType: ActionCreateRepo,
RepoID: repo.ID, RepoID: repo.ID,
RepoUserName: repo.Owner.Name, RepoUserName: repo.Owner.Name,
RepoName: repo.Name, RepoName: repo.Name,
@ -198,7 +198,7 @@ func renameRepoAction(e Engine, actUser *User, oldRepoName string, repo *Reposit
if err = notifyWatchers(e, &Action{ if err = notifyWatchers(e, &Action{
ActUserID: actUser.ID, ActUserID: actUser.ID,
ActUserName: actUser.Name, ActUserName: actUser.Name,
OpType: ACTION_RENAME_REPO, OpType: ActionRenameRepo,
RepoID: repo.ID, RepoID: repo.ID,
RepoUserName: repo.Owner.Name, RepoUserName: repo.Owner.Name,
RepoName: repo.Name, RepoName: repo.Name,
@ -454,10 +454,10 @@ func CommitRepoAction(opts CommitRepoActionOptions) error {
} }
isNewBranch := false isNewBranch := false
opType := ACTION_COMMIT_REPO opType := ActionCommitRepo
// Check it's tag push or branch. // Check it's tag push or branch.
if strings.HasPrefix(opts.RefFullName, git.TAG_PREFIX) { if strings.HasPrefix(opts.RefFullName, git.TAG_PREFIX) {
opType = ACTION_PUSH_TAG opType = ActionPushTag
opts.Commits = &PushCommits{} opts.Commits = &PushCommits{}
} else { } else {
// if not the first commit, set the compare URL. // if not the first commit, set the compare URL.
@ -503,8 +503,8 @@ func CommitRepoAction(opts CommitRepoActionOptions) error {
apiPusher := pusher.APIFormat() apiPusher := pusher.APIFormat()
apiRepo := repo.APIFormat(nil) apiRepo := repo.APIFormat(nil)
switch opType { switch opType {
case ACTION_COMMIT_REPO: // Push case ActionCommitRepo: // Push
if err = PrepareWebhooks(repo, HOOK_EVENT_PUSH, &api.PushPayload{ if err = PrepareWebhooks(repo, HookEventPush, &api.PushPayload{
Ref: opts.RefFullName, Ref: opts.RefFullName,
Before: opts.OldCommitID, Before: opts.OldCommitID,
After: opts.NewCommitID, After: opts.NewCommitID,
@ -518,7 +518,7 @@ func CommitRepoAction(opts CommitRepoActionOptions) error {
} }
if isNewBranch { if isNewBranch {
return PrepareWebhooks(repo, HOOK_EVENT_CREATE, &api.CreatePayload{ return PrepareWebhooks(repo, HookEventCreate, &api.CreatePayload{
Ref: refName, Ref: refName,
RefType: "branch", RefType: "branch",
Repo: apiRepo, Repo: apiRepo,
@ -526,8 +526,8 @@ func CommitRepoAction(opts CommitRepoActionOptions) error {
}) })
} }
case ACTION_PUSH_TAG: // Create case ActionPushTag: // Create
return PrepareWebhooks(repo, HOOK_EVENT_CREATE, &api.CreatePayload{ return PrepareWebhooks(repo, HookEventCreate, &api.CreatePayload{
Ref: refName, Ref: refName,
RefType: "tag", RefType: "tag",
Repo: apiRepo, Repo: apiRepo,
@ -542,7 +542,7 @@ func transferRepoAction(e Engine, doer, oldOwner *User, repo *Repository) (err e
if err = notifyWatchers(e, &Action{ if err = notifyWatchers(e, &Action{
ActUserID: doer.ID, ActUserID: doer.ID,
ActUserName: doer.Name, ActUserName: doer.Name,
OpType: ACTION_TRANSFER_REPO, OpType: ActionTransferRepo,
RepoID: repo.ID, RepoID: repo.ID,
RepoUserName: repo.Owner.Name, RepoUserName: repo.Owner.Name,
RepoName: repo.Name, RepoName: repo.Name,
@ -572,7 +572,7 @@ func mergePullRequestAction(e Engine, doer *User, repo *Repository, issue *Issue
return notifyWatchers(e, &Action{ return notifyWatchers(e, &Action{
ActUserID: doer.ID, ActUserID: doer.ID,
ActUserName: doer.Name, ActUserName: doer.Name,
OpType: ACTION_MERGE_PULL_REQUEST, OpType: ActionMergePullRequest,
Content: fmt.Sprintf("%d|%s", issue.Index, issue.Title), Content: fmt.Sprintf("%d|%s", issue.Index, issue.Title),
RepoID: repo.ID, RepoID: repo.ID,
RepoUserName: repo.Owner.Name, RepoUserName: repo.Owner.Name,

View file

@ -22,7 +22,7 @@ import (
type NoticeType int type NoticeType int
const ( const (
NOTICE_REPOSITORY NoticeType = iota + 1 NoticeRepository NoticeType = iota + 1
) )
// Notice represents a system notice for admin. // Notice represents a system notice for admin.
@ -65,9 +65,9 @@ func CreateNotice(tp NoticeType, desc string) error {
return err return err
} }
// CreateRepositoryNotice creates new system notice with type NOTICE_REPOSITORY. // CreateRepositoryNotice creates new system notice with type NoticeRepository.
func CreateRepositoryNotice(desc string) error { func CreateRepositoryNotice(desc string) error {
return CreateNotice(NOTICE_REPOSITORY, desc) return CreateNotice(NoticeRepository, desc)
} }
// RemoveAllWithNotice removes all directories in given path and // RemoveAllWithNotice removes all directories in given path and

View file

@ -31,19 +31,19 @@ import (
type DiffLineType uint8 type DiffLineType uint8
const ( const (
DIFF_LINE_PLAIN DiffLineType = iota + 1 DiffLinePlain DiffLineType = iota + 1
DIFF_LINE_ADD DiffLineAdd
DIFF_LINE_DEL DiffLineDel
DIFF_LINE_SECTION DiffLineSection
) )
type DiffFileType uint8 type DiffFileType uint8
const ( const (
DIFF_FILE_ADD DiffFileType = iota + 1 DiffFileAdd DiffFileType = iota + 1
DIFF_FILE_CHANGE DiffFileChange
DIFF_FILE_DEL DiffFileDel
DIFF_FILE_RENAME DiffFileRename
) )
type DiffLine struct { type DiffLine struct {
@ -73,19 +73,19 @@ func diffToHTML(diffs []diffmatchpatch.Diff, lineType DiffLineType) template.HTM
// Reproduce signs which are cutted for inline diff before. // Reproduce signs which are cutted for inline diff before.
switch lineType { switch lineType {
case DIFF_LINE_ADD: case DiffLineAdd:
buf.WriteByte('+') buf.WriteByte('+')
case DIFF_LINE_DEL: case DiffLineDel:
buf.WriteByte('-') buf.WriteByte('-')
} }
for i := range diffs { for i := range diffs {
switch { switch {
case diffs[i].Type == diffmatchpatch.DiffInsert && lineType == DIFF_LINE_ADD: case diffs[i].Type == diffmatchpatch.DiffInsert && lineType == DiffLineAdd:
buf.Write(addedCodePrefix) buf.Write(addedCodePrefix)
buf.WriteString(html.EscapeString(diffs[i].Text)) buf.WriteString(html.EscapeString(diffs[i].Text))
buf.Write(codeTagSuffix) buf.Write(codeTagSuffix)
case diffs[i].Type == diffmatchpatch.DiffDelete && lineType == DIFF_LINE_DEL: case diffs[i].Type == diffmatchpatch.DiffDelete && lineType == DiffLineDel:
buf.Write(removedCodePrefix) buf.Write(removedCodePrefix)
buf.WriteString(html.EscapeString(diffs[i].Text)) buf.WriteString(html.EscapeString(diffs[i].Text))
buf.Write(codeTagSuffix) buf.Write(codeTagSuffix)
@ -109,9 +109,9 @@ func (diffSection *DiffSection) GetLine(lineType DiffLineType, idx int) *DiffLin
LOOP: LOOP:
for _, diffLine := range diffSection.Lines { for _, diffLine := range diffSection.Lines {
switch diffLine.Type { switch diffLine.Type {
case DIFF_LINE_ADD: case DiffLineAdd:
addCount++ addCount++
case DIFF_LINE_DEL: case DiffLineDel:
delCount++ delCount++
default: default:
if matchDiffLine != nil { if matchDiffLine != nil {
@ -123,11 +123,11 @@ LOOP:
} }
switch lineType { switch lineType {
case DIFF_LINE_DEL: case DiffLineDel:
if diffLine.RightIdx == 0 && diffLine.LeftIdx == idx-difference { if diffLine.RightIdx == 0 && diffLine.LeftIdx == idx-difference {
matchDiffLine = diffLine matchDiffLine = diffLine
} }
case DIFF_LINE_ADD: case DiffLineAdd:
if diffLine.LeftIdx == 0 && diffLine.RightIdx == idx+difference { if diffLine.LeftIdx == 0 && diffLine.RightIdx == idx+difference {
matchDiffLine = diffLine matchDiffLine = diffLine
} }
@ -159,15 +159,15 @@ func (diffSection *DiffSection) GetComputedInlineDiffFor(diffLine *DiffLine) tem
// try to find equivalent diff line. ignore, otherwise // try to find equivalent diff line. ignore, otherwise
switch diffLine.Type { switch diffLine.Type {
case DIFF_LINE_ADD: case DiffLineAdd:
compareDiffLine = diffSection.GetLine(DIFF_LINE_DEL, diffLine.RightIdx) compareDiffLine = diffSection.GetLine(DiffLineDel, diffLine.RightIdx)
if compareDiffLine == nil { if compareDiffLine == nil {
return template.HTML(html.EscapeString(diffLine.Content)) return template.HTML(html.EscapeString(diffLine.Content))
} }
diff1 = compareDiffLine.Content diff1 = compareDiffLine.Content
diff2 = diffLine.Content diff2 = diffLine.Content
case DIFF_LINE_DEL: case DiffLineDel:
compareDiffLine = diffSection.GetLine(DIFF_LINE_ADD, diffLine.LeftIdx) compareDiffLine = diffSection.GetLine(DiffLineAdd, diffLine.LeftIdx)
if compareDiffLine == nil { if compareDiffLine == nil {
return template.HTML(html.EscapeString(diffLine.Content)) return template.HTML(html.EscapeString(diffLine.Content))
} }
@ -264,7 +264,7 @@ func ParsePatch(maxLines, maxLineCharacteres, maxFiles int, reader io.Reader) (*
switch { switch {
case line[0] == ' ': case line[0] == ' ':
diffLine := &DiffLine{Type: DIFF_LINE_PLAIN, Content: line, LeftIdx: leftLine, RightIdx: rightLine} diffLine := &DiffLine{Type: DiffLinePlain, Content: line, LeftIdx: leftLine, RightIdx: rightLine}
leftLine++ leftLine++
rightLine++ rightLine++
curSection.Lines = append(curSection.Lines, diffLine) curSection.Lines = append(curSection.Lines, diffLine)
@ -273,7 +273,7 @@ func ParsePatch(maxLines, maxLineCharacteres, maxFiles int, reader io.Reader) (*
curSection = &DiffSection{} curSection = &DiffSection{}
curFile.Sections = append(curFile.Sections, curSection) curFile.Sections = append(curFile.Sections, curSection)
ss := strings.Split(line, "@@") ss := strings.Split(line, "@@")
diffLine := &DiffLine{Type: DIFF_LINE_SECTION, Content: line} diffLine := &DiffLine{Type: DiffLineSection, Content: line}
curSection.Lines = append(curSection.Lines, diffLine) curSection.Lines = append(curSection.Lines, diffLine)
// Parse line number. // Parse line number.
@ -289,14 +289,14 @@ func ParsePatch(maxLines, maxLineCharacteres, maxFiles int, reader io.Reader) (*
case line[0] == '+': case line[0] == '+':
curFile.Addition++ curFile.Addition++
diff.TotalAddition++ diff.TotalAddition++
diffLine := &DiffLine{Type: DIFF_LINE_ADD, Content: line, RightIdx: rightLine} diffLine := &DiffLine{Type: DiffLineAdd, Content: line, RightIdx: rightLine}
rightLine++ rightLine++
curSection.Lines = append(curSection.Lines, diffLine) curSection.Lines = append(curSection.Lines, diffLine)
continue continue
case line[0] == '-': case line[0] == '-':
curFile.Deletion++ curFile.Deletion++
diff.TotalDeletion++ diff.TotalDeletion++
diffLine := &DiffLine{Type: DIFF_LINE_DEL, Content: line, LeftIdx: leftLine} diffLine := &DiffLine{Type: DiffLineDel, Content: line, LeftIdx: leftLine}
if leftLine > 0 { if leftLine > 0 {
leftLine++ leftLine++
} }
@ -330,7 +330,7 @@ func ParsePatch(maxLines, maxLineCharacteres, maxFiles int, reader io.Reader) (*
curFile = &DiffFile{ curFile = &DiffFile{
Name: a, Name: a,
Index: len(diff.Files) + 1, Index: len(diff.Files) + 1,
Type: DIFF_FILE_CHANGE, Type: DiffFileChange,
Sections: make([]*DiffSection, 0, 10), Sections: make([]*DiffSection, 0, 10),
} }
diff.Files = append(diff.Files, curFile) diff.Files = append(diff.Files, curFile)
@ -354,15 +354,15 @@ func ParsePatch(maxLines, maxLineCharacteres, maxFiles int, reader io.Reader) (*
switch { switch {
case strings.HasPrefix(line, "new file"): case strings.HasPrefix(line, "new file"):
curFile.Type = DIFF_FILE_ADD curFile.Type = DiffFileAdd
curFile.IsCreated = true curFile.IsCreated = true
case strings.HasPrefix(line, "deleted"): case strings.HasPrefix(line, "deleted"):
curFile.Type = DIFF_FILE_DEL curFile.Type = DiffFileDel
curFile.IsDeleted = true curFile.IsDeleted = true
case strings.HasPrefix(line, "index"): case strings.HasPrefix(line, "index"):
curFile.Type = DIFF_FILE_CHANGE curFile.Type = DiffFileChange
case strings.HasPrefix(line, "similarity index 100%"): case strings.HasPrefix(line, "similarity index 100%"):
curFile.Type = DIFF_FILE_RENAME curFile.Type = DiffFileRename
curFile.IsRenamed = true curFile.IsRenamed = true
curFile.OldName = curFile.Name curFile.OldName = curFile.Name
curFile.Name = b curFile.Name = b
@ -459,8 +459,8 @@ func GetDiffRange(repoPath, beforeCommitID, afterCommitID string, maxLines, maxL
type RawDiffType string type RawDiffType string
const ( const (
RAW_DIFF_NORMAL RawDiffType = "diff" RawDiffNormal RawDiffType = "diff"
RAW_DIFF_PATCH RawDiffType = "patch" RawDiffPatch RawDiffType = "patch"
) )
// GetRawDiff dumps diff results of repository in given commit ID to io.Writer. // GetRawDiff dumps diff results of repository in given commit ID to io.Writer.
@ -478,14 +478,14 @@ func GetRawDiff(repoPath, commitID string, diffType RawDiffType, writer io.Write
var cmd *exec.Cmd var cmd *exec.Cmd
switch diffType { switch diffType {
case RAW_DIFF_NORMAL: case RawDiffNormal:
if commit.ParentCount() == 0 { if commit.ParentCount() == 0 {
cmd = exec.Command("git", "show", commitID) cmd = exec.Command("git", "show", commitID)
} else { } else {
c, _ := commit.Parent(0) c, _ := commit.Parent(0)
cmd = exec.Command("git", "diff", "-M", c.ID.String(), commitID) cmd = exec.Command("git", "diff", "-M", c.ID.String(), commitID)
} }
case RAW_DIFF_PATCH: case RawDiffPatch:
if commit.ParentCount() == 0 { if commit.ParentCount() == 0 {
cmd = exec.Command("git", "format-patch", "--no-signature", "--stdout", "--root", commitID) cmd = exec.Command("git", "format-patch", "--no-signature", "--stdout", "--root", commitID)
} else { } else {

View file

@ -24,12 +24,12 @@ func TestDiffToHTML(t *testing.T) {
dmp.Diff{dmp.DiffInsert, "bar"}, dmp.Diff{dmp.DiffInsert, "bar"},
dmp.Diff{dmp.DiffDelete, " baz"}, dmp.Diff{dmp.DiffDelete, " baz"},
dmp.Diff{dmp.DiffEqual, " biz"}, dmp.Diff{dmp.DiffEqual, " biz"},
}, DIFF_LINE_ADD)) }, DiffLineAdd))
assertEqual(t, "-foo <span class=\"removed-code\">bar</span> biz", diffToHTML([]dmp.Diff{ assertEqual(t, "-foo <span class=\"removed-code\">bar</span> biz", diffToHTML([]dmp.Diff{
dmp.Diff{dmp.DiffEqual, "foo "}, dmp.Diff{dmp.DiffEqual, "foo "},
dmp.Diff{dmp.DiffDelete, "bar"}, dmp.Diff{dmp.DiffDelete, "bar"},
dmp.Diff{dmp.DiffInsert, " baz"}, dmp.Diff{dmp.DiffInsert, " baz"},
dmp.Diff{dmp.DiffEqual, " biz"}, dmp.Diff{dmp.DiffEqual, " biz"},
}, DIFF_LINE_DEL)) }, DiffLineDel))
} }

View file

@ -239,8 +239,8 @@ func (issue *Issue) sendLabelUpdatedWebhook(doer *User) {
log.Error(4, "LoadIssue: %v", err) log.Error(4, "LoadIssue: %v", err)
return return
} }
err = PrepareWebhooks(issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{ err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
Action: api.HOOK_ISSUE_LABEL_UPDATED, Action: api.HookIssueLabelUpdated,
Index: issue.Index, Index: issue.Index,
PullRequest: issue.PullRequest.APIFormat(), PullRequest: issue.PullRequest.APIFormat(),
Repository: issue.Repo.APIFormat(nil), Repository: issue.Repo.APIFormat(nil),
@ -343,8 +343,8 @@ func (issue *Issue) ClearLabels(doer *User) (err error) {
log.Error(4, "LoadIssue: %v", err) log.Error(4, "LoadIssue: %v", err)
return return
} }
err = PrepareWebhooks(issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{ err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
Action: api.HOOK_ISSUE_LABEL_CLEARED, Action: api.HookIssueLabelCleared,
Index: issue.Index, Index: issue.Index,
PullRequest: issue.PullRequest.APIFormat(), PullRequest: issue.PullRequest.APIFormat(),
Repository: issue.Repo.APIFormat(nil), Repository: issue.Repo.APIFormat(nil),
@ -471,11 +471,11 @@ func (issue *Issue) ChangeStatus(doer *User, repo *Repository, isClosed bool) (e
Sender: doer.APIFormat(), Sender: doer.APIFormat(),
} }
if isClosed { if isClosed {
apiPullRequest.Action = api.HOOK_ISSUE_CLOSED apiPullRequest.Action = api.HookIssueClosed
} else { } else {
apiPullRequest.Action = api.HOOK_ISSUE_REOPENED apiPullRequest.Action = api.HookIssueReopened
} }
err = PrepareWebhooks(repo, HOOK_EVENT_PULL_REQUEST, apiPullRequest) err = PrepareWebhooks(repo, HookEventPullRequest, apiPullRequest)
} }
if err != nil { if err != nil {
log.Error(4, "PrepareWebhooks [is_pull: %v, is_closed: %v]: %v", issue.IsPull, isClosed, err) log.Error(4, "PrepareWebhooks [is_pull: %v, is_closed: %v]: %v", issue.IsPull, isClosed, err)
@ -495,8 +495,8 @@ func (issue *Issue) ChangeTitle(doer *User, title string) (err error) {
if issue.IsPull { if issue.IsPull {
issue.PullRequest.Issue = issue 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, Action: api.HookIssueEdited,
Index: issue.Index, Index: issue.Index,
Changes: &api.ChangesPayload{ Changes: &api.ChangesPayload{
Title: &api.ChangesFromPayload{ Title: &api.ChangesFromPayload{
@ -526,8 +526,8 @@ func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
if issue.IsPull { if issue.IsPull {
issue.PullRequest.Issue = issue 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, Action: api.HookIssueEdited,
Index: issue.Index, Index: issue.Index,
Changes: &api.ChangesPayload{ Changes: &api.ChangesPayload{
Body: &api.ChangesFromPayload{ Body: &api.ChangesFromPayload{
@ -571,11 +571,11 @@ func (issue *Issue) ChangeAssignee(doer *User, assigneeID int64) (err error) {
Sender: doer.APIFormat(), Sender: doer.APIFormat(),
} }
if isRemoveAssignee { if isRemoveAssignee {
apiPullRequest.Action = api.HOOK_ISSUE_UNASSIGNED apiPullRequest.Action = api.HookIssueUnassigned
} else { } else {
apiPullRequest.Action = api.HOOK_ISSUE_ASSIGNED apiPullRequest.Action = api.HookIssueAssigned
} }
err = PrepareWebhooks(issue.Repo, HOOK_EVENT_PULL_REQUEST, apiPullRequest) err = PrepareWebhooks(issue.Repo, HookEventPullRequest, apiPullRequest)
} }
if err != nil { if err != nil {
log.Error(4, "PrepareWebhooks [is_pull: %v, remove_assignee: %v]: %v", issue.IsPull, isRemoveAssignee, err) log.Error(4, "PrepareWebhooks [is_pull: %v, remove_assignee: %v]: %v", issue.IsPull, isRemoveAssignee, err)
@ -624,7 +624,7 @@ func newIssue(e *xorm.Session, opts NewIssueOptions) (err error) {
// Assume assignee is invalid and drop silently. // Assume assignee is invalid and drop silently.
opts.Issue.AssigneeID = 0 opts.Issue.AssigneeID = 0
if assignee != nil { if assignee != nil {
valid, err := hasAccess(e, assignee, opts.Repo, ACCESS_MODE_WRITE) valid, err := hasAccess(e, assignee, opts.Repo, AccessModeWrite)
if err != nil { if err != nil {
return fmt.Errorf("hasAccess [user_id: %d, repo_id: %d]: %v", assignee.ID, opts.Repo.ID, err) return fmt.Errorf("hasAccess [user_id: %d, repo_id: %d]: %v", assignee.ID, opts.Repo.ID, err)
} }
@ -714,7 +714,7 @@ func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string)
if err = NotifyWatchers(&Action{ if err = NotifyWatchers(&Action{
ActUserID: issue.Poster.ID, ActUserID: issue.Poster.ID,
ActUserName: issue.Poster.Name, ActUserName: issue.Poster.Name,
OpType: ACTION_CREATE_ISSUE, OpType: ActionCreateIssue,
Content: fmt.Sprintf("%d|%s", issue.Index, issue.Title), Content: fmt.Sprintf("%d|%s", issue.Index, issue.Title),
RepoID: repo.ID, RepoID: repo.ID,
RepoUserName: repo.Owner.Name, RepoUserName: repo.Owner.Name,
@ -1005,9 +1005,9 @@ func GetIssueUserPairsByMode(uid, rid int64, isClosed bool, page, filterMode int
} }
switch filterMode { switch filterMode {
case FM_ASSIGN: case FilterModeAssign:
sess.And("is_assigned=?", true) sess.And("is_assigned=?", true)
case FM_CREATE: case FilterModeCreate:
sess.And("is_poster=?", true) sess.And("is_poster=?", true)
default: default:
return ius, nil return ius, nil
@ -1070,10 +1070,10 @@ type IssueStats struct {
// Filter modes. // Filter modes.
const ( const (
FM_ALL = iota FilterModeAll = iota
FM_ASSIGN FilterModeAssign
FM_CREATE FilterModeCreate
FM_MENTION FilterModeMention
) )
func parseCountResult(results []map[string][]byte) int64 { func parseCountResult(results []map[string][]byte) int64 {
@ -1122,7 +1122,7 @@ func GetIssueStats(opts *IssueStatsOptions) *IssueStats {
} }
switch opts.FilterMode { switch opts.FilterMode {
case FM_ALL, FM_ASSIGN: case FilterModeAll, FilterModeAssign:
stats.OpenCount, _ = countSession(opts). stats.OpenCount, _ = countSession(opts).
And("is_closed = ?", false). And("is_closed = ?", false).
Count(&Issue{}) Count(&Issue{})
@ -1130,7 +1130,7 @@ func GetIssueStats(opts *IssueStatsOptions) *IssueStats {
stats.ClosedCount, _ = countSession(opts). stats.ClosedCount, _ = countSession(opts).
And("is_closed = ?", true). And("is_closed = ?", true).
Count(&Issue{}) Count(&Issue{})
case FM_CREATE: case FilterModeCreate:
stats.OpenCount, _ = countSession(opts). stats.OpenCount, _ = countSession(opts).
And("poster_id = ?", opts.UserID). And("poster_id = ?", opts.UserID).
And("is_closed = ?", false). And("is_closed = ?", false).
@ -1140,7 +1140,7 @@ func GetIssueStats(opts *IssueStatsOptions) *IssueStats {
And("poster_id = ?", opts.UserID). And("poster_id = ?", opts.UserID).
And("is_closed = ?", true). And("is_closed = ?", true).
Count(&Issue{}) Count(&Issue{})
case FM_MENTION: case FilterModeMention:
stats.OpenCount, _ = countSession(opts). stats.OpenCount, _ = countSession(opts).
Join("INNER", "issue_user", "issue.id = issue_user.issue_id"). Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
And("issue_user.uid = ?", opts.UserID). And("issue_user.uid = ?", opts.UserID).
@ -1186,10 +1186,10 @@ func GetUserIssueStats(repoID, uid int64, repoIDs []int64, filterMode int, isPul
closedCountSession := countSession(true, isPull, repoID, repoIDs) closedCountSession := countSession(true, isPull, repoID, repoIDs)
switch filterMode { switch filterMode {
case FM_ASSIGN: case FilterModeAssign:
openCountSession.And("assignee_id = ?", uid) openCountSession.And("assignee_id = ?", uid)
closedCountSession.And("assignee_id = ?", uid) closedCountSession.And("assignee_id = ?", uid)
case FM_CREATE: case FilterModeCreate:
openCountSession.And("poster_id = ?", uid) openCountSession.And("poster_id = ?", uid)
closedCountSession.And("poster_id = ?", uid) closedCountSession.And("poster_id = ?", uid)
} }
@ -1214,10 +1214,10 @@ func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen
closedCountSession := countSession(true, isPull, repoID) closedCountSession := countSession(true, isPull, repoID)
switch filterMode { switch filterMode {
case FM_ASSIGN: case FilterModeAssign:
openCountSession.And("assignee_id = ?", uid) openCountSession.And("assignee_id = ?", uid)
closedCountSession.And("assignee_id = ?", uid) closedCountSession.And("assignee_id = ?", uid)
case FM_CREATE: case FilterModeCreate:
openCountSession.And("poster_id = ?", uid) openCountSession.And("poster_id = ?", uid)
closedCountSession.And("poster_id = ?", uid) closedCountSession.And("poster_id = ?", uid)
} }

View file

@ -23,27 +23,27 @@ type CommentType int
const ( const (
// Plain comment, can be associated with a commit (CommitID > 0) and a line (LineNum > 0) // Plain comment, can be associated with a commit (CommitID > 0) and a line (LineNum > 0)
COMMENT_TYPE_COMMENT CommentType = iota CommentTypeComment CommentType = iota
COMMENT_TYPE_REOPEN CommentTypeReopen
COMMENT_TYPE_CLOSE CommentTypeClose
// References. // References.
COMMENT_TYPE_ISSUE_REF CommentTypeIssueRef
// Reference from a commit (not part of a pull request) // Reference from a commit (not part of a pull request)
COMMENT_TYPE_COMMIT_REF CommentTypeCommitRef
// Reference from a comment // Reference from a comment
COMMENT_TYPE_COMMENT_REF CommentTypeComment_REF
// Reference from a pull request // Reference from a pull request
COMMENT_TYPE_PULL_REF CommentTypePullRef
) )
type CommentTag int type CommentTag int
const ( const (
COMMENT_TAG_NONE CommentTag = iota CommentTagNone CommentTag = iota
COMMENT_TAG_POSTER CommentTagPoster
COMMENT_TAG_WRITER CommentTagWriter
COMMENT_TAG_OWNER CommentTagOwner
) )
// Comment represents a comment in commit and issue page. // Comment represents a comment in commit and issue page.
@ -144,11 +144,11 @@ func (cmt *Comment) MailParticipants(opType ActionType, issue *Issue) (err error
} }
switch opType { switch opType {
case ACTION_COMMENT_ISSUE: case ActionCommentIssue:
issue.Content = cmt.Content issue.Content = cmt.Content
case ACTION_CLOSE_ISSUE: case ActionCloseIssue:
issue.Content = fmt.Sprintf("Closed #%d", issue.Index) issue.Content = fmt.Sprintf("Closed #%d", issue.Index)
case ACTION_REOPEN_ISSUE: case ActionReopenIssue:
issue.Content = fmt.Sprintf("Reopened #%d", issue.Index) issue.Content = fmt.Sprintf("Reopened #%d", issue.Index)
} }
if err = mailIssueCommentToParticipants(issue, cmt.Poster, mentions); err != nil { if err = mailIssueCommentToParticipants(issue, cmt.Poster, mentions); err != nil {
@ -187,8 +187,8 @@ func createComment(e *xorm.Session, opts *CreateCommentOptions) (_ *Comment, err
// Check comment type. // Check comment type.
switch opts.Type { switch opts.Type {
case COMMENT_TYPE_COMMENT: case CommentTypeComment:
act.OpType = ACTION_COMMENT_ISSUE act.OpType = ActionCommentIssue
if _, err = e.Exec("UPDATE `issue` SET num_comments=num_comments+1 WHERE id=?", opts.Issue.ID); err != nil { if _, err = e.Exec("UPDATE `issue` SET num_comments=num_comments+1 WHERE id=?", opts.Issue.ID); err != nil {
return nil, err return nil, err
@ -216,10 +216,10 @@ func createComment(e *xorm.Session, opts *CreateCommentOptions) (_ *Comment, err
} }
} }
case COMMENT_TYPE_REOPEN: case CommentTypeReopen:
act.OpType = ACTION_REOPEN_ISSUE act.OpType = ActionReopenIssue
if opts.Issue.IsPull { if opts.Issue.IsPull {
act.OpType = ACTION_REOPEN_PULL_REQUEST act.OpType = ActionReopenPullRequest
} }
if opts.Issue.IsPull { if opts.Issue.IsPull {
@ -231,10 +231,10 @@ func createComment(e *xorm.Session, opts *CreateCommentOptions) (_ *Comment, err
return nil, err return nil, err
} }
case COMMENT_TYPE_CLOSE: case CommentTypeClose:
act.OpType = ACTION_CLOSE_ISSUE act.OpType = ActionCloseIssue
if opts.Issue.IsPull { if opts.Issue.IsPull {
act.OpType = ACTION_CLOSE_PULL_REQUEST act.OpType = ActionClosePullRequest
} }
if opts.Issue.IsPull { if opts.Issue.IsPull {
@ -260,9 +260,9 @@ func createComment(e *xorm.Session, opts *CreateCommentOptions) (_ *Comment, err
} }
func createStatusComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue) (*Comment, error) { func createStatusComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue) (*Comment, error) {
cmtType := COMMENT_TYPE_CLOSE cmtType := CommentTypeClose
if !issue.IsClosed { if !issue.IsClosed {
cmtType = COMMENT_TYPE_REOPEN cmtType = CommentTypeReopen
} }
return createComment(e, &CreateCommentOptions{ return createComment(e, &CreateCommentOptions{
Type: cmtType, Type: cmtType,
@ -304,7 +304,7 @@ func CreateComment(opts *CreateCommentOptions) (comment *Comment, err error) {
// CreateIssueComment creates a plain issue comment. // CreateIssueComment creates a plain issue comment.
func CreateIssueComment(doer *User, repo *Repository, issue *Issue, content string, attachments []string) (*Comment, error) { func CreateIssueComment(doer *User, repo *Repository, issue *Issue, content string, attachments []string) (*Comment, error) {
return CreateComment(&CreateCommentOptions{ return CreateComment(&CreateCommentOptions{
Type: COMMENT_TYPE_COMMENT, Type: CommentTypeComment,
Doer: doer, Doer: doer,
Repo: repo, Repo: repo,
Issue: issue, Issue: issue,
@ -321,7 +321,7 @@ func CreateRefComment(doer *User, repo *Repository, issue *Issue, content, commi
// Check if same reference from same commit has already existed. // Check if same reference from same commit has already existed.
has, err := x.Get(&Comment{ has, err := x.Get(&Comment{
Type: COMMENT_TYPE_COMMIT_REF, Type: CommentTypeCommitRef,
IssueID: issue.ID, IssueID: issue.ID,
CommitSHA: commitSHA, CommitSHA: commitSHA,
}) })
@ -332,7 +332,7 @@ func CreateRefComment(doer *User, repo *Repository, issue *Issue, content, commi
} }
_, err = CreateComment(&CreateCommentOptions{ _, err = CreateComment(&CreateCommentOptions{
Type: COMMENT_TYPE_COMMIT_REF, Type: CommentTypeCommitRef,
Doer: doer, Doer: doer,
Repo: repo, Repo: repo,
Issue: issue, Issue: issue,
@ -403,7 +403,7 @@ func DeleteCommentByID(id int64) error {
return err 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 { if _, err = sess.Exec("UPDATE `issue` SET num_comments = num_comments - 1 WHERE id = ?", comment.IssueID); err != nil {
return err return err
} }

View file

@ -28,25 +28,25 @@ type LoginType int
// Note: new type must append to the end of list to maintain compatibility. // Note: new type must append to the end of list to maintain compatibility.
const ( const (
LOGIN_NOTYPE LoginType = iota LoginNotype LoginType = iota
LOGIN_PLAIN // 1 LoginPlain // 1
LOGIN_LDAP // 2 LoginLdap // 2
LOGIN_SMTP // 3 LoginSmtp // 3
LOGIN_PAM // 4 LoginPam // 4
LOGIN_DLDAP // 5 LoginDldap // 5
) )
var LoginNames = map[LoginType]string{ var LoginNames = map[LoginType]string{
LOGIN_LDAP: "LDAP (via BindDN)", LoginLdap: "LDAP (via BindDN)",
LOGIN_DLDAP: "LDAP (simple auth)", // Via direct bind LoginDldap: "LDAP (simple auth)", // Via direct bind
LOGIN_SMTP: "SMTP", LoginSmtp: "SMTP",
LOGIN_PAM: "PAM", LoginPam: "PAM",
} }
var SecurityProtocolNames = map[ldap.SecurityProtocol]string{ var SecurityProtocolNames = map[ldap.SecurityProtocol]string{
ldap.SECURITY_PROTOCOL_UNENCRYPTED: "Unencrypted", ldap.SecurityProtocolUnencrypted: "Unencrypted",
ldap.SECURITY_PROTOCOL_LDAPS: "LDAPS", ldap.SecurityProtocolLdaps: "LDAPS",
ldap.SECURITY_PROTOCOL_START_TLS: "StartTLS", ldap.SecurityProtocolStartTls: "StartTLS",
} }
// Ensure structs implemented interface. // Ensure structs implemented interface.
@ -139,11 +139,11 @@ func (source *LoginSource) BeforeSet(colName string, val xorm.Cell) {
switch colName { switch colName {
case "type": case "type":
switch LoginType(Cell2Int64(val)) { switch LoginType(Cell2Int64(val)) {
case LOGIN_LDAP, LOGIN_DLDAP: case LoginLdap, LoginDldap:
source.Cfg = new(LDAPConfig) source.Cfg = new(LDAPConfig)
case LOGIN_SMTP: case LoginSmtp:
source.Cfg = new(SMTPConfig) source.Cfg = new(SMTPConfig)
case LOGIN_PAM: case LoginPam:
source.Cfg = new(PAMConfig) source.Cfg = new(PAMConfig)
default: default:
panic("unrecognized login source type: " + com.ToStr(*val)) panic("unrecognized login source type: " + com.ToStr(*val))
@ -165,32 +165,32 @@ func (source *LoginSource) TypeName() string {
} }
func (source *LoginSource) IsLDAP() bool { func (source *LoginSource) IsLDAP() bool {
return source.Type == LOGIN_LDAP return source.Type == LoginLdap
} }
func (source *LoginSource) IsDLDAP() bool { func (source *LoginSource) IsDLDAP() bool {
return source.Type == LOGIN_DLDAP return source.Type == LoginDldap
} }
func (source *LoginSource) IsSMTP() bool { func (source *LoginSource) IsSMTP() bool {
return source.Type == LOGIN_SMTP return source.Type == LoginSmtp
} }
func (source *LoginSource) IsPAM() bool { func (source *LoginSource) IsPAM() bool {
return source.Type == LOGIN_PAM return source.Type == LoginPam
} }
func (source *LoginSource) HasTLS() bool { func (source *LoginSource) HasTLS() bool {
return ((source.IsLDAP() || source.IsDLDAP()) && return ((source.IsLDAP() || source.IsDLDAP()) &&
source.LDAP().SecurityProtocol > ldap.SECURITY_PROTOCOL_UNENCRYPTED) || source.LDAP().SecurityProtocol > ldap.SecurityProtocolUnencrypted) ||
source.IsSMTP() source.IsSMTP()
} }
func (source *LoginSource) UseTLS() bool { func (source *LoginSource) UseTLS() bool {
switch source.Type { switch source.Type {
case LOGIN_LDAP, LOGIN_DLDAP: case LoginLdap, LoginDldap:
return source.LDAP().SecurityProtocol != ldap.SECURITY_PROTOCOL_UNENCRYPTED return source.LDAP().SecurityProtocol != ldap.SecurityProtocolUnencrypted
case LOGIN_SMTP: case LoginSmtp:
return source.SMTP().TLS return source.SMTP().TLS
} }
@ -199,9 +199,9 @@ func (source *LoginSource) UseTLS() bool {
func (source *LoginSource) SkipVerify() bool { func (source *LoginSource) SkipVerify() bool {
switch source.Type { switch source.Type {
case LOGIN_LDAP, LOGIN_DLDAP: case LoginLdap, LoginDldap:
return source.LDAP().SkipVerify return source.LDAP().SkipVerify
case LOGIN_SMTP: case LoginSmtp:
return source.SMTP().SkipVerify return source.SMTP().SkipVerify
} }
@ -293,7 +293,7 @@ func composeFullName(firstname, surname, username string) string {
// LoginViaLDAP queries if login/password is valid against the LDAP directory pool, // LoginViaLDAP queries if login/password is valid against the LDAP directory pool,
// and create a local user if success when enabled. // and create a local user if success when enabled.
func LoginViaLDAP(user *User, login, passowrd string, source *LoginSource, autoRegister bool) (*User, error) { func LoginViaLDAP(user *User, login, passowrd string, source *LoginSource, autoRegister bool) (*User, error) {
username, fn, sn, mail, isAdmin, succeed := source.Cfg.(*LDAPConfig).SearchEntry(login, passowrd, source.Type == LOGIN_DLDAP) username, fn, sn, mail, isAdmin, succeed := source.Cfg.(*LDAPConfig).SearchEntry(login, passowrd, source.Type == LoginDldap)
if !succeed { if !succeed {
// User not in LDAP, do nothing // User not in LDAP, do nothing
return nil, ErrUserNotExist{0, login} return nil, ErrUserNotExist{0, login}
@ -358,11 +358,11 @@ func (auth *smtpLoginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
} }
const ( const (
SMTP_PLAIN = "PLAIN" SmtpPlain = "PLAIN"
SMTP_LOGIN = "LOGIN" SmtpLogin = "LOGIN"
) )
var SMTPAuths = []string{SMTP_PLAIN, SMTP_LOGIN} var SMTPAuths = []string{SmtpPlain, SmtpLogin}
func SMTPAuth(a smtp.Auth, cfg *SMTPConfig) error { func SMTPAuth(a smtp.Auth, cfg *SMTPConfig) error {
c, err := smtp.Dial(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port)) c, err := smtp.Dial(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port))
@ -411,9 +411,9 @@ func LoginViaSMTP(user *User, login, password string, sourceID int64, cfg *SMTPC
} }
var auth smtp.Auth var auth smtp.Auth
if cfg.Auth == SMTP_PLAIN { if cfg.Auth == SmtpPlain {
auth = smtp.PlainAuth("", login, password, cfg.Host) auth = smtp.PlainAuth("", login, password, cfg.Host)
} else if cfg.Auth == SMTP_LOGIN { } else if cfg.Auth == SmtpLogin {
auth = &smtpLoginAuth{login, password} auth = &smtpLoginAuth{login, password}
} else { } else {
return nil, errors.New("Unsupported SMTP auth type") return nil, errors.New("Unsupported SMTP auth type")
@ -445,7 +445,7 @@ func LoginViaSMTP(user *User, login, password string, sourceID int64, cfg *SMTPC
Name: strings.ToLower(username), Name: strings.ToLower(username),
Email: login, Email: login,
Passwd: password, Passwd: password,
LoginType: LOGIN_SMTP, LoginType: LoginSmtp,
LoginSource: sourceID, LoginSource: sourceID,
LoginName: login, LoginName: login,
IsActive: true, IsActive: true,
@ -479,7 +479,7 @@ func LoginViaPAM(user *User, login, password string, sourceID int64, cfg *PAMCon
Name: login, Name: login,
Email: login, Email: login,
Passwd: password, Passwd: password,
LoginType: LOGIN_PAM, LoginType: LoginPam,
LoginSource: sourceID, LoginSource: sourceID,
LoginName: login, LoginName: login,
IsActive: true, IsActive: true,
@ -493,11 +493,11 @@ func ExternalUserLogin(user *User, login, password string, source *LoginSource,
} }
switch source.Type { switch source.Type {
case LOGIN_LDAP, LOGIN_DLDAP: case LoginLdap, LoginDldap:
return LoginViaLDAP(user, login, password, source, autoRegister) return LoginViaLDAP(user, login, password, source, autoRegister)
case LOGIN_SMTP: case LoginSmtp:
return LoginViaSMTP(user, login, password, source.ID, source.Cfg.(*SMTPConfig), autoRegister) 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) return LoginViaPAM(user, login, password, source.ID, source.Cfg.(*PAMConfig), autoRegister)
} }
@ -520,7 +520,7 @@ func UserSignIn(username, passowrd string) (*User, error) {
if hasUser { if hasUser {
switch user.LoginType { switch user.LoginType {
case LOGIN_NOTYPE, LOGIN_PLAIN: case LoginNotype, LoginPlain:
if user.ValidatePassword(passowrd) { if user.ValidatePassword(passowrd) {
return user, nil return user, nil
} }

View file

@ -20,15 +20,15 @@ import (
) )
const ( const (
MAIL_AUTH_ACTIVATE base.TplName = "auth/activate" MailAuthActivate base.TplName = "auth/activate"
MAIL_AUTH_ACTIVATE_EMAIL base.TplName = "auth/activate_email" MailAuthActivateEmail base.TplName = "auth/activate_email"
MAIL_AUTH_RESET_PASSWORD base.TplName = "auth/reset_passwd" MailAuthResetPassword base.TplName = "auth/reset_passwd"
MAIL_AUTH_REGISTER_NOTIFY base.TplName = "auth/register_notify" MailAuthRegisterNotify base.TplName = "auth/register_notify"
MAIL_ISSUE_COMMENT base.TplName = "issue/comment" MailIssueComment base.TplName = "issue/comment"
MAIL_ISSUE_MENTION base.TplName = "issue/mention" MailIssueMention base.TplName = "issue/mention"
MAIL_NOTIFY_COLLABORATOR base.TplName = "notify/collaborator" MailNotifyCollaborator base.TplName = "notify/collaborator"
) )
type MailRender interface { type MailRender interface {
@ -77,11 +77,11 @@ func SendUserMail(c *macaron.Context, u *User, tpl base.TplName, code, subject,
} }
func SendActivateAccountMail(c *macaron.Context, u *User) { func SendActivateAccountMail(c *macaron.Context, u *User) {
SendUserMail(c, u, MAIL_AUTH_ACTIVATE, u.GenerateActivateCode(), c.Tr("mail.activate_account"), "activate account") SendUserMail(c, u, MailAuthActivate, u.GenerateActivateCode(), c.Tr("mail.activate_account"), "activate account")
} }
func SendResetPasswordMail(c *macaron.Context, u *User) { func SendResetPasswordMail(c *macaron.Context, u *User) {
SendUserMail(c, u, MAIL_AUTH_RESET_PASSWORD, u.GenerateActivateCode(), c.Tr("mail.reset_password"), "reset password") SendUserMail(c, u, MailAuthResetPassword, u.GenerateActivateCode(), c.Tr("mail.reset_password"), "reset password")
} }
// SendActivateAccountMail sends confirmation email. // SendActivateAccountMail sends confirmation email.
@ -92,7 +92,7 @@ func SendActivateEmailMail(c *macaron.Context, u *User, email *EmailAddress) {
"Code": u.GenerateEmailActivateCode(email.Email), "Code": u.GenerateEmailActivateCode(email.Email),
"Email": email.Email, "Email": email.Email,
} }
body, err := mailRender.HTMLString(string(MAIL_AUTH_ACTIVATE_EMAIL), data) body, err := mailRender.HTMLString(string(MailAuthActivateEmail), data)
if err != nil { if err != nil {
log.Error(3, "HTMLString: %v", err) log.Error(3, "HTMLString: %v", err)
return return
@ -109,7 +109,7 @@ func SendRegisterNotifyMail(c *macaron.Context, u *User) {
data := map[string]interface{}{ data := map[string]interface{}{
"Username": u.DisplayName(), "Username": u.DisplayName(),
} }
body, err := mailRender.HTMLString(string(MAIL_AUTH_REGISTER_NOTIFY), data) body, err := mailRender.HTMLString(string(MailAuthRegisterNotify), data)
if err != nil { if err != nil {
log.Error(3, "HTMLString: %v", err) log.Error(3, "HTMLString: %v", err)
return return
@ -131,7 +131,7 @@ func SendCollaboratorMail(u, doer *User, repo *Repository) {
"RepoName": repoName, "RepoName": repoName,
"Link": repo.HTMLURL(), "Link": repo.HTMLURL(),
} }
body, err := mailRender.HTMLString(string(MAIL_NOTIFY_COLLABORATOR), data) body, err := mailRender.HTMLString(string(MailNotifyCollaborator), data)
if err != nil { if err != nil {
log.Error(3, "HTMLString: %v", err) log.Error(3, "HTMLString: %v", err)
return return
@ -171,7 +171,7 @@ func SendIssueCommentMail(issue *Issue, doer *User, tos []string) {
return return
} }
mailer.SendAsync(composeIssueMessage(issue, doer, MAIL_ISSUE_COMMENT, tos, "issue comment")) mailer.SendAsync(composeIssueMessage(issue, doer, MailIssueComment, tos, "issue comment"))
} }
// SendIssueMentionMail composes and sends issue mention emails to target receivers. // SendIssueMentionMail composes and sends issue mention emails to target receivers.
@ -179,5 +179,5 @@ func SendIssueMentionMail(issue *Issue, doer *User, tos []string) {
if len(tos) == 0 { if len(tos) == 0 {
return return
} }
mailer.SendAsync(composeIssueMessage(issue, doer, MAIL_ISSUE_MENTION, tos, "issue mention")) mailer.SendAsync(composeIssueMessage(issue, doer, MailIssueMention, tos, "issue mention"))
} }

View file

@ -141,7 +141,7 @@ func CreateOrganization(org, owner *User) (err error) {
OrgID: org.ID, OrgID: org.ID,
LowerName: strings.ToLower(OWNER_TEAM), LowerName: strings.ToLower(OWNER_TEAM),
Name: OWNER_TEAM, Name: OWNER_TEAM,
Authorize: ACCESS_MODE_OWNER, Authorize: AccessModeOwner,
NumMembers: 1, NumMembers: 1,
} }
if _, err = sess.Insert(t); err != nil { if _, err = sess.Insert(t); err != nil {
@ -170,7 +170,7 @@ func GetOrgByName(name string) (*User, error) {
} }
u := &User{ u := &User{
LowerName: strings.ToLower(name), LowerName: strings.ToLower(name),
Type: USER_TYPE_ORGANIZATION, Type: UserTypeOrganization,
} }
has, err := x.Get(u) has, err := x.Get(u)
if err != nil { if err != nil {

View file

@ -155,7 +155,7 @@ func (t *Team) removeRepository(e Engine, repo *Repository, recalculate bool) (e
return fmt.Errorf("get team members: %v", err) return fmt.Errorf("get team members: %v", err)
} }
for _, u := range t.Members { for _, u := range t.Members {
has, err := hasAccess(e, u, repo, ACCESS_MODE_READ) has, err := hasAccess(e, u, repo, AccessModeRead)
if err != nil { if err != nil {
return err return err
} else if has { } else if has {

View file

@ -26,16 +26,16 @@ var PullRequestQueue = sync.NewUniqueQueue(setting.Repository.PullRequestQueueLe
type PullRequestType int type PullRequestType int
const ( const (
PULL_REQUEST_GITEA PullRequestType = iota PullRequestGitea PullRequestType = iota
PULL_REQUEST_GIT PullRequestGit
) )
type PullRequestStatus int type PullRequestStatus int
const ( const (
PULL_REQUEST_STATUS_CONFLICT PullRequestStatus = iota PullRequestStatusConflict PullRequestStatus = iota
PULL_REQUEST_STATUS_CHECKING PullRequestStatusChecking
PULL_REQUEST_STATUS_MERGEABLE PullRequestStatusMergeable
) )
// PullRequest represents relation between pull request and repositories. // PullRequest represents relation between pull request and repositories.
@ -129,8 +129,8 @@ func (pr *PullRequest) APIFormat() *api.PullRequest {
HasMerged: pr.HasMerged, HasMerged: pr.HasMerged,
} }
if pr.Status != PULL_REQUEST_STATUS_CHECKING { if pr.Status != PullRequestStatusChecking {
mergeable := pr.Status != PULL_REQUEST_STATUS_CONFLICT mergeable := pr.Status != PullRequestStatusConflict
apiPullRequest.Mergeable = &mergeable apiPullRequest.Mergeable = &mergeable
} }
if pr.HasMerged { if pr.HasMerged {
@ -168,12 +168,12 @@ func (pr *PullRequest) GetBaseRepo() (err error) {
// IsChecking returns true if this pull request is still checking conflict. // IsChecking returns true if this pull request is still checking conflict.
func (pr *PullRequest) IsChecking() bool { 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. // CanAutoMerge returns true if this pull request can be merged automatically.
func (pr *PullRequest) CanAutoMerge() bool { func (pr *PullRequest) CanAutoMerge() bool {
return pr.Status == PULL_REQUEST_STATUS_MERGEABLE return pr.Status == PullRequestStatusMergeable
} }
// Merge merges pull request to base repository. // Merge merges pull request to base repository.
@ -285,8 +285,8 @@ func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository) (err error
log.Error(4, "LoadAttributes: %v", err) log.Error(4, "LoadAttributes: %v", err)
return nil 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, Action: api.HookIssueClosed,
Index: pr.Index, Index: pr.Index,
PullRequest: pr.APIFormat(), PullRequest: pr.APIFormat(),
Repository: pr.Issue.Repo.APIFormat(nil), Repository: pr.Issue.Repo.APIFormat(nil),
@ -323,7 +323,7 @@ func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository) (err error
Pusher: pr.HeadRepo.MustOwner().APIFormat(), Pusher: pr.HeadRepo.MustOwner().APIFormat(),
Sender: doer.APIFormat(), Sender: doer.APIFormat(),
} }
if err = PrepareWebhooks(pr.BaseRepo, HOOK_EVENT_PUSH, p); err != nil { if err = PrepareWebhooks(pr.BaseRepo, HookEventPush, p); err != nil {
return fmt.Errorf("PrepareWebhooks: %v", err) return fmt.Errorf("PrepareWebhooks: %v", err)
} }
return nil return nil
@ -367,7 +367,7 @@ func (pr *PullRequest) testPatch() (err error) {
return fmt.Errorf("UpdateLocalCopy: %v", err) return fmt.Errorf("UpdateLocalCopy: %v", err)
} }
pr.Status = PULL_REQUEST_STATUS_CHECKING pr.Status = PullRequestStatusChecking
_, stderr, err := process.ExecDir(-1, pr.BaseRepo.LocalCopyPath(), _, stderr, err := process.ExecDir(-1, pr.BaseRepo.LocalCopyPath(),
fmt.Sprintf("testPatch (git apply --check): %d", pr.BaseRepo.ID), fmt.Sprintf("testPatch (git apply --check): %d", pr.BaseRepo.ID),
"git", "apply", "--check", patchPath) "git", "apply", "--check", patchPath)
@ -376,7 +376,7 @@ func (pr *PullRequest) testPatch() (err error) {
if strings.Contains(stderr, patchConflicts[i]) { if strings.Contains(stderr, patchConflicts[i]) {
log.Trace("PullRequest[%d].testPatch (apply): has conflit", pr.ID) log.Trace("PullRequest[%d].testPatch (apply): has conflit", pr.ID)
fmt.Println(stderr) fmt.Println(stderr)
pr.Status = PULL_REQUEST_STATUS_CONFLICT pr.Status = PullRequestStatusConflict
return nil return nil
} }
} }
@ -414,8 +414,8 @@ func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []str
return fmt.Errorf("testPatch: %v", err) return fmt.Errorf("testPatch: %v", err)
} }
// No conflict appears after test means mergeable. // No conflict appears after test means mergeable.
if pr.Status == PULL_REQUEST_STATUS_CHECKING { if pr.Status == PullRequestStatusChecking {
pr.Status = PULL_REQUEST_STATUS_MERGEABLE pr.Status = PullRequestStatusMergeable
} }
pr.IssueID = pull.ID pr.IssueID = pull.ID
@ -430,7 +430,7 @@ func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []str
if err = NotifyWatchers(&Action{ if err = NotifyWatchers(&Action{
ActUserID: pull.Poster.ID, ActUserID: pull.Poster.ID,
ActUserName: pull.Poster.Name, ActUserName: pull.Poster.Name,
OpType: ACTION_CREATE_PULL_REQUEST, OpType: ActionCreatePullRequest,
Content: fmt.Sprintf("%d|%s", pull.Index, pull.Title), Content: fmt.Sprintf("%d|%s", pull.Index, pull.Title),
RepoID: repo.ID, RepoID: repo.ID,
RepoUserName: repo.Owner.Name, RepoUserName: repo.Owner.Name,
@ -444,8 +444,8 @@ func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []str
pr.Issue = pull pr.Issue = pull
pull.PullRequest = pr 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, Action: api.HookIssueOpened,
Index: pull.Index, Index: pull.Index,
PullRequest: pr.APIFormat(), PullRequest: pr.APIFormat(),
Repository: repo.APIFormat(nil), Repository: repo.APIFormat(nil),
@ -618,7 +618,7 @@ func (pr *PullRequest) PushToBaseRepo() (err error) {
// AddToTaskQueue adds itself to pull request test task queue. // AddToTaskQueue adds itself to pull request test task queue.
func (pr *PullRequest) AddToTaskQueue() { func (pr *PullRequest) AddToTaskQueue() {
go PullRequestQueue.AddFunc(pr.ID, func() { go PullRequestQueue.AddFunc(pr.ID, func() {
pr.Status = PULL_REQUEST_STATUS_CHECKING pr.Status = PullRequestStatusChecking
if err := pr.UpdateCols("status"); err != nil { if err := pr.UpdateCols("status"); err != nil {
log.Error(5, "AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err) log.Error(5, "AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
} }
@ -693,8 +693,8 @@ func AddTestPullRequestTask(doer *User, repoID int64, branch string, isSync bool
log.Error(4, "LoadAttributes: %v", err) log.Error(4, "LoadAttributes: %v", err)
continue 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, Action: api.HookIssueSynchronized,
Index: pr.Issue.Index, Index: pr.Issue.Index,
PullRequest: pr.Issue.PullRequest.APIFormat(), PullRequest: pr.Issue.PullRequest.APIFormat(),
Repository: pr.Issue.Repo.APIFormat(nil), Repository: pr.Issue.Repo.APIFormat(nil),
@ -733,8 +733,8 @@ func ChangeUsernameInPullRequests(oldUserName, newUserName string) error {
// and set to be either conflict or mergeable. // and set to be either conflict or mergeable.
func (pr *PullRequest) checkAndUpdateStatus() { func (pr *PullRequest) checkAndUpdateStatus() {
// Status is not changed to conflict means mergeable. // Status is not changed to conflict means mergeable.
if pr.Status == PULL_REQUEST_STATUS_CHECKING { if pr.Status == PullRequestStatusChecking {
pr.Status = PULL_REQUEST_STATUS_MERGEABLE pr.Status = PullRequestStatusMergeable
} }
// Make sure there is no waiting test to process before levaing the checking status. // Make sure there is no waiting test to process before levaing the checking status.
@ -750,7 +750,7 @@ func (pr *PullRequest) checkAndUpdateStatus() {
func TestPullRequests() { func TestPullRequests() {
prs := make([]*PullRequest, 0, 10) prs := make([]*PullRequest, 0, 10)
x.Iterate(PullRequest{ x.Iterate(PullRequest{
Status: PULL_REQUEST_STATUS_CHECKING, Status: PullRequestStatusChecking,
}, },
func(idx int, bean interface{}) error { func(idx int, bean interface{}) error {
pr := bean.(*PullRequest) pr := bean.(*PullRequest)

View file

@ -35,7 +35,7 @@ import (
) )
const ( const (
_TPL_UPDATE_HOOK = "#!/usr/bin/env %s\n%s update $1 $2 $3 --config='%s'\n" tplUpdateHook = "#!/usr/bin/env %s\n%s update $1 $2 $3 --config='%s'\n"
) )
var repoWorkingPool = sync.NewExclusivePool() var repoWorkingPool = sync.NewExclusivePool()
@ -334,7 +334,7 @@ func (repo *Repository) getAssignees(e Engine) (_ []*User, err error) {
} }
accesses := make([]*Access, 0, 10) accesses := make([]*Access, 0, 10)
if err = e.Where("repo_id = ? AND mode >= ?", repo.ID, ACCESS_MODE_WRITE).Find(&accesses); err != nil { if err = e.Where("repo_id = ? AND mode >= ?", repo.ID, AccessModeWrite).Find(&accesses); err != nil {
return nil, err return nil, err
} }
@ -418,7 +418,7 @@ func (repo *Repository) ComposeCompareURL(oldCommitID, newCommitID string) strin
} }
func (repo *Repository) HasAccess(u *User) bool { func (repo *Repository) HasAccess(u *User) bool {
has, _ := HasAccess(u, repo, ACCESS_MODE_READ) has, _ := HasAccess(u, repo, AccessModeRead)
return has return has
} }
@ -706,7 +706,7 @@ func cleanUpMigrateGitConfig(configPath string) error {
func createUpdateHook(repoPath string) error { func createUpdateHook(repoPath string) error {
return git.SetUpdateHook(repoPath, return git.SetUpdateHook(repoPath,
fmt.Sprintf(_TPL_UPDATE_HOOK, setting.ScriptType, "\""+setting.AppPath+"\"", setting.CustomConf)) fmt.Sprintf(tplUpdateHook, setting.ScriptType, "\""+setting.AppPath+"\"", setting.CustomConf))
} }
// Finish migrating repository and/or wiki with things that don't need to be done for mirrors. // Finish migrating repository and/or wiki with things that don't need to be done for mirrors.
@ -1613,18 +1613,18 @@ func RewriteRepositoryUpdateHook() error {
var taskStatusTable = sync.NewStatusTable() var taskStatusTable = sync.NewStatusTable()
const ( const (
_MIRROR_UPDATE = "mirror_update" mirrorUpdate = "mirror_update"
_GIT_FSCK = "git_fsck" gitFsck = "git_fsck"
_CHECK_REPOs = "check_repos" checkRepos = "check_repos"
) )
// GitFsck calls 'git fsck' to check repository health. // GitFsck calls 'git fsck' to check repository health.
func GitFsck() { func GitFsck() {
if taskStatusTable.IsRunning(_GIT_FSCK) { if taskStatusTable.IsRunning(gitFsck) {
return return
} }
taskStatusTable.Start(_GIT_FSCK) taskStatusTable.Start(gitFsck)
defer taskStatusTable.Stop(_GIT_FSCK) defer taskStatusTable.Stop(gitFsck)
log.Trace("Doing: GitFsck") log.Trace("Doing: GitFsck")
@ -1686,11 +1686,11 @@ func repoStatsCheck(checker *repoChecker) {
} }
func CheckRepoStats() { func CheckRepoStats() {
if taskStatusTable.IsRunning(_CHECK_REPOs) { if taskStatusTable.IsRunning(checkRepos) {
return return
} }
taskStatusTable.Start(_CHECK_REPOs) taskStatusTable.Start(checkRepos)
defer taskStatusTable.Stop(_CHECK_REPOs) defer taskStatusTable.Stop(checkRepos)
log.Trace("Doing: CheckRepoStats") log.Trace("Doing: CheckRepoStats")

View file

@ -18,11 +18,11 @@ type Collaboration struct {
func (c *Collaboration) ModeI18nKey() string { func (c *Collaboration) ModeI18nKey() string {
switch c.Mode { switch c.Mode {
case ACCESS_MODE_READ: case AccessModeRead:
return "repo.settings.collaboration.read" return "repo.settings.collaboration.read"
case ACCESS_MODE_WRITE: case AccessModeWrite:
return "repo.settings.collaboration.write" return "repo.settings.collaboration.write"
case ACCESS_MODE_ADMIN: case AccessModeAdmin:
return "repo.settings.collaboration.admin" return "repo.settings.collaboration.admin"
default: default:
return "repo.settings.collaboration.undefined" return "repo.settings.collaboration.undefined"
@ -42,7 +42,7 @@ func (repo *Repository) AddCollaborator(u *User) error {
} else if has { } else if has {
return nil return nil
} }
collaboration.Mode = ACCESS_MODE_WRITE collaboration.Mode = AccessModeWrite
sess := x.NewSession() sess := x.NewSession()
defer sessionRelease(sess) defer sessionRelease(sess)
@ -105,7 +105,7 @@ func (repo *Repository) GetCollaborators() ([]*Collaborator, error) {
// ChangeCollaborationAccessMode sets new access mode for the collaboration. // ChangeCollaborationAccessMode sets new access mode for the collaboration.
func (repo *Repository) ChangeCollaborationAccessMode(uid int64, mode AccessMode) error { func (repo *Repository) ChangeCollaborationAccessMode(uid int64, mode AccessMode) error {
// Discard invalid input // Discard invalid input
if mode <= ACCESS_MODE_NONE || mode > ACCESS_MODE_OWNER { if mode <= AccessModeNone || mode > AccessModeOwner {
return nil return nil
} }

View file

@ -191,11 +191,11 @@ func DeleteMirrorByRepoID(repoID int64) error {
// MirrorUpdate checks and updates mirror repositories. // MirrorUpdate checks and updates mirror repositories.
func MirrorUpdate() { func MirrorUpdate() {
if taskStatusTable.IsRunning(_MIRROR_UPDATE) { if taskStatusTable.IsRunning(mirrorUpdate) {
return return
} }
taskStatusTable.Start(_MIRROR_UPDATE) taskStatusTable.Start(mirrorUpdate)
defer taskStatusTable.Stop(_MIRROR_UPDATE) defer taskStatusTable.Stop(mirrorUpdate)
log.Trace("Doing: MirrorUpdate") log.Trace("Doing: MirrorUpdate")

View file

@ -29,7 +29,7 @@ import (
) )
const ( 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 var sshOpLocker sync.Mutex
@ -37,8 +37,8 @@ var sshOpLocker sync.Mutex
type KeyType int type KeyType int
const ( const (
KEY_TYPE_USER = iota + 1 KeyTypeUser = iota + 1
KEY_TYPE_DEPLOY KeyTypeDeploy
) )
// PublicKey represents a user or deploy SSH public key. // PublicKey represents a user or deploy SSH public key.
@ -85,7 +85,7 @@ func (k *PublicKey) OmitEmail() string {
// AuthorizedString returns formatted public key string for authorized_keys file. // AuthorizedString returns formatted public key string for authorized_keys file.
func (key *PublicKey) AuthorizedString() string { func (key *PublicKey) AuthorizedString() string {
return fmt.Sprintf(_TPL_PUBLICK_KEY, setting.AppPath, key.ID, setting.CustomConf, key.Content) return fmt.Sprintf(tplPublicKey, setting.AppPath, key.ID, setting.CustomConf, key.Content)
} }
func extractTypeFromBase64Key(key string) (string, error) { func extractTypeFromBase64Key(key string) (string, error) {
@ -352,7 +352,7 @@ func appendAuthorizedKeysToFile(keys ...*PublicKey) error {
func checkKeyContent(content string) error { func checkKeyContent(content string) error {
has, err := x.Get(&PublicKey{ has, err := x.Get(&PublicKey{
Content: content, Content: content,
Type: KEY_TYPE_USER, Type: KeyTypeUser,
}) })
if err != nil { if err != nil {
return err return err
@ -415,8 +415,8 @@ func AddPublicKey(ownerID int64, name, content string) (*PublicKey, error) {
OwnerID: ownerID, OwnerID: ownerID,
Name: name, Name: name,
Content: content, Content: content,
Mode: ACCESS_MODE_WRITE, Mode: AccessModeWrite,
Type: KEY_TYPE_USER, Type: KeyTypeUser,
} }
if err = addKey(sess, key); err != nil { if err = addKey(sess, key); err != nil {
return nil, fmt.Errorf("addKey: %v", err) return nil, fmt.Errorf("addKey: %v", err)
@ -642,8 +642,8 @@ func AddDeployKey(repoID int64, name, content string) (*DeployKey, error) {
pkey := &PublicKey{ pkey := &PublicKey{
Content: content, Content: content,
Mode: ACCESS_MODE_READ, Mode: AccessModeRead,
Type: KEY_TYPE_DEPLOY, Type: KeyTypeDeploy,
} }
has, err := x.Get(pkey) has, err := x.Get(pkey)
if err != nil { if err != nil {
@ -720,7 +720,7 @@ func DeleteDeployKey(doer *User, id int64) error {
if err != nil { if err != nil {
return fmt.Errorf("GetRepositoryByID: %v", err) return fmt.Errorf("GetRepositoryByID: %v", err)
} }
yes, err := HasAccess(doer, repo, ACCESS_MODE_ADMIN) yes, err := HasAccess(doer, repo, AccessModeAdmin)
if err != nil { if err != nil {
return fmt.Errorf("HasAccess: %v", err) return fmt.Errorf("HasAccess: %v", err)
} else if !yes { } else if !yes {

View file

@ -37,8 +37,8 @@ import (
type UserType int type UserType int
const ( const (
USER_TYPE_INDIVIDUAL UserType = iota // Historic reason to make it starts at 0. UserTypeIndividual UserType = iota // Historic reason to make it starts at 0.
USER_TYPE_ORGANIZATION UserTypeOrganization
) )
var ( var (
@ -140,9 +140,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 { 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. // HasForkedRepo checks if user has already forked a repository with given ID.
@ -375,7 +375,7 @@ func (u *User) DeleteAvatar() error {
// IsAdminOfRepo returns true if user has admin or higher access of repository. // IsAdminOfRepo returns true if user has admin or higher access of repository.
func (u *User) IsAdminOfRepo(repo *Repository) bool { func (u *User) IsAdminOfRepo(repo *Repository) bool {
has, err := HasAccess(u, repo, ACCESS_MODE_ADMIN) has, err := HasAccess(u, repo, AccessModeAdmin)
if err != nil { if err != nil {
log.Error(3, "HasAccess: %v", err) log.Error(3, "HasAccess: %v", err)
} }
@ -384,7 +384,7 @@ func (u *User) IsAdminOfRepo(repo *Repository) bool {
// IsWriterOfRepo returns true if user has write access to given repository. // IsWriterOfRepo returns true if user has write access to given repository.
func (u *User) IsWriterOfRepo(repo *Repository) bool { func (u *User) IsWriterOfRepo(repo *Repository) bool {
has, err := HasAccess(u, repo, ACCESS_MODE_WRITE) has, err := HasAccess(u, repo, AccessModeWrite)
if err != nil { if err != nil {
log.Error(3, "HasAccess: %v", err) log.Error(3, "HasAccess: %v", err)
} }
@ -393,7 +393,7 @@ func (u *User) IsWriterOfRepo(repo *Repository) bool {
// IsOrganization returns true if user is actually a organization. // IsOrganization returns true if user is actually a organization.
func (u *User) IsOrganization() bool { 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. // IsUserOrgOwner returns true if user is in the owner team of given organization.
@ -886,7 +886,7 @@ func GetUserByID(id int64) (*User, error) {
// GetAssigneeByID returns the user with write access of repository by given ID. // GetAssigneeByID returns the user with write access of repository by given ID.
func GetAssigneeByID(repo *Repository, userID int64) (*User, error) { func GetAssigneeByID(repo *Repository, userID int64) (*User, error) {
has, err := HasAccess(&User{ID: userID}, repo, ACCESS_MODE_WRITE) has, err := HasAccess(&User{ID: userID}, repo, AccessModeWrite)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {

View file

@ -28,13 +28,13 @@ var HookQueue = sync.NewUniqueQueue(setting.Webhook.QueueLength)
type HookContentType int type HookContentType int
const ( const (
JSON HookContentType = iota + 1 ContentTypeJson HookContentType = iota + 1
FORM ContentTypeForm
) )
var hookContentTypes = map[string]HookContentType{ var hookContentTypes = map[string]HookContentType{
"json": JSON, "json": ContentTypeJson,
"form": FORM, "form": ContentTypeForm,
} }
// ToHookContentType returns HookContentType by given name. // ToHookContentType returns HookContentType by given name.
@ -44,9 +44,9 @@ func ToHookContentType(name string) HookContentType {
func (t HookContentType) Name() string { func (t HookContentType) Name() string {
switch t { switch t {
case JSON: case ContentTypeJson:
return "json" return "json"
case FORM: case ContentTypeForm:
return "form" return "form"
} }
return "" return ""
@ -76,9 +76,9 @@ type HookEvent struct {
type HookStatus int type HookStatus int
const ( const (
HOOK_STATUS_NONE = iota HookStatusNone = iota
HOOK_STATUS_SUCCEED HookStatusSucceed
HOOK_STATUS_FAILED HookStatusFail
) )
// Webhook represents a web hook object. // Webhook represents a web hook object.
@ -323,9 +323,9 @@ func IsValidHookTaskType(name string) bool {
type HookEventType string type HookEventType string
const ( const (
HOOK_EVENT_CREATE HookEventType = "create" HookEventCreate HookEventType = "create"
HOOK_EVENT_PUSH HookEventType = "push" HookEventPush HookEventType = "push"
HOOK_EVENT_PULL_REQUEST HookEventType = "pull_request" HookEventPullRequest HookEventType = "pull_request"
) )
// HookRequest represents hook task request information. // HookRequest represents hook task request information.
@ -459,15 +459,15 @@ func PrepareWebhooks(repo *Repository, event HookEventType, p api.Payloader) err
var payloader api.Payloader var payloader api.Payloader
for _, w := range ws { for _, w := range ws {
switch event { switch event {
case HOOK_EVENT_CREATE: case HookEventCreate:
if !w.HasCreateEvent() { if !w.HasCreateEvent() {
continue continue
} }
case HOOK_EVENT_PUSH: case HookEventPush:
if !w.HasPushEvent() { if !w.HasPushEvent() {
continue continue
} }
case HOOK_EVENT_PULL_REQUEST: case HookEventPullRequest:
if !w.HasPullRequestEvent() { if !w.HasPullRequestEvent() {
continue continue
} }
@ -511,9 +511,9 @@ func (t *HookTask) deliver() {
SetTLSClientConfig(&tls.Config{InsecureSkipVerify: setting.Webhook.SkipTLSVerify}) SetTLSClientConfig(&tls.Config{InsecureSkipVerify: setting.Webhook.SkipTLSVerify})
switch t.ContentType { switch t.ContentType {
case JSON: case ContentTypeJson:
req = req.Header("Content-Type", "application/json").Body(t.PayloadContent) req = req.Header("Content-Type", "application/json").Body(t.PayloadContent)
case FORM: case ContentTypeForm:
req.Param("payload", t.PayloadContent) req.Param("payload", t.PayloadContent)
} }
@ -544,9 +544,9 @@ func (t *HookTask) deliver() {
return return
} }
if t.IsSucceed { if t.IsSucceed {
w.LastStatus = HOOK_STATUS_SUCCEED w.LastStatus = HookStatusSucceed
} else { } else {
w.LastStatus = HOOK_STATUS_FAILED w.LastStatus = HookStatusFail
} }
if err = UpdateWebhook(w); err != nil { if err = UpdateWebhook(w); err != nil {
log.Error(5, "UpdateWebhook: %v", err) log.Error(5, "UpdateWebhook: %v", err)

View file

@ -139,32 +139,32 @@ func getSlackPullRequestPayload(p *api.PullRequestPayload, slack *SlackMeta) (*S
fmt.Sprintf("#%d %s", p.Index, p.PullRequest.Title)) fmt.Sprintf("#%d %s", p.Index, p.PullRequest.Title))
var text, title, attachmentText string var text, title, attachmentText string
switch p.Action { switch p.Action {
case api.HOOK_ISSUE_OPENED: case api.HookIssueOpened:
text = fmt.Sprintf("[%s] Pull request submitted by %s", p.Repository.FullName, senderLink) text = fmt.Sprintf("[%s] Pull request submitted by %s", p.Repository.FullName, senderLink)
title = titleLink title = titleLink
attachmentText = SlackTextFormatter(p.PullRequest.Body) attachmentText = SlackTextFormatter(p.PullRequest.Body)
case api.HOOK_ISSUE_CLOSED: case api.HookIssueClosed:
if p.PullRequest.HasMerged { if p.PullRequest.HasMerged {
text = fmt.Sprintf("[%s] Pull request merged: %s by %s", p.Repository.FullName, titleLink, senderLink) text = fmt.Sprintf("[%s] Pull request merged: %s by %s", p.Repository.FullName, titleLink, senderLink)
} else { } else {
text = fmt.Sprintf("[%s] Pull request closed: %s by %s", p.Repository.FullName, titleLink, senderLink) text = fmt.Sprintf("[%s] Pull request closed: %s by %s", p.Repository.FullName, titleLink, senderLink)
} }
case api.HOOK_ISSUE_REOPENED: case api.HookIssueReopened:
text = fmt.Sprintf("[%s] Pull request re-opened: %s by %s", p.Repository.FullName, titleLink, senderLink) text = fmt.Sprintf("[%s] Pull request re-opened: %s by %s", p.Repository.FullName, titleLink, senderLink)
case api.HOOK_ISSUE_EDITED: case api.HookIssueEdited:
text = fmt.Sprintf("[%s] Pull request edited: %s by %s", p.Repository.FullName, titleLink, senderLink) text = fmt.Sprintf("[%s] Pull request edited: %s by %s", p.Repository.FullName, titleLink, senderLink)
attachmentText = SlackTextFormatter(p.PullRequest.Body) attachmentText = SlackTextFormatter(p.PullRequest.Body)
case api.HOOK_ISSUE_ASSIGNED: case api.HookIssueAssigned:
text = fmt.Sprintf("[%s] Pull request assigned to %s: %s by %s", p.Repository.FullName, text = fmt.Sprintf("[%s] Pull request assigned to %s: %s by %s", p.Repository.FullName,
SlackLinkFormatter(setting.AppUrl+p.PullRequest.Assignee.UserName, p.PullRequest.Assignee.UserName), SlackLinkFormatter(setting.AppUrl+p.PullRequest.Assignee.UserName, p.PullRequest.Assignee.UserName),
titleLink, senderLink) titleLink, senderLink)
case api.HOOK_ISSUE_UNASSIGNED: case api.HookIssueUnassigned:
text = fmt.Sprintf("[%s] Pull request unassigned: %s by %s", p.Repository.FullName, titleLink, senderLink) text = fmt.Sprintf("[%s] Pull request unassigned: %s by %s", p.Repository.FullName, titleLink, senderLink)
case api.HOOK_ISSUE_LABEL_UPDATED: case api.HookIssueLabelUpdated:
text = fmt.Sprintf("[%s] Pull request labels updated: %s by %s", p.Repository.FullName, titleLink, senderLink) text = fmt.Sprintf("[%s] Pull request labels updated: %s by %s", p.Repository.FullName, titleLink, senderLink)
case api.HOOK_ISSUE_LABEL_CLEARED: case api.HookIssueLabelCleared:
text = fmt.Sprintf("[%s] Pull request labels cleared: %s by %s", p.Repository.FullName, titleLink, senderLink) text = fmt.Sprintf("[%s] Pull request labels cleared: %s by %s", p.Repository.FullName, titleLink, senderLink)
case api.HOOK_ISSUE_SYNCHRONIZED: case api.HookIssueSynchronized:
text = fmt.Sprintf("[%s] Pull request synchronized: %s by %s", p.Repository.FullName, titleLink, senderLink) text = fmt.Sprintf("[%s] Pull request synchronized: %s by %s", p.Repository.FullName, titleLink, senderLink)
} }
@ -190,11 +190,11 @@ func GetSlackPayload(p api.Payloader, event HookEventType, meta string) (*SlackP
} }
switch event { switch event {
case HOOK_EVENT_CREATE: case HookEventCreate:
return getSlackCreatePayload(p.(*api.CreatePayload), slack) return getSlackCreatePayload(p.(*api.CreatePayload), slack)
case HOOK_EVENT_PUSH: case HookEventPush:
return getSlackPushPayload(p.(*api.PushPayload), slack) return getSlackPushPayload(p.(*api.PushPayload), slack)
case HOOK_EVENT_PULL_REQUEST: case HookEventPullRequest:
return getSlackPullRequestPayload(p.(*api.PullRequestPayload), slack) return getSlackPullRequestPayload(p.(*api.PullRequestPayload), slack)
} }

View file

@ -20,9 +20,9 @@ type SecurityProtocol int
// Note: new type must be added at the end of list to maintain compatibility. // Note: new type must be added at the end of list to maintain compatibility.
const ( const (
SECURITY_PROTOCOL_UNENCRYPTED SecurityProtocol = iota SecurityProtocolUnencrypted SecurityProtocol = iota
SECURITY_PROTOCOL_LDAPS SecurityProtocolLdaps
SECURITY_PROTOCOL_START_TLS SecurityProtocolStartTls
) )
// Basic LDAP authentication service // Basic LDAP authentication service
@ -118,7 +118,7 @@ func dial(ls *Source) (*ldap.Conn, error) {
ServerName: ls.Host, ServerName: ls.Host,
InsecureSkipVerify: ls.SkipVerify, InsecureSkipVerify: ls.SkipVerify,
} }
if ls.SecurityProtocol == SECURITY_PROTOCOL_LDAPS { if ls.SecurityProtocol == SecurityProtocolLdaps {
return ldap.DialTLS("tcp", fmt.Sprintf("%s:%d", ls.Host, ls.Port), tlsCfg) return ldap.DialTLS("tcp", fmt.Sprintf("%s:%d", ls.Host, ls.Port), tlsCfg)
} }
@ -127,7 +127,7 @@ func dial(ls *Source) (*ldap.Conn, error) {
return nil, fmt.Errorf("Dial: %v", err) return nil, fmt.Errorf("Dial: %v", err)
} }
if ls.SecurityProtocol == SECURITY_PROTOCOL_START_TLS { if ls.SecurityProtocol == SecurityProtocolStartTls {
if err = conn.StartTLS(tlsCfg); err != nil { if err = conn.StartTLS(tlsCfg); err != nil {
conn.Close() conn.Close()
return nil, fmt.Errorf("StartTLS: %v", err) return nil, fmt.Errorf("StartTLS: %v", err)

View file

@ -101,8 +101,8 @@ func (f *UpdateProfileForm) Validate(ctx *macaron.Context, errs binding.Errors)
} }
const ( const (
AVATAR_LOCAL string = "local" AvatarLocal string = "local"
AVATAR_BYMAIL string = "bymail" AvatarByMail string = "bymail"
) )
type AvatarForm struct { type AvatarForm struct {

View file

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

View file

@ -51,22 +51,22 @@ type Repository struct {
// IsOwner returns true if current user is the owner of repository. // IsOwner returns true if current user is the owner of repository.
func (r *Repository) IsOwner() bool { 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. // IsAdmin returns true if current user has admin or higher access of repository.
func (r *Repository) IsAdmin() bool { 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. // IsWriter returns true if current user has write or higher access of repository.
func (r *Repository) IsWriter() bool { 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 // HasAccess returns true if the current user has at least read access for this repository
func (r *Repository) HasAccess() bool { 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. // CanEnableEditor returns true if repository is editable and user has proper access level.
@ -192,7 +192,7 @@ func RepoAssignment(args ...bool) macaron.Handler {
// Admin has super access. // Admin has super access.
if ctx.IsSigned && ctx.User.IsAdmin { if ctx.IsSigned && ctx.User.IsAdmin {
ctx.Repo.AccessMode = models.ACCESS_MODE_OWNER ctx.Repo.AccessMode = models.AccessModeOwner
} else { } else {
mode, err := models.AccessLevel(ctx.User, repo) mode, err := models.AccessLevel(ctx.User, repo)
if err != nil { if err != nil {
@ -203,7 +203,7 @@ func RepoAssignment(args ...bool) macaron.Handler {
} }
// Check access. // Check access.
if ctx.Repo.AccessMode == models.ACCESS_MODE_NONE { if ctx.Repo.AccessMode == models.AccessModeNone {
if ctx.Query("go-get") == "1" { if ctx.Query("go-get") == "1" {
earlyResponseForGoGetMeta(ctx) earlyResponseForGoGetMeta(ctx)
return return

View file

@ -48,15 +48,15 @@ type dropdownItem struct {
var ( var (
authSources = []dropdownItem{ authSources = []dropdownItem{
{models.LoginNames[models.LOGIN_LDAP], models.LOGIN_LDAP}, {models.LoginNames[models.LoginLdap], models.LoginLdap},
{models.LoginNames[models.LOGIN_DLDAP], models.LOGIN_DLDAP}, {models.LoginNames[models.LoginDldap], models.LoginDldap},
{models.LoginNames[models.LOGIN_SMTP], models.LOGIN_SMTP}, {models.LoginNames[models.LoginSmtp], models.LoginSmtp},
{models.LoginNames[models.LOGIN_PAM], models.LOGIN_PAM}, {models.LoginNames[models.LoginPam], models.LoginPam},
} }
securityProtocols = []dropdownItem{ securityProtocols = []dropdownItem{
{models.SecurityProtocolNames[ldap.SECURITY_PROTOCOL_UNENCRYPTED], ldap.SECURITY_PROTOCOL_UNENCRYPTED}, {models.SecurityProtocolNames[ldap.SecurityProtocolUnencrypted], ldap.SecurityProtocolUnencrypted},
{models.SecurityProtocolNames[ldap.SECURITY_PROTOCOL_LDAPS], ldap.SECURITY_PROTOCOL_LDAPS}, {models.SecurityProtocolNames[ldap.SecurityProtocolLdaps], ldap.SecurityProtocolLdaps},
{models.SecurityProtocolNames[ldap.SECURITY_PROTOCOL_START_TLS], ldap.SECURITY_PROTOCOL_START_TLS}, {models.SecurityProtocolNames[ldap.SecurityProtocolStartTls], ldap.SecurityProtocolStartTls},
} }
) )
@ -65,9 +65,9 @@ func NewAuthSource(ctx *context.Context) {
ctx.Data["PageIsAdmin"] = true ctx.Data["PageIsAdmin"] = true
ctx.Data["PageIsAdminAuthentications"] = true ctx.Data["PageIsAdminAuthentications"] = true
ctx.Data["type"] = models.LOGIN_LDAP ctx.Data["type"] = models.LoginLdap
ctx.Data["CurrentTypeName"] = models.LoginNames[models.LOGIN_LDAP] ctx.Data["CurrentTypeName"] = models.LoginNames[models.LoginLdap]
ctx.Data["CurrentSecurityProtocol"] = models.SecurityProtocolNames[ldap.SECURITY_PROTOCOL_UNENCRYPTED] ctx.Data["CurrentSecurityProtocol"] = models.SecurityProtocolNames[ldap.SecurityProtocolUnencrypted]
ctx.Data["smtp_auth"] = "PLAIN" ctx.Data["smtp_auth"] = "PLAIN"
ctx.Data["is_active"] = true ctx.Data["is_active"] = true
ctx.Data["AuthSources"] = authSources ctx.Data["AuthSources"] = authSources
@ -125,13 +125,13 @@ func NewAuthSourcePost(ctx *context.Context, form auth.AuthenticationForm) {
hasTLS := false hasTLS := false
var config core.Conversion var config core.Conversion
switch models.LoginType(form.Type) { switch models.LoginType(form.Type) {
case models.LOGIN_LDAP, models.LOGIN_DLDAP: case models.LoginLdap, models.LoginDldap:
config = parseLDAPConfig(form) config = parseLDAPConfig(form)
hasTLS = ldap.SecurityProtocol(form.SecurityProtocol) > ldap.SECURITY_PROTOCOL_UNENCRYPTED hasTLS = ldap.SecurityProtocol(form.SecurityProtocol) > ldap.SecurityProtocolUnencrypted
case models.LOGIN_SMTP: case models.LoginSmtp:
config = parseSMTPConfig(form) config = parseSMTPConfig(form)
hasTLS = true hasTLS = true
case models.LOGIN_PAM: case models.LoginPam:
config = &models.PAMConfig{ config = &models.PAMConfig{
ServiceName: form.PAMServiceName, ServiceName: form.PAMServiceName,
} }
@ -208,11 +208,11 @@ func EditAuthSourcePost(ctx *context.Context, form auth.AuthenticationForm) {
var config core.Conversion var config core.Conversion
switch models.LoginType(form.Type) { switch models.LoginType(form.Type) {
case models.LOGIN_LDAP, models.LOGIN_DLDAP: case models.LoginLdap, models.LoginDldap:
config = parseLDAPConfig(form) config = parseLDAPConfig(form)
case models.LOGIN_SMTP: case models.LoginSmtp:
config = parseSMTPConfig(form) config = parseSMTPConfig(form)
case models.LOGIN_PAM: case models.LoginPam:
config = &models.PAMConfig{ config = &models.PAMConfig{
ServiceName: form.PAMServiceName, ServiceName: form.PAMServiceName,
} }

View file

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

View file

@ -30,7 +30,7 @@ func Users(ctx *context.Context) {
ctx.Data["PageIsAdminUsers"] = true ctx.Data["PageIsAdminUsers"] = true
routers.RenderUserSearch(ctx, &routers.UserSearchOptions{ routers.RenderUserSearch(ctx, &routers.UserSearchOptions{
Type: models.USER_TYPE_INDIVIDUAL, Type: models.UserTypeIndividual,
Counter: models.CountUsers, Counter: models.CountUsers,
Ranger: models.Users, Ranger: models.Users,
PageSize: setting.UI.Admin.UserPagingNum, PageSize: setting.UI.Admin.UserPagingNum,
@ -81,7 +81,7 @@ func NewUserPost(ctx *context.Context, form auth.AdminCrateUserForm) {
Email: form.Email, Email: form.Email,
Passwd: form.Password, Passwd: form.Password,
IsActive: true, IsActive: true,
LoginType: models.LOGIN_PLAIN, LoginType: models.LoginPlain,
} }
if len(form.LoginType) > 0 { if len(form.LoginType) > 0 {

View file

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

View file

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

View file

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

View file

@ -59,9 +59,9 @@ func CreateHook(ctx *context.APIContext, form api.CreateHookOption) {
HookEvent: &models.HookEvent{ HookEvent: &models.HookEvent{
ChooseEvents: true, ChooseEvents: true,
HookEvents: models.HookEvents{ HookEvents: models.HookEvents{
Create: com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_CREATE)), Create: com.IsSliceContainsStr(form.Events, string(models.HookEventCreate)),
Push: com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_PUSH)), Push: com.IsSliceContainsStr(form.Events, string(models.HookEventPush)),
PullRequest: com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_PULL_REQUEST)), PullRequest: com.IsSliceContainsStr(form.Events, string(models.HookEventPullRequest)),
}, },
}, },
IsActive: form.Active, IsActive: form.Active,
@ -145,9 +145,9 @@ func EditHook(ctx *context.APIContext, form api.EditHookOption) {
w.PushOnly = false w.PushOnly = false
w.SendEverything = false w.SendEverything = false
w.ChooseEvents = true w.ChooseEvents = true
w.Create = com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_CREATE)) w.Create = com.IsSliceContainsStr(form.Events, string(models.HookEventCreate))
w.Push = com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_PUSH)) w.Push = com.IsSliceContainsStr(form.Events, string(models.HookEventPush))
w.PullRequest = com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_PULL_REQUEST)) w.PullRequest = com.IsSliceContainsStr(form.Events, string(models.HookEventPullRequest))
if err = w.UpdateEvent(); err != nil { if err = w.UpdateEvent(); err != nil {
ctx.Error(500, "UpdateEvent", err) ctx.Error(500, "UpdateEvent", err)
return return

View file

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

View file

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

View file

@ -16,7 +16,7 @@ import (
func Search(ctx *context.APIContext) { func Search(ctx *context.APIContext) {
opts := &models.SearchUserOptions{ opts := &models.SearchUserOptions{
Keyword: ctx.Query("q"), Keyword: ctx.Query("q"),
Type: models.USER_TYPE_INDIVIDUAL, Type: models.UserTypeIndividual,
PageSize: com.StrTo(ctx.Query("limit")).MustInt(), PageSize: com.StrTo(ctx.Query("limit")).MustInt(),
} }
if opts.PageSize == 0 { if opts.PageSize == 0 {

View file

@ -172,7 +172,7 @@ func ExploreUsers(ctx *context.Context) {
ctx.Data["PageIsExploreUsers"] = true ctx.Data["PageIsExploreUsers"] = true
RenderUserSearch(ctx, &UserSearchOptions{ RenderUserSearch(ctx, &UserSearchOptions{
Type: models.USER_TYPE_INDIVIDUAL, Type: models.UserTypeIndividual,
Counter: models.CountUsers, Counter: models.CountUsers,
Ranger: models.Users, Ranger: models.Users,
PageSize: setting.UI.ExplorePagingNum, PageSize: setting.UI.ExplorePagingNum,
@ -187,7 +187,7 @@ func ExploreOrganizations(ctx *context.Context) {
ctx.Data["PageIsExploreOrganizations"] = true ctx.Data["PageIsExploreOrganizations"] = true
RenderUserSearch(ctx, &UserSearchOptions{ RenderUserSearch(ctx, &UserSearchOptions{
Type: models.USER_TYPE_ORGANIZATION, Type: models.UserTypeOrganization,
Counter: models.CountOrganizations, Counter: models.CountOrganizations,
Ranger: models.Organizations, Ranger: models.Organizations,
PageSize: setting.UI.ExplorePagingNum, PageSize: setting.UI.ExplorePagingNum,

View file

@ -33,7 +33,7 @@ func CreatePost(ctx *context.Context, form auth.CreateOrgForm) {
org := &models.User{ org := &models.User{
Name: form.OrgName, Name: form.OrgName,
IsActive: true, IsActive: true,
Type: models.USER_TYPE_ORGANIZATION, Type: models.UserTypeOrganization,
} }
if err := models.CreateOrganization(org, ctx.User); err != nil { if err := models.CreateOrganization(org, ctx.User); err != nil {

View file

@ -84,7 +84,7 @@ func SettingsPost(ctx *context.Context, form auth.UpdateOrgSettingForm) {
} }
func SettingsAvatar(ctx *context.Context, form auth.AvatarForm) { func SettingsAvatar(ctx *context.Context, form auth.AvatarForm) {
form.Source = auth.AVATAR_LOCAL form.Source = auth.AvatarLocal
if err := user.UpdateAvatarSetting(ctx, form, ctx.Org.Organization); err != nil { if err := user.UpdateAvatarSetting(ctx, form, ctx.Org.Organization); err != nil {
ctx.Flash.Error(err.Error()) ctx.Flash.Error(err.Error())
} else { } else {

View file

@ -226,11 +226,11 @@ func EditTeamPost(ctx *context.Context, form auth.CreateTeamForm) {
var auth models.AccessMode var auth models.AccessMode
switch form.Permission { switch form.Permission {
case "read": case "read":
auth = models.ACCESS_MODE_READ auth = models.AccessModeRead
case "write": case "write":
auth = models.ACCESS_MODE_WRITE auth = models.AccessModeWrite
case "admin": case "admin":
auth = models.ACCESS_MODE_ADMIN auth = models.AccessModeAdmin
default: default:
ctx.Error(401) ctx.Error(401)
return return

View file

@ -133,9 +133,9 @@ func HTTP(ctx *context.Context) {
} }
if !isPublicPull { if !isPublicPull {
var tp = models.ACCESS_MODE_WRITE var tp = models.AccessModeWrite
if isPull { if isPull {
tp = models.ACCESS_MODE_READ tp = models.AccessModeRead
} }
has, err := models.HasAccess(authUser, repo, tp) has, err := models.HasAccess(authUser, repo, tp)
@ -143,8 +143,8 @@ func HTTP(ctx *context.Context) {
ctx.Handle(http.StatusInternalServerError, "HasAccess", err) ctx.Handle(http.StatusInternalServerError, "HasAccess", err)
return return
} else if !has { } else if !has {
if tp == models.ACCESS_MODE_READ { if tp == models.AccessModeRead {
has, err = models.HasAccess(authUser, repo, models.ACCESS_MODE_WRITE) has, err = models.HasAccess(authUser, repo, models.AccessModeWrite)
if err != nil { if err != nil {
ctx.Handle(http.StatusInternalServerError, "HasAccess2", err) ctx.Handle(http.StatusInternalServerError, "HasAccess2", err)
return return

View file

@ -126,16 +126,16 @@ func Issues(ctx *context.Context) {
assigneeID = ctx.QueryInt64("assignee") assigneeID = ctx.QueryInt64("assignee")
posterID int64 posterID int64
) )
filterMode := models.FM_ALL filterMode := models.FilterModeAll
switch viewType { switch viewType {
case "assigned": case "assigned":
filterMode = models.FM_ASSIGN filterMode = models.FilterModeAssign
assigneeID = ctx.User.ID assigneeID = ctx.User.ID
case "created_by": case "created_by":
filterMode = models.FM_CREATE filterMode = models.FilterModeCreate
posterID = ctx.User.ID posterID = ctx.User.ID
case "mentioned": case "mentioned":
filterMode = models.FM_MENTION filterMode = models.FilterModeMention
} }
var uid int64 = -1 var uid int64 = -1
@ -179,7 +179,7 @@ func Issues(ctx *context.Context) {
MilestoneID: milestoneID, MilestoneID: milestoneID,
Page: pager.Current(), Page: pager.Current(),
IsClosed: isShowClosed, IsClosed: isShowClosed,
IsMention: filterMode == models.FM_MENTION, IsMention: filterMode == models.FilterModeMention,
IsPull: isPullList, IsPull: isPullList,
Labels: selectLabels, Labels: selectLabels,
SortType: sortType, SortType: sortType,
@ -599,7 +599,7 @@ func ViewIssue(ctx *context.Context) {
// Render comments and and fetch participants. // Render comments and and fetch participants.
participants[0] = issue.Poster participants[0] = issue.Poster
for _, comment = range issue.Comments { for _, comment = range issue.Comments {
if comment.Type == models.COMMENT_TYPE_COMMENT { if comment.Type == models.CommentTypeComment {
comment.RenderedContent = string(markdown.Render([]byte(comment.Content), ctx.Repo.RepoLink, comment.RenderedContent = string(markdown.Render([]byte(comment.Content), ctx.Repo.RepoLink,
ctx.Repo.Repository.ComposeMetas())) ctx.Repo.Repository.ComposeMetas()))
@ -612,11 +612,11 @@ func ViewIssue(ctx *context.Context) {
if repo.IsOwnedBy(comment.PosterID) || if repo.IsOwnedBy(comment.PosterID) ||
(repo.Owner.IsOrganization() && repo.Owner.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) { } else if comment.Poster.IsWriterOfRepo(repo) {
comment.ShowTag = models.COMMENT_TAG_WRITER comment.ShowTag = models.CommentTagWriter
} else if comment.PosterID == issue.PosterID { } else if comment.PosterID == issue.PosterID {
comment.ShowTag = models.COMMENT_TAG_POSTER comment.ShowTag = models.CommentTagPoster
} }
marked[comment.PosterID] = comment.ShowTag marked[comment.PosterID] = comment.ShowTag
@ -892,7 +892,7 @@ func UpdateCommentContent(ctx *context.Context) {
if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.IsAdmin()) { if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.IsAdmin()) {
ctx.Error(403) ctx.Error(403)
return return
} else if comment.Type != models.COMMENT_TYPE_COMMENT { } else if comment.Type != models.CommentTypeComment {
ctx.Error(204) ctx.Error(204)
return return
} }
@ -924,7 +924,7 @@ func DeleteComment(ctx *context.Context) {
if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.IsAdmin()) { if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.IsAdmin()) {
ctx.Error(403) ctx.Error(403)
return return
} else if comment.Type != models.COMMENT_TYPE_COMMENT { } else if comment.Type != models.CommentTypeComment {
ctx.Error(204) ctx.Error(204)
return return
} }

View file

@ -687,7 +687,7 @@ func CompareAndPullRequestPost(ctx *context.Context, form auth.CreateIssueForm)
HeadRepo: headRepo, HeadRepo: headRepo,
BaseRepo: repo, BaseRepo: repo,
MergeBase: prInfo.MergeBase, MergeBase: prInfo.MergeBase,
Type: models.PULL_REQUEST_GITEA, Type: models.PullRequestGitea,
} }
// FIXME: check error in the case two people send pull request at almost same time, give nice error prompt // FIXME: check error in the case two people send pull request at almost same time, give nice error prompt
// instead of 500. // instead of 500.

View file

@ -22,7 +22,7 @@ const (
SETTINGS_OPTIONS base.TplName = "repo/settings/options" SETTINGS_OPTIONS base.TplName = "repo/settings/options"
COLLABORATION base.TplName = "repo/settings/collaboration" COLLABORATION base.TplName = "repo/settings/collaboration"
GITHOOKS base.TplName = "repo/settings/githooks" GITHOOKS base.TplName = "repo/settings/githooks"
GITHOOK_EDIT base.TplName = "repo/settings/githook_edit" GithookEdit base.TplName = "repo/settings/githook_edit"
DEPLOY_KEYS base.TplName = "repo/settings/deploy_keys" DEPLOY_KEYS base.TplName = "repo/settings/deploy_keys"
) )
@ -425,7 +425,7 @@ func GitHooksEdit(ctx *context.Context) {
return return
} }
ctx.Data["Hook"] = hook ctx.Data["Hook"] = hook
ctx.HTML(200, GITHOOK_EDIT) ctx.HTML(200, GithookEdit)
} }
func GitHooksEditPost(ctx *context.Context) { func GitHooksEditPost(ctx *context.Context) {

View file

@ -24,8 +24,8 @@ import (
const ( const (
HOOKS base.TplName = "repo/settings/hooks" HOOKS base.TplName = "repo/settings/hooks"
HOOK_NEW base.TplName = "repo/settings/hook_new" HookNew base.TplName = "repo/settings/hook_new"
ORG_HOOK_NEW base.TplName = "org/settings/hook_new" ORG_HookNew base.TplName = "org/settings/hook_new"
) )
func Webhooks(ctx *context.Context) { func Webhooks(ctx *context.Context) {
@ -57,7 +57,7 @@ func getOrgRepoCtx(ctx *context.Context) (*OrgRepoCtx, error) {
return &OrgRepoCtx{ return &OrgRepoCtx{
RepoID: ctx.Repo.Repository.ID, RepoID: ctx.Repo.Repository.ID,
Link: ctx.Repo.RepoLink, Link: ctx.Repo.RepoLink,
NewTemplate: HOOK_NEW, NewTemplate: HookNew,
}, nil }, nil
} }
@ -65,7 +65,7 @@ func getOrgRepoCtx(ctx *context.Context) (*OrgRepoCtx, error) {
return &OrgRepoCtx{ return &OrgRepoCtx{
OrgID: ctx.Org.Organization.ID, OrgID: ctx.Org.Organization.ID,
Link: ctx.Org.OrgLink, Link: ctx.Org.OrgLink,
NewTemplate: ORG_HOOK_NEW, NewTemplate: ORG_HookNew,
}, nil }, nil
} }
@ -134,9 +134,9 @@ func WebHooksNewPost(ctx *context.Context, form auth.NewWebhookForm) {
return return
} }
contentType := models.JSON contentType := models.ContentTypeJson
if models.HookContentType(form.ContentType) == models.FORM { if models.HookContentType(form.ContentType) == models.ContentTypeForm {
contentType = models.FORM contentType = models.ContentTypeForm
} }
w := &models.Webhook{ w := &models.Webhook{
@ -192,7 +192,7 @@ func SlackHooksNewPost(ctx *context.Context, form auth.NewSlackHookForm) {
w := &models.Webhook{ w := &models.Webhook{
RepoID: orCtx.RepoID, RepoID: orCtx.RepoID,
URL: form.PayloadURL, URL: form.PayloadURL,
ContentType: models.JSON, ContentType: models.ContentTypeJson,
HookEvent: ParseHookEvent(form.WebhookForm), HookEvent: ParseHookEvent(form.WebhookForm),
IsActive: form.Active, IsActive: form.Active,
HookTaskType: models.SLACK, HookTaskType: models.SLACK,
@ -281,9 +281,9 @@ func WebHooksEditPost(ctx *context.Context, form auth.NewWebhookForm) {
return return
} }
contentType := models.JSON contentType := models.ContentTypeJson
if models.HookContentType(form.ContentType) == models.FORM { if models.HookContentType(form.ContentType) == models.ContentTypeForm {
contentType = models.FORM contentType = models.ContentTypeForm
} }
w.URL = form.PayloadURL w.URL = form.PayloadURL
@ -383,7 +383,7 @@ func TestWebhook(ctx *context.Context) {
Pusher: apiUser, Pusher: apiUser,
Sender: apiUser, Sender: apiUser,
} }
if err := models.PrepareWebhooks(ctx.Repo.Repository, models.HOOK_EVENT_PUSH, p); err != nil { if err := models.PrepareWebhooks(ctx.Repo.Repository, models.HookEventPush, p); err != nil {
ctx.Flash.Error("PrepareWebhooks: " + err.Error()) ctx.Flash.Error("PrepareWebhooks: " + err.Error())
ctx.Status(500) ctx.Status(500)
} else { } else {

View file

@ -172,7 +172,7 @@ func Issues(ctx *context.Context) {
var ( var (
viewType string viewType string
sortType = ctx.Query("sort") sortType = ctx.Query("sort")
filterMode = models.FM_ALL filterMode = models.FilterModeAll
assigneeID int64 assigneeID int64
posterID int64 posterID int64
) )
@ -187,10 +187,10 @@ func Issues(ctx *context.Context) {
switch viewType { switch viewType {
case "assigned": case "assigned":
filterMode = models.FM_ASSIGN filterMode = models.FilterModeAssign
assigneeID = ctxUser.ID assigneeID = ctxUser.ID
case "created_by": case "created_by":
filterMode = models.FM_CREATE filterMode = models.FilterModeCreate
posterID = ctxUser.ID posterID = ctxUser.ID
} }
} }
@ -235,7 +235,7 @@ func Issues(ctx *context.Context) {
allCount += repo.NumOpenIssues allCount += repo.NumOpenIssues
} }
if filterMode != models.FM_ALL { if filterMode != models.FilterModeAll {
// Calculate repository issue count with filter mode. // Calculate repository issue count with filter mode.
numOpen, numClosed := repo.IssueStats(ctxUser.ID, filterMode, isPullList) numOpen, numClosed := repo.IssueStats(ctxUser.ID, filterMode, isPullList)
repo.NumOpenIssues, repo.NumClosedIssues = int(numOpen), int(numClosed) repo.NumOpenIssues, repo.NumClosedIssues = int(numOpen), int(numClosed)

View file

@ -104,7 +104,7 @@ func SettingsPost(ctx *context.Context, form auth.UpdateProfileForm) {
// FIXME: limit size. // FIXME: limit size.
func UpdateAvatarSetting(ctx *context.Context, form auth.AvatarForm, ctxUser *models.User) error { func UpdateAvatarSetting(ctx *context.Context, form auth.AvatarForm, ctxUser *models.User) error {
ctxUser.UseCustomAvatar = form.Source == auth.AVATAR_LOCAL ctxUser.UseCustomAvatar = form.Source == auth.AvatarLocal
if len(form.Gravatar) > 0 { if len(form.Gravatar) > 0 {
ctxUser.Avatar = base.EncodeMD5(form.Gravatar) ctxUser.Avatar = base.EncodeMD5(form.Gravatar)
ctxUser.AvatarEmail = form.Gravatar ctxUser.AvatarEmail = form.Gravatar

View file

@ -102,13 +102,13 @@ func ListHooks(repoPath string) (_ []*Hook, err error) {
} }
const ( const (
HOOK_PATH_UPDATE = "hooks/update" HookPathUpdate = "hooks/update"
) )
// SetUpdateHook writes given content to update hook of the reposiotry. // SetUpdateHook writes given content to update hook of the reposiotry.
func SetUpdateHook(repoPath, content string) (err error) { func SetUpdateHook(repoPath, content string) (err error) {
log("Setting update hook: %s", repoPath) log("Setting update hook: %s", repoPath)
hookPath := path.Join(repoPath, HOOK_PATH_UPDATE) hookPath := path.Join(repoPath, HookPathUpdate)
if com.IsExist(hookPath) { if com.IsExist(hookPath) {
err = os.Remove(hookPath) err = os.Remove(hookPath)
} else { } else {

View file

@ -198,15 +198,15 @@ func (p *PushPayload) Branch() string {
type HookIssueAction string type HookIssueAction string
const ( const (
HOOK_ISSUE_OPENED HookIssueAction = "opened" HookIssueOpened HookIssueAction = "opened"
HOOK_ISSUE_CLOSED HookIssueAction = "closed" HookIssueClosed HookIssueAction = "closed"
HOOK_ISSUE_REOPENED HookIssueAction = "reopened" HookIssueReopened HookIssueAction = "reopened"
HOOK_ISSUE_EDITED HookIssueAction = "edited" HookIssueEdited HookIssueAction = "edited"
HOOK_ISSUE_ASSIGNED HookIssueAction = "assigned" HookIssueAssigned HookIssueAction = "assigned"
HOOK_ISSUE_UNASSIGNED HookIssueAction = "unassigned" HookIssueUnassigned HookIssueAction = "unassigned"
HOOK_ISSUE_LABEL_UPDATED HookIssueAction = "label_updated" HookIssueLabelUpdated HookIssueAction = "label_updated"
HOOK_ISSUE_LABEL_CLEARED HookIssueAction = "label_cleared" HookIssueLabelCleared HookIssueAction = "label_cleared"
HOOK_ISSUE_SYNCHRONIZED HookIssueAction = "synchronized" HookIssueSynchronized HookIssueAction = "synchronized"
) )
type ChangesFromPayload struct { type ChangesFromPayload struct {