Compare commits

..

2 Commits

Author SHA1 Message Date
ᴊᴏᴇ ᴄʜᴇɴ
91a705c6a7 Merge 335aeefbe6 into 295bfba729 2026-02-13 23:21:10 -05:00
Joe Chen
335aeefbe6 all: upgrade to Go 1.26
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 23:21:00 -05:00
164 changed files with 761 additions and 761 deletions

View File

@@ -113,10 +113,10 @@ jobs:
git tag -f "$RELEASE_TAG" git tag -f "$RELEASE_TAG"
git push origin "$RELEASE_TAG" --force || true git push origin "$RELEASE_TAG" --force || true
RELEASE_TITLE="Release archive testing" RELEASE_TITLE="Release Archive Testing"
RELEASE_NOTES="Automated testing release for workflow development." RELEASE_NOTES="Automated testing release for workflow development."
if [ "$RELEASE_TAG" = "latest-commit-build" ]; then if [ "$RELEASE_TAG" = "latest-commit-build" ]; then
RELEASE_TITLE="Latest commit build" RELEASE_TITLE="Latest Commit Build"
RELEASE_NOTES="Automated build from the latest commit on main branch. This release is updated automatically with every push to main." RELEASE_NOTES="Automated build from the latest commit on main branch. This release is updated automatically with every push to main."
fi fi

View File

