2021-12-12 18:48:20 +03:00
// Copyright 2017 The Gitea Authors. All rights reserved.
2022-11-27 21:20:29 +03:00
// SPDX-License-Identifier: MIT
2021-12-12 18:48:20 +03:00
package repo
import (
"context"
"fmt"
"strings"
"code.gitea.io/gitea/models/db"
2022-10-18 08:50:37 +03:00
"code.gitea.io/gitea/modules/util"
2021-12-12 18:48:20 +03:00
)
// ErrRedirectNotExist represents a "RedirectNotExist" kind of error.
type ErrRedirectNotExist struct {
OwnerID int64
RepoName string
}
// IsErrRedirectNotExist check if an error is an ErrRepoRedirectNotExist.
func IsErrRedirectNotExist ( err error ) bool {
_ , ok := err . ( ErrRedirectNotExist )
return ok
}
func ( err ErrRedirectNotExist ) Error ( ) string {
return fmt . Sprintf ( "repository redirect does not exist [uid: %d, name: %s]" , err . OwnerID , err . RepoName )
}
2022-10-18 08:50:37 +03:00
func ( err ErrRedirectNotExist ) Unwrap ( ) error {
return util . ErrNotExist
}
2021-12-12 18:48:20 +03:00
// Redirect represents that a repo name should be redirected to another
type Redirect struct {
ID int64 ` xorm:"pk autoincr" `
OwnerID int64 ` xorm:"UNIQUE(s)" `
LowerName string ` xorm:"UNIQUE(s) INDEX NOT NULL" `
RedirectRepoID int64 // repoID to redirect to
}
// TableName represents real table name in database
func ( Redirect ) TableName ( ) string {
return "repo_redirect"
}
func init ( ) {
db . RegisterModel ( new ( Redirect ) )
}
// LookupRedirect look up if a repository has a redirect name
2023-10-14 11:37:24 +03:00
func LookupRedirect ( ctx context . Context , ownerID int64 , repoName string ) ( int64 , error ) {
2021-12-12 18:48:20 +03:00
repoName = strings . ToLower ( repoName )
redirect := & Redirect { OwnerID : ownerID , LowerName : repoName }
2023-10-14 11:37:24 +03:00
if has , err := db . GetEngine ( ctx ) . Get ( redirect ) ; err != nil {
2021-12-12 18:48:20 +03:00
return 0 , err
} else if ! has {
return 0 , ErrRedirectNotExist { OwnerID : ownerID , RepoName : repoName }
}
return redirect . RedirectRepoID , nil
}
// NewRedirect create a new repo redirect
func NewRedirect ( ctx context . Context , ownerID , repoID int64 , oldRepoName , newRepoName string ) error {
oldRepoName = strings . ToLower ( oldRepoName )
newRepoName = strings . ToLower ( newRepoName )
if err := DeleteRedirect ( ctx , ownerID , newRepoName ) ; err != nil {
return err
}
return db . Insert ( ctx , & Redirect {
OwnerID : ownerID ,
LowerName : oldRepoName ,
RedirectRepoID : repoID ,
} )
}
// DeleteRedirect delete any redirect from the specified repo name to
// anything else
func DeleteRedirect ( ctx context . Context , ownerID int64 , repoName string ) error {
repoName = strings . ToLower ( repoName )
_ , err := db . GetEngine ( ctx ) . Delete ( & Redirect { OwnerID : ownerID , LowerName : repoName } )
return err
}