chore: rename internal/db to internal/database (#7665)

This commit is contained in:
Joe Chen 2024-02-18 19:39:41 -05:00 committed by GitHub
parent cad79a31d8
commit 3650b32ec5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
159 changed files with 1612 additions and 1612 deletions

View File

@ -162,7 +162,7 @@ jobs:
with: with:
go-version: ${{ matrix.go-version }} go-version: ${{ matrix.go-version }}
- name: Run tests with coverage - name: Run tests with coverage
run: go test -shuffle=on -v -race -coverprofile=coverage -covermode=atomic ./internal/db/... run: go test -shuffle=on -v -race -coverprofile=coverage -covermode=atomic ./internal/database/...
env: env:
GOGS_DATABASE_TYPE: postgres GOGS_DATABASE_TYPE: postgres
PGPORT: 5432 PGPORT: 5432
@ -188,7 +188,7 @@ jobs:
with: with:
go-version: ${{ matrix.go-version }} go-version: ${{ matrix.go-version }}
- name: Run tests with coverage - name: Run tests with coverage
run: go test -shuffle=on -v -race -coverprofile=coverage -covermode=atomic ./internal/db/... run: go test -shuffle=on -v -race -coverprofile=coverage -covermode=atomic ./internal/database/...
env: env:
GOGS_DATABASE_TYPE: mysql GOGS_DATABASE_TYPE: mysql
MYSQL_USER: root MYSQL_USER: root
@ -211,6 +211,6 @@ jobs:
with: with:
go-version: ${{ matrix.go-version }} go-version: ${{ matrix.go-version }}
- name: Run tests with coverage - name: Run tests with coverage
run: go test -shuffle=on -v -race -parallel=1 -coverprofile=coverage -covermode=atomic ./internal/db/... run: go test -shuffle=on -v -race -parallel=1 -coverprofile=coverage -covermode=atomic ./internal/database/...
env: env:
GOGS_DATABASE_TYPE: sqlite GOGS_DATABASE_TYPE: sqlite

View File

@ -42,7 +42,7 @@ tasks:
generate-schemadoc: generate-schemadoc:
desc: Generate database schema documentation desc: Generate database schema documentation
cmds: cmds:
- go generate ./internal/db/schemadoc - go generate ./internal/database/schemadoc
generate: generate:
desc: Run all go:generate commands desc: Run all go:generate commands

2
gen.go
View File

@ -4,5 +4,5 @@
package main package main
//go:generate go install golang.org/x/tools/cmd/goimports@v0.1.10 //go:generate go install golang.org/x/tools/cmd/goimports@v0.17.0
//go:generate go run github.com/derision-test/go-mockgen/cmd/go-mockgen@v1.3.7 //go:generate go run github.com/derision-test/go-mockgen/cmd/go-mockgen@v1.3.7

View File

@ -14,7 +14,7 @@ import (
"github.com/urfave/cli" "github.com/urfave/cli"
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/db" "gogs.io/gogs/internal/database"
) )
var ( var (
@ -52,7 +52,7 @@ to make automatic initialization process more smoothly`,
Name: "delete-inactive-users", Name: "delete-inactive-users",
Usage: "Delete all inactive accounts", Usage: "Delete all inactive accounts",
Action: adminDashboardOperation( Action: adminDashboardOperation(
func() error { return db.Users.DeleteInactivated() }, func() error { return database.Users.DeleteInactivated() },
"All inactivated accounts have been deleted successfully", "All inactivated accounts have been deleted successfully",
), ),
Flags: []cli.Flag{ Flags: []cli.Flag{
@ -64,7 +64,7 @@ to make automatic initialization process more smoothly`,
Name: "delete-repository-archives", Name: "delete-repository-archives",
Usage: "Delete all repositories archives", Usage: "Delete all repositories archives",
Action: adminDashboardOperation( Action: adminDashboardOperation(
db.DeleteRepositoryArchives, database.DeleteRepositoryArchives,
"All repositories archives have been deleted successfully", "All repositories archives have been deleted successfully",
), ),
Flags: []cli.Flag{ Flags: []cli.Flag{
@ -76,7 +76,7 @@ to make automatic initialization process more smoothly`,
Name: "delete-missing-repositories", Name: "delete-missing-repositories",
Usage: "Delete all repository records that lost Git files", Usage: "Delete all repository records that lost Git files",
Action: adminDashboardOperation( Action: adminDashboardOperation(
db.DeleteMissingRepositories, database.DeleteMissingRepositories,
"All repositories archives have been deleted successfully", "All repositories archives have been deleted successfully",
), ),
Flags: []cli.Flag{ Flags: []cli.Flag{
@ -88,7 +88,7 @@ to make automatic initialization process more smoothly`,
Name: "collect-garbage", Name: "collect-garbage",
Usage: "Do garbage collection on repositories", Usage: "Do garbage collection on repositories",
Action: adminDashboardOperation( Action: adminDashboardOperation(
db.GitGcRepos, database.GitGcRepos,
"All repositories have done garbage collection successfully", "All repositories have done garbage collection successfully",
), ),
Flags: []cli.Flag{ Flags: []cli.Flag{
@ -100,7 +100,7 @@ to make automatic initialization process more smoothly`,
Name: "rewrite-authorized-keys", Name: "rewrite-authorized-keys",
Usage: "Rewrite '.ssh/authorized_keys' file (caution: non-Gogs keys will be lost)", Usage: "Rewrite '.ssh/authorized_keys' file (caution: non-Gogs keys will be lost)",
Action: adminDashboardOperation( Action: adminDashboardOperation(
db.RewriteAuthorizedKeys, database.RewriteAuthorizedKeys,
"All public keys have been rewritten successfully", "All public keys have been rewritten successfully",
), ),
Flags: []cli.Flag{ Flags: []cli.Flag{
@ -112,7 +112,7 @@ to make automatic initialization process more smoothly`,
Name: "resync-hooks", Name: "resync-hooks",
Usage: "Resync pre-receive, update and post-receive hooks", Usage: "Resync pre-receive, update and post-receive hooks",
Action: adminDashboardOperation( Action: adminDashboardOperation(
db.SyncRepositoryHooks, database.SyncRepositoryHooks,
"All repositories' pre-receive, update and post-receive hooks have been resynced successfully", "All repositories' pre-receive, update and post-receive hooks have been resynced successfully",
), ),
Flags: []cli.Flag{ Flags: []cli.Flag{
@ -124,7 +124,7 @@ to make automatic initialization process more smoothly`,
Name: "reinit-missing-repositories", Name: "reinit-missing-repositories",
Usage: "Reinitialize all repository records that lost Git files", Usage: "Reinitialize all repository records that lost Git files",
Action: adminDashboardOperation( Action: adminDashboardOperation(
db.ReinitMissingRepositories, database.ReinitMissingRepositories,
"All repository records that lost Git files have been reinitialized successfully", "All repository records that lost Git files have been reinitialized successfully",
), ),
Flags: []cli.Flag{ Flags: []cli.Flag{
@ -148,15 +148,15 @@ func runCreateUser(c *cli.Context) error {
} }
conf.InitLogging(true) conf.InitLogging(true)
if _, err = db.SetEngine(); err != nil { if _, err = database.SetEngine(); err != nil {
return errors.Wrap(err, "set engine") return errors.Wrap(err, "set engine")
} }
user, err := db.Users.Create( user, err := database.Users.Create(
context.Background(), context.Background(),
c.String("name"), c.String("name"),
c.String("email"), c.String("email"),
db.CreateUserOptions{ database.CreateUserOptions{
Password: c.String("password"), Password: c.String("password"),
Activated: true, Activated: true,
Admin: c.Bool("admin"), Admin: c.Bool("admin"),
@ -178,7 +178,7 @@ func adminDashboardOperation(operation func() error, successMessage string) func
} }
conf.InitLogging(true) conf.InitLogging(true)
if _, err = db.SetEngine(); err != nil { if _, err = database.SetEngine(); err != nil {
return errors.Wrap(err, "set engine") return errors.Wrap(err, "set engine")
} }

View File

@ -20,7 +20,7 @@ import (
log "unknwon.dev/clog/v2" log "unknwon.dev/clog/v2"
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/db" "gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/osutil" "gogs.io/gogs/internal/osutil"
) )
@ -57,7 +57,7 @@ func runBackup(c *cli.Context) error {
} }
conf.InitLogging(true) conf.InitLogging(true)
conn, err := db.SetEngine() conn, err := database.SetEngine()
if err != nil { if err != nil {
return errors.Wrap(err, "set engine") return errors.Wrap(err, "set engine")
} }
@ -95,7 +95,7 @@ func runBackup(c *cli.Context) error {
// Database // Database
dbDir := filepath.Join(rootDir, "db") dbDir := filepath.Join(rootDir, "db")
if err = db.DumpDatabase(context.Background(), conn, dbDir, c.Bool("verbose")); err != nil { if err = database.DumpDatabase(context.Background(), conn, dbDir, c.Bool("verbose")); err != nil {
log.Fatal("Failed to dump database: %v", err) log.Fatal("Failed to dump database: %v", err)
} }
if err = z.AddDir(archiveRootDir+"/db", dbDir); err != nil { if err = z.AddDir(archiveRootDir+"/db", dbDir); err != nil {
@ -127,7 +127,7 @@ func runBackup(c *cli.Context) error {
reposDump := filepath.Join(rootDir, "repositories.zip") reposDump := filepath.Join(rootDir, "repositories.zip")
log.Info("Dumping repositories in %q", conf.Repository.Root) log.Info("Dumping repositories in %q", conf.Repository.Root)
if c.Bool("exclude-mirror-repos") { if c.Bool("exclude-mirror-repos") {
repos, err := db.GetNonMirrorRepositories() repos, err := database.GetNonMirrorRepositories()
if err != nil { if err != nil {
log.Fatal("Failed to get non-mirror repositories: %v", err) log.Fatal("Failed to get non-mirror repositories: %v", err)
} }

View File

@ -22,7 +22,7 @@ import (
"github.com/gogs/git-module" "github.com/gogs/git-module"
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/db" "gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/email" "gogs.io/gogs/internal/email"
"gogs.io/gogs/internal/httplib" "gogs.io/gogs/internal/httplib"
) )
@ -68,7 +68,7 @@ func runHookPreReceive(c *cli.Context) error {
} }
setup(c, "pre-receive.log", true) setup(c, "pre-receive.log", true)
isWiki := strings.Contains(os.Getenv(db.ENV_REPO_CUSTOM_HOOKS_PATH), ".wiki.git/") isWiki := strings.Contains(os.Getenv(database.ENV_REPO_CUSTOM_HOOKS_PATH), ".wiki.git/")
buf := bytes.NewBuffer(nil) buf := bytes.NewBuffer(nil)
scanner := bufio.NewScanner(os.Stdin) scanner := bufio.NewScanner(os.Stdin)
@ -89,10 +89,10 @@ func runHookPreReceive(c *cli.Context) error {
branchName := git.RefShortName(string(fields[2])) branchName := git.RefShortName(string(fields[2]))
// Branch protection // Branch protection
repoID := com.StrTo(os.Getenv(db.ENV_REPO_ID)).MustInt64() repoID := com.StrTo(os.Getenv(database.ENV_REPO_ID)).MustInt64()
protectBranch, err := db.GetProtectBranchOfRepoByName(repoID, branchName) protectBranch, err := database.GetProtectBranchOfRepoByName(repoID, branchName)
if err != nil { if err != nil {
if db.IsErrBranchNotExist(err) { if database.IsErrBranchNotExist(err) {
continue continue
} }
fail("Internal error", "GetProtectBranchOfRepoByName [repo_id: %d, branch: %s]: %v", repoID, branchName, err) fail("Internal error", "GetProtectBranchOfRepoByName [repo_id: %d, branch: %s]: %v", repoID, branchName, err)
@ -105,9 +105,9 @@ func runHookPreReceive(c *cli.Context) error {
bypassRequirePullRequest := false bypassRequirePullRequest := false
// Check if user is in whitelist when enabled // Check if user is in whitelist when enabled
userID := com.StrTo(os.Getenv(db.ENV_AUTH_USER_ID)).MustInt64() userID := com.StrTo(os.Getenv(database.ENV_AUTH_USER_ID)).MustInt64()
if protectBranch.EnableWhitelist { if protectBranch.EnableWhitelist {
if !db.IsUserInProtectBranchWhitelist(repoID, userID, branchName) { if !database.IsUserInProtectBranchWhitelist(repoID, userID, branchName) {
fail(fmt.Sprintf("Branch '%s' is protected and you are not in the push whitelist", branchName), "") fail(fmt.Sprintf("Branch '%s' is protected and you are not in the push whitelist", branchName), "")
} }
@ -126,7 +126,7 @@ func runHookPreReceive(c *cli.Context) error {
// Check force push // Check force push
output, err := git.NewCommand("rev-list", "--max-count=1", oldCommitID, "^"+newCommitID). output, err := git.NewCommand("rev-list", "--max-count=1", oldCommitID, "^"+newCommitID).
RunInDir(db.RepoPath(os.Getenv(db.ENV_REPO_OWNER_NAME), os.Getenv(db.ENV_REPO_NAME))) RunInDir(database.RepoPath(os.Getenv(database.ENV_REPO_OWNER_NAME), os.Getenv(database.ENV_REPO_NAME)))
if err != nil { if err != nil {
fail("Internal error", "Failed to detect force push: %v", err) fail("Internal error", "Failed to detect force push: %v", err)
} else if len(output) > 0 { } else if len(output) > 0 {
@ -134,7 +134,7 @@ func runHookPreReceive(c *cli.Context) error {
} }
} }
customHooksPath := filepath.Join(os.Getenv(db.ENV_REPO_CUSTOM_HOOKS_PATH), "pre-receive") customHooksPath := filepath.Join(os.Getenv(database.ENV_REPO_CUSTOM_HOOKS_PATH), "pre-receive")
if !com.IsFile(customHooksPath) { if !com.IsFile(customHooksPath) {
return nil return nil
} }
@ -145,7 +145,7 @@ func runHookPreReceive(c *cli.Context) error {
} else { } else {
hookCmd = exec.Command(customHooksPath) hookCmd = exec.Command(customHooksPath)
} }
hookCmd.Dir = db.RepoPath(os.Getenv(db.ENV_REPO_OWNER_NAME), os.Getenv(db.ENV_REPO_NAME)) hookCmd.Dir = database.RepoPath(os.Getenv(database.ENV_REPO_OWNER_NAME), os.Getenv(database.ENV_REPO_NAME))
hookCmd.Stdout = os.Stdout hookCmd.Stdout = os.Stdout
hookCmd.Stdin = buf hookCmd.Stdin = buf
hookCmd.Stderr = os.Stderr hookCmd.Stderr = os.Stderr
@ -168,7 +168,7 @@ func runHookUpdate(c *cli.Context) error {
fail("First argument 'refName' is empty", "First argument 'refName' is empty") fail("First argument 'refName' is empty", "First argument 'refName' is empty")
} }
customHooksPath := filepath.Join(os.Getenv(db.ENV_REPO_CUSTOM_HOOKS_PATH), "update") customHooksPath := filepath.Join(os.Getenv(database.ENV_REPO_CUSTOM_HOOKS_PATH), "update")
if !com.IsFile(customHooksPath) { if !com.IsFile(customHooksPath) {
return nil return nil
} }
@ -179,7 +179,7 @@ func runHookUpdate(c *cli.Context) error {
} else { } else {
hookCmd = exec.Command(customHooksPath, args...) hookCmd = exec.Command(customHooksPath, args...)
} }
hookCmd.Dir = db.RepoPath(os.Getenv(db.ENV_REPO_OWNER_NAME), os.Getenv(db.ENV_REPO_NAME)) hookCmd.Dir = database.RepoPath(os.Getenv(database.ENV_REPO_OWNER_NAME), os.Getenv(database.ENV_REPO_NAME))
hookCmd.Stdout = os.Stdout hookCmd.Stdout = os.Stdout
hookCmd.Stdin = os.Stdin hookCmd.Stdin = os.Stdin
hookCmd.Stderr = os.Stderr hookCmd.Stderr = os.Stderr
@ -199,7 +199,7 @@ func runHookPostReceive(c *cli.Context) error {
// so we need to setup additional services for email notifications. // so we need to setup additional services for email notifications.
email.NewContext() email.NewContext()
isWiki := strings.Contains(os.Getenv(db.ENV_REPO_CUSTOM_HOOKS_PATH), ".wiki.git/") isWiki := strings.Contains(os.Getenv(database.ENV_REPO_CUSTOM_HOOKS_PATH), ".wiki.git/")
buf := bytes.NewBuffer(nil) buf := bytes.NewBuffer(nil)
scanner := bufio.NewScanner(os.Stdin) scanner := bufio.NewScanner(os.Stdin)
@ -217,24 +217,24 @@ func runHookPostReceive(c *cli.Context) error {
continue continue
} }
options := db.PushUpdateOptions{ options := database.PushUpdateOptions{
OldCommitID: string(fields[0]), OldCommitID: string(fields[0]),
NewCommitID: string(fields[1]), NewCommitID: string(fields[1]),
FullRefspec: string(fields[2]), FullRefspec: string(fields[2]),
PusherID: com.StrTo(os.Getenv(db.ENV_AUTH_USER_ID)).MustInt64(), PusherID: com.StrTo(os.Getenv(database.ENV_AUTH_USER_ID)).MustInt64(),
PusherName: os.Getenv(db.ENV_AUTH_USER_NAME), PusherName: os.Getenv(database.ENV_AUTH_USER_NAME),
RepoUserName: os.Getenv(db.ENV_REPO_OWNER_NAME), RepoUserName: os.Getenv(database.ENV_REPO_OWNER_NAME),
RepoName: os.Getenv(db.ENV_REPO_NAME), RepoName: os.Getenv(database.ENV_REPO_NAME),
} }
if err := db.PushUpdate(options); err != nil { if err := database.PushUpdate(options); err != nil {
log.Error("PushUpdate: %v", err) log.Error("PushUpdate: %v", err)
} }
// Ask for running deliver hook and test pull request tasks // Ask for running deliver hook and test pull request tasks
q := make(url.Values) q := make(url.Values)
q.Add("branch", git.RefShortName(options.FullRefspec)) q.Add("branch", git.RefShortName(options.FullRefspec))
q.Add("secret", os.Getenv(db.ENV_REPO_OWNER_SALT_MD5)) q.Add("secret", os.Getenv(database.ENV_REPO_OWNER_SALT_MD5))
q.Add("pusher", os.Getenv(db.ENV_AUTH_USER_ID)) q.Add("pusher", os.Getenv(database.ENV_AUTH_USER_ID))
reqURL := fmt.Sprintf("%s%s/%s/tasks/trigger?%s", conf.Server.LocalRootURL, options.RepoUserName, options.RepoName, q.Encode()) reqURL := fmt.Sprintf("%s%s/%s/tasks/trigger?%s", conf.Server.LocalRootURL, options.RepoUserName, options.RepoName, q.Encode())
log.Trace("Trigger task: %s", reqURL) log.Trace("Trigger task: %s", reqURL)
@ -252,7 +252,7 @@ func runHookPostReceive(c *cli.Context) error {
} }
} }
customHooksPath := filepath.Join(os.Getenv(db.ENV_REPO_CUSTOM_HOOKS_PATH), "post-receive") customHooksPath := filepath.Join(os.Getenv(database.ENV_REPO_CUSTOM_HOOKS_PATH), "post-receive")
if !com.IsFile(customHooksPath) { if !com.IsFile(customHooksPath) {
return nil return nil
} }
@ -263,7 +263,7 @@ func runHookPostReceive(c *cli.Context) error {
} else { } else {
hookCmd = exec.Command(customHooksPath) hookCmd = exec.Command(customHooksPath)
} }
hookCmd.Dir = db.RepoPath(os.Getenv(db.ENV_REPO_OWNER_NAME), os.Getenv(db.ENV_REPO_NAME)) hookCmd.Dir = database.RepoPath(os.Getenv(database.ENV_REPO_OWNER_NAME), os.Getenv(database.ENV_REPO_NAME))
hookCmd.Stdout = os.Stdout hookCmd.Stdout = os.Stdout
hookCmd.Stdin = buf hookCmd.Stdin = buf
hookCmd.Stderr = os.Stderr hookCmd.Stderr = os.Stderr

View File

@ -17,7 +17,7 @@ import (
log "unknwon.dev/clog/v2" log "unknwon.dev/clog/v2"
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/db" "gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/osutil" "gogs.io/gogs/internal/osutil"
"gogs.io/gogs/internal/semverutil" "gogs.io/gogs/internal/semverutil"
) )
@ -108,14 +108,14 @@ func runRestore(c *cli.Context) error {
} }
conf.InitLogging(true) conf.InitLogging(true)
conn, err := db.SetEngine() conn, err := database.SetEngine()
if err != nil { if err != nil {
return errors.Wrap(err, "set engine") return errors.Wrap(err, "set engine")
} }
// Database // Database
dbDir := path.Join(archivePath, "db") dbDir := path.Join(archivePath, "db")
if err = db.ImportDatabase(context.Background(), conn, dbDir, c.Bool("verbose")); err != nil { if err = database.ImportDatabase(context.Background(), conn, dbDir, c.Bool("verbose")); err != nil {
log.Fatal("Failed to import database: %v", err) log.Fatal("Failed to import database: %v", err)
} }

View File

@ -18,7 +18,7 @@ import (
log "unknwon.dev/clog/v2" log "unknwon.dev/clog/v2"
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/db" "gogs.io/gogs/internal/database"
) )
const ( const (
@ -95,7 +95,7 @@ func setup(c *cli.Context, logFile string, connectDB bool) {
_ = os.Chdir(conf.WorkDir()) _ = os.Chdir(conf.WorkDir())
} }
if _, err := db.SetEngine(); err != nil { if _, err := database.SetEngine(); err != nil {
fail("Internal error", "Failed to set database engine: %v", err) fail("Internal error", "Failed to set database engine: %v", err)
} }
} }
@ -108,28 +108,28 @@ func parseSSHCmd(cmd string) (string, string) {
return ss[0], strings.Replace(ss[1], "'/", "'", 1) return ss[0], strings.Replace(ss[1], "'/", "'", 1)
} }
func checkDeployKey(key *db.PublicKey, repo *db.Repository) { func checkDeployKey(key *database.PublicKey, repo *database.Repository) {
// Check if this deploy key belongs to current repository. // Check if this deploy key belongs to current repository.
if !db.HasDeployKey(key.ID, repo.ID) { if !database.HasDeployKey(key.ID, repo.ID) {
fail("Key access denied", "Deploy key access denied: [key_id: %d, repo_id: %d]", key.ID, repo.ID) fail("Key access denied", "Deploy key access denied: [key_id: %d, repo_id: %d]", key.ID, repo.ID)
} }
// Update deploy key activity. // Update deploy key activity.
deployKey, err := db.GetDeployKeyByRepo(key.ID, repo.ID) deployKey, err := database.GetDeployKeyByRepo(key.ID, repo.ID)
if err != nil { if err != nil {
fail("Internal error", "GetDeployKey: %v", err) fail("Internal error", "GetDeployKey: %v", err)
} }
deployKey.Updated = time.Now() deployKey.Updated = time.Now()
if err = db.UpdateDeployKey(deployKey); err != nil { if err = database.UpdateDeployKey(deployKey); err != nil {
fail("Internal error", "UpdateDeployKey: %v", err) fail("Internal error", "UpdateDeployKey: %v", err)
} }
} }
var allowedCommands = map[string]db.AccessMode{ var allowedCommands = map[string]database.AccessMode{
"git-upload-pack": db.AccessModeRead, "git-upload-pack": database.AccessModeRead,
"git-upload-archive": db.AccessModeRead, "git-upload-archive": database.AccessModeRead,
"git-receive-pack": db.AccessModeWrite, "git-receive-pack": database.AccessModeWrite,
} }
func runServ(c *cli.Context) error { func runServ(c *cli.Context) error {
@ -162,17 +162,17 @@ func runServ(c *cli.Context) error {
repoName := strings.TrimSuffix(strings.ToLower(repoFields[1]), ".git") repoName := strings.TrimSuffix(strings.ToLower(repoFields[1]), ".git")
repoName = strings.TrimSuffix(repoName, ".wiki") repoName = strings.TrimSuffix(repoName, ".wiki")
owner, err := db.Users.GetByUsername(ctx, ownerName) owner, err := database.Users.GetByUsername(ctx, ownerName)
if err != nil { if err != nil {
if db.IsErrUserNotExist(err) { if database.IsErrUserNotExist(err) {
fail("Repository owner does not exist", "Unregistered owner: %s", ownerName) fail("Repository owner does not exist", "Unregistered owner: %s", ownerName)
} }
fail("Internal error", "Failed to get repository owner '%s': %v", ownerName, err) fail("Internal error", "Failed to get repository owner '%s': %v", ownerName, err)
} }
repo, err := db.GetRepositoryByName(owner.ID, repoName) repo, err := database.GetRepositoryByName(owner.ID, repoName)
if err != nil { if err != nil {
if db.IsErrRepoNotExist(err) { if database.IsErrRepoNotExist(err) {
fail(_ACCESS_DENIED_MESSAGE, "Repository does not exist: %s/%s", owner.Name, repoName) fail(_ACCESS_DENIED_MESSAGE, "Repository does not exist: %s/%s", owner.Name, repoName)
} }
fail("Internal error", "Failed to get repository: %v", err) fail("Internal error", "Failed to get repository: %v", err)
@ -185,19 +185,19 @@ func runServ(c *cli.Context) error {
} }
// Prohibit push to mirror repositories. // Prohibit push to mirror repositories.
if requestMode > db.AccessModeRead && repo.IsMirror { if requestMode > database.AccessModeRead && repo.IsMirror {
fail("Mirror repository is read-only", "") fail("Mirror repository is read-only", "")
} }
// Allow anonymous (user is nil) clone for public repositories. // Allow anonymous (user is nil) clone for public repositories.
var user *db.User var user *database.User
key, err := db.GetPublicKeyByID(com.StrTo(strings.TrimPrefix(c.Args()[0], "key-")).MustInt64()) key, err := database.GetPublicKeyByID(com.StrTo(strings.TrimPrefix(c.Args()[0], "key-")).MustInt64())
if err != nil { if err != nil {
fail("Invalid key ID", "Invalid key ID '%s': %v", c.Args()[0], err) fail("Invalid key ID", "Invalid key ID '%s': %v", c.Args()[0], err)
} }
if requestMode == db.AccessModeWrite || repo.IsPrivate { if requestMode == database.AccessModeWrite || repo.IsPrivate {
// Check deploy key or user key. // Check deploy key or user key.
if key.IsDeployKey() { if key.IsDeployKey() {
if key.Mode < requestMode { if key.Mode < requestMode {
@ -205,20 +205,20 @@ func runServ(c *cli.Context) error {
} }
checkDeployKey(key, repo) checkDeployKey(key, repo)
} else { } else {
user, err = db.Users.GetByKeyID(ctx, key.ID) user, err = database.Users.GetByKeyID(ctx, key.ID)
if err != nil { if err != nil {
fail("Internal error", "Failed to get user by key ID '%d': %v", key.ID, err) fail("Internal error", "Failed to get user by key ID '%d': %v", key.ID, err)
} }
mode := db.Perms.AccessMode(ctx, user.ID, repo.ID, mode := database.Perms.AccessMode(ctx, user.ID, repo.ID,
db.AccessModeOptions{ database.AccessModeOptions{
OwnerID: repo.OwnerID, OwnerID: repo.OwnerID,
Private: repo.IsPrivate, Private: repo.IsPrivate,
}, },
) )
if mode < requestMode { if mode < requestMode {
clientMessage := _ACCESS_DENIED_MESSAGE clientMessage := _ACCESS_DENIED_MESSAGE
if mode >= db.AccessModeRead { if mode >= database.AccessModeRead {
clientMessage = "You do not have sufficient authorization for this action" clientMessage = "You do not have sufficient authorization for this action"
} }
fail(clientMessage, fail(clientMessage,
@ -238,13 +238,13 @@ func runServ(c *cli.Context) error {
// Update user key activity. // Update user key activity.
if key.ID > 0 { if key.ID > 0 {
key, err := db.GetPublicKeyByID(key.ID) key, err := database.GetPublicKeyByID(key.ID)
if err != nil { if err != nil {
fail("Internal error", "GetPublicKeyByID: %v", err) fail("Internal error", "GetPublicKeyByID: %v", err)
} }
key.Updated = time.Now() key.Updated = time.Now()
if err = db.UpdatePublicKey(key); err != nil { if err = database.UpdatePublicKey(key); err != nil {
fail("Internal error", "UpdatePublicKey: %v", err) fail("Internal error", "UpdatePublicKey: %v", err)
} }
} }
@ -261,8 +261,8 @@ func runServ(c *cli.Context) error {
} else { } else {
gitCmd = exec.Command(verb, repoFullName) gitCmd = exec.Command(verb, repoFullName)
} }
if requestMode == db.AccessModeWrite { if requestMode == database.AccessModeWrite {
gitCmd.Env = append(os.Environ(), db.ComposeHookEnvs(db.ComposeHookEnvsOptions{ gitCmd.Env = append(os.Environ(), database.ComposeHookEnvs(database.ComposeHookEnvsOptions{
AuthUser: user, AuthUser: user,
OwnerName: owner.Name, OwnerName: owner.Name,
OwnerSalt: owner.Salt, OwnerSalt: owner.Salt,

View File

@ -33,7 +33,7 @@ import (
"gogs.io/gogs/internal/app" "gogs.io/gogs/internal/app"
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/context" "gogs.io/gogs/internal/context"
"gogs.io/gogs/internal/db" "gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/form" "gogs.io/gogs/internal/form"
"gogs.io/gogs/internal/osutil" "gogs.io/gogs/internal/osutil"
"gogs.io/gogs/internal/route" "gogs.io/gogs/internal/route"
@ -107,7 +107,7 @@ func newMacaron() *macaron.Macaron {
conf.Picture.RepositoryAvatarUploadPath, conf.Picture.RepositoryAvatarUploadPath,
macaron.StaticOptions{ macaron.StaticOptions{
ETag: true, ETag: true,
Prefix: db.REPO_AVATAR_URL_PREFIX, Prefix: database.REPO_AVATAR_URL_PREFIX,
SkipLogging: conf.Server.DisableRouterLog, SkipLogging: conf.Server.DisableRouterLog,
}, },
)) ))
@ -155,7 +155,7 @@ func newMacaron() *macaron.Macaron {
HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{ HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{
{ {
Desc: "Database connection", Desc: "Database connection",
Func: db.Ping, Func: database.Ping,
}, },
}, },
})) }))
@ -305,7 +305,7 @@ func runWeb(c *cli.Context) error {
}, context.InjectParamsUser()) }, context.InjectParamsUser())
m.Get("/attachments/:uuid", func(c *context.Context) { m.Get("/attachments/:uuid", func(c *context.Context) {
attach, err := db.GetAttachmentByUUID(c.Params(":uuid")) attach, err := database.GetAttachmentByUUID(c.Params(":uuid"))
if err != nil { if err != nil {
c.NotFoundOrError(err, "get attachment by UUID") c.NotFoundOrError(err, "get attachment by UUID")
return return

View File

@ -5,10 +5,10 @@
package context package context
import ( import (
"gogs.io/gogs/internal/db" "gogs.io/gogs/internal/database"
) )
type APIOrganization struct { type APIOrganization struct {
Organization *db.User Organization *database.User
Team *db.Team Team *database.Team
} }

View File

@ -19,7 +19,7 @@ import (
"gogs.io/gogs/internal/auth" "gogs.io/gogs/internal/auth"
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/db" "gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/tool" "gogs.io/gogs/internal/tool"
) )
@ -109,7 +109,7 @@ func isAPIPath(url string) bool {
// authenticatedUserID returns the ID of the authenticated user, along with a bool value // authenticatedUserID returns the ID of the authenticated user, along with a bool value
// which indicates whether the user uses token authentication. // which indicates whether the user uses token authentication.
func authenticatedUserID(c *macaron.Context, sess session.Store) (_ int64, isTokenAuth bool) { func authenticatedUserID(c *macaron.Context, sess session.Store) (_ int64, isTokenAuth bool) {
if !db.HasEngine { if !database.HasEngine {
return 0, false return 0, false
} }
@ -132,14 +132,14 @@ func authenticatedUserID(c *macaron.Context, sess session.Store) (_ int64, isTok
// Let's see if token is valid. // Let's see if token is valid.
if len(tokenSHA) > 0 { if len(tokenSHA) > 0 {
t, err := db.AccessTokens.GetBySHA1(c.Req.Context(), tokenSHA) t, err := database.AccessTokens.GetBySHA1(c.Req.Context(), tokenSHA)
if err != nil { if err != nil {
if !db.IsErrAccessTokenNotExist(err) { if !database.IsErrAccessTokenNotExist(err) {
log.Error("GetAccessTokenBySHA: %v", err) log.Error("GetAccessTokenBySHA: %v", err)
} }
return 0, false return 0, false
} }
if err = db.AccessTokens.Touch(c.Req.Context(), t.ID); err != nil { if err = database.AccessTokens.Touch(c.Req.Context(), t.ID); err != nil {
log.Error("Failed to touch access token: %v", err) log.Error("Failed to touch access token: %v", err)
} }
return t.UserID, true return t.UserID, true
@ -151,9 +151,9 @@ func authenticatedUserID(c *macaron.Context, sess session.Store) (_ int64, isTok
return 0, false return 0, false
} }
if id, ok := uid.(int64); ok { if id, ok := uid.(int64); ok {
_, err := db.Users.GetByID(c.Req.Context(), id) _, err := database.Users.GetByID(c.Req.Context(), id)
if err != nil { if err != nil {
if !db.IsErrUserNotExist(err) { if !database.IsErrUserNotExist(err) {
log.Error("Failed to get user by ID: %v", err) log.Error("Failed to get user by ID: %v", err)
} }
return 0, false return 0, false
@ -165,8 +165,8 @@ func authenticatedUserID(c *macaron.Context, sess session.Store) (_ int64, isTok
// authenticatedUser returns the user object of the authenticated user, along with two bool values // authenticatedUser returns the user object of the authenticated user, along with two bool values
// which indicate whether the user uses HTTP Basic Authentication or token authentication respectively. // which indicate whether the user uses HTTP Basic Authentication or token authentication respectively.
func authenticatedUser(ctx *macaron.Context, sess session.Store) (_ *db.User, isBasicAuth, isTokenAuth bool) { func authenticatedUser(ctx *macaron.Context, sess session.Store) (_ *database.User, isBasicAuth, isTokenAuth bool) {
if !db.HasEngine { if !database.HasEngine {
return nil, false, false return nil, false, false
} }
@ -176,20 +176,20 @@ func authenticatedUser(ctx *macaron.Context, sess session.Store) (_ *db.User, is
if conf.Auth.EnableReverseProxyAuthentication { if conf.Auth.EnableReverseProxyAuthentication {
webAuthUser := ctx.Req.Header.Get(conf.Auth.ReverseProxyAuthenticationHeader) webAuthUser := ctx.Req.Header.Get(conf.Auth.ReverseProxyAuthenticationHeader)
if len(webAuthUser) > 0 { if len(webAuthUser) > 0 {
user, err := db.Users.GetByUsername(ctx.Req.Context(), webAuthUser) user, err := database.Users.GetByUsername(ctx.Req.Context(), webAuthUser)
if err != nil { if err != nil {
if !db.IsErrUserNotExist(err) { if !database.IsErrUserNotExist(err) {
log.Error("Failed to get user by name: %v", err) log.Error("Failed to get user by name: %v", err)
return nil, false, false return nil, false, false
} }
// Check if enabled auto-registration. // Check if enabled auto-registration.
if conf.Auth.EnableReverseProxyAutoRegistration { if conf.Auth.EnableReverseProxyAutoRegistration {
user, err = db.Users.Create( user, err = database.Users.Create(
ctx.Req.Context(), ctx.Req.Context(),
webAuthUser, webAuthUser,
gouuid.NewV4().String()+"@localhost", gouuid.NewV4().String()+"@localhost",
db.CreateUserOptions{ database.CreateUserOptions{
Activated: true, Activated: true,
}, },
) )
@ -210,7 +210,7 @@ func authenticatedUser(ctx *macaron.Context, sess session.Store) (_ *db.User, is
if len(auths) == 2 && auths[0] == "Basic" { if len(auths) == 2 && auths[0] == "Basic" {
uname, passwd, _ := tool.BasicAuthDecode(auths[1]) uname, passwd, _ := tool.BasicAuthDecode(auths[1])
u, err := db.Users.Authenticate(ctx.Req.Context(), uname, passwd, -1) u, err := database.Users.Authenticate(ctx.Req.Context(), uname, passwd, -1)
if err != nil { if err != nil {
if !auth.IsErrBadCredentials(err) { if !auth.IsErrBadCredentials(err) {
log.Error("Failed to authenticate user: %v", err) log.Error("Failed to authenticate user: %v", err)
@ -224,7 +224,7 @@ func authenticatedUser(ctx *macaron.Context, sess session.Store) (_ *db.User, is
return nil, false, false return nil, false, false
} }
u, err := db.Users.GetByID(ctx.Req.Context(), uid) u, err := database.Users.GetByID(ctx.Req.Context(), uid)
if err != nil { if err != nil {
log.Error("GetUserByID: %v", err) log.Error("GetUserByID: %v", err)
return nil, false, false return nil, false, false
@ -233,19 +233,19 @@ func authenticatedUser(ctx *macaron.Context, sess session.Store) (_ *db.User, is
} }
// AuthenticateByToken attempts to authenticate a user by the given access // AuthenticateByToken attempts to authenticate a user by the given access
// token. It returns db.ErrAccessTokenNotExist when the access token does not // token. It returns database.ErrAccessTokenNotExist when the access token does not
// exist. // exist.
func AuthenticateByToken(ctx context.Context, token string) (*db.User, error) { func AuthenticateByToken(ctx context.Context, token string) (*database.User, error) {
t, err := db.AccessTokens.GetBySHA1(ctx, token) t, err := database.AccessTokens.GetBySHA1(ctx, token)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "get access token by SHA1") return nil, errors.Wrap(err, "get access token by SHA1")
} }
if err = db.AccessTokens.Touch(ctx, t.ID); err != nil { if err = database.AccessTokens.Touch(ctx, t.ID); err != nil {
// NOTE: There is no need to fail the auth flow if we can't touch the token. // NOTE: There is no need to fail the auth flow if we can't touch the token.
log.Error("Failed to touch access token [id: %d]: %v", t.ID, err) log.Error("Failed to touch access token [id: %d]: %v", t.ID, err)
} }
user, err := db.Users.GetByID(ctx, t.UserID) user, err := database.Users.GetByID(ctx, t.UserID)
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "get user by ID [user_id: %d]", t.UserID) return nil, errors.Wrapf(err, "get user by ID [user_id: %d]", t.UserID)
} }

View File

@ -19,7 +19,7 @@ import (
log "unknwon.dev/clog/v2" log "unknwon.dev/clog/v2"
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/db" "gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/errutil" "gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/form" "gogs.io/gogs/internal/form"
"gogs.io/gogs/internal/lazyregexp" "gogs.io/gogs/internal/lazyregexp"
@ -35,7 +35,7 @@ type Context struct {
Session session.Store Session session.Store
Link string // Current request URL Link string // Current request URL
User *db.User User *database.User
IsLogged bool IsLogged bool
IsBasicAuth bool IsBasicAuth bool
IsTokenAuth bool IsTokenAuth bool

View File

@ -9,7 +9,7 @@ import (
"gopkg.in/macaron.v1" "gopkg.in/macaron.v1"
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/db" "gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/repoutil" "gogs.io/gogs/internal/repoutil"
) )
@ -27,9 +27,9 @@ func ServeGoGet() macaron.Handler {
repoName := c.Params(":reponame") repoName := c.Params(":reponame")
branchName := "master" branchName := "master"
owner, err := db.Users.GetByUsername(c.Req.Context(), ownerName) owner, err := database.Users.GetByUsername(c.Req.Context(), ownerName)
if err == nil { if err == nil {
repo, err := db.Repos.GetByName(c.Req.Context(), owner.ID, repoName) repo, err := database.Repos.GetByName(c.Req.Context(), owner.ID, repoName)
if err == nil && repo.DefaultBranch != "" { if err == nil && repo.DefaultBranch != "" {
branchName = repo.DefaultBranch branchName = repo.DefaultBranch
} }

View File

@ -10,7 +10,7 @@ import (
"gopkg.in/macaron.v1" "gopkg.in/macaron.v1"
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/db" "gogs.io/gogs/internal/database"
) )
type Organization struct { type Organization struct {
@ -18,10 +18,10 @@ type Organization struct {
IsMember bool IsMember bool
IsTeamMember bool // Is member of team. IsTeamMember bool // Is member of team.
IsTeamAdmin bool // In owner team or team that has admin permission level. IsTeamAdmin bool // In owner team or team that has admin permission level.
Organization *db.User Organization *database.User
OrgLink string OrgLink string
Team *db.Team Team *database.Team
} }
func HandleOrgAssignment(c *Context, args ...bool) { func HandleOrgAssignment(c *Context, args ...bool) {
@ -47,7 +47,7 @@ func HandleOrgAssignment(c *Context, args ...bool) {
orgName := c.Params(":org") orgName := c.Params(":org")
var err error var err error
c.Org.Organization, err = db.Users.GetByUsername(c.Req.Context(), orgName) c.Org.Organization, err = database.Users.GetByUsername(c.Req.Context(), orgName)
if err != nil { if err != nil {
c.NotFoundOrError(err, "get organization by name") c.NotFoundOrError(err, "get organization by name")
return return
@ -78,7 +78,7 @@ func HandleOrgAssignment(c *Context, args ...bool) {
} }
} else { } else {
// Fake data. // Fake data.
c.Data["SignedUser"] = &db.User{} c.Data["SignedUser"] = &database.User{}
} }
if (requireMember && !c.Org.IsMember) || if (requireMember && !c.Org.IsMember) ||
(requireOwner && !c.Org.IsOwner) { (requireOwner && !c.Org.IsOwner) {
@ -131,7 +131,7 @@ func HandleOrgAssignment(c *Context, args ...bool) {
return return
} }
c.Org.IsTeamAdmin = c.Org.Team.IsOwnerTeam() || c.Org.Team.Authorize >= db.AccessModeAdmin c.Org.IsTeamAdmin = c.Org.Team.IsOwnerTeam() || c.Org.Team.Authorize >= database.AccessModeAdmin
c.Data["IsTeamAdmin"] = c.Org.IsTeamAdmin c.Data["IsTeamAdmin"] = c.Org.IsTeamAdmin
if requireTeamAdmin && !c.Org.IsTeamAdmin { if requireTeamAdmin && !c.Org.IsTeamAdmin {
c.NotFound() c.NotFound()

View File

@ -17,25 +17,25 @@ import (
"github.com/gogs/git-module" "github.com/gogs/git-module"
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/db" "gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/repoutil" "gogs.io/gogs/internal/repoutil"
) )
type PullRequest struct { type PullRequest struct {
BaseRepo *db.Repository BaseRepo *database.Repository
Allowed bool Allowed bool
SameRepo bool SameRepo bool
HeadInfo string // [<user>:]<branch> HeadInfo string // [<user>:]<branch>
} }
type Repository struct { type Repository struct {
AccessMode db.AccessMode AccessMode database.AccessMode
IsWatching bool IsWatching bool
IsViewBranch bool IsViewBranch bool
IsViewTag bool IsViewTag bool
IsViewCommit bool IsViewCommit bool
Repository *db.Repository Repository *database.Repository
Owner *db.User Owner *database.User
Commit *git.Commit Commit *git.Commit
Tag *git.Tag Tag *git.Tag
GitRepo *git.Repository GitRepo *git.Repository
@ -46,29 +46,29 @@ type Repository struct {
RepoLink string RepoLink string
CloneLink repoutil.CloneLink CloneLink repoutil.CloneLink
CommitsCount int64 CommitsCount int64
Mirror *db.Mirror Mirror *database.Mirror
PullRequest *PullRequest PullRequest *PullRequest
} }
// IsOwner returns true if current user is the owner of repository. // IsOwner returns true if current user is the owner of repository.
func (r *Repository) IsOwner() bool { func (r *Repository) IsOwner() bool {
return r.AccessMode >= db.AccessModeOwner return r.AccessMode >= database.AccessModeOwner
} }
// IsAdmin returns true if current user has admin or higher access of repository. // IsAdmin returns true if current user has admin or higher access of repository.
func (r *Repository) IsAdmin() bool { func (r *Repository) IsAdmin() bool {
return r.AccessMode >= db.AccessModeAdmin return r.AccessMode >= database.AccessModeAdmin
} }
// IsWriter returns true if current user has write or higher access of repository. // IsWriter returns true if current user has write or higher access of repository.
func (r *Repository) IsWriter() bool { func (r *Repository) IsWriter() bool {
return r.AccessMode >= db.AccessModeWrite return r.AccessMode >= database.AccessModeWrite
} }
// HasAccess returns true if the current user has at least read access for this repository // HasAccess returns true if the current user has at least read access for this repository
func (r *Repository) HasAccess() bool { func (r *Repository) HasAccess() bool {
return r.AccessMode >= db.AccessModeRead return r.AccessMode >= database.AccessModeRead
} }
// CanEnableEditor returns true if repository is editable and user has proper access level. // CanEnableEditor returns true if repository is editable and user has proper access level.
@ -125,7 +125,7 @@ func (r *Repository) PullRequestURL(baseBranch, headBranch string) string {
func RepoAssignment(pages ...bool) macaron.Handler { func RepoAssignment(pages ...bool) macaron.Handler {
return func(c *Context) { return func(c *Context) {
var ( var (
owner *db.User owner *database.User
err error err error
isIssuesPage bool isIssuesPage bool
isWikiPage bool isWikiPage bool
@ -145,7 +145,7 @@ func RepoAssignment(pages ...bool) macaron.Handler {
if c.IsLogged && c.User.LowerName == strings.ToLower(ownerName) { if c.IsLogged && c.User.LowerName == strings.ToLower(ownerName) {
owner = c.User owner = c.User
} else { } else {
owner, err = db.Users.GetByUsername(c.Req.Context(), ownerName) owner, err = database.Users.GetByUsername(c.Req.Context(), ownerName)
if err != nil { if err != nil {
c.NotFoundOrError(err, "get user by name") c.NotFoundOrError(err, "get user by name")
return return
@ -154,7 +154,7 @@ func RepoAssignment(pages ...bool) macaron.Handler {
c.Repo.Owner = owner c.Repo.Owner = owner
c.Data["Username"] = c.Repo.Owner.Name c.Data["Username"] = c.Repo.Owner.Name
repo, err := db.GetRepositoryByName(owner.ID, repoName) repo, err := database.GetRepositoryByName(owner.ID, repoName)
if err != nil { if err != nil {
c.NotFoundOrError(err, "get repository by name") c.NotFoundOrError(err, "get repository by name")
return return
@ -169,10 +169,10 @@ func RepoAssignment(pages ...bool) macaron.Handler {
// Admin has super access // Admin has super access
if c.IsLogged && c.User.IsAdmin { if c.IsLogged && c.User.IsAdmin {
c.Repo.AccessMode = db.AccessModeOwner c.Repo.AccessMode = database.AccessModeOwner
} else { } else {
c.Repo.AccessMode = db.Perms.AccessMode(c.Req.Context(), c.UserID(), repo.ID, c.Repo.AccessMode = database.Perms.AccessMode(c.Req.Context(), c.UserID(), repo.ID,
db.AccessModeOptions{ database.AccessModeOptions{
OwnerID: repo.OwnerID, OwnerID: repo.OwnerID,
Private: repo.IsPrivate, Private: repo.IsPrivate,
}, },
@ -181,23 +181,23 @@ func RepoAssignment(pages ...bool) macaron.Handler {
// If the authenticated user has no direct access, see if the repository is a fork // If the authenticated user has no direct access, see if the repository is a fork
// and whether the user has access to the base repository. // and whether the user has access to the base repository.
if c.Repo.AccessMode == db.AccessModeNone && repo.BaseRepo != nil { if c.Repo.AccessMode == database.AccessModeNone && repo.BaseRepo != nil {
mode := db.Perms.AccessMode(c.Req.Context(), c.UserID(), repo.BaseRepo.ID, mode := database.Perms.AccessMode(c.Req.Context(), c.UserID(), repo.BaseRepo.ID,
db.AccessModeOptions{ database.AccessModeOptions{
OwnerID: repo.BaseRepo.OwnerID, OwnerID: repo.BaseRepo.OwnerID,
Private: repo.BaseRepo.IsPrivate, Private: repo.BaseRepo.IsPrivate,
}, },
) )
// Users shouldn't have indirect access level higher than write. // Users shouldn't have indirect access level higher than write.
if mode > db.AccessModeWrite { if mode > database.AccessModeWrite {
mode = db.AccessModeWrite mode = database.AccessModeWrite
} }
c.Repo.AccessMode = mode c.Repo.AccessMode = mode
} }
// Check access // Check access
if c.Repo.AccessMode == db.AccessModeNone { if c.Repo.AccessMode == database.AccessModeNone {
// Redirect to any accessible page if not yet on it // Redirect to any accessible page if not yet on it
if repo.IsPartialPublic() && if repo.IsPartialPublic() &&
(!(isIssuesPage || isWikiPage) || (!(isIssuesPage || isWikiPage) ||
@ -227,7 +227,7 @@ func RepoAssignment(pages ...bool) macaron.Handler {
} }
if repo.IsMirror { if repo.IsMirror {
c.Repo.Mirror, err = db.GetMirrorByRepoID(repo.ID) c.Repo.Mirror, err = database.GetMirrorByRepoID(repo.ID)
if err != nil { if err != nil {
c.Error(err, "get mirror by repository ID") c.Error(err, "get mirror by repository ID")
return return
@ -237,7 +237,7 @@ func RepoAssignment(pages ...bool) macaron.Handler {
c.Data["Mirror"] = c.Repo.Mirror c.Data["Mirror"] = c.Repo.Mirror
} }
gitRepo, err := git.Open(db.RepoPath(ownerName, repoName)) gitRepo, err := git.Open(database.RepoPath(ownerName, repoName))
if err != nil { if err != nil {
c.Error(err, "open repository") c.Error(err, "open repository")
return return
@ -265,8 +265,8 @@ func RepoAssignment(pages ...bool) macaron.Handler {
c.Data["WikiCloneLink"] = repo.WikiCloneLink() c.Data["WikiCloneLink"] = repo.WikiCloneLink()
if c.IsLogged { if c.IsLogged {
c.Data["IsWatchingRepo"] = db.IsWatching(c.User.ID, repo.ID) c.Data["IsWatchingRepo"] = database.IsWatching(c.User.ID, repo.ID)
c.Data["IsStaringRepo"] = db.IsStaring(c.User.ID, repo.ID) c.Data["IsStaringRepo"] = database.IsStaring(c.User.ID, repo.ID)
} }
// repo is bare and display enable // repo is bare and display enable
@ -314,7 +314,7 @@ func RepoRef() macaron.Handler {
// For API calls. // For API calls.
if c.Repo.GitRepo == nil { if c.Repo.GitRepo == nil {
repoPath := db.RepoPath(c.Repo.Owner.Name, c.Repo.Repository.Name) repoPath := database.RepoPath(c.Repo.Owner.Name, c.Repo.Repository.Name)
c.Repo.GitRepo, err = git.Open(repoPath) c.Repo.GitRepo, err = git.Open(repoPath)
if err != nil { if err != nil {
c.Error(err, "open repository") c.Error(err, "open repository")
@ -403,7 +403,7 @@ func RepoRef() macaron.Handler {
c.Data["IsViewCommit"] = c.Repo.IsViewCommit c.Data["IsViewCommit"] = c.Repo.IsViewCommit
// People who have push access or have forked repository can propose a new pull request. // 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 && database.Repos.HasForkedBy(c.Req.Context(), c.Repo.Repository.ID, c.User.ID)) {
// Pull request is allowed if this is a fork repository // Pull request is allowed if this is a fork repository
// and base repository accepts pull requests. // and base repository accepts pull requests.
if c.Repo.Repository.BaseRepo != nil { if c.Repo.Repository.BaseRepo != nil {

View File

@ -7,19 +7,19 @@ package context
import ( import (
"gopkg.in/macaron.v1" "gopkg.in/macaron.v1"
"gogs.io/gogs/internal/db" "gogs.io/gogs/internal/database"
) )
// ParamsUser is the wrapper type of the target user defined by URL parameter, namely ':username'. // ParamsUser is the wrapper type of the target user defined by URL parameter, namely ':username'.
type ParamsUser struct { type ParamsUser struct {
*db.User *database.User
} }
// InjectParamsUser returns a handler that retrieves target user based on URL parameter ':username', // InjectParamsUser returns a handler that retrieves target user based on URL parameter ':username',
// and injects it as *ParamsUser. // and injects it as *ParamsUser.
func InjectParamsUser() macaron.Handler { func InjectParamsUser() macaron.Handler {
return func(c *Context) { return func(c *Context) {
user, err := db.Users.GetByUsername(c.Req.Context(), c.Params(":username")) user, err := database.Users.GetByUsername(c.Req.Context(), c.Params(":username"))
if err != nil { if err != nil {
c.NotFoundOrError(err, "get user by name") c.NotFoundOrError(err, "get user by name")
return return

View File

@ -12,7 +12,7 @@ import (
"github.com/gogs/cron" "github.com/gogs/cron"
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/db" "gogs.io/gogs/internal/database"
) )
var c = cron.New() var c = cron.New()
@ -23,47 +23,47 @@ func NewContext() {
err error err error
) )
if conf.Cron.UpdateMirror.Enabled { if conf.Cron.UpdateMirror.Enabled {
entry, err = c.AddFunc("Update mirrors", conf.Cron.UpdateMirror.Schedule, db.MirrorUpdate) entry, err = c.AddFunc("Update mirrors", conf.Cron.UpdateMirror.Schedule, database.MirrorUpdate)
if err != nil { if err != nil {
log.Fatal("Cron.(update mirrors): %v", err) log.Fatal("Cron.(update mirrors): %v", err)
} }
if conf.Cron.UpdateMirror.RunAtStart { if conf.Cron.UpdateMirror.RunAtStart {
entry.Prev = time.Now() entry.Prev = time.Now()
entry.ExecTimes++ entry.ExecTimes++
go db.MirrorUpdate() go database.MirrorUpdate()
} }
} }
if conf.Cron.RepoHealthCheck.Enabled { if conf.Cron.RepoHealthCheck.Enabled {
entry, err = c.AddFunc("Repository health check", conf.Cron.RepoHealthCheck.Schedule, db.GitFsck) entry, err = c.AddFunc("Repository health check", conf.Cron.RepoHealthCheck.Schedule, database.GitFsck)
if err != nil { if err != nil {
log.Fatal("Cron.(repository health check): %v", err) log.Fatal("Cron.(repository health check): %v", err)
} }
if conf.Cron.RepoHealthCheck.RunAtStart { if conf.Cron.RepoHealthCheck.RunAtStart {
entry.Prev = time.Now() entry.Prev = time.Now()
entry.ExecTimes++ entry.ExecTimes++
go db.GitFsck() go database.GitFsck()
} }
} }
if conf.Cron.CheckRepoStats.Enabled { if conf.Cron.CheckRepoStats.Enabled {
entry, err = c.AddFunc("Check repository statistics", conf.Cron.CheckRepoStats.Schedule, db.CheckRepoStats) entry, err = c.AddFunc("Check repository statistics", conf.Cron.CheckRepoStats.Schedule, database.CheckRepoStats)
if err != nil { if err != nil {
log.Fatal("Cron.(check repository statistics): %v", err) log.Fatal("Cron.(check repository statistics): %v", err)
} }
if conf.Cron.CheckRepoStats.RunAtStart { if conf.Cron.CheckRepoStats.RunAtStart {
entry.Prev = time.Now() entry.Prev = time.Now()
entry.ExecTimes++ entry.ExecTimes++
go db.CheckRepoStats() go database.CheckRepoStats()
} }
} }
if conf.Cron.RepoArchiveCleanup.Enabled { if conf.Cron.RepoArchiveCleanup.Enabled {
entry, err = c.AddFunc("Repository archive cleanup", conf.Cron.RepoArchiveCleanup.Schedule, db.DeleteOldRepositoryArchives) entry, err = c.AddFunc("Repository archive cleanup", conf.Cron.RepoArchiveCleanup.Schedule, database.DeleteOldRepositoryArchives)
if err != nil { if err != nil {
log.Fatal("Cron.(repository archive cleanup): %v", err) log.Fatal("Cron.(repository archive cleanup): %v", err)
} }
if conf.Cron.RepoArchiveCleanup.RunAtStart { if conf.Cron.RepoArchiveCleanup.RunAtStart {
entry.Prev = time.Now() entry.Prev = time.Now()
entry.ExecTimes++ entry.ExecTimes++
go db.DeleteOldRepositoryArchives() go database.DeleteOldRepositoryArchives()
} }
} }
c.Start() c.Start()

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"context" "context"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"context" "context"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"context" "context"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"context" "context"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"fmt" "fmt"

View File

@ -1,4 +1,4 @@
package db package database
import ( import (
"bufio" "bufio"
@ -25,9 +25,9 @@ import (
) )
// getTableType returns the type name of a table definition without package name, // getTableType returns the type name of a table definition without package name,
// e.g. *db.LFSObject -> LFSObject. // e.g. *database.LFSObject -> LFSObject.
func getTableType(t any) string { func getTableType(t any) string {
return strings.TrimPrefix(fmt.Sprintf("%T", t), "*db.") return strings.TrimPrefix(fmt.Sprintf("%T", t), "*database.")
} }
// DumpDatabase dumps all data from database to file system in JSON Lines format. // DumpDatabase dumps all data from database to file system in JSON Lines format.
@ -153,7 +153,7 @@ func ImportDatabase(ctx context.Context, db *gorm.DB, dirPath string, verbose bo
default: default:
} }
tableName := strings.TrimPrefix(fmt.Sprintf("%T", table), "*db.") tableName := strings.TrimPrefix(fmt.Sprintf("%T", table), "*database.")
err := func() error { err := func() error {
tableFile := filepath.Join(dirPath, tableName+".json") tableFile := filepath.Join(dirPath, tableName+".json")
if !osutil.IsFile(tableFile) { if !osutil.IsFile(tableFile) {
@ -245,7 +245,7 @@ func importLegacyTables(ctx context.Context, dirPath string, verbose bool) error
default: default:
} }
tableName := strings.TrimPrefix(fmt.Sprintf("%T", table), "*db.") tableName := strings.TrimPrefix(fmt.Sprintf("%T", table), "*database.")
tableFile := filepath.Join(dirPath, tableName+".json") tableFile := filepath.Join(dirPath, tableName+".json")
if !osutil.IsFile(tableFile) { if !osutil.IsFile(tableFile) {
continue continue

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"bytes" "bytes"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"context" "context"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"fmt" "fmt"
@ -100,14 +100,14 @@ func Init(w logger.Writer) (*gorm.DB, error) {
} }
// NOTE: GORM has problem detecting existing columns, see // NOTE: GORM has problem detecting existing columns, see
// https://github.com/gogs/gogs/issues/6091. Therefore only use it to create new // https://github.com/gogs/gogs/issues/6091. Therefore, only use it to create new
// tables, and do customized migration with future changes. // tables, and do customize migration with future changes.
for _, table := range Tables { for _, table := range Tables {
if db.Migrator().HasTable(table) { if db.Migrator().HasTable(table) {
continue continue
} }
name := strings.TrimPrefix(fmt.Sprintf("%T", table), "*db.") name := strings.TrimPrefix(fmt.Sprintf("%T", table), "*database.")
err = db.Migrator().AutoMigrate(table) err = db.Migrator().AutoMigrate(table)
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "auto migrate %q", name) return nil, errors.Wrapf(err, "auto migrate %q", name)

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"fmt" "fmt"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"context" "context"
@ -17,7 +17,7 @@ import (
api "github.com/gogs/go-gogs-client" api "github.com/gogs/go-gogs-client"
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/db/errors" "gogs.io/gogs/internal/database/errors"
"gogs.io/gogs/internal/errutil" "gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/markup" "gogs.io/gogs/internal/markup"
"gogs.io/gogs/internal/tool" "gogs.io/gogs/internal/tool"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"fmt" "fmt"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"context" "context"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"context" "context"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"context" "context"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"fmt" "fmt"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"testing" "testing"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"context" "context"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"context" "context"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"flag" "flag"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"fmt" "fmt"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"context" "context"
@ -19,7 +19,7 @@ import (
"github.com/gogs/git-module" "github.com/gogs/git-module"
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/db/errors" "gogs.io/gogs/internal/database/errors"
"gogs.io/gogs/internal/process" "gogs.io/gogs/internal/process"
"gogs.io/gogs/internal/sync" "gogs.io/gogs/internal/sync"
) )

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"testing" "testing"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"testing" "testing"

View File

@ -4,7 +4,7 @@
// To add additional mocks to this or another package, add a new entry to the // To add additional mocks to this or another package, add a new entry to the
// mockgen.yaml file in the root of this repository. // mockgen.yaml file in the root of this repository.
package db package database
import ( import (
"context" "context"
@ -14,7 +14,7 @@ import (
) )
// MockLoginSourcesStore is a mock implementation of the LoginSourcesStore // MockLoginSourcesStore is a mock implementation of the LoginSourcesStore
// interface (from the package gogs.io/gogs/internal/db) used for unit // interface (from the package gogs.io/gogs/internal/database) used for unit
// testing. // testing.
type MockLoginSourcesStore struct { type MockLoginSourcesStore struct {
// CountFunc is an instance of a mock function object controlling the // CountFunc is an instance of a mock function object controlling the
@ -902,7 +902,7 @@ func (c LoginSourcesStoreSaveFuncCall) Results() []interface{} {
// MockLoginSourceFileStore is a mock implementation of the // MockLoginSourceFileStore is a mock implementation of the
// loginSourceFileStore interface (from the package // loginSourceFileStore interface (from the package
// gogs.io/gogs/internal/db) used for unit testing. // gogs.io/gogs/internal/database) used for unit testing.
type MockLoginSourceFileStore struct { type MockLoginSourceFileStore struct {
// SaveFunc is an instance of a mock function object controlling the // SaveFunc is an instance of a mock function object controlling the
// behavior of the method Save. // behavior of the method Save.
@ -962,8 +962,8 @@ func NewStrictMockLoginSourceFileStore() *MockLoginSourceFileStore {
} }
// surrogateMockLoginSourceFileStore is a copy of the loginSourceFileStore // surrogateMockLoginSourceFileStore is a copy of the loginSourceFileStore
// interface (from the package gogs.io/gogs/internal/db). It is redefined // interface (from the package gogs.io/gogs/internal/database). It is
// here as it is unexported in the source package. // redefined here as it is unexported in the source package.
type surrogateMockLoginSourceFileStore interface { type surrogateMockLoginSourceFileStore interface {
Save() error Save() error
SetConfig(interface{}) error SetConfig(interface{}) error
@ -1296,7 +1296,7 @@ func (c LoginSourceFileStoreSetGeneralFuncCall) Results() []interface{} {
// MockLoginSourceFilesStore is a mock implementation of the // MockLoginSourceFilesStore is a mock implementation of the
// loginSourceFilesStore interface (from the package // loginSourceFilesStore interface (from the package
// gogs.io/gogs/internal/db) used for unit testing. // gogs.io/gogs/internal/database) used for unit testing.
type MockLoginSourceFilesStore struct { type MockLoginSourceFilesStore struct {
// GetByIDFunc is an instance of a mock function object controlling the // GetByIDFunc is an instance of a mock function object controlling the
// behavior of the method GetByID. // behavior of the method GetByID.
@ -1369,8 +1369,8 @@ func NewStrictMockLoginSourceFilesStore() *MockLoginSourceFilesStore {
} }
// surrogateMockLoginSourceFilesStore is a copy of the loginSourceFilesStore // surrogateMockLoginSourceFilesStore is a copy of the loginSourceFilesStore
// interface (from the package gogs.io/gogs/internal/db). It is redefined // interface (from the package gogs.io/gogs/internal/database). It is
// here as it is unexported in the source package. // redefined here as it is unexported in the source package.
type surrogateMockLoginSourceFilesStore interface { type surrogateMockLoginSourceFilesStore interface {
GetByID(int64) (*LoginSource, error) GetByID(int64) (*LoginSource, error)
Len() int Len() int

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"context" "context"
@ -22,7 +22,7 @@ import (
"xorm.io/xorm" "xorm.io/xorm"
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/db/migrations" "gogs.io/gogs/internal/database/migrations"
"gogs.io/gogs/internal/dbutil" "gogs.io/gogs/internal/dbutil"
) )

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"context" "context"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"context" "context"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"context" "context"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"context" "context"
@ -11,7 +11,7 @@ import (
"xorm.io/xorm" "xorm.io/xorm"
"gogs.io/gogs/internal/db/errors" "gogs.io/gogs/internal/database/errors"
"gogs.io/gogs/internal/errutil" "gogs.io/gogs/internal/errutil"
) )

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"context" "context"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"context" "context"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"context" "context"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"context" "context"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"os" "os"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"context" "context"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"context" "context"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"fmt" "fmt"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"bytes" "bytes"
@ -33,7 +33,7 @@ import (
embedConf "gogs.io/gogs/conf" embedConf "gogs.io/gogs/conf"
"gogs.io/gogs/internal/avatar" "gogs.io/gogs/internal/avatar"
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
dberrors "gogs.io/gogs/internal/db/errors" dberrors "gogs.io/gogs/internal/database/errors"
"gogs.io/gogs/internal/dbutil" "gogs.io/gogs/internal/dbutil"
"gogs.io/gogs/internal/errutil" "gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/markup" "gogs.io/gogs/internal/markup"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"context" "context"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"fmt" "fmt"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"fmt" "fmt"
@ -23,7 +23,7 @@ import (
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/cryptoutil" "gogs.io/gogs/internal/cryptoutil"
dberrors "gogs.io/gogs/internal/db/errors" dberrors "gogs.io/gogs/internal/database/errors"
"gogs.io/gogs/internal/gitutil" "gogs.io/gogs/internal/gitutil"
"gogs.io/gogs/internal/osutil" "gogs.io/gogs/internal/osutil"
"gogs.io/gogs/internal/pathutil" "gogs.io/gogs/internal/pathutil"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"testing" "testing"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"fmt" "fmt"

View File

@ -1,4 +1,4 @@
package db package database
import ( import (
"testing" "testing"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"context" "context"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"context" "context"

View File

@ -17,7 +17,7 @@ import (
"gorm.io/gorm/clause" "gorm.io/gorm/clause"
"gorm.io/gorm/schema" "gorm.io/gorm/schema"
"gogs.io/gogs/internal/db" "gogs.io/gogs/internal/database"
) )
//go:generate go run main.go ../../../docs/dev/database_schema.md //go:generate go run main.go ../../../docs/dev/database_schema.md
@ -138,8 +138,8 @@ func generate(dialector gorm.Dialector) ([]*tableInfo, error) {
RunWithValue(value any, fc func(*gorm.Statement) error) error RunWithValue(value any, fc func(*gorm.Statement) error) error
FullDataTypeOf(*schema.Field) clause.Expr FullDataTypeOf(*schema.Field) clause.Expr
}) })
tableInfos := make([]*tableInfo, 0, len(db.Tables)) tableInfos := make([]*tableInfo, 0, len(database.Tables))
for _, table := range db.Tables { for _, table := range database.Tables {
err = m.RunWithValue(table, func(stmt *gorm.Statement) error { err = m.RunWithValue(table, func(stmt *gorm.Statement) error {
fields := make([]*tableField, 0, len(stmt.Schema.DBNames)) fields := make([]*tableField, 0, len(stmt.Schema.DBNames))
for _, field := range stmt.Schema.Fields { for _, field := range stmt.Schema.Fields {

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"context" "context"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"testing" "testing"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"encoding/base64" "encoding/base64"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"context" "context"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"context" "context"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"context" "context"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"context" "context"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"context" "context"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"crypto/hmac" "crypto/hmac"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"fmt" "fmt"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"fmt" "fmt"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"fmt" "fmt"

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a MIT-style // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
package db package database
import ( import (
"fmt" "fmt"

View File

@ -13,7 +13,7 @@ import (
"gopkg.in/macaron.v1" "gopkg.in/macaron.v1"
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/db" "gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/netutil" "gogs.io/gogs/internal/netutil"
) )
@ -60,7 +60,7 @@ func (f *MigrateRepo) Validate(ctx *macaron.Context, errs binding.Errors) bindin
// and returns composed URL with needed username and password. // and returns composed URL with needed username and password.
// It also checks if given user has permission when remote address // It also checks if given user has permission when remote address
// is actually a local path. // is actually a local path.
func (f MigrateRepo) ParseRemoteAddr(user *db.User) (string, error) { func (f MigrateRepo) ParseRemoteAddr(user *database.User) (string, error) {
remoteAddr := strings.TrimSpace(f.CloneAddr) remoteAddr := strings.TrimSpace(f.CloneAddr)
// Remote address can be HTTP/HTTPS/Git URL or local path. // Remote address can be HTTP/HTTPS/Git URL or local path.
@ -69,11 +69,11 @@ func (f MigrateRepo) ParseRemoteAddr(user *db.User) (string, error) {
strings.HasPrefix(remoteAddr, "git://") { strings.HasPrefix(remoteAddr, "git://") {
u, err := url.Parse(remoteAddr) u, err := url.Parse(remoteAddr)
if err != nil { if err != nil {
return "", db.ErrInvalidCloneAddr{IsURLError: true} return "", database.ErrInvalidCloneAddr{IsURLError: true}
} }
if netutil.IsBlockedLocalHostname(u.Hostname(), conf.Security.LocalNetworkAllowlist) { if netutil.IsBlockedLocalHostname(u.Hostname(), conf.Security.LocalNetworkAllowlist) {
return "", db.ErrInvalidCloneAddr{IsBlockedLocalAddress: true} return "", database.ErrInvalidCloneAddr{IsBlockedLocalAddress: true}
} }
if len(f.AuthUsername)+len(f.AuthPassword) > 0 { if len(f.AuthUsername)+len(f.AuthPassword) > 0 {
@ -81,13 +81,13 @@ func (f MigrateRepo) ParseRemoteAddr(user *db.User) (string, error) {
} }
// To prevent CRLF injection in git protocol, see https://github.com/gogs/gogs/issues/6413 // To prevent CRLF injection in git protocol, see https://github.com/gogs/gogs/issues/6413
if u.Scheme == "git" && (strings.Contains(remoteAddr, "%0d") || strings.Contains(remoteAddr, "%0a")) { if u.Scheme == "git" && (strings.Contains(remoteAddr, "%0d") || strings.Contains(remoteAddr, "%0a")) {
return "", db.ErrInvalidCloneAddr{IsURLError: true} return "", database.ErrInvalidCloneAddr{IsURLError: true}
} }
remoteAddr = u.String() remoteAddr = u.String()
} else if !user.CanImportLocal() { } else if !user.CanImportLocal() {
return "", db.ErrInvalidCloneAddr{IsPermissionDenied: true} return "", database.ErrInvalidCloneAddr{IsPermissionDenied: true}
} else if !com.IsDir(remoteAddr) { } else if !com.IsDir(remoteAddr) {
return "", db.ErrInvalidCloneAddr{IsInvalidPath: true} return "", database.ErrInvalidCloneAddr{IsInvalidPath: true}
} }
return remoteAddr, nil return remoteAddr, nil

View File

@ -15,7 +15,7 @@ import (
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/context" "gogs.io/gogs/internal/context"
"gogs.io/gogs/internal/cron" "gogs.io/gogs/internal/cron"
"gogs.io/gogs/internal/db" "gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/email" "gogs.io/gogs/internal/email"
"gogs.io/gogs/internal/process" "gogs.io/gogs/internal/process"
"gogs.io/gogs/internal/tool" "gogs.io/gogs/internal/tool"
@ -119,7 +119,7 @@ func Dashboard(c *context.Context) {
c.Data["BuildTime"] = conf.BuildTime c.Data["BuildTime"] = conf.BuildTime
c.Data["BuildCommit"] = conf.BuildCommit c.Data["BuildCommit"] = conf.BuildCommit
c.Data["Stats"] = db.GetStatistic(c.Req.Context()) c.Data["Stats"] = database.GetStatistic(c.Req.Context())
// FIXME: update periodically // FIXME: update periodically
updateSystemStatus() updateSystemStatus()
c.Data["SysStatus"] = sysStatus c.Data["SysStatus"] = sysStatus
@ -145,25 +145,25 @@ func Operation(c *context.Context) {
switch AdminOperation(c.QueryInt("op")) { switch AdminOperation(c.QueryInt("op")) {
case CleanInactivateUser: case CleanInactivateUser:
success = c.Tr("admin.dashboard.delete_inactivate_accounts_success") success = c.Tr("admin.dashboard.delete_inactivate_accounts_success")
err = db.Users.DeleteInactivated() err = database.Users.DeleteInactivated()
case CleanRepoArchives: case CleanRepoArchives:
success = c.Tr("admin.dashboard.delete_repo_archives_success") success = c.Tr("admin.dashboard.delete_repo_archives_success")
err = db.DeleteRepositoryArchives() err = database.DeleteRepositoryArchives()
case CleanMissingRepos: case CleanMissingRepos:
success = c.Tr("admin.dashboard.delete_missing_repos_success") success = c.Tr("admin.dashboard.delete_missing_repos_success")
err = db.DeleteMissingRepositories() err = database.DeleteMissingRepositories()
case GitGCRepos: case GitGCRepos:
success = c.Tr("admin.dashboard.git_gc_repos_success") success = c.Tr("admin.dashboard.git_gc_repos_success")
err = db.GitGcRepos() err = database.GitGcRepos()
case SyncSSHAuthorizedKey: case SyncSSHAuthorizedKey:
success = c.Tr("admin.dashboard.resync_all_sshkeys_success") success = c.Tr("admin.dashboard.resync_all_sshkeys_success")
err = db.RewriteAuthorizedKeys() err = database.RewriteAuthorizedKeys()
case SyncRepositoryHooks: case SyncRepositoryHooks:
success = c.Tr("admin.dashboard.resync_all_hooks_success") success = c.Tr("admin.dashboard.resync_all_hooks_success")
err = db.SyncRepositoryHooks() err = database.SyncRepositoryHooks()
case ReinitMissingRepository: case ReinitMissingRepository:
success = c.Tr("admin.dashboard.reinit_missing_repos_success") success = c.Tr("admin.dashboard.reinit_missing_repos_success")
err = db.ReinitMissingRepositories() err = database.ReinitMissingRepositories()
} }
if err != nil { if err != nil {

View File

@ -19,7 +19,7 @@ import (
"gogs.io/gogs/internal/auth/smtp" "gogs.io/gogs/internal/auth/smtp"
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/context" "gogs.io/gogs/internal/context"
"gogs.io/gogs/internal/db" "gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/form" "gogs.io/gogs/internal/form"
) )
@ -35,13 +35,13 @@ func Authentications(c *context.Context) {
c.PageIs("AdminAuthentications") c.PageIs("AdminAuthentications")
var err error var err error
c.Data["Sources"], err = db.LoginSources.List(c.Req.Context(), db.ListLoginSourceOptions{}) c.Data["Sources"], err = database.LoginSources.List(c.Req.Context(), database.ListLoginSourceOptions{})
if err != nil { if err != nil {
c.Error(err, "list login sources") c.Error(err, "list login sources")
return return
} }
c.Data["Total"] = db.LoginSources.Count(c.Req.Context()) c.Data["Total"] = database.LoginSources.Count(c.Req.Context())
c.Success(AUTHS) c.Success(AUTHS)
} }
@ -159,8 +159,8 @@ func NewAuthSourcePost(c *context.Context, f form.Authentication) {
return return
} }
source, err := db.LoginSources.Create(c.Req.Context(), source, err := database.LoginSources.Create(c.Req.Context(),
db.CreateLoginSourceOptions{ database.CreateLoginSourceOptions{
Type: auth.Type(f.Type), Type: auth.Type(f.Type),
Name: f.Name, Name: f.Name,
Activated: f.IsActive, Activated: f.IsActive,
@ -169,7 +169,7 @@ func NewAuthSourcePost(c *context.Context, f form.Authentication) {
}, },
) )
if err != nil { if err != nil {
if db.IsErrLoginSourceAlreadyExist(err) { if database.IsErrLoginSourceAlreadyExist(err) {
c.FormErr("Name") c.FormErr("Name")
c.RenderWithErr(c.Tr("admin.auths.login_source_exist", f.Name), AUTH_NEW, f) c.RenderWithErr(c.Tr("admin.auths.login_source_exist", f.Name), AUTH_NEW, f)
} else { } else {
@ -179,7 +179,7 @@ func NewAuthSourcePost(c *context.Context, f form.Authentication) {
} }
if source.IsDefault { if source.IsDefault {
err = db.LoginSources.ResetNonDefault(c.Req.Context(), source) err = database.LoginSources.ResetNonDefault(c.Req.Context(), source)
if err != nil { if err != nil {
c.Error(err, "reset non-default login sources") c.Error(err, "reset non-default login sources")
return return
@ -200,7 +200,7 @@ func EditAuthSource(c *context.Context) {
c.Data["SecurityProtocols"] = securityProtocols c.Data["SecurityProtocols"] = securityProtocols
c.Data["SMTPAuths"] = smtp.AuthTypes c.Data["SMTPAuths"] = smtp.AuthTypes
source, err := db.LoginSources.GetByID(c.Req.Context(), c.ParamsInt64(":authid")) source, err := database.LoginSources.GetByID(c.Req.Context(), c.ParamsInt64(":authid"))
if err != nil { if err != nil {
c.Error(err, "get login source by ID") c.Error(err, "get login source by ID")
return return
@ -218,7 +218,7 @@ func EditAuthSourcePost(c *context.Context, f form.Authentication) {
c.Data["SMTPAuths"] = smtp.AuthTypes c.Data["SMTPAuths"] = smtp.AuthTypes
source, err := db.LoginSources.GetByID(c.Req.Context(), c.ParamsInt64(":authid")) source, err := database.LoginSources.GetByID(c.Req.Context(), c.ParamsInt64(":authid"))
if err != nil { if err != nil {
c.Error(err, "get login source by ID") c.Error(err, "get login source by ID")
return return
@ -257,13 +257,13 @@ func EditAuthSourcePost(c *context.Context, f form.Authentication) {
source.IsActived = f.IsActive source.IsActived = f.IsActive
source.IsDefault = f.IsDefault source.IsDefault = f.IsDefault
source.Provider = provider source.Provider = provider
if err := db.LoginSources.Save(c.Req.Context(), source); err != nil { if err := database.LoginSources.Save(c.Req.Context(), source); err != nil {
c.Error(err, "update login source") c.Error(err, "update login source")
return return
} }
if source.IsDefault { if source.IsDefault {
err = db.LoginSources.ResetNonDefault(c.Req.Context(), source) err = database.LoginSources.ResetNonDefault(c.Req.Context(), source)
if err != nil { if err != nil {
c.Error(err, "reset non-default login sources") c.Error(err, "reset non-default login sources")
return return
@ -278,8 +278,8 @@ func EditAuthSourcePost(c *context.Context, f form.Authentication) {
func DeleteAuthSource(c *context.Context) { func DeleteAuthSource(c *context.Context) {
id := c.ParamsInt64(":authid") id := c.ParamsInt64(":authid")
if err := db.LoginSources.DeleteByID(c.Req.Context(), id); err != nil { if err := database.LoginSources.DeleteByID(c.Req.Context(), id); err != nil {
if db.IsErrLoginSourceInUse(err) { if database.IsErrLoginSourceInUse(err) {
c.Flash.Error(c.Tr("admin.auths.still_in_used")) c.Flash.Error(c.Tr("admin.auths.still_in_used"))
} else { } else {
c.Flash.Error(fmt.Sprintf("DeleteSource: %v", err)) c.Flash.Error(fmt.Sprintf("DeleteSource: %v", err))

View File

@ -13,7 +13,7 @@ import (
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/context" "gogs.io/gogs/internal/context"
"gogs.io/gogs/internal/db" "gogs.io/gogs/internal/database"
) )
const ( const (
@ -25,14 +25,14 @@ func Notices(c *context.Context) {
c.Data["PageIsAdmin"] = true c.Data["PageIsAdmin"] = true
c.Data["PageIsAdminNotices"] = true c.Data["PageIsAdminNotices"] = true
total := db.Notices.Count(c.Req.Context()) total := database.Notices.Count(c.Req.Context())
page := c.QueryInt("page") page := c.QueryInt("page")
if page <= 1 { if page <= 1 {
page = 1 page = 1
} }
c.Data["Page"] = paginater.New(int(total), conf.UI.Admin.NoticePagingNum, page, 5) c.Data["Page"] = paginater.New(int(total), conf.UI.Admin.NoticePagingNum, page, 5)
notices, err := db.Notices.List(c.Req.Context(), page, conf.UI.Admin.NoticePagingNum) notices, err := database.Notices.List(c.Req.Context(), page, conf.UI.Admin.NoticePagingNum)
if err != nil { if err != nil {
c.Error(err, "list notices") c.Error(err, "list notices")
return return
@ -53,7 +53,7 @@ func DeleteNotices(c *context.Context) {
} }
} }
if err := db.Notices.DeleteByIDs(c.Req.Context(), ids...); err != nil { if err := database.Notices.DeleteByIDs(c.Req.Context(), ids...); err != nil {
c.Flash.Error("DeleteNoticesByIDs: " + err.Error()) c.Flash.Error("DeleteNoticesByIDs: " + err.Error())
c.Status(http.StatusInternalServerError) c.Status(http.StatusInternalServerError)
} else { } else {
@ -63,7 +63,7 @@ func DeleteNotices(c *context.Context) {
} }
func EmptyNotices(c *context.Context) { func EmptyNotices(c *context.Context) {
if err := db.Notices.DeleteAll(c.Req.Context()); err != nil { if err := database.Notices.DeleteAll(c.Req.Context()); err != nil {
c.Error(err, "delete notices") c.Error(err, "delete notices")
return return
} }

View File

@ -9,7 +9,7 @@ import (
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/context" "gogs.io/gogs/internal/context"
"gogs.io/gogs/internal/db" "gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/route" "gogs.io/gogs/internal/route"
) )
@ -23,12 +23,12 @@ func Organizations(c *context.Context) {
c.Data["PageIsAdminOrganizations"] = true c.Data["PageIsAdminOrganizations"] = true
route.RenderUserSearch(c, &route.UserSearchOptions{ route.RenderUserSearch(c, &route.UserSearchOptions{
Type: db.UserTypeOrganization, Type: database.UserTypeOrganization,
Counter: func(gocontext.Context) int64 { Counter: func(gocontext.Context) int64 {
return db.CountOrganizations() return database.CountOrganizations()
}, },
Ranger: func(_ gocontext.Context, page, pageSize int) ([]*db.User, error) { Ranger: func(_ gocontext.Context, page, pageSize int) ([]*database.User, error) {
return db.Organizations(page, pageSize) return database.Organizations(page, pageSize)
}, },
PageSize: conf.UI.Admin.OrgPagingNum, PageSize: conf.UI.Admin.OrgPagingNum,
OrderBy: "id ASC", OrderBy: "id ASC",

View File

@ -10,7 +10,7 @@ import (
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/context" "gogs.io/gogs/internal/context"
"gogs.io/gogs/internal/db" "gogs.io/gogs/internal/database"
) )
const ( const (
@ -28,21 +28,21 @@ func Repos(c *context.Context) {
} }
var ( var (
repos []*db.Repository repos []*database.Repository
count int64 count int64
err error err error
) )
keyword := c.Query("q") keyword := c.Query("q")
if keyword == "" { if keyword == "" {
repos, err = db.Repositories(page, conf.UI.Admin.RepoPagingNum) repos, err = database.Repositories(page, conf.UI.Admin.RepoPagingNum)
if err != nil { if err != nil {
c.Error(err, "list repositories") c.Error(err, "list repositories")
return return
} }
count = db.CountRepositories(true) count = database.CountRepositories(true)
} else { } else {
repos, count, err = db.SearchRepositoryByName(&db.SearchRepoOptions{ repos, count, err = database.SearchRepositoryByName(&database.SearchRepoOptions{
Keyword: keyword, Keyword: keyword,
OrderBy: "id ASC", OrderBy: "id ASC",
Private: true, Private: true,
@ -58,7 +58,7 @@ func Repos(c *context.Context) {
c.Data["Total"] = count c.Data["Total"] = count
c.Data["Page"] = paginater.New(int(count), conf.UI.Admin.RepoPagingNum, page, 5) c.Data["Page"] = paginater.New(int(count), conf.UI.Admin.RepoPagingNum, page, 5)
if err = db.RepositoryList(repos).LoadAttributes(); err != nil { if err = database.RepositoryList(repos).LoadAttributes(); err != nil {
c.Error(err, "load attributes") c.Error(err, "load attributes")
return return
} }
@ -68,13 +68,13 @@ func Repos(c *context.Context) {
} }
func DeleteRepo(c *context.Context) { func DeleteRepo(c *context.Context) {
repo, err := db.GetRepositoryByID(c.QueryInt64("id")) repo, err := database.GetRepositoryByID(c.QueryInt64("id"))
if err != nil { if err != nil {
c.Error(err, "get repository by ID") c.Error(err, "get repository by ID")
return return
} }
if err := db.DeleteRepository(repo.MustOwner().ID, repo.ID); err != nil { if err := database.DeleteRepository(repo.MustOwner().ID, repo.ID); err != nil {
c.Error(err, "delete repository") c.Error(err, "delete repository")
return return
} }

Some files were not shown because too many files have changed in this diff Show More