fix lint errors

dependabot/go_modules/modernc.org/sqlite-1.37.0
Joe Chen 2025-04-01 22:25:05 -04:00
parent 5a60b89b92
commit bef68aed7a
17 changed files with 372 additions and 380 deletions

View File

@ -13,8 +13,9 @@ linters:
- printf - printf
staticcheck: staticcheck:
checks: checks:
- -SA1019 # There are valid use cases of strings.Title
- all - all
- "-SA1019" # This project is under active refactoring and not all code is up to date.
- "-QF1001" # I'm a math noob
nakedret: nakedret:
max-func-lines: 0 # Disallow any unnamed return statement max-func-lines: 0 # Disallow any unnamed return statement
exclusions: exclusions:

View File

@ -11,7 +11,7 @@ import (
"fmt" "fmt"
"strings" "strings"
ldap "github.com/go-ldap/ldap/v3" "github.com/go-ldap/ldap/v3"
log "unknwon.dev/clog/v2" log "unknwon.dev/clog/v2"
) )
@ -166,7 +166,7 @@ func dial(ls *Config) (*ldap.Conn, error) {
conn, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", ls.Host, ls.Port)) conn, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", ls.Host, ls.Port))
if err != nil { if err != nil {
return nil, fmt.Errorf("Dial: %v", err) return nil, fmt.Errorf("dial: %v", err)
} }
if ls.SecurityProtocol == SecurityProtocolStartTLS { if ls.SecurityProtocol == SecurityProtocolStartTLS {

View File

@ -96,15 +96,6 @@ func (c *Context) UserID() int64 {
return c.User.ID return c.User.ID
} }
// HasError returns true if error occurs in form validation.
func (c *Context) HasApiError() bool {
hasErr, ok := c.Data["HasError"]
if !ok {
return false
}
return hasErr.(bool)
}
func (c *Context) GetErrMsg() string { func (c *Context) GetErrMsg() string {
return c.Data["ErrorMsg"].(string) return c.Data["ErrorMsg"].(string)
} }

View File

@ -49,8 +49,8 @@ func AttachmentLocalPath(uuid string) string {
} }
// LocalPath returns where attachment is stored in local file system. // LocalPath returns where attachment is stored in local file system.
func (attach *Attachment) LocalPath() string { func (a *Attachment) LocalPath() string {
return AttachmentLocalPath(attach.UUID) return AttachmentLocalPath(a.UUID)
} }
// NewAttachment creates a new attachment object. // NewAttachment creates a new attachment object.
@ -183,8 +183,8 @@ func DeleteAttachments(attachments []*Attachment, remove bool) (int, error) {
} }
// DeleteAttachmentsByIssue deletes all attachments associated with the given issue. // DeleteAttachmentsByIssue deletes all attachments associated with the given issue.
func DeleteAttachmentsByIssue(issueId int64, remove bool) (int, error) { func DeleteAttachmentsByIssue(issueID int64, remove bool) (int, error) {
attachments, err := GetAttachmentsByIssueID(issueId) attachments, err := GetAttachmentsByIssueID(issueID)
if err != nil { if err != nil {
return 0, err return 0, err
} }
@ -193,8 +193,8 @@ func DeleteAttachmentsByIssue(issueId int64, remove bool) (int, error) {
} }
// DeleteAttachmentsByComment deletes all attachments associated with the given comment. // DeleteAttachmentsByComment deletes all attachments associated with the given comment.
func DeleteAttachmentsByComment(commentId int64, remove bool) (int, error) { func DeleteAttachmentsByComment(commentID int64, remove bool) (int, error) {
attachments, err := GetAttachmentsByCommentID(commentId) attachments, err := GetAttachmentsByCommentID(commentID)
if err != nil { if err != nil {
return 0, err return 0, err
} }

View File

@ -166,21 +166,21 @@ func (c *Comment) EventTag() string {
// mailParticipants sends new comment emails to repository watchers // mailParticipants sends new comment emails to repository watchers
// and mentioned people. // and mentioned people.
func (cmt *Comment) mailParticipants(e Engine, opType ActionType, issue *Issue) (err error) { func (c *Comment) mailParticipants(e Engine, opType ActionType, issue *Issue) (err error) {
mentions := markup.FindAllMentions(cmt.Content) mentions := markup.FindAllMentions(c.Content)
if err = updateIssueMentions(e, cmt.IssueID, mentions); err != nil { if err = updateIssueMentions(e, c.IssueID, mentions); err != nil {
return fmt.Errorf("UpdateIssueMentions [%d]: %v", cmt.IssueID, err) return fmt.Errorf("UpdateIssueMentions [%d]: %v", c.IssueID, err)
} }
switch opType { switch opType {
case ActionCommentIssue: case ActionCommentIssue:
issue.Content = cmt.Content issue.Content = c.Content
case ActionCloseIssue: case ActionCloseIssue:
issue.Content = fmt.Sprintf("Closed #%d", issue.Index) issue.Content = fmt.Sprintf("Closed #%d", issue.Index)
case ActionReopenIssue: case ActionReopenIssue:
issue.Content = fmt.Sprintf("Reopened #%d", issue.Index) issue.Content = fmt.Sprintf("Reopened #%d", issue.Index)
} }
if err = mailIssueCommentToParticipants(issue, cmt.Poster, mentions); err != nil { if err = mailIssueCommentToParticipants(issue, c.Poster, mentions); err != nil {
log.Error("mailIssueCommentToParticipants: %v", err) log.Error("mailIssueCommentToParticipants: %v", err)
} }

View File

@ -6,7 +6,7 @@ package errors
import "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. // New is a wrapper of real errors.New function.
func New(text string) error { func New(text string) error {

View File

@ -1108,9 +1108,9 @@ func NewIssueUsers(repo *Repository, issue *Issue) (err error) {
} }
// PairsContains returns true when pairs list contains given issue. // 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 { for i := range ius {
if ius[i].IssueID == issueId && if ius[i].IssueID == issueID &&
ius[i].UserID == uid { ius[i].UserID == uid {
return i return i
} }

View File

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

View File

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

View File

@ -261,14 +261,14 @@ func IsOrganizationOwner(orgID, userID int64) bool {
} }
// IsOrganizationMember returns true if given user is member of organization. // IsOrganizationMember returns true if given user is member of organization.
func IsOrganizationMember(orgId, uid int64) bool { func IsOrganizationMember(orgID, uid int64) bool {
has, _ := x.Where("uid=?", uid).And("org_id=?", orgId).Get(new(OrgUser)) has, _ := x.Where("uid=?", uid).And("org_id=?", orgID).Get(new(OrgUser))
return has return has
} }
// IsPublicMembership returns true if given user public his/her membership. // IsPublicMembership returns true if given user public his/her membership.
func IsPublicMembership(orgId, uid int64) bool { func IsPublicMembership(orgID, uid int64) bool {
has, _ := x.Where("uid=?", uid).And("org_id=?", orgId).And("is_public=?", true).Get(new(OrgUser)) has, _ := x.Where("uid=?", uid).And("org_id=?", orgID).And("is_public=?", true).Get(new(OrgUser))
return has return has
} }

View File

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

View File

@ -64,18 +64,18 @@ func (ErrBranchNotExist) NotFound() bool {
return true return true
} }
func (repo *Repository) GetBranch(name string) (*Branch, error) { func (r *Repository) GetBranch(name string) (*Branch, error) {
if !git.RepoHasBranch(repo.RepoPath(), name) { if !git.RepoHasBranch(r.RepoPath(), name) {
return nil, ErrBranchNotExist{args: map[string]any{"name": name}} return nil, ErrBranchNotExist{args: map[string]any{"name": name}}
} }
return &Branch{ return &Branch{
RepoPath: repo.RepoPath(), RepoPath: r.RepoPath(),
Name: name, Name: name,
}, nil }, nil
} }
func (repo *Repository) GetBranches() ([]*Branch, error) { func (r *Repository) GetBranches() ([]*Branch, error) {
return GetBranchesByPath(repo.RepoPath()) return GetBranchesByPath(r.RepoPath())
} }
func (br *Branch) GetCommit() (*git.Commit, error) { func (br *Branch) GetCommit() (*git.Commit, error) {

View File

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

View File

@ -92,13 +92,13 @@ func discardLocalRepoBranchChanges(localPath, branch string) error {
return nil return nil
} }
func (repo *Repository) DiscardLocalRepoBranchChanges(branch string) error { func (r *Repository) DiscardLocalRepoBranchChanges(branch string) error {
return discardLocalRepoBranchChanges(repo.LocalCopyPath(), branch) return discardLocalRepoBranchChanges(r.LocalCopyPath(), branch)
} }
// CheckoutNewBranch checks out to a new branch from the a branch name. // CheckoutNewBranch checks out to a new branch from the a branch name.
func (repo *Repository) CheckoutNewBranch(oldBranch, newBranch string) error { func (r *Repository) CheckoutNewBranch(oldBranch, newBranch string) error {
if err := git.Checkout(repo.LocalCopyPath(), newBranch, git.CheckoutOptions{ if err := git.Checkout(r.LocalCopyPath(), newBranch, git.CheckoutOptions{
BaseBranch: oldBranch, BaseBranch: oldBranch,
Timeout: time.Duration(conf.Git.Timeout.Pull) * time.Second, Timeout: time.Duration(conf.Git.Timeout.Pull) * time.Second,
}); err != nil { }); err != nil {
@ -118,23 +118,23 @@ type UpdateRepoFileOptions struct {
} }
// UpdateRepoFile adds or updates a file in repository. // 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. // 🚨 SECURITY: Prevent uploading files into the ".git" directory.
if isRepositoryGitPath(opts.NewTreeName) { if isRepositoryGitPath(opts.NewTreeName) {
return errors.Errorf("bad tree path %q", opts.NewTreeName) return errors.Errorf("bad tree path %q", opts.NewTreeName)
} }
repoWorkingPool.CheckIn(com.ToStr(repo.ID)) repoWorkingPool.CheckIn(com.ToStr(r.ID))
defer repoWorkingPool.CheckOut(com.ToStr(repo.ID)) defer repoWorkingPool.CheckOut(com.ToStr(r.ID))
if err = repo.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil { if err = r.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
return fmt.Errorf("discard local repo branch[%s] changes: %v", opts.OldBranch, err) return fmt.Errorf("discard local r branch[%s] changes: %v", opts.OldBranch, err)
} else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil { } else if err = r.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err) return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err)
} }
repoPath := repo.RepoPath() repoPath := r.RepoPath()
localPath := repo.LocalCopyPath() localPath := r.LocalCopyPath()
if opts.OldBranch != opts.NewBranch { if opts.OldBranch != opts.NewBranch {
// Directly return error if new branch already exists in the server // 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) 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{ CommandOptions: git.CommandOptions{
Envs: ComposeHookEnvs(ComposeHookEnvsOptions{ Envs: ComposeHookEnvs(ComposeHookEnvsOptions{
AuthUser: doer, AuthUser: doer,
OwnerName: repo.MustOwner().Name, OwnerName: r.MustOwner().Name,
OwnerSalt: repo.MustOwner().Salt, OwnerSalt: r.MustOwner().Salt,
RepoID: repo.ID, RepoID: r.ID,
RepoName: repo.Name, RepoName: r.Name,
RepoPath: repo.RepoPath(), 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. // 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. // 🚨 SECURITY: Prevent uploading files into the ".git" directory.
if isRepositoryGitPath(treePath) { if isRepositoryGitPath(treePath) {
return nil, errors.Errorf("bad tree path %q", treePath) return nil, errors.Errorf("bad tree path %q", treePath)
} }
repoWorkingPool.CheckIn(com.ToStr(repo.ID)) repoWorkingPool.CheckIn(com.ToStr(r.ID))
defer repoWorkingPool.CheckOut(com.ToStr(repo.ID)) defer repoWorkingPool.CheckOut(com.ToStr(r.ID))
if err = repo.DiscardLocalRepoBranchChanges(branch); err != nil { if err = r.DiscardLocalRepoBranchChanges(branch); err != nil {
return nil, fmt.Errorf("discard local repo branch[%s] changes: %v", branch, err) return nil, fmt.Errorf("discard local r branch[%s] changes: %v", branch, err)
} else if err = repo.UpdateLocalCopyBranch(branch); err != nil { } else if err = r.UpdateLocalCopyBranch(branch); err != nil {
return nil, fmt.Errorf("update local copy branch[%s]: %v", branch, err) return nil, fmt.Errorf("update local copy branch[%s]: %v", branch, err)
} }
localPath := repo.LocalCopyPath() localPath := r.LocalCopyPath()
filePath := path.Join(localPath, treePath) filePath := path.Join(localPath, treePath)
if err = os.MkdirAll(filepath.Dir(filePath), os.ModePerm); err != nil { if err = os.MkdirAll(filepath.Dir(filePath), os.ModePerm); err != nil {
return nil, err return nil, err
@ -257,7 +257,7 @@ func (repo *Repository) GetDiffPreview(branch, treePath, content string) (diff *
return nil, fmt.Errorf("start: %v", err) 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) defer process.Remove(pid)
diff, err = gitutil.ParseDiff(stdout, conf.Git.MaxDiffFiles, conf.Git.MaxDiffLines, conf.Git.MaxDiffLineChars) diff, err = gitutil.ParseDiff(stdout, conf.Git.MaxDiffFiles, conf.Git.MaxDiffLines, conf.Git.MaxDiffLineChars)
@ -288,28 +288,28 @@ type DeleteRepoFileOptions struct {
Message string 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. // 🚨 SECURITY: Prevent uploading files into the ".git" directory.
if isRepositoryGitPath(opts.TreePath) { if isRepositoryGitPath(opts.TreePath) {
return errors.Errorf("bad tree path %q", opts.TreePath) return errors.Errorf("bad tree path %q", opts.TreePath)
} }
repoWorkingPool.CheckIn(com.ToStr(repo.ID)) repoWorkingPool.CheckIn(com.ToStr(r.ID))
defer repoWorkingPool.CheckOut(com.ToStr(repo.ID)) defer repoWorkingPool.CheckOut(com.ToStr(r.ID))
if err = repo.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil { if err = r.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
return fmt.Errorf("discard local repo branch[%s] changes: %v", opts.OldBranch, err) return fmt.Errorf("discard local r branch[%s] changes: %v", opts.OldBranch, err)
} else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil { } else if err = r.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err) return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err)
} }
if opts.OldBranch != opts.NewBranch { 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) 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 { if err = os.Remove(path.Join(localPath, opts.TreePath)); err != nil {
return fmt.Errorf("remove file %q: %v", opts.TreePath, err) 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{ CommandOptions: git.CommandOptions{
Envs: ComposeHookEnvs(ComposeHookEnvsOptions{ Envs: ComposeHookEnvs(ComposeHookEnvsOptions{
AuthUser: doer, AuthUser: doer,
OwnerName: repo.MustOwner().Name, OwnerName: r.MustOwner().Name,
OwnerSalt: repo.MustOwner().Salt, OwnerSalt: r.MustOwner().Salt,
RepoID: repo.ID, RepoID: r.ID,
RepoName: repo.Name, RepoName: r.Name,
RepoPath: repo.RepoPath(), RepoPath: r.RepoPath(),
}), }),
}, },
}, },
@ -509,7 +509,7 @@ func isRepositoryGitPath(path string) bool {
strings.Contains(path, `.git.\`) 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 { if len(opts.Files) == 0 {
return nil 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) return fmt.Errorf("get uploads by UUIDs[%v]: %v", opts.Files, err)
} }
repoWorkingPool.CheckIn(com.ToStr(repo.ID)) repoWorkingPool.CheckIn(com.ToStr(r.ID))
defer repoWorkingPool.CheckOut(com.ToStr(repo.ID)) defer repoWorkingPool.CheckOut(com.ToStr(r.ID))
if err = repo.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil { if err = r.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
return fmt.Errorf("discard local repo branch[%s] changes: %v", opts.OldBranch, err) return fmt.Errorf("discard local r branch[%s] changes: %v", opts.OldBranch, err)
} else if err = repo.UpdateLocalCopyBranch(opts.OldBranch); err != nil { } else if err = r.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err) return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err)
} }
if opts.OldBranch != opts.NewBranch { 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) 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) dirPath := path.Join(localPath, opts.TreePath)
if err = os.MkdirAll(dirPath, os.ModePerm); err != nil { if err = os.MkdirAll(dirPath, os.ModePerm); err != nil {
return err return err
@ -588,11 +588,11 @@ func (repo *Repository) UploadRepoFiles(doer *User, opts UploadRepoFileOptions)
CommandOptions: git.CommandOptions{ CommandOptions: git.CommandOptions{
Envs: ComposeHookEnvs(ComposeHookEnvsOptions{ Envs: ComposeHookEnvs(ComposeHookEnvsOptions{
AuthUser: doer, AuthUser: doer,
OwnerName: repo.MustOwner().Name, OwnerName: r.MustOwner().Name,
OwnerSalt: repo.MustOwner().Salt, OwnerSalt: r.MustOwner().Salt,
RepoID: repo.ID, RepoID: r.ID,
RepoName: repo.Name, RepoName: r.Name,
RepoPath: repo.RepoPath(), RepoPath: r.RepoPath(),
}), }),
}, },
}, },

View File

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

View File

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

View File

@ -282,7 +282,7 @@ func editFilePost(c *context.Context, f form.EditRepoFile, isNewFile bool) {
}); err != nil { }); err != nil {
log.Error("Failed to update repo file: %v", err) log.Error("Failed to update repo file: %v", err)
c.FormErr("TreePath") c.FormErr("TreePath")
c.RenderWithErr(c.Tr("repo.editor.fail_to_update_file", f.TreePath, errors.InternalServerError), tmplEditorEdit, &f) c.RenderWithErr(c.Tr("repo.editor.fail_to_update_file", f.TreePath, errors.ErrInternalServerError), tmplEditorEdit, &f)
return return
} }
@ -390,7 +390,7 @@ func DeleteFilePost(c *context.Context, f form.DeleteRepoFile) {
Message: message, Message: message,
}); err != nil { }); err != nil {
log.Error("Failed to delete repo file: %v", err) log.Error("Failed to delete repo file: %v", err)
c.RenderWithErr(c.Tr("repo.editor.fail_to_delete_file", c.Repo.TreePath, errors.InternalServerError), tmplEditorDelete, &f) c.RenderWithErr(c.Tr("repo.editor.fail_to_delete_file", c.Repo.TreePath, errors.ErrInternalServerError), tmplEditorDelete, &f)
return return
} }
@ -512,7 +512,7 @@ func UploadFilePost(c *context.Context, f form.UploadRepoFile) {
}); err != nil { }); err != nil {
log.Error("Failed to upload files: %v", err) log.Error("Failed to upload files: %v", err)
c.FormErr("TreePath") c.FormErr("TreePath")
c.RenderWithErr(c.Tr("repo.editor.unable_to_upload_files", f.TreePath, errors.InternalServerError), tmplEditorUpload, &f) c.RenderWithErr(c.Tr("repo.editor.unable_to_upload_files", f.TreePath, errors.ErrInternalServerError), tmplEditorUpload, &f)
return return
} }