1
0
Fork 0
mirror of https://codeberg.org/forgejo/forgejo.git synced 2024-11-22 08:42:32 -05:00

Merge pull request #295 from Bwko/Lint/repo_

Lint models/repo
This commit is contained in:
Andrey Nering 2016-11-28 20:29:15 -02:00 committed by GitHub
commit b9b22b4a0b
3 changed files with 86 additions and 17 deletions

View file

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

View file

@ -16,6 +16,7 @@ type Collaboration struct {
Mode AccessMode `xorm:"DEFAULT 2 NOT NULL"`
}
// ModeI18nKey returns the collaboration mode I18n Key
func (c *Collaboration) ModeI18nKey() string {
switch c.Mode {
case AccessModeRead:

View file

@ -50,6 +50,7 @@ func discardLocalRepoBranchChanges(localPath, branch string) error {
return nil
}
// DiscardLocalRepoBranchChanges discards the local repository branch changes
func (repo *Repository) DiscardLocalRepoBranchChanges(branch string) error {
return discardLocalRepoBranchChanges(repo.LocalCopyPath(), branch)
}
@ -66,10 +67,12 @@ func checkoutNewBranch(repoPath, localPath, oldBranch, newBranch string) error {
return nil
}
// CheckoutNewBranch checks out a new branch
func (repo *Repository) CheckoutNewBranch(oldBranch, newBranch string) error {
return checkoutNewBranch(repo.RepoPath(), repo.LocalCopyPath(), oldBranch, newBranch)
}
// UpdateRepoFileOptions holds the repository file update options
type UpdateRepoFileOptions struct {
LastCommitID string
OldBranch string
@ -223,6 +226,7 @@ func (repo *Repository) GetDiffPreview(branch, treePath, content string) (diff *
// \/ \/ \/ \/ \/ \/
//
// DeleteRepoFileOptions holds the repository delete file options
type DeleteRepoFileOptions struct {
LastCommitID string
OldBranch string
@ -231,6 +235,7 @@ type DeleteRepoFileOptions struct {
Message string
}
// DeleteRepoFile deletes a repository file
func (repo *Repository) DeleteRepoFile(doer *User, opts DeleteRepoFileOptions) (err error) {
repoWorkingPool.CheckIn(com.ToStr(repo.ID))
defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
@ -351,6 +356,7 @@ func NewUpload(name string, buf []byte, file multipart.File) (_ *Upload, err err
return upload, nil
}
// GetUploadByUUID returns the Upload by UUID
func GetUploadByUUID(uuid string) (*Upload, error) {
upload := &Upload{UUID: uuid}
has, err := x.Get(upload)
@ -362,6 +368,7 @@ func GetUploadByUUID(uuid string) (*Upload, error) {
return upload, nil
}
// GetUploadsByUUIDs returns multiple uploads by UUIDS
func GetUploadsByUUIDs(uuids []string) ([]*Upload, error) {
if len(uuids) == 0 {
return []*Upload{}, nil
@ -372,6 +379,7 @@ func GetUploadsByUUIDs(uuids []string) ([]*Upload, error) {
return uploads, x.In("uuid", uuids).Find(&uploads)
}
// DeleteUploads deletes multiple uploads
func DeleteUploads(uploads ...*Upload) (err error) {
if len(uploads) == 0 {
return nil
@ -407,10 +415,12 @@ func DeleteUploads(uploads ...*Upload) (err error) {
return sess.Commit()
}
// DeleteUpload delete a upload
func DeleteUpload(u *Upload) error {
return DeleteUploads(u)
}
// DeleteUploadByUUID deletes a upload by UUID
func DeleteUploadByUUID(uuid string) error {
upload, err := GetUploadByUUID(uuid)
if err != nil {
@ -427,6 +437,7 @@ func DeleteUploadByUUID(uuid string) error {
return nil
}
// UploadRepoFileOptions contains the uploaded repository file options
type UploadRepoFileOptions struct {
LastCommitID string
OldBranch string
@ -436,6 +447,7 @@ type UploadRepoFileOptions struct {
Files []string // In UUID format.
}
// UploadRepoFiles uploads files to a repository
func (repo *Repository) UploadRepoFiles(doer *User, opts UploadRepoFileOptions) (err error) {
if len(opts.Files) == 0 {
return nil