@@ -4,26 +4,16 @@ All notable changes to Gogs are documented in this file.
## 0.15.0+dev (`main`) ## 0.15.0+dev (`main`)
### Removed
- The `gogs cert` subcommand. [#8153](https://github.com/gogs/gogs/pull/8153)
- The `[email] DISABLE_HELO` configuration option. HELO/EHLO is now always sent during SMTP handshake. [#8164](https://github.com/gogs/gogs/pull/8164)
- Support for MSSQL as a database backend. Stay on 0.14 for continued usage. [#8173](https://github.com/gogs/gogs/pull/8173)
## 0.14.2
### Fixed ### Fixed
- _Security:_ Cross-repository LFS object overwrite via missing content hash verification. [#8166](https://github.com/gogs/gogs/pull/8166) - [GHSA-gmf8-978x-2fg2](https://github.com/gogs/gogs/security/advisories/GHSA-gmf8-978x-2fg2) - _Security:_ Cross-repository LFS object overwrite via missing content hash verification. [#8166](https://github.com/gogs/gogs/pull/8166) - [GHSA-gmf8-978x-2fg2](https://github.com/gogs/gogs/security/advisories/GHSA-gmf8-978x-2fg2)
- _Security:_ Stored XSS via data URI in issue comments. [#8174](https://github.com/gogs/gogs/pull/8174) - [GHSA-xrcr-gmf5-2r8j](https://github.com/gogs/gogs/security/advisories/GHSA-xrcr-gmf5-2r8j)
- _Security:_ Release tag option injection in release deletion. [#8175](https://github.com/gogs/gogs/pull/8175) - [GHSA-v9vm-r24h-6rqm](https://github.com/gogs/gogs/security/advisories/GHSA-v9vm-r24h-6rqm)
- _Security:_ Stored XSS in branch and wiki views through author and committer names. [#8176](https://github.com/gogs/gogs/pull/8176) - [GHSA-vgvf-m4fw-938j](https://github.com/gogs/gogs/security/advisories/GHSA-vgvf-m4fw-938j)
- _Security:_ DOM-based XSS via issue meta selection on the issue page. [#8178](https://github.com/gogs/gogs/pull/8178) - [GHSA-vgjm-2cpf-4g7c](https://github.com/gogs/gogs/security/advisories/GHSA-vgjm-2cpf-4g7c)
- Unable to update files via web editor and API. [#8184](https://github.com/gogs/gogs/pull/8184)
### Removed ### Removed
- Support for passing API access tokens via URL query parameters (`token`, `access_token`). Use the `Authorization` header instead. [#8177](https://github.com/gogs/gogs/pull/8177) - [GHSA-x9p5-w45c-7ffc](https://github.com/gogs/gogs/security/advisories/GHSA-x9p5-w45c-7ffc) - Support for passing API access tokens via URL query parameters (`token`, `access_token`). Use the `Authorization` header instead. [#8177](https://github.com/gogs/gogs/pull/8177) - [GHSA-x9p5-w45c-7ffc](https://github.com/gogs/gogs/security/advisories/GHSA-x9p5-w45c-7ffc)
- The `gogs cert` subcommand. [#8153](https://github.com/gogs/gogs/pull/8153)
- The `[email] DISABLE_HELO` configuration option. HELO/EHLO is now always sent during SMTP handshake. [#8164](https://github.com/gogs/gogs/pull/8164)
- Support for MSSQL as a database backend. Stay on 0.14 for continued usage. [#8173](https://github.com/gogs/gogs/pull/8173)
## 0.14.1 ## 0.14.1

View File

@@ -1,4 +1,4 @@
FROM golang:1.26-alpine3.23 AS binarybuilder FROM golang:alpine3.21 AS binarybuilder
RUN apk --no-cache --no-progress add --virtual \ RUN apk --no-cache --no-progress add --virtual \
build-deps \ build-deps \
build-base \ build-base \
@@ -11,7 +11,7 @@ COPY . .
RUN ./docker/build/install-task.sh RUN ./docker/build/install-task.sh
RUN TAGS="cert pam" task build RUN TAGS="cert pam" task build
FROM alpine:3.23 FROM alpine:3.21
RUN apk --no-cache --no-progress add \ RUN apk --no-cache --no-progress add \
bash \ bash \
ca-certificates \ ca-certificates \

View File

@@ -1,4 +1,4 @@
FROM golang:1.26-alpine3.23 AS binarybuilder FROM golang:alpine3.23 AS binarybuilder
RUN apk --no-cache --no-progress add --virtual \ RUN apk --no-cache --no-progress add --virtual \
build-deps \ build-deps \
build-base \ build-base \

View File

@@ -17,7 +17,7 @@ import (
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/database" "gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/osx" "gogs.io/gogs/internal/osutil"
) )
var backupCommand = cli.Command{ var backupCommand = cli.Command{
@@ -59,7 +59,7 @@ func runBackup(ctx context.Context, cmd *cli.Command) error {
} }
tmpDir := cmd.String("tempdir") tmpDir := cmd.String("tempdir")
if !osx.Exist(tmpDir) { if !osutil.Exist(tmpDir) {
log.Fatal("'--tempdir' does not exist: %s", tmpDir) log.Fatal("'--tempdir' does not exist: %s", tmpDir)
} }
rootDir, err := os.MkdirTemp(tmpDir, "gogs-backup-") rootDir, err := os.MkdirTemp(tmpDir, "gogs-backup-")
@@ -108,7 +108,7 @@ func runBackup(ctx context.Context, cmd *cli.Command) error {
// Data files // Data files
for _, dir := range []string{"ssh", "attachments", "avatars", "repo-avatars"} { for _, dir := range []string{"ssh", "attachments", "avatars", "repo-avatars"} {
dirPath := filepath.Join(conf.Server.AppDataPath, dir) dirPath := filepath.Join(conf.Server.AppDataPath, dir)
if !osx.IsDir(dirPath) { if !osutil.IsDir(dirPath) {
continue continue
} }

View File

@@ -22,7 +22,7 @@ import (
"gogs.io/gogs/internal/database" "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"
"gogs.io/gogs/internal/osx" "gogs.io/gogs/internal/osutil"
) )
var ( var (
@@ -133,7 +133,7 @@ func runHookPreReceive(_ context.Context, cmd *cli.Command) error {
} }
customHooksPath := filepath.Join(os.Getenv(database.EnvRepoCustomHooksPath), "pre-receive") customHooksPath := filepath.Join(os.Getenv(database.EnvRepoCustomHooksPath), "pre-receive")
if !osx.IsFile(customHooksPath) { if !osutil.IsFile(customHooksPath) {
return nil return nil
} }
@@ -167,7 +167,7 @@ func runHookUpdate(_ context.Context, cmd *cli.Command) error {
} }
customHooksPath := filepath.Join(os.Getenv(database.EnvRepoCustomHooksPath), "update") customHooksPath := filepath.Join(os.Getenv(database.EnvRepoCustomHooksPath), "update")
if !osx.IsFile(customHooksPath) { if !osutil.IsFile(customHooksPath) {
return nil return nil
} }
@@ -252,7 +252,7 @@ func runHookPostReceive(_ context.Context, cmd *cli.Command) error {
} }
customHooksPath := filepath.Join(os.Getenv(database.EnvRepoCustomHooksPath), "post-receive") customHooksPath := filepath.Join(os.Getenv(database.EnvRepoCustomHooksPath), "post-receive")
if !osx.IsFile(customHooksPath) { if !osutil.IsFile(customHooksPath) {
return nil return nil
} }

View File

@@ -13,7 +13,7 @@ import (
"github.com/urfave/cli/v3" "github.com/urfave/cli/v3"
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/osx" "gogs.io/gogs/internal/osutil"
) )
var ( var (
@@ -45,9 +45,9 @@ func runImportLocale(_ context.Context, cmd *cli.Command) error {
} else if !cmd.IsSet("target") { } else if !cmd.IsSet("target") {
return errors.New("target directory is not specified") return errors.New("target directory is not specified")
} }
if !osx.IsDir(cmd.String("source")) { if !osutil.IsDir(cmd.String("source")) {
return errors.Newf("source directory %q does not exist or is not a directory", cmd.String("source")) return errors.Newf("source directory %q does not exist or is not a directory", cmd.String("source"))
} else if !osx.IsDir(cmd.String("target")) { } else if !osutil.IsDir(cmd.String("target")) {
return errors.Newf("target directory %q does not exist or is not a directory", cmd.String("target")) return errors.Newf("target directory %q does not exist or is not a directory", cmd.String("target"))
} }
@@ -67,7 +67,7 @@ func runImportLocale(_ context.Context, cmd *cli.Command) error {
name := fmt.Sprintf("locale_%s.ini", lang) name := fmt.Sprintf("locale_%s.ini", lang)
source := filepath.Join(cmd.String("source"), name) source := filepath.Join(cmd.String("source"), name)
target := filepath.Join(cmd.String("target"), name) target := filepath.Join(cmd.String("target"), name)
if !osx.IsFile(source) { if !osutil.IsFile(source) {
continue continue
} }

View File

@@ -14,8 +14,8 @@ import (
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/database" "gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/osx" "gogs.io/gogs/internal/osutil"
"gogs.io/gogs/internal/semverx" "gogs.io/gogs/internal/semverutil"
) )
var restoreCommand = cli.Command{ var restoreCommand = cli.Command{
@@ -46,7 +46,7 @@ func runRestore(ctx context.Context, cmd *cli.Command) error {
zip.Verbose = cmd.Bool("verbose") zip.Verbose = cmd.Bool("verbose")
tmpDir := cmd.String("tempdir") tmpDir := cmd.String("tempdir")
if !osx.IsDir(tmpDir) { if !osutil.IsDir(tmpDir) {
log.Fatal("'--tempdir' does not exist: %s", tmpDir) log.Fatal("'--tempdir' does not exist: %s", tmpDir)
} }
archivePath := path.Join(tmpDir, archiveRootDir) archivePath := path.Join(tmpDir, archiveRootDir)
@@ -66,7 +66,7 @@ func runRestore(ctx context.Context, cmd *cli.Command) error {
// Check backup version // Check backup version
metaFile := filepath.Join(archivePath, "metadata.ini") metaFile := filepath.Join(archivePath, "metadata.ini")
if !osx.IsFile(metaFile) { if !osutil.IsFile(metaFile) {
log.Fatal("File 'metadata.ini' is missing") log.Fatal("File 'metadata.ini' is missing")
} }
metadata, err := ini.Load(metaFile) metadata, err := ini.Load(metaFile)
@@ -74,7 +74,7 @@ func runRestore(ctx context.Context, cmd *cli.Command) error {
log.Fatal("Failed to load metadata '%s': %v", metaFile, err) log.Fatal("Failed to load metadata '%s': %v", metaFile, err)
} }
backupVersion := metadata.Section("").Key("GOGS_VERSION").MustString("999.0") backupVersion := metadata.Section("").Key("GOGS_VERSION").MustString("999.0")
if semverx.Compare(conf.App.Version, "<", backupVersion) { if semverutil.Compare(conf.App.Version, "<", backupVersion) {
log.Fatal("Current Gogs version is lower than backup version: %s < %s", conf.App.Version, backupVersion) log.Fatal("Current Gogs version is lower than backup version: %s < %s", conf.App.Version, backupVersion)
} }
formatVersion := metadata.Section("").Key("VERSION").MustInt() formatVersion := metadata.Section("").Key("VERSION").MustInt()
@@ -92,7 +92,7 @@ func runRestore(ctx context.Context, cmd *cli.Command) error {
var customConf string var customConf string
if lineageConf := configFromLineage(cmd); lineageConf != "" { if lineageConf := configFromLineage(cmd); lineageConf != "" {
customConf = lineageConf customConf = lineageConf
} else if !osx.IsFile(configFile) { } else if !osutil.IsFile(configFile) {
log.Fatal("'--config' is not specified and custom config file is not found in backup") log.Fatal("'--config' is not specified and custom config file is not found in backup")
} else { } else {
customConf = configFile customConf = configFile
@@ -117,7 +117,7 @@ func runRestore(ctx context.Context, cmd *cli.Command) error {
if !cmd.Bool("database-only") { if !cmd.Bool("database-only") {
// Custom files // Custom files
if osx.IsDir(conf.CustomDir()) { if osutil.IsDir(conf.CustomDir()) {
if err = os.Rename(conf.CustomDir(), conf.CustomDir()+".bak"); err != nil { if err = os.Rename(conf.CustomDir(), conf.CustomDir()+".bak"); err != nil {
log.Fatal("Failed to backup current 'custom': %v", err) log.Fatal("Failed to backup current 'custom': %v", err)
} }
@@ -131,12 +131,12 @@ func runRestore(ctx context.Context, cmd *cli.Command) error {
for _, dir := range []string{"attachments", "avatars", "repo-avatars"} { for _, dir := range []string{"attachments", "avatars", "repo-avatars"} {
// Skip if backup archive does not have corresponding data // Skip if backup archive does not have corresponding data
srcPath := filepath.Join(archivePath, "data", dir) srcPath := filepath.Join(archivePath, "data", dir)
if !osx.IsDir(srcPath) { if !osutil.IsDir(srcPath) {
continue continue
} }
dirPath := filepath.Join(conf.Server.AppDataPath, dir) dirPath := filepath.Join(conf.Server.AppDataPath, dir)
if osx.IsDir(dirPath) { if osutil.IsDir(dirPath) {
if err = os.Rename(dirPath, dirPath+".bak"); err != nil { if err = os.Rename(dirPath, dirPath+".bak"); err != nil {
log.Fatal("Failed to backup current 'data': %v", err) log.Fatal("Failed to backup current 'data': %v", err)
} }
@@ -149,7 +149,7 @@ func runRestore(ctx context.Context, cmd *cli.Command) error {
// Repositories // Repositories
reposPath := filepath.Join(archivePath, "repositories.zip") reposPath := filepath.Join(archivePath, "repositories.zip")
if !cmd.Bool("exclude-repos") && !cmd.Bool("database-only") && osx.IsFile(reposPath) { if !cmd.Bool("exclude-repos") && !cmd.Bool("database-only") && osutil.IsFile(reposPath) {
if err := zip.ExtractTo(reposPath, filepath.Dir(conf.Repository.Root)); err != nil { if err := zip.ExtractTo(reposPath, filepath.Dir(conf.Repository.Root)); err != nil {
log.Fatal("Failed to extract 'repositories.zip': %v", err) log.Fatal("Failed to extract 'repositories.zip': %v", err)
} }

View File

@@ -31,7 +31,7 @@ import (
"gogs.io/gogs/internal/context" "gogs.io/gogs/internal/context"
"gogs.io/gogs/internal/database" "gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/form" "gogs.io/gogs/internal/form"
"gogs.io/gogs/internal/osx" "gogs.io/gogs/internal/osutil"
"gogs.io/gogs/internal/route" "gogs.io/gogs/internal/route"
"gogs.io/gogs/internal/route/admin" "gogs.io/gogs/internal/route/admin"
apiv1 "gogs.io/gogs/internal/route/api/v1" apiv1 "gogs.io/gogs/internal/route/api/v1"
@@ -308,7 +308,7 @@ func runWeb(_ stdctx.Context, cmd *cli.Command) error {
if err != nil { if err != nil {
c.NotFoundOrError(err, "get attachment by UUID") c.NotFoundOrError(err, "get attachment by UUID")
return return
} else if !osx.IsFile(attach.LocalPath()) { } else if !osutil.IsFile(attach.LocalPath()) {
c.NotFound() c.NotFound()
return return
} }
@@ -750,7 +750,7 @@ func runWeb(_ stdctx.Context, cmd *cli.Command) error {
err = fcgi.Serve(nil, m) err = fcgi.Serve(nil, m)
case "unix": case "unix":
if osx.Exist(listenAddr) { if osutil.Exist(listenAddr) {
err = os.Remove(listenAddr) err = os.Remove(listenAddr)
if err != nil { if err != nil {
log.Fatal("Failed to remove existing Unix domain socket: %v", err) log.Fatal("Failed to remove existing Unix domain socket: %v", err)

2
go.mod
View File

@@ -21,7 +21,7 @@ require (
github.com/go-macaron/toolbox v0.0.0-20190813233741-94defb8383c6 github.com/go-macaron/toolbox v0.0.0-20190813233741-94defb8383c6
github.com/gogs/chardet v0.0.0-20150115103509-2404f7772561 github.com/gogs/chardet v0.0.0-20150115103509-2404f7772561
github.com/gogs/cron v0.0.0-20171120032916-9f6c956d3e14 github.com/gogs/cron v0.0.0-20171120032916-9f6c956d3e14
github.com/gogs/git-module v1.8.7 github.com/gogs/git-module v1.8.6
github.com/gogs/go-libravatar v0.0.0-20191106065024-33a75213d0a0 github.com/gogs/go-libravatar v0.0.0-20191106065024-33a75213d0a0
github.com/gogs/minwinsvc v0.0.0-20170301035411-95be6356811a github.com/gogs/minwinsvc v0.0.0-20170301035411-95be6356811a
github.com/google/go-github v17.0.0+incompatible github.com/google/go-github v17.0.0+incompatible

4
go.sum
View File

@@ -142,8 +142,8 @@ github.com/gogs/chardet v0.0.0-20150115103509-2404f7772561 h1:aBzukfDxQlCTVS0NBU
github.com/gogs/chardet v0.0.0-20150115103509-2404f7772561/go.mod h1:Pcatq5tYkCW2Q6yrR2VRHlbHpZ/R4/7qyL1TCF7vl14= github.com/gogs/chardet v0.0.0-20150115103509-2404f7772561/go.mod h1:Pcatq5tYkCW2Q6yrR2VRHlbHpZ/R4/7qyL1TCF7vl14=
github.com/gogs/cron v0.0.0-20171120032916-9f6c956d3e14 h1:yXtpJr/LV6PFu4nTLgfjQdcMdzjbqqXMEnHfq0Or6p8= github.com/gogs/cron v0.0.0-20171120032916-9f6c956d3e14 h1:yXtpJr/LV6PFu4nTLgfjQdcMdzjbqqXMEnHfq0Or6p8=
github.com/gogs/cron v0.0.0-20171120032916-9f6c956d3e14/go.mod h1:jPoNZLWDAqA5N3G5amEoiNbhVrmM+ZQEcnQvNQ2KaZk= github.com/gogs/cron v0.0.0-20171120032916-9f6c956d3e14/go.mod h1:jPoNZLWDAqA5N3G5amEoiNbhVrmM+ZQEcnQvNQ2KaZk=
github.com/gogs/git-module v1.8.7 h1:GDyfzB1Z8ytld3LajTfUE4PuIcGcuCHpWB6j8/oD7Tk= github.com/gogs/git-module v1.8.6 h1:4Io9vWZYQyIjdIPxfKgeYZXnDKNgydc6OZTxII5xCH4=
github.com/gogs/git-module v1.8.7/go.mod h1:IiMSJqi8XH62Kjqjt5Rw8IawSo+DHfM2dDjkSzWLjhs= github.com/gogs/git-module v1.8.6/go.mod h1:IiMSJqi8XH62Kjqjt5Rw8IawSo+DHfM2dDjkSzWLjhs=
github.com/gogs/go-libravatar v0.0.0-20191106065024-33a75213d0a0 h1:K02vod+sn3M1OOkdqi2tPxN2+xESK4qyITVQ3JkGEv4= github.com/gogs/go-libravatar v0.0.0-20191106065024-33a75213d0a0 h1:K02vod+sn3M1OOkdqi2tPxN2+xESK4qyITVQ3JkGEv4=
github.com/gogs/go-libravatar v0.0.0-20191106065024-33a75213d0a0/go.mod h1:Zas3BtO88pk1cwUfEYlvnl/CRwh0ybDxRWSwRjG8I3w= github.com/gogs/go-libravatar v0.0.0-20191106065024-33a75213d0a0/go.mod h1:Zas3BtO88pk1cwUfEYlvnl/CRwh0ybDxRWSwRjG8I3w=
github.com/gogs/minwinsvc v0.0.0-20170301035411-95be6356811a h1:8DZwxETOVWIinYxDK+i6L+rMb7eGATGaakD6ZucfHVk= github.com/gogs/minwinsvc v0.0.0-20170301035411-95be6356811a h1:8DZwxETOVWIinYxDK+i6L+rMb7eGATGaakD6ZucfHVk=

View File

@@ -5,7 +5,7 @@ import (
"gopkg.in/macaron.v1" "gopkg.in/macaron.v1"
"gogs.io/gogs/internal/authx" "gogs.io/gogs/internal/authutil"
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
) )
@@ -20,7 +20,7 @@ func MetricsFilter() macaron.Handler {
return return
} }
username, password := authx.DecodeBasic(r.Header) username, password := authutil.DecodeBasic(r.Header)
if username != conf.Prometheus.BasicAuthUsername || password != conf.Prometheus.BasicAuthPassword { if username != conf.Prometheus.BasicAuthUsername || password != conf.Prometheus.BasicAuthPassword {
w.WriteHeader(http.StatusForbidden) w.WriteHeader(http.StatusForbidden)
return return

View File

@@ -5,7 +5,7 @@ import (
"github.com/cockroachdb/errors" "github.com/cockroachdb/errors"
"gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/errutil"
) )
type Type int type Type int
@@ -34,10 +34,10 @@ func Name(typ Type) string {
}[typ] }[typ]
} }
var _ errx.NotFound = (*ErrBadCredentials)(nil) var _ errutil.NotFound = (*ErrBadCredentials)(nil)
type ErrBadCredentials struct { type ErrBadCredentials struct {
Args errx.Args Args errutil.Args
} }
// IsErrBadCredentials returns true if the underlying error has the type // IsErrBadCredentials returns true if the underlying error has the type

View File

@@ -1,4 +1,4 @@
package authx package authutil
import ( import (
"encoding/base64" "encoding/base64"

View File

@@ -1,4 +1,4 @@
package authx package authutil
import ( import (
"net/http" "net/http"

View File

@@ -7,7 +7,7 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"gogs.io/gogs/internal/testx" "gogs.io/gogs/internal/testutil"
) )
func TestIsProdMode(t *testing.T) { func TestIsProdMode(t *testing.T) {
@@ -36,7 +36,7 @@ func TestIsProdMode(t *testing.T) {
} }
func TestWorkDirHelper(_ *testing.T) { func TestWorkDirHelper(_ *testing.T) {
if !testx.WantHelperProcess() { if !testutil.WantHelperProcess() {
return return
} }
@@ -53,7 +53,7 @@ func TestWorkDir(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
t.Run("", func(t *testing.T) { t.Run("", func(t *testing.T) {
out, err := testx.Exec("TestWorkDirHelper", test.env) out, err := testutil.Exec("TestWorkDirHelper", test.env)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -64,7 +64,7 @@ func TestWorkDir(t *testing.T) {
} }
func TestCustomDirHelper(_ *testing.T) { func TestCustomDirHelper(_ *testing.T) {
if !testx.WantHelperProcess() { if !testutil.WantHelperProcess() {
return return
} }
@@ -81,7 +81,7 @@ func TestCustomDir(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
t.Run("", func(t *testing.T) { t.Run("", func(t *testing.T) {
out, err := testx.Exec("TestCustomDirHelper", test.env) out, err := testutil.Exec("TestCustomDirHelper", test.env)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -92,7 +92,7 @@ func TestCustomDir(t *testing.T) {
} }
func TestHomeDirHelper(_ *testing.T) { func TestHomeDirHelper(_ *testing.T) {
if !testx.WantHelperProcess() { if !testutil.WantHelperProcess() {
return return
} }
@@ -111,7 +111,7 @@ func TestHomeDir(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
t.Run("", func(t *testing.T) { t.Run("", func(t *testing.T) {
out, err := testx.Exec("TestHomeDirHelper", test.envs...) out, err := testutil.Exec("TestHomeDirHelper", test.envs...)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View File

@@ -18,8 +18,8 @@ import (
log "unknwon.dev/clog/v2" log "unknwon.dev/clog/v2"
"gogs.io/gogs/conf" "gogs.io/gogs/conf"
"gogs.io/gogs/internal/osx" "gogs.io/gogs/internal/osutil"
"gogs.io/gogs/internal/semverx" "gogs.io/gogs/internal/semverutil"
) )
func init() { func init() {
@@ -66,7 +66,7 @@ func Init(customConf string) error {
} }
CustomConf = customConf CustomConf = customConf
if osx.IsFile(customConf) { if osutil.IsFile(customConf) {
if err = File.Append(customConf); err != nil { if err = File.Append(customConf); err != nil {
return errors.Wrapf(err, "append %q", customConf) return errors.Wrapf(err, "append %q", customConf)
} }
@@ -141,7 +141,7 @@ func Init(customConf string) error {
return errors.Wrap(err, "get OpenSSH version") return errors.Wrap(err, "get OpenSSH version")
} }
if IsWindowsRuntime() || semverx.Compare(sshVersion, "<", "5.1") { if IsWindowsRuntime() || semverutil.Compare(sshVersion, "<", "5.1") {
if !HookMode { if !HookMode {
log.Warn(`SSH minimum key size check is forced to be disabled because server is not eligible: log.Warn(`SSH minimum key size check is forced to be disabled because server is not eligible:
1. Windows server 1. Windows server
@@ -383,7 +383,7 @@ func Init(customConf string) error {
return errors.Wrap(err, "mapping [other] section") return errors.Wrap(err, "mapping [other] section")
} }
HasRobotsTxt = osx.IsFile(filepath.Join(CustomDir(), "robots.txt")) HasRobotsTxt = osutil.IsFile(filepath.Join(CustomDir(), "robots.txt"))
return nil return nil
} }

View File

@@ -8,7 +8,7 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"gopkg.in/ini.v1" "gopkg.in/ini.v1"
"gogs.io/gogs/internal/testx" "gogs.io/gogs/internal/testutil"
) )
func TestInit(t *testing.T) { func TestInit(t *testing.T) {
@@ -55,5 +55,5 @@ func TestInit(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
testx.AssertGolden(t, filepath.Join("testdata", "TestInit.golden.ini"), testx.Update("TestInit"), buf.String()) testutil.AssertGolden(t, filepath.Join("testdata", "TestInit.golden.ini"), testutil.Update("TestInit"), buf.String())
} }

View File

@@ -6,7 +6,7 @@ import (
"github.com/cockroachdb/errors" "github.com/cockroachdb/errors"
"gogs.io/gogs/internal/osx" "gogs.io/gogs/internal/osutil"
"gogs.io/gogs/internal/process" "gogs.io/gogs/internal/process"
) )
@@ -44,6 +44,6 @@ func CheckRunUser(runUser string) (string, bool) {
return "", true return "", true
} }
currentUser := osx.CurrentUsername() currentUser := osutil.CurrentUsername()
return currentUser, runUser == currentUser return currentUser, runUser == currentUser
} }

View File

@@ -11,7 +11,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/errx" "gogs.io/gogs/internal/errutil"
) )
type APIContext struct { type APIContext struct {
@@ -62,7 +62,7 @@ func (c *APIContext) Errorf(err error, format string, args ...any) {
// is about not found. It responses with 404 status code for not found error, // is about not found. It responses with 404 status code for not found error,
// or error context description for logging purpose of 500 server error. // or error context description for logging purpose of 500 server error.
func (c *APIContext) NotFoundOrError(err error, msg string) { func (c *APIContext) NotFoundOrError(err error, msg string) {
if errx.IsNotFound(err) { if errutil.IsNotFound(err) {
c.NotFound() c.NotFound()
return return
} }

View File

@@ -16,7 +16,7 @@ import (
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/database" "gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/errx" "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"
"gogs.io/gogs/internal/template" "gogs.io/gogs/internal/template"
@@ -182,7 +182,7 @@ func (c *Context) Errorf(err error, format string, args ...any) {
// NotFoundOrError responses with 404 page for not found error and 500 page otherwise. // NotFoundOrError responses with 404 page for not found error and 500 page otherwise.
func (c *Context) NotFoundOrError(err error, msg string) { func (c *Context) NotFoundOrError(err error, msg string) {
if errx.IsNotFound(err) { if errutil.IsNotFound(err) {
c.NotFound() c.NotFound()
return return
} }

View File

@@ -10,7 +10,7 @@ import (
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/database" "gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/repox" "gogs.io/gogs/internal/repoutil"
) )
// ServeGoGet does quick responses for appropriate go-get meta with status OK // ServeGoGet does quick responses for appropriate go-get meta with status OK
@@ -53,7 +53,7 @@ func ServeGoGet() macaron.Handler {
`, `,
map[string]string{ map[string]string{
"GoGetImport": path.Join(conf.Server.URL.Host, conf.Server.Subpath, ownerName, repoName), "GoGetImport": path.Join(conf.Server.URL.Host, conf.Server.Subpath, ownerName, repoName),
"CloneLink": repox.HTTPSCloneURL(ownerName, repoName), "CloneLink": repoutil.HTTPSCloneURL(ownerName, repoName),
"GoDocDirectory": prefix + "{/dir}", "GoDocDirectory": prefix + "{/dir}",
"GoDocFile": prefix + "{/dir}/{file}#L{line}", "GoDocFile": prefix + "{/dir}/{file}#L{line}",
"InsecureFlag": insecureFlag, "InsecureFlag": insecureFlag,

View File

@@ -8,7 +8,7 @@ import (
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/markup" "gogs.io/gogs/internal/markup"
"gogs.io/gogs/internal/osx" "gogs.io/gogs/internal/osutil"
"gogs.io/gogs/internal/tool" "gogs.io/gogs/internal/tool"
) )
@@ -16,7 +16,7 @@ import (
// on all pages. // on all pages.
func (c *Context) renderNoticeBanner() { func (c *Context) renderNoticeBanner() {
fpath := filepath.Join(conf.CustomDir(), "notice", "banner.md") fpath := filepath.Join(conf.CustomDir(), "notice", "banner.md")
if !osx.Exist(fpath) { if !osutil.Exist(fpath) {
return return
} }

View File

@@ -14,7 +14,7 @@ import (
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/database" "gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/repox" "gogs.io/gogs/internal/repoutil"
) )
type PullRequest struct { type PullRequest struct {
@@ -40,7 +40,7 @@ type Repository struct {
TreePath string TreePath string
CommitID string CommitID string
RepoLink string RepoLink string
CloneLink repox.CloneLink CloneLink repoutil.CloneLink
CommitsCount int64 CommitsCount int64
Mirror *database.Mirror Mirror *database.Mirror

View File

@@ -1,4 +1,4 @@
package cryptox package cryptoutil
import ( import (
"crypto/aes" "crypto/aes"

View File

@@ -1,4 +1,4 @@
package cryptox package cryptoutil
import ( import (
"crypto/rand" "crypto/rand"

View File

@@ -1,4 +1,4 @@
package cryptox package cryptoutil
import ( import (
"crypto/md5" "crypto/md5"

View File

@@ -1,4 +1,4 @@
package cryptox package cryptoutil
import ( import (
"testing" "testing"

View File

@@ -1,4 +1,4 @@
package cryptox package cryptoutil
import ( import (
"crypto/sha1" "crypto/sha1"

View File

@@ -1,4 +1,4 @@
package cryptox package cryptoutil
import ( import (
"testing" "testing"

View File

@@ -9,8 +9,8 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
"gorm.io/gorm" "gorm.io/gorm"
"gogs.io/gogs/internal/cryptox" "gogs.io/gogs/internal/cryptoutil"
"gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/errutil"
) )
// AccessToken is a personal access token. // AccessToken is a personal access token.
@@ -58,7 +58,7 @@ func newAccessTokensStore(db *gorm.DB) *AccessTokensStore {
} }
type ErrAccessTokenAlreadyExist struct { type ErrAccessTokenAlreadyExist struct {
args errx.Args args errutil.Args
} }
func IsErrAccessTokenAlreadyExist(err error) bool { func IsErrAccessTokenAlreadyExist(err error) bool {
@@ -75,13 +75,13 @@ func (err ErrAccessTokenAlreadyExist) Error() string {
func (s *AccessTokensStore) Create(ctx context.Context, userID int64, name string) (*AccessToken, error) { func (s *AccessTokensStore) Create(ctx context.Context, userID int64, name string) (*AccessToken, error) {
err := s.db.WithContext(ctx).Where("uid = ? AND name = ?", userID, name).First(new(AccessToken)).Error err := s.db.WithContext(ctx).Where("uid = ? AND name = ?", userID, name).First(new(AccessToken)).Error
if err == nil { if err == nil {
return nil, ErrAccessTokenAlreadyExist{args: errx.Args{"userID": userID, "name": name}} return nil, ErrAccessTokenAlreadyExist{args: errutil.Args{"userID": userID, "name": name}}
} else if !errors.Is(err, gorm.ErrRecordNotFound) { } else if !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, err return nil, err
} }
token := cryptox.SHA1(uuid.New().String()) token := cryptoutil.SHA1(uuid.New().String())
sha256 := cryptox.SHA256(token) sha256 := cryptoutil.SHA256(token)
accessToken := &AccessToken{ accessToken := &AccessToken{
UserID: userID, UserID: userID,
@@ -106,10 +106,10 @@ func (s *AccessTokensStore) DeleteByID(ctx context.Context, userID, id int64) er
return s.db.WithContext(ctx).Where("id = ? AND uid = ?", id, userID).Delete(new(AccessToken)).Error return s.db.WithContext(ctx).Where("id = ? AND uid = ?", id, userID).Delete(new(AccessToken)).Error
} }
var _ errx.NotFound = (*ErrAccessTokenNotExist)(nil) var _ errutil.NotFound = (*ErrAccessTokenNotExist)(nil)
type ErrAccessTokenNotExist struct { type ErrAccessTokenNotExist struct {
args errx.Args args errutil.Args
} }
// IsErrAccessTokenNotExist returns true if the underlying error has the type // IsErrAccessTokenNotExist returns true if the underlying error has the type
@@ -131,14 +131,14 @@ func (ErrAccessTokenNotExist) NotFound() bool {
func (s *AccessTokensStore) GetBySHA1(ctx context.Context, sha1 string) (*AccessToken, error) { func (s *AccessTokensStore) GetBySHA1(ctx context.Context, sha1 string) (*AccessToken, error) {
// No need to waste a query for an empty SHA1. // No need to waste a query for an empty SHA1.
if sha1 == "" { if sha1 == "" {
return nil, ErrAccessTokenNotExist{args: errx.Args{"sha": sha1}} return nil, ErrAccessTokenNotExist{args: errutil.Args{"sha": sha1}}
} }
sha256 := cryptox.SHA256(sha1) sha256 := cryptoutil.SHA256(sha1)
token := new(AccessToken) token := new(AccessToken)
err := s.db.WithContext(ctx).Where("sha256 = ?", sha256).First(token).Error err := s.db.WithContext(ctx).Where("sha256 = ?", sha256).First(token).Error
if errors.Is(err, gorm.ErrRecordNotFound) { if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrAccessTokenNotExist{args: errx.Args{"sha": sha1}} return nil, ErrAccessTokenNotExist{args: errutil.Args{"sha": sha1}}
} else if err != nil { } else if err != nil {
return nil, err return nil, err
} }

View File

@@ -9,7 +9,7 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"gorm.io/gorm" "gorm.io/gorm"
"gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/errutil"
) )
func TestAccessToken_BeforeCreate(t *testing.T) { func TestAccessToken_BeforeCreate(t *testing.T) {
@@ -138,7 +138,7 @@ func accessTokensCreate(t *testing.T, ctx context.Context, s *AccessTokensStore)
// Try create second access token with same name should fail // Try create second access token with same name should fail
_, err = s.Create(ctx, token.UserID, token.Name) _, err = s.Create(ctx, token.UserID, token.Name)
wantErr := ErrAccessTokenAlreadyExist{ wantErr := ErrAccessTokenAlreadyExist{
args: errx.Args{ args: errutil.Args{
"userID": token.UserID, "userID": token.UserID,
"name": token.Name, "name": token.Name,
}, },
@@ -166,7 +166,7 @@ func accessTokensDeleteByID(t *testing.T, ctx context.Context, s *AccessTokensSt
// We should get token not found error // We should get token not found error
_, err = s.GetBySHA1(ctx, token.Sha1) _, err = s.GetBySHA1(ctx, token.Sha1)
wantErr := ErrAccessTokenNotExist{ wantErr := ErrAccessTokenNotExist{
args: errx.Args{ args: errutil.Args{
"sha": token.Sha1, "sha": token.Sha1,
}, },
} }
@@ -185,7 +185,7 @@ func accessTokensGetBySHA(t *testing.T, ctx context.Context, s *AccessTokensStor
// Try to get a non-existent token // Try to get a non-existent token
_, err = s.GetBySHA1(ctx, "bad_sha") _, err = s.GetBySHA1(ctx, "bad_sha")
wantErr := ErrAccessTokenNotExist{ wantErr := ErrAccessTokenNotExist{
args: errx.Args{ args: errutil.Args{
"sha": "bad_sha", "sha": "bad_sha",
}, },
} }

View File

@@ -17,10 +17,10 @@ import (
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/lazyregexp" "gogs.io/gogs/internal/lazyregexp"
"gogs.io/gogs/internal/repox" "gogs.io/gogs/internal/repoutil"
apiv1types "gogs.io/gogs/internal/route/api/v1/types" apiv1types "gogs.io/gogs/internal/route/api/v1/types"
"gogs.io/gogs/internal/strx" "gogs.io/gogs/internal/strutil"
"gogs.io/gogs/internal/testx" "gogs.io/gogs/internal/testutil"
"gogs.io/gogs/internal/tool" "gogs.io/gogs/internal/tool"
) )
@@ -218,14 +218,14 @@ func (s *ActionsStore) MirrorSyncPush(ctx context.Context, opts MirrorSyncPushOp
apiCommits, err := opts.Commits.APIFormat(ctx, apiCommits, err := opts.Commits.APIFormat(ctx,
newUsersStore(s.db), newUsersStore(s.db),
repox.RepositoryPath(opts.Owner.Name, opts.Repo.Name), repoutil.RepositoryPath(opts.Owner.Name, opts.Repo.Name),
repox.HTMLURL(opts.Owner.Name, opts.Repo.Name), repoutil.HTMLURL(opts.Owner.Name, opts.Repo.Name),
) )
if err != nil { if err != nil {
return errors.Wrap(err, "convert commits to API format") return errors.Wrap(err, "convert commits to API format")
} }
opts.Commits.CompareURL = repox.CompareCommitsPath(opts.Owner.Name, opts.Repo.Name, opts.OldCommitID, opts.NewCommitID) opts.Commits.CompareURL = repoutil.CompareCommitsPath(opts.Owner.Name, opts.Repo.Name, opts.OldCommitID, opts.NewCommitID)
apiPusher := opts.Owner.APIFormat() apiPusher := opts.Owner.APIFormat()
err = PrepareWebhooks( err = PrepareWebhooks(
opts.Repo, opts.Repo,
@@ -476,7 +476,7 @@ func (s *ActionsStore) CommitRepo(ctx context.Context, opts CommitRepoOptions) e
// If not the first commit, set the compare URL. // If not the first commit, set the compare URL.
if !isNewRef && !isDelRef { if !isNewRef && !isDelRef {
opts.Commits.CompareURL = repox.CompareCommitsPath(opts.Owner.Name, opts.Repo.Name, opts.OldCommitID, opts.NewCommitID) opts.Commits.CompareURL = repoutil.CompareCommitsPath(opts.Owner.Name, opts.Repo.Name, opts.OldCommitID, opts.NewCommitID)
} }
refName := git.RefShortName(opts.RefFullName) refName := git.RefShortName(opts.RefFullName)
@@ -563,8 +563,8 @@ func (s *ActionsStore) CommitRepo(ctx context.Context, opts CommitRepoOptions) e
commits, err := opts.Commits.APIFormat(ctx, commits, err := opts.Commits.APIFormat(ctx,
newUsersStore(s.db), newUsersStore(s.db),
repox.RepositoryPath(opts.Owner.Name, opts.Repo.Name), repoutil.RepositoryPath(opts.Owner.Name, opts.Repo.Name),
repox.HTMLURL(opts.Owner.Name, opts.Repo.Name), repoutil.HTMLURL(opts.Owner.Name, opts.Repo.Name),
) )
if err != nil { if err != nil {
return errors.Wrap(err, "convert commits to API format") return errors.Wrap(err, "convert commits to API format")
@@ -751,7 +751,7 @@ func (a *Action) GetActUserName() string {
} }
func (a *Action) ShortActUserName() string { func (a *Action) ShortActUserName() string {
return strx.Ellipsis(a.ActUserName, 20) return strutil.Ellipsis(a.ActUserName, 20)
} }
func (a *Action) GetRepoUserName() string { func (a *Action) GetRepoUserName() string {
@@ -759,7 +759,7 @@ func (a *Action) GetRepoUserName() string {
} }
func (a *Action) ShortRepoUserName() string { func (a *Action) ShortRepoUserName() string {
return strx.Ellipsis(a.RepoUserName, 20) return strutil.Ellipsis(a.RepoUserName, 20)
} }
func (a *Action) GetRepoName() string { func (a *Action) GetRepoName() string {
@@ -767,7 +767,7 @@ func (a *Action) GetRepoName() string {
} }
func (a *Action) ShortRepoName() string { func (a *Action) ShortRepoName() string {
return strx.Ellipsis(a.RepoName, 33) return strutil.Ellipsis(a.RepoName, 33)
} }
func (a *Action) GetRepoPath() string { func (a *Action) GetRepoPath() string {
@@ -883,7 +883,7 @@ func (pcs *PushCommits) APIFormat(ctx context.Context, usersStore *UsersStore, r
} }
nameStatus := &git.NameStatus{} nameStatus := &git.NameStatus{}
if !testx.InTest { if !testutil.InTest {
nameStatus, err = git.ShowNameStatus(repoPath, commit.Sha1) nameStatus, err = git.ShowNameStatus(repoPath, commit.Sha1)
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "show name status [commit_sha1: %s]", commit.Sha1) return nil, errors.Wrapf(err, "show name status [commit_sha1: %s]", commit.Sha1)

View File

@@ -13,7 +13,7 @@ import (
"xorm.io/xorm" "xorm.io/xorm"
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/errutil"
) )
// Attachment represent a attachment of issue/comment/release. // Attachment represent a attachment of issue/comment/release.
@@ -81,7 +81,7 @@ func NewAttachment(name string, buf []byte, file multipart.File) (_ *Attachment,
return attach, nil return attach, nil
} }
var _ errx.NotFound = (*ErrAttachmentNotExist)(nil) var _ errutil.NotFound = (*ErrAttachmentNotExist)(nil)
type ErrAttachmentNotExist struct { type ErrAttachmentNotExist struct {
args map[string]any args map[string]any

View File

@@ -21,7 +21,7 @@ import (
"xorm.io/xorm" "xorm.io/xorm"
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/osx" "gogs.io/gogs/internal/osutil"
) )
// getTableType returns the type name of a table definition without package name, // getTableType returns the type name of a table definition without package name,
@@ -156,7 +156,7 @@ func ImportDatabase(ctx context.Context, db *gorm.DB, dirPath string, verbose bo
tableName := strings.TrimPrefix(fmt.Sprintf("%T", table), "*database.") 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 !osx.IsFile(tableFile) { if !osutil.IsFile(tableFile) {
log.Info("Skipped table %q", tableName) log.Info("Skipped table %q", tableName)
return nil return nil
} }
@@ -247,7 +247,7 @@ func importLegacyTables(ctx context.Context, dirPath string, verbose bool) error
tableName := strings.TrimPrefix(fmt.Sprintf("%T", table), "*database.") tableName := strings.TrimPrefix(fmt.Sprintf("%T", table), "*database.")
tableFile := filepath.Join(dirPath, tableName+".json") tableFile := filepath.Join(dirPath, tableName+".json")
if !osx.IsFile(tableFile) { if !osutil.IsFile(tableFile) {
continue continue
} }

View File

@@ -15,10 +15,10 @@ import (
"gogs.io/gogs/internal/auth" "gogs.io/gogs/internal/auth"
"gogs.io/gogs/internal/auth/github" "gogs.io/gogs/internal/auth/github"
"gogs.io/gogs/internal/auth/pam" "gogs.io/gogs/internal/auth/pam"
"gogs.io/gogs/internal/cryptox" "gogs.io/gogs/internal/cryptoutil"
"gogs.io/gogs/internal/dbtest" "gogs.io/gogs/internal/dbtest"
"gogs.io/gogs/internal/lfsx" "gogs.io/gogs/internal/lfsutil"
"gogs.io/gogs/internal/testx" "gogs.io/gogs/internal/testutil"
) )
func TestDumpAndImport(t *testing.T) { func TestDumpAndImport(t *testing.T) {
@@ -59,30 +59,30 @@ func setupDBToDump(t *testing.T, db *gorm.DB) {
&AccessToken{ &AccessToken{
UserID: 1, UserID: 1,
Name: "test1", Name: "test1",
Sha1: cryptox.SHA1("2910d03d-c0b5-4f71-bad5-c4086e4efae3"), Sha1: cryptoutil.SHA1("2910d03d-c0b5-4f71-bad5-c4086e4efae3"),
SHA256: cryptox.SHA256(cryptox.SHA1("2910d03d-c0b5-4f71-bad5-c4086e4efae3")), SHA256: cryptoutil.SHA256(cryptoutil.SHA1("2910d03d-c0b5-4f71-bad5-c4086e4efae3")),
CreatedUnix: 1588568886, CreatedUnix: 1588568886,
UpdatedUnix: 1588572486, // 1 hour later UpdatedUnix: 1588572486, // 1 hour later
}, },
&AccessToken{ &AccessToken{
UserID: 1, UserID: 1,
Name: "test2", Name: "test2",
Sha1: cryptox.SHA1("84117e17-7e67-4024-bd04-1c23e6e809d4"), Sha1: cryptoutil.SHA1("84117e17-7e67-4024-bd04-1c23e6e809d4"),
SHA256: cryptox.SHA256(cryptox.SHA1("84117e17-7e67-4024-bd04-1c23e6e809d4")), SHA256: cryptoutil.SHA256(cryptoutil.SHA1("84117e17-7e67-4024-bd04-1c23e6e809d4")),
CreatedUnix: 1588568886, CreatedUnix: 1588568886,
}, },
&AccessToken{ &AccessToken{
UserID: 2, UserID: 2,
Name: "test1", Name: "test1",
Sha1: cryptox.SHA1("da2775ce-73dd-47ba-b9d2-bbcc346585c4"), Sha1: cryptoutil.SHA1("da2775ce-73dd-47ba-b9d2-bbcc346585c4"),
SHA256: cryptox.SHA256(cryptox.SHA1("da2775ce-73dd-47ba-b9d2-bbcc346585c4")), SHA256: cryptoutil.SHA256(cryptoutil.SHA1("da2775ce-73dd-47ba-b9d2-bbcc346585c4")),
CreatedUnix: 1588568886, CreatedUnix: 1588568886,
}, },
&AccessToken{ &AccessToken{
UserID: 2, UserID: 2,
Name: "test2", Name: "test2",
Sha1: cryptox.SHA256(cryptox.SHA1("1b2dccd1-a262-470f-bb8c-7fc73192e9bb"))[:40], Sha1: cryptoutil.SHA256(cryptoutil.SHA1("1b2dccd1-a262-470f-bb8c-7fc73192e9bb"))[:40],
SHA256: cryptox.SHA256(cryptox.SHA1("1b2dccd1-a262-470f-bb8c-7fc73192e9bb")), SHA256: cryptoutil.SHA256(cryptoutil.SHA1("1b2dccd1-a262-470f-bb8c-7fc73192e9bb")),
CreatedUnix: 1588568886, CreatedUnix: 1588568886,
}, },
@@ -156,14 +156,14 @@ func setupDBToDump(t *testing.T, db *gorm.DB) {
RepoID: 1, RepoID: 1,
OID: "ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f", OID: "ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f",
Size: 100, Size: 100,
Storage: lfsx.StorageLocal, Storage: lfsutil.StorageLocal,
CreatedAt: time.Unix(1588568886, 0).UTC(), CreatedAt: time.Unix(1588568886, 0).UTC(),
}, },
&LFSObject{ &LFSObject{
RepoID: 2, RepoID: 2,
OID: "ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f", OID: "ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f",
Size: 100, Size: 100,
Storage: lfsx.StorageLocal, Storage: lfsutil.StorageLocal,
CreatedAt: time.Unix(1588568886, 0).UTC(), CreatedAt: time.Unix(1588568886, 0).UTC(),
}, },
@@ -213,7 +213,7 @@ func dumpTables(t *testing.T, db *gorm.DB) {
} }
golden := filepath.Join("testdata", "backup", tableName+".golden.json") golden := filepath.Join("testdata", "backup", tableName+".golden.json")
testx.AssertGolden(t, golden, testx.Update("TestDumpAndImport"), buf.String()) testutil.AssertGolden(t, golden, testutil.Update("TestDumpAndImport"), buf.String())
} }
} }

View File

@@ -11,7 +11,7 @@ import (
log "unknwon.dev/clog/v2" log "unknwon.dev/clog/v2"
"xorm.io/xorm" "xorm.io/xorm"
"gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/markup" "gogs.io/gogs/internal/markup"
apiv1types "gogs.io/gogs/internal/route/api/v1/types" apiv1types "gogs.io/gogs/internal/route/api/v1/types"
) )
@@ -388,7 +388,7 @@ func CreateRefComment(doer *User, repo *Repository, issue *Issue, content, commi
return err return err
} }
var _ errx.NotFound = (*ErrCommentNotExist)(nil) var _ errutil.NotFound = (*ErrCommentNotExist)(nil)
type ErrCommentNotExist struct { type ErrCommentNotExist struct {
args map[string]any args map[string]any

View File

@@ -13,7 +13,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/dbx" "gogs.io/gogs/internal/dbutil"
) )
func newLogWriter() (logger.Writer, error) { func newLogWriter() (logger.Writer, error) {
@@ -30,7 +30,7 @@ func newLogWriter() (logger.Writer, error) {
if err != nil { if err != nil {
return nil, errors.Wrap(err, `create "gorm.log"`) return nil, errors.Wrap(err, `create "gorm.log"`)
} }
return &dbx.Logger{Writer: w}, nil return &dbutil.Logger{Writer: w}, nil
} }
// Tables is the list of struct-to-table mappings. // Tables is the list of struct-to-table mappings.
@@ -59,7 +59,7 @@ func NewConnection(w logger.Writer) (*gorm.DB, error) {
LogLevel: level, LogLevel: level,
}) })
db, err := dbx.OpenDB( db, err := dbutil.OpenDB(
conf.Database, conf.Database,
&gorm.Config{ &gorm.Config{
SkipDefaultTransaction: true, SkipDefaultTransaction: true,

View File

@@ -12,7 +12,7 @@ import (
"xorm.io/xorm" "xorm.io/xorm"
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/markup" "gogs.io/gogs/internal/markup"
apiv1types "gogs.io/gogs/internal/route/api/v1/types" apiv1types "gogs.io/gogs/internal/route/api/v1/types"
"gogs.io/gogs/internal/tool" "gogs.io/gogs/internal/tool"
@@ -82,7 +82,7 @@ func getUserByID(e Engine, id int64) (*User, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
return nil, ErrUserNotExist{args: errx.Args{"userID": id}} return nil, ErrUserNotExist{args: errutil.Args{"userID": id}}
} }
// TODO(unknwon): Rely on AfterFind hook to sanitize user full name. // TODO(unknwon): Rely on AfterFind hook to sanitize user full name.
@@ -801,7 +801,7 @@ func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string)
return nil return nil
} }
var _ errx.NotFound = (*ErrIssueNotExist)(nil) var _ errutil.NotFound = (*ErrIssueNotExist)(nil)
type ErrIssueNotExist struct { type ErrIssueNotExist struct {
args map[string]any args map[string]any

View File

@@ -10,7 +10,7 @@ import (
"github.com/cockroachdb/errors" "github.com/cockroachdb/errors"
"gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/lazyregexp" "gogs.io/gogs/internal/lazyregexp"
apiv1types "gogs.io/gogs/internal/route/api/v1/types" apiv1types "gogs.io/gogs/internal/route/api/v1/types"
"gogs.io/gogs/internal/tool" "gogs.io/gogs/internal/tool"
@@ -101,7 +101,7 @@ func NewLabels(labels ...*Label) error {
return err return err
} }
var _ errx.NotFound = (*ErrLabelNotExist)(nil) var _ errutil.NotFound = (*ErrLabelNotExist)(nil)
type ErrLabelNotExist struct { type ErrLabelNotExist struct {
args map[string]any args map[string]any

View File

@@ -10,8 +10,8 @@ import (
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/email" "gogs.io/gogs/internal/email"
"gogs.io/gogs/internal/markup" "gogs.io/gogs/internal/markup"
"gogs.io/gogs/internal/strx" "gogs.io/gogs/internal/strutil"
"gogs.io/gogs/internal/userx" "gogs.io/gogs/internal/userutil"
) )
func (issue *Issue) MailSubject() string { func (issue *Issue) MailSubject() string {
@@ -36,7 +36,7 @@ func (mu mailerUser) Email() string {
} }
func (mu mailerUser) GenerateEmailActivateCode(email string) string { func (mu mailerUser) GenerateEmailActivateCode(email string) string {
return userx.GenerateActivateCode( return userutil.GenerateActivateCode(
mu.user.ID, mu.user.ID,
email, email,
mu.user.Name, mu.user.Name,
@@ -138,7 +138,7 @@ func mailIssueCommentToParticipants(issue *Issue, doer *User, mentions []string)
for i := range participants { for i := range participants {
if participants[i].ID == doer.ID { if participants[i].ID == doer.ID {
continue continue
} else if strx.ContainsFold(names, participants[i].Name) { } else if strutil.ContainsFold(names, participants[i].Name) {
continue continue
} }
@@ -146,7 +146,7 @@ func mailIssueCommentToParticipants(issue *Issue, doer *User, mentions []string)
names = append(names, participants[i].Name) names = append(names, participants[i].Name)
} }
if issue.Assignee != nil && issue.Assignee.ID != doer.ID { if issue.Assignee != nil && issue.Assignee.ID != doer.ID {
if !strx.ContainsFold(names, issue.Assignee.Name) { if !strutil.ContainsFold(names, issue.Assignee.Name) {
tos = append(tos, issue.Assignee.Email) tos = append(tos, issue.Assignee.Email)
names = append(names, issue.Assignee.Name) names = append(names, issue.Assignee.Name)
} }
@@ -159,7 +159,7 @@ func mailIssueCommentToParticipants(issue *Issue, doer *User, mentions []string)
names = append(names, doer.Name) names = append(names, doer.Name)
toUsernames := make([]string, 0, len(mentions)) // list of user names. toUsernames := make([]string, 0, len(mentions)) // list of user names.
for i := range mentions { for i := range mentions {
if strx.ContainsFold(names, mentions[i]) { if strutil.ContainsFold(names, mentions[i]) {
continue continue
} }

View File

@@ -8,17 +8,17 @@ import (
"github.com/cockroachdb/errors" "github.com/cockroachdb/errors"
"gorm.io/gorm" "gorm.io/gorm"
"gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/lfsx" "gogs.io/gogs/internal/lfsutil"
) )
// LFSObject is the relation between an LFS object and a repository. // LFSObject is the relation between an LFS object and a repository.
type LFSObject struct { type LFSObject struct {
RepoID int64 `gorm:"primaryKey;auto_increment:false"` RepoID int64 `gorm:"primaryKey;auto_increment:false"`
OID lfsx.OID `gorm:"primaryKey;column:oid"` OID lfsutil.OID `gorm:"primaryKey;column:oid"`
Size int64 `gorm:"not null"` Size int64 `gorm:"not null"`
Storage lfsx.Storage `gorm:"not null"` Storage lfsutil.Storage `gorm:"not null"`
CreatedAt time.Time `gorm:"not null"` CreatedAt time.Time `gorm:"not null"`
} }
// LFSStore is the storage layer for LFS objects. // LFSStore is the storage layer for LFS objects.
@@ -31,7 +31,7 @@ func newLFSStore(db *gorm.DB) *LFSStore {
} }
// CreateObject creates an LFS object record in database. // CreateObject creates an LFS object record in database.
func (s *LFSStore) CreateObject(ctx context.Context, repoID int64, oid lfsx.OID, size int64, storage lfsx.Storage) error { func (s *LFSStore) CreateObject(ctx context.Context, repoID int64, oid lfsutil.OID, size int64, storage lfsutil.Storage) error {
object := &LFSObject{ object := &LFSObject{
RepoID: repoID, RepoID: repoID,
OID: oid, OID: oid,
@@ -42,7 +42,7 @@ func (s *LFSStore) CreateObject(ctx context.Context, repoID int64, oid lfsx.OID,
} }
type ErrLFSObjectNotExist struct { type ErrLFSObjectNotExist struct {
args errx.Args args errutil.Args
} }
func IsErrLFSObjectNotExist(err error) bool { func IsErrLFSObjectNotExist(err error) bool {
@@ -59,12 +59,12 @@ func (ErrLFSObjectNotExist) NotFound() bool {
// GetObjectByOID returns the LFS object with given OID. It returns // GetObjectByOID returns the LFS object with given OID. It returns
// ErrLFSObjectNotExist when not found. // ErrLFSObjectNotExist when not found.
func (s *LFSStore) GetObjectByOID(ctx context.Context, repoID int64, oid lfsx.OID) (*LFSObject, error) { func (s *LFSStore) GetObjectByOID(ctx context.Context, repoID int64, oid lfsutil.OID) (*LFSObject, error) {
object := new(LFSObject) object := new(LFSObject)
err := s.db.WithContext(ctx).Where("repo_id = ? AND oid = ?", repoID, oid).First(object).Error err := s.db.WithContext(ctx).Where("repo_id = ? AND oid = ?", repoID, oid).First(object).Error
if err != nil { if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) { if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrLFSObjectNotExist{args: errx.Args{"repoID": repoID, "oid": oid}} return nil, ErrLFSObjectNotExist{args: errutil.Args{"repoID": repoID, "oid": oid}}
} }
return nil, err return nil, err
} }
@@ -73,7 +73,7 @@ func (s *LFSStore) GetObjectByOID(ctx context.Context, repoID int64, oid lfsx.OI
// GetObjectsByOIDs returns LFS objects found within "oids". The returned list // GetObjectsByOIDs returns LFS objects found within "oids". The returned list
// could have fewer elements if some oids were not found. // could have fewer elements if some oids were not found.
func (s *LFSStore) GetObjectsByOIDs(ctx context.Context, repoID int64, oids ...lfsx.OID) ([]*LFSObject, error) { func (s *LFSStore) GetObjectsByOIDs(ctx context.Context, repoID int64, oids ...lfsutil.OID) ([]*LFSObject, error) {
if len(oids) == 0 { if len(oids) == 0 {
return []*LFSObject{}, nil return []*LFSObject{}, nil
} }

View File

@@ -8,8 +8,8 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/lfsx" "gogs.io/gogs/internal/lfsutil"
) )
func TestLFS(t *testing.T) { func TestLFS(t *testing.T) {
@@ -47,8 +47,8 @@ func TestLFS(t *testing.T) {
func lfsCreateObject(t *testing.T, ctx context.Context, s *LFSStore) { func lfsCreateObject(t *testing.T, ctx context.Context, s *LFSStore) {
// Create first LFS object // Create first LFS object
repoID := int64(1) repoID := int64(1)
oid := lfsx.OID("ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f") oid := lfsutil.OID("ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f")
err := s.CreateObject(ctx, repoID, oid, 12, lfsx.StorageLocal) err := s.CreateObject(ctx, repoID, oid, 12, lfsutil.StorageLocal)
require.NoError(t, err) require.NoError(t, err)
// Get it back and check the CreatedAt field // Get it back and check the CreatedAt field
@@ -57,15 +57,15 @@ func lfsCreateObject(t *testing.T, ctx context.Context, s *LFSStore) {
assert.Equal(t, s.db.NowFunc().Format(time.RFC3339), object.CreatedAt.UTC().Format(time.RFC3339)) assert.Equal(t, s.db.NowFunc().Format(time.RFC3339), object.CreatedAt.UTC().Format(time.RFC3339))
// Try to create second LFS object with same oid should fail // Try to create second LFS object with same oid should fail
err = s.CreateObject(ctx, repoID, oid, 12, lfsx.StorageLocal) err = s.CreateObject(ctx, repoID, oid, 12, lfsutil.StorageLocal)
assert.Error(t, err) assert.Error(t, err)
} }
func lfsGetObjectByOID(t *testing.T, ctx context.Context, s *LFSStore) { func lfsGetObjectByOID(t *testing.T, ctx context.Context, s *LFSStore) {
// Create a LFS object // Create a LFS object
repoID := int64(1) repoID := int64(1)
oid := lfsx.OID("ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f") oid := lfsutil.OID("ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f")
err := s.CreateObject(ctx, repoID, oid, 12, lfsx.StorageLocal) err := s.CreateObject(ctx, repoID, oid, 12, lfsutil.StorageLocal)
require.NoError(t, err) require.NoError(t, err)
// We should be able to get it back // We should be able to get it back
@@ -74,18 +74,18 @@ func lfsGetObjectByOID(t *testing.T, ctx context.Context, s *LFSStore) {
// Try to get a non-existent object // Try to get a non-existent object
_, err = s.GetObjectByOID(ctx, repoID, "bad_oid") _, err = s.GetObjectByOID(ctx, repoID, "bad_oid")
expErr := ErrLFSObjectNotExist{args: errx.Args{"repoID": repoID, "oid": lfsx.OID("bad_oid")}} expErr := ErrLFSObjectNotExist{args: errutil.Args{"repoID": repoID, "oid": lfsutil.OID("bad_oid")}}
assert.Equal(t, expErr, err) assert.Equal(t, expErr, err)
} }
func lfsGetObjectsByOIDs(t *testing.T, ctx context.Context, s *LFSStore) { func lfsGetObjectsByOIDs(t *testing.T, ctx context.Context, s *LFSStore) {
// Create two LFS objects // Create two LFS objects
repoID := int64(1) repoID := int64(1)
oid1 := lfsx.OID("ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f") oid1 := lfsutil.OID("ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f")
oid2 := lfsx.OID("ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64g") oid2 := lfsutil.OID("ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64g")
err := s.CreateObject(ctx, repoID, oid1, 12, lfsx.StorageLocal) err := s.CreateObject(ctx, repoID, oid1, 12, lfsutil.StorageLocal)
require.NoError(t, err) require.NoError(t, err)
err = s.CreateObject(ctx, repoID, oid2, 12, lfsx.StorageLocal) err = s.CreateObject(ctx, repoID, oid2, 12, lfsutil.StorageLocal)
require.NoError(t, err) require.NoError(t, err)
// We should be able to get them back and ignore non-existent ones // We should be able to get them back and ignore non-existent ones

View File

@@ -16,8 +16,8 @@ import (
"gogs.io/gogs/internal/auth/ldap" "gogs.io/gogs/internal/auth/ldap"
"gogs.io/gogs/internal/auth/pam" "gogs.io/gogs/internal/auth/pam"
"gogs.io/gogs/internal/auth/smtp" "gogs.io/gogs/internal/auth/smtp"
"gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/osx" "gogs.io/gogs/internal/osutil"
) )
// loginSourceFilesStore is the in-memory interface for login source files stored on file system. // loginSourceFilesStore is the in-memory interface for login source files stored on file system.
@@ -41,10 +41,10 @@ type loginSourceFiles struct {
clock func() time.Time clock func() time.Time
} }
var _ errx.NotFound = (*ErrLoginSourceNotExist)(nil) var _ errutil.NotFound = (*ErrLoginSourceNotExist)(nil)
type ErrLoginSourceNotExist struct { type ErrLoginSourceNotExist struct {
args errx.Args args errutil.Args
} }
func IsErrLoginSourceNotExist(err error) bool { func IsErrLoginSourceNotExist(err error) bool {
@@ -69,7 +69,7 @@ func (s *loginSourceFiles) GetByID(id int64) (*LoginSource, error) {
} }
} }
return nil, ErrLoginSourceNotExist{args: errx.Args{"id": id}} return nil, ErrLoginSourceNotExist{args: errutil.Args{"id": id}}
} }
func (s *loginSourceFiles) Len() int { func (s *loginSourceFiles) Len() int {
@@ -109,7 +109,7 @@ func (s *loginSourceFiles) Update(source *LoginSource) {
// loadLoginSourceFiles loads login sources from file system. // loadLoginSourceFiles loads login sources from file system.
func loadLoginSourceFiles(authdPath string, clock func() time.Time) (loginSourceFilesStore, error) { func loadLoginSourceFiles(authdPath string, clock func() time.Time) (loginSourceFilesStore, error) {
if !osx.IsDir(authdPath) { if !osutil.IsDir(authdPath) {
return &loginSourceFiles{clock: clock}, nil return &loginSourceFiles{clock: clock}, nil
} }

View File

@@ -7,7 +7,7 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/errutil"
) )
func TestLoginSourceFiles_GetByID(t *testing.T) { func TestLoginSourceFiles_GetByID(t *testing.T) {
@@ -19,7 +19,7 @@ func TestLoginSourceFiles_GetByID(t *testing.T) {
t.Run("source does not exist", func(t *testing.T) { t.Run("source does not exist", func(t *testing.T) {
_, err := store.GetByID(1) _, err := store.GetByID(1)
wantErr := ErrLoginSourceNotExist{args: errx.Args{"id": int64(1)}} wantErr := ErrLoginSourceNotExist{args: errutil.Args{"id": int64(1)}}
assert.Equal(t, wantErr, err) assert.Equal(t, wantErr, err)
}) })

View File

@@ -15,7 +15,7 @@ import (
"gogs.io/gogs/internal/auth/ldap" "gogs.io/gogs/internal/auth/ldap"
"gogs.io/gogs/internal/auth/pam" "gogs.io/gogs/internal/auth/pam"
"gogs.io/gogs/internal/auth/smtp" "gogs.io/gogs/internal/auth/smtp"
"gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/errutil"
) )
// LoginSource represents an external way for authorizing users. // LoginSource represents an external way for authorizing users.
@@ -189,7 +189,7 @@ type CreateLoginSourceOptions struct {
} }
type ErrLoginSourceAlreadyExist struct { type ErrLoginSourceAlreadyExist struct {
args errx.Args args errutil.Args
} }
func IsErrLoginSourceAlreadyExist(err error) bool { func IsErrLoginSourceAlreadyExist(err error) bool {
@@ -205,7 +205,7 @@ func (err ErrLoginSourceAlreadyExist) Error() string {
func (s *LoginSourcesStore) Create(ctx context.Context, opts CreateLoginSourceOptions) (*LoginSource, error) { func (s *LoginSourcesStore) Create(ctx context.Context, opts CreateLoginSourceOptions) (*LoginSource, error) {
err := s.db.WithContext(ctx).Where("name = ?", opts.Name).First(new(LoginSource)).Error err := s.db.WithContext(ctx).Where("name = ?", opts.Name).First(new(LoginSource)).Error
if err == nil { if err == nil {
return nil, ErrLoginSourceAlreadyExist{args: errx.Args{"name": opts.Name}} return nil, ErrLoginSourceAlreadyExist{args: errutil.Args{"name": opts.Name}}
} else if !errors.Is(err, gorm.ErrRecordNotFound) { } else if !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, err return nil, err
} }
@@ -232,7 +232,7 @@ func (s *LoginSourcesStore) Count(ctx context.Context) int64 {
} }
type ErrLoginSourceInUse struct { type ErrLoginSourceInUse struct {
args errx.Args args errutil.Args
} }
func IsErrLoginSourceInUse(err error) bool { func IsErrLoginSourceInUse(err error) bool {
@@ -251,7 +251,7 @@ func (s *LoginSourcesStore) DeleteByID(ctx context.Context, id int64) error {
if err != nil { if err != nil {
return err return err
} else if count > 0 { } else if count > 0 {
return ErrLoginSourceInUse{args: errx.Args{"id": id}} return ErrLoginSourceInUse{args: errutil.Args{"id": id}}
} }
return s.db.WithContext(ctx).Where("id = ?", id).Delete(new(LoginSource)).Error return s.db.WithContext(ctx).Where("id = ?", id).Delete(new(LoginSource)).Error

View File

@@ -15,7 +15,7 @@ import (
"gogs.io/gogs/internal/auth/ldap" "gogs.io/gogs/internal/auth/ldap"
"gogs.io/gogs/internal/auth/pam" "gogs.io/gogs/internal/auth/pam"
"gogs.io/gogs/internal/auth/smtp" "gogs.io/gogs/internal/auth/smtp"
"gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/errutil"
) )
func TestLoginSource_BeforeSave(t *testing.T) { func TestLoginSource_BeforeSave(t *testing.T) {
@@ -211,7 +211,7 @@ func loginSourcesCreate(t *testing.T, ctx context.Context, s *LoginSourcesStore)
// Try to create second login source with same name should fail. // Try to create second login source with same name should fail.
_, err = s.Create(ctx, CreateLoginSourceOptions{Name: source.Name}) _, err = s.Create(ctx, CreateLoginSourceOptions{Name: source.Name})
wantErr := ErrLoginSourceAlreadyExist{args: errx.Args{"name": source.Name}} wantErr := ErrLoginSourceAlreadyExist{args: errutil.Args{"name": source.Name}}
assert.Equal(t, wantErr, err) assert.Equal(t, wantErr, err)
} }
@@ -270,13 +270,13 @@ func loginSourcesDeleteByID(t *testing.T, ctx context.Context, s *LoginSourcesSt
// Delete the login source will result in error // Delete the login source will result in error
err = s.DeleteByID(ctx, source.ID) err = s.DeleteByID(ctx, source.ID)
wantErr := ErrLoginSourceInUse{args: errx.Args{"id": source.ID}} wantErr := ErrLoginSourceInUse{args: errutil.Args{"id": source.ID}}
assert.Equal(t, wantErr, err) assert.Equal(t, wantErr, err)
}) })
mock := NewMockLoginSourceFilesStore() mock := NewMockLoginSourceFilesStore()
mock.GetByIDFunc.SetDefaultHook(func(id int64) (*LoginSource, error) { mock.GetByIDFunc.SetDefaultHook(func(id int64) (*LoginSource, error) {
return nil, ErrLoginSourceNotExist{args: errx.Args{"id": id}} return nil, ErrLoginSourceNotExist{args: errutil.Args{"id": id}}
}) })
setMockLoginSourceFilesStore(t, s, mock) setMockLoginSourceFilesStore(t, s, mock)
@@ -308,7 +308,7 @@ func loginSourcesDeleteByID(t *testing.T, ctx context.Context, s *LoginSourcesSt
// We should get token not found error // We should get token not found error
_, err = s.GetByID(ctx, source.ID) _, err = s.GetByID(ctx, source.ID)
wantErr := ErrLoginSourceNotExist{args: errx.Args{"id": source.ID}} wantErr := ErrLoginSourceNotExist{args: errutil.Args{"id": source.ID}}
assert.Equal(t, wantErr, err) assert.Equal(t, wantErr, err)
} }
@@ -316,7 +316,7 @@ func loginSourcesGetByID(t *testing.T, ctx context.Context, s *LoginSourcesStore
mock := NewMockLoginSourceFilesStore() mock := NewMockLoginSourceFilesStore()
mock.GetByIDFunc.SetDefaultHook(func(id int64) (*LoginSource, error) { mock.GetByIDFunc.SetDefaultHook(func(id int64) (*LoginSource, error) {
if id != 101 { if id != 101 {
return nil, ErrLoginSourceNotExist{args: errx.Args{"id": id}} return nil, ErrLoginSourceNotExist{args: errutil.Args{"id": id}}
} }
return &LoginSource{ID: id}, nil return &LoginSource{ID: id}, nil
}) })

View File

@@ -12,7 +12,7 @@ import (
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/dbtest" "gogs.io/gogs/internal/dbtest"
"gogs.io/gogs/internal/testx" "gogs.io/gogs/internal/testutil"
) )
func TestMain(m *testing.M) { func TestMain(m *testing.M) {
@@ -22,7 +22,7 @@ func TestMain(m *testing.M) {
if !testing.Verbose() { if !testing.Verbose() {
// Remove the primary logger and register a noop logger. // Remove the primary logger and register a noop logger.
log.Remove(log.DefaultConsoleName) log.Remove(log.DefaultConsoleName)
err := log.New("noop", testx.InitNoopLogger) err := log.New("noop", testutil.InitNoopLogger)
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
os.Exit(1) os.Exit(1)

View File

@@ -9,7 +9,7 @@ import (
"gorm.io/gorm/logger" "gorm.io/gorm/logger"
log "unknwon.dev/clog/v2" log "unknwon.dev/clog/v2"
"gogs.io/gogs/internal/testx" "gogs.io/gogs/internal/testutil"
) )
func TestMain(m *testing.M) { func TestMain(m *testing.M) {
@@ -19,7 +19,7 @@ func TestMain(m *testing.M) {
if !testing.Verbose() { if !testing.Verbose() {
// Remove the primary logger and register a noop logger. // Remove the primary logger and register a noop logger.
log.Remove(log.DefaultConsoleName) log.Remove(log.DefaultConsoleName)
err := log.New("noop", testx.InitNoopLogger) err := log.New("noop", testutil.InitNoopLogger)
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
os.Exit(1) os.Exit(1)

View File

@@ -4,7 +4,7 @@ import (
"github.com/cockroachdb/errors" "github.com/cockroachdb/errors"
"gorm.io/gorm" "gorm.io/gorm"
"gogs.io/gogs/internal/cryptox" "gogs.io/gogs/internal/cryptoutil"
) )
func migrateAccessTokenToSHA256(db *gorm.DB) error { func migrateAccessTokenToSHA256(db *gorm.DB) error {
@@ -33,7 +33,7 @@ func migrateAccessTokenToSHA256(db *gorm.DB) error {
} }
for _, t := range accessTokens { for _, t := range accessTokens {
sha256 := cryptox.SHA256(t.Sha1) sha256 := cryptoutil.SHA256(t.Sha1)
err = tx.Model(&accessToken{}).Where("id = ?", t.ID).Update("sha256", sha256).Error err = tx.Model(&accessToken{}).Where("id = ?", t.ID).Update("sha256", sha256).Error
if err != nil { if err != nil {
return errors.Wrap(err, "update") return errors.Wrap(err, "update")

View File

@@ -10,7 +10,7 @@ import (
"github.com/cockroachdb/errors" "github.com/cockroachdb/errors"
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/errutil"
apiv1types "gogs.io/gogs/internal/route/api/v1/types" apiv1types "gogs.io/gogs/internal/route/api/v1/types"
) )
@@ -128,7 +128,7 @@ func NewMilestone(m *Milestone) (err error) {
return sess.Commit() return sess.Commit()
} }
var _ errx.NotFound = (*ErrMilestoneNotExist)(nil) var _ errutil.NotFound = (*ErrMilestoneNotExist)(nil)
type ErrMilestoneNotExist struct { type ErrMilestoneNotExist struct {
args map[string]any args map[string]any

View File

@@ -20,7 +20,7 @@ import (
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/database/migrations" "gogs.io/gogs/internal/database/migrations"
"gogs.io/gogs/internal/dbx" "gogs.io/gogs/internal/dbutil"
) )
// Engine represents a XORM engine or session. // Engine represents a XORM engine or session.
@@ -89,7 +89,7 @@ func getEngine() (*xorm.Engine, error) {
case "postgres": case "postgres":
conf.UsePostgreSQL = true conf.UsePostgreSQL = true
host, port := dbx.ParsePostgreSQLHostPort(conf.Database.Host) host, port := dbutil.ParsePostgreSQLHostPort(conf.Database.Host)
connStr = fmt.Sprintf("user='%s' password='%s' host='%s' port='%s' dbname='%s' sslmode='%s' search_path='%s'", connStr = fmt.Sprintf("user='%s' password='%s' host='%s' port='%s' dbname='%s' sslmode='%s' search_path='%s'",
conf.Database.User, conf.Database.Password, host, port, conf.Database.Name, conf.Database.SSLMode, conf.Database.Schema) conf.Database.User, conf.Database.Password, host, port, conf.Database.Name, conf.Database.SSLMode, conf.Database.Schema)
driver = "pgx" driver = "pgx"
@@ -166,7 +166,7 @@ func SetEngine() (*gorm.DB, error) {
var gormLogger logger.Writer var gormLogger logger.Writer
if conf.HookMode { if conf.HookMode {
gormLogger = &dbx.Logger{Writer: fileWriter} gormLogger = &dbutil.Logger{Writer: fileWriter}
} else { } else {
gormLogger, err = newLogWriter() gormLogger, err = newLogWriter()
if err != nil { if err != nil {

View File

@@ -9,9 +9,9 @@ import (
"xorm.io/builder" "xorm.io/builder"
"xorm.io/xorm" "xorm.io/xorm"
"gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/repox" "gogs.io/gogs/internal/repoutil"
"gogs.io/gogs/internal/userx" "gogs.io/gogs/internal/userutil"
) )
var ErrOrgNotExist = errors.New("Organization does not exist") var ErrOrgNotExist = errors.New("Organization does not exist")
@@ -103,17 +103,17 @@ func CreateOrganization(org, owner *User) (err error) {
if Handle.Users().IsUsernameUsed(context.TODO(), org.Name, 0) { if Handle.Users().IsUsernameUsed(context.TODO(), org.Name, 0) {
return ErrUserAlreadyExist{ return ErrUserAlreadyExist{
args: errx.Args{ args: errutil.Args{
"name": org.Name, "name": org.Name,
}, },
} }
} }
org.LowerName = strings.ToLower(org.Name) org.LowerName = strings.ToLower(org.Name)
if org.Rands, err = userx.RandomSalt(); err != nil { if org.Rands, err = userutil.RandomSalt(); err != nil {
return err return err
} }
if org.Salt, err = userx.RandomSalt(); err != nil { if org.Salt, err = userutil.RandomSalt(); err != nil {
return err return err
} }
org.UseCustomAvatar = true org.UseCustomAvatar = true
@@ -130,7 +130,7 @@ func CreateOrganization(org, owner *User) (err error) {
if _, err = sess.Insert(org); err != nil { if _, err = sess.Insert(org); err != nil {
return errors.Newf("insert organization: %v", err) return errors.Newf("insert organization: %v", err)
} }
_ = userx.GenerateRandomAvatar(org.ID, org.Name, org.Email) _ = userutil.GenerateRandomAvatar(org.ID, org.Name, org.Email)
// Add initial creator to organization and owner team. // Add initial creator to organization and owner team.
if _, err = sess.Insert(&OrgUser{ if _, err = sess.Insert(&OrgUser{
@@ -162,7 +162,7 @@ func CreateOrganization(org, owner *User) (err error) {
return errors.Newf("insert team-user relation: %v", err) return errors.Newf("insert team-user relation: %v", err)
} }
if err = os.MkdirAll(repox.UserPath(org.Name), os.ModePerm); err != nil { if err = os.MkdirAll(repoutil.UserPath(org.Name), os.ModePerm); err != nil {
return errors.Newf("create directory: %v", err) return errors.Newf("create directory: %v", err)
} }

View File

@@ -8,7 +8,7 @@ import (
"github.com/cockroachdb/errors" "github.com/cockroachdb/errors"
"xorm.io/xorm" "xorm.io/xorm"
"gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/errutil"
) )
const ownerTeamName = "Owners" const ownerTeamName = "Owners"
@@ -297,7 +297,7 @@ func NewTeam(t *Team) error {
return sess.Commit() return sess.Commit()
} }
var _ errx.NotFound = (*ErrTeamNotExist)(nil) var _ errutil.NotFound = (*ErrTeamNotExist)(nil)
type ErrTeamNotExist struct { type ErrTeamNotExist struct {
args map[string]any args map[string]any

View File

@@ -6,7 +6,7 @@ import (
"github.com/cockroachdb/errors" "github.com/cockroachdb/errors"
"gorm.io/gorm" "gorm.io/gorm"
"gogs.io/gogs/internal/dbx" "gogs.io/gogs/internal/dbutil"
) )
// OrganizationsStore is the storage layer for organizations. // OrganizationsStore is the storage layer for organizations.
@@ -42,9 +42,9 @@ func (s *OrganizationsStore) List(ctx context.Context, opts ListOrgsOptions) ([]
ORDER BY org.id ASC ORDER BY org.id ASC
*/ */
tx := s.db.WithContext(ctx). tx := s.db.WithContext(ctx).
Joins(dbx.Quote("JOIN org_user ON org_user.org_id = %s.id", "user")). Joins(dbutil.Quote("JOIN org_user ON org_user.org_id = %s.id", "user")).
Where("org_user.uid = ?", opts.MemberID). Where("org_user.uid = ?", opts.MemberID).
Order(dbx.Quote("%s.id ASC", "user")) Order(dbutil.Quote("%s.id ASC", "user"))
if !opts.IncludePrivateMembers { if !opts.IncludePrivateMembers {
tx = tx.Where("org_user.is_public = ?", true) tx = tx.Where("org_user.is_public = ?", true)
} }

View File

@@ -7,7 +7,7 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"gogs.io/gogs/internal/dbx" "gogs.io/gogs/internal/dbutil"
) )
func TestOrgs(t *testing.T) { func TestOrgs(t *testing.T) {
@@ -55,7 +55,7 @@ func orgsList(t *testing.T, ctx context.Context, s *OrganizationsStore) {
org2, err := usersStore.Create(ctx, "org2", "org2@example.com", CreateUserOptions{}) org2, err := usersStore.Create(ctx, "org2", "org2@example.com", CreateUserOptions{})
require.NoError(t, err) require.NoError(t, err)
err = s.db.Exec( err = s.db.Exec(
dbx.Quote("UPDATE %s SET type = ? WHERE id IN (?, ?)", "user"), dbutil.Quote("UPDATE %s SET type = ? WHERE id IN (?, ?)", "user"),
UserTypeOrganization, org1.ID, org2.ID, UserTypeOrganization, org1.ID, org2.ID,
).Error ).Error
require.NoError(t, err) require.NoError(t, err)
@@ -120,7 +120,7 @@ func organizationsSearchByName(t *testing.T, ctx context.Context, s *Organizatio
org2, err := usersStore.Create(ctx, "org2", "org2@example.com", CreateUserOptions{FullName: "Acme Corp 2"}) org2, err := usersStore.Create(ctx, "org2", "org2@example.com", CreateUserOptions{FullName: "Acme Corp 2"})
require.NoError(t, err) require.NoError(t, err)
err = s.db.Exec( err = s.db.Exec(
dbx.Quote("UPDATE %s SET type = ? WHERE id IN (?, ?)", "user"), dbutil.Quote("UPDATE %s SET type = ? WHERE id IN (?, ?)", "user"),
UserTypeOrganization, org1.ID, org2.ID, UserTypeOrganization, org1.ID, org2.ID,
).Error ).Error
require.NoError(t, err) require.NoError(t, err)

View File

@@ -8,7 +8,7 @@ import (
"gorm.io/gorm" "gorm.io/gorm"
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/osx" "gogs.io/gogs/internal/osutil"
) )
// PublicKeysStore is the storage layer for public keys. // PublicKeysStore is the storage layer for public keys.
@@ -73,7 +73,7 @@ func (s *PublicKeysStore) RewriteAuthorizedKeys() error {
if err != nil { if err != nil {
return errors.Wrap(err, "close temporary file") return errors.Wrap(err, "close temporary file")
} }
if osx.Exist(fpath) { if osutil.Exist(fpath) {
err = os.Remove(fpath) err = os.Remove(fpath)
if err != nil { if err != nil {
return errors.Wrap(err, "remove") return errors.Wrap(err, "remove")

View File

@@ -15,8 +15,8 @@ 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/errx" "gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/osx" "gogs.io/gogs/internal/osutil"
"gogs.io/gogs/internal/process" "gogs.io/gogs/internal/process"
apiv1types "gogs.io/gogs/internal/route/api/v1/types" apiv1types "gogs.io/gogs/internal/route/api/v1/types"
"gogs.io/gogs/internal/sync" "gogs.io/gogs/internal/sync"
@@ -409,7 +409,7 @@ func (pr *PullRequest) testPatch() (err error) {
} }
// Fast fail if patch does not exist, this assumes data is corrupted. // Fast fail if patch does not exist, this assumes data is corrupted.
if !osx.IsFile(patchPath) { if !osutil.IsFile(patchPath) {
log.Trace("PullRequest[%d].testPatch: ignored corrupted data", pr.ID) log.Trace("PullRequest[%d].testPatch: ignored corrupted data", pr.ID)
return nil return nil
} }
@@ -552,7 +552,7 @@ func GetUnmergedPullRequestsByBaseInfo(repoID int64, branch string) ([]*PullRequ
Join("INNER", "issue", "issue.id=pull_request.issue_id").Find(&prs) Join("INNER", "issue", "issue.id=pull_request.issue_id").Find(&prs)
} }
var _ errx.NotFound = (*ErrPullRequestNotExist)(nil) var _ errutil.NotFound = (*ErrPullRequestNotExist)(nil)
type ErrPullRequestNotExist struct { type ErrPullRequestNotExist struct {
args map[string]any args map[string]any
@@ -684,7 +684,7 @@ func (pr *PullRequest) PushToBaseRepo() (err error) {
headRefspec := fmt.Sprintf("refs/pull/%d/head", pr.Index) headRefspec := fmt.Sprintf("refs/pull/%d/head", pr.Index)
headFile := filepath.Join(pr.BaseRepo.RepoPath(), headRefspec) headFile := filepath.Join(pr.BaseRepo.RepoPath(), headRefspec)
if osx.Exist(headFile) { if osutil.Exist(headFile) {
err = os.Remove(headFile) err = os.Remove(headFile)
if err != nil { if err != nil {
return errors.Newf("remove head file [repo_id: %d]: %v", pr.BaseRepoID, err) return errors.Newf("remove head file [repo_id: %d]: %v", pr.BaseRepoID, err)

View File

@@ -12,7 +12,7 @@ import (
"github.com/cockroachdb/errors" "github.com/cockroachdb/errors"
"github.com/gogs/git-module" "github.com/gogs/git-module"
"gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/errutil"
apiv1types "gogs.io/gogs/internal/route/api/v1/types" apiv1types "gogs.io/gogs/internal/route/api/v1/types"
) )
@@ -202,7 +202,7 @@ func NewRelease(gitRepo *git.Repository, r *Release, uuids []string) error {
return nil return nil
} }
var _ errx.NotFound = (*ErrReleaseNotExist)(nil) var _ errutil.NotFound = (*ErrReleaseNotExist)(nil)
type ErrReleaseNotExist struct { type ErrReleaseNotExist struct {
args map[string]any args map[string]any

View File

@@ -30,15 +30,15 @@ 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"
"gogs.io/gogs/internal/dbx" "gogs.io/gogs/internal/dbutil"
"gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/markup" "gogs.io/gogs/internal/markup"
"gogs.io/gogs/internal/osx" "gogs.io/gogs/internal/osutil"
"gogs.io/gogs/internal/process" "gogs.io/gogs/internal/process"
"gogs.io/gogs/internal/repox" "gogs.io/gogs/internal/repoutil"
apiv1types "gogs.io/gogs/internal/route/api/v1/types" apiv1types "gogs.io/gogs/internal/route/api/v1/types"
"gogs.io/gogs/internal/semverx" "gogs.io/gogs/internal/semverutil"
"gogs.io/gogs/internal/strx" "gogs.io/gogs/internal/strutil"
"gogs.io/gogs/internal/sync" "gogs.io/gogs/internal/sync"
) )
@@ -80,7 +80,7 @@ func LoadRepoConfig() {
} }
customPath := filepath.Join(conf.CustomDir(), "conf", t) customPath := filepath.Join(conf.CustomDir(), "conf", t)
if osx.IsDir(customPath) { if osutil.IsDir(customPath) {
entries, err := os.ReadDir(customPath) entries, err := os.ReadDir(customPath)
if err != nil { if err != nil {
log.Fatal("Failed to get custom %s files: %v", t, err) log.Fatal("Failed to get custom %s files: %v", t, err)
@@ -88,7 +88,7 @@ func LoadRepoConfig() {
for _, entry := range entries { for _, entry := range entries {
f := entry.Name() f := entry.Name()
if !strx.ContainsFold(files, f) { if !strutil.ContainsFold(files, f) {
files = append(files, f) files = append(files, f)
} }
} }
@@ -136,7 +136,7 @@ func NewRepoContext() {
} }
log.Trace("Git version: %s", conf.Git.Version) log.Trace("Git version: %s", conf.Git.Version)
if semverx.Compare(conf.Git.Version, "<", "1.8.3") { if semverutil.Compare(conf.Git.Version, "<", "1.8.3") {
log.Fatal("Gogs requires Git version greater or equal to 1.8.3") log.Fatal("Gogs requires Git version greater or equal to 1.8.3")
} }
@@ -307,7 +307,7 @@ func (r *Repository) FullName() string {
return r.MustOwner().Name + "/" + r.Name return r.MustOwner().Name + "/" + r.Name
} }
// Deprecated: Use repox.HTMLURL instead. // Deprecated: Use repoutil.HTMLURL instead.
func (r *Repository) HTMLURL() string { func (r *Repository) HTMLURL() string {
return conf.Server.ExternalURL + r.FullName() return conf.Server.ExternalURL + r.FullName()
} }
@@ -322,7 +322,7 @@ func (r *Repository) CustomAvatarPath() string {
// Since Gravatar support not needed here - just check for image path. // Since Gravatar support not needed here - just check for image path.
func (r *Repository) RelAvatarLink() string { func (r *Repository) RelAvatarLink() string {
defaultImgURL := "" defaultImgURL := ""
if !osx.Exist(r.CustomAvatarPath()) { if !osutil.Exist(r.CustomAvatarPath()) {
return defaultImgURL return defaultImgURL
} }
return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, RepoAvatarURLPrefix, r.ID) return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, RepoAvatarURLPrefix, r.ID)
@@ -556,7 +556,7 @@ func (r *Repository) GetAssigneeByID(userID int64) (*User, error) {
Private: r.IsPrivate, Private: r.IsPrivate,
}, },
) { ) {
return nil, ErrUserNotExist{args: errx.Args{"userID": userID}} return nil, ErrUserNotExist{args: errutil.Args{"userID": userID}}
} }
return Handle.Users().GetByID(ctx, userID) return Handle.Users().GetByID(ctx, userID)
} }
@@ -585,7 +585,7 @@ func (r *Repository) repoPath(e Engine) string {
return RepoPath(r.mustOwner(e).Name, r.Name) return RepoPath(r.mustOwner(e).Name, r.Name)
} }
// Deprecated: Use repox.RepositoryPath instead. // Deprecated: Use repoutil.RepositoryPath instead.
func (r *Repository) RepoPath() string { func (r *Repository) RepoPath() string {
return r.repoPath(x) return r.repoPath(x)
} }
@@ -602,7 +602,7 @@ func (r *Repository) Link() string {
return conf.Server.Subpath + "/" + r.FullName() return conf.Server.Subpath + "/" + r.FullName()
} }
// Deprecated: Use repox.ComparePath instead. // Deprecated: Use repoutil.ComparePath instead.
func (r *Repository) ComposeCompareURL(oldCommitID, newCommitID string) string { func (r *Repository) ComposeCompareURL(oldCommitID, newCommitID string) string {
return fmt.Sprintf("%s/%s/compare/%s...%s", r.MustOwner().Name, r.Name, oldCommitID, newCommitID) return fmt.Sprintf("%s/%s/compare/%s...%s", r.MustOwner().Name, r.Name, oldCommitID, newCommitID)
} }
@@ -661,7 +661,7 @@ func (r *Repository) LocalCopyPath() string {
// assume subsequent operations are against target branch when caller has confidence // assume subsequent operations are against target branch when caller has confidence
// about no race condition. // about no race condition.
func UpdateLocalCopyBranch(repoPath, localPath, branch string, isWiki bool) (err error) { func UpdateLocalCopyBranch(repoPath, localPath, branch string, isWiki bool) (err error) {
if !osx.Exist(localPath) { if !osutil.Exist(localPath) {
// Checkout to a specific branch fails when wiki is an empty repository. // Checkout to a specific branch fails when wiki is an empty repository.
if isWiki { if isWiki {
branch = "" branch = ""
@@ -736,7 +736,7 @@ func isRepositoryExist(e Engine, u *User, repoName string) (bool, error) {
OwnerID: u.ID, OwnerID: u.ID,
LowerName: strings.ToLower(repoName), LowerName: strings.ToLower(repoName),
}) })
return has && osx.IsDir(RepoPath(u.Name, repoName)), err return has && osutil.IsDir(RepoPath(u.Name, repoName)), err
} }
// IsRepositoryExist returns true if the repository with given name under user has already existed. // IsRepositoryExist returns true if the repository with given name under user has already existed.
@@ -744,28 +744,28 @@ func IsRepositoryExist(u *User, repoName string) (bool, error) {
return isRepositoryExist(x, u, repoName) return isRepositoryExist(x, u, repoName)
} }
// Deprecated: Use repox.NewCloneLink instead. // Deprecated: Use repoutil.NewCloneLink instead.
func (r *Repository) cloneLink(isWiki bool) *repox.CloneLink { func (r *Repository) cloneLink(isWiki bool) *repoutil.CloneLink {
repoName := r.Name repoName := r.Name
if isWiki { if isWiki {
repoName += ".wiki" repoName += ".wiki"
} }
r.Owner = r.MustOwner() r.Owner = r.MustOwner()
cl := new(repox.CloneLink) cl := new(repoutil.CloneLink)
if conf.SSH.Port != 22 { if conf.SSH.Port != 22 {
cl.SSH = fmt.Sprintf("ssh://%s@%s:%d/%s/%s.git", conf.App.RunUser, conf.SSH.Domain, conf.SSH.Port, r.Owner.Name, repoName) cl.SSH = fmt.Sprintf("ssh://%s@%s:%d/%s/%s.git", conf.App.RunUser, conf.SSH.Domain, conf.SSH.Port, r.Owner.Name, repoName)
} else { } else {
cl.SSH = fmt.Sprintf("%s@%s:%s/%s.git", conf.App.RunUser, conf.SSH.Domain, r.Owner.Name, repoName) cl.SSH = fmt.Sprintf("%s@%s:%s/%s.git", conf.App.RunUser, conf.SSH.Domain, r.Owner.Name, repoName)
} }
cl.HTTPS = repox.HTTPSCloneURL(r.Owner.Name, repoName) cl.HTTPS = repoutil.HTTPSCloneURL(r.Owner.Name, repoName)
return cl return cl
} }
// CloneLink returns clone URLs of repository. // CloneLink returns clone URLs of repository.
// //
// Deprecated: Use repox.NewCloneLink instead. // Deprecated: Use repoutil.NewCloneLink instead.
func (r *Repository) CloneLink() (cl *repox.CloneLink) { func (r *Repository) CloneLink() (cl *repoutil.CloneLink) {
return r.cloneLink(false) return r.cloneLink(false)
} }
@@ -990,7 +990,7 @@ func getRepoInitFile(tp, name string) ([]byte, error) {
// Use custom file when available. // Use custom file when available.
customPath := filepath.Join(conf.CustomDir(), "conf", relPath) customPath := filepath.Join(conf.CustomDir(), "conf", relPath)
if osx.IsFile(customPath) { if osutil.IsFile(customPath) {
return os.ReadFile(customPath) return os.ReadFile(customPath)
} }
return embedConf.Files.ReadFile(relPath) return embedConf.Files.ReadFile(relPath)
@@ -1148,14 +1148,14 @@ func createRepository(e *xorm.Session, doer, owner *User, repo *Repository) (err
if err != nil { if err != nil {
return errors.Newf("IsRepositoryExist: %v", err) return errors.Newf("IsRepositoryExist: %v", err)
} else if has { } else if has {
return ErrRepoAlreadyExist{args: errx.Args{"ownerID": owner.ID, "name": repo.Name}} return ErrRepoAlreadyExist{args: errutil.Args{"ownerID": owner.ID, "name": repo.Name}}
} }
if _, err = e.Insert(repo); err != nil { if _, err = e.Insert(repo); err != nil {
return err return err
} }
_, err = e.Exec(dbx.Quote("UPDATE %s SET num_repos = num_repos + 1 WHERE id = ?", "user"), owner.ID) _, err = e.Exec(dbutil.Quote("UPDATE %s SET num_repos = num_repos + 1 WHERE id = ?", "user"), owner.ID)
if err != nil { if err != nil {
return errors.Wrap(err, "increase owned repository count") return errors.Wrap(err, "increase owned repository count")
} }
@@ -1222,7 +1222,7 @@ func (err ErrReachLimitOfRepo) Error() string {
// CreateRepository creates a repository for given user or organization. // CreateRepository creates a repository for given user or organization.
func CreateRepository(doer, owner *User, opts CreateRepoOptionsLegacy) (_ *Repository, err error) { func CreateRepository(doer, owner *User, opts CreateRepoOptionsLegacy) (_ *Repository, err error) {
repoPath := RepoPath(owner.Name, opts.Name) repoPath := RepoPath(owner.Name, opts.Name)
if osx.Exist(repoPath) { if osutil.Exist(repoPath) {
return nil, errors.Errorf("repository directory already exists: %s", repoPath) return nil, errors.Errorf("repository directory already exists: %s", repoPath)
} }
if !owner.canCreateRepo() { if !owner.canCreateRepo() {
@@ -1361,9 +1361,9 @@ func FilterRepositoryWithIssues(repoIDs []int64) ([]int64, error) {
// RepoPath returns repository path by given user and repository name. // RepoPath returns repository path by given user and repository name.
// //
// Deprecated: Use repox.RepositoryPath instead. // Deprecated: Use repoutil.RepositoryPath instead.
func RepoPath(userName, repoName string) string { func RepoPath(userName, repoName string) string {
return filepath.Join(repox.UserPath(userName), strings.ToLower(repoName)+".git") return filepath.Join(repoutil.UserPath(userName), strings.ToLower(repoName)+".git")
} }
// TransferOwnership transfers all corresponding setting from old user to new one. // TransferOwnership transfers all corresponding setting from old user to new one.
@@ -1378,7 +1378,7 @@ func TransferOwnership(doer *User, newOwnerName string, repo *Repository) error
if err != nil { if err != nil {
return errors.Newf("IsRepositoryExist: %v", err) return errors.Newf("IsRepositoryExist: %v", err)
} else if has { } else if has {
return ErrRepoAlreadyExist{args: errx.Args{"ownerName": newOwnerName, "name": repo.Name}} return ErrRepoAlreadyExist{args: errutil.Args{"ownerName": newOwnerName, "name": repo.Name}}
} }
sess := x.NewSession() sess := x.NewSession()
@@ -1490,7 +1490,7 @@ func TransferOwnership(doer *User, newOwnerName string, repo *Repository) error
} }
// Rename remote repository to new path and delete local copy. // Rename remote repository to new path and delete local copy.
if err = os.MkdirAll(repox.UserPath(newOwner.Name), os.ModePerm); err != nil { if err = os.MkdirAll(repoutil.UserPath(newOwner.Name), os.ModePerm); err != nil {
return err return err
} }
if err = os.Rename(RepoPath(owner.Name, repo.Name), RepoPath(newOwner.Name, repo.Name)); err != nil { if err = os.Rename(RepoPath(owner.Name, repo.Name), RepoPath(newOwner.Name, repo.Name)); err != nil {
@@ -1501,7 +1501,7 @@ func TransferOwnership(doer *User, newOwnerName string, repo *Repository) error
// Rename remote wiki repository to new path and delete local copy. // Rename remote wiki repository to new path and delete local copy.
wikiPath := WikiPath(owner.Name, repo.Name) wikiPath := WikiPath(owner.Name, repo.Name)
if osx.Exist(wikiPath) { if osutil.Exist(wikiPath) {
RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath()) RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
if err = os.Rename(wikiPath, WikiPath(newOwner.Name, repo.Name)); err != nil { if err = os.Rename(wikiPath, WikiPath(newOwner.Name, repo.Name)); err != nil {
return errors.Newf("rename repository wiki: %v", err) return errors.Newf("rename repository wiki: %v", err)
@@ -1514,7 +1514,7 @@ func TransferOwnership(doer *User, newOwnerName string, repo *Repository) error
func deleteRepoLocalCopy(repoID int64) { func deleteRepoLocalCopy(repoID int64) {
repoWorkingPool.CheckIn(strconv.FormatInt(repoID, 10)) repoWorkingPool.CheckIn(strconv.FormatInt(repoID, 10))
defer repoWorkingPool.CheckOut(strconv.FormatInt(repoID, 10)) defer repoWorkingPool.CheckOut(strconv.FormatInt(repoID, 10))
RemoveAllWithNotice(fmt.Sprintf("Delete repository %d local copy", repoID), repox.RepositoryLocalPath(repoID)) RemoveAllWithNotice(fmt.Sprintf("Delete repository %d local copy", repoID), repoutil.RepositoryLocalPath(repoID))
} }
// ChangeRepositoryName changes all corresponding setting from old repository name to new one. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
@@ -1529,7 +1529,7 @@ func ChangeRepositoryName(u *User, oldRepoName, newRepoName string) (err error)
if err != nil { if err != nil {
return errors.Newf("IsRepositoryExist: %v", err) return errors.Newf("IsRepositoryExist: %v", err)
} else if has { } else if has {
return ErrRepoAlreadyExist{args: errx.Args{"ownerID": u.ID, "name": newRepoName}} return ErrRepoAlreadyExist{args: errutil.Args{"ownerID": u.ID, "name": newRepoName}}
} }
repo, err := GetRepositoryByName(u.ID, oldRepoName) repo, err := GetRepositoryByName(u.ID, oldRepoName)
@@ -1543,7 +1543,7 @@ func ChangeRepositoryName(u *User, oldRepoName, newRepoName string) (err error)
} }
wikiPath := repo.WikiPath() wikiPath := repo.WikiPath()
if osx.Exist(wikiPath) { if osutil.Exist(wikiPath) {
if err = os.Rename(wikiPath, WikiPath(u.Name, newRepoName)); err != nil { if err = os.Rename(wikiPath, WikiPath(u.Name, newRepoName)); err != nil {
return errors.Newf("rename repository wiki: %v", err) return errors.Newf("rename repository wiki: %v", err)
} }
@@ -1601,11 +1601,11 @@ func updateRepository(e Engine, repo *Repository, visibilityChanged bool) (err e
// Create/Remove git-daemon-export-ok for git-daemon // Create/Remove git-daemon-export-ok for git-daemon
daemonExportFile := path.Join(repo.RepoPath(), "git-daemon-export-ok") daemonExportFile := path.Join(repo.RepoPath(), "git-daemon-export-ok")
if repo.IsPrivate && osx.Exist(daemonExportFile) { if repo.IsPrivate && osutil.Exist(daemonExportFile) {
if err = os.Remove(daemonExportFile); err != nil { if err = os.Remove(daemonExportFile); err != nil {
log.Error("Failed to remove %s: %v", daemonExportFile, err) log.Error("Failed to remove %s: %v", daemonExportFile, err)
} }
} else if !repo.IsPrivate && !osx.Exist(daemonExportFile) { } else if !repo.IsPrivate && !osutil.Exist(daemonExportFile) {
if f, err := os.Create(daemonExportFile); err != nil { if f, err := os.Create(daemonExportFile); err != nil {
log.Error("Failed to create %s: %v", daemonExportFile, err) log.Error("Failed to create %s: %v", daemonExportFile, err)
} else { } else {
@@ -1937,7 +1937,7 @@ func DeleteOldRepositoryArchives() {
basePath := filepath.Join(repo.RepoPath(), "archives") basePath := filepath.Join(repo.RepoPath(), "archives")
for _, format := range formats { for _, format := range formats {
dirPath := filepath.Join(basePath, format) dirPath := filepath.Join(basePath, format)
if !osx.IsDir(dirPath) { if !osutil.IsDir(dirPath) {
continue continue
} }
@@ -2000,7 +2000,7 @@ func gatherMissingRepoRecords() ([]*Repository, error) {
if err := x.Where("id > 0").Iterate(new(Repository), if err := x.Where("id > 0").Iterate(new(Repository),
func(idx int, bean any) error { func(idx int, bean any) error {
repo := bean.(*Repository) repo := bean.(*Repository)
if !osx.IsDir(repo.RepoPath()) { if !osutil.IsDir(repo.RepoPath()) {
repos = append(repos, repo) repos = append(repos, repo)
} }
return nil return nil

View File

@@ -9,7 +9,7 @@ import (
"github.com/cockroachdb/errors" "github.com/cockroachdb/errors"
"github.com/gogs/git-module" "github.com/gogs/git-module"
"gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/tool" "gogs.io/gogs/internal/tool"
) )
@@ -42,7 +42,7 @@ func GetBranchesByPath(path string) ([]*Branch, error) {
return branches, nil return branches, nil
} }
var _ errx.NotFound = (*ErrBranchNotExist)(nil) var _ errutil.NotFound = (*ErrBranchNotExist)(nil)
type ErrBranchNotExist struct { type ErrBranchNotExist struct {
args map[string]any args map[string]any

View File

@@ -18,11 +18,11 @@ 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/cryptox" "gogs.io/gogs/internal/cryptoutil"
"gogs.io/gogs/internal/gitx" "gogs.io/gogs/internal/gitutil"
"gogs.io/gogs/internal/iox" "gogs.io/gogs/internal/ioutil"
"gogs.io/gogs/internal/osx" "gogs.io/gogs/internal/osutil"
"gogs.io/gogs/internal/pathx" "gogs.io/gogs/internal/pathutil"
"gogs.io/gogs/internal/process" "gogs.io/gogs/internal/process"
) )
@@ -68,7 +68,7 @@ func ComposeHookEnvs(opts ComposeHookEnvsOptions) []string {
EnvAuthUserName + "=" + opts.AuthUser.Name, EnvAuthUserName + "=" + opts.AuthUser.Name,
EnvAuthUserEmail + "=" + opts.AuthUser.Email, EnvAuthUserEmail + "=" + opts.AuthUser.Email,
EnvRepoOwnerName + "=" + opts.OwnerName, EnvRepoOwnerName + "=" + opts.OwnerName,
EnvRepoOwnerSaltMd5 + "=" + cryptox.MD5(opts.OwnerSalt), EnvRepoOwnerSaltMd5 + "=" + cryptoutil.MD5(opts.OwnerSalt),
EnvRepoID + "=" + strconv.FormatInt(opts.RepoID, 10), EnvRepoID + "=" + strconv.FormatInt(opts.RepoID, 10),
EnvRepoName + "=" + opts.RepoName, EnvRepoName + "=" + opts.RepoName,
EnvRepoCustomHooksPath + "=" + filepath.Join(opts.RepoPath, "custom_hooks"), EnvRepoCustomHooksPath + "=" + filepath.Join(opts.RepoPath, "custom_hooks"),
@@ -86,7 +86,7 @@ func ComposeHookEnvs(opts ComposeHookEnvsOptions) []string {
// discardLocalRepoBranchChanges discards local commits/changes of // discardLocalRepoBranchChanges discards local commits/changes of
// given branch to make sure it is even to remote branch. // given branch to make sure it is even to remote branch.
func discardLocalRepoBranchChanges(localPath, branch string) error { func discardLocalRepoBranchChanges(localPath, branch string) error {
if !osx.Exist(localPath) { if !osutil.Exist(localPath) {
return nil return nil
} }
@@ -123,7 +123,7 @@ func hasSymlinkInPath(base, relPath string) bool {
parts := strings.Split(filepath.ToSlash(relPath), "/") parts := strings.Split(filepath.ToSlash(relPath), "/")
for i := range parts { for i := range parts {
filePath := path.Join(append([]string{base}, parts[:i+1]...)...) filePath := path.Join(append([]string{base}, parts[:i+1]...)...)
if osx.IsSymlink(filePath) { if osutil.IsSymlink(filePath) {
return true return true
} }
} }
@@ -189,7 +189,7 @@ func (r *Repository) UpdateRepoFile(doer *User, opts UpdateRepoFileOptions) erro
newFilePath := path.Join(localPath, opts.NewTreeName) newFilePath := path.Join(localPath, opts.NewTreeName)
// Prompt the user if the meant-to-be new file already exists. // Prompt the user if the meant-to-be new file already exists.
if osx.Exist(newFilePath) && opts.IsNewFile { if osutil.Exist(newFilePath) && opts.IsNewFile {
return ErrRepoFileAlreadyExist{newFilePath} return ErrRepoFileAlreadyExist{newFilePath}
} }
@@ -197,7 +197,7 @@ func (r *Repository) UpdateRepoFile(doer *User, opts UpdateRepoFileOptions) erro
return errors.Wrapf(err, "create parent directories of %q", newFilePath) return errors.Wrapf(err, "create parent directories of %q", newFilePath)
} }
if osx.IsFile(oldFilePath) && opts.OldTreeName != opts.NewTreeName { if osutil.IsFile(oldFilePath) && opts.OldTreeName != opts.NewTreeName {
if err := git.Move(localPath, opts.OldTreeName, opts.NewTreeName); err != nil { if err := git.Move(localPath, opts.OldTreeName, opts.NewTreeName); err != nil {
return errors.Wrapf(err, "git mv %q %q", opts.OldTreeName, opts.NewTreeName) return errors.Wrapf(err, "git mv %q %q", opts.OldTreeName, opts.NewTreeName)
} }
@@ -244,7 +244,7 @@ func (r *Repository) UpdateRepoFile(doer *User, opts UpdateRepoFileOptions) erro
} }
// GetDiffPreview produces and returns diff result of a file which is not yet committed. // GetDiffPreview produces and returns diff result of a file which is not yet committed.
func (r *Repository) GetDiffPreview(branch, treePath, content string) (*gitx.Diff, error) { func (r *Repository) GetDiffPreview(branch, treePath, content string) (*gitutil.Diff, error) {
// 🚨 SECURITY: Prevent uploading files into the ".git" directory. // 🚨 SECURITY: Prevent uploading files into the ".git" directory.
if isRepositoryGitPath(treePath) { if isRepositoryGitPath(treePath) {
return nil, errors.Errorf("bad tree path %q", treePath) return nil, errors.Errorf("bad tree path %q", treePath)
@@ -291,7 +291,7 @@ func (r *Repository) GetDiffPreview(branch, treePath, content string) (*gitx.Dif
pid := process.Add(fmt.Sprintf("GetDiffPreview [repo_path: %s]", r.RepoPath()), cmd) pid := process.Add(fmt.Sprintf("GetDiffPreview [repo_path: %s]", r.RepoPath()), cmd)
defer process.Remove(pid) defer process.Remove(pid)
diff, err := gitx.ParseDiff(stdout, conf.Git.MaxDiffFiles, conf.Git.MaxDiffLines, conf.Git.MaxDiffLineChars) diff, err := gitutil.ParseDiff(stdout, conf.Git.MaxDiffFiles, conf.Git.MaxDiffLines, conf.Git.MaxDiffLineChars)
if err != nil { if err != nil {
return nil, errors.Newf("parse diff: %v", err) return nil, errors.Newf("parse diff: %v", err)
} }
@@ -416,7 +416,7 @@ func (upload *Upload) LocalPath() string {
// NewUpload creates a new upload object. // NewUpload creates a new upload object.
func NewUpload(name string, buf []byte, file multipart.File) (_ *Upload, err error) { func NewUpload(name string, buf []byte, file multipart.File) (_ *Upload, err error) {
// 🚨 SECURITY: Prevent path traversal. // 🚨 SECURITY: Prevent path traversal.
name = pathx.Clean(name) name = pathutil.Clean(name)
if name == "" { if name == "" {
return nil, errors.New("empty file name") return nil, errors.New("empty file name")
} }
@@ -492,7 +492,7 @@ func DeleteUploads(uploads ...*Upload) (err error) {
for _, upload := range uploads { for _, upload := range uploads {
localPath := upload.LocalPath() localPath := upload.LocalPath()
if !osx.IsFile(localPath) { if !osutil.IsFile(localPath) {
continue continue
} }
@@ -536,7 +536,7 @@ type UploadRepoFileOptions struct {
// isRepositoryGitPath returns true if given path is or resides inside ".git" // isRepositoryGitPath returns true if given path is or resides inside ".git"
// path of the repository. // path of the repository.
// //
// TODO(unknwon): Move to repox during refactoring for this file. // TODO(unknwon): Move to repoutil during refactoring for this file.
func isRepositoryGitPath(path string) bool { func isRepositoryGitPath(path string) bool {
path = strings.ToLower(path) path = strings.ToLower(path)
return strings.HasSuffix(path, ".git") || return strings.HasSuffix(path, ".git") ||
@@ -587,12 +587,12 @@ func (r *Repository) UploadRepoFiles(doer *User, opts UploadRepoFileOptions) err
// Copy uploaded files into repository // Copy uploaded files into repository
for _, upload := range uploads { for _, upload := range uploads {
tmpPath := upload.LocalPath() tmpPath := upload.LocalPath()
if !osx.IsFile(tmpPath) { if !osutil.IsFile(tmpPath) {
continue continue
} }
// 🚨 SECURITY: Prevent path traversal. // 🚨 SECURITY: Prevent path traversal.
upload.Name = pathx.Clean(upload.Name) upload.Name = pathutil.Clean(upload.Name)
// 🚨 SECURITY: Prevent uploading files into the ".git" directory. // 🚨 SECURITY: Prevent uploading files into the ".git" directory.
if isRepositoryGitPath(upload.Name) { if isRepositoryGitPath(upload.Name) {
@@ -603,11 +603,11 @@ func (r *Repository) UploadRepoFiles(doer *User, opts UploadRepoFileOptions) err
// 🚨 SECURITY: Prevent updating files in surprising place, check if the target // 🚨 SECURITY: Prevent updating files in surprising place, check if the target
// is a symlink. // is a symlink.
if osx.IsSymlink(targetPath) { if osutil.IsSymlink(targetPath) {
return errors.Newf("cannot overwrite symbolic link: %s", upload.Name) return errors.Newf("cannot overwrite symbolic link: %s", upload.Name)
} }
if err = iox.CopyFile(tmpPath, targetPath); err != nil { if err = ioutil.CopyFile(tmpPath, targetPath); err != nil {
return errors.Newf("copy: %v", err) return errors.Newf("copy: %v", err)
} }
} }

View File

@@ -10,7 +10,7 @@ import (
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/markup" "gogs.io/gogs/internal/markup"
"gogs.io/gogs/internal/osx" "gogs.io/gogs/internal/osutil"
) )
func TestRepository_ComposeMetas(t *testing.T) { func TestRepository_ComposeMetas(t *testing.T) {
@@ -81,5 +81,5 @@ func Test_CreateRepository_PreventDeletion(t *testing.T) {
_, err = CreateRepository(owner, owner, opts) _, err = CreateRepository(owner, owner, opts)
require.Error(t, err) require.Error(t, err)
assert.Contains(t, err.Error(), "repository directory already exists") assert.Contains(t, err.Error(), "repository directory already exists")
assert.True(t, osx.Exist(canary)) assert.True(t, osutil.Exist(canary))
} }

View File

@@ -9,8 +9,8 @@ import (
"github.com/cockroachdb/errors" "github.com/cockroachdb/errors"
"gorm.io/gorm" "gorm.io/gorm"
"gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/repox" "gogs.io/gogs/internal/repoutil"
apiv1types "gogs.io/gogs/internal/route/api/v1/types" apiv1types "gogs.io/gogs/internal/route/api/v1/types"
) )
@@ -47,7 +47,7 @@ func (r *Repository) APIFormat(owner *User, opts ...RepositoryAPIFormatOptions)
opt = opts[0] opt = opts[0]
} }
cloneLink := repox.NewCloneLink(owner.Name, r.Name, false) cloneLink := repoutil.NewCloneLink(owner.Name, r.Name, false)
return &apiv1types.Repository{ return &apiv1types.Repository{
ID: r.ID, ID: r.ID,
Owner: owner.APIFormat(), Owner: owner.APIFormat(),
@@ -60,7 +60,7 @@ func (r *Repository) APIFormat(owner *User, opts ...RepositoryAPIFormatOptions)
Empty: r.IsBare, Empty: r.IsBare,
Mirror: r.IsMirror, Mirror: r.IsMirror,
Size: r.Size, Size: r.Size,
HTMLURL: repox.HTMLURL(owner.Name, r.Name), HTMLURL: repoutil.HTMLURL(owner.Name, r.Name),
SSHURL: cloneLink.SSH, SSHURL: cloneLink.SSH,
CloneURL: cloneLink.HTTPS, CloneURL: cloneLink.HTTPS,
Website: r.Website, Website: r.Website,
@@ -85,7 +85,7 @@ func newReposStore(db *gorm.DB) *RepositoriesStore {
} }
type ErrRepoAlreadyExist struct { type ErrRepoAlreadyExist struct {
args errx.Args args errutil.Args
} }
func IsErrRepoAlreadyExist(err error) bool { func IsErrRepoAlreadyExist(err error) bool {
@@ -123,7 +123,7 @@ func (s *RepositoriesStore) Create(ctx context.Context, ownerID int64, opts Crea
_, err = s.GetByName(ctx, ownerID, opts.Name) _, err = s.GetByName(ctx, ownerID, opts.Name)
if err == nil { if err == nil {
return nil, ErrRepoAlreadyExist{ return nil, ErrRepoAlreadyExist{
args: errx.Args{ args: errutil.Args{
"ownerID": ownerID, "ownerID": ownerID,
"name": opts.Name, "name": opts.Name,
}, },
@@ -221,10 +221,10 @@ func (s *RepositoriesStore) GetByCollaboratorIDWithAccessMode(ctx context.Contex
return repos, nil return repos, nil
} }
var _ errx.NotFound = (*ErrRepoNotExist)(nil) var _ errutil.NotFound = (*ErrRepoNotExist)(nil)
type ErrRepoNotExist struct { type ErrRepoNotExist struct {
args errx.Args args errutil.Args
} }
func IsErrRepoNotExist(err error) bool { func IsErrRepoNotExist(err error) bool {
@@ -247,7 +247,7 @@ func (s *RepositoriesStore) GetByID(ctx context.Context, id int64) (*Repository,
err := s.db.WithContext(ctx).Where("id = ?", id).First(repo).Error err := s.db.WithContext(ctx).Where("id = ?", id).First(repo).Error
if err != nil { if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) { if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrRepoNotExist{errx.Args{"repoID": id}} return nil, ErrRepoNotExist{errutil.Args{"repoID": id}}
} }
return nil, err return nil, err
} }
@@ -265,7 +265,7 @@ func (s *RepositoriesStore) GetByName(ctx context.Context, ownerID int64, name s
if err != nil { if err != nil {
if err == gorm.ErrRecordNotFound { if err == gorm.ErrRecordNotFound {
return nil, ErrRepoNotExist{ return nil, ErrRepoNotExist{
args: errx.Args{ args: errutil.Args{
"ownerID": ownerID, "ownerID": ownerID,
"name": name, "name": name,
}, },

View File

@@ -9,7 +9,7 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"gorm.io/gorm" "gorm.io/gorm"
"gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/errutil"
) )
func TestRepository_BeforeCreate(t *testing.T) { func TestRepository_BeforeCreate(t *testing.T) {
@@ -121,7 +121,7 @@ func reposCreate(t *testing.T, ctx context.Context, s *RepositoriesStore) {
Name: "my.git", Name: "my.git",
}, },
) )
wantErr := ErrNameNotAllowed{args: errx.Args{"reason": "reserved", "pattern": "*.git"}} wantErr := ErrNameNotAllowed{args: errutil.Args{"reason": "reserved", "pattern": "*.git"}}
assert.Equal(t, wantErr, err) assert.Equal(t, wantErr, err)
}) })
@@ -138,7 +138,7 @@ func reposCreate(t *testing.T, ctx context.Context, s *RepositoriesStore) {
Name: "repo1", Name: "repo1",
}, },
) )
wantErr := ErrRepoAlreadyExist{args: errx.Args{"ownerID": int64(2), "name": "repo1"}} wantErr := ErrRepoAlreadyExist{args: errutil.Args{"ownerID": int64(2), "name": "repo1"}}
assert.Equal(t, wantErr, err) assert.Equal(t, wantErr, err)
}) })
@@ -218,7 +218,7 @@ func reposGetByID(t *testing.T, ctx context.Context, s *RepositoriesStore) {
assert.Equal(t, repo1.Name, got.Name) assert.Equal(t, repo1.Name, got.Name)
_, err = s.GetByID(ctx, 404) _, err = s.GetByID(ctx, 404)
wantErr := ErrRepoNotExist{args: errx.Args{"repoID": int64(404)}} wantErr := ErrRepoNotExist{args: errutil.Args{"repoID": int64(404)}}
assert.Equal(t, wantErr, err) assert.Equal(t, wantErr, err)
} }
@@ -234,7 +234,7 @@ func reposGetByName(t *testing.T, ctx context.Context, s *RepositoriesStore) {
require.NoError(t, err) require.NoError(t, err)
_, err = s.GetByName(ctx, 1, "bad_name") _, err = s.GetByName(ctx, 1, "bad_name")
wantErr := ErrRepoNotExist{args: errx.Args{"ownerID": int64(1), "name": "bad_name"}} wantErr := ErrRepoNotExist{args: errutil.Args{"ownerID": int64(1), "name": "bad_name"}}
assert.Equal(t, wantErr, err) assert.Equal(t, wantErr, err)
} }

View File

@@ -20,8 +20,8 @@ import (
"xorm.io/xorm" "xorm.io/xorm"
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/osx" "gogs.io/gogs/internal/osutil"
"gogs.io/gogs/internal/process" "gogs.io/gogs/internal/process"
) )
@@ -542,7 +542,7 @@ func RewriteAuthorizedKeys() error {
return err return err
} }
if osx.Exist(fpath) { if osutil.Exist(fpath) {
if err = os.Remove(fpath); err != nil { if err = os.Remove(fpath); err != nil {
return err return err
} }
@@ -685,7 +685,7 @@ func AddDeployKey(repoID int64, name, content string) (*DeployKey, error) {
return key, sess.Commit() return key, sess.Commit()
} }
var _ errx.NotFound = (*ErrDeployKeyNotExist)(nil) var _ errutil.NotFound = (*ErrDeployKeyNotExist)(nil)
type ErrDeployKeyNotExist struct { type ErrDeployKeyNotExist struct {
args map[string]any args map[string]any

View File

@@ -9,7 +9,7 @@ import (
"github.com/pquerna/otp/totp" "github.com/pquerna/otp/totp"
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/cryptox" "gogs.io/gogs/internal/cryptoutil"
) )
// TwoFactor is a 2FA token of a user. // TwoFactor is a 2FA token of a user.
@@ -28,7 +28,7 @@ func (t *TwoFactor) ValidateTOTP(passcode string) (bool, error) {
if err != nil { if err != nil {
return false, errors.Newf("DecodeString: %v", err) return false, errors.Newf("DecodeString: %v", err)
} }
decryptSecret, err := cryptox.AESGCMDecrypt(cryptox.MD5Bytes(conf.Security.SecretKey), secret) decryptSecret, err := cryptoutil.AESGCMDecrypt(cryptoutil.MD5Bytes(conf.Security.SecretKey), secret)
if err != nil { if err != nil {
return false, errors.Newf("AESGCMDecrypt: %v", err) return false, errors.Newf("AESGCMDecrypt: %v", err)
} }

View File

@@ -11,9 +11,9 @@ import (
"gorm.io/gorm" "gorm.io/gorm"
log "unknwon.dev/clog/v2" log "unknwon.dev/clog/v2"
"gogs.io/gogs/internal/cryptox" "gogs.io/gogs/internal/cryptoutil"
"gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/strx" "gogs.io/gogs/internal/strutil"
) )
// BeforeCreate implements the GORM create hook. // BeforeCreate implements the GORM create hook.
@@ -44,7 +44,7 @@ func newTwoFactorsStore(db *gorm.DB) *TwoFactorsStore {
// configured in site-level and change of the "key" will break all existing 2FA // configured in site-level and change of the "key" will break all existing 2FA
// tokens. // tokens.
func (s *TwoFactorsStore) Create(ctx context.Context, userID int64, key, secret string) error { func (s *TwoFactorsStore) Create(ctx context.Context, userID int64, key, secret string) error {
encrypted, err := cryptox.AESGCMEncrypt(cryptox.MD5Bytes(key), []byte(secret)) encrypted, err := cryptoutil.AESGCMEncrypt(cryptoutil.MD5Bytes(key), []byte(secret))
if err != nil { if err != nil {
return errors.Wrap(err, "encrypt secret") return errors.Wrap(err, "encrypt secret")
} }
@@ -68,10 +68,10 @@ func (s *TwoFactorsStore) Create(ctx context.Context, userID int64, key, secret
}) })
} }
var _ errx.NotFound = (*ErrTwoFactorNotFound)(nil) var _ errutil.NotFound = (*ErrTwoFactorNotFound)(nil)
type ErrTwoFactorNotFound struct { type ErrTwoFactorNotFound struct {
args errx.Args args errutil.Args
} }
func IsErrTwoFactorNotFound(err error) bool { func IsErrTwoFactorNotFound(err error) bool {
@@ -93,7 +93,7 @@ func (s *TwoFactorsStore) GetByUserID(ctx context.Context, userID int64) (*TwoFa
err := s.db.WithContext(ctx).Where("user_id = ?", userID).First(tf).Error err := s.db.WithContext(ctx).Where("user_id = ?", userID).First(tf).Error
if err != nil { if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) { if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrTwoFactorNotFound{args: errx.Args{"userID": userID}} return nil, ErrTwoFactorNotFound{args: errutil.Args{"userID": userID}}
} }
return nil, err return nil, err
} }
@@ -136,7 +136,7 @@ func (s *TwoFactorsStore) UseRecoveryCode(ctx context.Context, userID int64, cod
func generateRecoveryCodes(userID int64, n int) ([]*TwoFactorRecoveryCode, error) { func generateRecoveryCodes(userID int64, n int) ([]*TwoFactorRecoveryCode, error) {
recoveryCodes := make([]*TwoFactorRecoveryCode, n) recoveryCodes := make([]*TwoFactorRecoveryCode, n)
for i := range n { for i := range n {
code, err := strx.RandomChars(10) code, err := strutil.RandomChars(10)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "generate random characters") return nil, errors.Wrap(err, "generate random characters")
} }

View File

@@ -9,7 +9,7 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"gorm.io/gorm" "gorm.io/gorm"
"gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/errutil"
) )
func TestTwoFactor_BeforeCreate(t *testing.T) { func TestTwoFactor_BeforeCreate(t *testing.T) {
@@ -117,7 +117,7 @@ func twoFactorsGetByUserID(t *testing.T, ctx context.Context, s *TwoFactorsStore
// Try to get a non-existent 2FA token // Try to get a non-existent 2FA token
_, err = s.GetByUserID(ctx, 2) _, err = s.GetByUserID(ctx, 2)
wantErr := ErrTwoFactorNotFound{args: errx.Args{"userID": int64(2)}} wantErr := ErrTwoFactorNotFound{args: errutil.Args{"userID": int64(2)}}
assert.Equal(t, wantErr, err) assert.Equal(t, wantErr, err)
} }

View File

@@ -16,16 +16,16 @@ 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/cryptox" "gogs.io/gogs/internal/cryptoutil"
"gogs.io/gogs/internal/dbx" "gogs.io/gogs/internal/dbutil"
"gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/markup" "gogs.io/gogs/internal/markup"
"gogs.io/gogs/internal/osx" "gogs.io/gogs/internal/osutil"
"gogs.io/gogs/internal/repox" "gogs.io/gogs/internal/repoutil"
apiv1types "gogs.io/gogs/internal/route/api/v1/types" apiv1types "gogs.io/gogs/internal/route/api/v1/types"
"gogs.io/gogs/internal/strx" "gogs.io/gogs/internal/strutil"
"gogs.io/gogs/internal/tool" "gogs.io/gogs/internal/tool"
"gogs.io/gogs/internal/userx" "gogs.io/gogs/internal/userutil"
) )
// UsersStore is the storage layer for users. // UsersStore is the storage layer for users.
@@ -38,7 +38,7 @@ func newUsersStore(db *gorm.DB) *UsersStore {
} }
type ErrLoginSourceMismatch struct { type ErrLoginSourceMismatch struct {
args errx.Args args errutil.Args
} }
// IsErrLoginSourceMismatch returns true if the underlying error has the type // IsErrLoginSourceMismatch returns true if the underlying error has the type
@@ -86,12 +86,12 @@ func (s *UsersStore) Authenticate(ctx context.Context, login, password string, l
// Note: This check is unnecessary but to reduce user confusion at login page // Note: This check is unnecessary but to reduce user confusion at login page
// and make it more consistent from user's perspective. // and make it more consistent from user's perspective.
if loginSourceID >= 0 && user.LoginSource != loginSourceID { if loginSourceID >= 0 && user.LoginSource != loginSourceID {
return nil, ErrLoginSourceMismatch{args: errx.Args{"expect": loginSourceID, "actual": user.LoginSource}} return nil, ErrLoginSourceMismatch{args: errutil.Args{"expect": loginSourceID, "actual": user.LoginSource}}
} }
// Validate password hash fetched from database for local accounts. // Validate password hash fetched from database for local accounts.
if user.IsLocal() { if user.IsLocal() {
if userx.ValidatePassword(user.Password, user.Salt, password) { if userutil.ValidatePassword(user.Password, user.Salt, password) {
return user, nil return user, nil
} }
@@ -158,7 +158,7 @@ func (s *UsersStore) ChangeUsername(ctx context.Context, userID int64, newUserna
if s.IsUsernameUsed(ctx, newUsername, userID) { if s.IsUsernameUsed(ctx, newUsername, userID) {
return ErrUserAlreadyExist{ return ErrUserAlreadyExist{
args: errx.Args{ args: errutil.Args{
"name": newUsername, "name": newUsername,
}, },
} }
@@ -212,16 +212,16 @@ func (s *UsersStore) ChangeUsername(ctx context.Context, userID int64, newUserna
} }
deleteRepoLocalCopy(repo.ID) deleteRepoLocalCopy(repo.ID)
RemoveAllWithNotice(fmt.Sprintf("Delete repository %d wiki local copy", repo.ID), repox.RepositoryLocalWikiPath(repo.ID)) RemoveAllWithNotice(fmt.Sprintf("Delete repository %d wiki local copy", repo.ID), repoutil.RepositoryLocalWikiPath(repo.ID))
} }
if err = rows.Err(); err != nil { if err = rows.Err(); err != nil {
return errors.Wrap(err, "check rows.Err") return errors.Wrap(err, "check rows.Err")
} }
// Rename user directory if exists // Rename user directory if exists
userPath := repox.UserPath(user.Name) userPath := repoutil.UserPath(user.Name)
if osx.Exist(userPath) { if osutil.Exist(userPath) {
newUserPath := repox.UserPath(newUsername) newUserPath := repoutil.UserPath(newUsername)
err = os.Rename(userPath, newUserPath) err = os.Rename(userPath, newUserPath)
if err != nil { if err != nil {
return errors.Wrap(err, "rename user directory") return errors.Wrap(err, "rename user directory")
@@ -250,7 +250,7 @@ type CreateUserOptions struct {
} }
type ErrUserAlreadyExist struct { type ErrUserAlreadyExist struct {
args errx.Args args errutil.Args
} }
// IsErrUserAlreadyExist returns true if the underlying error has the type // IsErrUserAlreadyExist returns true if the underlying error has the type
@@ -264,7 +264,7 @@ func (err ErrUserAlreadyExist) Error() string {
} }
type ErrEmailAlreadyUsed struct { type ErrEmailAlreadyUsed struct {
args errx.Args args errutil.Args
} }
// IsErrEmailAlreadyUsed returns true if the underlying error has the type // IsErrEmailAlreadyUsed returns true if the underlying error has the type
@@ -297,7 +297,7 @@ func (s *UsersStore) Create(ctx context.Context, username, email string, opts Cr
if s.IsUsernameUsed(ctx, username, 0) { if s.IsUsernameUsed(ctx, username, 0) {
return nil, ErrUserAlreadyExist{ return nil, ErrUserAlreadyExist{
args: errx.Args{ args: errutil.Args{
"name": username, "name": username,
}, },
} }
@@ -307,7 +307,7 @@ func (s *UsersStore) Create(ctx context.Context, username, email string, opts Cr
_, err = s.GetByEmail(ctx, email) _, err = s.GetByEmail(ctx, email)
if err == nil { if err == nil {
return nil, ErrEmailAlreadyUsed{ return nil, ErrEmailAlreadyUsed{
args: errx.Args{ args: errutil.Args{
"email": email, "email": email,
}, },
} }
@@ -328,19 +328,19 @@ func (s *UsersStore) Create(ctx context.Context, username, email string, opts Cr
MaxRepoCreation: -1, MaxRepoCreation: -1,
IsActive: opts.Activated, IsActive: opts.Activated,
IsAdmin: opts.Admin, IsAdmin: opts.Admin,
Avatar: cryptox.MD5(email), // Gravatar URL uses the MD5 hash of the email, see https://en.gravatar.com/site/implement/hash/ Avatar: cryptoutil.MD5(email), // Gravatar URL uses the MD5 hash of the email, see https://en.gravatar.com/site/implement/hash/
AvatarEmail: email, AvatarEmail: email,
} }
user.Rands, err = userx.RandomSalt() user.Rands, err = userutil.RandomSalt()
if err != nil { if err != nil {
return nil, err return nil, err
} }
user.Salt, err = userx.RandomSalt() user.Salt, err = userutil.RandomSalt()
if err != nil { if err != nil {
return nil, err return nil, err
} }
user.Password = userx.EncodePassword(user.Password, user.Salt) user.Password = userutil.EncodePassword(user.Password, user.Salt)
return user, s.db.WithContext(ctx).Create(user).Error return user, s.db.WithContext(ctx).Create(user).Error
} }
@@ -348,7 +348,7 @@ func (s *UsersStore) Create(ctx context.Context, username, email string, opts Cr
// DeleteCustomAvatar deletes the current user custom avatar and falls back to // DeleteCustomAvatar deletes the current user custom avatar and falls back to
// use look up avatar by email. // use look up avatar by email.
func (s *UsersStore) DeleteCustomAvatar(ctx context.Context, userID int64) error { func (s *UsersStore) DeleteCustomAvatar(ctx context.Context, userID int64) error {
_ = os.Remove(userx.CustomAvatarPath(userID)) _ = os.Remove(userutil.CustomAvatarPath(userID))
return s.db.WithContext(ctx). return s.db.WithContext(ctx).
Model(&User{}). Model(&User{}).
Where("id = ?", userID). Where("id = ?", userID).
@@ -360,7 +360,7 @@ func (s *UsersStore) DeleteCustomAvatar(ctx context.Context, userID int64) error
} }
type ErrUserOwnRepos struct { type ErrUserOwnRepos struct {
args errx.Args args errutil.Args
} }
// IsErrUserOwnRepos returns true if the underlying error has the type // IsErrUserOwnRepos returns true if the underlying error has the type
@@ -374,7 +374,7 @@ func (err ErrUserOwnRepos) Error() string {
} }
type ErrUserHasOrgs struct { type ErrUserHasOrgs struct {
args errx.Args args errutil.Args
} }
// IsErrUserHasOrgs returns true if the underlying error has the type // IsErrUserHasOrgs returns true if the underlying error has the type
@@ -408,14 +408,14 @@ func (s *UsersStore) DeleteByID(ctx context.Context, userID int64, skipRewriteAu
if err != nil { if err != nil {
return errors.Wrap(err, "count repositories") return errors.Wrap(err, "count repositories")
} else if count > 0 { } else if count > 0 {
return ErrUserOwnRepos{args: errx.Args{"userID": userID}} return ErrUserOwnRepos{args: errutil.Args{"userID": userID}}
} }
err = s.db.WithContext(ctx).Model(&OrgUser{}).Where("uid = ?", userID).Count(&count).Error err = s.db.WithContext(ctx).Model(&OrgUser{}).Where("uid = ?", userID).Count(&count).Error
if err != nil { if err != nil {
return errors.Wrap(err, "count organization membership") return errors.Wrap(err, "count organization membership")
} else if count > 0 { } else if count > 0 {
return ErrUserHasOrgs{args: errx.Args{"userID": userID}} return ErrUserHasOrgs{args: errutil.Args{"userID": userID}}
} }
needsRewriteAuthorizedKeys := false needsRewriteAuthorizedKeys := false
@@ -542,8 +542,8 @@ func (s *UsersStore) DeleteByID(ctx context.Context, userID int64, skipRewriteAu
return err return err
} }
_ = os.RemoveAll(repox.UserPath(user.Name)) _ = os.RemoveAll(repoutil.UserPath(user.Name))
_ = os.Remove(userx.CustomAvatarPath(userID)) _ = os.Remove(userutil.CustomAvatarPath(userID))
if needsRewriteAuthorizedKeys { if needsRewriteAuthorizedKeys {
err = newPublicKeysStore(s.db).RewriteAuthorizedKeys() err = newPublicKeysStore(s.db).RewriteAuthorizedKeys()
@@ -667,10 +667,10 @@ func (s *UsersStore) IsFollowing(ctx context.Context, userID, followID int64) bo
return s.db.WithContext(ctx).Where("user_id = ? AND follow_id = ?", userID, followID).First(&Follow{}).Error == nil return s.db.WithContext(ctx).Where("user_id = ? AND follow_id = ?", userID, followID).First(&Follow{}).Error == nil
} }
var _ errx.NotFound = (*ErrUserNotExist)(nil) var _ errutil.NotFound = (*ErrUserNotExist)(nil)
type ErrUserNotExist struct { type ErrUserNotExist struct {
args errx.Args args errutil.Args
} }
// IsErrUserNotExist returns true if the underlying error has the type // IsErrUserNotExist returns true if the underlying error has the type
@@ -692,7 +692,7 @@ func (ErrUserNotExist) NotFound() bool {
// records with unverified emails and returns ErrUserNotExist when not found. // records with unverified emails and returns ErrUserNotExist when not found.
func (s *UsersStore) GetByEmail(ctx context.Context, email string) (*User, error) { func (s *UsersStore) GetByEmail(ctx context.Context, email string) (*User, error) {
if email == "" { if email == "" {
return nil, ErrUserNotExist{args: errx.Args{"email": email}} return nil, ErrUserNotExist{args: errutil.Args{"email": email}}
} }
email = strings.ToLower(email) email = strings.ToLower(email)
@@ -710,17 +710,17 @@ func (s *UsersStore) GetByEmail(ctx context.Context, email string) (*User, error
*/ */
user := new(User) user := new(User)
err := s.db.WithContext(ctx). err := s.db.WithContext(ctx).
Joins(dbx.Quote("LEFT JOIN email_address ON email_address.uid = %s.id", "user"), true). Joins(dbutil.Quote("LEFT JOIN email_address ON email_address.uid = %s.id", "user"), true).
Where(dbx.Quote("%s.type = ?", "user"), UserTypeIndividual). Where(dbutil.Quote("%s.type = ?", "user"), UserTypeIndividual).
Where(s.db. Where(s.db.
Where(dbx.Quote("%[1]s.email = ? AND %[1]s.is_active = ?", "user"), email, true). Where(dbutil.Quote("%[1]s.email = ? AND %[1]s.is_active = ?", "user"), email, true).
Or("email_address.email = ? AND email_address.is_activated = ?", email, true), Or("email_address.email = ? AND email_address.is_activated = ?", email, true),
). ).
First(&user). First(&user).
Error Error
if err != nil { if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) { if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrUserNotExist{args: errx.Args{"email": email}} return nil, ErrUserNotExist{args: errutil.Args{"email": email}}
} }
return nil, err return nil, err
} }
@@ -734,7 +734,7 @@ func (s *UsersStore) GetByID(ctx context.Context, id int64) (*User, error) {
err := s.db.WithContext(ctx).Where("id = ?", id).First(user).Error err := s.db.WithContext(ctx).Where("id = ?", id).First(user).Error
if err != nil { if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) { if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrUserNotExist{args: errx.Args{"userID": id}} return nil, ErrUserNotExist{args: errutil.Args{"userID": id}}
} }
return nil, err return nil, err
} }
@@ -748,7 +748,7 @@ func (s *UsersStore) GetByUsername(ctx context.Context, username string) (*User,
err := s.db.WithContext(ctx).Where("lower_name = ?", strings.ToLower(username)).First(user).Error err := s.db.WithContext(ctx).Where("lower_name = ?", strings.ToLower(username)).First(user).Error
if err != nil { if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) { if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrUserNotExist{args: errx.Args{"name": username}} return nil, ErrUserNotExist{args: errutil.Args{"name": username}}
} }
return nil, err return nil, err
} }
@@ -760,13 +760,13 @@ func (s *UsersStore) GetByUsername(ctx context.Context, username string) (*User,
func (s *UsersStore) GetByKeyID(ctx context.Context, keyID int64) (*User, error) { func (s *UsersStore) GetByKeyID(ctx context.Context, keyID int64) (*User, error) {
user := new(User) user := new(User)
err := s.db.WithContext(ctx). err := s.db.WithContext(ctx).
Joins(dbx.Quote("JOIN public_key ON public_key.owner_id = %s.id", "user")). Joins(dbutil.Quote("JOIN public_key ON public_key.owner_id = %s.id", "user")).
Where("public_key.id = ?", keyID). Where("public_key.id = ?", keyID).
First(user). First(user).
Error Error
if err != nil { if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) { if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrUserNotExist{args: errx.Args{"keyID": keyID}} return nil, ErrUserNotExist{args: errutil.Args{"keyID": keyID}}
} }
return nil, err return nil, err
} }
@@ -826,7 +826,7 @@ func (s *UsersStore) ListFollowers(ctx context.Context, userID int64, page, page
*/ */
users := make([]*User, 0, pageSize) users := make([]*User, 0, pageSize)
return users, s.db.WithContext(ctx). return users, s.db.WithContext(ctx).
Joins(dbx.Quote("LEFT JOIN follow ON follow.user_id = %s.id", "user")). Joins(dbutil.Quote("LEFT JOIN follow ON follow.user_id = %s.id", "user")).
Where("follow.follow_id = ?", userID). Where("follow.follow_id = ?", userID).
Limit(pageSize).Offset((page - 1) * pageSize). Limit(pageSize).Offset((page - 1) * pageSize).
Order("follow.id DESC"). Order("follow.id DESC").
@@ -849,7 +849,7 @@ func (s *UsersStore) ListFollowings(ctx context.Context, userID int64, page, pag
*/ */
users := make([]*User, 0, pageSize) users := make([]*User, 0, pageSize)
return users, s.db.WithContext(ctx). return users, s.db.WithContext(ctx).
Joins(dbx.Quote("LEFT JOIN follow ON follow.follow_id = %s.id", "user")). Joins(dbutil.Quote("LEFT JOIN follow ON follow.follow_id = %s.id", "user")).
Where("follow.user_id = ?", userID). Where("follow.user_id = ?", userID).
Limit(pageSize).Offset((page - 1) * pageSize). Limit(pageSize).Offset((page - 1) * pageSize).
Order("follow.id DESC"). Order("follow.id DESC").
@@ -926,16 +926,16 @@ func (s *UsersStore) Update(ctx context.Context, userID int64, opts UpdateUserOp
} }
if opts.Password != nil { if opts.Password != nil {
salt, err := userx.RandomSalt() salt, err := userutil.RandomSalt()
if err != nil { if err != nil {
return errors.Wrap(err, "generate salt") return errors.Wrap(err, "generate salt")
} }
updates["salt"] = salt updates["salt"] = salt
updates["passwd"] = userx.EncodePassword(*opts.Password, salt) updates["passwd"] = userutil.EncodePassword(*opts.Password, salt)
opts.GenerateNewRands = true opts.GenerateNewRands = true
} }
if opts.GenerateNewRands { if opts.GenerateNewRands {
rands, err := userx.RandomSalt() rands, err := userutil.RandomSalt()
if err != nil { if err != nil {
return errors.Wrap(err, "generate rands") return errors.Wrap(err, "generate rands")
} }
@@ -943,25 +943,25 @@ func (s *UsersStore) Update(ctx context.Context, userID int64, opts UpdateUserOp
} }
if opts.FullName != nil { if opts.FullName != nil {
updates["full_name"] = strx.Truncate(*opts.FullName, 255) updates["full_name"] = strutil.Truncate(*opts.FullName, 255)
} }
if opts.Email != nil { if opts.Email != nil {
_, err := s.GetByEmail(ctx, *opts.Email) _, err := s.GetByEmail(ctx, *opts.Email)
if err == nil { if err == nil {
return ErrEmailAlreadyUsed{args: errx.Args{"email": *opts.Email}} return ErrEmailAlreadyUsed{args: errutil.Args{"email": *opts.Email}}
} else if !IsErrUserNotExist(err) { } else if !IsErrUserNotExist(err) {
return errors.Wrap(err, "check email") return errors.Wrap(err, "check email")
} }
updates["email"] = *opts.Email updates["email"] = *opts.Email
} }
if opts.Website != nil { if opts.Website != nil {
updates["website"] = strx.Truncate(*opts.Website, 255) updates["website"] = strutil.Truncate(*opts.Website, 255)
} }
if opts.Location != nil { if opts.Location != nil {
updates["location"] = strx.Truncate(*opts.Location, 255) updates["location"] = strutil.Truncate(*opts.Location, 255)
} }
if opts.Description != nil { if opts.Description != nil {
updates["description"] = strx.Truncate(*opts.Description, 255) updates["description"] = strutil.Truncate(*opts.Description, 255)
} }
if opts.MaxRepoCreation != nil { if opts.MaxRepoCreation != nil {
@@ -991,10 +991,10 @@ func (s *UsersStore) Update(ctx context.Context, userID int64, opts UpdateUserOp
} }
if opts.Avatar != nil { if opts.Avatar != nil {
updates["avatar"] = strx.Truncate(*opts.Avatar, 2048) updates["avatar"] = strutil.Truncate(*opts.Avatar, 2048)
} }
if opts.AvatarEmail != nil { if opts.AvatarEmail != nil {
updates["avatar_email"] = strx.Truncate(*opts.AvatarEmail, 255) updates["avatar_email"] = strutil.Truncate(*opts.AvatarEmail, 255)
} }
return s.db.WithContext(ctx).Model(&User{}).Where("id = ?", userID).Updates(updates).Error return s.db.WithContext(ctx).Model(&User{}).Where("id = ?", userID).Updates(updates).Error
@@ -1002,7 +1002,7 @@ func (s *UsersStore) Update(ctx context.Context, userID int64, opts UpdateUserOp
// UseCustomAvatar uses the given avatar as the user custom avatar. // UseCustomAvatar uses the given avatar as the user custom avatar.
func (s *UsersStore) UseCustomAvatar(ctx context.Context, userID int64, avatar []byte) error { func (s *UsersStore) UseCustomAvatar(ctx context.Context, userID int64, avatar []byte) error {
err := userx.SaveAvatar(userID, avatar) err := userutil.SaveAvatar(userID, avatar)
if err != nil { if err != nil {
return errors.Wrap(err, "save avatar") return errors.Wrap(err, "save avatar")
} }
@@ -1024,7 +1024,7 @@ func (s *UsersStore) AddEmail(ctx context.Context, userID int64, email string, i
_, err := s.GetByEmail(ctx, email) _, err := s.GetByEmail(ctx, email)
if err == nil { if err == nil {
return ErrEmailAlreadyUsed{ return ErrEmailAlreadyUsed{
args: errx.Args{ args: errutil.Args{
"email": email, "email": email,
}, },
} }
@@ -1041,10 +1041,10 @@ func (s *UsersStore) AddEmail(ctx context.Context, userID int64, email string, i
).Error ).Error
} }
var _ errx.NotFound = (*ErrEmailNotExist)(nil) var _ errutil.NotFound = (*ErrEmailNotExist)(nil)
type ErrEmailNotExist struct { type ErrEmailNotExist struct {
args errx.Args args errutil.Args
} }
// IsErrEmailAddressNotExist returns true if the underlying error has the type // IsErrEmailAddressNotExist returns true if the underlying error has the type
@@ -1077,7 +1077,7 @@ func (s *UsersStore) GetEmail(ctx context.Context, userID int64, email string, n
if err != nil { if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) { if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrEmailNotExist{ return nil, ErrEmailNotExist{
args: errx.Args{ args: errutil.Args{
"email": email, "email": email,
}, },
} }
@@ -1140,7 +1140,7 @@ func (s *UsersStore) MarkEmailActivated(ctx context.Context, userID int64, email
} }
type ErrEmailNotVerified struct { type ErrEmailNotVerified struct {
args errx.Args args errutil.Args
} }
// IsErrEmailNotVerified returns true if the underlying error has the type // IsErrEmailNotVerified returns true if the underlying error has the type
@@ -1162,13 +1162,13 @@ func (s *UsersStore) MarkEmailPrimary(ctx context.Context, userID int64, email s
err := s.db.WithContext(ctx).Where("uid = ? AND email = ?", userID, email).First(&emailAddress).Error err := s.db.WithContext(ctx).Where("uid = ? AND email = ?", userID, email).First(&emailAddress).Error
if err != nil { if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) { if errors.Is(err, gorm.ErrRecordNotFound) {
return ErrEmailNotExist{args: errx.Args{"email": email}} return ErrEmailNotExist{args: errutil.Args{"email": email}}
} }
return errors.Wrap(err, "get email address") return errors.Wrap(err, "get email address")
} }
if !emailAddress.IsActivated { if !emailAddress.IsActivated {
return ErrEmailNotVerified{args: errx.Args{"email": email}} return ErrEmailNotVerified{args: errutil.Args{"email": email}}
} }
user, err := s.GetByID(ctx, userID) user, err := s.GetByID(ctx, userID)
@@ -1349,7 +1349,7 @@ func (u *User) DisplayName() string {
// HomeURLPath returns the URL path to the user or organization home page. // HomeURLPath returns the URL path to the user or organization home page.
// //
// TODO(unknwon): This is also used in templates, which should be fixed by // TODO(unknwon): This is also used in templates, which should be fixed by
// having a dedicated type `template.User` and move this to the "userx" // having a dedicated type `template.User` and move this to the "userutil"
// package. // package.
func (u *User) HomeURLPath() string { func (u *User) HomeURLPath() string {
return conf.Server.Subpath + "/" + u.Name return conf.Server.Subpath + "/" + u.Name
@@ -1358,7 +1358,7 @@ func (u *User) HomeURLPath() string {
// HTMLURL returns the full URL to the user or organization home page. // HTMLURL returns the full URL to the user or organization home page.
// //
// TODO(unknwon): This is also used in templates, which should be fixed by // TODO(unknwon): This is also used in templates, which should be fixed by
// having a dedicated type `template.User` and move this to the "userx" // having a dedicated type `template.User` and move this to the "userutil"
// package. // package.
func (u *User) HTMLURL() string { func (u *User) HTMLURL() string {
return conf.Server.ExternalURL + u.Name return conf.Server.ExternalURL + u.Name
@@ -1368,7 +1368,7 @@ func (u *User) HTMLURL() string {
// user enables Gravatar-like service, then an external URL will be returned. // user enables Gravatar-like service, then an external URL will be returned.
// //
// TODO(unknwon): This is also used in templates, which should be fixed by // TODO(unknwon): This is also used in templates, which should be fixed by
// having a dedicated type `template.User` and move this to the "userx" // having a dedicated type `template.User` and move this to the "userutil"
// package. // package.
func (u *User) AvatarURLPath() string { func (u *User) AvatarURLPath() string {
defaultURLPath := conf.UserDefaultAvatarURLPath() defaultURLPath := conf.UserDefaultAvatarURLPath()
@@ -1376,7 +1376,7 @@ func (u *User) AvatarURLPath() string {
return defaultURLPath return defaultURLPath
} }
hasCustomAvatar := osx.IsFile(userx.CustomAvatarPath(u.ID)) hasCustomAvatar := osutil.IsFile(userutil.CustomAvatarPath(u.ID))
switch { switch {
case u.UseCustomAvatar: case u.UseCustomAvatar:
if !hasCustomAvatar { if !hasCustomAvatar {
@@ -1385,7 +1385,7 @@ func (u *User) AvatarURLPath() string {
return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, conf.UsersAvatarPathPrefix, u.ID) return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, conf.UsersAvatarPathPrefix, u.ID)
case conf.Picture.DisableGravatar: case conf.Picture.DisableGravatar:
if !hasCustomAvatar { if !hasCustomAvatar {
if err := userx.GenerateRandomAvatar(u.ID, u.Name, u.Email); err != nil { if err := userutil.GenerateRandomAvatar(u.ID, u.Name, u.Email); err != nil {
log.Error("Failed to generate random avatar [user_id: %d]: %v", u.ID, err) log.Error("Failed to generate random avatar [user_id: %d]: %v", u.ID, err)
} }
} }
@@ -1398,7 +1398,7 @@ func (u *User) AvatarURLPath() string {
// user enables Gravatar-like service, then an external URL will be returned. // user enables Gravatar-like service, then an external URL will be returned.
// //
// TODO(unknwon): This is also used in templates, which should be fixed by // TODO(unknwon): This is also used in templates, which should be fixed by
// having a dedicated type `template.User` and move this to the "userx" // having a dedicated type `template.User` and move this to the "userutil"
// package. // package.
func (u *User) AvatarURL() string { func (u *User) AvatarURL() string {
link := u.AvatarURLPath() link := u.AvatarURLPath()
@@ -1448,7 +1448,7 @@ func (u *User) GetOrganizationCount() (int64, error) {
// TODO(unknwon): This is also used in templates, which should be fixed by // TODO(unknwon): This is also used in templates, which should be fixed by
// having a dedicated type `template.User`. // having a dedicated type `template.User`.
func (u *User) ShortName(length int) string { func (u *User) ShortName(length int) string {
return strx.Ellipsis(u.Name, length) return strutil.Ellipsis(u.Name, length)
} }
// NewGhostUser creates and returns a fake user for people who has deleted their // NewGhostUser creates and returns a fake user for people who has deleted their
@@ -1498,7 +1498,7 @@ var (
) )
type ErrNameNotAllowed struct { type ErrNameNotAllowed struct {
args errx.Args args errutil.Args
} }
// IsErrNameNotAllowed returns true if the underlying error has the type // IsErrNameNotAllowed returns true if the underlying error has the type
@@ -1533,7 +1533,7 @@ func isNameAllowed(names map[string]struct{}, patterns []string, name string) er
name = strings.TrimSpace(strings.ToLower(name)) name = strings.TrimSpace(strings.ToLower(name))
if utf8.RuneCountInString(name) == 0 { if utf8.RuneCountInString(name) == 0 {
return ErrNameNotAllowed{ return ErrNameNotAllowed{
args: errx.Args{ args: errutil.Args{
"reason": "empty name", "reason": "empty name",
}, },
} }
@@ -1541,7 +1541,7 @@ func isNameAllowed(names map[string]struct{}, patterns []string, name string) er
if _, ok := names[name]; ok { if _, ok := names[name]; ok {
return ErrNameNotAllowed{ return ErrNameNotAllowed{
args: errx.Args{ args: errutil.Args{
"reason": "reserved", "reason": "reserved",
"name": name, "name": name,
}, },
@@ -1552,7 +1552,7 @@ func isNameAllowed(names map[string]struct{}, patterns []string, name string) er
if pattern[0] == '*' && strings.HasSuffix(name, pattern[1:]) || if pattern[0] == '*' && strings.HasSuffix(name, pattern[1:]) ||
(pattern[len(pattern)-1] == '*' && strings.HasPrefix(name, pattern[:len(pattern)-1])) { (pattern[len(pattern)-1] == '*' && strings.HasPrefix(name, pattern[:len(pattern)-1])) {
return ErrNameNotAllowed{ return ErrNameNotAllowed{
args: errx.Args{ args: errutil.Args{
"reason": "reserved", "reason": "reserved",
"pattern": pattern, "pattern": pattern,
}, },

View File

@@ -15,11 +15,11 @@ 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/dbx" "gogs.io/gogs/internal/dbutil"
"gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/osx" "gogs.io/gogs/internal/osutil"
"gogs.io/gogs/internal/repox" "gogs.io/gogs/internal/repoutil"
"gogs.io/gogs/internal/userx" "gogs.io/gogs/internal/userutil"
"gogs.io/gogs/public" "gogs.io/gogs/public"
) )
@@ -240,7 +240,7 @@ func usersChangeUsername(t *testing.T, ctx context.Context, s *UsersStore) {
t.Run("name not allowed", func(t *testing.T) { t.Run("name not allowed", func(t *testing.T) {
err := s.ChangeUsername(ctx, alice.ID, "-") err := s.ChangeUsername(ctx, alice.ID, "-")
wantErr := ErrNameNotAllowed{ wantErr := ErrNameNotAllowed{
args: errx.Args{ args: errutil.Args{
"reason": "reserved", "reason": "reserved",
"name": "-", "name": "-",
}, },
@@ -261,7 +261,7 @@ func usersChangeUsername(t *testing.T, ctx context.Context, s *UsersStore) {
err = s.ChangeUsername(ctx, alice.ID, bob.Name) err = s.ChangeUsername(ctx, alice.ID, bob.Name)
wantErr := ErrUserAlreadyExist{ wantErr := ErrUserAlreadyExist{
args: errx.Args{ args: errutil.Args{
"name": bob.Name, "name": bob.Name,
}, },
} }
@@ -306,11 +306,11 @@ func usersChangeUsername(t *testing.T, ctx context.Context, s *UsersStore) {
err = s.db.Model(&User{}).Where("id = ?", alice.ID).Update("updated_unix", 0).Error err = s.db.Model(&User{}).Where("id = ?", alice.ID).Update("updated_unix", 0).Error
require.NoError(t, err) require.NoError(t, err)
err = os.MkdirAll(repox.UserPath(alice.Name), os.ModePerm) err = os.MkdirAll(repoutil.UserPath(alice.Name), os.ModePerm)
require.NoError(t, err) require.NoError(t, err)
err = os.MkdirAll(repox.RepositoryLocalPath(repo.ID), os.ModePerm) err = os.MkdirAll(repoutil.RepositoryLocalPath(repo.ID), os.ModePerm)
require.NoError(t, err) require.NoError(t, err)
err = os.MkdirAll(repox.RepositoryLocalWikiPath(repo.ID), os.ModePerm) err = os.MkdirAll(repoutil.RepositoryLocalWikiPath(repo.ID), os.ModePerm)
require.NoError(t, err) require.NoError(t, err)
// Make sure mock data is set up correctly // Make sure mock data is set up correctly
@@ -325,9 +325,9 @@ func usersChangeUsername(t *testing.T, ctx context.Context, s *UsersStore) {
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, int64(0), updatedUnix) assert.Equal(t, int64(0), updatedUnix)
assert.True(t, osx.Exist(repox.UserPath(alice.Name))) assert.True(t, osutil.Exist(repoutil.UserPath(alice.Name)))
assert.True(t, osx.Exist(repox.RepositoryLocalPath(repo.ID))) assert.True(t, osutil.Exist(repoutil.RepositoryLocalPath(repo.ID)))
assert.True(t, osx.Exist(repox.RepositoryLocalWikiPath(repo.ID))) assert.True(t, osutil.Exist(repoutil.RepositoryLocalWikiPath(repo.ID)))
const newUsername = "alice-new" const newUsername = "alice-new"
err = s.ChangeUsername(ctx, alice.ID, newUsername) err = s.ChangeUsername(ctx, alice.ID, newUsername)
@@ -338,10 +338,10 @@ func usersChangeUsername(t *testing.T, ctx context.Context, s *UsersStore) {
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, headUserName, newUsername) assert.Equal(t, headUserName, newUsername)
assert.True(t, osx.Exist(repox.UserPath(newUsername))) assert.True(t, osutil.Exist(repoutil.UserPath(newUsername)))
assert.False(t, osx.Exist(repox.UserPath(alice.Name))) assert.False(t, osutil.Exist(repoutil.UserPath(alice.Name)))
assert.False(t, osx.Exist(repox.RepositoryLocalPath(repo.ID))) assert.False(t, osutil.Exist(repoutil.RepositoryLocalPath(repo.ID)))
assert.False(t, osx.Exist(repox.RepositoryLocalWikiPath(repo.ID))) assert.False(t, osutil.Exist(repoutil.RepositoryLocalWikiPath(repo.ID)))
alice, err = s.GetByID(ctx, alice.ID) alice, err = s.GetByID(ctx, alice.ID)
require.NoError(t, err) require.NoError(t, err)
@@ -371,7 +371,7 @@ func usersCount(t *testing.T, ctx context.Context, s *UsersStore) {
org1, err := s.Create(ctx, "org1", "org1@example.com", CreateUserOptions{}) org1, err := s.Create(ctx, "org1", "org1@example.com", CreateUserOptions{})
require.NoError(t, err) require.NoError(t, err)
err = s.db.Exec( err = s.db.Exec(
dbx.Quote("UPDATE %s SET type = ? WHERE id = ?", "user"), dbutil.Quote("UPDATE %s SET type = ? WHERE id = ?", "user"),
UserTypeOrganization, org1.ID, UserTypeOrganization, org1.ID,
).Error ).Error
require.NoError(t, err) require.NoError(t, err)
@@ -393,7 +393,7 @@ func usersCreate(t *testing.T, ctx context.Context, s *UsersStore) {
t.Run("name not allowed", func(t *testing.T) { t.Run("name not allowed", func(t *testing.T) {
_, err := s.Create(ctx, "-", "", CreateUserOptions{}) _, err := s.Create(ctx, "-", "", CreateUserOptions{})
wantErr := ErrNameNotAllowed{ wantErr := ErrNameNotAllowed{
args: errx.Args{ args: errutil.Args{
"reason": "reserved", "reason": "reserved",
"name": "-", "name": "-",
}, },
@@ -404,7 +404,7 @@ func usersCreate(t *testing.T, ctx context.Context, s *UsersStore) {
t.Run("name already exists", func(t *testing.T) { t.Run("name already exists", func(t *testing.T) {
_, err := s.Create(ctx, alice.Name, "", CreateUserOptions{}) _, err := s.Create(ctx, alice.Name, "", CreateUserOptions{})
wantErr := ErrUserAlreadyExist{ wantErr := ErrUserAlreadyExist{
args: errx.Args{ args: errutil.Args{
"name": alice.Name, "name": alice.Name,
}, },
} }
@@ -414,7 +414,7 @@ func usersCreate(t *testing.T, ctx context.Context, s *UsersStore) {
t.Run("email already exists", func(t *testing.T) { t.Run("email already exists", func(t *testing.T) {
_, err := s.Create(ctx, "bob", alice.Email, CreateUserOptions{}) _, err := s.Create(ctx, "bob", alice.Email, CreateUserOptions{})
wantErr := ErrEmailAlreadyUsed{ wantErr := ErrEmailAlreadyUsed{
args: errx.Args{ args: errutil.Args{
"email": alice.Email, "email": alice.Email,
}, },
} }
@@ -434,7 +434,7 @@ func usersDeleteCustomAvatar(t *testing.T, ctx context.Context, s *UsersStore) {
avatar, err := public.Files.ReadFile("img/avatar_default.png") avatar, err := public.Files.ReadFile("img/avatar_default.png")
require.NoError(t, err) require.NoError(t, err)
avatarPath := userx.CustomAvatarPath(alice.ID) avatarPath := userutil.CustomAvatarPath(alice.ID)
_ = os.Remove(avatarPath) _ = os.Remove(avatarPath)
defer func() { _ = os.Remove(avatarPath) }() defer func() { _ = os.Remove(avatarPath) }()
@@ -442,7 +442,7 @@ func usersDeleteCustomAvatar(t *testing.T, ctx context.Context, s *UsersStore) {
require.NoError(t, err) require.NoError(t, err)
// Make sure avatar is saved and the user flag is updated. // Make sure avatar is saved and the user flag is updated.
got := osx.IsFile(avatarPath) got := osutil.IsFile(avatarPath)
assert.True(t, got) assert.True(t, got)
alice, err = s.GetByID(ctx, alice.ID) alice, err = s.GetByID(ctx, alice.ID)
@@ -453,7 +453,7 @@ func usersDeleteCustomAvatar(t *testing.T, ctx context.Context, s *UsersStore) {
err = s.DeleteCustomAvatar(ctx, alice.ID) err = s.DeleteCustomAvatar(ctx, alice.ID)
require.NoError(t, err) require.NoError(t, err)
got = osx.IsFile(avatarPath) got = osutil.IsFile(avatarPath)
assert.False(t, got) assert.False(t, got)
alice, err = s.GetByID(ctx, alice.ID) alice, err = s.GetByID(ctx, alice.ID)
@@ -472,7 +472,7 @@ func usersDeleteByID(t *testing.T, ctx context.Context, s *UsersStore) {
require.NoError(t, err) require.NoError(t, err)
err = s.DeleteByID(ctx, alice.ID, false) err = s.DeleteByID(ctx, alice.ID, false)
wantErr := ErrUserOwnRepos{errx.Args{"userID": alice.ID}} wantErr := ErrUserOwnRepos{errutil.Args{"userID": alice.ID}}
assert.Equal(t, wantErr, err) assert.Equal(t, wantErr, err)
}) })
@@ -484,7 +484,7 @@ func usersDeleteByID(t *testing.T, ctx context.Context, s *UsersStore) {
org1, err := s.Create(ctx, "org1", "org1@example.com", CreateUserOptions{}) org1, err := s.Create(ctx, "org1", "org1@example.com", CreateUserOptions{})
require.NoError(t, err) require.NoError(t, err)
err = s.db.Exec( err = s.db.Exec(
dbx.Quote("UPDATE %s SET type = ? WHERE id IN (?)", "user"), dbutil.Quote("UPDATE %s SET type = ? WHERE id IN (?)", "user"),
UserTypeOrganization, org1.ID, UserTypeOrganization, org1.ID,
).Error ).Error
require.NoError(t, err) require.NoError(t, err)
@@ -494,7 +494,7 @@ func usersDeleteByID(t *testing.T, ctx context.Context, s *UsersStore) {
require.NoError(t, err) require.NoError(t, err)
err = s.DeleteByID(ctx, bob.ID, false) err = s.DeleteByID(ctx, bob.ID, false)
wantErr := ErrUserHasOrgs{errx.Args{"userID": bob.ID}} wantErr := ErrUserHasOrgs{errutil.Args{"userID": bob.ID}}
assert.Equal(t, wantErr, err) assert.Equal(t, wantErr, err)
}) })
@@ -561,7 +561,7 @@ func usersDeleteByID(t *testing.T, ctx context.Context, s *UsersStore) {
// Mock user directory // Mock user directory
tempRepositoryRoot := filepath.Join(os.TempDir(), "usersDeleteByID-tempRepositoryRoot") tempRepositoryRoot := filepath.Join(os.TempDir(), "usersDeleteByID-tempRepositoryRoot")
conf.SetMockRepository(t, conf.RepositoryOpts{Root: tempRepositoryRoot}) conf.SetMockRepository(t, conf.RepositoryOpts{Root: tempRepositoryRoot})
tempUserPath := repox.UserPath(testUser.Name) tempUserPath := repoutil.UserPath(testUser.Name)
err = os.MkdirAll(tempUserPath, os.ModePerm) err = os.MkdirAll(tempUserPath, os.ModePerm)
require.NoError(t, err) require.NoError(t, err)
@@ -570,7 +570,7 @@ func usersDeleteByID(t *testing.T, ctx context.Context, s *UsersStore) {
conf.SetMockPicture(t, conf.PictureOpts{AvatarUploadPath: tempPictureAvatarUploadPath}) conf.SetMockPicture(t, conf.PictureOpts{AvatarUploadPath: tempPictureAvatarUploadPath})
err = os.MkdirAll(tempPictureAvatarUploadPath, os.ModePerm) err = os.MkdirAll(tempPictureAvatarUploadPath, os.ModePerm)
require.NoError(t, err) require.NoError(t, err)
tempCustomAvatarPath := userx.CustomAvatarPath(testUser.ID) tempCustomAvatarPath := userutil.CustomAvatarPath(testUser.ID)
err = os.WriteFile(tempCustomAvatarPath, []byte("test"), 0o600) err = os.WriteFile(tempCustomAvatarPath, []byte("test"), 0o600)
require.NoError(t, err) require.NoError(t, err)
@@ -616,8 +616,8 @@ func usersDeleteByID(t *testing.T, ctx context.Context, s *UsersStore) {
assert.NotZero(t, count, "table for %T", table) assert.NotZero(t, count, "table for %T", table)
} }
assert.True(t, osx.Exist(tempUserPath)) assert.True(t, osutil.Exist(tempUserPath))
assert.True(t, osx.Exist(tempCustomAvatarPath)) assert.True(t, osutil.Exist(tempCustomAvatarPath))
// Pull the trigger // Pull the trigger
err = s.DeleteByID(ctx, testUser.ID, false) err = s.DeleteByID(ctx, testUser.ID, false)
@@ -663,11 +663,11 @@ func usersDeleteByID(t *testing.T, ctx context.Context, s *UsersStore) {
assert.Equal(t, int64(0), count, "table for %T", table) assert.Equal(t, int64(0), count, "table for %T", table)
} }
assert.False(t, osx.Exist(tempUserPath)) assert.False(t, osutil.Exist(tempUserPath))
assert.False(t, osx.Exist(tempCustomAvatarPath)) assert.False(t, osutil.Exist(tempCustomAvatarPath))
_, err = s.GetByID(ctx, testUser.ID) _, err = s.GetByID(ctx, testUser.ID)
wantErr := ErrUserNotExist{errx.Args{"userID": testUser.ID}} wantErr := ErrUserNotExist{errutil.Args{"userID": testUser.ID}}
assert.Equal(t, wantErr, err) assert.Equal(t, wantErr, err)
} }
@@ -686,7 +686,7 @@ func usersDeleteInactivated(t *testing.T, ctx context.Context, s *UsersStore) {
org1, err := s.Create(ctx, "org1", "org1@example.com", CreateUserOptions{}) org1, err := s.Create(ctx, "org1", "org1@example.com", CreateUserOptions{})
require.NoError(t, err) require.NoError(t, err)
err = s.db.Exec( err = s.db.Exec(
dbx.Quote("UPDATE %s SET type = ? WHERE id IN (?)", "user"), dbutil.Quote("UPDATE %s SET type = ? WHERE id IN (?)", "user"),
UserTypeOrganization, org1.ID, UserTypeOrganization, org1.ID,
).Error ).Error
require.NoError(t, err) require.NoError(t, err)
@@ -709,7 +709,7 @@ func usersDeleteInactivated(t *testing.T, ctx context.Context, s *UsersStore) {
require.NoError(t, err) require.NoError(t, err)
_, err = s.GetByID(ctx, david.ID) _, err = s.GetByID(ctx, david.ID)
wantErr := ErrUserNotExist{errx.Args{"userID": david.ID}} wantErr := ErrUserNotExist{errutil.Args{"userID": david.ID}}
assert.Equal(t, wantErr, err) assert.Equal(t, wantErr, err)
users, err := s.List(ctx, 1, 10) users, err := s.List(ctx, 1, 10)
@@ -720,7 +720,7 @@ func usersDeleteInactivated(t *testing.T, ctx context.Context, s *UsersStore) {
func usersGetByEmail(t *testing.T, ctx context.Context, s *UsersStore) { func usersGetByEmail(t *testing.T, ctx context.Context, s *UsersStore) {
t.Run("empty email", func(t *testing.T) { t.Run("empty email", func(t *testing.T) {
_, err := s.GetByEmail(ctx, "") _, err := s.GetByEmail(ctx, "")
wantErr := ErrUserNotExist{args: errx.Args{"email": ""}} wantErr := ErrUserNotExist{args: errutil.Args{"email": ""}}
assert.Equal(t, wantErr, err) assert.Equal(t, wantErr, err)
}) })
@@ -733,7 +733,7 @@ func usersGetByEmail(t *testing.T, ctx context.Context, s *UsersStore) {
require.NoError(t, err) require.NoError(t, err)
_, err = s.GetByEmail(ctx, org.Email) _, err = s.GetByEmail(ctx, org.Email)
wantErr := ErrUserNotExist{args: errx.Args{"email": org.Email}} wantErr := ErrUserNotExist{args: errutil.Args{"email": org.Email}}
assert.Equal(t, wantErr, err) assert.Equal(t, wantErr, err)
}) })
@@ -742,7 +742,7 @@ func usersGetByEmail(t *testing.T, ctx context.Context, s *UsersStore) {
require.NoError(t, err) require.NoError(t, err)
_, err = s.GetByEmail(ctx, alice.Email) _, err = s.GetByEmail(ctx, alice.Email)
wantErr := ErrUserNotExist{args: errx.Args{"email": alice.Email}} wantErr := ErrUserNotExist{args: errutil.Args{"email": alice.Email}}
assert.Equal(t, wantErr, err) assert.Equal(t, wantErr, err)
// Mark user as activated // Mark user as activated
@@ -765,7 +765,7 @@ func usersGetByEmail(t *testing.T, ctx context.Context, s *UsersStore) {
require.NoError(t, err) require.NoError(t, err)
_, err = s.GetByEmail(ctx, email2) _, err = s.GetByEmail(ctx, email2)
wantErr := ErrUserNotExist{args: errx.Args{"email": email2}} wantErr := ErrUserNotExist{args: errutil.Args{"email": email2}}
assert.Equal(t, wantErr, err) assert.Equal(t, wantErr, err)
// TODO: Use UserEmails.Verify to replace SQL hack when the method is available. // TODO: Use UserEmails.Verify to replace SQL hack when the method is available.
@@ -787,7 +787,7 @@ func usersGetByID(t *testing.T, ctx context.Context, s *UsersStore) {
assert.Equal(t, alice.Name, user.Name) assert.Equal(t, alice.Name, user.Name)
_, err = s.GetByID(ctx, 404) _, err = s.GetByID(ctx, 404)
wantErr := ErrUserNotExist{args: errx.Args{"userID": int64(404)}} wantErr := ErrUserNotExist{args: errutil.Args{"userID": int64(404)}}
assert.Equal(t, wantErr, err) assert.Equal(t, wantErr, err)
} }
@@ -800,7 +800,7 @@ func usersGetByUsername(t *testing.T, ctx context.Context, s *UsersStore) {
assert.Equal(t, alice.Name, user.Name) assert.Equal(t, alice.Name, user.Name)
_, err = s.GetByUsername(ctx, "bad_username") _, err = s.GetByUsername(ctx, "bad_username")
wantErr := ErrUserNotExist{args: errx.Args{"name": "bad_username"}} wantErr := ErrUserNotExist{args: errutil.Args{"name": "bad_username"}}
assert.Equal(t, wantErr, err) assert.Equal(t, wantErr, err)
} }
@@ -825,7 +825,7 @@ func usersGetByKeyID(t *testing.T, ctx context.Context, s *UsersStore) {
assert.Equal(t, alice.Name, user.Name) assert.Equal(t, alice.Name, user.Name)
_, err = s.GetByKeyID(ctx, publicKey.ID+1) _, err = s.GetByKeyID(ctx, publicKey.ID+1)
wantErr := ErrUserNotExist{args: errx.Args{"keyID": publicKey.ID + 1}} wantErr := ErrUserNotExist{args: errutil.Args{"keyID": publicKey.ID + 1}}
assert.Equal(t, wantErr, err) assert.Equal(t, wantErr, err)
} }
@@ -904,7 +904,7 @@ func usersList(t *testing.T, ctx context.Context, s *UsersStore) {
org1, err := s.Create(ctx, "org1", "org1@example.com", CreateUserOptions{}) org1, err := s.Create(ctx, "org1", "org1@example.com", CreateUserOptions{})
require.NoError(t, err) require.NoError(t, err)
err = s.db.Exec( err = s.db.Exec(
dbx.Quote("UPDATE %s SET type = ? WHERE id = ?", "user"), dbutil.Quote("UPDATE %s SET type = ? WHERE id = ?", "user"),
UserTypeOrganization, org1.ID, UserTypeOrganization, org1.ID,
).Error ).Error
require.NoError(t, err) require.NoError(t, err)
@@ -1046,7 +1046,7 @@ func usersUpdate(t *testing.T, ctx context.Context, s *UsersStore) {
require.NoError(t, err) require.NoError(t, err)
t.Run("update password", func(t *testing.T) { t.Run("update password", func(t *testing.T) {
got := userx.ValidatePassword(alice.Password, alice.Salt, oldPassword) got := userutil.ValidatePassword(alice.Password, alice.Salt, oldPassword)
require.True(t, got) require.True(t, got)
newPassword := "NewPassword" newPassword := "NewPassword"
@@ -1055,10 +1055,10 @@ func usersUpdate(t *testing.T, ctx context.Context, s *UsersStore) {
alice, err = s.GetByID(ctx, alice.ID) alice, err = s.GetByID(ctx, alice.ID)
require.NoError(t, err) require.NoError(t, err)
got = userx.ValidatePassword(alice.Password, alice.Salt, oldPassword) got = userutil.ValidatePassword(alice.Password, alice.Salt, oldPassword)
assert.False(t, got, "Old password should stop working") assert.False(t, got, "Old password should stop working")
got = userx.ValidatePassword(alice.Password, alice.Salt, newPassword) got = userutil.ValidatePassword(alice.Password, alice.Salt, newPassword)
assert.True(t, got, "New password should work") assert.True(t, got, "New password should work")
}) })
@@ -1074,7 +1074,7 @@ func usersUpdate(t *testing.T, ctx context.Context, s *UsersStore) {
require.NoError(t, err) require.NoError(t, err)
got := s.Update(ctx, alice.ID, UpdateUserOptions{Email: &bob.Email}) got := s.Update(ctx, alice.ID, UpdateUserOptions{Email: &bob.Email})
want := ErrEmailAlreadyUsed{args: errx.Args{"email": bob.Email}} want := ErrEmailAlreadyUsed{args: errutil.Args{"email": bob.Email}}
assert.Equal(t, want, got) assert.Equal(t, want, got)
}) })
@@ -1146,7 +1146,7 @@ func usersUseCustomAvatar(t *testing.T, ctx context.Context, s *UsersStore) {
avatar, err := public.Files.ReadFile("img/avatar_default.png") avatar, err := public.Files.ReadFile("img/avatar_default.png")
require.NoError(t, err) require.NoError(t, err)
avatarPath := userx.CustomAvatarPath(alice.ID) avatarPath := userutil.CustomAvatarPath(alice.ID)
_ = os.Remove(avatarPath) _ = os.Remove(avatarPath)
defer func() { _ = os.Remove(avatarPath) }() defer func() { _ = os.Remove(avatarPath) }()
@@ -1154,7 +1154,7 @@ func usersUseCustomAvatar(t *testing.T, ctx context.Context, s *UsersStore) {
require.NoError(t, err) require.NoError(t, err)
// Make sure avatar is saved and the user flag is updated. // Make sure avatar is saved and the user flag is updated.
got := osx.IsFile(avatarPath) got := osutil.IsFile(avatarPath)
assert.True(t, got) assert.True(t, got)
alice, err = s.GetByID(ctx, alice.ID) alice, err = s.GetByID(ctx, alice.ID)
@@ -1189,7 +1189,7 @@ func usersAddEmail(t *testing.T, ctx context.Context, s *UsersStore) {
bob, err := s.Create(ctx, "bob", "verified@example.com", CreateUserOptions{Activated: true}) bob, err := s.Create(ctx, "bob", "verified@example.com", CreateUserOptions{Activated: true})
require.NoError(t, err) require.NoError(t, err)
got := s.AddEmail(ctx, bob.ID+1, "verified@example.com", true) got := s.AddEmail(ctx, bob.ID+1, "verified@example.com", true)
want := ErrEmailAlreadyUsed{args: errx.Args{"email": "verified@example.com"}} want := ErrEmailAlreadyUsed{args: errutil.Args{"email": "verified@example.com"}}
require.Equal(t, want, got) require.Equal(t, want, got)
}) })
} }
@@ -1199,7 +1199,7 @@ func usersGetEmail(t *testing.T, ctx context.Context, s *UsersStore) {
const testEmail = "alice@example.com" const testEmail = "alice@example.com"
_, err := s.GetEmail(ctx, testUserID, testEmail, false) _, err := s.GetEmail(ctx, testUserID, testEmail, false)
wantErr := ErrEmailNotExist{ wantErr := ErrEmailNotExist{
args: errx.Args{ args: errutil.Args{
"email": testEmail, "email": testEmail,
}, },
} }
@@ -1288,7 +1288,7 @@ func usersMarkEmailPrimary(t *testing.T, ctx context.Context, s *UsersStore) {
// Should fail because email not verified // Should fail because email not verified
gotError := s.MarkEmailPrimary(ctx, alice.ID, "alice2@example.com") gotError := s.MarkEmailPrimary(ctx, alice.ID, "alice2@example.com")
wantError := ErrEmailNotVerified{args: errx.Args{"email": "alice2@example.com"}} wantError := ErrEmailNotVerified{args: errutil.Args{"email": "alice2@example.com"}}
assert.Equal(t, wantError, gotError) assert.Equal(t, wantError, gotError)
// Mark email as verified and should succeed // Mark email as verified and should succeed
@@ -1318,7 +1318,7 @@ func usersDeleteEmail(t *testing.T, ctx context.Context, s *UsersStore) {
err = s.DeleteEmail(ctx, alice.ID, "alice2@example.com") err = s.DeleteEmail(ctx, alice.ID, "alice2@example.com")
require.NoError(t, err) require.NoError(t, err)
_, got := s.GetEmail(ctx, alice.ID, "alice2@example.com", false) _, got := s.GetEmail(ctx, alice.ID, "alice2@example.com", false)
want := ErrEmailNotExist{args: errx.Args{"email": "alice2@example.com"}} want := ErrEmailNotExist{args: errutil.Args{"email": "alice2@example.com"}}
require.Equal(t, want, got) require.Equal(t, want, got)
} }

View File

@@ -18,12 +18,12 @@ import (
"xorm.io/xorm" "xorm.io/xorm"
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/errutil"
"gogs.io/gogs/internal/httplib" "gogs.io/gogs/internal/httplib"
"gogs.io/gogs/internal/netx" "gogs.io/gogs/internal/netutil"
apiv1types "gogs.io/gogs/internal/route/api/v1/types" apiv1types "gogs.io/gogs/internal/route/api/v1/types"
"gogs.io/gogs/internal/sync" "gogs.io/gogs/internal/sync"
"gogs.io/gogs/internal/testx" "gogs.io/gogs/internal/testutil"
) )
var HookQueue = sync.NewUniqueQueue(1000) var HookQueue = sync.NewUniqueQueue(1000)
@@ -234,7 +234,7 @@ func CreateWebhook(w *Webhook) error {
return err return err
} }
var _ errx.NotFound = (*ErrWebhookNotExist)(nil) var _ errutil.NotFound = (*ErrWebhookNotExist)(nil)
type ErrWebhookNotExist struct { type ErrWebhookNotExist struct {
args map[string]any args map[string]any
@@ -517,7 +517,7 @@ func createHookTask(e Engine, t *HookTask) error {
return err return err
} }
var _ errx.NotFound = (*ErrHookTaskNotExist)(nil) var _ errutil.NotFound = (*ErrHookTaskNotExist)(nil)
type ErrHookTaskNotExist struct { type ErrHookTaskNotExist struct {
args map[string]any args map[string]any
@@ -676,7 +676,7 @@ func prepareWebhooks(e Engine, repo *Repository, event HookEventType, p apiv1typ
func PrepareWebhooks(repo *Repository, event HookEventType, p apiv1types.WebhookPayloader) error { func PrepareWebhooks(repo *Repository, event HookEventType, p apiv1types.WebhookPayloader) error {
// NOTE: To prevent too many cascading changes in a single refactoring PR, we // NOTE: To prevent too many cascading changes in a single refactoring PR, we
// choose to ignore this function in tests. // choose to ignore this function in tests.
if x == nil && testx.InTest { if x == nil && testutil.InTest {
return nil return nil
} }
return prepareWebhooks(x, repo, event, p) return prepareWebhooks(x, repo, event, p)
@@ -697,7 +697,7 @@ func (t *HookTask) deliver() {
t.ResponseContent = fmt.Sprintf(`{"body": "Cannot parse payload URL: %v"}`, err) t.ResponseContent = fmt.Sprintf(`{"body": "Cannot parse payload URL: %v"}`, err)
return return
} }
if netx.IsBlockedLocalHostname(payloadURL.Hostname(), conf.Security.LocalNetworkAllowlist) { if netutil.IsBlockedLocalHostname(payloadURL.Hostname(), conf.Security.LocalNetworkAllowlist) {
t.ResponseContent = `{"body": "Payload URL resolved to a local network address that is implicitly blocked."}` t.ResponseContent = `{"body": "Payload URL resolved to a local network address that is implicitly blocked."}`
return return
} }

View File

@@ -133,7 +133,7 @@ func getDingtalkPushPayload(p *apiv1types.WebhookPushPayload) *DingtalkPayload {
for i, commit := range p.Commits { for i, commit := range p.Commits {
msg := strings.Split(commit.Message, "\n")[0] msg := strings.Split(commit.Message, "\n")[0]
commitLink := MarkdownLinkFormatter(commit.URL, commit.ID[:7]) commitLink := MarkdownLinkFormatter(commit.URL, commit.ID[:7])
fmt.Fprintf(&detail, "> %d. %s %s - %s\n", i, commitLink, commit.Author.Name, msg) detail.WriteString(fmt.Sprintf("> %d. %s %s - %s\n", i, commitLink, commit.Author.Name, msg))
} }
actionCard := NewDingtalkActionCard("View Changes", p.CompareURL) actionCard := NewDingtalkActionCard("View Changes", p.CompareURL)

View File

@@ -140,11 +140,11 @@ func getDiscordPushPayload(p *apiv1types.WebhookPushPayload, slack *SlackMeta) *
repoLink := DiscordLinkFormatter(p.Repo.HTMLURL, p.Repo.Name) repoLink := DiscordLinkFormatter(p.Repo.HTMLURL, p.Repo.Name)
branchLink := DiscordLinkFormatter(p.Repo.HTMLURL+"/src/"+branchName, branchName) branchLink := DiscordLinkFormatter(p.Repo.HTMLURL+"/src/"+branchName, branchName)
var content strings.Builder var content strings.Builder
fmt.Fprintf(&content, "Pushed %s to %s/%s\n", commitString, repoLink, branchLink) content.WriteString(fmt.Sprintf("Pushed %s to %s/%s\n", commitString, repoLink, branchLink))
// for each commit, generate attachment text // for each commit, generate attachment text
for i, commit := range p.Commits { for i, commit := range p.Commits {
fmt.Fprintf(&content, "%s %s - %s", DiscordSHALinkFormatter(commit.URL, commit.ID[:7]), DiscordTextFormatter(commit.Message), commit.Author.Name) content.WriteString(fmt.Sprintf("%s %s - %s", DiscordSHALinkFormatter(commit.URL, commit.ID[:7]), DiscordTextFormatter(commit.Message), commit.Author.Name))
// add linebreak to each commit but the last // add linebreak to each commit but the last
if i < len(p.Commits)-1 { if i < len(p.Commits)-1 {
content.WriteString("\n") content.WriteString("\n")

View File

@@ -123,7 +123,7 @@ func getSlackPushPayload(p *apiv1types.WebhookPushPayload, slack *SlackMeta) *Sl
var attachmentText strings.Builder var attachmentText strings.Builder
// for each commit, generate attachment text // for each commit, generate attachment text
for i, commit := range p.Commits { for i, commit := range p.Commits {
fmt.Fprintf(&attachmentText, "%s: %s - %s", SlackLinkFormatter(commit.URL, commit.ID[:7]), SlackShortTextFormatter(commit.Message), SlackTextFormatter(commit.Author.Name)) attachmentText.WriteString(fmt.Sprintf("%s: %s - %s", SlackLinkFormatter(commit.URL, commit.ID[:7]), SlackShortTextFormatter(commit.Message), SlackTextFormatter(commit.Author.Name)))
// add linebreak to each commit but the last // add linebreak to each commit but the last
if i < len(p.Commits)-1 { if i < len(p.Commits)-1 {
attachmentText.WriteString("\n") attachmentText.WriteString("\n")

View File

@@ -14,9 +14,9 @@ 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/osx" "gogs.io/gogs/internal/osutil"
"gogs.io/gogs/internal/pathx" "gogs.io/gogs/internal/pathutil"
"gogs.io/gogs/internal/repox" "gogs.io/gogs/internal/repoutil"
"gogs.io/gogs/internal/sync" "gogs.io/gogs/internal/sync"
) )
@@ -40,20 +40,20 @@ func ToWikiPageURL(name string) string {
// single-level hierarchy by replacing all "/" with spaces. // single-level hierarchy by replacing all "/" with spaces.
func ToWikiPageName(urlString string) string { func ToWikiPageName(urlString string) string {
name, _ := url.QueryUnescape(urlString) name, _ := url.QueryUnescape(urlString)
name = pathx.Clean(name) name = pathutil.Clean(name)
return strings.ReplaceAll(name, "/", " ") return strings.ReplaceAll(name, "/", " ")
} }
// WikiCloneLink returns clone URLs of repository wiki. // WikiCloneLink returns clone URLs of repository wiki.
// //
// Deprecated: Use repox.NewCloneLink instead. // Deprecated: Use repoutil.NewCloneLink instead.
func (r *Repository) WikiCloneLink() (cl *repox.CloneLink) { func (r *Repository) WikiCloneLink() (cl *repoutil.CloneLink) {
return r.cloneLink(true) return r.cloneLink(true)
} }
// WikiPath returns wiki data path by given user and repository name. // WikiPath returns wiki data path by given user and repository name.
func WikiPath(userName, repoName string) string { func WikiPath(userName, repoName string) string {
return filepath.Join(repox.UserPath(userName), strings.ToLower(repoName)+".wiki.git") return filepath.Join(repoutil.UserPath(userName), strings.ToLower(repoName)+".wiki.git")
} }
func (r *Repository) WikiPath() string { func (r *Repository) WikiPath() string {
@@ -62,7 +62,7 @@ func (r *Repository) WikiPath() string {
// HasWiki returns true if repository has wiki. // HasWiki returns true if repository has wiki.
func (r *Repository) HasWiki() bool { func (r *Repository) HasWiki() bool {
return osx.IsDir(r.WikiPath()) return osutil.IsDir(r.WikiPath())
} }
// InitWiki initializes a wiki for repository, // InitWiki initializes a wiki for repository,
@@ -115,7 +115,7 @@ func (r *Repository) updateWikiPage(doer *User, oldTitle, title, content, messag
// If not a new file, show perform update not create. // If not a new file, show perform update not create.
if isNew { if isNew {
if osx.Exist(filename) { if osutil.Exist(filename) {
return ErrWikiAlreadyExist{filename} return ErrWikiAlreadyExist{filename}
} }
} else { } else {

View File

@@ -13,7 +13,7 @@ import (
"gorm.io/gorm/schema" "gorm.io/gorm/schema"
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/dbx" "gogs.io/gogs/internal/dbutil"
) )
// NewDB creates a new test database and initializes the given list of tables // NewDB creates a new test database and initializes the given list of tables
@@ -35,7 +35,7 @@ func NewDB(t *testing.T, suite string, tables ...any) *gorm.DB {
Password: os.Getenv("MYSQL_PASSWORD"), Password: os.Getenv("MYSQL_PASSWORD"),
} }
dsn, err := dbx.NewDSN(dbOpts) dsn, err := dbutil.NewDSN(dbOpts)
require.NoError(t, err) require.NoError(t, err)
sqlDB, err := sql.Open("mysql", dsn) sqlDB, err := sql.Open("mysql", dsn)
@@ -71,7 +71,7 @@ func NewDB(t *testing.T, suite string, tables ...any) *gorm.DB {
SSLMode: os.Getenv("PGSSLMODE"), SSLMode: os.Getenv("PGSSLMODE"),
} }
dsn, err := dbx.NewDSN(dbOpts) dsn, err := dbutil.NewDSN(dbOpts)
require.NoError(t, err) require.NoError(t, err)
sqlDB, err := sql.Open("pgx", dsn) sqlDB, err := sql.Open("pgx", dsn)
@@ -112,7 +112,7 @@ func NewDB(t *testing.T, suite string, tables ...any) *gorm.DB {
} }
now := time.Now().UTC().Truncate(time.Second) now := time.Now().UTC().Truncate(time.Second)
db, err := dbx.OpenDB( db, err := dbutil.OpenDB(
dbOpts, dbOpts,
&gorm.Config{ &gorm.Config{
SkipDefaultTransaction: true, SkipDefaultTransaction: true,

View File

@@ -1,4 +1,4 @@
package dbx package dbutil
import ( import (
"fmt" "fmt"

View File

@@ -1,4 +1,4 @@
package dbx package dbutil
import ( import (
"fmt" "fmt"

View File

@@ -1,4 +1,4 @@
package dbx package dbutil
import ( import (
"fmt" "fmt"

View File

@@ -1,4 +1,4 @@
package dbx package dbutil
import ( import (
"fmt" "fmt"

View File

@@ -1,4 +1,4 @@
package dbx package dbutil
import ( import (
"testing" "testing"

View File

@@ -1,4 +1,4 @@
package errx package errutil
// NotFound represents a not found error. // NotFound represents a not found error.
type NotFound interface { type NotFound interface {

View File

@@ -1,4 +1,4 @@
package errx package errutil
import ( import (
"testing" "testing"

View File

@@ -9,8 +9,8 @@ import (
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/database" "gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/netx" "gogs.io/gogs/internal/netutil"
"gogs.io/gogs/internal/osx" "gogs.io/gogs/internal/osutil"
) )
// _______________________________________ _________.______________________ _______________.___. // _______________________________________ _________.______________________ _______________.___.
@@ -68,7 +68,7 @@ func (f MigrateRepo) ParseRemoteAddr(user *database.User) (string, error) {
return "", database.ErrInvalidCloneAddr{IsURLError: true} return "", database.ErrInvalidCloneAddr{IsURLError: true}
} }
if netx.IsBlockedLocalHostname(u.Hostname(), conf.Security.LocalNetworkAllowlist) { if netutil.IsBlockedLocalHostname(u.Hostname(), conf.Security.LocalNetworkAllowlist) {
return "", database.ErrInvalidCloneAddr{IsBlockedLocalAddress: true} return "", database.ErrInvalidCloneAddr{IsBlockedLocalAddress: true}
} }
@@ -82,7 +82,7 @@ func (f MigrateRepo) ParseRemoteAddr(user *database.User) (string, error) {
remoteAddr = u.String() remoteAddr = u.String()
} else if !user.CanImportLocal() { } else if !user.CanImportLocal() {
return "", database.ErrInvalidCloneAddr{IsPermissionDenied: true} return "", database.ErrInvalidCloneAddr{IsPermissionDenied: true}
} else if !osx.IsDir(remoteAddr) { } else if !osutil.IsDir(remoteAddr) {
return "", database.ErrInvalidCloneAddr{IsInvalidPath: true} return "", database.ErrInvalidCloneAddr{IsInvalidPath: true}
} }

View File

@@ -1,4 +1,4 @@
package gitx package gitutil
import ( import (
"bytes" "bytes"

View File

@@ -1,4 +1,4 @@
package gitx package gitutil
import ( import (
"html/template" "html/template"

View File

@@ -1,13 +1,13 @@
package gitx package gitutil
import ( import (
"github.com/cockroachdb/errors" "github.com/cockroachdb/errors"
"github.com/gogs/git-module" "github.com/gogs/git-module"
"gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/errutil"
) )
var _ errx.NotFound = (*Error)(nil) var _ errutil.NotFound = (*Error)(nil)
// Error is a wrapper of a Git error, which handles not found. // Error is a wrapper of a Git error, which handles not found.
type Error struct { type Error struct {

View File

@@ -1,4 +1,4 @@
package gitx package gitutil
import ( import (
"os" "os"
@@ -7,7 +7,7 @@ import (
"github.com/gogs/git-module" "github.com/gogs/git-module"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/errutil"
) )
func TestError_NotFound(t *testing.T) { func TestError_NotFound(t *testing.T) {
@@ -21,7 +21,7 @@ func TestError_NotFound(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
t.Run("", func(t *testing.T) { t.Run("", func(t *testing.T) {
assert.Equal(t, test.expVal, errx.IsNotFound(NewError(test.err))) assert.Equal(t, test.expVal, errutil.IsNotFound(NewError(test.err)))
}) })
} }
} }

View File

@@ -1,4 +1,4 @@
package gitx package gitutil
import ( import (
"testing" "testing"

View File

@@ -1,4 +1,4 @@
package gitx package gitutil
import ( import (
"github.com/gogs/git-module" "github.com/gogs/git-module"

View File

@@ -1,4 +1,4 @@
package gitx package gitutil
import ( import (
"strconv" "strconv"

View File

@@ -1,4 +1,4 @@
package gitx package gitutil
import ( import (
"testing" "testing"

View File

@@ -1,4 +1,4 @@
package gitx package gitutil
import ( import (
"fmt" "fmt"

View File

@@ -1,4 +1,4 @@
package gitx package gitutil
import ( import (
"testing" "testing"

View File

@@ -1,4 +1,4 @@
package gitx package gitutil
import ( import (
"github.com/cockroachdb/errors" "github.com/cockroachdb/errors"

View File

@@ -1,4 +1,4 @@
package gitx package gitutil
import ( import (
"testing" "testing"

View File

@@ -1,4 +1,4 @@
package iox package ioutil
import ( import (
"io" "io"

View File

@@ -10,7 +10,7 @@ import (
"regexp" "regexp"
"sync" "sync"
"gogs.io/gogs/internal/testx" "gogs.io/gogs/internal/testutil"
) )
// Regexp is a wrapper around regexp.Regexp, where the underlying regexp will be // Regexp is a wrapper around regexp.Regexp, where the underlying regexp will be
@@ -104,7 +104,7 @@ func (r *Regexp) ReplaceAll(src, repl []byte) []byte {
// happen immediately. // happen immediately.
func New(str string) *Regexp { func New(str string) *Regexp {
lr := &Regexp{str: str} lr := &Regexp{str: str}
if testx.InTest { if testutil.InTest {
// In tests, always compile the regexps early. // In tests, always compile the regexps early.
lr.Regexp() lr.Regexp()
} }

View File

@@ -1,4 +1,4 @@
package lfsx package lfsutil
import ( import (
"github.com/cockroachdb/errors" "github.com/cockroachdb/errors"

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