mod: bump modernc.org/sqlite from 1.36.0 to 1.37.0 (#7947)

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Joe Chen <jc@unknwon.io>
This commit is contained in:
dependabot[bot]
2025-04-14 18:00:07 -04:00
committed by GitHub
parent 4acaaac85a
commit 139ea3ce7d
76 changed files with 1085 additions and 1097 deletions

View File

@@ -233,7 +233,7 @@ func (s *ActionsStore) MirrorSyncPush(ctx context.Context, opts MirrorSyncPushOp
apiPusher := opts.Owner.APIFormat()
err = PrepareWebhooks(
opts.Repo,
HOOK_EVENT_PUSH,
HookEventTypePush,
&api.PushPayload{
Ref: opts.RefName,
Before: opts.OldCommitID,
@@ -499,7 +499,7 @@ func (s *ActionsStore) CommitRepo(ctx context.Context, opts CommitRepoOptions) e
if isDelRef {
err = PrepareWebhooks(
opts.Repo,
HOOK_EVENT_DELETE,
HookEventTypeDelete,
&api.DeletePayload{
Ref: refName,
RefType: "branch",
@@ -543,7 +543,7 @@ func (s *ActionsStore) CommitRepo(ctx context.Context, opts CommitRepoOptions) e
if isNewRef {
err = PrepareWebhooks(
opts.Repo,
HOOK_EVENT_CREATE,
HookEventTypeCreate,
&api.CreatePayload{
Ref: refName,
RefType: "branch",
@@ -576,7 +576,7 @@ func (s *ActionsStore) CommitRepo(ctx context.Context, opts CommitRepoOptions) e
err = PrepareWebhooks(
opts.Repo,
HOOK_EVENT_PUSH,
HookEventTypePush,
&api.PushPayload{
Ref: opts.RefFullName,
Before: opts.OldCommitID,
@@ -638,7 +638,7 @@ func (s *ActionsStore) PushTag(ctx context.Context, opts PushTagOptions) error {
if opts.NewCommitID == git.EmptyID {
err = PrepareWebhooks(
opts.Repo,
HOOK_EVENT_DELETE,
HookEventTypeDelete,
&api.DeletePayload{
Ref: refName,
RefType: "tag",
@@ -661,7 +661,7 @@ func (s *ActionsStore) PushTag(ctx context.Context, opts PushTagOptions) error {
err = PrepareWebhooks(
opts.Repo,
HOOK_EVENT_CREATE,
HookEventTypeCreate,
&api.CreatePayload{
Ref: refName,
RefType: "tag",

View File

@@ -49,8 +49,8 @@ func AttachmentLocalPath(uuid string) string {
}
// LocalPath returns where attachment is stored in local file system.
func (attach *Attachment) LocalPath() string {
return AttachmentLocalPath(attach.UUID)
func (a *Attachment) LocalPath() string {
return AttachmentLocalPath(a.UUID)
}
// NewAttachment creates a new attachment object.
@@ -72,9 +72,9 @@ func NewAttachment(name string, buf []byte, file multipart.File) (_ *Attachment,
defer fw.Close()
if _, err = fw.Write(buf); err != nil {
return nil, fmt.Errorf("Write: %v", err)
return nil, fmt.Errorf("write: %v", err)
} else if _, err = io.Copy(fw, file); err != nil {
return nil, fmt.Errorf("Copy: %v", err)
return nil, fmt.Errorf("copy: %v", err)
}
if _, err := x.Insert(attach); err != nil {
@@ -183,8 +183,8 @@ func DeleteAttachments(attachments []*Attachment, remove bool) (int, error) {
}
// DeleteAttachmentsByIssue deletes all attachments associated with the given issue.
func DeleteAttachmentsByIssue(issueId int64, remove bool) (int, error) {
attachments, err := GetAttachmentsByIssueID(issueId)
func DeleteAttachmentsByIssue(issueID int64, remove bool) (int, error) {
attachments, err := GetAttachmentsByIssueID(issueID)
if err != nil {
return 0, err
}
@@ -193,8 +193,8 @@ func DeleteAttachmentsByIssue(issueId int64, remove bool) (int, error) {
}
// DeleteAttachmentsByComment deletes all attachments associated with the given comment.
func DeleteAttachmentsByComment(commentId int64, remove bool) (int, error) {
attachments, err := GetAttachmentsByCommentID(commentId)
func DeleteAttachmentsByComment(commentID int64, remove bool) (int, error) {
attachments, err := GetAttachmentsByCommentID(commentID)
if err != nil {
return 0, err
}

View File

@@ -25,27 +25,27 @@ type CommentType int
const (
// Plain comment, can be associated with a commit (CommitID > 0) and a line (LineNum > 0)
COMMENT_TYPE_COMMENT CommentType = iota
COMMENT_TYPE_REOPEN
COMMENT_TYPE_CLOSE
CommentTypeComment CommentType = iota
CommentTypeReopen
CommentTypeClose
// References.
COMMENT_TYPE_ISSUE_REF
CommentTypeIssueRef
// Reference from a commit (not part of a pull request)
COMMENT_TYPE_COMMIT_REF
CommentTypeCommitRef
// Reference from a comment
COMMENT_TYPE_COMMENT_REF
CommentTypeCommentRef
// Reference from a pull request
COMMENT_TYPE_PULL_REF
CommentTypePullRef
)
type CommentTag int
const (
COMMENT_TAG_NONE CommentTag = iota
COMMENT_TAG_POSTER
COMMENT_TAG_WRITER
COMMENT_TAG_OWNER
CommentTagNone CommentTag = iota
CommentTagPoster
CommentTagWriter
CommentTagOwner
)
// Comment represents a comment in commit and issue page.
@@ -166,21 +166,21 @@ func (c *Comment) EventTag() string {
// mailParticipants sends new comment emails to repository watchers
// and mentioned people.
func (cmt *Comment) mailParticipants(e Engine, opType ActionType, issue *Issue) (err error) {
mentions := markup.FindAllMentions(cmt.Content)
if err = updateIssueMentions(e, cmt.IssueID, mentions); err != nil {
return fmt.Errorf("UpdateIssueMentions [%d]: %v", cmt.IssueID, err)
func (c *Comment) mailParticipants(e Engine, opType ActionType, issue *Issue) (err error) {
mentions := markup.FindAllMentions(c.Content)
if err = updateIssueMentions(e, c.IssueID, mentions); err != nil {
return fmt.Errorf("UpdateIssueMentions [%d]: %v", c.IssueID, err)
}
switch opType {
case ActionCommentIssue:
issue.Content = cmt.Content
issue.Content = c.Content
case ActionCloseIssue:
issue.Content = fmt.Sprintf("Closed #%d", issue.Index)
case ActionReopenIssue:
issue.Content = fmt.Sprintf("Reopened #%d", issue.Index)
}
if err = mailIssueCommentToParticipants(issue, cmt.Poster, mentions); err != nil {
if err = mailIssueCommentToParticipants(issue, c.Poster, mentions); err != nil {
log.Error("mailIssueCommentToParticipants: %v", err)
}
@@ -216,7 +216,7 @@ func createComment(e *xorm.Session, opts *CreateCommentOptions) (_ *Comment, err
// Check comment type.
switch opts.Type {
case COMMENT_TYPE_COMMENT:
case CommentTypeComment:
act.OpType = ActionCommentIssue
if _, err = e.Exec("UPDATE `issue` SET num_comments=num_comments+1 WHERE id=?", opts.Issue.ID); err != nil {
@@ -245,7 +245,7 @@ func createComment(e *xorm.Session, opts *CreateCommentOptions) (_ *Comment, err
}
}
case COMMENT_TYPE_REOPEN:
case CommentTypeReopen:
act.OpType = ActionReopenIssue
if opts.Issue.IsPull {
act.OpType = ActionReopenPullRequest
@@ -260,7 +260,7 @@ func createComment(e *xorm.Session, opts *CreateCommentOptions) (_ *Comment, err
return nil, err
}
case COMMENT_TYPE_CLOSE:
case CommentTypeClose:
act.OpType = ActionCloseIssue
if opts.Issue.IsPull {
act.OpType = ActionClosePullRequest
@@ -294,9 +294,9 @@ func createComment(e *xorm.Session, opts *CreateCommentOptions) (_ *Comment, err
}
func createStatusComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue) (*Comment, error) {
cmtType := COMMENT_TYPE_CLOSE
cmtType := CommentTypeClose
if !issue.IsClosed {
cmtType = COMMENT_TYPE_REOPEN
cmtType = CommentTypeReopen
}
return createComment(e, &CreateCommentOptions{
Type: cmtType,
@@ -338,7 +338,7 @@ func CreateComment(opts *CreateCommentOptions) (comment *Comment, err error) {
// CreateIssueComment creates a plain issue comment.
func CreateIssueComment(doer *User, repo *Repository, issue *Issue, content string, attachments []string) (*Comment, error) {
comment, err := CreateComment(&CreateCommentOptions{
Type: COMMENT_TYPE_COMMENT,
Type: CommentTypeComment,
Doer: doer,
Repo: repo,
Issue: issue,
@@ -350,7 +350,7 @@ func CreateIssueComment(doer *User, repo *Repository, issue *Issue, content stri
}
comment.Issue = issue
if err = PrepareWebhooks(repo, HOOK_EVENT_ISSUE_COMMENT, &api.IssueCommentPayload{
if err = PrepareWebhooks(repo, HookEventTypeIssueComment, &api.IssueCommentPayload{
Action: api.HOOK_ISSUE_COMMENT_CREATED,
Issue: issue.APIFormat(),
Comment: comment.APIFormat(),
@@ -371,7 +371,7 @@ func CreateRefComment(doer *User, repo *Repository, issue *Issue, content, commi
// Check if same reference from same commit has already existed.
has, err := x.Get(&Comment{
Type: COMMENT_TYPE_COMMIT_REF,
Type: CommentTypeCommitRef,
IssueID: issue.ID,
CommitSHA: commitSHA,
})
@@ -382,7 +382,7 @@ func CreateRefComment(doer *User, repo *Repository, issue *Issue, content, commi
}
_, err = CreateComment(&CreateCommentOptions{
Type: COMMENT_TYPE_COMMIT_REF,
Type: CommentTypeCommitRef,
Doer: doer,
Repo: repo,
Issue: issue,
@@ -486,7 +486,7 @@ func UpdateComment(doer *User, c *Comment, oldContent string) (err error) {
if err = c.Issue.LoadAttributes(); err != nil {
log.Error("Issue.LoadAttributes [issue_id: %d]: %v", c.IssueID, err)
} else if err = PrepareWebhooks(c.Issue.Repo, HOOK_EVENT_ISSUE_COMMENT, &api.IssueCommentPayload{
} else if err = PrepareWebhooks(c.Issue.Repo, HookEventTypeIssueComment, &api.IssueCommentPayload{
Action: api.HOOK_ISSUE_COMMENT_EDITED,
Issue: c.Issue.APIFormat(),
Comment: c.APIFormat(),
@@ -524,7 +524,7 @@ func DeleteCommentByID(doer *User, id int64) error {
return err
}
if comment.Type == COMMENT_TYPE_COMMENT {
if comment.Type == CommentTypeComment {
if _, err = sess.Exec("UPDATE `issue` SET num_comments = num_comments - 1 WHERE id = ?", comment.IssueID); err != nil {
return err
}
@@ -541,7 +541,7 @@ func DeleteCommentByID(doer *User, id int64) error {
if err = comment.Issue.LoadAttributes(); err != nil {
log.Error("Issue.LoadAttributes [issue_id: %d]: %v", comment.IssueID, err)
} else if err = PrepareWebhooks(comment.Issue.Repo, HOOK_EVENT_ISSUE_COMMENT, &api.IssueCommentPayload{
} else if err = PrepareWebhooks(comment.Issue.Repo, HookEventTypeIssueComment, &api.IssueCommentPayload{
Action: api.HOOK_ISSUE_COMMENT_DELETED,
Issue: comment.Issue.APIFormat(),
Comment: comment.APIFormat(),

View File

@@ -6,7 +6,7 @@ package errors
import "errors"
var InternalServerError = errors.New("internal server error")
var ErrInternalServerError = errors.New("internal server error")
// New is a wrapper of real errors.New function.
func New(text string) error {

View File

@@ -250,7 +250,7 @@ func (issue *Issue) sendLabelUpdatedWebhook(doer *User) {
log.Error("LoadIssue: %v", err)
return
}
err = PrepareWebhooks(issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{
err = PrepareWebhooks(issue.Repo, HookEventTypePullRequest, &api.PullRequestPayload{
Action: api.HOOK_ISSUE_LABEL_UPDATED,
Index: issue.Index,
PullRequest: issue.PullRequest.APIFormat(),
@@ -258,7 +258,7 @@ func (issue *Issue) sendLabelUpdatedWebhook(doer *User) {
Sender: doer.APIFormat(),
})
} else {
err = PrepareWebhooks(issue.Repo, HOOK_EVENT_ISSUES, &api.IssuesPayload{
err = PrepareWebhooks(issue.Repo, HookEventTypeIssues, &api.IssuesPayload{
Action: api.HOOK_ISSUE_LABEL_UPDATED,
Index: issue.Index,
Issue: issue.APIFormat(),
@@ -354,7 +354,7 @@ func (issue *Issue) ClearLabels(doer *User) (err error) {
}
if err = sess.Commit(); err != nil {
return fmt.Errorf("Commit: %v", err)
return fmt.Errorf("commit: %v", err)
}
if issue.IsPull {
@@ -363,7 +363,7 @@ func (issue *Issue) ClearLabels(doer *User) (err error) {
log.Error("LoadIssue: %v", err)
return err
}
err = PrepareWebhooks(issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{
err = PrepareWebhooks(issue.Repo, HookEventTypePullRequest, &api.PullRequestPayload{
Action: api.HOOK_ISSUE_LABEL_CLEARED,
Index: issue.Index,
PullRequest: issue.PullRequest.APIFormat(),
@@ -371,7 +371,7 @@ func (issue *Issue) ClearLabels(doer *User) (err error) {
Sender: doer.APIFormat(),
})
} else {
err = PrepareWebhooks(issue.Repo, HOOK_EVENT_ISSUES, &api.IssuesPayload{
err = PrepareWebhooks(issue.Repo, HookEventTypeIssues, &api.IssuesPayload{
Action: api.HOOK_ISSUE_LABEL_CLEARED,
Index: issue.Index,
Issue: issue.APIFormat(),
@@ -485,7 +485,7 @@ func (issue *Issue) ChangeStatus(doer *User, repo *Repository, isClosed bool) (e
}
if err = sess.Commit(); err != nil {
return fmt.Errorf("Commit: %v", err)
return fmt.Errorf("commit: %v", err)
}
if issue.IsPull {
@@ -502,7 +502,7 @@ func (issue *Issue) ChangeStatus(doer *User, repo *Repository, isClosed bool) (e
} else {
apiPullRequest.Action = api.HOOK_ISSUE_REOPENED
}
err = PrepareWebhooks(repo, HOOK_EVENT_PULL_REQUEST, apiPullRequest)
err = PrepareWebhooks(repo, HookEventTypePullRequest, apiPullRequest)
} else {
apiIssues := &api.IssuesPayload{
Index: issue.Index,
@@ -515,7 +515,7 @@ func (issue *Issue) ChangeStatus(doer *User, repo *Repository, isClosed bool) (e
} else {
apiIssues.Action = api.HOOK_ISSUE_REOPENED
}
err = PrepareWebhooks(repo, HOOK_EVENT_ISSUES, apiIssues)
err = PrepareWebhooks(repo, HookEventTypeIssues, apiIssues)
}
if err != nil {
log.Error("PrepareWebhooks [is_pull: %v, is_closed: %v]: %v", issue.IsPull, isClosed, err)
@@ -533,7 +533,7 @@ func (issue *Issue) ChangeTitle(doer *User, title string) (err error) {
if issue.IsPull {
issue.PullRequest.Issue = issue
err = PrepareWebhooks(issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{
err = PrepareWebhooks(issue.Repo, HookEventTypePullRequest, &api.PullRequestPayload{
Action: api.HOOK_ISSUE_EDITED,
Index: issue.Index,
PullRequest: issue.PullRequest.APIFormat(),
@@ -546,7 +546,7 @@ func (issue *Issue) ChangeTitle(doer *User, title string) (err error) {
Sender: doer.APIFormat(),
})
} else {
err = PrepareWebhooks(issue.Repo, HOOK_EVENT_ISSUES, &api.IssuesPayload{
err = PrepareWebhooks(issue.Repo, HookEventTypeIssues, &api.IssuesPayload{
Action: api.HOOK_ISSUE_EDITED,
Index: issue.Index,
Issue: issue.APIFormat(),
@@ -575,7 +575,7 @@ func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
if issue.IsPull {
issue.PullRequest.Issue = issue
err = PrepareWebhooks(issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{
err = PrepareWebhooks(issue.Repo, HookEventTypePullRequest, &api.PullRequestPayload{
Action: api.HOOK_ISSUE_EDITED,
Index: issue.Index,
PullRequest: issue.PullRequest.APIFormat(),
@@ -588,7 +588,7 @@ func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
Sender: doer.APIFormat(),
})
} else {
err = PrepareWebhooks(issue.Repo, HOOK_EVENT_ISSUES, &api.IssuesPayload{
err = PrepareWebhooks(issue.Repo, HookEventTypeIssues, &api.IssuesPayload{
Action: api.HOOK_ISSUE_EDITED,
Index: issue.Index,
Issue: issue.APIFormat(),
@@ -635,7 +635,7 @@ func (issue *Issue) ChangeAssignee(doer *User, assigneeID int64) (err error) {
} else {
apiPullRequest.Action = api.HOOK_ISSUE_ASSIGNED
}
err = PrepareWebhooks(issue.Repo, HOOK_EVENT_PULL_REQUEST, apiPullRequest)
err = PrepareWebhooks(issue.Repo, HookEventTypePullRequest, apiPullRequest)
} else {
apiIssues := &api.IssuesPayload{
Index: issue.Index,
@@ -648,7 +648,7 @@ func (issue *Issue) ChangeAssignee(doer *User, assigneeID int64) (err error) {
} else {
apiIssues.Action = api.HOOK_ISSUE_ASSIGNED
}
err = PrepareWebhooks(issue.Repo, HOOK_EVENT_ISSUES, apiIssues)
err = PrepareWebhooks(issue.Repo, HookEventTypeIssues, apiIssues)
}
if err != nil {
log.Error("PrepareWebhooks [is_pull: %v, remove_assignee: %v]: %v", issue.IsPull, isRemoveAssignee, err)
@@ -770,11 +770,11 @@ func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string)
LableIDs: labelIDs,
Attachments: uuids,
}); err != nil {
return fmt.Errorf("newIssue: %v", err)
return fmt.Errorf("new issue: %v", err)
}
if err = sess.Commit(); err != nil {
return fmt.Errorf("Commit: %v", err)
return fmt.Errorf("commit: %v", err)
}
if err = NotifyWatchers(&Action{
@@ -793,7 +793,7 @@ func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string)
log.Error("MailParticipants: %v", err)
}
if err = PrepareWebhooks(repo, HOOK_EVENT_ISSUES, &api.IssuesPayload{
if err = PrepareWebhooks(repo, HookEventTypeIssues, &api.IssuesPayload{
Action: api.HOOK_ISSUE_OPENED,
Index: issue.Index,
Issue: issue.APIFormat(),
@@ -1001,7 +1001,7 @@ func Issues(opts *IssuesOptions) ([]*Issue, error) {
issues := make([]*Issue, 0, conf.UI.IssuePagingNum)
if err := sess.Find(&issues); err != nil {
return nil, fmt.Errorf("Find: %v", err)
return nil, fmt.Errorf("find: %v", err)
}
// FIXME: use IssueList to improve performance.
@@ -1108,9 +1108,9 @@ func NewIssueUsers(repo *Repository, issue *Issue) (err error) {
}
// PairsContains returns true when pairs list contains given issue.
func PairsContains(ius []*IssueUser, issueId, uid int64) int {
func PairsContains(ius []*IssueUser, issueID, uid int64) int {
for i := range ius {
if ius[i].IssueID == issueId &&
if ius[i].IssueID == issueID &&
ius[i].UserID == uid {
return i
}
@@ -1146,9 +1146,9 @@ func GetIssueUserPairsByMode(userID, repoID int64, filterMode FilterMode, isClos
}
switch filterMode {
case FILTER_MODE_ASSIGN:
case FilterModeAssign:
sess.And("is_assigned=?", true)
case FILTER_MODE_CREATE:
case FilterModeCreate:
sess.And("is_poster=?", true)
default:
return ius, nil
@@ -1212,10 +1212,10 @@ type IssueStats struct {
type FilterMode string
const (
FILTER_MODE_YOUR_REPOS FilterMode = "your_repositories"
FILTER_MODE_ASSIGN FilterMode = "assigned"
FILTER_MODE_CREATE FilterMode = "created_by"
FILTER_MODE_MENTION FilterMode = "mentioned"
FilterModeYourRepos FilterMode = "your_repositories"
FilterModeAssign FilterMode = "assigned"
FilterModeCreate FilterMode = "created_by"
FilterModeMention FilterMode = "mentioned"
)
func parseCountResult(results []map[string][]byte) int64 {
@@ -1264,7 +1264,7 @@ func GetIssueStats(opts *IssueStatsOptions) *IssueStats {
}
switch opts.FilterMode {
case FILTER_MODE_YOUR_REPOS, FILTER_MODE_ASSIGN:
case FilterModeYourRepos, FilterModeAssign:
stats.OpenCount, _ = countSession(opts).
And("is_closed = ?", false).
Count(new(Issue))
@@ -1272,7 +1272,7 @@ func GetIssueStats(opts *IssueStatsOptions) *IssueStats {
stats.ClosedCount, _ = countSession(opts).
And("is_closed = ?", true).
Count(new(Issue))
case FILTER_MODE_CREATE:
case FilterModeCreate:
stats.OpenCount, _ = countSession(opts).
And("poster_id = ?", opts.UserID).
And("is_closed = ?", false).
@@ -1282,7 +1282,7 @@ func GetIssueStats(opts *IssueStatsOptions) *IssueStats {
And("poster_id = ?", opts.UserID).
And("is_closed = ?", true).
Count(new(Issue))
case FILTER_MODE_MENTION:
case FilterModeMention:
stats.OpenCount, _ = countSession(opts).
Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
And("issue_user.uid = ?", opts.UserID).
@@ -1330,7 +1330,7 @@ func GetUserIssueStats(repoID, userID int64, repoIDs []int64, filterMode FilterM
}
switch filterMode {
case FILTER_MODE_YOUR_REPOS:
case FilterModeYourRepos:
if !hasAnyRepo {
break
}
@@ -1339,14 +1339,14 @@ func GetUserIssueStats(repoID, userID int64, repoIDs []int64, filterMode FilterM
Count(new(Issue))
stats.ClosedCount, _ = countSession(true, isPull, repoID, repoIDs).
Count(new(Issue))
case FILTER_MODE_ASSIGN:
case FilterModeAssign:
stats.OpenCount, _ = countSession(false, isPull, repoID, nil).
And("assignee_id = ?", userID).
Count(new(Issue))
stats.ClosedCount, _ = countSession(true, isPull, repoID, nil).
And("assignee_id = ?", userID).
Count(new(Issue))
case FILTER_MODE_CREATE:
case FilterModeCreate:
stats.OpenCount, _ = countSession(false, isPull, repoID, nil).
And("poster_id = ?", userID).
Count(new(Issue))
@@ -1372,10 +1372,10 @@ func GetRepoIssueStats(repoID, userID int64, filterMode FilterMode, isPull bool)
closedCountSession := countSession(true, isPull, repoID)
switch filterMode {
case FILTER_MODE_ASSIGN:
case FilterModeAssign:
openCountSession.And("assignee_id = ?", userID)
closedCountSession.And("assignee_id = ?", userID)
case FILTER_MODE_CREATE:
case FilterModeCreate:
openCountSession.And("poster_id = ?", userID)
closedCountSession.And("poster_id = ?", userID)
}

View File

@@ -65,17 +65,17 @@ type Label struct {
IsChecked bool `xorm:"-" json:"-" gorm:"-"`
}
func (label *Label) APIFormat() *api.Label {
func (l *Label) APIFormat() *api.Label {
return &api.Label{
ID: label.ID,
Name: label.Name,
Color: strings.TrimLeft(label.Color, "#"),
ID: l.ID,
Name: l.Name,
Color: strings.TrimLeft(l.Color, "#"),
}
}
// CalOpenIssues calculates the open issues of label.
func (label *Label) CalOpenIssues() {
label.NumOpenIssues = label.NumIssues - label.NumClosedIssues
func (l *Label) CalOpenIssues() {
l.NumOpenIssues = l.NumIssues - l.NumClosedIssues
}
// ForegroundColor calculates the text color for labels based

View File

@@ -27,25 +27,25 @@ type mailerUser struct {
user *User
}
func (this mailerUser) ID() int64 {
return this.user.ID
func (mu mailerUser) ID() int64 {
return mu.user.ID
}
func (this mailerUser) DisplayName() string {
return this.user.DisplayName()
func (mu mailerUser) DisplayName() string {
return mu.user.DisplayName()
}
func (this mailerUser) Email() string {
return this.user.Email
func (mu mailerUser) Email() string {
return mu.user.Email
}
func (this mailerUser) GenerateEmailActivateCode(email string) string {
func (mu mailerUser) GenerateEmailActivateCode(email string) string {
return userutil.GenerateActivateCode(
this.user.ID,
mu.user.ID,
email,
this.user.Name,
this.user.Password,
this.user.Rands,
mu.user.Name,
mu.user.Password,
mu.user.Rands,
)
}
@@ -58,16 +58,16 @@ type mailerRepo struct {
repo *Repository
}
func (this mailerRepo) FullName() string {
return this.repo.FullName()
func (mr mailerRepo) FullName() string {
return mr.repo.FullName()
}
func (this mailerRepo) HTMLURL() string {
return this.repo.HTMLURL()
func (mr mailerRepo) HTMLURL() string {
return mr.repo.HTMLURL()
}
func (this mailerRepo) ComposeMetas() map[string]string {
return this.repo.ComposeMetas()
func (mr mailerRepo) ComposeMetas() map[string]string {
return mr.repo.ComposeMetas()
}
func NewMailerRepo(repo *Repository) email.Repository {
@@ -79,16 +79,16 @@ type mailerIssue struct {
issue *Issue
}
func (this mailerIssue) MailSubject() string {
return this.issue.MailSubject()
func (mi mailerIssue) MailSubject() string {
return mi.issue.MailSubject()
}
func (this mailerIssue) Content() string {
return this.issue.Content
func (mi mailerIssue) Content() string {
return mi.issue.Content
}
func (this mailerIssue) HTMLURL() string {
return this.issue.HTMLURL()
func (mi mailerIssue) HTMLURL() string {
return mi.issue.HTMLURL()
}
func NewMailerIssue(issue *Issue) email.Issue {

View File

@@ -343,7 +343,7 @@ func ChangeMilestoneAssign(doer *User, issue *Issue, oldMilestoneID int64) (err
}
if err = sess.Commit(); err != nil {
return fmt.Errorf("Commit: %v", err)
return fmt.Errorf("commit: %v", err)
}
var hookAction api.HookIssueAction
@@ -359,7 +359,7 @@ func ChangeMilestoneAssign(doer *User, issue *Issue, oldMilestoneID int64) (err
log.Error("LoadIssue: %v", err)
return err
}
err = PrepareWebhooks(issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{
err = PrepareWebhooks(issue.Repo, HookEventTypePullRequest, &api.PullRequestPayload{
Action: hookAction,
Index: issue.Index,
PullRequest: issue.PullRequest.APIFormat(),
@@ -367,7 +367,7 @@ func ChangeMilestoneAssign(doer *User, issue *Issue, oldMilestoneID int64) (err
Sender: doer.APIFormat(),
})
} else {
err = PrepareWebhooks(issue.Repo, HOOK_EVENT_ISSUES, &api.IssuesPayload{
err = PrepareWebhooks(issue.Repo, HookEventTypeIssues, &api.IssuesPayload{
Action: hookAction,
Index: issue.Index,
Issue: issue.APIFormat(),

View File

@@ -229,9 +229,13 @@ func (m *Mirror) runSync() ([]*mirrorSyncResult, bool) {
timeout, repoPath, fmt.Sprintf("Mirror.runSync: %s", repoPath),
"git", gitArgs...)
if err != nil {
desc := fmt.Sprintf("Failed to update mirror repository '%s': %s", repoPath, stderr)
log.Error(desc)
if err = Handle.Notices().Create(context.TODO(), NoticeTypeRepository, desc); err != nil {
const fmtStr = "Failed to update mirror repository %q: %s"
log.Error(fmtStr, repoPath, stderr)
if err = Handle.Notices().Create(
context.TODO(),
NoticeTypeRepository,
fmt.Sprintf(fmtStr, repoPath, stderr),
); err != nil {
log.Error("CreateRepositoryNotice: %v", err)
}
return nil, false
@@ -247,9 +251,13 @@ func (m *Mirror) runSync() ([]*mirrorSyncResult, bool) {
if _, stderr, err := process.ExecDir(
timeout, wikiPath, fmt.Sprintf("Mirror.runSync: %s", wikiPath),
"git", "remote", "update", "--prune"); err != nil {
desc := fmt.Sprintf("Failed to update mirror wiki repository '%s': %s", wikiPath, stderr)
log.Error(desc)
if err = Handle.Notices().Create(context.TODO(), NoticeTypeRepository, desc); err != nil {
const fmtStr = "Failed to update mirror wiki repository %q: %s"
log.Error(fmtStr, wikiPath, stderr)
if err = Handle.Notices().Create(
context.TODO(),
NoticeTypeRepository,
fmt.Sprintf(fmtStr, wikiPath, stderr),
); err != nil {
log.Error("CreateRepositoryNotice: %v", err)
}
}
@@ -290,11 +298,11 @@ func DeleteMirrorByRepoID(repoID int64) error {
// MirrorUpdate checks and updates mirror repositories.
func MirrorUpdate() {
if taskStatusTable.IsRunning(_MIRROR_UPDATE) {
if taskStatusTable.IsRunning(taskNameMirrorUpdate) {
return
}
taskStatusTable.Start(_MIRROR_UPDATE)
defer taskStatusTable.Stop(_MIRROR_UPDATE)
taskStatusTable.Start(taskNameMirrorUpdate)
defer taskStatusTable.Stop(taskNameMirrorUpdate)
log.Trace("Doing: MirrorUpdate")

View File

@@ -41,7 +41,7 @@ func (org *User) GetTeam(name string) (*Team, error) {
}
func (org *User) getOwnerTeam(e Engine) (*Team, error) {
return org.getTeam(e, OWNER_TEAM)
return org.getTeam(e, ownerTeamName)
}
// GetOwnerTeam returns owner team of organization.
@@ -73,7 +73,7 @@ func (org *User) GetMembers(limit int) error {
org.Members = make([]*User, len(ous))
for i, ou := range ous {
org.Members[i], err = Handle.Users().GetByID(context.TODO(), ou.Uid)
org.Members[i], err = Handle.Users().GetByID(context.TODO(), ou.UID)
if err != nil {
return err
}
@@ -139,7 +139,7 @@ func CreateOrganization(org, owner *User) (err error) {
// Add initial creator to organization and owner team.
if _, err = sess.Insert(&OrgUser{
Uid: owner.ID,
UID: owner.ID,
OrgID: org.ID,
IsOwner: true,
NumTeams: 1,
@@ -150,8 +150,8 @@ func CreateOrganization(org, owner *User) (err error) {
// Create default owner team.
t := &Team{
OrgID: org.ID,
LowerName: strings.ToLower(OWNER_TEAM),
Name: OWNER_TEAM,
LowerName: strings.ToLower(ownerTeamName),
Name: ownerTeamName,
Authorize: AccessModeOwner,
NumMembers: 1,
}
@@ -247,7 +247,7 @@ func DeleteOrganization(org *User) error {
// OrgUser represents relations of organizations and their members.
type OrgUser struct {
ID int64 `gorm:"primaryKey"`
Uid int64 `xorm:"INDEX UNIQUE(s)" gorm:"uniqueIndex:org_user_user_org_unique;index;not null"`
UID int64 `xorm:"uid INDEX UNIQUE(s)" gorm:"column:uid;uniqueIndex:org_user_user_org_unique;index;not null"`
OrgID int64 `xorm:"INDEX UNIQUE(s)" gorm:"uniqueIndex:org_user_user_org_unique;index;not null"`
IsPublic bool `gorm:"not null;default:FALSE"`
IsOwner bool `gorm:"not null;default:FALSE"`
@@ -261,14 +261,14 @@ func IsOrganizationOwner(orgID, userID int64) bool {
}
// IsOrganizationMember returns true if given user is member of organization.
func IsOrganizationMember(orgId, uid int64) bool {
has, _ := x.Where("uid=?", uid).And("org_id=?", orgId).Get(new(OrgUser))
func IsOrganizationMember(orgID, uid int64) bool {
has, _ := x.Where("uid=?", uid).And("org_id=?", orgID).Get(new(OrgUser))
return has
}
// IsPublicMembership returns true if given user public his/her membership.
func IsPublicMembership(orgId, uid int64) bool {
has, _ := x.Where("uid=?", uid).And("org_id=?", orgId).And("is_public=?", true).Get(new(OrgUser))
func IsPublicMembership(orgID, uid int64) bool {
has, _ := x.Where("uid=?", uid).And("org_id=?", orgID).And("is_public=?", true).Get(new(OrgUser))
return has
}
@@ -349,7 +349,7 @@ func AddOrgUser(orgID, uid int64) error {
}
ou := &OrgUser{
Uid: uid,
UID: uid,
OrgID: orgID,
}

View File

@@ -15,7 +15,7 @@ import (
"gogs.io/gogs/internal/errutil"
)
const OWNER_TEAM = "Owners"
const ownerTeamName = "Owners"
// Team represents a organization team.
type Team struct {
@@ -43,7 +43,7 @@ func (t *Team) AfterSet(colName string, _ xorm.Cell) {
// IsOwnerTeam returns true if team is owner team.
func (t *Team) IsOwnerTeam() bool {
return t.Name == OWNER_TEAM
return t.Name == ownerTeamName
}
// HasWriteAccess returns true if team has at least write level access mode.

View File

@@ -30,16 +30,16 @@ var PullRequestQueue = sync.NewUniqueQueue(1000)
type PullRequestType int
const (
PULL_REQUEST_GOGS PullRequestType = iota
PLLL_ERQUEST_GIT
PullRequestTypeGogs PullRequestType = iota
PullRequestTypeGit
)
type PullRequestStatus int
const (
PULL_REQUEST_STATUS_CONFLICT PullRequestStatus = iota
PULL_REQUEST_STATUS_CHECKING
PULL_REQUEST_STATUS_MERGEABLE
PullRequestStatusConflict PullRequestStatus = iota
PullRequestStatusChecking
PullRequestStatusMergeable
)
// PullRequest represents relation between pull request and repositories.
@@ -161,8 +161,8 @@ func (pr *PullRequest) APIFormat() *api.PullRequest {
HasMerged: pr.HasMerged,
}
if pr.Status != PULL_REQUEST_STATUS_CHECKING {
mergeable := pr.Status != PULL_REQUEST_STATUS_CONFLICT
if pr.Status != PullRequestStatusChecking {
mergeable := pr.Status != PullRequestStatusConflict
apiPullRequest.Mergeable = &mergeable
}
if pr.HasMerged {
@@ -176,20 +176,20 @@ func (pr *PullRequest) APIFormat() *api.PullRequest {
// IsChecking returns true if this pull request is still checking conflict.
func (pr *PullRequest) IsChecking() bool {
return pr.Status == PULL_REQUEST_STATUS_CHECKING
return pr.Status == PullRequestStatusChecking
}
// CanAutoMerge returns true if this pull request can be merged automatically.
func (pr *PullRequest) CanAutoMerge() bool {
return pr.Status == PULL_REQUEST_STATUS_MERGEABLE
return pr.Status == PullRequestStatusMergeable
}
// MergeStyle represents the approach to merge commits into base branch.
type MergeStyle string
const (
MERGE_STYLE_REGULAR MergeStyle = "create_merge_commit"
MERGE_STYLE_REBASE MergeStyle = "rebase_before_merging"
MergeStyleRegular MergeStyle = "create_merge_commit"
MergeStyleRebase MergeStyle = "rebase_before_merging"
)
// Merge merges pull request to base repository.
@@ -254,12 +254,12 @@ func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository, mergeStyle
remoteHeadBranch := "head_repo/" + pr.HeadBranch
// Check if merge style is allowed, reset to default style if not
if mergeStyle == MERGE_STYLE_REBASE && !pr.BaseRepo.PullsAllowRebase {
mergeStyle = MERGE_STYLE_REGULAR
if mergeStyle == MergeStyleRebase && !pr.BaseRepo.PullsAllowRebase {
mergeStyle = MergeStyleRegular
}
switch mergeStyle {
case MERGE_STYLE_REGULAR: // Create merge commit
case MergeStyleRegular: // Create merge commit
// Merge changes from head branch.
if _, stderr, err = process.ExecDir(-1, tmpBasePath,
@@ -277,7 +277,7 @@ func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository, mergeStyle
return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, stderr)
}
case MERGE_STYLE_REBASE: // Rebase before merging
case MergeStyleRebase: // Rebase before merging
// Rebase head branch based on base branch, this creates a non-branch commit state.
if _, stderr, err = process.ExecDir(-1, tmpBasePath,
@@ -332,7 +332,7 @@ func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository, mergeStyle
}
if err = sess.Commit(); err != nil {
return fmt.Errorf("Commit: %v", err)
return fmt.Errorf("commit: %v", err)
}
if err = Handle.Actions().MergePullRequest(ctx, doer, pr.Issue.Repo.Owner, pr.Issue.Repo, pr.Issue); err != nil {
@@ -344,7 +344,7 @@ func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository, mergeStyle
log.Error("LoadAttributes: %v", err)
return nil
}
if err = PrepareWebhooks(pr.Issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{
if err = PrepareWebhooks(pr.Issue.Repo, HookEventTypePullRequest, &api.PullRequestPayload{
Action: api.HOOK_ISSUE_CLOSED,
Index: pr.Index,
PullRequest: pr.APIFormat(),
@@ -369,7 +369,7 @@ func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository, mergeStyle
log.Error("Failed to get base branch %q commit: %v", pr.BaseBranch, err)
return nil
}
if mergeStyle == MERGE_STYLE_REGULAR {
if mergeStyle == MergeStyleRegular {
commits = append([]*git.Commit{mergeCommit}, commits...)
}
@@ -389,7 +389,7 @@ func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository, mergeStyle
Pusher: pr.HeadRepo.MustOwner().APIFormat(),
Sender: doer.APIFormat(),
}
if err = PrepareWebhooks(pr.BaseRepo, HOOK_EVENT_PUSH, p); err != nil {
if err = PrepareWebhooks(pr.BaseRepo, HookEventTypePush, p); err != nil {
log.Error("Failed to prepare webhooks: %v", err)
return nil
}
@@ -432,13 +432,13 @@ func (pr *PullRequest) testPatch() (err error) {
}
args = append(args, patchPath)
pr.Status = PULL_REQUEST_STATUS_CHECKING
pr.Status = PullRequestStatusChecking
_, stderr, err := process.ExecDir(-1, pr.BaseRepo.LocalCopyPath(),
fmt.Sprintf("testPatch (git apply --check): %d", pr.BaseRepo.ID),
"git", args...)
if err != nil {
log.Trace("PullRequest[%d].testPatch (apply): has conflict\n%s", pr.ID, stderr)
pr.Status = PULL_REQUEST_STATUS_CONFLICT
pr.Status = PullRequestStatusConflict
return nil
}
return nil
@@ -472,8 +472,8 @@ func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []str
return fmt.Errorf("testPatch: %v", err)
}
// No conflict appears after test means mergeable.
if pr.Status == PULL_REQUEST_STATUS_CHECKING {
pr.Status = PULL_REQUEST_STATUS_MERGEABLE
if pr.Status == PullRequestStatusChecking {
pr.Status = PullRequestStatusMergeable
}
pr.IssueID = pull.ID
@@ -482,7 +482,7 @@ func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []str
}
if err = sess.Commit(); err != nil {
return fmt.Errorf("Commit: %v", err)
return fmt.Errorf("commit: %v", err)
}
if err = NotifyWatchers(&Action{
@@ -503,7 +503,7 @@ func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []str
pr.Issue = pull
pull.PullRequest = pr
if err = PrepareWebhooks(repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{
if err = PrepareWebhooks(repo, HookEventTypePullRequest, &api.PullRequestPayload{
Action: api.HOOK_ISSUE_OPENED,
Index: pull.Index,
PullRequest: pr.APIFormat(),
@@ -705,7 +705,7 @@ func (pr *PullRequest) PushToBaseRepo() (err error) {
// AddToTaskQueue adds itself to pull request test task queue.
func (pr *PullRequest) AddToTaskQueue() {
go PullRequestQueue.AddFunc(pr.ID, func() {
pr.Status = PULL_REQUEST_STATUS_CHECKING
pr.Status = PullRequestStatusChecking
if err := pr.UpdateCols("status"); err != nil {
log.Error("AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
}
@@ -795,7 +795,7 @@ func AddTestPullRequestTask(doer *User, repoID int64, branch string, isSync bool
log.Error("LoadAttributes: %v", err)
continue
}
if err = PrepareWebhooks(pr.Issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{
if err = PrepareWebhooks(pr.Issue.Repo, HookEventTypePullRequest, &api.PullRequestPayload{
Action: api.HOOK_ISSUE_SYNCHRONIZED,
Index: pr.Issue.Index,
PullRequest: pr.Issue.PullRequest.APIFormat(),
@@ -826,8 +826,8 @@ func AddTestPullRequestTask(doer *User, repoID int64, branch string, isSync bool
// and set to be either conflict or mergeable.
func (pr *PullRequest) checkAndUpdateStatus() {
// Status is not changed to conflict means mergeable.
if pr.Status == PULL_REQUEST_STATUS_CHECKING {
pr.Status = PULL_REQUEST_STATUS_MERGEABLE
if pr.Status == PullRequestStatusChecking {
pr.Status = PullRequestStatusMergeable
}
// Make sure there is no waiting test to process before leaving the checking status.
@@ -843,7 +843,7 @@ func (pr *PullRequest) checkAndUpdateStatus() {
func TestPullRequests() {
prs := make([]*PullRequest, 0, 10)
_ = x.Iterate(PullRequest{
Status: PULL_REQUEST_STATUS_CHECKING,
Status: PullRequestStatusChecking,
},
func(idx int, bean any) error {
pr := bean.(*PullRequest)

View File

@@ -150,7 +150,7 @@ func createTag(gitRepo *git.Repository, r *Release) error {
}
func (r *Release) preparePublishWebhooks() {
if err := PrepareWebhooks(r.Repo, HOOK_EVENT_RELEASE, &api.ReleasePayload{
if err := PrepareWebhooks(r.Repo, HookEventTypeRelease, &api.ReleasePayload{
Action: api.HOOK_RELEASE_PUBLISHED,
Release: r.APIFormat(),
Repository: r.Repo.APIFormatLegacy(nil),
@@ -181,7 +181,7 @@ func NewRelease(gitRepo *git.Repository, r *Release, uuids []string) error {
}
if _, err = sess.Insert(r); err != nil {
return fmt.Errorf("Insert: %v", err)
return fmt.Errorf("insert: %v", err)
}
if len(uuids) > 0 {
@@ -191,7 +191,7 @@ func NewRelease(gitRepo *git.Repository, r *Release, uuids []string) error {
}
if err = sess.Commit(); err != nil {
return fmt.Errorf("Commit: %v", err)
return fmt.Errorf("commit: %v", err)
}
// Only send webhook when actually published, skip drafts
@@ -236,7 +236,7 @@ func GetRelease(repoID int64, tagName string) (*Release, error) {
r := &Release{RepoID: repoID, LowerTagName: strings.ToLower(tagName)}
if _, err = x.Get(r); err != nil {
return nil, fmt.Errorf("Get: %v", err)
return nil, fmt.Errorf("get: %v", err)
}
return r, r.LoadAttributes()
@@ -334,7 +334,7 @@ func UpdateRelease(doer *User, gitRepo *git.Repository, r *Release, isPublish bo
}
if err = sess.Commit(); err != nil {
return fmt.Errorf("Commit: %v", err)
return fmt.Errorf("commit: %v", err)
}
if !isPublish {
@@ -370,7 +370,7 @@ func DeleteReleaseOfRepoByID(repoID, id int64) error {
}
if _, err = x.Id(rel.ID).Delete(new(Release)); err != nil {
return fmt.Errorf("Delete: %v", err)
return fmt.Errorf("delete: %v", err)
}
return nil

View File

@@ -44,8 +44,8 @@ import (
"gogs.io/gogs/internal/sync"
)
// REPO_AVATAR_URL_PREFIX is used to identify a URL is to access repository avatar.
const REPO_AVATAR_URL_PREFIX = "repo-avatars"
// RepoAvatarURLPrefix is used to identify a URL is to access repository avatar.
const RepoAvatarURLPrefix = "repo-avatars"
var repoWorkingPool = sync.NewExclusivePool()
@@ -213,49 +213,49 @@ type Repository struct {
UpdatedUnix int64
}
func (repo *Repository) BeforeInsert() {
repo.CreatedUnix = time.Now().Unix()
repo.UpdatedUnix = repo.CreatedUnix
func (r *Repository) BeforeInsert() {
r.CreatedUnix = time.Now().Unix()
r.UpdatedUnix = r.CreatedUnix
}
func (repo *Repository) AfterSet(colName string, _ xorm.Cell) {
func (r *Repository) AfterSet(colName string, _ xorm.Cell) {
switch colName {
case "default_branch":
// FIXME: use db migration to solve all at once.
if repo.DefaultBranch == "" {
repo.DefaultBranch = conf.Repository.DefaultBranch
if r.DefaultBranch == "" {
r.DefaultBranch = conf.Repository.DefaultBranch
}
case "num_closed_issues":
repo.NumOpenIssues = repo.NumIssues - repo.NumClosedIssues
r.NumOpenIssues = r.NumIssues - r.NumClosedIssues
case "num_closed_pulls":
repo.NumOpenPulls = repo.NumPulls - repo.NumClosedPulls
r.NumOpenPulls = r.NumPulls - r.NumClosedPulls
case "num_closed_milestones":
repo.NumOpenMilestones = repo.NumMilestones - repo.NumClosedMilestones
r.NumOpenMilestones = r.NumMilestones - r.NumClosedMilestones
case "external_tracker_style":
if repo.ExternalTrackerStyle == "" {
repo.ExternalTrackerStyle = markup.IssueNameStyleNumeric
if r.ExternalTrackerStyle == "" {
r.ExternalTrackerStyle = markup.IssueNameStyleNumeric
}
case "created_unix":
repo.Created = time.Unix(repo.CreatedUnix, 0).Local()
r.Created = time.Unix(r.CreatedUnix, 0).Local()
case "updated_unix":
repo.Updated = time.Unix(repo.UpdatedUnix, 0)
r.Updated = time.Unix(r.UpdatedUnix, 0)
}
}
func (repo *Repository) loadAttributes(e Engine) (err error) {
if repo.Owner == nil {
repo.Owner, err = getUserByID(e, repo.OwnerID)
func (r *Repository) loadAttributes(e Engine) (err error) {
if r.Owner == nil {
r.Owner, err = getUserByID(e, r.OwnerID)
if err != nil {
return fmt.Errorf("getUserByID [%d]: %v", repo.OwnerID, err)
return fmt.Errorf("getUserByID [%d]: %v", r.OwnerID, err)
}
}
if repo.IsFork && repo.BaseRepo == nil {
repo.BaseRepo, err = getRepositoryByID(e, repo.ForkID)
if r.IsFork && r.BaseRepo == nil {
r.BaseRepo, err = getRepositoryByID(e, r.ForkID)
if err != nil {
if IsErrRepoNotExist(err) {
repo.IsFork = false
repo.ForkID = 0
r.IsFork = false
r.ForkID = 0
} else {
return fmt.Errorf("get fork repository by ID: %v", err)
}
@@ -265,57 +265,57 @@ func (repo *Repository) loadAttributes(e Engine) (err error) {
return nil
}
func (repo *Repository) LoadAttributes() error {
return repo.loadAttributes(x)
func (r *Repository) LoadAttributes() error {
return r.loadAttributes(x)
}
// IsPartialPublic returns true if repository is public or allow public access to wiki or issues.
func (repo *Repository) IsPartialPublic() bool {
return !repo.IsPrivate || repo.AllowPublicWiki || repo.AllowPublicIssues
func (r *Repository) IsPartialPublic() bool {
return !r.IsPrivate || r.AllowPublicWiki || r.AllowPublicIssues
}
func (repo *Repository) CanGuestViewWiki() bool {
return repo.EnableWiki && !repo.EnableExternalWiki && repo.AllowPublicWiki
func (r *Repository) CanGuestViewWiki() bool {
return r.EnableWiki && !r.EnableExternalWiki && r.AllowPublicWiki
}
func (repo *Repository) CanGuestViewIssues() bool {
return repo.EnableIssues && !repo.EnableExternalTracker && repo.AllowPublicIssues
func (r *Repository) CanGuestViewIssues() bool {
return r.EnableIssues && !r.EnableExternalTracker && r.AllowPublicIssues
}
// MustOwner always returns a valid *User object to avoid conceptually impossible error handling.
// It creates a fake object that contains error details when error occurs.
func (repo *Repository) MustOwner() *User {
return repo.mustOwner(x)
func (r *Repository) MustOwner() *User {
return r.mustOwner(x)
}
func (repo *Repository) FullName() string {
return repo.MustOwner().Name + "/" + repo.Name
func (r *Repository) FullName() string {
return r.MustOwner().Name + "/" + r.Name
}
// Deprecated: Use repoutil.HTMLURL instead.
func (repo *Repository) HTMLURL() string {
return conf.Server.ExternalURL + repo.FullName()
func (r *Repository) HTMLURL() string {
return conf.Server.ExternalURL + r.FullName()
}
// CustomAvatarPath returns repository custom avatar file path.
func (repo *Repository) CustomAvatarPath() string {
return filepath.Join(conf.Picture.RepositoryAvatarUploadPath, com.ToStr(repo.ID))
func (r *Repository) CustomAvatarPath() string {
return filepath.Join(conf.Picture.RepositoryAvatarUploadPath, com.ToStr(r.ID))
}
// RelAvatarLink returns relative avatar link to the site domain,
// which includes app sub-url as prefix.
// Since Gravatar support not needed here - just check for image path.
func (repo *Repository) RelAvatarLink() string {
defaultImgUrl := ""
if !com.IsExist(repo.CustomAvatarPath()) {
return defaultImgUrl
func (r *Repository) RelAvatarLink() string {
defaultImgURL := ""
if !com.IsExist(r.CustomAvatarPath()) {
return defaultImgURL
}
return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, REPO_AVATAR_URL_PREFIX, repo.ID)
return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, RepoAvatarURLPrefix, r.ID)
}
// AvatarLink returns repository avatar absolute link.
func (repo *Repository) AvatarLink() string {
link := repo.RelAvatarLink()
func (r *Repository) AvatarLink() string {
link := r.RelAvatarLink()
if link[0] == '/' && link[1] != '/' {
return conf.Server.ExternalURL + strings.TrimPrefix(link, conf.Server.Subpath)[1:]
}
@@ -324,14 +324,14 @@ func (repo *Repository) AvatarLink() string {
// UploadAvatar saves custom avatar for repository.
// FIXME: split uploads to different subdirs in case we have massive number of repositories.
func (repo *Repository) UploadAvatar(data []byte) error {
func (r *Repository) UploadAvatar(data []byte) error {
img, _, err := image.Decode(bytes.NewReader(data))
if err != nil {
return fmt.Errorf("decode image: %v", err)
}
_ = os.MkdirAll(conf.Picture.RepositoryAvatarUploadPath, os.ModePerm)
fw, err := os.Create(repo.CustomAvatarPath())
fw, err := os.Create(r.CustomAvatarPath())
if err != nil {
return fmt.Errorf("create custom avatar directory: %v", err)
}
@@ -346,14 +346,14 @@ func (repo *Repository) UploadAvatar(data []byte) error {
}
// DeleteAvatar deletes the repository custom avatar.
func (repo *Repository) DeleteAvatar() error {
log.Trace("DeleteAvatar [%d]: %s", repo.ID, repo.CustomAvatarPath())
if err := os.Remove(repo.CustomAvatarPath()); err != nil {
func (r *Repository) DeleteAvatar() error {
log.Trace("DeleteAvatar [%d]: %s", r.ID, r.CustomAvatarPath())
if err := os.Remove(r.CustomAvatarPath()); err != nil {
return err
}
repo.UseCustomAvatar = false
return UpdateRepository(repo, false)
r.UseCustomAvatar = false
return UpdateRepository(r, false)
}
// This method assumes following fields have been assigned with valid values:
@@ -361,133 +361,133 @@ func (repo *Repository) DeleteAvatar() error {
// Arguments that are allowed to be nil: permission
//
// Deprecated: Use APIFormat instead.
func (repo *Repository) APIFormatLegacy(permission *api.Permission, user ...*User) *api.Repository {
cloneLink := repo.CloneLink()
func (r *Repository) APIFormatLegacy(permission *api.Permission, user ...*User) *api.Repository {
cloneLink := r.CloneLink()
apiRepo := &api.Repository{
ID: repo.ID,
Owner: repo.Owner.APIFormat(),
Name: repo.Name,
FullName: repo.FullName(),
Description: repo.Description,
Private: repo.IsPrivate,
Fork: repo.IsFork,
Empty: repo.IsBare,
Mirror: repo.IsMirror,
Size: repo.Size,
HTMLURL: repo.HTMLURL(),
ID: r.ID,
Owner: r.Owner.APIFormat(),
Name: r.Name,
FullName: r.FullName(),
Description: r.Description,
Private: r.IsPrivate,
Fork: r.IsFork,
Empty: r.IsBare,
Mirror: r.IsMirror,
Size: r.Size,
HTMLURL: r.HTMLURL(),
SSHURL: cloneLink.SSH,
CloneURL: cloneLink.HTTPS,
Website: repo.Website,
Stars: repo.NumStars,
Forks: repo.NumForks,
Watchers: repo.NumWatches,
OpenIssues: repo.NumOpenIssues,
DefaultBranch: repo.DefaultBranch,
Created: repo.Created,
Updated: repo.Updated,
Website: r.Website,
Stars: r.NumStars,
Forks: r.NumForks,
Watchers: r.NumWatches,
OpenIssues: r.NumOpenIssues,
DefaultBranch: r.DefaultBranch,
Created: r.Created,
Updated: r.Updated,
Permissions: permission,
// Reserved for go-gogs-client change
// AvatarUrl: repo.AvatarLink(),
// AvatarUrl: r.AvatarLink(),
}
if repo.IsFork {
if r.IsFork {
p := &api.Permission{Pull: true}
if len(user) != 0 {
accessMode := Handle.Permissions().AccessMode(
context.TODO(),
user[0].ID,
repo.ID,
r.ID,
AccessModeOptions{
OwnerID: repo.OwnerID,
Private: repo.IsPrivate,
OwnerID: r.OwnerID,
Private: r.IsPrivate,
},
)
p.Admin = accessMode >= AccessModeAdmin
p.Push = accessMode >= AccessModeWrite
}
apiRepo.Parent = repo.BaseRepo.APIFormatLegacy(p)
apiRepo.Parent = r.BaseRepo.APIFormatLegacy(p)
}
return apiRepo
}
func (repo *Repository) getOwner(e Engine) (err error) {
if repo.Owner != nil {
func (r *Repository) getOwner(e Engine) (err error) {
if r.Owner != nil {
return nil
}
repo.Owner, err = getUserByID(e, repo.OwnerID)
r.Owner, err = getUserByID(e, r.OwnerID)
return err
}
func (repo *Repository) GetOwner() error {
return repo.getOwner(x)
func (r *Repository) GetOwner() error {
return r.getOwner(x)
}
func (repo *Repository) mustOwner(e Engine) *User {
if err := repo.getOwner(e); err != nil {
func (r *Repository) mustOwner(e Engine) *User {
if err := r.getOwner(e); err != nil {
return &User{
Name: "error",
FullName: err.Error(),
}
}
return repo.Owner
return r.Owner
}
func (repo *Repository) UpdateSize() error {
countObject, err := git.CountObjects(repo.RepoPath())
func (r *Repository) UpdateSize() error {
countObject, err := git.CountObjects(r.RepoPath())
if err != nil {
return fmt.Errorf("count repository objects: %v", err)
}
repo.Size = countObject.Size + countObject.SizePack
if _, err = x.Id(repo.ID).Cols("size").Update(repo); err != nil {
r.Size = countObject.Size + countObject.SizePack
if _, err = x.Id(r.ID).Cols("size").Update(r); err != nil {
return fmt.Errorf("update size: %v", err)
}
return nil
}
// ComposeMetas composes a map of metas for rendering SHA1 URL and external issue tracker URL.
func (repo *Repository) ComposeMetas() map[string]string {
if repo.ExternalMetas != nil {
return repo.ExternalMetas
func (r *Repository) ComposeMetas() map[string]string {
if r.ExternalMetas != nil {
return r.ExternalMetas
}
repo.ExternalMetas = map[string]string{
"repoLink": repo.Link(),
r.ExternalMetas = map[string]string{
"repoLink": r.Link(),
}
if repo.EnableExternalTracker {
repo.ExternalMetas["user"] = repo.MustOwner().Name
repo.ExternalMetas["repo"] = repo.Name
repo.ExternalMetas["format"] = repo.ExternalTrackerFormat
if r.EnableExternalTracker {
r.ExternalMetas["user"] = r.MustOwner().Name
r.ExternalMetas["repo"] = r.Name
r.ExternalMetas["format"] = r.ExternalTrackerFormat
switch repo.ExternalTrackerStyle {
switch r.ExternalTrackerStyle {
case markup.IssueNameStyleAlphanumeric:
repo.ExternalMetas["style"] = markup.IssueNameStyleAlphanumeric
r.ExternalMetas["style"] = markup.IssueNameStyleAlphanumeric
default:
repo.ExternalMetas["style"] = markup.IssueNameStyleNumeric
r.ExternalMetas["style"] = markup.IssueNameStyleNumeric
}
}
return repo.ExternalMetas
return r.ExternalMetas
}
// DeleteWiki removes the actual and local copy of repository wiki.
func (repo *Repository) DeleteWiki() {
wikiPaths := []string{repo.WikiPath(), repo.LocalWikiPath()}
func (r *Repository) DeleteWiki() {
wikiPaths := []string{r.WikiPath(), r.LocalWikiPath()}
for _, wikiPath := range wikiPaths {
RemoveAllWithNotice("Delete repository wiki", wikiPath)
}
}
// getUsersWithAccesMode returns users that have at least given access mode to the repository.
func (repo *Repository) getUsersWithAccesMode(e Engine, mode AccessMode) (_ []*User, err error) {
if err = repo.getOwner(e); err != nil {
func (r *Repository) getUsersWithAccesMode(e Engine, mode AccessMode) (_ []*User, err error) {
if err = r.getOwner(e); err != nil {
return nil, err
}
accesses := make([]*Access, 0, 10)
if err = e.Where("repo_id = ? AND mode >= ?", repo.ID, mode).Find(&accesses); err != nil {
if err = e.Where("repo_id = ? AND mode >= ?", r.ID, mode).Find(&accesses); err != nil {
return nil, err
}
@@ -509,35 +509,35 @@ func (repo *Repository) getUsersWithAccesMode(e Engine, mode AccessMode) (_ []*U
u.FullName = markup.Sanitize(u.FullName)
}
}
if !repo.Owner.IsOrganization() {
users = append(users, repo.Owner)
if !r.Owner.IsOrganization() {
users = append(users, r.Owner)
}
return users, nil
}
// getAssignees returns a list of users who can be assigned to issues in this repository.
func (repo *Repository) getAssignees(e Engine) (_ []*User, err error) {
return repo.getUsersWithAccesMode(e, AccessModeRead)
func (r *Repository) getAssignees(e Engine) (_ []*User, err error) {
return r.getUsersWithAccesMode(e, AccessModeRead)
}
// GetAssignees returns all users that have read access and can be assigned to issues
// of the repository,
func (repo *Repository) GetAssignees() (_ []*User, err error) {
return repo.getAssignees(x)
func (r *Repository) GetAssignees() (_ []*User, err error) {
return r.getAssignees(x)
}
// GetAssigneeByID returns the user that has write access of repository by given ID.
func (repo *Repository) GetAssigneeByID(userID int64) (*User, error) {
func (r *Repository) GetAssigneeByID(userID int64) (*User, error) {
ctx := context.TODO()
if !Handle.Permissions().Authorize(
ctx,
userID,
repo.ID,
r.ID,
AccessModeRead,
AccessModeOptions{
OwnerID: repo.OwnerID,
Private: repo.IsPrivate,
OwnerID: r.OwnerID,
Private: r.IsPrivate,
},
) {
return nil, ErrUserNotExist{args: errutil.Args{"userID": userID}}
@@ -546,96 +546,96 @@ func (repo *Repository) GetAssigneeByID(userID int64) (*User, error) {
}
// GetWriters returns all users that have write access to the repository.
func (repo *Repository) GetWriters() (_ []*User, err error) {
return repo.getUsersWithAccesMode(x, AccessModeWrite)
func (r *Repository) GetWriters() (_ []*User, err error) {
return r.getUsersWithAccesMode(x, AccessModeWrite)
}
// GetMilestoneByID returns the milestone belongs to repository by given ID.
func (repo *Repository) GetMilestoneByID(milestoneID int64) (*Milestone, error) {
return GetMilestoneByRepoID(repo.ID, milestoneID)
func (r *Repository) GetMilestoneByID(milestoneID int64) (*Milestone, error) {
return GetMilestoneByRepoID(r.ID, milestoneID)
}
// IssueStats returns number of open and closed repository issues by given filter mode.
func (repo *Repository) IssueStats(userID int64, filterMode FilterMode, isPull bool) (int64, int64) {
return GetRepoIssueStats(repo.ID, userID, filterMode, isPull)
func (r *Repository) IssueStats(userID int64, filterMode FilterMode, isPull bool) (int64, int64) {
return GetRepoIssueStats(r.ID, userID, filterMode, isPull)
}
func (repo *Repository) GetMirror() (err error) {
repo.Mirror, err = GetMirrorByRepoID(repo.ID)
func (r *Repository) GetMirror() (err error) {
r.Mirror, err = GetMirrorByRepoID(r.ID)
return err
}
func (repo *Repository) repoPath(e Engine) string {
return RepoPath(repo.mustOwner(e).Name, repo.Name)
func (r *Repository) repoPath(e Engine) string {
return RepoPath(r.mustOwner(e).Name, r.Name)
}
// Deprecated: Use repoutil.RepositoryPath instead.
func (repo *Repository) RepoPath() string {
return repo.repoPath(x)
func (r *Repository) RepoPath() string {
return r.repoPath(x)
}
func (repo *Repository) GitConfigPath() string {
return filepath.Join(repo.RepoPath(), "config")
func (r *Repository) GitConfigPath() string {
return filepath.Join(r.RepoPath(), "config")
}
func (repo *Repository) RelLink() string {
return "/" + repo.FullName()
func (r *Repository) RelLink() string {
return "/" + r.FullName()
}
func (repo *Repository) Link() string {
return conf.Server.Subpath + "/" + repo.FullName()
func (r *Repository) Link() string {
return conf.Server.Subpath + "/" + r.FullName()
}
// Deprecated: Use repoutil.ComparePath instead.
func (repo *Repository) ComposeCompareURL(oldCommitID, newCommitID string) string {
return fmt.Sprintf("%s/%s/compare/%s...%s", repo.MustOwner().Name, repo.Name, oldCommitID, newCommitID)
func (r *Repository) ComposeCompareURL(oldCommitID, newCommitID string) string {
return fmt.Sprintf("%s/%s/compare/%s...%s", r.MustOwner().Name, r.Name, oldCommitID, newCommitID)
}
func (repo *Repository) HasAccess(userID int64) bool {
return Handle.Permissions().Authorize(context.TODO(), userID, repo.ID, AccessModeRead,
func (r *Repository) HasAccess(userID int64) bool {
return Handle.Permissions().Authorize(context.TODO(), userID, r.ID, AccessModeRead,
AccessModeOptions{
OwnerID: repo.OwnerID,
Private: repo.IsPrivate,
OwnerID: r.OwnerID,
Private: r.IsPrivate,
},
)
}
func (repo *Repository) IsOwnedBy(userID int64) bool {
return repo.OwnerID == userID
func (r *Repository) IsOwnedBy(userID int64) bool {
return r.OwnerID == userID
}
// CanBeForked returns true if repository meets the requirements of being forked.
func (repo *Repository) CanBeForked() bool {
return !repo.IsBare
func (r *Repository) CanBeForked() bool {
return !r.IsBare
}
// CanEnablePulls returns true if repository meets the requirements of accepting pulls.
func (repo *Repository) CanEnablePulls() bool {
return !repo.IsMirror && !repo.IsBare
func (r *Repository) CanEnablePulls() bool {
return !r.IsMirror && !r.IsBare
}
// AllowPulls returns true if repository meets the requirements of accepting pulls and has them enabled.
func (repo *Repository) AllowsPulls() bool {
return repo.CanEnablePulls() && repo.EnablePulls
func (r *Repository) AllowsPulls() bool {
return r.CanEnablePulls() && r.EnablePulls
}
func (repo *Repository) IsBranchRequirePullRequest(name string) bool {
return IsBranchOfRepoRequirePullRequest(repo.ID, name)
func (r *Repository) IsBranchRequirePullRequest(name string) bool {
return IsBranchOfRepoRequirePullRequest(r.ID, name)
}
// CanEnableEditor returns true if repository meets the requirements of web editor.
func (repo *Repository) CanEnableEditor() bool {
return !repo.IsMirror
func (r *Repository) CanEnableEditor() bool {
return !r.IsMirror
}
// FIXME: should have a mutex to prevent producing same index for two issues that are created
// closely enough.
func (repo *Repository) NextIssueIndex() int64 {
return int64(repo.NumIssues+repo.NumPulls) + 1
func (r *Repository) NextIssueIndex() int64 {
return int64(r.NumIssues+r.NumPulls) + 1
}
func (repo *Repository) LocalCopyPath() string {
return filepath.Join(conf.Server.AppDataPath, "tmp", "local-repo", com.ToStr(repo.ID))
func (r *Repository) LocalCopyPath() string {
return filepath.Join(conf.Server.AppDataPath, "tmp", "local-r", com.ToStr(r.ID))
}
// UpdateLocalCopy fetches latest changes of given branch from repoPath to localPath.
@@ -685,22 +685,22 @@ func UpdateLocalCopyBranch(repoPath, localPath, branch string, isWiki bool) (err
}
// UpdateLocalCopyBranch makes sure local copy of repository in given branch is up-to-date.
func (repo *Repository) UpdateLocalCopyBranch(branch string) error {
return UpdateLocalCopyBranch(repo.RepoPath(), repo.LocalCopyPath(), branch, false)
func (r *Repository) UpdateLocalCopyBranch(branch string) error {
return UpdateLocalCopyBranch(r.RepoPath(), r.LocalCopyPath(), branch, false)
}
// PatchPath returns corresponding patch file path of repository by given issue ID.
func (repo *Repository) PatchPath(index int64) (string, error) {
if err := repo.GetOwner(); err != nil {
func (r *Repository) PatchPath(index int64) (string, error) {
if err := r.GetOwner(); err != nil {
return "", err
}
return filepath.Join(RepoPath(repo.Owner.Name, repo.Name), "pulls", com.ToStr(index)+".patch"), nil
return filepath.Join(RepoPath(r.Owner.Name, r.Name), "pulls", com.ToStr(index)+".patch"), nil
}
// SavePatch saves patch data to corresponding location by given issue ID.
func (repo *Repository) SavePatch(index int64, patch []byte) error {
patchPath, err := repo.PatchPath(index)
func (r *Repository) SavePatch(index int64, patch []byte) error {
patchPath, err := r.PatchPath(index)
if err != nil {
return fmt.Errorf("PatchPath: %v", err)
}
@@ -729,28 +729,28 @@ func IsRepositoryExist(u *User, repoName string) (bool, error) {
}
// Deprecated: Use repoutil.NewCloneLink instead.
func (repo *Repository) cloneLink(isWiki bool) *repoutil.CloneLink {
repoName := repo.Name
func (r *Repository) cloneLink(isWiki bool) *repoutil.CloneLink {
repoName := r.Name
if isWiki {
repoName += ".wiki"
}
repo.Owner = repo.MustOwner()
r.Owner = r.MustOwner()
cl := new(repoutil.CloneLink)
if conf.SSH.Port != 22 {
cl.SSH = fmt.Sprintf("ssh://%s@%s:%d/%s/%s.git", conf.App.RunUser, conf.SSH.Domain, conf.SSH.Port, repo.Owner.Name, repoName)
cl.SSH = fmt.Sprintf("ssh://%s@%s:%d/%s/%s.git", conf.App.RunUser, conf.SSH.Domain, conf.SSH.Port, r.Owner.Name, repoName)
} else {
cl.SSH = fmt.Sprintf("%s@%s:%s/%s.git", conf.App.RunUser, conf.SSH.Domain, repo.Owner.Name, repoName)
cl.SSH = fmt.Sprintf("%s@%s:%s/%s.git", conf.App.RunUser, conf.SSH.Domain, r.Owner.Name, repoName)
}
cl.HTTPS = repoutil.HTTPSCloneURL(repo.Owner.Name, repoName)
cl.HTTPS = repoutil.HTTPSCloneURL(r.Owner.Name, repoName)
return cl
}
// CloneLink returns clone URLs of repository.
//
// Deprecated: Use repoutil.NewCloneLink instead.
func (repo *Repository) CloneLink() (cl *repoutil.CloneLink) {
return repo.cloneLink(false)
func (r *Repository) CloneLink() (cl *repoutil.CloneLink) {
return r.cloneLink(false)
}
type MigrateRepoOptions struct {
@@ -1729,7 +1729,7 @@ func DeleteRepository(ownerID, repoID int64) error {
}
if err = sess.Commit(); err != nil {
return fmt.Errorf("Commit: %v", err)
return fmt.Errorf("commit: %v", err)
}
// Remove repository files.
@@ -1905,11 +1905,11 @@ func SearchRepositoryByName(opts *SearchRepoOptions) (repos []*Repository, count
}
func DeleteOldRepositoryArchives() {
if taskStatusTable.IsRunning(_CLEAN_OLD_ARCHIVES) {
if taskStatusTable.IsRunning(taskNameCleanOldArchives) {
return
}
taskStatusTable.Start(_CLEAN_OLD_ARCHIVES)
defer taskStatusTable.Stop(_CLEAN_OLD_ARCHIVES)
taskStatusTable.Start(taskNameCleanOldArchives)
defer taskStatusTable.Stop(taskNameCleanOldArchives)
log.Trace("Doing: DeleteOldRepositoryArchives")
@@ -1945,9 +1945,13 @@ func DeleteOldRepositoryArchives() {
archivePath := filepath.Join(dirPath, fi.Name())
if err = os.Remove(archivePath); err != nil {
desc := fmt.Sprintf("Failed to health delete archive '%s': %v", archivePath, err)
log.Warn(desc)
if err = Handle.Notices().Create(context.TODO(), NoticeTypeRepository, desc); err != nil {
const fmtStr = "Failed to health delete archive %q: %v"
log.Warn(fmtStr, archivePath, err)
if err = Handle.Notices().Create(
context.TODO(),
NoticeTypeRepository,
fmt.Sprintf(fmtStr, archivePath, err),
); err != nil {
log.Error("CreateRepositoryNotice: %v", err)
}
}
@@ -1962,11 +1966,11 @@ func DeleteOldRepositoryArchives() {
// DeleteRepositoryArchives deletes all repositories' archives.
func DeleteRepositoryArchives() error {
if taskStatusTable.IsRunning(_CLEAN_OLD_ARCHIVES) {
if taskStatusTable.IsRunning(taskNameCleanOldArchives) {
return nil
}
taskStatusTable.Start(_CLEAN_OLD_ARCHIVES)
defer taskStatusTable.Stop(_CLEAN_OLD_ARCHIVES)
taskStatusTable.Start(taskNameCleanOldArchives)
defer taskStatusTable.Stop(taskNameCleanOldArchives)
return x.Where("id > 0").Iterate(new(Repository),
func(idx int, bean any) error {
@@ -2057,19 +2061,19 @@ func SyncRepositoryHooks() error {
var taskStatusTable = sync.NewStatusTable()
const (
_MIRROR_UPDATE = "mirror_update"
_GIT_FSCK = "git_fsck"
_CHECK_REPO_STATS = "check_repos_stats"
_CLEAN_OLD_ARCHIVES = "clean_old_archives"
taskNameMirrorUpdate = "mirror_update"
taskNameGitFSCK = "git_fsck"
taskNameCheckRepoStats = "check_repos_stats"
taskNameCleanOldArchives = "clean_old_archives"
)
// GitFsck calls 'git fsck' to check repository health.
func GitFsck() {
if taskStatusTable.IsRunning(_GIT_FSCK) {
if taskStatusTable.IsRunning(taskNameGitFSCK) {
return
}
taskStatusTable.Start(_GIT_FSCK)
defer taskStatusTable.Stop(_GIT_FSCK)
taskStatusTable.Start(taskNameGitFSCK)
defer taskStatusTable.Stop(taskNameGitFSCK)
log.Trace("Doing: GitFsck")
@@ -2084,9 +2088,13 @@ func GitFsck() {
Timeout: conf.Cron.RepoHealthCheck.Timeout,
})
if err != nil {
desc := fmt.Sprintf("Failed to perform health check on repository '%s': %v", repoPath, err)
log.Warn(desc)
if err = Handle.Notices().Create(context.TODO(), NoticeTypeRepository, desc); err != nil {
const fmtStr = "Failed to perform health check on repository %q: %v"
log.Warn(fmtStr, repoPath, err)
if err = Handle.Notices().Create(
context.TODO(),
NoticeTypeRepository,
fmt.Sprintf(fmtStr, repoPath, err),
); err != nil {
log.Error("CreateRepositoryNotice: %v", err)
}
}
@@ -2137,11 +2145,11 @@ func repoStatsCheck(checker *repoChecker) {
}
func CheckRepoStats() {
if taskStatusTable.IsRunning(_CHECK_REPO_STATS) {
if taskStatusTable.IsRunning(taskNameCheckRepoStats) {
return
}
taskStatusTable.Start(_CHECK_REPO_STATS)
defer taskStatusTable.Stop(_CHECK_REPO_STATS)
taskStatusTable.Start(taskNameCheckRepoStats)
defer taskStatusTable.Stop(taskNameCheckRepoStats)
log.Trace("Doing: CheckRepoStats")
@@ -2389,9 +2397,9 @@ func GetWatchers(repoID int64) ([]*Watch, error) {
}
// Repository.GetWatchers returns range of users watching given repository.
func (repo *Repository) GetWatchers(page int) ([]*User, error) {
func (r *Repository) GetWatchers(page int) ([]*User, error) {
users := make([]*User, 0, ItemsPerPage)
sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("watch.repo_id=?", repo.ID)
sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("watch.repo_id=?", r.ID)
if conf.UsePostgreSQL {
sess = sess.Join("LEFT", "watch", `"user".id=watch.user_id`)
} else {
@@ -2489,9 +2497,9 @@ func IsStaring(userID, repoID int64) bool {
return has
}
func (repo *Repository) GetStargazers(page int) ([]*User, error) {
func (r *Repository) GetStargazers(page int) ([]*User, error) {
users := make([]*User, 0, ItemsPerPage)
sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("star.repo_id=?", repo.ID)
sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("star.repo_id=?", r.ID)
if conf.UsePostgreSQL {
sess = sess.Join("LEFT", "star", `"user".id=star.uid`)
} else {
@@ -2573,7 +2581,7 @@ func ForkRepository(doer, owner *User, baseRepo *Repository, name, desc string)
}
if err = sess.Commit(); err != nil {
return nil, fmt.Errorf("Commit: %v", err)
return nil, fmt.Errorf("commit: %v", err)
}
// Remember visibility preference
@@ -2585,7 +2593,7 @@ func ForkRepository(doer, owner *User, baseRepo *Repository, name, desc string)
if err = repo.UpdateSize(); err != nil {
log.Error("UpdateSize [repo_id: %d]: %v", repo.ID, err)
}
if err = PrepareWebhooks(baseRepo, HOOK_EVENT_FORK, &api.ForkPayload{
if err = PrepareWebhooks(baseRepo, HookEventTypeFork, &api.ForkPayload{
Forkee: repo.APIFormatLegacy(nil),
Repo: baseRepo.APIFormatLegacy(nil),
Sender: doer.APIFormat(),
@@ -2595,14 +2603,14 @@ func ForkRepository(doer, owner *User, baseRepo *Repository, name, desc string)
return repo, nil
}
func (repo *Repository) GetForks() ([]*Repository, error) {
forks := make([]*Repository, 0, repo.NumForks)
if err := x.Find(&forks, &Repository{ForkID: repo.ID}); err != nil {
func (r *Repository) GetForks() ([]*Repository, error) {
forks := make([]*Repository, 0, r.NumForks)
if err := x.Find(&forks, &Repository{ForkID: r.ID}); err != nil {
return nil, err
}
for _, fork := range forks {
fork.BaseRepo = repo
fork.BaseRepo = r
}
return forks, nil
}
@@ -2615,19 +2623,19 @@ func (repo *Repository) GetForks() ([]*Repository, error) {
// \/ \/ \/ \/ \/
//
func (repo *Repository) CreateNewBranch(oldBranch, newBranch string) (err error) {
repoWorkingPool.CheckIn(com.ToStr(repo.ID))
defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
func (r *Repository) CreateNewBranch(oldBranch, newBranch string) (err error) {
repoWorkingPool.CheckIn(com.ToStr(r.ID))
defer repoWorkingPool.CheckOut(com.ToStr(r.ID))
localPath := repo.LocalCopyPath()
localPath := r.LocalCopyPath()
if err = discardLocalRepoBranchChanges(localPath, oldBranch); err != nil {
return fmt.Errorf("discard changes in local copy [path: %s, branch: %s]: %v", localPath, oldBranch, err)
} else if err = repo.UpdateLocalCopyBranch(oldBranch); err != nil {
} else if err = r.UpdateLocalCopyBranch(oldBranch); err != nil {
return fmt.Errorf("update branch for local copy [path: %s, branch: %s]: %v", localPath, oldBranch, err)
}
if err = repo.CheckoutNewBranch(oldBranch, newBranch); err != nil {
if err = r.CheckoutNewBranch(oldBranch, newBranch); err != nil {
return fmt.Errorf("create new branch [base: %s, new: %s]: %v", oldBranch, newBranch, err)
}
@@ -2639,18 +2647,18 @@ func (repo *Repository) CreateNewBranch(oldBranch, newBranch string) (err error)
}
// Deprecated: Use Perms.SetRepoPerms instead.
func (repo *Repository) refreshAccesses(e Engine, accessMap map[int64]AccessMode) (err error) {
func (r *Repository) refreshAccesses(e Engine, accessMap map[int64]AccessMode) (err error) {
newAccesses := make([]Access, 0, len(accessMap))
for userID, mode := range accessMap {
newAccesses = append(newAccesses, Access{
UserID: userID,
RepoID: repo.ID,
RepoID: r.ID,
Mode: mode,
})
}
// Delete old accesses and insert new ones for repository.
if _, err = e.Delete(&Access{RepoID: repo.ID}); err != nil {
if _, err = e.Delete(&Access{RepoID: r.ID}); err != nil {
return fmt.Errorf("delete old accesses: %v", err)
} else if _, err = e.Insert(newAccesses); err != nil {
return fmt.Errorf("insert new accesses: %v", err)
@@ -2659,8 +2667,8 @@ func (repo *Repository) refreshAccesses(e Engine, accessMap map[int64]AccessMode
}
// refreshCollaboratorAccesses retrieves repository collaborations with their access modes.
func (repo *Repository) refreshCollaboratorAccesses(e Engine, accessMap map[int64]AccessMode) error {
collaborations, err := repo.getCollaborations(e)
func (r *Repository) refreshCollaboratorAccesses(e Engine, accessMap map[int64]AccessMode) error {
collaborations, err := r.getCollaborations(e)
if err != nil {
return fmt.Errorf("getCollaborations: %v", err)
}
@@ -2673,20 +2681,20 @@ func (repo *Repository) refreshCollaboratorAccesses(e Engine, accessMap map[int6
// recalculateTeamAccesses recalculates new accesses for teams of an organization
// except the team whose ID is given. It is used to assign a team ID when
// remove repository from that team.
func (repo *Repository) recalculateTeamAccesses(e Engine, ignTeamID int64) (err error) {
func (r *Repository) recalculateTeamAccesses(e Engine, ignTeamID int64) (err error) {
accessMap := make(map[int64]AccessMode, 20)
if err = repo.getOwner(e); err != nil {
if err = r.getOwner(e); err != nil {
return err
} else if !repo.Owner.IsOrganization() {
return fmt.Errorf("owner is not an organization: %d", repo.OwnerID)
} else if !r.Owner.IsOrganization() {
return fmt.Errorf("owner is not an organization: %d", r.OwnerID)
}
if err = repo.refreshCollaboratorAccesses(e, accessMap); err != nil {
if err = r.refreshCollaboratorAccesses(e, accessMap); err != nil {
return fmt.Errorf("refreshCollaboratorAccesses: %v", err)
}
if err = repo.Owner.getTeams(e); err != nil {
if err = r.Owner.getTeams(e); err != nil {
return err
}
@@ -2700,7 +2708,7 @@ func (repo *Repository) recalculateTeamAccesses(e Engine, ignTeamID int64) (err
return max
}
for _, t := range repo.Owner.Teams {
for _, t := range r.Owner.Teams {
if t.ID == ignTeamID {
continue
}
@@ -2709,7 +2717,7 @@ func (repo *Repository) recalculateTeamAccesses(e Engine, ignTeamID int64) (err
// have relations with repository.
if t.IsOwnerTeam() {
t.Authorize = AccessModeOwner
} else if !t.hasRepository(e, repo.ID) {
} else if !t.hasRepository(e, r.ID) {
continue
}
@@ -2721,22 +2729,22 @@ func (repo *Repository) recalculateTeamAccesses(e Engine, ignTeamID int64) (err
}
}
return repo.refreshAccesses(e, accessMap)
return r.refreshAccesses(e, accessMap)
}
func (repo *Repository) recalculateAccesses(e Engine) error {
if repo.Owner.IsOrganization() {
return repo.recalculateTeamAccesses(e, 0)
func (r *Repository) recalculateAccesses(e Engine) error {
if r.Owner.IsOrganization() {
return r.recalculateTeamAccesses(e, 0)
}
accessMap := make(map[int64]AccessMode, 10)
if err := repo.refreshCollaboratorAccesses(e, accessMap); err != nil {
if err := r.refreshCollaboratorAccesses(e, accessMap); err != nil {
return fmt.Errorf("refreshCollaboratorAccesses: %v", err)
}
return repo.refreshAccesses(e, accessMap)
return r.refreshAccesses(e, accessMap)
}
// RecalculateAccesses recalculates all accesses for repository.
func (repo *Repository) RecalculateAccesses() error {
return repo.recalculateAccesses(x)
func (r *Repository) RecalculateAccesses() error {
return r.recalculateAccesses(x)
}

View File

@@ -64,18 +64,18 @@ func (ErrBranchNotExist) NotFound() bool {
return true
}
func (repo *Repository) GetBranch(name string) (*Branch, error) {
if !git.RepoHasBranch(repo.RepoPath(), name) {
func (r *Repository) GetBranch(name string) (*Branch, error) {
if !git.RepoHasBranch(r.RepoPath(), name) {
return nil, ErrBranchNotExist{args: map[string]any{"name": name}}
}
return &Branch{
RepoPath: repo.RepoPath(),
RepoPath: r.RepoPath(),
Name: name,
}, nil
}
func (repo *Repository) GetBranches() ([]*Branch, error) {
return GetBranchesByPath(repo.RepoPath())
func (r *Repository) GetBranches() ([]*Branch, error) {
return GetBranchesByPath(r.RepoPath())
}
func (br *Branch) GetCommit() (*git.Commit, error) {
@@ -147,12 +147,12 @@ func UpdateProtectBranch(protectBranch *ProtectBranch) (err error) {
if protectBranch.ID == 0 {
if _, err = sess.Insert(protectBranch); err != nil {
return fmt.Errorf("Insert: %v", err)
return fmt.Errorf("insert: %v", err)
}
}
if _, err = sess.ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil {
return fmt.Errorf("Update: %v", err)
return fmt.Errorf("update: %v", err)
}
return sess.Commit()
@@ -213,7 +213,7 @@ func UpdateOrgProtectBranch(repo *Repository, protectBranch *ProtectBranch, whit
// Make sure protectBranch.ID is not 0 for whitelists
if protectBranch.ID == 0 {
if _, err = x.Insert(protectBranch); err != nil {
return fmt.Errorf("Insert: %v", err)
return fmt.Errorf("insert: %v", err)
}
}

View File

@@ -47,14 +47,14 @@ func IsCollaborator(repoID, userID int64) bool {
return has
}
func (repo *Repository) IsCollaborator(userID int64) bool {
return IsCollaborator(repo.ID, userID)
func (r *Repository) IsCollaborator(userID int64) bool {
return IsCollaborator(r.ID, userID)
}
// AddCollaborator adds new collaboration to a repository with default access mode.
func (repo *Repository) AddCollaborator(u *User) error {
func (r *Repository) AddCollaborator(u *User) error {
collaboration := &Collaboration{
RepoID: repo.ID,
RepoID: r.ID,
UserID: u.ID,
}
@@ -74,16 +74,16 @@ func (repo *Repository) AddCollaborator(u *User) error {
if _, err = sess.Insert(collaboration); err != nil {
return err
} else if err = repo.recalculateAccesses(sess); err != nil {
return fmt.Errorf("recalculateAccesses [repo_id: %v]: %v", repo.ID, err)
} else if err = r.recalculateAccesses(sess); err != nil {
return fmt.Errorf("recalculateAccesses [repo_id: %v]: %v", r.ID, err)
}
return sess.Commit()
}
func (repo *Repository) getCollaborations(e Engine) ([]*Collaboration, error) {
func (r *Repository) getCollaborations(e Engine) ([]*Collaboration, error) {
collaborations := make([]*Collaboration, 0)
return collaborations, e.Find(&collaborations, &Collaboration{RepoID: repo.ID})
return collaborations, e.Find(&collaborations, &Collaboration{RepoID: r.ID})
}
// Collaborator represents a user with collaboration details.
@@ -103,8 +103,8 @@ func (c *Collaborator) APIFormat() *api.Collaborator {
}
}
func (repo *Repository) getCollaborators(e Engine) ([]*Collaborator, error) {
collaborations, err := repo.getCollaborations(e)
func (r *Repository) getCollaborators(e Engine) ([]*Collaborator, error) {
collaborations, err := r.getCollaborations(e)
if err != nil {
return nil, fmt.Errorf("getCollaborations: %v", err)
}
@@ -124,19 +124,19 @@ func (repo *Repository) getCollaborators(e Engine) ([]*Collaborator, error) {
}
// GetCollaborators returns the collaborators for a repository
func (repo *Repository) GetCollaborators() ([]*Collaborator, error) {
return repo.getCollaborators(x)
func (r *Repository) GetCollaborators() ([]*Collaborator, error) {
return r.getCollaborators(x)
}
// ChangeCollaborationAccessMode sets new access mode for the collaboration.
func (repo *Repository) ChangeCollaborationAccessMode(userID int64, mode AccessMode) error {
func (r *Repository) ChangeCollaborationAccessMode(userID int64, mode AccessMode) error {
// Discard invalid input
if mode <= AccessModeNone || mode > AccessModeOwner {
return nil
}
collaboration := &Collaboration{
RepoID: repo.ID,
RepoID: r.ID,
UserID: userID,
}
has, err := x.Get(collaboration)
@@ -152,10 +152,10 @@ func (repo *Repository) ChangeCollaborationAccessMode(userID int64, mode AccessM
collaboration.Mode = mode
// If it's an organizational repository, merge with team access level for highest permission
if repo.Owner.IsOrganization() {
teams, err := GetUserTeams(repo.OwnerID, userID)
if r.Owner.IsOrganization() {
teams, err := GetUserTeams(r.OwnerID, userID)
if err != nil {
return fmt.Errorf("GetUserTeams: [org_id: %d, user_id: %d]: %v", repo.OwnerID, userID, err)
return fmt.Errorf("GetUserTeams: [org_id: %d, user_id: %d]: %v", r.OwnerID, userID, err)
}
for i := range teams {
if mode < teams[i].Authorize {
@@ -176,14 +176,14 @@ func (repo *Repository) ChangeCollaborationAccessMode(userID int64, mode AccessM
access := &Access{
UserID: userID,
RepoID: repo.ID,
RepoID: r.ID,
}
has, err = sess.Get(access)
if err != nil {
return fmt.Errorf("get access record: %v", err)
}
if has {
_, err = sess.Exec("UPDATE access SET mode = ? WHERE user_id = ? AND repo_id = ?", mode, userID, repo.ID)
_, err = sess.Exec("UPDATE access SET mode = ? WHERE user_id = ? AND repo_id = ?", mode, userID, r.ID)
} else {
access.Mode = mode
_, err = sess.Insert(access)
@@ -221,6 +221,6 @@ func DeleteCollaboration(repo *Repository, userID int64) (err error) {
return sess.Commit()
}
func (repo *Repository) DeleteCollaboration(userID int64) error {
return DeleteCollaboration(repo, userID)
func (r *Repository) DeleteCollaboration(userID int64) error {
return DeleteCollaboration(r, userID)
}

View File

@@ -32,14 +32,14 @@ import (
)
const (
ENV_AUTH_USER_ID = "GOGS_AUTH_USER_ID"
ENV_AUTH_USER_NAME = "GOGS_AUTH_USER_NAME"
ENV_AUTH_USER_EMAIL = "GOGS_AUTH_USER_EMAIL"
ENV_REPO_OWNER_NAME = "GOGS_REPO_OWNER_NAME"
ENV_REPO_OWNER_SALT_MD5 = "GOGS_REPO_OWNER_SALT_MD5"
ENV_REPO_ID = "GOGS_REPO_ID"
ENV_REPO_NAME = "GOGS_REPO_NAME"
ENV_REPO_CUSTOM_HOOKS_PATH = "GOGS_REPO_CUSTOM_HOOKS_PATH"
EnvAuthUserID = "GOGS_AUTH_USER_ID"
EnvAuthUserName = "GOGS_AUTH_USER_NAME"
EnvAuthUserEmail = "GOGS_AUTH_USER_EMAIL"
EnvRepoOwnerName = "GOGS_REPO_OWNER_NAME"
EnvRepoOwnerSaltMd5 = "GOGS_REPO_OWNER_SALT_MD5"
EnvRepoID = "GOGS_REPO_ID"
EnvRepoName = "GOGS_REPO_NAME"
EnvRepoCustomHooksPath = "GOGS_REPO_CUSTOM_HOOKS_PATH"
)
type ComposeHookEnvsOptions struct {
@@ -54,14 +54,14 @@ type ComposeHookEnvsOptions struct {
func ComposeHookEnvs(opts ComposeHookEnvsOptions) []string {
envs := []string{
"SSH_ORIGINAL_COMMAND=1",
ENV_AUTH_USER_ID + "=" + com.ToStr(opts.AuthUser.ID),
ENV_AUTH_USER_NAME + "=" + opts.AuthUser.Name,
ENV_AUTH_USER_EMAIL + "=" + opts.AuthUser.Email,
ENV_REPO_OWNER_NAME + "=" + opts.OwnerName,
ENV_REPO_OWNER_SALT_MD5 + "=" + cryptoutil.MD5(opts.OwnerSalt),
ENV_REPO_ID + "=" + com.ToStr(opts.RepoID),
ENV_REPO_NAME + "=" + opts.RepoName,
ENV_REPO_CUSTOM_HOOKS_PATH + "=" + filepath.Join(opts.RepoPath, "custom_hooks"),
EnvAuthUserID + "=" + com.ToStr(opts.AuthUser.ID),
EnvAuthUserName + "=" + opts.AuthUser.Name,
EnvAuthUserEmail + "=" + opts.AuthUser.Email,
EnvRepoOwnerName + "=" + opts.OwnerName,
EnvRepoOwnerSaltMd5 + "=" + cryptoutil.MD5(opts.OwnerSalt),
EnvRepoID + "=" + com.ToStr(opts.RepoID),
EnvRepoName + "=" + opts.RepoName,
EnvRepoCustomHooksPath + "=" + filepath.Join(opts.RepoPath, "custom_hooks"),
}
return envs
}
@@ -92,13 +92,13 @@ func discardLocalRepoBranchChanges(localPath, branch string) error {
return nil
}
func (repo *Repository) DiscardLocalRepoBranchChanges(branch string) error {
return discardLocalRepoBranchChanges(repo.LocalCopyPath(), branch)
func (r *Repository) DiscardLocalRepoBranchChanges(branch string) error {
return discardLocalRepoBranchChanges(r.LocalCopyPath(), branch)
}
// CheckoutNewBranch checks out to a new branch from the a branch name.
func (repo *Repository) CheckoutNewBranch(oldBranch, newBranch string) error {
if err := git.Checkout(repo.LocalCopyPath(), newBranch, git.CheckoutOptions{
func (r *Repository) CheckoutNewBranch(oldBranch, newBranch string) error {
if err := git.Checkout(r.LocalCopyPath(), newBranch, git.CheckoutOptions{
BaseBranch: oldBranch,
Timeout: time.Duration(conf.Git.Timeout.Pull) * time.Second,
}); err != nil {
@@ -118,23 +118,23 @@ type UpdateRepoFileOptions struct {
}
// UpdateRepoFile adds or updates a file in repository.
func (repo *Repository) UpdateRepoFile(doer *User, opts UpdateRepoFileOptions) (err error) {
func (r *Repository) UpdateRepoFile(doer *User, opts UpdateRepoFileOptions) (err error) {
// 🚨 SECURITY: Prevent uploading files into the ".git" directory.
if isRepositoryGitPath(opts.NewTreeName) {
return errors.Errorf("bad tree path %q", opts.NewTreeName)
}
repoWorkingPool.CheckIn(com.ToStr(repo.ID))
defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
repoWorkingPool.CheckIn(com.ToStr(r.ID))
defer repoWorkingPool.CheckOut(com.ToStr(r.ID))
if err = repo.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
return fmt.Errorf("discard local repo branch[%s] changes: %v", opts.OldBranch, err)
} else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
if err = r.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
return fmt.Errorf("discard local r branch[%s] changes: %v", opts.OldBranch, err)
} else if err = r.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err)
}
repoPath := repo.RepoPath()
localPath := repo.LocalCopyPath()
repoPath := r.RepoPath()
localPath := r.LocalCopyPath()
if opts.OldBranch != opts.NewBranch {
// Directly return error if new branch already exists in the server
@@ -151,7 +151,7 @@ func (repo *Repository) UpdateRepoFile(doer *User, opts UpdateRepoFileOptions) (
}
}
if err := repo.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
if err := r.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
return fmt.Errorf("checkout new branch[%s] from old branch[%s]: %v", opts.NewBranch, opts.OldBranch, err)
}
}
@@ -203,11 +203,11 @@ func (repo *Repository) UpdateRepoFile(doer *User, opts UpdateRepoFileOptions) (
CommandOptions: git.CommandOptions{
Envs: ComposeHookEnvs(ComposeHookEnvsOptions{
AuthUser: doer,
OwnerName: repo.MustOwner().Name,
OwnerSalt: repo.MustOwner().Salt,
RepoID: repo.ID,
RepoName: repo.Name,
RepoPath: repo.RepoPath(),
OwnerName: r.MustOwner().Name,
OwnerSalt: r.MustOwner().Salt,
RepoID: r.ID,
RepoName: r.Name,
RepoPath: r.RepoPath(),
}),
},
},
@@ -219,22 +219,22 @@ func (repo *Repository) UpdateRepoFile(doer *User, opts UpdateRepoFileOptions) (
}
// GetDiffPreview produces and returns diff result of a file which is not yet committed.
func (repo *Repository) GetDiffPreview(branch, treePath, content string) (diff *gitutil.Diff, err error) {
func (r *Repository) GetDiffPreview(branch, treePath, content string) (diff *gitutil.Diff, err error) {
// 🚨 SECURITY: Prevent uploading files into the ".git" directory.
if isRepositoryGitPath(treePath) {
return nil, errors.Errorf("bad tree path %q", treePath)
}
repoWorkingPool.CheckIn(com.ToStr(repo.ID))
defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
repoWorkingPool.CheckIn(com.ToStr(r.ID))
defer repoWorkingPool.CheckOut(com.ToStr(r.ID))
if err = repo.DiscardLocalRepoBranchChanges(branch); err != nil {
return nil, fmt.Errorf("discard local repo branch[%s] changes: %v", branch, err)
} else if err = repo.UpdateLocalCopyBranch(branch); err != nil {
if err = r.DiscardLocalRepoBranchChanges(branch); err != nil {
return nil, fmt.Errorf("discard local r branch[%s] changes: %v", branch, err)
} else if err = r.UpdateLocalCopyBranch(branch); err != nil {
return nil, fmt.Errorf("update local copy branch[%s]: %v", branch, err)
}
localPath := repo.LocalCopyPath()
localPath := r.LocalCopyPath()
filePath := path.Join(localPath, treePath)
if err = os.MkdirAll(filepath.Dir(filePath), os.ModePerm); err != nil {
return nil, err
@@ -257,7 +257,7 @@ func (repo *Repository) GetDiffPreview(branch, treePath, content string) (diff *
return nil, fmt.Errorf("start: %v", err)
}
pid := process.Add(fmt.Sprintf("GetDiffPreview [repo_path: %s]", repo.RepoPath()), cmd)
pid := process.Add(fmt.Sprintf("GetDiffPreview [repo_path: %s]", r.RepoPath()), cmd)
defer process.Remove(pid)
diff, err = gitutil.ParseDiff(stdout, conf.Git.MaxDiffFiles, conf.Git.MaxDiffLines, conf.Git.MaxDiffLineChars)
@@ -288,28 +288,28 @@ type DeleteRepoFileOptions struct {
Message string
}
func (repo *Repository) DeleteRepoFile(doer *User, opts DeleteRepoFileOptions) (err error) {
func (r *Repository) DeleteRepoFile(doer *User, opts DeleteRepoFileOptions) (err error) {
// 🚨 SECURITY: Prevent uploading files into the ".git" directory.
if isRepositoryGitPath(opts.TreePath) {
return errors.Errorf("bad tree path %q", opts.TreePath)
}
repoWorkingPool.CheckIn(com.ToStr(repo.ID))
defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
repoWorkingPool.CheckIn(com.ToStr(r.ID))
defer repoWorkingPool.CheckOut(com.ToStr(r.ID))
if err = repo.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
return fmt.Errorf("discard local repo branch[%s] changes: %v", opts.OldBranch, err)
} else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
if err = r.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
return fmt.Errorf("discard local r branch[%s] changes: %v", opts.OldBranch, err)
} else if err = r.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err)
}
if opts.OldBranch != opts.NewBranch {
if err := repo.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
if err := r.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
return fmt.Errorf("checkout new branch[%s] from old branch[%s]: %v", opts.NewBranch, opts.OldBranch, err)
}
}
localPath := repo.LocalCopyPath()
localPath := r.LocalCopyPath()
if err = os.Remove(path.Join(localPath, opts.TreePath)); err != nil {
return fmt.Errorf("remove file %q: %v", opts.TreePath, err)
}
@@ -336,11 +336,11 @@ func (repo *Repository) DeleteRepoFile(doer *User, opts DeleteRepoFileOptions) (
CommandOptions: git.CommandOptions{
Envs: ComposeHookEnvs(ComposeHookEnvsOptions{
AuthUser: doer,
OwnerName: repo.MustOwner().Name,
OwnerSalt: repo.MustOwner().Salt,
RepoID: repo.ID,
RepoName: repo.Name,
RepoPath: repo.RepoPath(),
OwnerName: r.MustOwner().Name,
OwnerSalt: r.MustOwner().Salt,
RepoID: r.ID,
RepoName: r.Name,
RepoPath: r.RepoPath(),
}),
},
},
@@ -509,7 +509,7 @@ func isRepositoryGitPath(path string) bool {
strings.Contains(path, `.git.\`)
}
func (repo *Repository) UploadRepoFiles(doer *User, opts UploadRepoFileOptions) error {
func (r *Repository) UploadRepoFiles(doer *User, opts UploadRepoFileOptions) error {
if len(opts.Files) == 0 {
return nil
}
@@ -524,22 +524,22 @@ func (repo *Repository) UploadRepoFiles(doer *User, opts UploadRepoFileOptions)
return fmt.Errorf("get uploads by UUIDs[%v]: %v", opts.Files, err)
}
repoWorkingPool.CheckIn(com.ToStr(repo.ID))
defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
repoWorkingPool.CheckIn(com.ToStr(r.ID))
defer repoWorkingPool.CheckOut(com.ToStr(r.ID))
if err = repo.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
return fmt.Errorf("discard local repo branch[%s] changes: %v", opts.OldBranch, err)
} else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
if err = r.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
return fmt.Errorf("discard local r branch[%s] changes: %v", opts.OldBranch, err)
} else if err = r.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err)
}
if opts.OldBranch != opts.NewBranch {
if err = repo.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
if err = r.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
return fmt.Errorf("checkout new branch[%s] from old branch[%s]: %v", opts.NewBranch, opts.OldBranch, err)
}
}
localPath := repo.LocalCopyPath()
localPath := r.LocalCopyPath()
dirPath := path.Join(localPath, opts.TreePath)
if err = os.MkdirAll(dirPath, os.ModePerm); err != nil {
return err
@@ -588,11 +588,11 @@ func (repo *Repository) UploadRepoFiles(doer *User, opts UploadRepoFileOptions)
CommandOptions: git.CommandOptions{
Envs: ComposeHookEnvs(ComposeHookEnvsOptions{
AuthUser: doer,
OwnerName: repo.MustOwner().Name,
OwnerSalt: repo.MustOwner().Salt,
RepoID: repo.ID,
RepoName: repo.Name,
RepoPath: repo.RepoPath(),
OwnerName: r.MustOwner().Name,
OwnerSalt: r.MustOwner().Salt,
RepoID: r.ID,
RepoName: r.Name,
RepoPath: r.RepoPath(),
}),
},
},

View File

@@ -47,6 +47,6 @@ func GetTagsByPath(path string) ([]*Tag, error) {
return tags, nil
}
func (repo *Repository) GetTags() ([]*Tag, error) {
return GetTagsByPath(repo.RepoPath())
func (r *Repository) GetTags() ([]*Tag, error) {
return GetTagsByPath(r.RepoPath())
}

View File

@@ -23,7 +23,7 @@ func TestRepository_ComposeMetas(t *testing.T) {
metas := repo.ComposeMetas()
assert.Equal(t, metas["repoLink"], repo.Link())
// Should no format and style if no external tracker is configured
// Should not have format and style if no external tracker is configured
_, ok := metas["format"]
assert.False(t, ok)
_, ok = metas["style"]

View File

@@ -82,12 +82,12 @@ func main() {
if len(ti.Indexes) > 0 {
_, _ = w.WriteString("Indexes: \n")
for _, index := range ti.Indexes {
_, _ = w.WriteString(fmt.Sprintf("\t%q", index.Name))
_, _ = fmt.Fprintf(w, "\t%q", index.Name)
if index.Class != "" {
_, _ = w.WriteString(fmt.Sprintf(" %s", index.Class))
_, _ = fmt.Fprintf(w, " %s", index.Class)
}
if index.Type != "" {
_, _ = w.WriteString(fmt.Sprintf(", %s", index.Type))
_, _ = fmt.Fprintf(w, ", %s", index.Type)
}
if len(index.Fields) > 0 {
@@ -95,7 +95,7 @@ func main() {
for i := range index.Fields {
fields[i] = index.Fields[i].DBName
}
_, _ = w.WriteString(fmt.Sprintf(" (%s)", strings.Join(fields, ", ")))
_, _ = fmt.Fprintf(w, " (%s)", strings.Join(fields, ", "))
}
_, _ = w.WriteString("\n")
}

View File

@@ -29,7 +29,7 @@ import (
)
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
@@ -37,8 +37,8 @@ var sshOpLocker sync.Mutex
type KeyType int
const (
KEY_TYPE_USER = iota + 1
KEY_TYPE_DEPLOY
KeyTypeUser = iota + 1
KeyTypeDeploy
)
// PublicKey represents a user or deploy SSH public key.
@@ -85,12 +85,12 @@ func (k *PublicKey) OmitEmail() string {
// AuthorizedString returns formatted public key string for authorized_keys file.
func (k *PublicKey) AuthorizedString() string {
return fmt.Sprintf(_TPL_PUBLICK_KEY, conf.AppPath(), k.ID, conf.CustomConf, k.Content)
return fmt.Sprintf(tplPublicKey, conf.AppPath(), k.ID, conf.CustomConf, k.Content)
}
// IsDeployKey returns true if the public key is used as deploy key.
func (k *PublicKey) IsDeployKey() bool {
return k.Type == KEY_TYPE_DEPLOY
return k.Type == KeyTypeDeploy
}
func extractTypeFromBase64Key(key string) (string, error) {
@@ -362,7 +362,7 @@ func appendAuthorizedKeysToFile(keys ...*PublicKey) error {
func checkKeyContent(content string) error {
has, err := x.Get(&PublicKey{
Content: content,
Type: KEY_TYPE_USER,
Type: KeyTypeUser,
})
if err != nil {
return err
@@ -402,7 +402,7 @@ func addKey(e Engine, key *PublicKey) (err error) {
// AddPublicKey adds new public key to database and authorized_keys file.
func AddPublicKey(ownerID int64, name, content string) (*PublicKey, error) {
log.Trace(content)
log.Trace("Add public key: %s", content)
if err := checkKeyContent(content); err != nil {
return nil, err
}
@@ -426,7 +426,7 @@ func AddPublicKey(ownerID int64, name, content string) (*PublicKey, error) {
Name: name,
Content: content,
Mode: AccessModeWrite,
Type: KEY_TYPE_USER,
Type: KeyTypeUser,
}
if err = addKey(sess, key); err != nil {
return nil, fmt.Errorf("addKey: %v", err)
@@ -659,7 +659,7 @@ func AddDeployKey(repoID int64, name, content string) (*DeployKey, error) {
pkey := &PublicKey{
Content: content,
Mode: AccessModeRead,
Type: KEY_TYPE_DEPLOY,
Type: KeyTypeDeploy,
}
has, err := x.Get(pkey)
if err != nil {

View File

@@ -792,13 +792,13 @@ func (s *UsersStore) GetMailableEmailsByUsernames(ctx context.Context, usernames
// IsUsernameUsed returns true if the given username has been used other than
// the excluded user (a non-positive ID effectively meaning check against all
// users).
func (s *UsersStore) IsUsernameUsed(ctx context.Context, username string, excludeUserId int64) bool {
func (s *UsersStore) IsUsernameUsed(ctx context.Context, username string, excludeUserID int64) bool {
if username == "" {
return false
}
return s.db.WithContext(ctx).
Select("id").
Where("lower_name = ? AND id != ?", strings.ToLower(username), excludeUserId).
Where("lower_name = ? AND id != ?", strings.ToLower(username), excludeUserID).
First(&User{}).
Error != gorm.ErrRecordNotFound
}
@@ -1425,8 +1425,8 @@ func (u *User) IsFollowing(followID int64) bool {
//
// TODO(unknwon): This is also used in templates, which should be fixed by
// having a dedicated type `template.User`.
func (u *User) IsUserOrgOwner(orgId int64) bool {
return IsOrganizationOwner(orgId, u.ID)
func (u *User) IsUserOrgOwner(orgID int64) bool {
return IsOrganizationOwner(orgID, u.ID)
}
// IsPublicMember returns true if the user has public membership of the given
@@ -1434,8 +1434,8 @@ func (u *User) IsUserOrgOwner(orgId int64) bool {
//
// TODO(unknwon): This is also used in templates, which should be fixed by
// having a dedicated type `template.User`.
func (u *User) IsPublicMember(orgId int64) bool {
return IsPublicMembership(orgId, u.ID)
func (u *User) IsPublicMember(orgID int64) bool {
return IsPublicMembership(orgID, u.ID)
}
// GetOrganizationCount returns the count of organization membership that the

View File

@@ -88,9 +88,9 @@ type HookEvent struct {
type HookStatus int
const (
HOOK_STATUS_NONE = iota
HOOK_STATUS_SUCCEED
HOOK_STATUS_FAILED
HookStatusNone = iota
HookStatusSucceed
HookStatusFailed
)
// Webhook represents a web hook object.
@@ -162,49 +162,49 @@ func (w *Webhook) UpdateEvent() error {
// HasCreateEvent returns true if hook enabled create event.
func (w *Webhook) HasCreateEvent() bool {
return w.SendEverything ||
(w.ChooseEvents && w.HookEvents.Create)
(w.ChooseEvents && w.Create)
}
// HasDeleteEvent returns true if hook enabled delete event.
func (w *Webhook) HasDeleteEvent() bool {
return w.SendEverything ||
(w.ChooseEvents && w.HookEvents.Delete)
(w.ChooseEvents && w.Delete)
}
// HasForkEvent returns true if hook enabled fork event.
func (w *Webhook) HasForkEvent() bool {
return w.SendEverything ||
(w.ChooseEvents && w.HookEvents.Fork)
(w.ChooseEvents && w.Fork)
}
// HasPushEvent returns true if hook enabled push event.
func (w *Webhook) HasPushEvent() bool {
return w.PushOnly || w.SendEverything ||
(w.ChooseEvents && w.HookEvents.Push)
(w.ChooseEvents && w.Push)
}
// HasIssuesEvent returns true if hook enabled issues event.
func (w *Webhook) HasIssuesEvent() bool {
return w.SendEverything ||
(w.ChooseEvents && w.HookEvents.Issues)
(w.ChooseEvents && w.Issues)
}
// HasPullRequestEvent returns true if hook enabled pull request event.
func (w *Webhook) HasPullRequestEvent() bool {
return w.SendEverything ||
(w.ChooseEvents && w.HookEvents.PullRequest)
(w.ChooseEvents && w.PullRequest)
}
// HasIssueCommentEvent returns true if hook enabled issue comment event.
func (w *Webhook) HasIssueCommentEvent() bool {
return w.SendEverything ||
(w.ChooseEvents && w.HookEvents.IssueComment)
(w.ChooseEvents && w.IssueComment)
}
// HasReleaseEvent returns true if hook enabled release event.
func (w *Webhook) HasReleaseEvent() bool {
return w.SendEverything ||
(w.ChooseEvents && w.HookEvents.Release)
(w.ChooseEvents && w.Release)
}
type eventChecker struct {
@@ -215,14 +215,14 @@ type eventChecker struct {
func (w *Webhook) EventsArray() []string {
events := make([]string, 0, 8)
eventCheckers := []eventChecker{
{w.HasCreateEvent, HOOK_EVENT_CREATE},
{w.HasDeleteEvent, HOOK_EVENT_DELETE},
{w.HasForkEvent, HOOK_EVENT_FORK},
{w.HasPushEvent, HOOK_EVENT_PUSH},
{w.HasIssuesEvent, HOOK_EVENT_ISSUES},
{w.HasPullRequestEvent, HOOK_EVENT_PULL_REQUEST},
{w.HasIssueCommentEvent, HOOK_EVENT_ISSUE_COMMENT},
{w.HasReleaseEvent, HOOK_EVENT_RELEASE},
{w.HasCreateEvent, HookEventTypeCreate},
{w.HasDeleteEvent, HookEventTypeDelete},
{w.HasForkEvent, HookEventTypeFork},
{w.HasPushEvent, HookEventTypePush},
{w.HasIssuesEvent, HookEventTypeIssues},
{w.HasPullRequestEvent, HookEventTypePullRequest},
{w.HasIssueCommentEvent, HookEventTypeIssueComment},
{w.HasReleaseEvent, HookEventTypeRelease},
}
for _, c := range eventCheckers {
if c.checker() {
@@ -409,14 +409,14 @@ func IsValidHookTaskType(name string) bool {
type HookEventType string
const (
HOOK_EVENT_CREATE HookEventType = "create"
HOOK_EVENT_DELETE HookEventType = "delete"
HOOK_EVENT_FORK HookEventType = "fork"
HOOK_EVENT_PUSH HookEventType = "push"
HOOK_EVENT_ISSUES HookEventType = "issues"
HOOK_EVENT_PULL_REQUEST HookEventType = "pull_request"
HOOK_EVENT_ISSUE_COMMENT HookEventType = "issue_comment"
HOOK_EVENT_RELEASE HookEventType = "release"
HookEventTypeCreate HookEventType = "create"
HookEventTypeDelete HookEventType = "delete"
HookEventTypeFork HookEventType = "fork"
HookEventTypePush HookEventType = "push"
HookEventTypeIssues HookEventType = "issues"
HookEventTypePullRequest HookEventType = "pull_request"
HookEventTypeIssueComment HookEventType = "issue_comment"
HookEventTypeRelease HookEventType = "release"
)
// HookRequest represents hook task request information.
@@ -511,7 +511,7 @@ func HookTasks(hookID int64, page int) ([]*HookTask, error) {
// createHookTask creates a new hook task,
// it handles conversion from Payload to PayloadContent.
func createHookTask(e Engine, t *HookTask) error {
data, err := t.Payloader.JSONPayload()
data, err := t.JSONPayload()
if err != nil {
return err
}
@@ -570,35 +570,35 @@ func prepareHookTasks(e Engine, repo *Repository, event HookEventType, p api.Pay
var payloader api.Payloader
for _, w := range webhooks {
switch event {
case HOOK_EVENT_CREATE:
case HookEventTypeCreate:
if !w.HasCreateEvent() {
continue
}
case HOOK_EVENT_DELETE:
case HookEventTypeDelete:
if !w.HasDeleteEvent() {
continue
}
case HOOK_EVENT_FORK:
case HookEventTypeFork:
if !w.HasForkEvent() {
continue
}
case HOOK_EVENT_PUSH:
case HookEventTypePush:
if !w.HasPushEvent() {
continue
}
case HOOK_EVENT_ISSUES:
case HookEventTypeIssues:
if !w.HasIssuesEvent() {
continue
}
case HOOK_EVENT_PULL_REQUEST:
case HookEventTypePullRequest:
if !w.HasPullRequestEvent() {
continue
}
case HOOK_EVENT_ISSUE_COMMENT:
case HookEventTypeIssueComment:
if !w.HasIssueCommentEvent() {
continue
}
case HOOK_EVENT_RELEASE:
case HookEventTypeRelease:
if !w.HasReleaseEvent() {
continue
}
@@ -751,9 +751,9 @@ func (t *HookTask) deliver() {
return
}
if t.IsSucceed {
w.LastStatus = HOOK_STATUS_SUCCEED
w.LastStatus = HookStatusSucceed
} else {
w.LastStatus = HOOK_STATUS_FAILED
w.LastStatus = HookStatusFailed
}
if err = UpdateWebhook(w); err != nil {
log.Error("UpdateWebhook: %v", err)

View File

@@ -61,21 +61,21 @@ func NewDingtalkActionCard(singleTitle, singleURL string) DingtalkActionCard {
// TODO: add content
func GetDingtalkPayload(p api.Payloader, event HookEventType) (payload *DingtalkPayload, err error) {
switch event {
case HOOK_EVENT_CREATE:
case HookEventTypeCreate:
payload = getDingtalkCreatePayload(p.(*api.CreatePayload))
case HOOK_EVENT_DELETE:
case HookEventTypeDelete:
payload = getDingtalkDeletePayload(p.(*api.DeletePayload))
case HOOK_EVENT_FORK:
case HookEventTypeFork:
payload = getDingtalkForkPayload(p.(*api.ForkPayload))
case HOOK_EVENT_PUSH:
case HookEventTypePush:
payload = getDingtalkPushPayload(p.(*api.PushPayload))
case HOOK_EVENT_ISSUES:
case HookEventTypeIssues:
payload = getDingtalkIssuesPayload(p.(*api.IssuesPayload))
case HOOK_EVENT_ISSUE_COMMENT:
case HookEventTypeIssueComment:
payload = getDingtalkIssueCommentPayload(p.(*api.IssueCommentPayload))
case HOOK_EVENT_PULL_REQUEST:
case HookEventTypePullRequest:
payload = getDingtalkPullRequestPayload(p.(*api.PullRequestPayload))
case HOOK_EVENT_RELEASE:
case HookEventTypeRelease:
payload = getDingtalkReleasePayload(p.(*api.ReleasePayload))
default:
return nil, errors.Errorf("unexpected event %q", event)
@@ -162,11 +162,12 @@ func getDingtalkIssuesPayload(p *api.IssuesPayload) *DingtalkPayload {
actionCard.Text += "# Issue Event " + strings.Title(string(p.Action))
actionCard.Text += "\n- Issue: **" + MarkdownLinkFormatter(issueURL, issueName) + "**"
if p.Action == api.HOOK_ISSUE_ASSIGNED {
switch p.Action {
case api.HOOK_ISSUE_ASSIGNED:
actionCard.Text += "\n- New Assignee: **" + p.Issue.Assignee.UserName + "**"
} else if p.Action == api.HOOK_ISSUE_MILESTONED {
case api.HOOK_ISSUE_MILESTONED:
actionCard.Text += "\n- New Milestone: **" + p.Issue.Milestone.Title + "**"
} else if p.Action == api.HOOK_ISSUE_LABEL_UPDATED {
case api.HOOK_ISSUE_LABEL_UPDATED:
if len(p.Issue.Labels) > 0 {
labels := make([]string, len(p.Issue.Labels))
for i, label := range p.Issue.Labels {
@@ -218,11 +219,12 @@ func getDingtalkPullRequestPayload(p *api.PullRequestPayload) *DingtalkPayload {
pullRequestURL := fmt.Sprintf("%s/pulls/%d", p.Repository.HTMLURL, p.Index)
content := "- PR: " + MarkdownLinkFormatter(pullRequestURL, fmt.Sprintf("#%d %s", p.Index, p.PullRequest.Title))
if p.Action == api.HOOK_ISSUE_ASSIGNED {
switch p.Action {
case api.HOOK_ISSUE_ASSIGNED:
content += "\n- New Assignee: **" + p.PullRequest.Assignee.UserName + "**"
} else if p.Action == api.HOOK_ISSUE_MILESTONED {
case api.HOOK_ISSUE_MILESTONED:
content += "\n- New Milestone: *" + p.PullRequest.Milestone.Title + "*"
} else if p.Action == api.HOOK_ISSUE_LABEL_UPDATED {
case api.HOOK_ISSUE_LABEL_UPDATED:
labels := make([]string, len(p.PullRequest.Labels))
for i, label := range p.PullRequest.Labels {
labels[i] = "**" + label.Name + "**"

View File

@@ -378,21 +378,21 @@ func GetDiscordPayload(p api.Payloader, event HookEventType, meta string) (paylo
}
switch event {
case HOOK_EVENT_CREATE:
case HookEventTypeCreate:
payload = getDiscordCreatePayload(p.(*api.CreatePayload))
case HOOK_EVENT_DELETE:
case HookEventTypeDelete:
payload = getDiscordDeletePayload(p.(*api.DeletePayload))
case HOOK_EVENT_FORK:
case HookEventTypeFork:
payload = getDiscordForkPayload(p.(*api.ForkPayload))
case HOOK_EVENT_PUSH:
case HookEventTypePush:
payload = getDiscordPushPayload(p.(*api.PushPayload), slack)
case HOOK_EVENT_ISSUES:
case HookEventTypeIssues:
payload = getDiscordIssuesPayload(p.(*api.IssuesPayload), slack)
case HOOK_EVENT_ISSUE_COMMENT:
case HookEventTypeIssueComment:
payload = getDiscordIssueCommentPayload(p.(*api.IssueCommentPayload), slack)
case HOOK_EVENT_PULL_REQUEST:
case HookEventTypePullRequest:
payload = getDiscordPullRequestPayload(p.(*api.PullRequestPayload), slack)
case HOOK_EVENT_RELEASE:
case HookEventTypeRelease:
payload = getDiscordReleasePayload(p.(*api.ReleasePayload))
default:
return nil, errors.Errorf("unexpected event %q", event)

View File

@@ -291,25 +291,25 @@ func getSlackReleasePayload(p *api.ReleasePayload) *SlackPayload {
func GetSlackPayload(p api.Payloader, event HookEventType, meta string) (payload *SlackPayload, err error) {
slack := &SlackMeta{}
if err := jsoniter.Unmarshal([]byte(meta), &slack); err != nil {
return nil, fmt.Errorf("Unmarshal: %v", err)
return nil, fmt.Errorf("unmarshal: %v", err)
}
switch event {
case HOOK_EVENT_CREATE:
case HookEventTypeCreate:
payload = getSlackCreatePayload(p.(*api.CreatePayload))
case HOOK_EVENT_DELETE:
case HookEventTypeDelete:
payload = getSlackDeletePayload(p.(*api.DeletePayload))
case HOOK_EVENT_FORK:
case HookEventTypeFork:
payload = getSlackForkPayload(p.(*api.ForkPayload))
case HOOK_EVENT_PUSH:
case HookEventTypePush:
payload = getSlackPushPayload(p.(*api.PushPayload), slack)
case HOOK_EVENT_ISSUES:
case HookEventTypeIssues:
payload = getSlackIssuesPayload(p.(*api.IssuesPayload), slack)
case HOOK_EVENT_ISSUE_COMMENT:
case HookEventTypeIssueComment:
payload = getSlackIssueCommentPayload(p.(*api.IssueCommentPayload), slack)
case HOOK_EVENT_PULL_REQUEST:
case HookEventTypePullRequest:
payload = getSlackPullRequestPayload(p.(*api.PullRequestPayload), slack)
case HOOK_EVENT_RELEASE:
case HookEventTypeRelease:
payload = getSlackReleasePayload(p.(*api.ReleasePayload))
default:
return nil, errors.Errorf("unexpected event %q", event)

View File

@@ -40,8 +40,8 @@ func ToWikiPageName(urlString string) string {
// WikiCloneLink returns clone URLs of repository wiki.
//
// Deprecated: Use repoutil.NewCloneLink instead.
func (repo *Repository) WikiCloneLink() (cl *repoutil.CloneLink) {
return repo.cloneLink(true)
func (r *Repository) WikiCloneLink() (cl *repoutil.CloneLink) {
return r.cloneLink(true)
}
// WikiPath returns wiki data path by given user and repository name.
@@ -49,37 +49,37 @@ func WikiPath(userName, repoName string) string {
return filepath.Join(repoutil.UserPath(userName), strings.ToLower(repoName)+".wiki.git")
}
func (repo *Repository) WikiPath() string {
return WikiPath(repo.MustOwner().Name, repo.Name)
func (r *Repository) WikiPath() string {
return WikiPath(r.MustOwner().Name, r.Name)
}
// HasWiki returns true if repository has wiki.
func (repo *Repository) HasWiki() bool {
return com.IsDir(repo.WikiPath())
func (r *Repository) HasWiki() bool {
return com.IsDir(r.WikiPath())
}
// InitWiki initializes a wiki for repository,
// it does nothing when repository already has wiki.
func (repo *Repository) InitWiki() error {
if repo.HasWiki() {
func (r *Repository) InitWiki() error {
if r.HasWiki() {
return nil
}
if err := git.Init(repo.WikiPath(), git.InitOptions{Bare: true}); err != nil {
if err := git.Init(r.WikiPath(), git.InitOptions{Bare: true}); err != nil {
return fmt.Errorf("init repository: %v", err)
} else if err = createDelegateHooks(repo.WikiPath()); err != nil {
} else if err = createDelegateHooks(r.WikiPath()); err != nil {
return fmt.Errorf("createDelegateHooks: %v", err)
}
return nil
}
func (repo *Repository) LocalWikiPath() string {
return filepath.Join(conf.Server.AppDataPath, "tmp", "local-wiki", com.ToStr(repo.ID))
func (r *Repository) LocalWikiPath() string {
return filepath.Join(conf.Server.AppDataPath, "tmp", "local-wiki", com.ToStr(r.ID))
}
// UpdateLocalWiki makes sure the local copy of repository wiki is up-to-date.
func (repo *Repository) UpdateLocalWiki() error {
return UpdateLocalCopyBranch(repo.WikiPath(), repo.LocalWikiPath(), "master", true)
func (r *Repository) UpdateLocalWiki() error {
return UpdateLocalCopyBranch(r.WikiPath(), r.LocalWikiPath(), "master", true)
}
func discardLocalWikiChanges(localPath string) error {
@@ -87,18 +87,18 @@ func discardLocalWikiChanges(localPath string) error {
}
// updateWikiPage adds new page to repository wiki.
func (repo *Repository) updateWikiPage(doer *User, oldTitle, title, content, message string, isNew bool) (err error) {
wikiWorkingPool.CheckIn(com.ToStr(repo.ID))
defer wikiWorkingPool.CheckOut(com.ToStr(repo.ID))
func (r *Repository) updateWikiPage(doer *User, oldTitle, title, content, message string, isNew bool) (err error) {
wikiWorkingPool.CheckIn(com.ToStr(r.ID))
defer wikiWorkingPool.CheckOut(com.ToStr(r.ID))
if err = repo.InitWiki(); err != nil {
if err = r.InitWiki(); err != nil {
return fmt.Errorf("InitWiki: %v", err)
}
localPath := repo.LocalWikiPath()
localPath := r.LocalWikiPath()
if err = discardLocalWikiChanges(localPath); err != nil {
return fmt.Errorf("discardLocalWikiChanges: %v", err)
} else if err = repo.UpdateLocalWiki(); err != nil {
} else if err = r.UpdateLocalWiki(); err != nil {
return fmt.Errorf("UpdateLocalWiki: %v", err)
}
@@ -150,22 +150,22 @@ func (repo *Repository) updateWikiPage(doer *User, oldTitle, title, content, mes
return nil
}
func (repo *Repository) AddWikiPage(doer *User, title, content, message string) error {
return repo.updateWikiPage(doer, "", title, content, message, true)
func (r *Repository) AddWikiPage(doer *User, title, content, message string) error {
return r.updateWikiPage(doer, "", title, content, message, true)
}
func (repo *Repository) EditWikiPage(doer *User, oldTitle, title, content, message string) error {
return repo.updateWikiPage(doer, oldTitle, title, content, message, false)
func (r *Repository) EditWikiPage(doer *User, oldTitle, title, content, message string) error {
return r.updateWikiPage(doer, oldTitle, title, content, message, false)
}
func (repo *Repository) DeleteWikiPage(doer *User, title string) (err error) {
wikiWorkingPool.CheckIn(com.ToStr(repo.ID))
defer wikiWorkingPool.CheckOut(com.ToStr(repo.ID))
func (r *Repository) DeleteWikiPage(doer *User, title string) (err error) {
wikiWorkingPool.CheckIn(com.ToStr(r.ID))
defer wikiWorkingPool.CheckOut(com.ToStr(r.ID))
localPath := repo.LocalWikiPath()
localPath := r.LocalWikiPath()
if err = discardLocalWikiChanges(localPath); err != nil {
return fmt.Errorf("discardLocalWikiChanges: %v", err)
} else if err = repo.UpdateLocalWiki(); err != nil {
} else if err = r.UpdateLocalWiki(); err != nil {
return fmt.Errorf("UpdateLocalWiki: %v", err)
}