This commit is contained in:
Joe Chen 2023-11-02 21:32:33 -04:00
parent 9cc3cc7a26
commit 371c56e306
No known key found for this signature in database
GPG Key ID: 0BDE5280C552FF60
35 changed files with 689 additions and 618 deletions

View File

@ -29,7 +29,7 @@ func ServeGoGet() macaron.Handler {
owner, err := db.Users.GetByUsername(c.Req.Context(), ownerName)
if err == nil {
repo, err := db.Repos.GetByName(c.Req.Context(), owner.ID, repoName)
repo, err := db.Repositories.GetByName(c.Req.Context(), owner.ID, repoName)
if err == nil && repo.DefaultBranch != "" {
branchName = repo.DefaultBranch
}

View File

@ -74,7 +74,7 @@ func HandleOrgAssignment(c *Context, args ...bool) {
c.Org.IsTeamMember = true
c.Org.IsTeamAdmin = true
} else {
c.Org.IsMember, _ = db.Orgs.HasMember(c.Req.Context(), org.ID, c.User.ID)
c.Org.IsMember, _ = db.Organizations.HasMember(c.Req.Context(), org.ID, c.User.ID)
}
} else {
// Fake data.

View File

@ -403,7 +403,7 @@ func RepoRef() macaron.Handler {
c.Data["IsViewCommit"] = c.Repo.IsViewCommit
// People who have push access or have forked repository can propose a new pull request.
if c.Repo.IsWriter() || (c.IsLogged && db.Repos.HasForkedBy(c.Req.Context(), c.Repo.Repository.ID, c.User.ID)) {
if c.Repo.IsWriter() || (c.IsLogged && db.Repositories.HasForkedBy(c.Req.Context(), c.Repo.Repository.ID, c.User.ID)) {
// Pull request is allowed if this is a fork repository
// and base repository accepts pull requests.
if c.Repo.Repository.BaseRepo != nil {

View File

@ -165,7 +165,7 @@ func (db *actions) ListByUser(ctx context.Context, userID, actorID, afterID int6
// notifyWatchers creates rows in action table for watchers who are able to see the action.
func (db *actions) notifyWatchers(ctx context.Context, act *Action) error {
watches, err := NewReposStore(db.DB).ListWatches(ctx, act.RepoID)
watches, err := NewRepositoriesStore(db.DB).ListWatches(ctx, act.RepoID)
if err != nil {
return errors.Wrap(err, "list watches")
}
@ -489,7 +489,7 @@ type CommitRepoOptions struct {
}
func (db *actions) CommitRepo(ctx context.Context, opts CommitRepoOptions) error {
err := NewReposStore(db.DB).Touch(ctx, opts.Repo.ID)
err := NewRepositoriesStore(db.DB).Touch(ctx, opts.Repo.ID)
if err != nil {
return errors.Wrap(err, "touch repository")
}
@ -633,7 +633,7 @@ type PushTagOptions struct {
}
func (db *actions) PushTag(ctx context.Context, opts PushTagOptions) error {
err := NewReposStore(db.DB).Touch(ctx, opts.Repo.ID)
err := NewRepositoriesStore(db.DB).Touch(ctx, opts.Repo.ID)
if err != nil {
return errors.Wrap(err, "touch repository")
}

View File

@ -137,7 +137,7 @@ func TestActions(t *testing.T) {
func actionsCommitRepo(t *testing.T, ctx context.Context, db *actions) {
alice, err := NewUsersStore(db.DB).Create(ctx, "alice", "alice@example.com", CreateUserOptions{})
require.NoError(t, err)
repo, err := NewReposStore(db.DB).Create(ctx,
repo, err := NewRepositoriesStore(db.DB).Create(ctx,
alice.ID,
CreateRepoOptions{
Name: "example",
@ -440,7 +440,7 @@ func actionsListByUser(t *testing.T, ctx context.Context, db *actions) {
func actionsMergePullRequest(t *testing.T, ctx context.Context, db *actions) {
alice, err := NewUsersStore(db.DB).Create(ctx, "alice", "alice@example.com", CreateUserOptions{})
require.NoError(t, err)
repo, err := NewReposStore(db.DB).Create(ctx,
repo, err := NewRepositoriesStore(db.DB).Create(ctx,
alice.ID,
CreateRepoOptions{
Name: "example",
@ -485,7 +485,7 @@ func actionsMergePullRequest(t *testing.T, ctx context.Context, db *actions) {
func actionsMirrorSyncCreate(t *testing.T, ctx context.Context, db *actions) {
alice, err := NewUsersStore(db.DB).Create(ctx, "alice", "alice@example.com", CreateUserOptions{})
require.NoError(t, err)
repo, err := NewReposStore(db.DB).Create(ctx,
repo, err := NewRepositoriesStore(db.DB).Create(ctx,
alice.ID,
CreateRepoOptions{
Name: "example",
@ -526,7 +526,7 @@ func actionsMirrorSyncCreate(t *testing.T, ctx context.Context, db *actions) {
func actionsMirrorSyncDelete(t *testing.T, ctx context.Context, db *actions) {
alice, err := NewUsersStore(db.DB).Create(ctx, "alice", "alice@example.com", CreateUserOptions{})
require.NoError(t, err)
repo, err := NewReposStore(db.DB).Create(ctx,
repo, err := NewRepositoriesStore(db.DB).Create(ctx,
alice.ID,
CreateRepoOptions{
Name: "example",
@ -567,7 +567,7 @@ func actionsMirrorSyncDelete(t *testing.T, ctx context.Context, db *actions) {
func actionsMirrorSyncPush(t *testing.T, ctx context.Context, db *actions) {
alice, err := NewUsersStore(db.DB).Create(ctx, "alice", "alice@example.com", CreateUserOptions{})
require.NoError(t, err)
repo, err := NewReposStore(db.DB).Create(ctx,
repo, err := NewRepositoriesStore(db.DB).Create(ctx,
alice.ID,
CreateRepoOptions{
Name: "example",
@ -632,7 +632,7 @@ func actionsMirrorSyncPush(t *testing.T, ctx context.Context, db *actions) {
func actionsNewRepo(t *testing.T, ctx context.Context, db *actions) {
alice, err := NewUsersStore(db.DB).Create(ctx, "alice", "alice@example.com", CreateUserOptions{})
require.NoError(t, err)
repo, err := NewReposStore(db.DB).Create(ctx,
repo, err := NewRepositoriesStore(db.DB).Create(ctx,
alice.ID,
CreateRepoOptions{
Name: "example",
@ -711,7 +711,7 @@ func actionsPushTag(t *testing.T, ctx context.Context, db *actions) {
alice, err := NewUsersStore(db.DB).Create(ctx, "alice", "alice@example.com", CreateUserOptions{})
require.NoError(t, err)
repo, err := NewReposStore(db.DB).Create(ctx,
repo, err := NewRepositoriesStore(db.DB).Create(ctx,
alice.ID,
CreateRepoOptions{
Name: "example",
@ -803,7 +803,7 @@ func actionsPushTag(t *testing.T, ctx context.Context, db *actions) {
func actionsRenameRepo(t *testing.T, ctx context.Context, db *actions) {
alice, err := NewUsersStore(db.DB).Create(ctx, "alice", "alice@example.com", CreateUserOptions{})
require.NoError(t, err)
repo, err := NewReposStore(db.DB).Create(ctx,
repo, err := NewRepositoriesStore(db.DB).Create(ctx,
alice.ID,
CreateRepoOptions{
Name: "example",
@ -842,7 +842,7 @@ func actionsTransferRepo(t *testing.T, ctx context.Context, db *actions) {
require.NoError(t, err)
bob, err := NewUsersStore(db.DB).Create(ctx, "bob", "bob@example.com", CreateUserOptions{})
require.NoError(t, err)
repo, err := NewReposStore(db.DB).Create(ctx,
repo, err := NewRepositoriesStore(db.DB).Create(ctx,
alice.ID,
CreateRepoOptions{
Name: "example",

View File

@ -127,9 +127,9 @@ func Init(w logger.Writer) (*gorm.DB, error) {
LoginSources = &loginSources{DB: db, files: sourceFiles}
LFS = &lfs{DB: db}
Notices = NewNoticesStore(db)
Orgs = NewOrgsStore(db)
Organizations = NewOrganizationsStore(db)
Perms = NewPermsStore(db)
Repos = NewReposStore(db)
Repositories = NewRepositoriesStore(db)
TwoFactors = &twoFactors{DB: db}
Users = NewUsersStore(db)

View File

@ -48,11 +48,11 @@ func SetMockPermsStore(t *testing.T, mock PermsStore) {
})
}
func SetMockReposStore(t *testing.T, mock ReposStore) {
before := Repos
Repos = mock
func SetMockReposStore(t *testing.T, mock RepositoriesStore) {
before := Repositories
Repositories = mock
t.Cleanup(func() {
Repos = before
Repositories = before
})
}

View File

@ -211,7 +211,7 @@ type Statistic struct {
func GetStatistic(ctx context.Context) (stats Statistic) {
stats.Counter.User = Users.Count(ctx)
stats.Counter.Org = Orgs.Count(ctx)
stats.Counter.Org = Organizations.Count(ctx)
stats.Counter.PublicKey, _ = x.Count(new(PublicKey))
stats.Counter.Repo = CountRepositories(true)
stats.Counter.Watch, _ = x.Count(new(Watch))

View File

@ -7,97 +7,11 @@ package db
import (
"context"
"fmt"
"os"
"strings"
"xorm.io/builder"
"xorm.io/xorm"
"gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/repoutil"
"gogs.io/gogs/internal/userutil"
)
// CreateOrganization creates record of a new organization.
func CreateOrganization(org, owner *User) (err error) {
if err = isUsernameAllowed(org.Name); err != nil {
return err
}
if Users.IsUsernameUsed(context.TODO(), org.Name, 0) {
return ErrUserAlreadyExist{
args: errutil.Args{
"name": org.Name,
},
}
}
org.LowerName = strings.ToLower(org.Name)
if org.Rands, err = userutil.RandomSalt(); err != nil {
return err
}
if org.Salt, err = userutil.RandomSalt(); err != nil {
return err
}
org.UseCustomAvatar = true
org.MaxRepoCreation = -1
org.NumTeams = 1
org.NumMembers = 1
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if _, err = sess.Insert(org); err != nil {
return fmt.Errorf("insert organization: %v", err)
}
_ = userutil.GenerateRandomAvatar(org.ID, org.Name, org.Email)
// Add initial creator to organization and owner team.
if _, err = sess.Insert(&OrgUser{
UserID: owner.ID,
OrgID: org.ID,
IsOwner: true,
NumTeams: 1,
}); err != nil {
return fmt.Errorf("insert org-user relation: %v", err)
}
// Create default owner team.
t := &Team{
OrgID: org.ID,
LowerName: strings.ToLower(TeamNameOwners),
Name: TeamNameOwners,
Authorize: AccessModeOwner,
NumMembers: 1,
}
if _, err = sess.Insert(t); err != nil {
return fmt.Errorf("insert owner team: %v", err)
}
if _, err = sess.Insert(&TeamUser{
UID: owner.ID,
OrgID: org.ID,
TeamID: t.ID,
}); err != nil {
return fmt.Errorf("insert team-user relation: %v", err)
}
if err = os.MkdirAll(repoutil.UserPath(org.Name), os.ModePerm); err != nil {
return fmt.Errorf("create directory: %v", err)
}
return sess.Commit()
}
// Organizations returns number of organizations in given page.
func Organizations(page, pageSize int) ([]*User, error) {
orgs := make([]*User, 0, pageSize)
return orgs, x.Limit(pageSize, (page-1)*pageSize).Where("type=1").Asc("id").Find(&orgs)
}
// deleteBeans deletes all given beans, beans should contain delete conditions.
func deleteBeans(e Engine, beans ...any) (err error) {
for i := range beans {

View File

@ -486,7 +486,7 @@ func AddTeamMember(orgID, teamID, userID int64) error {
return nil
}
if err := Orgs.AddMember(context.TODO(), orgID, userID); err != nil {
if err := Organizations.AddMember(context.TODO(), orgID, userID); err != nil {
return err
}

View File

@ -7,6 +7,7 @@ package db
import (
"context"
"fmt"
"os"
"strings"
"github.com/pkg/errors"
@ -14,10 +15,32 @@ import (
"gogs.io/gogs/internal/dbutil"
"gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/repoutil"
"gogs.io/gogs/internal/userutil"
)
// OrgsStore is the persistent interface for organizations.
type OrgsStore interface {
// OrganizationsStore is the persistent interface for organizations.
type OrganizationsStore interface {
// Create creates a new organization with the initial owner and persists to
// database. It returns ErrNameNotAllowed if the given name or pattern of the
// name is not allowed as an organization name, or ErrOrganizationAlreadyExist
// when a user or an organization with same name already exists.
Create(ctx context.Context, name string, ownerID int64, opts CreateOrganizationOptions) (*Organization, error)
// GetByName returns the organization with given name.
GetByName(ctx context.Context, name string) (*Organization, error)
// SearchByName returns a list of organizations whose username or full name
// matches the given keyword case-insensitively. Results are paginated by given
// page and page size, and sorted by the given order (e.g. "id DESC"). A total
// count of all results is also returned. If the order is not given, it's up to
// the database to decide.
SearchByName(ctx context.Context, keyword string, page, pageSize int, orderBy string) ([]*Organization, int64, error)
// List returns a list of organizations filtered by options.
List(ctx context.Context, opts ListOrganizationsOptions) ([]*Organization, error)
// CountByUser returns the number of organizations the user is a member of.
CountByUser(ctx context.Context, userID int64) (int64, error)
// Count returns the total number of organizations.
Count(ctx context.Context) int64
// AddMember adds a new member to the given organization.
AddMember(ctx context.Context, orgID, userID int64) error
// RemoveMember removes a member from the given organization.
@ -33,21 +56,6 @@ type OrgsStore interface {
// SetMemberVisibility sets the visibility of the given user in the organization.
SetMemberVisibility(ctx context.Context, orgID, userID int64, public bool) error
// GetByName returns the organization with given name.
GetByName(ctx context.Context, name string) (*Organization, error)
// SearchByName returns a list of organizations whose username or full name
// matches the given keyword case-insensitively. Results are paginated by given
// page and page size, and sorted by the given order (e.g. "id DESC"). A total
// count of all results is also returned. If the order is not given, it's up to
// the database to decide.
SearchByName(ctx context.Context, keyword string, page, pageSize int, orderBy string) ([]*Organization, int64, error)
// List returns a list of organizations filtered by options.
List(ctx context.Context, opts ListOrgsOptions) ([]*Organization, error)
// CountByUser returns the number of organizations the user is a member of.
CountByUser(ctx context.Context, userID int64) (int64, error)
// Count returns the total number of organizations.
Count(ctx context.Context) int64
// GetTeamByName returns the team with given name under the given organization.
// It returns ErrTeamNotExist whe not found.
GetTeamByName(ctx context.Context, orgID int64, name string) (*Team, error)
@ -59,21 +67,21 @@ type OrgsStore interface {
AccessibleRepositoriesByUser(ctx context.Context, orgID, userID int64, page, pageSize int, opts AccessibleRepositoriesByUserOptions) ([]*Repository, int64, error)
}
var Orgs OrgsStore
var Organizations OrganizationsStore
var _ OrgsStore = (*orgs)(nil)
var _ OrganizationsStore = (*organizations)(nil)
type orgs struct {
type organizations struct {
*gorm.DB
}
// NewOrgsStore returns a persistent interface for orgs with given database
// connection.
func NewOrgsStore(db *gorm.DB) OrgsStore {
return &orgs{DB: db}
// NewOrganizationsStore returns a persistent interface for orgs with given
// database connection.
func NewOrganizationsStore(db *gorm.DB) OrganizationsStore {
return &organizations{DB: db}
}
func (*orgs) recountMembers(tx *gorm.DB, orgID int64) error {
func (*organizations) recountMembers(tx *gorm.DB, orgID int64) error {
/*
Equivalent SQL for PostgreSQL:
@ -96,7 +104,7 @@ func (*orgs) recountMembers(tx *gorm.DB, orgID int64) error {
return nil
}
func (db *orgs) AddMember(ctx context.Context, orgID, userID int64) error {
func (db *organizations) AddMember(ctx context.Context, orgID, userID int64) error {
return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
ou := &OrgUser{
UserID: userID,
@ -124,7 +132,7 @@ func (err ErrLastOrgOwner) Error() string {
return fmt.Sprintf("user is the last owner of the organization: %v", err.args)
}
func (db *orgs) RemoveMember(ctx context.Context, orgID, userID int64) error {
func (db *organizations) RemoveMember(ctx context.Context, orgID, userID int64) error {
ou, err := db.getOrgUser(ctx, orgID, userID)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
@ -210,7 +218,7 @@ type accessibleRepositoriesByUserOptions struct {
pageSize int
}
func (*orgs) accessibleRepositoriesByUser(tx *gorm.DB, orgID, userID int64, opts accessibleRepositoriesByUserOptions) *gorm.DB {
func (*organizations) accessibleRepositoriesByUser(tx *gorm.DB, orgID, userID int64, opts accessibleRepositoriesByUserOptions) *gorm.DB {
/*
Equivalent SQL for PostgreSQL:
@ -252,7 +260,7 @@ type AccessibleRepositoriesByUserOptions struct {
SkipCount bool
}
func (db *orgs) AccessibleRepositoriesByUser(ctx context.Context, orgID, userID int64, page, pageSize int, opts AccessibleRepositoriesByUserOptions) ([]*Repository, int64, error) {
func (db *organizations) AccessibleRepositoriesByUser(ctx context.Context, orgID, userID int64, page, pageSize int, opts AccessibleRepositoriesByUserOptions) ([]*Repository, int64, error) {
conds := db.accessibleRepositoriesByUser(
db.DB,
orgID,
@ -281,21 +289,21 @@ func (db *orgs) AccessibleRepositoriesByUser(ctx context.Context, orgID, userID
return repos, count, nil
}
func (db *orgs) getOrgUser(ctx context.Context, orgID, userID int64) (*OrgUser, error) {
func (db *organizations) getOrgUser(ctx context.Context, orgID, userID int64) (*OrgUser, error) {
var ou OrgUser
return &ou, db.WithContext(ctx).Where("org_id = ? AND uid = ?", orgID, userID).First(&ou).Error
}
func (db *orgs) IsOwnedBy(ctx context.Context, orgID, userID int64) bool {
func (db *organizations) IsOwnedBy(ctx context.Context, orgID, userID int64) bool {
ou, err := db.getOrgUser(ctx, orgID, userID)
return err == nil && ou.IsOwner
}
func (db *orgs) SetMemberVisibility(ctx context.Context, orgID, userID int64, public bool) error {
func (db *organizations) SetMemberVisibility(ctx context.Context, orgID, userID int64, public bool) error {
return db.Table("org_user").Where("org_id = ? AND uid = ?", orgID, userID).UpdateColumn("is_public", public).Error
}
func (db *orgs) HasMember(ctx context.Context, orgID, userID int64) (bool, bool) {
func (db *organizations) HasMember(ctx context.Context, orgID, userID int64) (bool, bool) {
ou, err := db.getOrgUser(ctx, orgID, userID)
return err == nil, ou != nil && ou.IsPublic
}
@ -305,7 +313,7 @@ type ListOrgMembersOptions struct {
Limit int
}
func (db *orgs) ListMembers(ctx context.Context, orgID int64, opts ListOrgMembersOptions) ([]*User, error) {
func (db *organizations) ListMembers(ctx context.Context, orgID int64, opts ListOrgMembersOptions) ([]*User, error) {
/*
Equivalent SQL for PostgreSQL:
@ -327,14 +335,18 @@ func (db *orgs) ListMembers(ctx context.Context, orgID int64, opts ListOrgMember
return users, conds.Find(&users).Error
}
type ListOrgsOptions struct {
type ListOrganizationsOptions struct {
// Filter by the membership with the given user ID.
MemberID int64
// Whether to include private memberships.
IncludePrivateMembers bool
// 1-based page number.
Page int
// Number of results per page.
PageSize int
}
func (db *orgs) List(ctx context.Context, opts ListOrgsOptions) ([]*Organization, error) {
func (db *organizations) List(ctx context.Context, opts ListOrganizationsOptions) ([]*Organization, error) {
if opts.MemberID <= 0 {
return nil, errors.New("MemberID must be greater than 0")
}
@ -343,24 +355,144 @@ func (db *orgs) List(ctx context.Context, opts ListOrgsOptions) ([]*Organization
Equivalent SQL for PostgreSQL:
SELECT * FROM "user"
JOIN org_user ON org_user.org_id = user.id
[JOIN org_user ON org_user.org_id = user.id]
WHERE
org_user.uid = @memberID
[AND org_user.is_public = @includePrivateMembers]
type = @type
[AND org_user.uid = @memberID
AND org_user.is_public = @includePrivateMembers]
ORDER BY user.id ASC
[LIMIT @limit OFFSET @offset]
*/
conds := db.WithContext(ctx).
Joins(dbutil.Quote("JOIN org_user ON org_user.org_id = %s.id", "user")).
Where("org_user.uid = ?", opts.MemberID).
Where("type = ?", UserTypeOrganization).
Order(dbutil.Quote("%s.id ASC", "user"))
if opts.MemberID > 0 || !opts.IncludePrivateMembers {
conds.Joins(dbutil.Quote("JOIN org_user ON org_user.org_id = %s.id", "user"))
}
if opts.MemberID > 0 {
conds.Where("org_user.uid = ?", opts.MemberID)
}
if !opts.IncludePrivateMembers {
conds.Where("org_user.is_public = ?", true)
}
if opts.Page > 0 && opts.PageSize > 0 {
conds.Limit(opts.PageSize).Offset((opts.Page - 1) * opts.PageSize)
}
var orgs []*Organization
return orgs, conds.Find(&orgs).Error
}
type CreateOrganizationOptions struct {
FullName string
Location string
Website string
Description string
}
type ErrOrganizationAlreadyExist struct {
args errutil.Args
}
// IsErrOrganizationAlreadyExist returns true if the underlying error has the
// type ErrOrganizationAlreadyExist.
func IsErrOrganizationAlreadyExist(err error) bool {
return errors.As(err, &ErrOrganizationAlreadyExist{})
}
func (err ErrOrganizationAlreadyExist) Error() string {
return fmt.Sprintf("organization already exists: %v", err.args)
}
func (db *organizations) Create(ctx context.Context, name string, ownerID int64, opts CreateOrganizationOptions) (*Organization, error) {
err := isUsernameAllowed(name)
if err != nil {
return nil, err
}
if Users.IsUsernameUsed(ctx, name, 0) {
return nil, ErrOrganizationAlreadyExist{
args: errutil.Args{
"name": name,
},
}
}
org := &Organization{
LowerName: strings.ToLower(name),
Name: name,
FullName: opts.FullName,
Type: UserTypeOrganization,
Location: opts.Location,
Website: opts.Website,
MaxRepoCreation: -1,
IsActive: true,
UseCustomAvatar: true,
Description: opts.Description,
NumTeams: 1, // The default "owners" team
NumMembers: 1, // The initial owner
}
org.Rands, err = userutil.RandomSalt()
if err != nil {
return nil, err
}
org.Salt, err = userutil.RandomSalt()
if err != nil {
return nil, err
}
return org, db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
err := tx.Create(org).Error
if err != nil {
return errors.Wrap(err, "create organization")
}
err = tx.Create(&OrgUser{
UserID: ownerID,
OrgID: org.ID,
IsOwner: true,
NumTeams: 1,
}).Error
if err != nil {
return errors.Wrap(err, "create org-user relation")
}
team := &Team{
OrgID: org.ID,
LowerName: strings.ToLower(TeamNameOwners),
Name: TeamNameOwners,
Authorize: AccessModeOwner,
NumMembers: 1,
}
err = tx.Create(team).Error
if err != nil {
return errors.Wrap(err, "create owner team")
}
err = tx.Create(&TeamUser{
UID: ownerID,
OrgID: org.ID,
TeamID: team.ID,
}).Error
if err != nil {
return errors.Wrap(err, "create team-user relation")
}
err = userutil.GenerateRandomAvatar(org.ID, org.Name, org.Email)
if err != nil {
return errors.Wrap(err, "generate organization avatar")
}
err = os.MkdirAll(repoutil.UserPath(org.Name), os.ModePerm)
if err != nil {
return errors.Wrap(err, "create organization directory")
}
return nil
})
}
var _ errutil.NotFound = (*ErrUserNotExist)(nil)
type ErrOrganizationNotExist struct {
@ -381,7 +513,7 @@ func (ErrOrganizationNotExist) NotFound() bool {
return true
}
func (db *orgs) GetByName(ctx context.Context, name string) (*Organization, error) {
func (db *organizations) GetByName(ctx context.Context, name string) (*Organization, error) {
org, err := getUserByUsername(ctx, db.DB, UserTypeOrganization, name)
if err != nil {
if IsErrUserNotExist(err) {
@ -392,16 +524,16 @@ func (db *orgs) GetByName(ctx context.Context, name string) (*Organization, erro
return org, nil
}
func (db *orgs) SearchByName(ctx context.Context, keyword string, page, pageSize int, orderBy string) ([]*Organization, int64, error) {
func (db *organizations) SearchByName(ctx context.Context, keyword string, page, pageSize int, orderBy string) ([]*Organization, int64, error) {
return searchUserByName(ctx, db.DB, UserTypeOrganization, keyword, page, pageSize, orderBy)
}
func (db *orgs) CountByUser(ctx context.Context, userID int64) (int64, error) {
func (db *organizations) CountByUser(ctx context.Context, userID int64) (int64, error) {
var count int64
return count, db.WithContext(ctx).Model(&OrgUser{}).Where("uid = ?", userID).Count(&count).Error
}
func (db *orgs) Count(ctx context.Context) int64 {
func (db *organizations) Count(ctx context.Context) int64 {
var count int64
db.WithContext(ctx).Model(&User{}).Where("type = ?", UserTypeOrganization).Count(&count)
return count
@ -425,7 +557,7 @@ func (ErrTeamNotExist) NotFound() bool {
return true
}
func (db *orgs) GetTeamByName(ctx context.Context, orgID int64, name string) (*Team, error) {
func (db *organizations) GetTeamByName(ctx context.Context, orgID int64, name string) (*Team, error) {
var team Team
err := db.WithContext(ctx).Where("org_id = ? AND lower_name = ?", orgID, strings.ToLower(name)).First(&team).Error
if err != nil {
@ -448,7 +580,7 @@ func (u *Organization) TableName() string {
// TODO(unknwon): This is also used in templates, which should be fixed by
// having a dedicated type `template.Organization`.
func (u *Organization) IsOwnedBy(userID int64) bool {
return Orgs.IsOwnedBy(context.TODO(), u.ID, userID)
return Organizations.IsOwnedBy(context.TODO(), u.ID, userID)
}
// OrgUser represents relations of organizations and their members.

View File

@ -23,13 +23,13 @@ func TestOrgs(t *testing.T) {
ctx := context.Background()
tables := []any{new(User), new(EmailAddress), new(OrgUser)}
db := &orgs{
db := &organizations{
DB: dbtest.NewDB(t, "orgs", tables...),
}
for _, tc := range []struct {
name string
test func(t *testing.T, ctx context.Context, db *orgs)
test func(t *testing.T, ctx context.Context, db *organizations)
}{
{"List", orgsList},
{"SearchByName", orgsSearchByName},
@ -48,7 +48,7 @@ func TestOrgs(t *testing.T) {
}
}
func orgsList(t *testing.T, ctx context.Context, db *orgs) {
func orgsList(t *testing.T, ctx context.Context, db *organizations) {
usersStore := NewUsersStore(db.DB)
alice, err := usersStore.Create(ctx, "alice", "alice@example.com", CreateUserOptions{})
require.NoError(t, err)
@ -76,12 +76,12 @@ func orgsList(t *testing.T, ctx context.Context, db *orgs) {
tests := []struct {
name string
opts ListOrgsOptions
opts ListOrganizationsOptions
wantOrgNames []string
}{
{
name: "only public memberships for a user",
opts: ListOrgsOptions{
opts: ListOrganizationsOptions{
MemberID: alice.ID,
IncludePrivateMembers: false,
},
@ -89,7 +89,7 @@ func orgsList(t *testing.T, ctx context.Context, db *orgs) {
},
{
name: "all memberships for a user",
opts: ListOrgsOptions{
opts: ListOrganizationsOptions{
MemberID: alice.ID,
IncludePrivateMembers: true,
},
@ -97,7 +97,7 @@ func orgsList(t *testing.T, ctx context.Context, db *orgs) {
},
{
name: "no membership for a non-existent user",
opts: ListOrgsOptions{
opts: ListOrganizationsOptions{
MemberID: 404,
IncludePrivateMembers: true,
},
@ -118,7 +118,7 @@ func orgsList(t *testing.T, ctx context.Context, db *orgs) {
}
}
func orgsSearchByName(t *testing.T, ctx context.Context, db *orgs) {
func orgsSearchByName(t *testing.T, ctx context.Context, db *organizations) {
// TODO: Use Orgs.Create to replace SQL hack when the method is available.
usersStore := NewUsersStore(db.DB)
org1, err := usersStore.Create(ctx, "org1", "org1@example.com", CreateUserOptions{FullName: "Acme Corp"})
@ -163,7 +163,7 @@ func orgsSearchByName(t *testing.T, ctx context.Context, db *orgs) {
})
}
func orgsCountByUser(t *testing.T, ctx context.Context, db *orgs) {
func orgsCountByUser(t *testing.T, ctx context.Context, db *organizations) {
// TODO: Use Orgs.Join to replace SQL hack when the method is available.
err := db.Exec(`INSERT INTO org_user (uid, org_id) VALUES (?, ?)`, 1, 1).Error
require.NoError(t, err)

View File

@ -798,7 +798,7 @@ func MigrateRepository(doer, owner *User, opts MigrateRepoOptions) (*Repository,
wikiPath := WikiPath(owner.Name, opts.Name)
if owner.IsOrganization() {
t, err := Orgs.GetTeamByName(context.TODO(), owner.ID, TeamNameOwners)
t, err := Organizations.GetTeamByName(context.TODO(), owner.ID, TeamNameOwners)
if err != nil {
return nil, err
}
@ -1135,7 +1135,7 @@ func createRepository(e *xorm.Session, doer, owner *User, repo *Repository) (err
if err != nil {
return fmt.Errorf("IsRepositoryExist: %v", err)
} else if has {
return ErrRepoAlreadyExist{args: errutil.Args{"ownerID": owner.ID, "name": repo.Name}}
return ErrRepositoryAlreadyExist{args: errutil.Args{"ownerID": owner.ID, "name": repo.Name}}
}
if _, err = e.Insert(repo); err != nil {
@ -1311,14 +1311,14 @@ func CountUserRepositories(userID int64, private bool) int64 {
return countRepositories(userID, private)
}
func Repositories(page, pageSize int) (_ []*Repository, err error) {
func ListRepositories(page, pageSize int) (_ []*Repository, err error) {
repos := make([]*Repository, 0, pageSize)
return repos, x.Limit(pageSize, (page-1)*pageSize).Asc("id").Find(&repos)
}
// RepositoriesWithUsers returns number of repos in given page.
func RepositoriesWithUsers(page, pageSize int) (_ []*Repository, err error) {
repos, err := Repositories(page, pageSize)
repos, err := ListRepositories(page, pageSize)
if err != nil {
return nil, fmt.Errorf("Repositories: %v", err)
}
@ -1379,7 +1379,7 @@ func TransferOwnership(doer *User, newOwnerName string, repo *Repository) error
if err != nil {
return fmt.Errorf("IsRepositoryExist: %v", err)
} else if has {
return ErrRepoAlreadyExist{args: errutil.Args{"ownerName": newOwnerName, "name": repo.Name}}
return ErrRepositoryAlreadyExist{args: errutil.Args{"ownerName": newOwnerName, "name": repo.Name}}
}
sess := x.NewSession()
@ -1411,7 +1411,7 @@ func TransferOwnership(doer *User, newOwnerName string, repo *Repository) error
for _, c := range collaborators {
collaboration.UserID = c.ID
if c.ID == newOwner.ID ||
(newOwner.IsOrganization() && func() bool { member, _ := Orgs.HasMember(context.TODO(), newOwner.ID, c.ID); return member }()) {
(newOwner.IsOrganization() && func() bool { member, _ := Organizations.HasMember(context.TODO(), newOwner.ID, c.ID); return member }()) {
if _, err = sess.Delete(collaboration); err != nil {
return fmt.Errorf("remove collaborator '%d': %v", c.ID, err)
}
@ -1552,7 +1552,7 @@ func ChangeRepositoryName(u *User, oldRepoName, newRepoName string) (err error)
if err != nil {
return fmt.Errorf("IsRepositoryExist: %v", err)
} else if has {
return ErrRepoAlreadyExist{args: errutil.Args{"ownerID": u.ID, "name": newRepoName}}
return ErrRepositoryAlreadyExist{args: errutil.Args{"ownerID": u.ID, "name": newRepoName}}
}
repo, err := GetRepositoryByName(u.ID, oldRepoName)

View File

@ -18,11 +18,11 @@ import (
"gogs.io/gogs/internal/repoutil"
)
// ReposStore is the persistent interface for repositories.
type ReposStore interface {
// RepositoriesStore is the persistent interface for repositories.
type RepositoriesStore interface {
// Create creates a new repository record in the database. It returns
// ErrNameNotAllowed when the repository name is not allowed, or
// ErrRepoAlreadyExist when a repository with same name already exists for the
// ErrRepositoryAlreadyExist when a repository with same name already exists for the
// owner.
Create(ctx context.Context, ownerID int64, opts CreateRepoOptions) (*Repository, error)
// GetByCollaboratorID returns a list of repositories that the given
@ -56,7 +56,7 @@ type ReposStore interface {
HasForkedBy(ctx context.Context, repoID, userID int64) bool
}
var Repos ReposStore
var Repositories RepositoriesStore
// BeforeCreate implements the GORM create hook.
func (r *Repository) BeforeCreate(tx *gorm.DB) error {
@ -119,28 +119,27 @@ func (r *Repository) APIFormat(owner *User, opts ...RepositoryAPIFormatOptions)
}
}
var _ ReposStore = (*repos)(nil)
var _ RepositoriesStore = (*repositories)(nil)
type repos struct {
type repositories struct {
*gorm.DB
}
// NewReposStore returns a persistent interface for repositories with given
// NewRepositoriesStore returns a persistent interface for repositories with given
// database connection.
func NewReposStore(db *gorm.DB) ReposStore {
return &repos{DB: db}
func NewRepositoriesStore(db *gorm.DB) RepositoriesStore {
return &repositories{DB: db}
}
type ErrRepoAlreadyExist struct {
type ErrRepositoryAlreadyExist struct {
args errutil.Args
}
func IsErrRepoAlreadyExist(err error) bool {
_, ok := err.(ErrRepoAlreadyExist)
return ok
return errors.As(err, &ErrRepositoryAlreadyExist{})
}
func (err ErrRepoAlreadyExist) Error() string {
func (err ErrRepositoryAlreadyExist) Error() string {
return fmt.Sprintf("repository already exists: %v", err.args)
}
@ -157,7 +156,7 @@ type CreateRepoOptions struct {
ForkID int64
}
func (db *repos) Create(ctx context.Context, ownerID int64, opts CreateRepoOptions) (*Repository, error) {
func (db *repositories) Create(ctx context.Context, ownerID int64, opts CreateRepoOptions) (*Repository, error) {
err := isRepoNameAllowed(opts.Name)
if err != nil {
return nil, err
@ -165,7 +164,7 @@ func (db *repos) Create(ctx context.Context, ownerID int64, opts CreateRepoOptio
_, err = db.GetByName(ctx, ownerID, opts.Name)
if err == nil {
return nil, ErrRepoAlreadyExist{
return nil, ErrRepositoryAlreadyExist{
args: errutil.Args{
"ownerID": ownerID,
"name": opts.Name,
@ -195,7 +194,7 @@ func (db *repos) Create(ctx context.Context, ownerID int64, opts CreateRepoOptio
return errors.Wrap(err, "create")
}
err = NewReposStore(tx).Watch(ctx, ownerID, repo.ID)
err = NewRepositoriesStore(tx).Watch(ctx, ownerID, repo.ID)
if err != nil {
return errors.Wrap(err, "watch")
}
@ -203,7 +202,7 @@ func (db *repos) Create(ctx context.Context, ownerID int64, opts CreateRepoOptio
})
}
func (db *repos) GetByCollaboratorID(ctx context.Context, collaboratorID int64, limit int, orderBy string) ([]*Repository, error) {
func (db *repositories) GetByCollaboratorID(ctx context.Context, collaboratorID int64, limit int, orderBy string) ([]*Repository, error) {
/*
Equivalent SQL for PostgreSQL:
@ -223,7 +222,7 @@ func (db *repos) GetByCollaboratorID(ctx context.Context, collaboratorID int64,
Error
}
func (db *repos) GetByCollaboratorIDWithAccessMode(ctx context.Context, collaboratorID int64) (map[*Repository]AccessMode, error) {
func (db *repositories) GetByCollaboratorIDWithAccessMode(ctx context.Context, collaboratorID int64) (map[*Repository]AccessMode, error) {
/*
Equivalent SQL for PostgreSQL:
@ -274,7 +273,7 @@ func (ErrRepoNotExist) NotFound() bool {
return true
}
func (db *repos) GetByID(ctx context.Context, id int64) (*Repository, error) {
func (db *repositories) GetByID(ctx context.Context, id int64) (*Repository, error) {
repo := new(Repository)
err := db.WithContext(ctx).Where("id = ?", id).First(repo).Error
if err != nil {
@ -286,7 +285,7 @@ func (db *repos) GetByID(ctx context.Context, id int64) (*Repository, error) {
return repo, nil
}
func (db *repos) GetByName(ctx context.Context, ownerID int64, name string) (*Repository, error) {
func (db *repositories) GetByName(ctx context.Context, ownerID int64, name string) (*Repository, error) {
repo := new(Repository)
err := db.WithContext(ctx).
Where("owner_id = ? AND lower_name = ?", ownerID, strings.ToLower(name)).
@ -306,7 +305,7 @@ func (db *repos) GetByName(ctx context.Context, ownerID int64, name string) (*Re
return repo, nil
}
func (db *repos) recountStars(tx *gorm.DB, userID, repoID int64) error {
func (db *repositories) recountStars(tx *gorm.DB, userID, repoID int64) error {
/*
Equivalent SQL for PostgreSQL:
@ -349,7 +348,7 @@ func (db *repos) recountStars(tx *gorm.DB, userID, repoID int64) error {
return nil
}
func (db *repos) Star(ctx context.Context, userID, repoID int64) error {
func (db *repositories) Star(ctx context.Context, userID, repoID int64) error {
return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
s := &Star{
UserID: userID,
@ -366,7 +365,7 @@ func (db *repos) Star(ctx context.Context, userID, repoID int64) error {
})
}
func (db *repos) Touch(ctx context.Context, id int64) error {
func (db *repositories) Touch(ctx context.Context, id int64) error {
return db.WithContext(ctx).
Model(new(Repository)).
Where("id = ?", id).
@ -377,12 +376,12 @@ func (db *repos) Touch(ctx context.Context, id int64) error {
Error
}
func (db *repos) ListWatches(ctx context.Context, repoID int64) ([]*Watch, error) {
func (db *repositories) ListWatches(ctx context.Context, repoID int64) ([]*Watch, error) {
var watches []*Watch
return watches, db.WithContext(ctx).Where("repo_id = ?", repoID).Find(&watches).Error
}
func (db *repos) recountWatches(tx *gorm.DB, repoID int64) error {
func (db *repositories) recountWatches(tx *gorm.DB, repoID int64) error {
/*
Equivalent SQL for PostgreSQL:
@ -401,7 +400,7 @@ func (db *repos) recountWatches(tx *gorm.DB, repoID int64) error {
Error
}
func (db *repos) Watch(ctx context.Context, userID, repoID int64) error {
func (db *repositories) Watch(ctx context.Context, userID, repoID int64) error {
return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
w := &Watch{
UserID: userID,
@ -418,7 +417,7 @@ func (db *repos) Watch(ctx context.Context, userID, repoID int64) error {
})
}
func (db *repos) HasForkedBy(ctx context.Context, repoID, userID int64) bool {
func (db *repositories) HasForkedBy(ctx context.Context, repoID, userID int64) bool {
var count int64
db.WithContext(ctx).Model(new(Repository)).Where("owner_id = ? AND fork_id = ?", userID, repoID).Count(&count)
return count > 0

View File

@ -87,13 +87,13 @@ func TestRepos(t *testing.T) {
ctx := context.Background()
tables := []any{new(Repository), new(Access), new(Watch), new(User), new(EmailAddress), new(Star)}
db := &repos{
db := &repositories{
DB: dbtest.NewDB(t, "repos", tables...),
}
for _, tc := range []struct {
name string
test func(t *testing.T, ctx context.Context, db *repos)
test func(t *testing.T, ctx context.Context, db *repositories)
}{
{"Create", reposCreate},
{"GetByCollaboratorID", reposGetByCollaboratorID},
@ -119,7 +119,7 @@ func TestRepos(t *testing.T) {
}
}
func reposCreate(t *testing.T, ctx context.Context, db *repos) {
func reposCreate(t *testing.T, ctx context.Context, db *repositories) {
t.Run("name not allowed", func(t *testing.T) {
_, err := db.Create(ctx,
1,
@ -144,7 +144,7 @@ func reposCreate(t *testing.T, ctx context.Context, db *repos) {
Name: "repo1",
},
)
wantErr := ErrRepoAlreadyExist{args: errutil.Args{"ownerID": int64(2), "name": "repo1"}}
wantErr := ErrRepositoryAlreadyExist{args: errutil.Args{"ownerID": int64(2), "name": "repo1"}}
assert.Equal(t, wantErr, err)
})
@ -161,7 +161,7 @@ func reposCreate(t *testing.T, ctx context.Context, db *repos) {
assert.Equal(t, 1, repo.NumWatches) // The owner is watching the repo by default.
}
func reposGetByCollaboratorID(t *testing.T, ctx context.Context, db *repos) {
func reposGetByCollaboratorID(t *testing.T, ctx context.Context, db *repositories) {
repo1, err := db.Create(ctx, 1, CreateRepoOptions{Name: "repo1"})
require.NoError(t, err)
repo2, err := db.Create(ctx, 2, CreateRepoOptions{Name: "repo2"})
@ -187,7 +187,7 @@ func reposGetByCollaboratorID(t *testing.T, ctx context.Context, db *repos) {
})
}
func reposGetByCollaboratorIDWithAccessMode(t *testing.T, ctx context.Context, db *repos) {
func reposGetByCollaboratorIDWithAccessMode(t *testing.T, ctx context.Context, db *repositories) {
repo1, err := db.Create(ctx, 1, CreateRepoOptions{Name: "repo1"})
require.NoError(t, err)
repo2, err := db.Create(ctx, 2, CreateRepoOptions{Name: "repo2"})
@ -215,7 +215,7 @@ func reposGetByCollaboratorIDWithAccessMode(t *testing.T, ctx context.Context, d
assert.Equal(t, AccessModeAdmin, accessModes[repo2.ID])
}
func reposGetByID(t *testing.T, ctx context.Context, db *repos) {
func reposGetByID(t *testing.T, ctx context.Context, db *repositories) {
repo1, err := db.Create(ctx, 1, CreateRepoOptions{Name: "repo1"})
require.NoError(t, err)
@ -228,7 +228,7 @@ func reposGetByID(t *testing.T, ctx context.Context, db *repos) {
assert.Equal(t, wantErr, err)
}
func reposGetByName(t *testing.T, ctx context.Context, db *repos) {
func reposGetByName(t *testing.T, ctx context.Context, db *repositories) {
repo, err := db.Create(ctx, 1,
CreateRepoOptions{
Name: "repo1",
@ -244,7 +244,7 @@ func reposGetByName(t *testing.T, ctx context.Context, db *repos) {
assert.Equal(t, wantErr, err)
}
func reposStar(t *testing.T, ctx context.Context, db *repos) {
func reposStar(t *testing.T, ctx context.Context, db *repositories) {
repo1, err := db.Create(ctx, 1, CreateRepoOptions{Name: "repo1"})
require.NoError(t, err)
usersStore := NewUsersStore(db.DB)
@ -263,7 +263,7 @@ func reposStar(t *testing.T, ctx context.Context, db *repos) {
assert.Equal(t, 1, alice.NumStars)
}
func reposTouch(t *testing.T, ctx context.Context, db *repos) {
func reposTouch(t *testing.T, ctx context.Context, db *repositories) {
repo, err := db.Create(ctx, 1,
CreateRepoOptions{
Name: "repo1",
@ -289,7 +289,7 @@ func reposTouch(t *testing.T, ctx context.Context, db *repos) {
assert.False(t, got.IsBare)
}
func reposListWatches(t *testing.T, ctx context.Context, db *repos) {
func reposListWatches(t *testing.T, ctx context.Context, db *repositories) {
err := db.Watch(ctx, 1, 1)
require.NoError(t, err)
err = db.Watch(ctx, 2, 1)
@ -310,9 +310,8 @@ func reposListWatches(t *testing.T, ctx context.Context, db *repos) {
assert.Equal(t, want, got)
}
func reposWatch(t *testing.T, ctx context.Context, db *repos) {
reposStore := NewReposStore(db.DB)
repo1, err := reposStore.Create(ctx, 1, CreateRepoOptions{Name: "repo1"})
func reposWatch(t *testing.T, ctx context.Context, db *repositories) {
repo1, err := db.Create(ctx, 1, CreateRepoOptions{Name: "repo1"})
require.NoError(t, err)
err = db.Watch(ctx, 2, repo1.ID)
@ -322,16 +321,16 @@ func reposWatch(t *testing.T, ctx context.Context, db *repos) {
err = db.Watch(ctx, 2, repo1.ID)
require.NoError(t, err)
repo1, err = reposStore.GetByID(ctx, repo1.ID)
repo1, err = db.GetByID(ctx, repo1.ID)
require.NoError(t, err)
assert.Equal(t, 2, repo1.NumWatches) // The owner is watching the repo by default.
}
func reposHasForkedBy(t *testing.T, ctx context.Context, db *repos) {
func reposHasForkedBy(t *testing.T, ctx context.Context, db *repositories) {
has := db.HasForkedBy(ctx, 1, 2)
assert.False(t, has)
_, err := NewReposStore(db.DB).Create(
_, err := NewRepositoriesStore(db.DB).Create(
ctx,
2,
CreateRepoOptions{

View File

@ -48,8 +48,9 @@ type UsersStore interface {
Authenticate(ctx context.Context, username, password string, loginSourceID int64) (*User, error)
// Create creates a new user and persists to database. It returns
// ErrNameNotAllowed if the given name or pattern of the name is not allowed as
// a username, or ErrUserAlreadyExist when a user with same name already exists,
// or ErrEmailAlreadyUsed if the email has been verified by another user.
// a username, or ErrUserAlreadyExist when a user or an organization with same
// name already exists, or ErrEmailAlreadyUsed if the email has been verified by
// another user.
Create(ctx context.Context, username, email string, opts CreateUserOptions) (*User, error)
// GetByEmail returns the user (not organization) with given email. It ignores
@ -362,8 +363,7 @@ type ErrUserAlreadyExist struct {
// IsErrUserAlreadyExist returns true if the underlying error has the type
// ErrUserAlreadyExist.
func IsErrUserAlreadyExist(err error) bool {
_, ok := errors.Cause(err).(ErrUserAlreadyExist)
return ok
return errors.As(err, &ErrUserAlreadyExist{})
}
func (err ErrUserAlreadyExist) Error() string {
@ -377,8 +377,7 @@ type ErrEmailAlreadyUsed struct {
// IsErrEmailAlreadyUsed returns true if the underlying error has the type
// ErrEmailAlreadyUsed.
func IsErrEmailAlreadyUsed(err error) bool {
_, ok := errors.Cause(err).(ErrEmailAlreadyUsed)
return ok
return errors.As(err, &ErrEmailAlreadyUsed{})
}
func (err ErrEmailAlreadyUsed) Email() string {
@ -880,11 +879,13 @@ func (db *users) IsUsernameUsed(ctx context.Context, username string, excludeUse
if username == "" {
return false
}
return db.WithContext(ctx).
err := db.WithContext(ctx).
Select("id").
Where("lower_name = ? AND id != ?", strings.ToLower(username), excludeUserId).
First(&User{}).
Error != gorm.ErrRecordNotFound
Error
return !errors.Is(err, gorm.ErrRecordNotFound)
}
func (db *users) List(ctx context.Context, page, pageSize int) ([]*User, error) {
@ -1479,7 +1480,7 @@ func (u *User) IsFollowing(followID int64) bool {
// TODO(unknwon): This is also used in templates, which should be fixed by
// having a dedicated type `template.User`.
func (u *User) IsUserOrgOwner(orgID int64) bool {
return Orgs.IsOwnedBy(context.TODO(), orgID, u.ID)
return Organizations.IsOwnedBy(context.TODO(), orgID, u.ID)
}
// IsPublicMember returns true if the user has public membership of the given
@ -1488,7 +1489,7 @@ func (u *User) IsUserOrgOwner(orgID int64) bool {
// TODO(unknwon): This is also used in templates, which should be fixed by
// having a dedicated type `template.User`.
func (u *User) IsPublicMember(orgID int64) bool {
_, public := Orgs.HasMember(context.TODO(), orgID, u.ID)
_, public := Organizations.HasMember(context.TODO(), orgID, u.ID)
return public
}
@ -1498,7 +1499,7 @@ func (u *User) IsPublicMember(orgID int64) bool {
// TODO(unknwon): This is also used in templates, which should be fixed by
// having a dedicated type `template.User`.
func (u *User) GetOrganizationCount() (int64, error) {
return Orgs.CountByUser(context.TODO(), u.ID)
return Organizations.CountByUser(context.TODO(), u.ID)
}
// ShortName truncates and returns the username at most in given length.

View File

@ -299,7 +299,7 @@ func usersChangeUsername(t *testing.T, ctx context.Context, db *users) {
require.NoError(t, err)
defer func() { _ = os.RemoveAll(tempServerAppDataPath) }()
repo, err := NewReposStore(db.DB).Create(
repo, err := NewRepositoriesStore(db.DB).Create(
ctx,
alice.ID,
CreateRepoOptions{
@ -471,7 +471,7 @@ func usersDeleteCustomAvatar(t *testing.T, ctx context.Context, db *users) {
}
func usersDeleteByID(t *testing.T, ctx context.Context, db *users) {
reposStore := NewReposStore(db.DB)
reposStore := NewRepositoriesStore(db.DB)
t.Run("user still has repository ownership", func(t *testing.T) {
alice, err := db.Create(ctx, "alice", "alice@exmaple.com", CreateUserOptions{})
@ -684,7 +684,7 @@ func usersDeleteInactivated(t *testing.T, ctx context.Context, db *users) {
// User with repository ownership should be skipped
alice, err := db.Create(ctx, "alice", "alice@exmaple.com", CreateUserOptions{})
require.NoError(t, err)
reposStore := NewReposStore(db.DB)
reposStore := NewRepositoriesStore(db.DB)
_, err = reposStore.Create(ctx, alice.ID, CreateRepoOptions{Name: "repo1"})
require.NoError(t, err)
@ -815,7 +815,7 @@ func usersGetByUsername(t *testing.T, ctx context.Context, db *users) {
})
t.Run("wrong user type", func(t *testing.T) {
// org1,err:=NewOrgsStore(db.DB).Create(ctx,"org1","// TODO: Use Orgs.Create
// org1,err:=NewOrganizationsStore(db.DB).Create(ctx,"org1","// TODO: Use Orgs.Create
})
}

View File

@ -24,9 +24,15 @@ func Organizations(c *context.Context) {
route.RenderUserSearch(c, &route.UserSearchOptions{
Type: db.UserTypeOrganization,
Counter: db.Orgs.Count,
Ranger: func(_ gocontext.Context, page, pageSize int) ([]*db.User, error) {
return db.Organizations(page, pageSize)
Counter: db.Organizations.Count,
Ranger: func(ctx gocontext.Context, page, pageSize int) ([]*db.User, error) {
return db.Organizations.List(
ctx,
db.ListOrganizationsOptions{
Page: page,
PageSize: pageSize,
},
)
},
PageSize: conf.UI.Admin.OrgPagingNum,
OrderBy: "id ASC",

View File

@ -35,7 +35,7 @@ func Repos(c *context.Context) {
keyword := c.Query("q")
if keyword == "" {
repos, err = db.Repositories(page, conf.UI.Admin.RepoPagingNum)
repos, err = db.ListRepositories(page, conf.UI.Admin.RepoPagingNum)
if err != nil {
c.Error(err, "list repositories")
return

View File

@ -45,7 +45,7 @@ func repoAssignment() macaron.Handler {
}
c.Repo.Owner = owner
repo, err := db.Repos.GetByName(c.Req.Context(), owner.ID, reponame)
repo, err := db.Repositories.GetByName(c.Req.Context(), owner.ID, reponame)
if err != nil {
c.NotFoundOrError(err, "get repository by name")
return

View File

@ -20,17 +20,19 @@ func CreateOrgForUser(c *context.APIContext, apiForm api.CreateOrgOption, user *
return
}
org := &db.User{
Name: apiForm.UserName,
FullName: apiForm.FullName,
Description: apiForm.Description,
Website: apiForm.Website,
Location: apiForm.Location,
IsActive: true,
Type: db.UserTypeOrganization,
}
if err := db.CreateOrganization(org, user); err != nil {
if db.IsErrUserAlreadyExist(err) ||
org, err := db.Organizations.Create(
c.Req.Context(),
apiForm.UserName,
user.ID,
db.CreateOrganizationOptions{
FullName: apiForm.FullName,
Location: apiForm.Location,
Website: apiForm.Website,
Description: apiForm.Description,
},
)
if err != nil {
if db.IsErrOrganizationAlreadyExist(err) ||
db.IsErrNameNotAllowed(err) {
c.ErrorStatus(http.StatusUnprocessableEntity, err)
} else {
@ -39,13 +41,13 @@ func CreateOrgForUser(c *context.APIContext, apiForm api.CreateOrgOption, user *
return
}
c.JSON(201, convert.ToOrganization(org))
c.JSON(http.StatusCreated, convert.ToOrganization(org))
}
func listUserOrgs(c *context.APIContext, u *db.User, all bool) {
orgs, err := db.Orgs.List(
orgs, err := db.Organizations.List(
c.Req.Context(),
db.ListOrgsOptions{
db.ListOrganizationsOptions{
MemberID: u.ID,
IncludePrivateMembers: all,
},
@ -104,7 +106,7 @@ func Edit(c *context.APIContext, form api.EditOrgOption) {
return
}
org, err = db.Orgs.GetByName(c.Req.Context(), org.Name)
org, err = db.Organizations.GetByName(c.Req.Context(), org.Name)
if err != nil {
c.Error(err, "get organization")
return

View File

@ -87,7 +87,7 @@ func listUserRepositories(c *context.APIContext, username string) {
// or an organization isn't a member of.
var ownRepos []*db.Repository
if user.IsOrganization() {
ownRepos, _, err = db.Orgs.AccessibleRepositoriesByUser(
ownRepos, _, err = db.Organizations.AccessibleRepositoriesByUser(
c.Req.Context(),
user.ID,
c.User.ID,
@ -123,7 +123,7 @@ func listUserRepositories(c *context.APIContext, username string) {
return
}
accessibleRepos, err := db.Repos.GetByCollaboratorIDWithAccessMode(c.Req.Context(), user.ID)
accessibleRepos, err := db.Repositories.GetByCollaboratorIDWithAccessMode(c.Req.Context(), user.ID)
if err != nil {
c.Error(err, "get repositories accesses by collaborator")
return
@ -198,7 +198,7 @@ func Create(c *context.APIContext, opt api.CreateRepoOption) {
}
func CreateOrgRepo(c *context.APIContext, opt api.CreateRepoOption) {
org, err := db.Orgs.GetByName(c.Req.Context(), c.Params(":org"))
org, err := db.Organizations.GetByName(c.Req.Context(), c.Params(":org"))
if err != nil {
c.NotFoundOrError(err, "get organization by name")
return

View File

@ -115,7 +115,7 @@ func RenderUserSearch(c *context.Context, opts *UserSearchOptions) {
} else {
search := db.Users.SearchByName
if opts.Type == db.UserTypeOrganization {
search = db.Orgs.SearchByName
search = db.Organizations.SearchByName
}
users, count, err = search(c.Req.Context(), keyword, page, opts.PageSize, opts.OrderBy)
if err != nil {
@ -153,9 +153,15 @@ func ExploreOrganizations(c *context.Context) {
RenderUserSearch(c, &UserSearchOptions{
Type: db.UserTypeOrganization,
Counter: db.Orgs.Count,
Ranger: func(_ gocontext.Context, page, pageSize int) ([]*db.User, error) {
return db.Organizations(page, pageSize)
Counter: db.Organizations.Count,
Ranger: func(ctx gocontext.Context, page, pageSize int) ([]*db.User, error) {
return db.Organizations.List(
ctx,
db.ListOrganizationsOptions{
Page: page,
PageSize: pageSize,
},
)
},
PageSize: conf.UI.ExplorePagingNum,
OrderBy: "updated_unix DESC",

File diff suppressed because it is too large Load Diff

View File

@ -117,7 +117,7 @@ func authorize(mode db.AccessMode) macaron.Handler {
return
}
repo, err := db.Repos.GetByName(c.Req.Context(), owner.ID, reponame)
repo, err := db.Repositories.GetByName(c.Req.Context(), owner.ID, reponame)
if err != nil {
if db.IsErrRepoNotExist(err) {
c.Status(http.StatusNotFound)

View File

@ -192,7 +192,7 @@ func Test_authorize(t *testing.T) {
name string
authroize macaron.Handler
mockUsersStore func() db.UsersStore
mockReposStore func() db.ReposStore
mockReposStore func() db.RepositoriesStore
mockPermsStore func() db.PermsStore
expStatusCode int
expBody string
@ -217,8 +217,8 @@ func Test_authorize(t *testing.T) {
})
return mock
},
mockReposStore: func() db.ReposStore {
mock := NewMockReposStore()
mockReposStore: func() db.RepositoriesStore {
mock := NewMockRepositoriesStore()
mock.GetByNameFunc.SetDefaultReturn(nil, db.ErrRepoNotExist{})
return mock
},
@ -234,8 +234,8 @@ func Test_authorize(t *testing.T) {
})
return mock
},
mockReposStore: func() db.ReposStore {
mock := NewMockReposStore()
mockReposStore: func() db.RepositoriesStore {
mock := NewMockRepositoriesStore()
mock.GetByNameFunc.SetDefaultHook(func(ctx context.Context, ownerID int64, name string) (*db.Repository, error) {
return &db.Repository{Name: name}, nil
})
@ -261,8 +261,8 @@ func Test_authorize(t *testing.T) {
})
return mock
},
mockReposStore: func() db.ReposStore {
mock := NewMockReposStore()
mockReposStore: func() db.RepositoriesStore {
mock := NewMockRepositoriesStore()
mock.GetByNameFunc.SetDefaultHook(func(ctx context.Context, ownerID int64, name string) (*db.Repository, error) {
return &db.Repository{Name: name}, nil
})

View File

@ -23,7 +23,7 @@ func Members(c *context.Context) {
c.Data["Title"] = org.FullName
c.Data["PageIsOrgMembers"] = true
members, err := db.Orgs.ListMembers(c.Req.Context(), org.ID, db.ListOrgMembersOptions{})
members, err := db.Organizations.ListMembers(c.Req.Context(), org.ID, db.ListOrgMembersOptions{})
if err != nil {
c.Error(err, "list members")
return
@ -48,26 +48,26 @@ func MembersAction(c *context.Context) {
c.NotFound()
return
}
err = db.Orgs.SetMemberVisibility(c.Req.Context(), org.ID, uid, false)
err = db.Organizations.SetMemberVisibility(c.Req.Context(), org.ID, uid, false)
case "public":
if c.User.ID != uid && !c.Org.IsOwner {
c.NotFound()
return
}
err = db.Orgs.SetMemberVisibility(c.Req.Context(), org.ID, uid, true)
err = db.Organizations.SetMemberVisibility(c.Req.Context(), org.ID, uid, true)
case "remove":
if !c.Org.IsOwner {
c.NotFound()
return
}
err = db.Orgs.RemoveMember(c.Req.Context(), org.ID, uid)
err = db.Organizations.RemoveMember(c.Req.Context(), org.ID, uid)
if db.IsErrLastOrgOwner(err) {
c.Flash.Error(c.Tr("form.last_org_owner"))
c.Redirect(c.Org.OrgLink + "/members")
return
}
case "leave":
err = db.Orgs.RemoveMember(c.Req.Context(), org.ID, c.User.ID)
err = db.Organizations.RemoveMember(c.Req.Context(), org.ID, c.User.ID)
if db.IsErrLastOrgOwner(err) {
c.Flash.Error(c.Tr("form.last_org_owner"))
c.Redirect(c.Org.OrgLink + "/members")
@ -109,7 +109,7 @@ func Invitation(c *context.Context) {
return
}
if err = db.Orgs.AddMember(c.Req.Context(), org.ID, u.ID); err != nil {
if err = db.Organizations.AddMember(c.Req.Context(), org.ID, u.ID); err != nil {
c.Error(err, "add member")
return
}

View File

@ -29,16 +29,16 @@ func CreatePost(c *context.Context, f form.CreateOrg) {
return
}
org := &db.User{
Name: f.OrgName,
IsActive: true,
Type: db.UserTypeOrganization,
}
if err := db.CreateOrganization(org, c.User); err != nil {
org, err := db.Organizations.Create(
c.Req.Context(),
f.OrgName,
c.User.ID,
db.CreateOrganizationOptions{},
)
if err != nil {
c.Data["Err_OrgName"] = true
switch {
case db.IsErrUserAlreadyExist(err):
case db.IsErrOrganizationAlreadyExist(err):
c.RenderWithErr(c.Tr("form.org_name_been_taken"), CREATE, &f)
case db.IsErrNameNotAllowed(err):
c.RenderWithErr(c.Tr("org.form.name_not_allowed", err.(db.ErrNameNotAllowed).Value()), CREATE, &f)

View File

@ -77,7 +77,7 @@ func HTTPContexter() macaron.Handler {
return
}
repo, err := db.Repos.GetByName(c.Req.Context(), owner.ID, repoName)
repo, err := db.Repositories.GetByName(c.Req.Context(), owner.ID, repoName)
if err != nil {
if db.IsErrRepoNotExist(err) {
c.Status(http.StatusNotFound)

View File

@ -68,7 +68,7 @@ func MustAllowPulls(c *context.Context) {
}
// User can send pull request if owns a forked repository.
if c.IsLogged && db.Repos.HasForkedBy(c.Req.Context(), c.Repo.Repository.ID, c.User.ID) {
if c.IsLogged && db.Repositories.HasForkedBy(c.Req.Context(), c.Repo.Repository.ID, c.User.ID) {
c.Repo.PullRequest.Allowed = true
c.Repo.PullRequest.HeadInfo = c.User.Name + ":" + c.Repo.BranchName
}

View File

@ -69,9 +69,9 @@ func parseBaseRepository(c *context.Context) *db.Repository {
}
c.Data["ForkFrom"] = baseRepo.Owner.Name + "/" + baseRepo.Name
orgs, err := db.Orgs.List(
orgs, err := db.Organizations.List(
c.Req.Context(),
db.ListOrgsOptions{
db.ListOrganizationsOptions{
MemberID: c.User.ID,
IncludePrivateMembers: true,
},

View File

@ -44,7 +44,7 @@ func TriggerTask(c *macaron.Context) {
return
}
repo, err := db.Repos.GetByName(c.Req.Context(), owner.ID, reponame)
repo, err := db.Repositories.GetByName(c.Req.Context(), owner.ID, reponame)
if err != nil {
if db.IsErrRepoNotExist(err) {
c.Error(http.StatusBadRequest, "Repository does not exist")

View File

@ -40,9 +40,9 @@ func getDashboardContextUser(c *context.Context) *db.User {
}
c.Data["ContextUser"] = ctxUser
orgs, err := db.Orgs.List(
orgs, err := db.Organizations.List(
c.Req.Context(),
db.ListOrgsOptions{
db.ListOrganizationsOptions{
MemberID: c.User.ID,
IncludePrivateMembers: true,
},
@ -125,7 +125,7 @@ func Dashboard(c *context.Context) {
// Only user can have collaborative repositories.
if !ctxUser.IsOrganization() {
collaborateRepos, err := db.Repos.GetByCollaboratorID(c.Req.Context(), c.User.ID, conf.UI.User.RepoPagingNum, "updated_unix DESC")
collaborateRepos, err := db.Repositories.GetByCollaboratorID(c.Req.Context(), c.User.ID, conf.UI.User.RepoPagingNum, "updated_unix DESC")
if err != nil {
c.Error(err, "get accessible repositories by collaborator")
return
@ -140,7 +140,7 @@ func Dashboard(c *context.Context) {
var repos, mirrors []*db.Repository
var repoCount int64
if ctxUser.IsOrganization() {
repos, repoCount, err = db.Orgs.AccessibleRepositoriesByUser(
repos, repoCount, err = db.Organizations.AccessibleRepositoriesByUser(
c.Req.Context(),
ctxUser.ID,
c.User.ID,
@ -243,7 +243,7 @@ func Issues(c *context.Context) {
showRepos = make([]*db.Repository, 0, 10)
)
if ctxUser.IsOrganization() {
repos, _, err = db.Orgs.AccessibleRepositoriesByUser(
repos, _, err = db.Organizations.AccessibleRepositoriesByUser(
c.Req.Context(),
ctxUser.ID,
c.User.ID,
@ -423,7 +423,7 @@ func showOrgProfile(c *context.Context) {
err error
)
if c.IsLogged && !c.User.IsAdmin {
repos, count, err = db.Orgs.AccessibleRepositoriesByUser(
repos, count, err = db.Organizations.AccessibleRepositoriesByUser(
c.Req.Context(),
org.ID,
c.User.ID,
@ -453,7 +453,7 @@ func showOrgProfile(c *context.Context) {
}
c.Data["Page"] = paginater.New(int(count), conf.UI.User.RepoPagingNum, page, 5)
members, err := db.Orgs.ListMembers(c.Req.Context(), org.ID, db.ListOrgMembersOptions{Limit: 12})
members, err := db.Organizations.ListMembers(c.Req.Context(), org.ID, db.ListOrgMembersOptions{Limit: 12})
if err != nil {
c.Error(err, "list members")
return

View File

@ -566,7 +566,7 @@ func SettingsOrganizations(c *context.Context) {
}
func SettingsLeaveOrganization(c *context.Context) {
if err := db.Orgs.RemoveMember(c.Req.Context(), c.QueryInt64("id"), c.User.ID); err != nil {
if err := db.Organizations.RemoveMember(c.Req.Context(), c.QueryInt64("id"), c.User.ID); err != nil {
if db.IsErrLastOrgOwner(err) {
c.Flash.Error(c.Tr("form.last_org_owner"))
} else {

View File

@ -40,5 +40,5 @@ mocks:
- UsersStore
- TwoFactorsStore
- AccessTokensStore
- ReposStore
- RepositoriesStore
- PermsStore