1
1
mirror of https://github.com/go-gitea/gitea synced 2024-06-02 09:25:48 +00:00

Lint models/repo.go

This commit is contained in:
Bwko 2016-11-28 18:27:55 +01:00
parent a5aae1c145
commit bad1bc6518

View File

@ -41,20 +41,40 @@ const (
var repoWorkingPool = sync.NewExclusivePool() var repoWorkingPool = sync.NewExclusivePool()
var ( var (
ErrRepoFileNotExist = errors.New("Repository file does not exist") // ErrRepoFileNotExist repository file does not exist error
ErrRepoFileNotExist = errors.New("Repository file does not exist")
// ErrRepoFileNotLoaded repository file not loaded error
ErrRepoFileNotLoaded = errors.New("Repository file not loaded") ErrRepoFileNotLoaded = errors.New("Repository file not loaded")
ErrMirrorNotExist = errors.New("Mirror does not exist")
ErrInvalidReference = errors.New("Invalid reference specified") // ErrMirrorNotExist mirror does not exist error
ErrNameEmpty = errors.New("Name is empty") ErrMirrorNotExist = errors.New("Mirror does not exist")
// ErrInvalidReference invalid reference specified error
ErrInvalidReference = errors.New("Invalid reference specified")
// ErrNameEmpty name is empty error
ErrNameEmpty = errors.New("Name is empty")
) )
var ( var (
Gitignores, Licenses, Readmes, LabelTemplates []string // Gitignores contains the gitiginore files
Gitignores []string
// Maximum items per page in forks, watchers and stars of a repo // Licenses contains the license files
Licenses []string
// Readmes contains the readme files
Readmes []string
// LabelTemplates contains the label template files
LabelTemplates []string
// ItemsPerPage maximum items per page in forks, watchers and stars of a repo
ItemsPerPage = 40 ItemsPerPage = 40
) )
// LoadRepoConfig loads the repository config
func LoadRepoConfig() { func LoadRepoConfig() {
// Load .gitignore and license files and readme templates. // Load .gitignore and license files and readme templates.
types := []string{"gitignore", "license", "readme", "label"} types := []string{"gitignore", "license", "readme", "label"}
@ -104,6 +124,7 @@ func LoadRepoConfig() {
Licenses = sortedLicenses Licenses = sortedLicenses
} }
// NewRepoContext creates a new repository context
func NewRepoContext() { func NewRepoContext() {
zip.Verbose = false zip.Verbose = false
@ -200,15 +221,18 @@ type Repository struct {
UpdatedUnix int64 UpdatedUnix int64
} }
// BeforeInsert is invoked from XORM before inserting an object of this type.
func (repo *Repository) BeforeInsert() { func (repo *Repository) BeforeInsert() {
repo.CreatedUnix = time.Now().Unix() repo.CreatedUnix = time.Now().Unix()
repo.UpdatedUnix = repo.CreatedUnix repo.UpdatedUnix = repo.CreatedUnix
} }
// BeforeUpdate is invoked from XORM before updating this object.
func (repo *Repository) BeforeUpdate() { func (repo *Repository) BeforeUpdate() {
repo.UpdatedUnix = time.Now().Unix() repo.UpdatedUnix = time.Now().Unix()
} }
// AfterSet is invoked from XORM after setting the value of a field of this object.
func (repo *Repository) AfterSet(colName string, _ xorm.Cell) { func (repo *Repository) AfterSet(colName string, _ xorm.Cell) {
switch colName { switch colName {
case "default_branch": case "default_branch":
@ -241,14 +265,17 @@ func (repo *Repository) MustOwner() *User {
return repo.mustOwner(x) return repo.mustOwner(x)
} }
// FullName returns the repository full name
func (repo *Repository) FullName() string { func (repo *Repository) FullName() string {
return repo.MustOwner().Name + "/" + repo.Name return repo.MustOwner().Name + "/" + repo.Name
} }
// HTMLURL returns the repository HTML URL
func (repo *Repository) HTMLURL() string { func (repo *Repository) HTMLURL() string {
return setting.AppURL + repo.FullName() return setting.AppURL + repo.FullName()
} }
// APIFormat converts a Repository to api.Repository
// Arguments that are allowed to be nil: permission // Arguments that are allowed to be nil: permission
func (repo *Repository) APIFormat(permission *api.Permission) *api.Repository { func (repo *Repository) APIFormat(permission *api.Permission) *api.Repository {
cloneLink := repo.CloneLink() cloneLink := repo.CloneLink()
@ -284,6 +311,7 @@ func (repo *Repository) getOwner(e Engine) (err error) {
return err return err
} }
// GetOwner returns the repository owner
func (repo *Repository) GetOwner() error { func (repo *Repository) GetOwner() error {
return repo.getOwner(x) return repo.getOwner(x)
} }
@ -381,11 +409,13 @@ func (repo *Repository) IssueStats(uid int64, filterMode int, isPull bool) (int6
return GetRepoIssueStats(repo.ID, uid, filterMode, isPull) return GetRepoIssueStats(repo.ID, uid, filterMode, isPull)
} }
// GetMirror sets the repository mirror, returns an error upon failure
func (repo *Repository) GetMirror() (err error) { func (repo *Repository) GetMirror() (err error) {
repo.Mirror, err = GetMirrorByRepoID(repo.ID) repo.Mirror, err = GetMirrorByRepoID(repo.ID)
return err return err
} }
// GetBaseRepo returns the base repository
func (repo *Repository) GetBaseRepo() (err error) { func (repo *Repository) GetBaseRepo() (err error) {
if !repo.IsFork { if !repo.IsFork {
return nil return nil
@ -399,31 +429,38 @@ func (repo *Repository) repoPath(e Engine) string {
return RepoPath(repo.mustOwner(e).Name, repo.Name) return RepoPath(repo.mustOwner(e).Name, repo.Name)
} }
// RepoPath returns the repository path
func (repo *Repository) RepoPath() string { func (repo *Repository) RepoPath() string {
return repo.repoPath(x) return repo.repoPath(x)
} }
// GitConfigPath returns the repository git config path
func (repo *Repository) GitConfigPath() string { func (repo *Repository) GitConfigPath() string {
return filepath.Join(repo.RepoPath(), "config") return filepath.Join(repo.RepoPath(), "config")
} }
// RelLink returns the repository relative link
func (repo *Repository) RelLink() string { func (repo *Repository) RelLink() string {
return "/" + repo.FullName() return "/" + repo.FullName()
} }
// Link returns the repository link
func (repo *Repository) Link() string { func (repo *Repository) Link() string {
return setting.AppSubURL + "/" + repo.FullName() return setting.AppSubURL + "/" + repo.FullName()
} }
// ComposeCompareURL returns the repository comparison URL
func (repo *Repository) ComposeCompareURL(oldCommitID, newCommitID string) string { func (repo *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", repo.MustOwner().Name, repo.Name, oldCommitID, newCommitID)
} }
// HasAccess returns true when user has access to this repository
func (repo *Repository) HasAccess(u *User) bool { func (repo *Repository) HasAccess(u *User) bool {
has, _ := HasAccess(u, repo, AccessModeRead) has, _ := HasAccess(u, repo, AccessModeRead)
return has return has
} }
// IsOwnedBy returns true when user owns this repository
func (repo *Repository) IsOwnedBy(userID int64) bool { func (repo *Repository) IsOwnedBy(userID int64) bool {
return repo.OwnerID == userID return repo.OwnerID == userID
} }
@ -438,7 +475,7 @@ func (repo *Repository) CanEnablePulls() bool {
return !repo.IsMirror return !repo.IsMirror
} }
// AllowPulls returns true if repository meets the requirements of accepting pulls and has them enabled. // AllowsPulls returns true if repository meets the requirements of accepting pulls and has them enabled.
func (repo *Repository) AllowsPulls() bool { func (repo *Repository) AllowsPulls() bool {
return repo.CanEnablePulls() && repo.EnablePulls return repo.CanEnablePulls() && repo.EnablePulls
} }
@ -448,6 +485,7 @@ func (repo *Repository) CanEnableEditor() bool {
return !repo.IsMirror return !repo.IsMirror
} }
// NextIssueIndex returns the next issue index
// 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 (repo *Repository) NextIssueIndex() int64 {
@ -455,22 +493,23 @@ func (repo *Repository) NextIssueIndex() int64 {
} }
var ( var (
DescPattern = regexp.MustCompile(`https?://\S+`) descPattern = regexp.MustCompile(`https?://\S+`)
) )
// DescriptionHtml does special handles to description and return HTML string. // DescriptionHTML does special handles to description and return HTML string.
func (repo *Repository) DescriptionHtml() template.HTML { func (repo *Repository) DescriptionHTML() template.HTML {
sanitize := func(s string) string { sanitize := func(s string) string {
return fmt.Sprintf(`<a href="%[1]s" target="_blank">%[1]s</a>`, s) return fmt.Sprintf(`<a href="%[1]s" target="_blank">%[1]s</a>`, s)
} }
return template.HTML(DescPattern.ReplaceAllStringFunc(markdown.Sanitizer.Sanitize(repo.Description), sanitize)) return template.HTML(descPattern.ReplaceAllStringFunc(markdown.Sanitizer.Sanitize(repo.Description), sanitize))
} }
// LocalCopyPath returns the local repository copy path
func (repo *Repository) LocalCopyPath() string { func (repo *Repository) LocalCopyPath() string {
return path.Join(setting.AppDataPath, "tmp/local-rpeo", com.ToStr(repo.ID)) return path.Join(setting.AppDataPath, "tmp/local-rpeo", com.ToStr(repo.ID))
} }
// UpdateLocalCopy pulls latest changes of given branch from repoPath to localPath. // UpdateLocalCopyBranch pulls latest changes of given branch from repoPath to localPath.
// It creates a new clone if local copy does not exist. // It creates a new clone if local copy does not exist.
// This function checks out target branch by default, it is safe to assume subsequent // This function checks out target branch by default, it is safe to assume subsequent
// operations are operating against target branch when caller has confidence for no race condition. // operations are operating against target branch when caller has confidence for no race condition.
@ -575,6 +614,7 @@ func (repo *Repository) CloneLink() (cl *CloneLink) {
return repo.cloneLink(false) return repo.cloneLink(false)
} }
// MigrateRepoOptions contains the repository migrate options
type MigrateRepoOptions struct { type MigrateRepoOptions struct {
Name string Name string
Description string Description string
@ -711,7 +751,7 @@ func createUpdateHook(repoPath string) error {
fmt.Sprintf(tplUpdateHook, setting.ScriptType, "\""+setting.AppPath+"\"", setting.CustomConf)) fmt.Sprintf(tplUpdateHook, setting.ScriptType, "\""+setting.AppPath+"\"", setting.CustomConf))
} }
// Finish migrating repository and/or wiki with things that don't need to be done for mirrors. // CleanUpMigrateInfo finishes migrating repository and/or wiki with things that don't need to be done for mirrors.
func CleanUpMigrateInfo(repo *Repository) (*Repository, error) { func CleanUpMigrateInfo(repo *Repository) (*Repository, error) {
repoPath := repo.RepoPath() repoPath := repo.RepoPath()
if err := createUpdateHook(repoPath); err != nil { if err := createUpdateHook(repoPath); err != nil {
@ -759,6 +799,7 @@ func initRepoCommit(tmpPath string, sig *git.Signature) (err error) {
return nil return nil
} }
// CreateRepoOptions contains the create repository options
type CreateRepoOptions struct { type CreateRepoOptions struct {
Name string Name string
Description string Description string
@ -897,6 +938,7 @@ var (
reservedRepoPatterns = []string{"*.git", "*.wiki"} reservedRepoPatterns = []string{"*.git", "*.wiki"}
) )
// IsUsableRepoName returns true when repository is usable
func IsUsableRepoName(name string) error { func IsUsableRepoName(name string) error {
return isUsableName(reservedRepoNames, reservedRepoPatterns, name) return isUsableName(reservedRepoNames, reservedRepoPatterns, name)
} }
@ -1030,6 +1072,7 @@ func CountUserRepositories(userID int64, private bool) int64 {
return countRepositories(userID, private) return countRepositories(userID, private)
} }
// Repositories returns all repositories
func Repositories(page, pageSize int) (_ []*Repository, err error) { func Repositories(page, pageSize int) (_ []*Repository, err error) {
repos := make([]*Repository, 0, pageSize) repos := make([]*Repository, 0, pageSize)
return repos, x.Limit(pageSize, (page-1)*pageSize).Asc("id").Find(&repos) return repos, x.Limit(pageSize, (page-1)*pageSize).Asc("id").Find(&repos)
@ -1275,6 +1318,7 @@ func updateRepository(e Engine, repo *Repository, visibilityChanged bool) (err e
return nil return nil
} }
// UpdateRepository updates a repository
func UpdateRepository(repo *Repository, visibilityChanged bool) (err error) { func UpdateRepository(repo *Repository, visibilityChanged bool) (err error) {
sess := x.NewSession() sess := x.NewSession()
defer sessionRelease(sess) defer sessionRelease(sess)
@ -1474,7 +1518,7 @@ func GetUserRepositories(userID int64, private bool, page, pageSize int) ([]*Rep
return repos, sess.Find(&repos) return repos, sess.Find(&repos)
} }
// GetUserRepositories returns a list of mirror repositories of given user. // GetUserMirrorRepositories returns a list of mirror repositories of given user.
func GetUserMirrorRepositories(userID int64) ([]*Repository, error) { func GetUserMirrorRepositories(userID int64) ([]*Repository, error) {
repos := make([]*Repository, 0, 10) repos := make([]*Repository, 0, 10)
return repos, x. return repos, x.
@ -1502,6 +1546,7 @@ func GetRepositoryCount(u *User) (int64, error) {
return getRepositoryCount(x, u) return getRepositoryCount(x, u)
} }
// SearchRepoOptions holds the search options
type SearchRepoOptions struct { type SearchRepoOptions struct {
Keyword string Keyword string
OwnerID int64 OwnerID int64
@ -1670,6 +1715,7 @@ func GitFsck() {
} }
} }
// GitGcRepos calls 'git gc' to remove unnecessary files and optimize the local repository
func GitGcRepos() error { func GitGcRepos() error {
args := append([]string{"gc"}, setting.Git.GCArgs...) args := append([]string{"gc"}, setting.Git.GCArgs...)
return x. return x.
@ -1712,6 +1758,7 @@ func repoStatsCheck(checker *repoChecker) {
} }
} }
// CheckRepoStats checks the repository stats
func CheckRepoStats() { func CheckRepoStats() {
if taskStatusTable.IsRunning(checkRepos) { if taskStatusTable.IsRunning(checkRepos) {
return return
@ -1806,6 +1853,7 @@ func CheckRepoStats() {
// ***** END: Repository.NumForks ***** // ***** END: Repository.NumForks *****
} }
// RepositoryList contains a list of repositories
type RepositoryList []*Repository type RepositoryList []*Repository
func (repos RepositoryList) loadAttributes(e Engine) error { func (repos RepositoryList) loadAttributes(e Engine) error {
@ -1838,10 +1886,12 @@ func (repos RepositoryList) loadAttributes(e Engine) error {
return nil return nil
} }
// LoadAttributes loads the attributes for the given RepositoryList
func (repos RepositoryList) LoadAttributes() error { func (repos RepositoryList) LoadAttributes() error {
return repos.loadAttributes(x) return repos.loadAttributes(x)
} }
// MirrorRepositoryList contains the mirror repositories
type MirrorRepositoryList []*Repository type MirrorRepositoryList []*Repository
func (repos MirrorRepositoryList) loadAttributes(e Engine) error { func (repos MirrorRepositoryList) loadAttributes(e Engine) error {
@ -1876,6 +1926,7 @@ func (repos MirrorRepositoryList) loadAttributes(e Engine) error {
return nil return nil
} }
// LoadAttributes loads the attributes for the given MirrorRepositoryList
func (repos MirrorRepositoryList) LoadAttributes() error { func (repos MirrorRepositoryList) LoadAttributes() error {
return repos.loadAttributes(x) return repos.loadAttributes(x)
} }
@ -1925,7 +1976,7 @@ func watchRepo(e Engine, userID, repoID int64, watch bool) (err error) {
return err return err
} }
// Watch or unwatch repository. // WatchRepo watch or unwatch repository.
func WatchRepo(userID, repoID int64, watch bool) (err error) { func WatchRepo(userID, repoID int64, watch bool) (err error) {
return watchRepo(x, userID, repoID, watch) return watchRepo(x, userID, repoID, watch)
} }
@ -1940,7 +1991,7 @@ func GetWatchers(repoID int64) ([]*Watch, error) {
return getWatchers(x, repoID) return getWatchers(x, repoID)
} }
// Repository.GetWatchers returns range of users watching given repository. // GetWatchers returns range of users watching given repository.
func (repo *Repository) GetWatchers(page int) ([]*User, error) { func (repo *Repository) GetWatchers(page int) ([]*User, error) {
users := make([]*User, 0, ItemsPerPage) users := make([]*User, 0, ItemsPerPage)
sess := x. sess := x.
@ -1993,13 +2044,14 @@ func NotifyWatchers(act *Action) error {
// /_______ /|__| (____ /__| // /_______ /|__| (____ /__|
// \/ \/ // \/ \/
// Star contains the star information
type Star struct { type Star struct {
ID int64 `xorm:"pk autoincr"` ID int64 `xorm:"pk autoincr"`
UID int64 `xorm:"UNIQUE(s)"` UID int64 `xorm:"UNIQUE(s)"`
RepoID int64 `xorm:"UNIQUE(s)"` RepoID int64 `xorm:"UNIQUE(s)"`
} }
// Star or unstar repository. // StarRepo star or unstar repository.
func StarRepo(userID, repoID int64, star bool) (err error) { func StarRepo(userID, repoID int64, star bool) (err error) {
if star { if star {
if IsStaring(userID, repoID) { if IsStaring(userID, repoID) {
@ -2031,6 +2083,7 @@ func IsStaring(userID, repoID int64) bool {
return has return has
} }
// GetStargazers returns the users who gave stars to this repository
func (repo *Repository) GetStargazers(page int) ([]*User, error) { func (repo *Repository) GetStargazers(page int) ([]*User, error) {
users := make([]*User, 0, ItemsPerPage) users := make([]*User, 0, ItemsPerPage)
sess := x. sess := x.
@ -2060,6 +2113,7 @@ func HasForkedRepo(ownerID, repoID int64) (*Repository, bool) {
return repo, has return repo, has
} }
// ForkRepository forks a repository
func ForkRepository(u *User, oldRepo *Repository, name, desc string) (_ *Repository, err error) { func ForkRepository(u *User, oldRepo *Repository, name, desc string) (_ *Repository, err error) {
repo := &Repository{ repo := &Repository{
OwnerID: u.ID, OwnerID: u.ID,
@ -2109,6 +2163,7 @@ func ForkRepository(u *User, oldRepo *Repository, name, desc string) (_ *Reposit
return repo, sess.Commit() return repo, sess.Commit()
} }
// GetForks returns all the forks of the repository
func (repo *Repository) GetForks() ([]*Repository, error) { func (repo *Repository) GetForks() ([]*Repository, error) {
forks := make([]*Repository, 0, repo.NumForks) forks := make([]*Repository, 0, repo.NumForks)
return forks, x.Find(&forks, &Repository{ForkID: repo.ID}) return forks, x.Find(&forks, &Repository{ForkID: repo.ID})
@ -2122,6 +2177,7 @@ func (repo *Repository) GetForks() ([]*Repository, error) {
// \/ \/ \/ \/ \/ // \/ \/ \/ \/ \/
// //
// CreateNewBranch creates a new repository branch
func (repo *Repository) CreateNewBranch(doer *User, oldBranchName, branchName string) (err error) { func (repo *Repository) CreateNewBranch(doer *User, oldBranchName, branchName string) (err error) {
repoWorkingPool.CheckIn(com.ToStr(repo.ID)) repoWorkingPool.CheckIn(com.ToStr(repo.ID))
defer repoWorkingPool.CheckOut(com.ToStr(repo.ID)) defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))