From 36d56d5525972d9a87a136a490469a997efdcd66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=B4=8A=E1=B4=8F=E1=B4=87=20=E1=B4=84=CA=9C=E1=B4=87?= =?UTF-8?q?=C9=B4?= Date: Mon, 16 Feb 2026 13:25:19 -0500 Subject: [PATCH] all: rename packages ending with "util" to end with "x" (#8182) Co-authored-by: JSS Co-authored-by: Claude Opus 4.6 --- cmd/gogs/backup.go | 6 +- cmd/gogs/hook.go | 8 +- cmd/gogs/import.go | 8 +- cmd/gogs/restore.go | 20 +-- cmd/gogs/web.go | 6 +- internal/app/metrics.go | 4 +- internal/auth/auth.go | 6 +- internal/{authutil => authx}/basic.go | 2 +- internal/{authutil => authx}/basic_test.go | 2 +- internal/conf/computed_test.go | 14 +- internal/conf/conf.go | 10 +- internal/conf/conf_test.go | 4 +- internal/conf/utils.go | 4 +- internal/context/api.go | 4 +- internal/context/context.go | 4 +- internal/context/go_get.go | 4 +- internal/context/notice.go | 4 +- internal/context/repo.go | 4 +- internal/{cryptoutil => cryptox}/aes.go | 2 +- internal/{cryptoutil => cryptox}/aes_test.go | 2 +- internal/{cryptoutil => cryptox}/md5.go | 2 +- internal/{cryptoutil => cryptox}/md5_test.go | 2 +- internal/{cryptoutil => cryptox}/sha.go | 2 +- internal/{cryptoutil => cryptox}/sha_test.go | 2 +- internal/database/access_tokens.go | 22 +-- internal/database/access_tokens_test.go | 8 +- internal/database/actions.go | 26 ++-- internal/database/attachment.go | 4 +- internal/database/backup.go | 6 +- internal/database/backup_test.go | 28 ++-- internal/database/comment.go | 4 +- internal/database/database.go | 6 +- internal/database/issue.go | 6 +- internal/database/issue_label.go | 4 +- internal/database/issue_mail.go | 12 +- internal/database/lfs.go | 24 +-- internal/database/lfs_test.go | 24 +-- internal/database/login_source_files.go | 12 +- internal/database/login_source_files_test.go | 4 +- internal/database/login_sources.go | 10 +- internal/database/login_sources_test.go | 12 +- internal/database/main_test.go | 4 +- internal/database/migrations/main_test.go | 4 +- internal/database/migrations/v20.go | 4 +- internal/database/milestone.go | 4 +- internal/database/models.go | 6 +- internal/database/org.go | 16 +- internal/database/org_team.go | 4 +- internal/database/organizations.go | 6 +- internal/database/organizations_test.go | 6 +- internal/database/public_keys.go | 4 +- internal/database/pull.go | 10 +- internal/database/release.go | 4 +- internal/database/repo.go | 76 ++++----- internal/database/repo_branch.go | 4 +- internal/database/repo_editor.go | 38 ++--- internal/database/repo_test.go | 4 +- internal/database/repositories.go | 20 +-- internal/database/repositories_test.go | 10 +- internal/database/ssh_key.go | 8 +- internal/database/two_factor.go | 4 +- internal/database/two_factors.go | 16 +- internal/database/two_factors_test.go | 4 +- internal/database/users.go | 144 +++++++++--------- internal/database/users_test.go | 108 ++++++------- internal/database/webhook.go | 14 +- internal/database/wiki.go | 18 +-- internal/dbtest/dbtest.go | 8 +- internal/{dbutil => dbx}/dsn.go | 2 +- internal/{dbutil => dbx}/dsn_test.go | 2 +- internal/{dbutil => dbx}/logger.go | 2 +- internal/{dbutil => dbx}/string.go | 2 +- internal/{dbutil => dbx}/string_test.go | 2 +- internal/{errutil/errutil.go => errx/errx.go} | 2 +- .../errutil_test.go => errx/errx_test.go} | 2 +- internal/form/repo.go | 8 +- internal/{gitutil => gitx}/diff.go | 2 +- internal/{gitutil => gitx}/diff_test.go | 2 +- internal/{gitutil => gitx}/error.go | 6 +- internal/{gitutil => gitx}/error_test.go | 6 +- internal/{gitutil => gitx}/mocks.go | 2 +- internal/{gitutil => gitx}/module.go | 2 +- internal/{gitutil => gitx}/pull_request.go | 2 +- .../{gitutil => gitx}/pull_request_test.go | 2 +- internal/{gitutil => gitx}/submodule.go | 2 +- internal/{gitutil => gitx}/submodule_test.go | 2 +- internal/{gitutil => gitx}/tag.go | 2 +- internal/{gitutil => gitx}/tag_test.go | 2 +- internal/{ioutil/ioutil.go => iox/iox.go} | 2 +- internal/lazyregexp/lazyre.go | 4 +- internal/{lfsutil => lfsx}/oid.go | 2 +- internal/{lfsutil => lfsx}/oid_test.go | 2 +- internal/{lfsutil => lfsx}/storage.go | 6 +- internal/{lfsutil => lfsx}/storage_test.go | 6 +- internal/{netutil/netutil.go => netx/netx.go} | 2 +- .../netutil_test.go => netx/netx_test.go} | 2 +- internal/{osutil => osx}/error.go | 6 +- internal/{osutil => osx}/error_test.go | 6 +- internal/{osutil/osutil.go => osx/osx.go} | 2 +- .../osutil_test.go => osx/osx_test.go} | 14 +- .../{pathutil/pathutil.go => pathx/pathx.go} | 2 +- .../pathutil_test.go => pathx/pathx_test.go} | 2 +- .../{repoutil/repoutil.go => repox/repox.go} | 2 +- .../repoutil_test.go => repox/repox_test.go} | 2 +- internal/route/api/v1/repo_blob.go | 10 +- internal/route/api/v1/repo_commits.go | 6 +- internal/route/api/v1/repo_contents.go | 26 ++-- internal/route/api/v1/repo_file.go | 6 +- internal/route/api/v1/repo_tree.go | 4 +- internal/route/install.go | 10 +- internal/route/lfs/basic.go | 26 ++-- internal/route/lfs/basic_test.go | 18 +-- internal/route/lfs/batch.go | 18 +-- internal/route/lfs/main_test.go | 4 +- internal/route/lfs/mocks_test.go | 70 ++++----- internal/route/lfs/route.go | 16 +- internal/route/lfs/route_test.go | 4 +- internal/route/lfs/store.go | 14 +- internal/route/repo/branch.go | 4 +- internal/route/repo/commit.go | 18 +-- internal/route/repo/download.go | 4 +- internal/route/repo/editor.go | 22 +-- internal/route/repo/http.go | 4 +- internal/route/repo/pull.go | 18 +-- internal/route/repo/release.go | 4 +- internal/route/repo/repo.go | 10 +- internal/route/repo/setting.go | 12 +- internal/route/repo/tasks.go | 4 +- internal/route/repo/view.go | 8 +- internal/route/repo/webhook.go | 4 +- internal/route/repo/wiki.go | 4 +- internal/route/user/auth.go | 22 +-- internal/route/user/profile.go | 4 +- internal/route/user/setting.go | 8 +- .../semverutil.go => semverx/semverx.go} | 2 +- .../semverx_test.go} | 2 +- internal/ssh/ssh.go | 4 +- internal/{strutil/strutil.go => strx/strx.go} | 2 +- .../strutil_test.go => strx/strx_test.go} | 2 +- internal/template/template.go | 12 +- internal/{testutil => testx}/exec.go | 2 +- internal/{testutil => testx}/exec_test.go | 2 +- internal/{testutil => testx}/golden.go | 2 +- internal/{testutil => testx}/golden_test.go | 2 +- internal/{testutil => testx}/noop_logger.go | 2 +- internal/{testutil => testx}/testdata/golden | 0 .../{testutil/testutil.go => testx/testx.go} | 2 +- .../testutil_test.go => testx/testx_test.go} | 2 +- internal/tool/tool.go | 4 +- internal/{urlutil/urlutil.go => urlx/urlx.go} | 2 +- .../urlutil_test.go => urlx/urlx_test.go} | 2 +- .../{userutil/userutil.go => userx/userx.go} | 6 +- .../userutil_test.go => userx/userx_test.go} | 8 +- templates/embed.go | 4 +- 154 files changed, 724 insertions(+), 724 deletions(-) rename internal/{authutil => authx}/basic.go (97%) rename internal/{authutil => authx}/basic_test.go (98%) rename internal/{cryptoutil => cryptox}/aes.go (98%) rename internal/{cryptoutil => cryptox}/aes_test.go (96%) rename internal/{cryptoutil => cryptox}/md5.go (94%) rename internal/{cryptoutil => cryptox}/md5_test.go (96%) rename internal/{cryptoutil => cryptox}/sha.go (95%) rename internal/{cryptoutil => cryptox}/sha_test.go (98%) rename internal/{dbutil => dbx}/dsn.go (99%) rename internal/{dbutil => dbx}/dsn_test.go (99%) rename internal/{dbutil => dbx}/logger.go (93%) rename internal/{dbutil => dbx}/string.go (96%) rename internal/{dbutil => dbx}/string_test.go (96%) rename internal/{errutil/errutil.go => errx/errx.go} (95%) rename internal/{errutil/errutil_test.go => errx/errx_test.go} (98%) rename internal/{gitutil => gitx}/diff.go (99%) rename internal/{gitutil => gitx}/diff_test.go (98%) rename internal/{gitutil => gitx}/error.go (91%) rename internal/{gitutil => gitx}/error_test.go (85%) rename internal/{gitutil => gitx}/mocks.go (99%) rename internal/{gitutil => gitx}/module.go (99%) rename internal/{gitutil => gitx}/pull_request.go (99%) rename internal/{gitutil => gitx}/pull_request_test.go (99%) rename internal/{gitutil => gitx}/submodule.go (98%) rename internal/{gitutil => gitx}/submodule_test.go (99%) rename internal/{gitutil => gitx}/tag.go (99%) rename internal/{gitutil => gitx}/tag_test.go (99%) rename internal/{ioutil/ioutil.go => iox/iox.go} (98%) rename internal/{lfsutil => lfsx}/oid.go (96%) rename internal/{lfsutil => lfsx}/oid_test.go (97%) rename internal/{lfsutil => lfsx}/storage.go (97%) rename internal/{lfsutil => lfsx}/storage_test.go (96%) rename internal/{netutil/netutil.go => netx/netx.go} (99%) rename internal/{netutil/netutil_test.go => netx/netx_test.go} (98%) rename internal/{osutil => osx}/error.go (76%) rename internal/{osutil => osx}/error_test.go (72%) rename internal/{osutil/osutil.go => osx/osx.go} (98%) rename internal/{osutil/osutil_test.go => osx/osx_test.go} (93%) rename internal/{pathutil/pathutil.go => pathx/pathx.go} (95%) rename internal/{pathutil/pathutil_test.go => pathx/pathx_test.go} (98%) rename internal/{repoutil/repoutil.go => repox/repox.go} (99%) rename internal/{repoutil/repoutil_test.go => repox/repox_test.go} (99%) rename internal/{semverutil/semverutil.go => semverx/semverx.go} (97%) rename internal/{semverutil/semverutil_test.go => semverx/semverx_test.go} (97%) rename internal/{strutil/strutil.go => strx/strx.go} (99%) rename internal/{strutil/strutil_test.go => strx/strx_test.go} (99%) rename internal/{testutil => testx}/exec.go (98%) rename internal/{testutil => testx}/exec_test.go (98%) rename internal/{testutil => testx}/golden.go (98%) rename internal/{testutil => testx}/golden_test.go (98%) rename internal/{testutil => testx}/noop_logger.go (96%) rename internal/{testutil => testx}/testdata/golden (100%) rename internal/{testutil/testutil.go => testx/testx.go} (92%) rename internal/{testutil/testutil_test.go => testx/testx_test.go} (87%) rename internal/{urlutil/urlutil.go => urlx/urlx.go} (91%) rename internal/{urlutil/urlutil_test.go => urlx/urlx_test.go} (96%) rename internal/{userutil/userutil.go => userx/userx.go} (97%) rename internal/{userutil/userutil_test.go => userx/userx_test.go} (97%) diff --git a/cmd/gogs/backup.go b/cmd/gogs/backup.go index a01a06632..0ba38efe2 100644 --- a/cmd/gogs/backup.go +++ b/cmd/gogs/backup.go @@ -17,7 +17,7 @@ import ( "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/database" - "gogs.io/gogs/internal/osutil" + "gogs.io/gogs/internal/osx" ) var backupCommand = cli.Command{ @@ -59,7 +59,7 @@ func runBackup(ctx context.Context, cmd *cli.Command) error { } tmpDir := cmd.String("tempdir") - if !osutil.Exist(tmpDir) { + if !osx.Exist(tmpDir) { log.Fatal("'--tempdir' does not exist: %s", tmpDir) } rootDir, err := os.MkdirTemp(tmpDir, "gogs-backup-") @@ -108,7 +108,7 @@ func runBackup(ctx context.Context, cmd *cli.Command) error { // Data files for _, dir := range []string{"ssh", "attachments", "avatars", "repo-avatars"} { dirPath := filepath.Join(conf.Server.AppDataPath, dir) - if !osutil.IsDir(dirPath) { + if !osx.IsDir(dirPath) { continue } diff --git a/cmd/gogs/hook.go b/cmd/gogs/hook.go index cd86a15b3..8c31797dd 100644 --- a/cmd/gogs/hook.go +++ b/cmd/gogs/hook.go @@ -22,7 +22,7 @@ import ( "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/email" "gogs.io/gogs/internal/httplib" - "gogs.io/gogs/internal/osutil" + "gogs.io/gogs/internal/osx" ) var ( @@ -133,7 +133,7 @@ func runHookPreReceive(_ context.Context, cmd *cli.Command) error { } customHooksPath := filepath.Join(os.Getenv(database.EnvRepoCustomHooksPath), "pre-receive") - if !osutil.IsFile(customHooksPath) { + if !osx.IsFile(customHooksPath) { return nil } @@ -167,7 +167,7 @@ func runHookUpdate(_ context.Context, cmd *cli.Command) error { } customHooksPath := filepath.Join(os.Getenv(database.EnvRepoCustomHooksPath), "update") - if !osutil.IsFile(customHooksPath) { + if !osx.IsFile(customHooksPath) { return nil } @@ -252,7 +252,7 @@ func runHookPostReceive(_ context.Context, cmd *cli.Command) error { } customHooksPath := filepath.Join(os.Getenv(database.EnvRepoCustomHooksPath), "post-receive") - if !osutil.IsFile(customHooksPath) { + if !osx.IsFile(customHooksPath) { return nil } diff --git a/cmd/gogs/import.go b/cmd/gogs/import.go index 52bd02e8d..fe40a58c6 100644 --- a/cmd/gogs/import.go +++ b/cmd/gogs/import.go @@ -13,7 +13,7 @@ import ( "github.com/urfave/cli/v3" "gogs.io/gogs/internal/conf" - "gogs.io/gogs/internal/osutil" + "gogs.io/gogs/internal/osx" ) var ( @@ -45,9 +45,9 @@ func runImportLocale(_ context.Context, cmd *cli.Command) error { } else if !cmd.IsSet("target") { return errors.New("target directory is not specified") } - if !osutil.IsDir(cmd.String("source")) { + if !osx.IsDir(cmd.String("source")) { return errors.Newf("source directory %q does not exist or is not a directory", cmd.String("source")) - } else if !osutil.IsDir(cmd.String("target")) { + } else if !osx.IsDir(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) source := filepath.Join(cmd.String("source"), name) target := filepath.Join(cmd.String("target"), name) - if !osutil.IsFile(source) { + if !osx.IsFile(source) { continue } diff --git a/cmd/gogs/restore.go b/cmd/gogs/restore.go index 7297843bc..53b9a015c 100644 --- a/cmd/gogs/restore.go +++ b/cmd/gogs/restore.go @@ -14,8 +14,8 @@ import ( "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/database" - "gogs.io/gogs/internal/osutil" - "gogs.io/gogs/internal/semverutil" + "gogs.io/gogs/internal/osx" + "gogs.io/gogs/internal/semverx" ) var restoreCommand = cli.Command{ @@ -46,7 +46,7 @@ func runRestore(ctx context.Context, cmd *cli.Command) error { zip.Verbose = cmd.Bool("verbose") tmpDir := cmd.String("tempdir") - if !osutil.IsDir(tmpDir) { + if !osx.IsDir(tmpDir) { log.Fatal("'--tempdir' does not exist: %s", tmpDir) } archivePath := path.Join(tmpDir, archiveRootDir) @@ -66,7 +66,7 @@ func runRestore(ctx context.Context, cmd *cli.Command) error { // Check backup version metaFile := filepath.Join(archivePath, "metadata.ini") - if !osutil.IsFile(metaFile) { + if !osx.IsFile(metaFile) { log.Fatal("File 'metadata.ini' is missing") } 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) } backupVersion := metadata.Section("").Key("GOGS_VERSION").MustString("999.0") - if semverutil.Compare(conf.App.Version, "<", backupVersion) { + if semverx.Compare(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() @@ -92,7 +92,7 @@ func runRestore(ctx context.Context, cmd *cli.Command) error { var customConf string if lineageConf := configFromLineage(cmd); lineageConf != "" { customConf = lineageConf - } else if !osutil.IsFile(configFile) { + } else if !osx.IsFile(configFile) { log.Fatal("'--config' is not specified and custom config file is not found in backup") } else { customConf = configFile @@ -117,7 +117,7 @@ func runRestore(ctx context.Context, cmd *cli.Command) error { if !cmd.Bool("database-only") { // Custom files - if osutil.IsDir(conf.CustomDir()) { + if osx.IsDir(conf.CustomDir()) { if err = os.Rename(conf.CustomDir(), conf.CustomDir()+".bak"); err != nil { 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"} { // Skip if backup archive does not have corresponding data srcPath := filepath.Join(archivePath, "data", dir) - if !osutil.IsDir(srcPath) { + if !osx.IsDir(srcPath) { continue } dirPath := filepath.Join(conf.Server.AppDataPath, dir) - if osutil.IsDir(dirPath) { + if osx.IsDir(dirPath) { if err = os.Rename(dirPath, dirPath+".bak"); err != nil { log.Fatal("Failed to backup current 'data': %v", err) } @@ -149,7 +149,7 @@ func runRestore(ctx context.Context, cmd *cli.Command) error { // Repositories reposPath := filepath.Join(archivePath, "repositories.zip") - if !cmd.Bool("exclude-repos") && !cmd.Bool("database-only") && osutil.IsFile(reposPath) { + if !cmd.Bool("exclude-repos") && !cmd.Bool("database-only") && osx.IsFile(reposPath) { if err := zip.ExtractTo(reposPath, filepath.Dir(conf.Repository.Root)); err != nil { log.Fatal("Failed to extract 'repositories.zip': %v", err) } diff --git a/cmd/gogs/web.go b/cmd/gogs/web.go index cb2f5416d..faa7d92dd 100644 --- a/cmd/gogs/web.go +++ b/cmd/gogs/web.go @@ -31,7 +31,7 @@ import ( "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/form" - "gogs.io/gogs/internal/osutil" + "gogs.io/gogs/internal/osx" "gogs.io/gogs/internal/route" "gogs.io/gogs/internal/route/admin" apiv1 "gogs.io/gogs/internal/route/api/v1" @@ -308,7 +308,7 @@ func runWeb(_ stdctx.Context, cmd *cli.Command) error { if err != nil { c.NotFoundOrError(err, "get attachment by UUID") return - } else if !osutil.IsFile(attach.LocalPath()) { + } else if !osx.IsFile(attach.LocalPath()) { c.NotFound() return } @@ -750,7 +750,7 @@ func runWeb(_ stdctx.Context, cmd *cli.Command) error { err = fcgi.Serve(nil, m) case "unix": - if osutil.Exist(listenAddr) { + if osx.Exist(listenAddr) { err = os.Remove(listenAddr) if err != nil { log.Fatal("Failed to remove existing Unix domain socket: %v", err) diff --git a/internal/app/metrics.go b/internal/app/metrics.go index e1d327e30..5e125b443 100644 --- a/internal/app/metrics.go +++ b/internal/app/metrics.go @@ -5,7 +5,7 @@ import ( "gopkg.in/macaron.v1" - "gogs.io/gogs/internal/authutil" + "gogs.io/gogs/internal/authx" "gogs.io/gogs/internal/conf" ) @@ -20,7 +20,7 @@ func MetricsFilter() macaron.Handler { return } - username, password := authutil.DecodeBasic(r.Header) + username, password := authx.DecodeBasic(r.Header) if username != conf.Prometheus.BasicAuthUsername || password != conf.Prometheus.BasicAuthPassword { w.WriteHeader(http.StatusForbidden) return diff --git a/internal/auth/auth.go b/internal/auth/auth.go index 21f99c326..3b53fd9eb 100644 --- a/internal/auth/auth.go +++ b/internal/auth/auth.go @@ -5,7 +5,7 @@ import ( "github.com/cockroachdb/errors" - "gogs.io/gogs/internal/errutil" + "gogs.io/gogs/internal/errx" ) type Type int @@ -34,10 +34,10 @@ func Name(typ Type) string { }[typ] } -var _ errutil.NotFound = (*ErrBadCredentials)(nil) +var _ errx.NotFound = (*ErrBadCredentials)(nil) type ErrBadCredentials struct { - Args errutil.Args + Args errx.Args } // IsErrBadCredentials returns true if the underlying error has the type diff --git a/internal/authutil/basic.go b/internal/authx/basic.go similarity index 97% rename from internal/authutil/basic.go rename to internal/authx/basic.go index 28107a725..9e1f44d4b 100644 --- a/internal/authutil/basic.go +++ b/internal/authx/basic.go @@ -1,4 +1,4 @@ -package authutil +package authx import ( "encoding/base64" diff --git a/internal/authutil/basic_test.go b/internal/authx/basic_test.go similarity index 98% rename from internal/authutil/basic_test.go rename to internal/authx/basic_test.go index 693da7657..1f5ac16d8 100644 --- a/internal/authutil/basic_test.go +++ b/internal/authx/basic_test.go @@ -1,4 +1,4 @@ -package authutil +package authx import ( "net/http" diff --git a/internal/conf/computed_test.go b/internal/conf/computed_test.go index 04dc0993d..dabbb2449 100644 --- a/internal/conf/computed_test.go +++ b/internal/conf/computed_test.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/assert" - "gogs.io/gogs/internal/testutil" + "gogs.io/gogs/internal/testx" ) func TestIsProdMode(t *testing.T) { @@ -36,7 +36,7 @@ func TestIsProdMode(t *testing.T) { } func TestWorkDirHelper(_ *testing.T) { - if !testutil.WantHelperProcess() { + if !testx.WantHelperProcess() { return } @@ -53,7 +53,7 @@ func TestWorkDir(t *testing.T) { } for _, test := range tests { t.Run("", func(t *testing.T) { - out, err := testutil.Exec("TestWorkDirHelper", test.env) + out, err := testx.Exec("TestWorkDirHelper", test.env) if err != nil { t.Fatal(err) } @@ -64,7 +64,7 @@ func TestWorkDir(t *testing.T) { } func TestCustomDirHelper(_ *testing.T) { - if !testutil.WantHelperProcess() { + if !testx.WantHelperProcess() { return } @@ -81,7 +81,7 @@ func TestCustomDir(t *testing.T) { } for _, test := range tests { t.Run("", func(t *testing.T) { - out, err := testutil.Exec("TestCustomDirHelper", test.env) + out, err := testx.Exec("TestCustomDirHelper", test.env) if err != nil { t.Fatal(err) } @@ -92,7 +92,7 @@ func TestCustomDir(t *testing.T) { } func TestHomeDirHelper(_ *testing.T) { - if !testutil.WantHelperProcess() { + if !testx.WantHelperProcess() { return } @@ -111,7 +111,7 @@ func TestHomeDir(t *testing.T) { } for _, test := range tests { t.Run("", func(t *testing.T) { - out, err := testutil.Exec("TestHomeDirHelper", test.envs...) + out, err := testx.Exec("TestHomeDirHelper", test.envs...) if err != nil { t.Fatal(err) } diff --git a/internal/conf/conf.go b/internal/conf/conf.go index 8c51c7b6c..6be97a58b 100644 --- a/internal/conf/conf.go +++ b/internal/conf/conf.go @@ -18,8 +18,8 @@ import ( log "unknwon.dev/clog/v2" "gogs.io/gogs/conf" - "gogs.io/gogs/internal/osutil" - "gogs.io/gogs/internal/semverutil" + "gogs.io/gogs/internal/osx" + "gogs.io/gogs/internal/semverx" ) func init() { @@ -66,7 +66,7 @@ func Init(customConf string) error { } CustomConf = customConf - if osutil.IsFile(customConf) { + if osx.IsFile(customConf) { if err = File.Append(customConf); err != nil { return errors.Wrapf(err, "append %q", customConf) } @@ -141,7 +141,7 @@ func Init(customConf string) error { return errors.Wrap(err, "get OpenSSH version") } - if IsWindowsRuntime() || semverutil.Compare(sshVersion, "<", "5.1") { + if IsWindowsRuntime() || semverx.Compare(sshVersion, "<", "5.1") { if !HookMode { log.Warn(`SSH minimum key size check is forced to be disabled because server is not eligible: 1. Windows server @@ -383,7 +383,7 @@ func Init(customConf string) error { return errors.Wrap(err, "mapping [other] section") } - HasRobotsTxt = osutil.IsFile(filepath.Join(CustomDir(), "robots.txt")) + HasRobotsTxt = osx.IsFile(filepath.Join(CustomDir(), "robots.txt")) return nil } diff --git a/internal/conf/conf_test.go b/internal/conf/conf_test.go index b741b465e..23a7392a2 100644 --- a/internal/conf/conf_test.go +++ b/internal/conf/conf_test.go @@ -8,7 +8,7 @@ import ( "github.com/stretchr/testify/assert" "gopkg.in/ini.v1" - "gogs.io/gogs/internal/testutil" + "gogs.io/gogs/internal/testx" ) func TestInit(t *testing.T) { @@ -55,5 +55,5 @@ func TestInit(t *testing.T) { t.Fatal(err) } - testutil.AssertGolden(t, filepath.Join("testdata", "TestInit.golden.ini"), testutil.Update("TestInit"), buf.String()) + testx.AssertGolden(t, filepath.Join("testdata", "TestInit.golden.ini"), testx.Update("TestInit"), buf.String()) } diff --git a/internal/conf/utils.go b/internal/conf/utils.go index 7fb7eb339..364108d4e 100644 --- a/internal/conf/utils.go +++ b/internal/conf/utils.go @@ -6,7 +6,7 @@ import ( "github.com/cockroachdb/errors" - "gogs.io/gogs/internal/osutil" + "gogs.io/gogs/internal/osx" "gogs.io/gogs/internal/process" ) @@ -44,6 +44,6 @@ func CheckRunUser(runUser string) (string, bool) { return "", true } - currentUser := osutil.CurrentUsername() + currentUser := osx.CurrentUsername() return currentUser, runUser == currentUser } diff --git a/internal/context/api.go b/internal/context/api.go index 112fb4a29..e40b0700e 100644 --- a/internal/context/api.go +++ b/internal/context/api.go @@ -11,7 +11,7 @@ import ( log "unknwon.dev/clog/v2" "gogs.io/gogs/internal/conf" - "gogs.io/gogs/internal/errutil" + "gogs.io/gogs/internal/errx" ) 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, // or error context description for logging purpose of 500 server error. func (c *APIContext) NotFoundOrError(err error, msg string) { - if errutil.IsNotFound(err) { + if errx.IsNotFound(err) { c.NotFound() return } diff --git a/internal/context/context.go b/internal/context/context.go index 454579e73..ca560219d 100644 --- a/internal/context/context.go +++ b/internal/context/context.go @@ -16,7 +16,7 @@ import ( "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/database" - "gogs.io/gogs/internal/errutil" + "gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/form" "gogs.io/gogs/internal/lazyregexp" "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. func (c *Context) NotFoundOrError(err error, msg string) { - if errutil.IsNotFound(err) { + if errx.IsNotFound(err) { c.NotFound() return } diff --git a/internal/context/go_get.go b/internal/context/go_get.go index 8a5336c3e..ca067d063 100644 --- a/internal/context/go_get.go +++ b/internal/context/go_get.go @@ -10,7 +10,7 @@ import ( "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/database" - "gogs.io/gogs/internal/repoutil" + "gogs.io/gogs/internal/repox" ) // ServeGoGet does quick responses for appropriate go-get meta with status OK @@ -53,7 +53,7 @@ func ServeGoGet() macaron.Handler { `, map[string]string{ "GoGetImport": path.Join(conf.Server.URL.Host, conf.Server.Subpath, ownerName, repoName), - "CloneLink": repoutil.HTTPSCloneURL(ownerName, repoName), + "CloneLink": repox.HTTPSCloneURL(ownerName, repoName), "GoDocDirectory": prefix + "{/dir}", "GoDocFile": prefix + "{/dir}/{file}#L{line}", "InsecureFlag": insecureFlag, diff --git a/internal/context/notice.go b/internal/context/notice.go index 68a3ce341..897fea1de 100644 --- a/internal/context/notice.go +++ b/internal/context/notice.go @@ -8,7 +8,7 @@ import ( "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/markup" - "gogs.io/gogs/internal/osutil" + "gogs.io/gogs/internal/osx" "gogs.io/gogs/internal/tool" ) @@ -16,7 +16,7 @@ import ( // on all pages. func (c *Context) renderNoticeBanner() { fpath := filepath.Join(conf.CustomDir(), "notice", "banner.md") - if !osutil.Exist(fpath) { + if !osx.Exist(fpath) { return } diff --git a/internal/context/repo.go b/internal/context/repo.go index d9708ed3a..a6c7dead7 100644 --- a/internal/context/repo.go +++ b/internal/context/repo.go @@ -14,7 +14,7 @@ import ( "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/database" - "gogs.io/gogs/internal/repoutil" + "gogs.io/gogs/internal/repox" ) type PullRequest struct { @@ -40,7 +40,7 @@ type Repository struct { TreePath string CommitID string RepoLink string - CloneLink repoutil.CloneLink + CloneLink repox.CloneLink CommitsCount int64 Mirror *database.Mirror diff --git a/internal/cryptoutil/aes.go b/internal/cryptox/aes.go similarity index 98% rename from internal/cryptoutil/aes.go rename to internal/cryptox/aes.go index f61d2bf02..0978e0d41 100644 --- a/internal/cryptoutil/aes.go +++ b/internal/cryptox/aes.go @@ -1,4 +1,4 @@ -package cryptoutil +package cryptox import ( "crypto/aes" diff --git a/internal/cryptoutil/aes_test.go b/internal/cryptox/aes_test.go similarity index 96% rename from internal/cryptoutil/aes_test.go rename to internal/cryptox/aes_test.go index 2ecc0c185..13c195ffc 100644 --- a/internal/cryptoutil/aes_test.go +++ b/internal/cryptox/aes_test.go @@ -1,4 +1,4 @@ -package cryptoutil +package cryptox import ( "crypto/rand" diff --git a/internal/cryptoutil/md5.go b/internal/cryptox/md5.go similarity index 94% rename from internal/cryptoutil/md5.go rename to internal/cryptox/md5.go index 1436e637d..14c35b1ab 100644 --- a/internal/cryptoutil/md5.go +++ b/internal/cryptox/md5.go @@ -1,4 +1,4 @@ -package cryptoutil +package cryptox import ( "crypto/md5" diff --git a/internal/cryptoutil/md5_test.go b/internal/cryptox/md5_test.go similarity index 96% rename from internal/cryptoutil/md5_test.go rename to internal/cryptox/md5_test.go index 20a6ca1e0..f89f57a89 100644 --- a/internal/cryptoutil/md5_test.go +++ b/internal/cryptox/md5_test.go @@ -1,4 +1,4 @@ -package cryptoutil +package cryptox import ( "testing" diff --git a/internal/cryptoutil/sha.go b/internal/cryptox/sha.go similarity index 95% rename from internal/cryptoutil/sha.go rename to internal/cryptox/sha.go index e36b5c44c..2e02cdf6c 100644 --- a/internal/cryptoutil/sha.go +++ b/internal/cryptox/sha.go @@ -1,4 +1,4 @@ -package cryptoutil +package cryptox import ( "crypto/sha1" diff --git a/internal/cryptoutil/sha_test.go b/internal/cryptox/sha_test.go similarity index 98% rename from internal/cryptoutil/sha_test.go rename to internal/cryptox/sha_test.go index bc9c43441..e1d28220a 100644 --- a/internal/cryptoutil/sha_test.go +++ b/internal/cryptox/sha_test.go @@ -1,4 +1,4 @@ -package cryptoutil +package cryptox import ( "testing" diff --git a/internal/database/access_tokens.go b/internal/database/access_tokens.go index 9837fe87f..d68d37d89 100644 --- a/internal/database/access_tokens.go +++ b/internal/database/access_tokens.go @@ -9,8 +9,8 @@ import ( "github.com/google/uuid" "gorm.io/gorm" - "gogs.io/gogs/internal/cryptoutil" - "gogs.io/gogs/internal/errutil" + "gogs.io/gogs/internal/cryptox" + "gogs.io/gogs/internal/errx" ) // AccessToken is a personal access token. @@ -58,7 +58,7 @@ func newAccessTokensStore(db *gorm.DB) *AccessTokensStore { } type ErrAccessTokenAlreadyExist struct { - args errutil.Args + args errx.Args } 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) { err := s.db.WithContext(ctx).Where("uid = ? AND name = ?", userID, name).First(new(AccessToken)).Error if err == nil { - return nil, ErrAccessTokenAlreadyExist{args: errutil.Args{"userID": userID, "name": name}} + return nil, ErrAccessTokenAlreadyExist{args: errx.Args{"userID": userID, "name": name}} } else if !errors.Is(err, gorm.ErrRecordNotFound) { return nil, err } - token := cryptoutil.SHA1(uuid.New().String()) - sha256 := cryptoutil.SHA256(token) + token := cryptox.SHA1(uuid.New().String()) + sha256 := cryptox.SHA256(token) accessToken := &AccessToken{ 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 } -var _ errutil.NotFound = (*ErrAccessTokenNotExist)(nil) +var _ errx.NotFound = (*ErrAccessTokenNotExist)(nil) type ErrAccessTokenNotExist struct { - args errutil.Args + args errx.Args } // 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) { // No need to waste a query for an empty SHA1. if sha1 == "" { - return nil, ErrAccessTokenNotExist{args: errutil.Args{"sha": sha1}} + return nil, ErrAccessTokenNotExist{args: errx.Args{"sha": sha1}} } - sha256 := cryptoutil.SHA256(sha1) + sha256 := cryptox.SHA256(sha1) token := new(AccessToken) err := s.db.WithContext(ctx).Where("sha256 = ?", sha256).First(token).Error if errors.Is(err, gorm.ErrRecordNotFound) { - return nil, ErrAccessTokenNotExist{args: errutil.Args{"sha": sha1}} + return nil, ErrAccessTokenNotExist{args: errx.Args{"sha": sha1}} } else if err != nil { return nil, err } diff --git a/internal/database/access_tokens_test.go b/internal/database/access_tokens_test.go index b7926185b..f66271371 100644 --- a/internal/database/access_tokens_test.go +++ b/internal/database/access_tokens_test.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/require" "gorm.io/gorm" - "gogs.io/gogs/internal/errutil" + "gogs.io/gogs/internal/errx" ) 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 _, err = s.Create(ctx, token.UserID, token.Name) wantErr := ErrAccessTokenAlreadyExist{ - args: errutil.Args{ + args: errx.Args{ "userID": token.UserID, "name": token.Name, }, @@ -166,7 +166,7 @@ func accessTokensDeleteByID(t *testing.T, ctx context.Context, s *AccessTokensSt // We should get token not found error _, err = s.GetBySHA1(ctx, token.Sha1) wantErr := ErrAccessTokenNotExist{ - args: errutil.Args{ + args: errx.Args{ "sha": token.Sha1, }, } @@ -185,7 +185,7 @@ func accessTokensGetBySHA(t *testing.T, ctx context.Context, s *AccessTokensStor // Try to get a non-existent token _, err = s.GetBySHA1(ctx, "bad_sha") wantErr := ErrAccessTokenNotExist{ - args: errutil.Args{ + args: errx.Args{ "sha": "bad_sha", }, } diff --git a/internal/database/actions.go b/internal/database/actions.go index e6e0a6b2b..7a2c3f217 100644 --- a/internal/database/actions.go +++ b/internal/database/actions.go @@ -17,10 +17,10 @@ import ( "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/lazyregexp" - "gogs.io/gogs/internal/repoutil" + "gogs.io/gogs/internal/repox" apiv1types "gogs.io/gogs/internal/route/api/v1/types" - "gogs.io/gogs/internal/strutil" - "gogs.io/gogs/internal/testutil" + "gogs.io/gogs/internal/strx" + "gogs.io/gogs/internal/testx" "gogs.io/gogs/internal/tool" ) @@ -218,14 +218,14 @@ func (s *ActionsStore) MirrorSyncPush(ctx context.Context, opts MirrorSyncPushOp apiCommits, err := opts.Commits.APIFormat(ctx, newUsersStore(s.db), - repoutil.RepositoryPath(opts.Owner.Name, opts.Repo.Name), - repoutil.HTMLURL(opts.Owner.Name, opts.Repo.Name), + repox.RepositoryPath(opts.Owner.Name, opts.Repo.Name), + repox.HTMLURL(opts.Owner.Name, opts.Repo.Name), ) if err != nil { return errors.Wrap(err, "convert commits to API format") } - opts.Commits.CompareURL = repoutil.CompareCommitsPath(opts.Owner.Name, opts.Repo.Name, opts.OldCommitID, opts.NewCommitID) + opts.Commits.CompareURL = repox.CompareCommitsPath(opts.Owner.Name, opts.Repo.Name, opts.OldCommitID, opts.NewCommitID) apiPusher := opts.Owner.APIFormat() err = PrepareWebhooks( 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 !isNewRef && !isDelRef { - opts.Commits.CompareURL = repoutil.CompareCommitsPath(opts.Owner.Name, opts.Repo.Name, opts.OldCommitID, opts.NewCommitID) + opts.Commits.CompareURL = repox.CompareCommitsPath(opts.Owner.Name, opts.Repo.Name, opts.OldCommitID, opts.NewCommitID) } 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, newUsersStore(s.db), - repoutil.RepositoryPath(opts.Owner.Name, opts.Repo.Name), - repoutil.HTMLURL(opts.Owner.Name, opts.Repo.Name), + repox.RepositoryPath(opts.Owner.Name, opts.Repo.Name), + repox.HTMLURL(opts.Owner.Name, opts.Repo.Name), ) if err != nil { return errors.Wrap(err, "convert commits to API format") @@ -751,7 +751,7 @@ func (a *Action) GetActUserName() string { } func (a *Action) ShortActUserName() string { - return strutil.Ellipsis(a.ActUserName, 20) + return strx.Ellipsis(a.ActUserName, 20) } func (a *Action) GetRepoUserName() string { @@ -759,7 +759,7 @@ func (a *Action) GetRepoUserName() string { } func (a *Action) ShortRepoUserName() string { - return strutil.Ellipsis(a.RepoUserName, 20) + return strx.Ellipsis(a.RepoUserName, 20) } func (a *Action) GetRepoName() string { @@ -767,7 +767,7 @@ func (a *Action) GetRepoName() string { } func (a *Action) ShortRepoName() string { - return strutil.Ellipsis(a.RepoName, 33) + return strx.Ellipsis(a.RepoName, 33) } func (a *Action) GetRepoPath() string { @@ -883,7 +883,7 @@ func (pcs *PushCommits) APIFormat(ctx context.Context, usersStore *UsersStore, r } nameStatus := &git.NameStatus{} - if !testutil.InTest { + if !testx.InTest { nameStatus, err = git.ShowNameStatus(repoPath, commit.Sha1) if err != nil { return nil, errors.Wrapf(err, "show name status [commit_sha1: %s]", commit.Sha1) diff --git a/internal/database/attachment.go b/internal/database/attachment.go index aba01d684..dd227306e 100644 --- a/internal/database/attachment.go +++ b/internal/database/attachment.go @@ -13,7 +13,7 @@ import ( "xorm.io/xorm" "gogs.io/gogs/internal/conf" - "gogs.io/gogs/internal/errutil" + "gogs.io/gogs/internal/errx" ) // 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 } -var _ errutil.NotFound = (*ErrAttachmentNotExist)(nil) +var _ errx.NotFound = (*ErrAttachmentNotExist)(nil) type ErrAttachmentNotExist struct { args map[string]any diff --git a/internal/database/backup.go b/internal/database/backup.go index cebedf4a5..4ede981aa 100644 --- a/internal/database/backup.go +++ b/internal/database/backup.go @@ -21,7 +21,7 @@ import ( "xorm.io/xorm" "gogs.io/gogs/internal/conf" - "gogs.io/gogs/internal/osutil" + "gogs.io/gogs/internal/osx" ) // 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.") err := func() error { tableFile := filepath.Join(dirPath, tableName+".json") - if !osutil.IsFile(tableFile) { + if !osx.IsFile(tableFile) { log.Info("Skipped table %q", tableName) return nil } @@ -247,7 +247,7 @@ func importLegacyTables(ctx context.Context, dirPath string, verbose bool) error tableName := strings.TrimPrefix(fmt.Sprintf("%T", table), "*database.") tableFile := filepath.Join(dirPath, tableName+".json") - if !osutil.IsFile(tableFile) { + if !osx.IsFile(tableFile) { continue } diff --git a/internal/database/backup_test.go b/internal/database/backup_test.go index ff899b366..4df1f785f 100644 --- a/internal/database/backup_test.go +++ b/internal/database/backup_test.go @@ -15,10 +15,10 @@ import ( "gogs.io/gogs/internal/auth" "gogs.io/gogs/internal/auth/github" "gogs.io/gogs/internal/auth/pam" - "gogs.io/gogs/internal/cryptoutil" + "gogs.io/gogs/internal/cryptox" "gogs.io/gogs/internal/dbtest" - "gogs.io/gogs/internal/lfsutil" - "gogs.io/gogs/internal/testutil" + "gogs.io/gogs/internal/lfsx" + "gogs.io/gogs/internal/testx" ) func TestDumpAndImport(t *testing.T) { @@ -59,30 +59,30 @@ func setupDBToDump(t *testing.T, db *gorm.DB) { &AccessToken{ UserID: 1, Name: "test1", - Sha1: cryptoutil.SHA1("2910d03d-c0b5-4f71-bad5-c4086e4efae3"), - SHA256: cryptoutil.SHA256(cryptoutil.SHA1("2910d03d-c0b5-4f71-bad5-c4086e4efae3")), + Sha1: cryptox.SHA1("2910d03d-c0b5-4f71-bad5-c4086e4efae3"), + SHA256: cryptox.SHA256(cryptox.SHA1("2910d03d-c0b5-4f71-bad5-c4086e4efae3")), CreatedUnix: 1588568886, UpdatedUnix: 1588572486, // 1 hour later }, &AccessToken{ UserID: 1, Name: "test2", - Sha1: cryptoutil.SHA1("84117e17-7e67-4024-bd04-1c23e6e809d4"), - SHA256: cryptoutil.SHA256(cryptoutil.SHA1("84117e17-7e67-4024-bd04-1c23e6e809d4")), + Sha1: cryptox.SHA1("84117e17-7e67-4024-bd04-1c23e6e809d4"), + SHA256: cryptox.SHA256(cryptox.SHA1("84117e17-7e67-4024-bd04-1c23e6e809d4")), CreatedUnix: 1588568886, }, &AccessToken{ UserID: 2, Name: "test1", - Sha1: cryptoutil.SHA1("da2775ce-73dd-47ba-b9d2-bbcc346585c4"), - SHA256: cryptoutil.SHA256(cryptoutil.SHA1("da2775ce-73dd-47ba-b9d2-bbcc346585c4")), + Sha1: cryptox.SHA1("da2775ce-73dd-47ba-b9d2-bbcc346585c4"), + SHA256: cryptox.SHA256(cryptox.SHA1("da2775ce-73dd-47ba-b9d2-bbcc346585c4")), CreatedUnix: 1588568886, }, &AccessToken{ UserID: 2, Name: "test2", - Sha1: cryptoutil.SHA256(cryptoutil.SHA1("1b2dccd1-a262-470f-bb8c-7fc73192e9bb"))[:40], - SHA256: cryptoutil.SHA256(cryptoutil.SHA1("1b2dccd1-a262-470f-bb8c-7fc73192e9bb")), + Sha1: cryptox.SHA256(cryptox.SHA1("1b2dccd1-a262-470f-bb8c-7fc73192e9bb"))[:40], + SHA256: cryptox.SHA256(cryptox.SHA1("1b2dccd1-a262-470f-bb8c-7fc73192e9bb")), CreatedUnix: 1588568886, }, @@ -156,14 +156,14 @@ func setupDBToDump(t *testing.T, db *gorm.DB) { RepoID: 1, OID: "ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f", Size: 100, - Storage: lfsutil.StorageLocal, + Storage: lfsx.StorageLocal, CreatedAt: time.Unix(1588568886, 0).UTC(), }, &LFSObject{ RepoID: 2, OID: "ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f", Size: 100, - Storage: lfsutil.StorageLocal, + Storage: lfsx.StorageLocal, 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") - testutil.AssertGolden(t, golden, testutil.Update("TestDumpAndImport"), buf.String()) + testx.AssertGolden(t, golden, testx.Update("TestDumpAndImport"), buf.String()) } } diff --git a/internal/database/comment.go b/internal/database/comment.go index bea1a52f4..3f9bc9b8d 100644 --- a/internal/database/comment.go +++ b/internal/database/comment.go @@ -11,7 +11,7 @@ import ( log "unknwon.dev/clog/v2" "xorm.io/xorm" - "gogs.io/gogs/internal/errutil" + "gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/markup" 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 } -var _ errutil.NotFound = (*ErrCommentNotExist)(nil) +var _ errx.NotFound = (*ErrCommentNotExist)(nil) type ErrCommentNotExist struct { args map[string]any diff --git a/internal/database/database.go b/internal/database/database.go index 4ccdec778..ddfa9e6d2 100644 --- a/internal/database/database.go +++ b/internal/database/database.go @@ -13,7 +13,7 @@ import ( log "unknwon.dev/clog/v2" "gogs.io/gogs/internal/conf" - "gogs.io/gogs/internal/dbutil" + "gogs.io/gogs/internal/dbx" ) func newLogWriter() (logger.Writer, error) { @@ -30,7 +30,7 @@ func newLogWriter() (logger.Writer, error) { if err != nil { return nil, errors.Wrap(err, `create "gorm.log"`) } - return &dbutil.Logger{Writer: w}, nil + return &dbx.Logger{Writer: w}, nil } // Tables is the list of struct-to-table mappings. @@ -59,7 +59,7 @@ func NewConnection(w logger.Writer) (*gorm.DB, error) { LogLevel: level, }) - db, err := dbutil.OpenDB( + db, err := dbx.OpenDB( conf.Database, &gorm.Config{ SkipDefaultTransaction: true, diff --git a/internal/database/issue.go b/internal/database/issue.go index 4d8af355c..a787e77db 100644 --- a/internal/database/issue.go +++ b/internal/database/issue.go @@ -12,7 +12,7 @@ import ( "xorm.io/xorm" "gogs.io/gogs/internal/conf" - "gogs.io/gogs/internal/errutil" + "gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/markup" apiv1types "gogs.io/gogs/internal/route/api/v1/types" "gogs.io/gogs/internal/tool" @@ -82,7 +82,7 @@ func getUserByID(e Engine, id int64) (*User, error) { if err != nil { return nil, err } else if !has { - return nil, ErrUserNotExist{args: errutil.Args{"userID": id}} + return nil, ErrUserNotExist{args: errx.Args{"userID": id}} } // 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 } -var _ errutil.NotFound = (*ErrIssueNotExist)(nil) +var _ errx.NotFound = (*ErrIssueNotExist)(nil) type ErrIssueNotExist struct { args map[string]any diff --git a/internal/database/issue_label.go b/internal/database/issue_label.go index 331ccc718..e3f827541 100644 --- a/internal/database/issue_label.go +++ b/internal/database/issue_label.go @@ -10,7 +10,7 @@ import ( "github.com/cockroachdb/errors" - "gogs.io/gogs/internal/errutil" + "gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/lazyregexp" apiv1types "gogs.io/gogs/internal/route/api/v1/types" "gogs.io/gogs/internal/tool" @@ -101,7 +101,7 @@ func NewLabels(labels ...*Label) error { return err } -var _ errutil.NotFound = (*ErrLabelNotExist)(nil) +var _ errx.NotFound = (*ErrLabelNotExist)(nil) type ErrLabelNotExist struct { args map[string]any diff --git a/internal/database/issue_mail.go b/internal/database/issue_mail.go index 59d6aa1e6..6144e7100 100644 --- a/internal/database/issue_mail.go +++ b/internal/database/issue_mail.go @@ -10,8 +10,8 @@ import ( "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/email" "gogs.io/gogs/internal/markup" - "gogs.io/gogs/internal/strutil" - "gogs.io/gogs/internal/userutil" + "gogs.io/gogs/internal/strx" + "gogs.io/gogs/internal/userx" ) func (issue *Issue) MailSubject() string { @@ -36,7 +36,7 @@ func (mu mailerUser) Email() string { } func (mu mailerUser) GenerateEmailActivateCode(email string) string { - return userutil.GenerateActivateCode( + return userx.GenerateActivateCode( mu.user.ID, email, mu.user.Name, @@ -138,7 +138,7 @@ func mailIssueCommentToParticipants(issue *Issue, doer *User, mentions []string) for i := range participants { if participants[i].ID == doer.ID { continue - } else if strutil.ContainsFold(names, participants[i].Name) { + } else if strx.ContainsFold(names, participants[i].Name) { continue } @@ -146,7 +146,7 @@ func mailIssueCommentToParticipants(issue *Issue, doer *User, mentions []string) names = append(names, participants[i].Name) } if issue.Assignee != nil && issue.Assignee.ID != doer.ID { - if !strutil.ContainsFold(names, issue.Assignee.Name) { + if !strx.ContainsFold(names, issue.Assignee.Name) { tos = append(tos, issue.Assignee.Email) names = append(names, issue.Assignee.Name) } @@ -159,7 +159,7 @@ func mailIssueCommentToParticipants(issue *Issue, doer *User, mentions []string) names = append(names, doer.Name) toUsernames := make([]string, 0, len(mentions)) // list of user names. for i := range mentions { - if strutil.ContainsFold(names, mentions[i]) { + if strx.ContainsFold(names, mentions[i]) { continue } diff --git a/internal/database/lfs.go b/internal/database/lfs.go index baa43b883..5b2a6e590 100644 --- a/internal/database/lfs.go +++ b/internal/database/lfs.go @@ -8,17 +8,17 @@ import ( "github.com/cockroachdb/errors" "gorm.io/gorm" - "gogs.io/gogs/internal/errutil" - "gogs.io/gogs/internal/lfsutil" + "gogs.io/gogs/internal/errx" + "gogs.io/gogs/internal/lfsx" ) // LFSObject is the relation between an LFS object and a repository. type LFSObject struct { - RepoID int64 `gorm:"primaryKey;auto_increment:false"` - OID lfsutil.OID `gorm:"primaryKey;column:oid"` - Size int64 `gorm:"not null"` - Storage lfsutil.Storage `gorm:"not null"` - CreatedAt time.Time `gorm:"not null"` + RepoID int64 `gorm:"primaryKey;auto_increment:false"` + OID lfsx.OID `gorm:"primaryKey;column:oid"` + Size int64 `gorm:"not null"` + Storage lfsx.Storage `gorm:"not null"` + CreatedAt time.Time `gorm:"not null"` } // 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. -func (s *LFSStore) CreateObject(ctx context.Context, repoID int64, oid lfsutil.OID, size int64, storage lfsutil.Storage) error { +func (s *LFSStore) CreateObject(ctx context.Context, repoID int64, oid lfsx.OID, size int64, storage lfsx.Storage) error { object := &LFSObject{ RepoID: repoID, OID: oid, @@ -42,7 +42,7 @@ func (s *LFSStore) CreateObject(ctx context.Context, repoID int64, oid lfsutil.O } type ErrLFSObjectNotExist struct { - args errutil.Args + args errx.Args } func IsErrLFSObjectNotExist(err error) bool { @@ -59,12 +59,12 @@ func (ErrLFSObjectNotExist) NotFound() bool { // GetObjectByOID returns the LFS object with given OID. It returns // ErrLFSObjectNotExist when not found. -func (s *LFSStore) GetObjectByOID(ctx context.Context, repoID int64, oid lfsutil.OID) (*LFSObject, error) { +func (s *LFSStore) GetObjectByOID(ctx context.Context, repoID int64, oid lfsx.OID) (*LFSObject, error) { object := new(LFSObject) err := s.db.WithContext(ctx).Where("repo_id = ? AND oid = ?", repoID, oid).First(object).Error if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { - return nil, ErrLFSObjectNotExist{args: errutil.Args{"repoID": repoID, "oid": oid}} + return nil, ErrLFSObjectNotExist{args: errx.Args{"repoID": repoID, "oid": oid}} } return nil, err } @@ -73,7 +73,7 @@ func (s *LFSStore) GetObjectByOID(ctx context.Context, repoID int64, oid lfsutil // GetObjectsByOIDs returns LFS objects found within "oids". The returned list // could have fewer elements if some oids were not found. -func (s *LFSStore) GetObjectsByOIDs(ctx context.Context, repoID int64, oids ...lfsutil.OID) ([]*LFSObject, error) { +func (s *LFSStore) GetObjectsByOIDs(ctx context.Context, repoID int64, oids ...lfsx.OID) ([]*LFSObject, error) { if len(oids) == 0 { return []*LFSObject{}, nil } diff --git a/internal/database/lfs_test.go b/internal/database/lfs_test.go index b3d6d5395..64c45a90f 100644 --- a/internal/database/lfs_test.go +++ b/internal/database/lfs_test.go @@ -8,8 +8,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "gogs.io/gogs/internal/errutil" - "gogs.io/gogs/internal/lfsutil" + "gogs.io/gogs/internal/errx" + "gogs.io/gogs/internal/lfsx" ) func TestLFS(t *testing.T) { @@ -47,8 +47,8 @@ func TestLFS(t *testing.T) { func lfsCreateObject(t *testing.T, ctx context.Context, s *LFSStore) { // Create first LFS object repoID := int64(1) - oid := lfsutil.OID("ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f") - err := s.CreateObject(ctx, repoID, oid, 12, lfsutil.StorageLocal) + oid := lfsx.OID("ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f") + err := s.CreateObject(ctx, repoID, oid, 12, lfsx.StorageLocal) require.NoError(t, err) // 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)) // Try to create second LFS object with same oid should fail - err = s.CreateObject(ctx, repoID, oid, 12, lfsutil.StorageLocal) + err = s.CreateObject(ctx, repoID, oid, 12, lfsx.StorageLocal) assert.Error(t, err) } func lfsGetObjectByOID(t *testing.T, ctx context.Context, s *LFSStore) { // Create a LFS object repoID := int64(1) - oid := lfsutil.OID("ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f") - err := s.CreateObject(ctx, repoID, oid, 12, lfsutil.StorageLocal) + oid := lfsx.OID("ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f") + err := s.CreateObject(ctx, repoID, oid, 12, lfsx.StorageLocal) require.NoError(t, err) // 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 _, err = s.GetObjectByOID(ctx, repoID, "bad_oid") - expErr := ErrLFSObjectNotExist{args: errutil.Args{"repoID": repoID, "oid": lfsutil.OID("bad_oid")}} + expErr := ErrLFSObjectNotExist{args: errx.Args{"repoID": repoID, "oid": lfsx.OID("bad_oid")}} assert.Equal(t, expErr, err) } func lfsGetObjectsByOIDs(t *testing.T, ctx context.Context, s *LFSStore) { // Create two LFS objects repoID := int64(1) - oid1 := lfsutil.OID("ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f") - oid2 := lfsutil.OID("ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64g") - err := s.CreateObject(ctx, repoID, oid1, 12, lfsutil.StorageLocal) + oid1 := lfsx.OID("ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f") + oid2 := lfsx.OID("ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64g") + err := s.CreateObject(ctx, repoID, oid1, 12, lfsx.StorageLocal) require.NoError(t, err) - err = s.CreateObject(ctx, repoID, oid2, 12, lfsutil.StorageLocal) + err = s.CreateObject(ctx, repoID, oid2, 12, lfsx.StorageLocal) require.NoError(t, err) // We should be able to get them back and ignore non-existent ones diff --git a/internal/database/login_source_files.go b/internal/database/login_source_files.go index 9f1fd33d9..dc7ca5f3f 100644 --- a/internal/database/login_source_files.go +++ b/internal/database/login_source_files.go @@ -16,8 +16,8 @@ import ( "gogs.io/gogs/internal/auth/ldap" "gogs.io/gogs/internal/auth/pam" "gogs.io/gogs/internal/auth/smtp" - "gogs.io/gogs/internal/errutil" - "gogs.io/gogs/internal/osutil" + "gogs.io/gogs/internal/errx" + "gogs.io/gogs/internal/osx" ) // 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 } -var _ errutil.NotFound = (*ErrLoginSourceNotExist)(nil) +var _ errx.NotFound = (*ErrLoginSourceNotExist)(nil) type ErrLoginSourceNotExist struct { - args errutil.Args + args errx.Args } func IsErrLoginSourceNotExist(err error) bool { @@ -69,7 +69,7 @@ func (s *loginSourceFiles) GetByID(id int64) (*LoginSource, error) { } } - return nil, ErrLoginSourceNotExist{args: errutil.Args{"id": id}} + return nil, ErrLoginSourceNotExist{args: errx.Args{"id": id}} } func (s *loginSourceFiles) Len() int { @@ -109,7 +109,7 @@ func (s *loginSourceFiles) Update(source *LoginSource) { // loadLoginSourceFiles loads login sources from file system. func loadLoginSourceFiles(authdPath string, clock func() time.Time) (loginSourceFilesStore, error) { - if !osutil.IsDir(authdPath) { + if !osx.IsDir(authdPath) { return &loginSourceFiles{clock: clock}, nil } diff --git a/internal/database/login_source_files_test.go b/internal/database/login_source_files_test.go index 2d1d7bf5c..26c79878a 100644 --- a/internal/database/login_source_files_test.go +++ b/internal/database/login_source_files_test.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "gogs.io/gogs/internal/errutil" + "gogs.io/gogs/internal/errx" ) 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) { _, err := store.GetByID(1) - wantErr := ErrLoginSourceNotExist{args: errutil.Args{"id": int64(1)}} + wantErr := ErrLoginSourceNotExist{args: errx.Args{"id": int64(1)}} assert.Equal(t, wantErr, err) }) diff --git a/internal/database/login_sources.go b/internal/database/login_sources.go index 17b596ab1..236c03814 100644 --- a/internal/database/login_sources.go +++ b/internal/database/login_sources.go @@ -15,7 +15,7 @@ import ( "gogs.io/gogs/internal/auth/ldap" "gogs.io/gogs/internal/auth/pam" "gogs.io/gogs/internal/auth/smtp" - "gogs.io/gogs/internal/errutil" + "gogs.io/gogs/internal/errx" ) // LoginSource represents an external way for authorizing users. @@ -189,7 +189,7 @@ type CreateLoginSourceOptions struct { } type ErrLoginSourceAlreadyExist struct { - args errutil.Args + args errx.Args } 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) { err := s.db.WithContext(ctx).Where("name = ?", opts.Name).First(new(LoginSource)).Error if err == nil { - return nil, ErrLoginSourceAlreadyExist{args: errutil.Args{"name": opts.Name}} + return nil, ErrLoginSourceAlreadyExist{args: errx.Args{"name": opts.Name}} } else if !errors.Is(err, gorm.ErrRecordNotFound) { return nil, err } @@ -232,7 +232,7 @@ func (s *LoginSourcesStore) Count(ctx context.Context) int64 { } type ErrLoginSourceInUse struct { - args errutil.Args + args errx.Args } func IsErrLoginSourceInUse(err error) bool { @@ -251,7 +251,7 @@ func (s *LoginSourcesStore) DeleteByID(ctx context.Context, id int64) error { if err != nil { return err } else if count > 0 { - return ErrLoginSourceInUse{args: errutil.Args{"id": id}} + return ErrLoginSourceInUse{args: errx.Args{"id": id}} } return s.db.WithContext(ctx).Where("id = ?", id).Delete(new(LoginSource)).Error diff --git a/internal/database/login_sources_test.go b/internal/database/login_sources_test.go index 797fd1352..d4d9ec95d 100644 --- a/internal/database/login_sources_test.go +++ b/internal/database/login_sources_test.go @@ -15,7 +15,7 @@ import ( "gogs.io/gogs/internal/auth/ldap" "gogs.io/gogs/internal/auth/pam" "gogs.io/gogs/internal/auth/smtp" - "gogs.io/gogs/internal/errutil" + "gogs.io/gogs/internal/errx" ) 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. _, err = s.Create(ctx, CreateLoginSourceOptions{Name: source.Name}) - wantErr := ErrLoginSourceAlreadyExist{args: errutil.Args{"name": source.Name}} + wantErr := ErrLoginSourceAlreadyExist{args: errx.Args{"name": source.Name}} 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 err = s.DeleteByID(ctx, source.ID) - wantErr := ErrLoginSourceInUse{args: errutil.Args{"id": source.ID}} + wantErr := ErrLoginSourceInUse{args: errx.Args{"id": source.ID}} assert.Equal(t, wantErr, err) }) mock := NewMockLoginSourceFilesStore() mock.GetByIDFunc.SetDefaultHook(func(id int64) (*LoginSource, error) { - return nil, ErrLoginSourceNotExist{args: errutil.Args{"id": id}} + return nil, ErrLoginSourceNotExist{args: errx.Args{"id": id}} }) 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 _, err = s.GetByID(ctx, source.ID) - wantErr := ErrLoginSourceNotExist{args: errutil.Args{"id": source.ID}} + wantErr := ErrLoginSourceNotExist{args: errx.Args{"id": source.ID}} assert.Equal(t, wantErr, err) } @@ -316,7 +316,7 @@ func loginSourcesGetByID(t *testing.T, ctx context.Context, s *LoginSourcesStore mock := NewMockLoginSourceFilesStore() mock.GetByIDFunc.SetDefaultHook(func(id int64) (*LoginSource, error) { if id != 101 { - return nil, ErrLoginSourceNotExist{args: errutil.Args{"id": id}} + return nil, ErrLoginSourceNotExist{args: errx.Args{"id": id}} } return &LoginSource{ID: id}, nil }) diff --git a/internal/database/main_test.go b/internal/database/main_test.go index ffa7846b2..f75921a0d 100644 --- a/internal/database/main_test.go +++ b/internal/database/main_test.go @@ -12,7 +12,7 @@ import ( "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/dbtest" - "gogs.io/gogs/internal/testutil" + "gogs.io/gogs/internal/testx" ) func TestMain(m *testing.M) { @@ -22,7 +22,7 @@ func TestMain(m *testing.M) { if !testing.Verbose() { // Remove the primary logger and register a noop logger. log.Remove(log.DefaultConsoleName) - err := log.New("noop", testutil.InitNoopLogger) + err := log.New("noop", testx.InitNoopLogger) if err != nil { fmt.Println(err) os.Exit(1) diff --git a/internal/database/migrations/main_test.go b/internal/database/migrations/main_test.go index 0e7aebee1..859ea3430 100644 --- a/internal/database/migrations/main_test.go +++ b/internal/database/migrations/main_test.go @@ -9,7 +9,7 @@ import ( "gorm.io/gorm/logger" log "unknwon.dev/clog/v2" - "gogs.io/gogs/internal/testutil" + "gogs.io/gogs/internal/testx" ) func TestMain(m *testing.M) { @@ -19,7 +19,7 @@ func TestMain(m *testing.M) { if !testing.Verbose() { // Remove the primary logger and register a noop logger. log.Remove(log.DefaultConsoleName) - err := log.New("noop", testutil.InitNoopLogger) + err := log.New("noop", testx.InitNoopLogger) if err != nil { fmt.Println(err) os.Exit(1) diff --git a/internal/database/migrations/v20.go b/internal/database/migrations/v20.go index eb767085e..d42e4db02 100644 --- a/internal/database/migrations/v20.go +++ b/internal/database/migrations/v20.go @@ -4,7 +4,7 @@ import ( "github.com/cockroachdb/errors" "gorm.io/gorm" - "gogs.io/gogs/internal/cryptoutil" + "gogs.io/gogs/internal/cryptox" ) func migrateAccessTokenToSHA256(db *gorm.DB) error { @@ -33,7 +33,7 @@ func migrateAccessTokenToSHA256(db *gorm.DB) error { } for _, t := range accessTokens { - sha256 := cryptoutil.SHA256(t.Sha1) + sha256 := cryptox.SHA256(t.Sha1) err = tx.Model(&accessToken{}).Where("id = ?", t.ID).Update("sha256", sha256).Error if err != nil { return errors.Wrap(err, "update") diff --git a/internal/database/milestone.go b/internal/database/milestone.go index 6e81aa23f..f8186daf1 100644 --- a/internal/database/milestone.go +++ b/internal/database/milestone.go @@ -10,7 +10,7 @@ import ( "github.com/cockroachdb/errors" "gogs.io/gogs/internal/conf" - "gogs.io/gogs/internal/errutil" + "gogs.io/gogs/internal/errx" apiv1types "gogs.io/gogs/internal/route/api/v1/types" ) @@ -128,7 +128,7 @@ func NewMilestone(m *Milestone) (err error) { return sess.Commit() } -var _ errutil.NotFound = (*ErrMilestoneNotExist)(nil) +var _ errx.NotFound = (*ErrMilestoneNotExist)(nil) type ErrMilestoneNotExist struct { args map[string]any diff --git a/internal/database/models.go b/internal/database/models.go index a6458a2b2..7bcf1f1d1 100644 --- a/internal/database/models.go +++ b/internal/database/models.go @@ -20,7 +20,7 @@ import ( "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/database/migrations" - "gogs.io/gogs/internal/dbutil" + "gogs.io/gogs/internal/dbx" ) // Engine represents a XORM engine or session. @@ -89,7 +89,7 @@ func getEngine() (*xorm.Engine, error) { case "postgres": conf.UsePostgreSQL = true - host, port := dbutil.ParsePostgreSQLHostPort(conf.Database.Host) + host, port := dbx.ParsePostgreSQLHostPort(conf.Database.Host) 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) driver = "pgx" @@ -166,7 +166,7 @@ func SetEngine() (*gorm.DB, error) { var gormLogger logger.Writer if conf.HookMode { - gormLogger = &dbutil.Logger{Writer: fileWriter} + gormLogger = &dbx.Logger{Writer: fileWriter} } else { gormLogger, err = newLogWriter() if err != nil { diff --git a/internal/database/org.go b/internal/database/org.go index fcbff087b..806139916 100644 --- a/internal/database/org.go +++ b/internal/database/org.go @@ -9,9 +9,9 @@ import ( "xorm.io/builder" "xorm.io/xorm" - "gogs.io/gogs/internal/errutil" - "gogs.io/gogs/internal/repoutil" - "gogs.io/gogs/internal/userutil" + "gogs.io/gogs/internal/errx" + "gogs.io/gogs/internal/repox" + "gogs.io/gogs/internal/userx" ) 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) { return ErrUserAlreadyExist{ - args: errutil.Args{ + args: errx.Args{ "name": org.Name, }, } } org.LowerName = strings.ToLower(org.Name) - if org.Rands, err = userutil.RandomSalt(); err != nil { + if org.Rands, err = userx.RandomSalt(); err != nil { return err } - if org.Salt, err = userutil.RandomSalt(); err != nil { + if org.Salt, err = userx.RandomSalt(); err != nil { return err } org.UseCustomAvatar = true @@ -130,7 +130,7 @@ func CreateOrganization(org, owner *User) (err error) { if _, err = sess.Insert(org); err != nil { return errors.Newf("insert organization: %v", err) } - _ = userutil.GenerateRandomAvatar(org.ID, org.Name, org.Email) + _ = userx.GenerateRandomAvatar(org.ID, org.Name, org.Email) // Add initial creator to organization and owner team. 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) } - if err = os.MkdirAll(repoutil.UserPath(org.Name), os.ModePerm); err != nil { + if err = os.MkdirAll(repox.UserPath(org.Name), os.ModePerm); err != nil { return errors.Newf("create directory: %v", err) } diff --git a/internal/database/org_team.go b/internal/database/org_team.go index 7e6630db4..61076b76c 100644 --- a/internal/database/org_team.go +++ b/internal/database/org_team.go @@ -8,7 +8,7 @@ import ( "github.com/cockroachdb/errors" "xorm.io/xorm" - "gogs.io/gogs/internal/errutil" + "gogs.io/gogs/internal/errx" ) const ownerTeamName = "Owners" @@ -297,7 +297,7 @@ func NewTeam(t *Team) error { return sess.Commit() } -var _ errutil.NotFound = (*ErrTeamNotExist)(nil) +var _ errx.NotFound = (*ErrTeamNotExist)(nil) type ErrTeamNotExist struct { args map[string]any diff --git a/internal/database/organizations.go b/internal/database/organizations.go index 531a85bab..2342df305 100644 --- a/internal/database/organizations.go +++ b/internal/database/organizations.go @@ -6,7 +6,7 @@ import ( "github.com/cockroachdb/errors" "gorm.io/gorm" - "gogs.io/gogs/internal/dbutil" + "gogs.io/gogs/internal/dbx" ) // 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 */ tx := s.db.WithContext(ctx). - Joins(dbutil.Quote("JOIN org_user ON org_user.org_id = %s.id", "user")). + Joins(dbx.Quote("JOIN org_user ON org_user.org_id = %s.id", "user")). Where("org_user.uid = ?", opts.MemberID). - Order(dbutil.Quote("%s.id ASC", "user")) + Order(dbx.Quote("%s.id ASC", "user")) if !opts.IncludePrivateMembers { tx = tx.Where("org_user.is_public = ?", true) } diff --git a/internal/database/organizations_test.go b/internal/database/organizations_test.go index aaa07bd74..18a57ee66 100644 --- a/internal/database/organizations_test.go +++ b/internal/database/organizations_test.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "gogs.io/gogs/internal/dbutil" + "gogs.io/gogs/internal/dbx" ) 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{}) require.NoError(t, err) err = s.db.Exec( - dbutil.Quote("UPDATE %s SET type = ? WHERE id IN (?, ?)", "user"), + dbx.Quote("UPDATE %s SET type = ? WHERE id IN (?, ?)", "user"), UserTypeOrganization, org1.ID, org2.ID, ).Error 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"}) require.NoError(t, err) err = s.db.Exec( - dbutil.Quote("UPDATE %s SET type = ? WHERE id IN (?, ?)", "user"), + dbx.Quote("UPDATE %s SET type = ? WHERE id IN (?, ?)", "user"), UserTypeOrganization, org1.ID, org2.ID, ).Error require.NoError(t, err) diff --git a/internal/database/public_keys.go b/internal/database/public_keys.go index c114cc231..42361cdef 100644 --- a/internal/database/public_keys.go +++ b/internal/database/public_keys.go @@ -8,7 +8,7 @@ import ( "gorm.io/gorm" "gogs.io/gogs/internal/conf" - "gogs.io/gogs/internal/osutil" + "gogs.io/gogs/internal/osx" ) // PublicKeysStore is the storage layer for public keys. @@ -73,7 +73,7 @@ func (s *PublicKeysStore) RewriteAuthorizedKeys() error { if err != nil { return errors.Wrap(err, "close temporary file") } - if osutil.Exist(fpath) { + if osx.Exist(fpath) { err = os.Remove(fpath) if err != nil { return errors.Wrap(err, "remove") diff --git a/internal/database/pull.go b/internal/database/pull.go index 2d8165df8..d127ca5f9 100644 --- a/internal/database/pull.go +++ b/internal/database/pull.go @@ -15,8 +15,8 @@ import ( "github.com/gogs/git-module" "gogs.io/gogs/internal/conf" - "gogs.io/gogs/internal/errutil" - "gogs.io/gogs/internal/osutil" + "gogs.io/gogs/internal/errx" + "gogs.io/gogs/internal/osx" "gogs.io/gogs/internal/process" apiv1types "gogs.io/gogs/internal/route/api/v1/types" "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. - if !osutil.IsFile(patchPath) { + if !osx.IsFile(patchPath) { log.Trace("PullRequest[%d].testPatch: ignored corrupted data", pr.ID) return nil } @@ -552,7 +552,7 @@ func GetUnmergedPullRequestsByBaseInfo(repoID int64, branch string) ([]*PullRequ Join("INNER", "issue", "issue.id=pull_request.issue_id").Find(&prs) } -var _ errutil.NotFound = (*ErrPullRequestNotExist)(nil) +var _ errx.NotFound = (*ErrPullRequestNotExist)(nil) type ErrPullRequestNotExist struct { args map[string]any @@ -684,7 +684,7 @@ func (pr *PullRequest) PushToBaseRepo() (err error) { headRefspec := fmt.Sprintf("refs/pull/%d/head", pr.Index) headFile := filepath.Join(pr.BaseRepo.RepoPath(), headRefspec) - if osutil.Exist(headFile) { + if osx.Exist(headFile) { err = os.Remove(headFile) if err != nil { return errors.Newf("remove head file [repo_id: %d]: %v", pr.BaseRepoID, err) diff --git a/internal/database/release.go b/internal/database/release.go index 384501aed..d5eaa856d 100644 --- a/internal/database/release.go +++ b/internal/database/release.go @@ -12,7 +12,7 @@ import ( "github.com/cockroachdb/errors" "github.com/gogs/git-module" - "gogs.io/gogs/internal/errutil" + "gogs.io/gogs/internal/errx" 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 } -var _ errutil.NotFound = (*ErrReleaseNotExist)(nil) +var _ errx.NotFound = (*ErrReleaseNotExist)(nil) type ErrReleaseNotExist struct { args map[string]any diff --git a/internal/database/repo.go b/internal/database/repo.go index 54956c8cd..1e75ede26 100644 --- a/internal/database/repo.go +++ b/internal/database/repo.go @@ -30,15 +30,15 @@ import ( embedConf "gogs.io/gogs/conf" "gogs.io/gogs/internal/avatar" "gogs.io/gogs/internal/conf" - "gogs.io/gogs/internal/dbutil" - "gogs.io/gogs/internal/errutil" + "gogs.io/gogs/internal/dbx" + "gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/markup" - "gogs.io/gogs/internal/osutil" + "gogs.io/gogs/internal/osx" "gogs.io/gogs/internal/process" - "gogs.io/gogs/internal/repoutil" + "gogs.io/gogs/internal/repox" apiv1types "gogs.io/gogs/internal/route/api/v1/types" - "gogs.io/gogs/internal/semverutil" - "gogs.io/gogs/internal/strutil" + "gogs.io/gogs/internal/semverx" + "gogs.io/gogs/internal/strx" "gogs.io/gogs/internal/sync" ) @@ -80,7 +80,7 @@ func LoadRepoConfig() { } customPath := filepath.Join(conf.CustomDir(), "conf", t) - if osutil.IsDir(customPath) { + if osx.IsDir(customPath) { entries, err := os.ReadDir(customPath) if err != nil { log.Fatal("Failed to get custom %s files: %v", t, err) @@ -88,7 +88,7 @@ func LoadRepoConfig() { for _, entry := range entries { f := entry.Name() - if !strutil.ContainsFold(files, f) { + if !strx.ContainsFold(files, f) { files = append(files, f) } } @@ -136,7 +136,7 @@ func NewRepoContext() { } log.Trace("Git version: %s", conf.Git.Version) - if semverutil.Compare(conf.Git.Version, "<", "1.8.3") { + if semverx.Compare(conf.Git.Version, "<", "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 } -// Deprecated: Use repoutil.HTMLURL instead. +// Deprecated: Use repox.HTMLURL instead. func (r *Repository) HTMLURL() string { 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. func (r *Repository) RelAvatarLink() string { defaultImgURL := "" - if !osutil.Exist(r.CustomAvatarPath()) { + if !osx.Exist(r.CustomAvatarPath()) { return defaultImgURL } 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, }, ) { - return nil, ErrUserNotExist{args: errutil.Args{"userID": userID}} + return nil, ErrUserNotExist{args: errx.Args{"userID": 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) } -// Deprecated: Use repoutil.RepositoryPath instead. +// Deprecated: Use repox.RepositoryPath instead. func (r *Repository) RepoPath() string { return r.repoPath(x) } @@ -602,7 +602,7 @@ func (r *Repository) Link() string { return conf.Server.Subpath + "/" + r.FullName() } -// Deprecated: Use repoutil.ComparePath instead. +// Deprecated: Use repox.ComparePath instead. func (r *Repository) ComposeCompareURL(oldCommitID, newCommitID string) string { 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 // about no race condition. func UpdateLocalCopyBranch(repoPath, localPath, branch string, isWiki bool) (err error) { - if !osutil.Exist(localPath) { + if !osx.Exist(localPath) { // Checkout to a specific branch fails when wiki is an empty repository. if isWiki { branch = "" @@ -736,7 +736,7 @@ func isRepositoryExist(e Engine, u *User, repoName string) (bool, error) { OwnerID: u.ID, LowerName: strings.ToLower(repoName), }) - return has && osutil.IsDir(RepoPath(u.Name, repoName)), err + return has && osx.IsDir(RepoPath(u.Name, repoName)), err } // 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) } -// Deprecated: Use repoutil.NewCloneLink instead. -func (r *Repository) cloneLink(isWiki bool) *repoutil.CloneLink { +// Deprecated: Use repox.NewCloneLink instead. +func (r *Repository) cloneLink(isWiki bool) *repox.CloneLink { repoName := r.Name if isWiki { repoName += ".wiki" } r.Owner = r.MustOwner() - cl := new(repoutil.CloneLink) + cl := new(repox.CloneLink) 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) } else { cl.SSH = fmt.Sprintf("%s@%s:%s/%s.git", conf.App.RunUser, conf.SSH.Domain, r.Owner.Name, repoName) } - cl.HTTPS = repoutil.HTTPSCloneURL(r.Owner.Name, repoName) + cl.HTTPS = repox.HTTPSCloneURL(r.Owner.Name, repoName) return cl } // CloneLink returns clone URLs of repository. // -// Deprecated: Use repoutil.NewCloneLink instead. -func (r *Repository) CloneLink() (cl *repoutil.CloneLink) { +// Deprecated: Use repox.NewCloneLink instead. +func (r *Repository) CloneLink() (cl *repox.CloneLink) { return r.cloneLink(false) } @@ -990,7 +990,7 @@ func getRepoInitFile(tp, name string) ([]byte, error) { // Use custom file when available. customPath := filepath.Join(conf.CustomDir(), "conf", relPath) - if osutil.IsFile(customPath) { + if osx.IsFile(customPath) { return os.ReadFile(customPath) } return embedConf.Files.ReadFile(relPath) @@ -1148,14 +1148,14 @@ func createRepository(e *xorm.Session, doer, owner *User, repo *Repository) (err if err != nil { return errors.Newf("IsRepositoryExist: %v", err) } else if has { - return ErrRepoAlreadyExist{args: errutil.Args{"ownerID": owner.ID, "name": repo.Name}} + return ErrRepoAlreadyExist{args: errx.Args{"ownerID": owner.ID, "name": repo.Name}} } if _, err = e.Insert(repo); err != nil { return err } - _, err = e.Exec(dbutil.Quote("UPDATE %s SET num_repos = num_repos + 1 WHERE id = ?", "user"), owner.ID) + _, err = e.Exec(dbx.Quote("UPDATE %s SET num_repos = num_repos + 1 WHERE id = ?", "user"), owner.ID) if err != nil { 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. func CreateRepository(doer, owner *User, opts CreateRepoOptionsLegacy) (_ *Repository, err error) { repoPath := RepoPath(owner.Name, opts.Name) - if osutil.Exist(repoPath) { + if osx.Exist(repoPath) { return nil, errors.Errorf("repository directory already exists: %s", repoPath) } if !owner.canCreateRepo() { @@ -1361,9 +1361,9 @@ func FilterRepositoryWithIssues(repoIDs []int64) ([]int64, error) { // RepoPath returns repository path by given user and repository name. // -// Deprecated: Use repoutil.RepositoryPath instead. +// Deprecated: Use repox.RepositoryPath instead. func RepoPath(userName, repoName string) string { - return filepath.Join(repoutil.UserPath(userName), strings.ToLower(repoName)+".git") + return filepath.Join(repox.UserPath(userName), strings.ToLower(repoName)+".git") } // 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 { return errors.Newf("IsRepositoryExist: %v", err) } else if has { - return ErrRepoAlreadyExist{args: errutil.Args{"ownerName": newOwnerName, "name": repo.Name}} + return ErrRepoAlreadyExist{args: errx.Args{"ownerName": newOwnerName, "name": repo.Name}} } 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. - if err = os.MkdirAll(repoutil.UserPath(newOwner.Name), os.ModePerm); err != nil { + if err = os.MkdirAll(repox.UserPath(newOwner.Name), os.ModePerm); err != nil { return err } 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. wikiPath := WikiPath(owner.Name, repo.Name) - if osutil.Exist(wikiPath) { + if osx.Exist(wikiPath) { RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath()) if err = os.Rename(wikiPath, WikiPath(newOwner.Name, repo.Name)); err != nil { 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) { repoWorkingPool.CheckIn(strconv.FormatInt(repoID, 10)) defer repoWorkingPool.CheckOut(strconv.FormatInt(repoID, 10)) - RemoveAllWithNotice(fmt.Sprintf("Delete repository %d local copy", repoID), repoutil.RepositoryLocalPath(repoID)) + RemoveAllWithNotice(fmt.Sprintf("Delete repository %d local copy", repoID), repox.RepositoryLocalPath(repoID)) } // 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 { return errors.Newf("IsRepositoryExist: %v", err) } else if has { - return ErrRepoAlreadyExist{args: errutil.Args{"ownerID": u.ID, "name": newRepoName}} + return ErrRepoAlreadyExist{args: errx.Args{"ownerID": u.ID, "name": newRepoName}} } repo, err := GetRepositoryByName(u.ID, oldRepoName) @@ -1543,7 +1543,7 @@ func ChangeRepositoryName(u *User, oldRepoName, newRepoName string) (err error) } wikiPath := repo.WikiPath() - if osutil.Exist(wikiPath) { + if osx.Exist(wikiPath) { if err = os.Rename(wikiPath, WikiPath(u.Name, newRepoName)); err != nil { 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 daemonExportFile := path.Join(repo.RepoPath(), "git-daemon-export-ok") - if repo.IsPrivate && osutil.Exist(daemonExportFile) { + if repo.IsPrivate && osx.Exist(daemonExportFile) { if err = os.Remove(daemonExportFile); err != nil { log.Error("Failed to remove %s: %v", daemonExportFile, err) } - } else if !repo.IsPrivate && !osutil.Exist(daemonExportFile) { + } else if !repo.IsPrivate && !osx.Exist(daemonExportFile) { if f, err := os.Create(daemonExportFile); err != nil { log.Error("Failed to create %s: %v", daemonExportFile, err) } else { @@ -1937,7 +1937,7 @@ func DeleteOldRepositoryArchives() { basePath := filepath.Join(repo.RepoPath(), "archives") for _, format := range formats { dirPath := filepath.Join(basePath, format) - if !osutil.IsDir(dirPath) { + if !osx.IsDir(dirPath) { continue } @@ -2000,7 +2000,7 @@ func gatherMissingRepoRecords() ([]*Repository, error) { if err := x.Where("id > 0").Iterate(new(Repository), func(idx int, bean any) error { repo := bean.(*Repository) - if !osutil.IsDir(repo.RepoPath()) { + if !osx.IsDir(repo.RepoPath()) { repos = append(repos, repo) } return nil diff --git a/internal/database/repo_branch.go b/internal/database/repo_branch.go index f31585f61..3eefc0ae7 100644 --- a/internal/database/repo_branch.go +++ b/internal/database/repo_branch.go @@ -9,7 +9,7 @@ import ( "github.com/cockroachdb/errors" "github.com/gogs/git-module" - "gogs.io/gogs/internal/errutil" + "gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/tool" ) @@ -42,7 +42,7 @@ func GetBranchesByPath(path string) ([]*Branch, error) { return branches, nil } -var _ errutil.NotFound = (*ErrBranchNotExist)(nil) +var _ errx.NotFound = (*ErrBranchNotExist)(nil) type ErrBranchNotExist struct { args map[string]any diff --git a/internal/database/repo_editor.go b/internal/database/repo_editor.go index 7346f8e7f..7a4c9e202 100644 --- a/internal/database/repo_editor.go +++ b/internal/database/repo_editor.go @@ -18,11 +18,11 @@ import ( "github.com/gogs/git-module" "gogs.io/gogs/internal/conf" - "gogs.io/gogs/internal/cryptoutil" - "gogs.io/gogs/internal/gitutil" - "gogs.io/gogs/internal/ioutil" - "gogs.io/gogs/internal/osutil" - "gogs.io/gogs/internal/pathutil" + "gogs.io/gogs/internal/cryptox" + "gogs.io/gogs/internal/gitx" + "gogs.io/gogs/internal/iox" + "gogs.io/gogs/internal/osx" + "gogs.io/gogs/internal/pathx" "gogs.io/gogs/internal/process" ) @@ -68,7 +68,7 @@ func ComposeHookEnvs(opts ComposeHookEnvsOptions) []string { EnvAuthUserName + "=" + opts.AuthUser.Name, EnvAuthUserEmail + "=" + opts.AuthUser.Email, EnvRepoOwnerName + "=" + opts.OwnerName, - EnvRepoOwnerSaltMd5 + "=" + cryptoutil.MD5(opts.OwnerSalt), + EnvRepoOwnerSaltMd5 + "=" + cryptox.MD5(opts.OwnerSalt), EnvRepoID + "=" + strconv.FormatInt(opts.RepoID, 10), EnvRepoName + "=" + opts.RepoName, EnvRepoCustomHooksPath + "=" + filepath.Join(opts.RepoPath, "custom_hooks"), @@ -86,7 +86,7 @@ func ComposeHookEnvs(opts ComposeHookEnvsOptions) []string { // discardLocalRepoBranchChanges discards local commits/changes of // given branch to make sure it is even to remote branch. func discardLocalRepoBranchChanges(localPath, branch string) error { - if !osutil.Exist(localPath) { + if !osx.Exist(localPath) { return nil } @@ -123,7 +123,7 @@ func hasSymlinkInPath(base, relPath string) bool { parts := strings.Split(filepath.ToSlash(relPath), "/") for i := range parts { filePath := path.Join(append([]string{base}, parts[:i+1]...)...) - if osutil.IsSymlink(filePath) { + if osx.IsSymlink(filePath) { return true } } @@ -189,7 +189,7 @@ func (r *Repository) UpdateRepoFile(doer *User, opts UpdateRepoFileOptions) erro newFilePath := path.Join(localPath, opts.NewTreeName) // Prompt the user if the meant-to-be new file already exists. - if osutil.Exist(newFilePath) && opts.IsNewFile { + if osx.Exist(newFilePath) && opts.IsNewFile { 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) } - if osutil.IsFile(oldFilePath) && opts.OldTreeName != opts.NewTreeName { + if osx.IsFile(oldFilePath) && opts.OldTreeName != opts.NewTreeName { if err := git.Move(localPath, opts.OldTreeName, opts.NewTreeName); err != nil { 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. -func (r *Repository) GetDiffPreview(branch, treePath, content string) (*gitutil.Diff, error) { +func (r *Repository) GetDiffPreview(branch, treePath, content string) (*gitx.Diff, error) { // 🚨 SECURITY: Prevent uploading files into the ".git" directory. if isRepositoryGitPath(treePath) { return nil, errors.Errorf("bad tree path %q", treePath) @@ -291,7 +291,7 @@ func (r *Repository) GetDiffPreview(branch, treePath, content string) (*gitutil. pid := process.Add(fmt.Sprintf("GetDiffPreview [repo_path: %s]", r.RepoPath()), cmd) defer process.Remove(pid) - diff, err := gitutil.ParseDiff(stdout, conf.Git.MaxDiffFiles, conf.Git.MaxDiffLines, conf.Git.MaxDiffLineChars) + diff, err := gitx.ParseDiff(stdout, conf.Git.MaxDiffFiles, conf.Git.MaxDiffLines, conf.Git.MaxDiffLineChars) if err != nil { return nil, errors.Newf("parse diff: %v", err) } @@ -416,7 +416,7 @@ func (upload *Upload) LocalPath() string { // NewUpload creates a new upload object. func NewUpload(name string, buf []byte, file multipart.File) (_ *Upload, err error) { // 🚨 SECURITY: Prevent path traversal. - name = pathutil.Clean(name) + name = pathx.Clean(name) if name == "" { return nil, errors.New("empty file name") } @@ -492,7 +492,7 @@ func DeleteUploads(uploads ...*Upload) (err error) { for _, upload := range uploads { localPath := upload.LocalPath() - if !osutil.IsFile(localPath) { + if !osx.IsFile(localPath) { continue } @@ -536,7 +536,7 @@ type UploadRepoFileOptions struct { // isRepositoryGitPath returns true if given path is or resides inside ".git" // path of the repository. // -// TODO(unknwon): Move to repoutil during refactoring for this file. +// TODO(unknwon): Move to repox during refactoring for this file. func isRepositoryGitPath(path string) bool { path = strings.ToLower(path) return strings.HasSuffix(path, ".git") || @@ -587,12 +587,12 @@ func (r *Repository) UploadRepoFiles(doer *User, opts UploadRepoFileOptions) err // Copy uploaded files into repository for _, upload := range uploads { tmpPath := upload.LocalPath() - if !osutil.IsFile(tmpPath) { + if !osx.IsFile(tmpPath) { continue } // 🚨 SECURITY: Prevent path traversal. - upload.Name = pathutil.Clean(upload.Name) + upload.Name = pathx.Clean(upload.Name) // 🚨 SECURITY: Prevent uploading files into the ".git" directory. 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 // is a symlink. - if osutil.IsSymlink(targetPath) { + if osx.IsSymlink(targetPath) { return errors.Newf("cannot overwrite symbolic link: %s", upload.Name) } - if err = ioutil.CopyFile(tmpPath, targetPath); err != nil { + if err = iox.CopyFile(tmpPath, targetPath); err != nil { return errors.Newf("copy: %v", err) } } diff --git a/internal/database/repo_test.go b/internal/database/repo_test.go index 725dadd63..f98f01f8c 100644 --- a/internal/database/repo_test.go +++ b/internal/database/repo_test.go @@ -10,7 +10,7 @@ import ( "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/markup" - "gogs.io/gogs/internal/osutil" + "gogs.io/gogs/internal/osx" ) func TestRepository_ComposeMetas(t *testing.T) { @@ -81,5 +81,5 @@ func Test_CreateRepository_PreventDeletion(t *testing.T) { _, err = CreateRepository(owner, owner, opts) require.Error(t, err) assert.Contains(t, err.Error(), "repository directory already exists") - assert.True(t, osutil.Exist(canary)) + assert.True(t, osx.Exist(canary)) } diff --git a/internal/database/repositories.go b/internal/database/repositories.go index 8edb8e78a..37deb0e35 100644 --- a/internal/database/repositories.go +++ b/internal/database/repositories.go @@ -9,8 +9,8 @@ import ( "github.com/cockroachdb/errors" "gorm.io/gorm" - "gogs.io/gogs/internal/errutil" - "gogs.io/gogs/internal/repoutil" + "gogs.io/gogs/internal/errx" + "gogs.io/gogs/internal/repox" apiv1types "gogs.io/gogs/internal/route/api/v1/types" ) @@ -47,7 +47,7 @@ func (r *Repository) APIFormat(owner *User, opts ...RepositoryAPIFormatOptions) opt = opts[0] } - cloneLink := repoutil.NewCloneLink(owner.Name, r.Name, false) + cloneLink := repox.NewCloneLink(owner.Name, r.Name, false) return &apiv1types.Repository{ ID: r.ID, Owner: owner.APIFormat(), @@ -60,7 +60,7 @@ func (r *Repository) APIFormat(owner *User, opts ...RepositoryAPIFormatOptions) Empty: r.IsBare, Mirror: r.IsMirror, Size: r.Size, - HTMLURL: repoutil.HTMLURL(owner.Name, r.Name), + HTMLURL: repox.HTMLURL(owner.Name, r.Name), SSHURL: cloneLink.SSH, CloneURL: cloneLink.HTTPS, Website: r.Website, @@ -85,7 +85,7 @@ func newReposStore(db *gorm.DB) *RepositoriesStore { } type ErrRepoAlreadyExist struct { - args errutil.Args + args errx.Args } 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) if err == nil { return nil, ErrRepoAlreadyExist{ - args: errutil.Args{ + args: errx.Args{ "ownerID": ownerID, "name": opts.Name, }, @@ -221,10 +221,10 @@ func (s *RepositoriesStore) GetByCollaboratorIDWithAccessMode(ctx context.Contex return repos, nil } -var _ errutil.NotFound = (*ErrRepoNotExist)(nil) +var _ errx.NotFound = (*ErrRepoNotExist)(nil) type ErrRepoNotExist struct { - args errutil.Args + args errx.Args } 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 if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { - return nil, ErrRepoNotExist{errutil.Args{"repoID": id}} + return nil, ErrRepoNotExist{errx.Args{"repoID": id}} } return nil, err } @@ -265,7 +265,7 @@ func (s *RepositoriesStore) GetByName(ctx context.Context, ownerID int64, name s if err != nil { if err == gorm.ErrRecordNotFound { return nil, ErrRepoNotExist{ - args: errutil.Args{ + args: errx.Args{ "ownerID": ownerID, "name": name, }, diff --git a/internal/database/repositories_test.go b/internal/database/repositories_test.go index 4b8583e91..3b98db8a0 100644 --- a/internal/database/repositories_test.go +++ b/internal/database/repositories_test.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/require" "gorm.io/gorm" - "gogs.io/gogs/internal/errutil" + "gogs.io/gogs/internal/errx" ) func TestRepository_BeforeCreate(t *testing.T) { @@ -121,7 +121,7 @@ func reposCreate(t *testing.T, ctx context.Context, s *RepositoriesStore) { Name: "my.git", }, ) - wantErr := ErrNameNotAllowed{args: errutil.Args{"reason": "reserved", "pattern": "*.git"}} + wantErr := ErrNameNotAllowed{args: errx.Args{"reason": "reserved", "pattern": "*.git"}} assert.Equal(t, wantErr, err) }) @@ -138,7 +138,7 @@ func reposCreate(t *testing.T, ctx context.Context, s *RepositoriesStore) { Name: "repo1", }, ) - wantErr := ErrRepoAlreadyExist{args: errutil.Args{"ownerID": int64(2), "name": "repo1"}} + wantErr := ErrRepoAlreadyExist{args: errx.Args{"ownerID": int64(2), "name": "repo1"}} 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) _, err = s.GetByID(ctx, 404) - wantErr := ErrRepoNotExist{args: errutil.Args{"repoID": int64(404)}} + wantErr := ErrRepoNotExist{args: errx.Args{"repoID": int64(404)}} assert.Equal(t, wantErr, err) } @@ -234,7 +234,7 @@ func reposGetByName(t *testing.T, ctx context.Context, s *RepositoriesStore) { require.NoError(t, err) _, err = s.GetByName(ctx, 1, "bad_name") - wantErr := ErrRepoNotExist{args: errutil.Args{"ownerID": int64(1), "name": "bad_name"}} + wantErr := ErrRepoNotExist{args: errx.Args{"ownerID": int64(1), "name": "bad_name"}} assert.Equal(t, wantErr, err) } diff --git a/internal/database/ssh_key.go b/internal/database/ssh_key.go index 81fa514c4..de051c2f9 100644 --- a/internal/database/ssh_key.go +++ b/internal/database/ssh_key.go @@ -20,8 +20,8 @@ import ( "xorm.io/xorm" "gogs.io/gogs/internal/conf" - "gogs.io/gogs/internal/errutil" - "gogs.io/gogs/internal/osutil" + "gogs.io/gogs/internal/errx" + "gogs.io/gogs/internal/osx" "gogs.io/gogs/internal/process" ) @@ -542,7 +542,7 @@ func RewriteAuthorizedKeys() error { return err } - if osutil.Exist(fpath) { + if osx.Exist(fpath) { if err = os.Remove(fpath); err != nil { return err } @@ -685,7 +685,7 @@ func AddDeployKey(repoID int64, name, content string) (*DeployKey, error) { return key, sess.Commit() } -var _ errutil.NotFound = (*ErrDeployKeyNotExist)(nil) +var _ errx.NotFound = (*ErrDeployKeyNotExist)(nil) type ErrDeployKeyNotExist struct { args map[string]any diff --git a/internal/database/two_factor.go b/internal/database/two_factor.go index 95fc93306..9e5b716e7 100644 --- a/internal/database/two_factor.go +++ b/internal/database/two_factor.go @@ -9,7 +9,7 @@ import ( "github.com/pquerna/otp/totp" "gogs.io/gogs/internal/conf" - "gogs.io/gogs/internal/cryptoutil" + "gogs.io/gogs/internal/cryptox" ) // TwoFactor is a 2FA token of a user. @@ -28,7 +28,7 @@ func (t *TwoFactor) ValidateTOTP(passcode string) (bool, error) { if err != nil { return false, errors.Newf("DecodeString: %v", err) } - decryptSecret, err := cryptoutil.AESGCMDecrypt(cryptoutil.MD5Bytes(conf.Security.SecretKey), secret) + decryptSecret, err := cryptox.AESGCMDecrypt(cryptox.MD5Bytes(conf.Security.SecretKey), secret) if err != nil { return false, errors.Newf("AESGCMDecrypt: %v", err) } diff --git a/internal/database/two_factors.go b/internal/database/two_factors.go index d95354267..c38cbcd1c 100644 --- a/internal/database/two_factors.go +++ b/internal/database/two_factors.go @@ -11,9 +11,9 @@ import ( "gorm.io/gorm" log "unknwon.dev/clog/v2" - "gogs.io/gogs/internal/cryptoutil" - "gogs.io/gogs/internal/errutil" - "gogs.io/gogs/internal/strutil" + "gogs.io/gogs/internal/cryptox" + "gogs.io/gogs/internal/errx" + "gogs.io/gogs/internal/strx" ) // 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 // tokens. func (s *TwoFactorsStore) Create(ctx context.Context, userID int64, key, secret string) error { - encrypted, err := cryptoutil.AESGCMEncrypt(cryptoutil.MD5Bytes(key), []byte(secret)) + encrypted, err := cryptox.AESGCMEncrypt(cryptox.MD5Bytes(key), []byte(secret)) if err != nil { return errors.Wrap(err, "encrypt secret") } @@ -68,10 +68,10 @@ func (s *TwoFactorsStore) Create(ctx context.Context, userID int64, key, secret }) } -var _ errutil.NotFound = (*ErrTwoFactorNotFound)(nil) +var _ errx.NotFound = (*ErrTwoFactorNotFound)(nil) type ErrTwoFactorNotFound struct { - args errutil.Args + args errx.Args } 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 if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { - return nil, ErrTwoFactorNotFound{args: errutil.Args{"userID": userID}} + return nil, ErrTwoFactorNotFound{args: errx.Args{"userID": userID}} } 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) { recoveryCodes := make([]*TwoFactorRecoveryCode, n) for i := range n { - code, err := strutil.RandomChars(10) + code, err := strx.RandomChars(10) if err != nil { return nil, errors.Wrap(err, "generate random characters") } diff --git a/internal/database/two_factors_test.go b/internal/database/two_factors_test.go index 88db77e14..745f073e6 100644 --- a/internal/database/two_factors_test.go +++ b/internal/database/two_factors_test.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/require" "gorm.io/gorm" - "gogs.io/gogs/internal/errutil" + "gogs.io/gogs/internal/errx" ) 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 _, err = s.GetByUserID(ctx, 2) - wantErr := ErrTwoFactorNotFound{args: errutil.Args{"userID": int64(2)}} + wantErr := ErrTwoFactorNotFound{args: errx.Args{"userID": int64(2)}} assert.Equal(t, wantErr, err) } diff --git a/internal/database/users.go b/internal/database/users.go index 11cb3ed97..59e40edc2 100644 --- a/internal/database/users.go +++ b/internal/database/users.go @@ -16,16 +16,16 @@ import ( "gogs.io/gogs/internal/auth" "gogs.io/gogs/internal/conf" - "gogs.io/gogs/internal/cryptoutil" - "gogs.io/gogs/internal/dbutil" - "gogs.io/gogs/internal/errutil" + "gogs.io/gogs/internal/cryptox" + "gogs.io/gogs/internal/dbx" + "gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/markup" - "gogs.io/gogs/internal/osutil" - "gogs.io/gogs/internal/repoutil" + "gogs.io/gogs/internal/osx" + "gogs.io/gogs/internal/repox" apiv1types "gogs.io/gogs/internal/route/api/v1/types" - "gogs.io/gogs/internal/strutil" + "gogs.io/gogs/internal/strx" "gogs.io/gogs/internal/tool" - "gogs.io/gogs/internal/userutil" + "gogs.io/gogs/internal/userx" ) // UsersStore is the storage layer for users. @@ -38,7 +38,7 @@ func newUsersStore(db *gorm.DB) *UsersStore { } type ErrLoginSourceMismatch struct { - args errutil.Args + args errx.Args } // 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 // and make it more consistent from user's perspective. if loginSourceID >= 0 && user.LoginSource != loginSourceID { - return nil, ErrLoginSourceMismatch{args: errutil.Args{"expect": loginSourceID, "actual": user.LoginSource}} + return nil, ErrLoginSourceMismatch{args: errx.Args{"expect": loginSourceID, "actual": user.LoginSource}} } // Validate password hash fetched from database for local accounts. if user.IsLocal() { - if userutil.ValidatePassword(user.Password, user.Salt, password) { + if userx.ValidatePassword(user.Password, user.Salt, password) { return user, nil } @@ -158,7 +158,7 @@ func (s *UsersStore) ChangeUsername(ctx context.Context, userID int64, newUserna if s.IsUsernameUsed(ctx, newUsername, userID) { return ErrUserAlreadyExist{ - args: errutil.Args{ + args: errx.Args{ "name": newUsername, }, } @@ -212,16 +212,16 @@ func (s *UsersStore) ChangeUsername(ctx context.Context, userID int64, newUserna } deleteRepoLocalCopy(repo.ID) - RemoveAllWithNotice(fmt.Sprintf("Delete repository %d wiki local copy", repo.ID), repoutil.RepositoryLocalWikiPath(repo.ID)) + RemoveAllWithNotice(fmt.Sprintf("Delete repository %d wiki local copy", repo.ID), repox.RepositoryLocalWikiPath(repo.ID)) } if err = rows.Err(); err != nil { return errors.Wrap(err, "check rows.Err") } // Rename user directory if exists - userPath := repoutil.UserPath(user.Name) - if osutil.Exist(userPath) { - newUserPath := repoutil.UserPath(newUsername) + userPath := repox.UserPath(user.Name) + if osx.Exist(userPath) { + newUserPath := repox.UserPath(newUsername) err = os.Rename(userPath, newUserPath) if err != nil { return errors.Wrap(err, "rename user directory") @@ -250,7 +250,7 @@ type CreateUserOptions struct { } type ErrUserAlreadyExist struct { - args errutil.Args + args errx.Args } // IsErrUserAlreadyExist returns true if the underlying error has the type @@ -264,7 +264,7 @@ func (err ErrUserAlreadyExist) Error() string { } type ErrEmailAlreadyUsed struct { - args errutil.Args + args errx.Args } // 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) { return nil, ErrUserAlreadyExist{ - args: errutil.Args{ + args: errx.Args{ "name": username, }, } @@ -307,7 +307,7 @@ func (s *UsersStore) Create(ctx context.Context, username, email string, opts Cr _, err = s.GetByEmail(ctx, email) if err == nil { return nil, ErrEmailAlreadyUsed{ - args: errutil.Args{ + args: errx.Args{ "email": email, }, } @@ -328,19 +328,19 @@ func (s *UsersStore) Create(ctx context.Context, username, email string, opts Cr MaxRepoCreation: -1, IsActive: opts.Activated, IsAdmin: opts.Admin, - Avatar: cryptoutil.MD5(email), // Gravatar URL uses the MD5 hash of the email, see https://en.gravatar.com/site/implement/hash/ + Avatar: cryptox.MD5(email), // Gravatar URL uses the MD5 hash of the email, see https://en.gravatar.com/site/implement/hash/ AvatarEmail: email, } - user.Rands, err = userutil.RandomSalt() + user.Rands, err = userx.RandomSalt() if err != nil { return nil, err } - user.Salt, err = userutil.RandomSalt() + user.Salt, err = userx.RandomSalt() if err != nil { return nil, err } - user.Password = userutil.EncodePassword(user.Password, user.Salt) + user.Password = userx.EncodePassword(user.Password, user.Salt) 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 // use look up avatar by email. func (s *UsersStore) DeleteCustomAvatar(ctx context.Context, userID int64) error { - _ = os.Remove(userutil.CustomAvatarPath(userID)) + _ = os.Remove(userx.CustomAvatarPath(userID)) return s.db.WithContext(ctx). Model(&User{}). Where("id = ?", userID). @@ -360,7 +360,7 @@ func (s *UsersStore) DeleteCustomAvatar(ctx context.Context, userID int64) error } type ErrUserOwnRepos struct { - args errutil.Args + args errx.Args } // IsErrUserOwnRepos returns true if the underlying error has the type @@ -374,7 +374,7 @@ func (err ErrUserOwnRepos) Error() string { } type ErrUserHasOrgs struct { - args errutil.Args + args errx.Args } // 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 { return errors.Wrap(err, "count repositories") } else if count > 0 { - return ErrUserOwnRepos{args: errutil.Args{"userID": userID}} + return ErrUserOwnRepos{args: errx.Args{"userID": userID}} } err = s.db.WithContext(ctx).Model(&OrgUser{}).Where("uid = ?", userID).Count(&count).Error if err != nil { return errors.Wrap(err, "count organization membership") } else if count > 0 { - return ErrUserHasOrgs{args: errutil.Args{"userID": userID}} + return ErrUserHasOrgs{args: errx.Args{"userID": userID}} } needsRewriteAuthorizedKeys := false @@ -542,8 +542,8 @@ func (s *UsersStore) DeleteByID(ctx context.Context, userID int64, skipRewriteAu return err } - _ = os.RemoveAll(repoutil.UserPath(user.Name)) - _ = os.Remove(userutil.CustomAvatarPath(userID)) + _ = os.RemoveAll(repox.UserPath(user.Name)) + _ = os.Remove(userx.CustomAvatarPath(userID)) if needsRewriteAuthorizedKeys { 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 } -var _ errutil.NotFound = (*ErrUserNotExist)(nil) +var _ errx.NotFound = (*ErrUserNotExist)(nil) type ErrUserNotExist struct { - args errutil.Args + args errx.Args } // 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. func (s *UsersStore) GetByEmail(ctx context.Context, email string) (*User, error) { if email == "" { - return nil, ErrUserNotExist{args: errutil.Args{"email": email}} + return nil, ErrUserNotExist{args: errx.Args{"email": email}} } email = strings.ToLower(email) @@ -710,17 +710,17 @@ func (s *UsersStore) GetByEmail(ctx context.Context, email string) (*User, error */ user := new(User) err := s.db.WithContext(ctx). - Joins(dbutil.Quote("LEFT JOIN email_address ON email_address.uid = %s.id", "user"), true). - Where(dbutil.Quote("%s.type = ?", "user"), UserTypeIndividual). + Joins(dbx.Quote("LEFT JOIN email_address ON email_address.uid = %s.id", "user"), true). + Where(dbx.Quote("%s.type = ?", "user"), UserTypeIndividual). Where(s.db. - Where(dbutil.Quote("%[1]s.email = ? AND %[1]s.is_active = ?", "user"), email, true). + Where(dbx.Quote("%[1]s.email = ? AND %[1]s.is_active = ?", "user"), email, true). Or("email_address.email = ? AND email_address.is_activated = ?", email, true), ). First(&user). Error if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { - return nil, ErrUserNotExist{args: errutil.Args{"email": email}} + return nil, ErrUserNotExist{args: errx.Args{"email": email}} } 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 if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { - return nil, ErrUserNotExist{args: errutil.Args{"userID": id}} + return nil, ErrUserNotExist{args: errx.Args{"userID": id}} } 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 if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { - return nil, ErrUserNotExist{args: errutil.Args{"name": username}} + return nil, ErrUserNotExist{args: errx.Args{"name": username}} } 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) { user := new(User) err := s.db.WithContext(ctx). - Joins(dbutil.Quote("JOIN public_key ON public_key.owner_id = %s.id", "user")). + Joins(dbx.Quote("JOIN public_key ON public_key.owner_id = %s.id", "user")). Where("public_key.id = ?", keyID). First(user). Error if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { - return nil, ErrUserNotExist{args: errutil.Args{"keyID": keyID}} + return nil, ErrUserNotExist{args: errx.Args{"keyID": keyID}} } return nil, err } @@ -826,7 +826,7 @@ func (s *UsersStore) ListFollowers(ctx context.Context, userID int64, page, page */ users := make([]*User, 0, pageSize) return users, s.db.WithContext(ctx). - Joins(dbutil.Quote("LEFT JOIN follow ON follow.user_id = %s.id", "user")). + Joins(dbx.Quote("LEFT JOIN follow ON follow.user_id = %s.id", "user")). Where("follow.follow_id = ?", userID). Limit(pageSize).Offset((page - 1) * pageSize). Order("follow.id DESC"). @@ -849,7 +849,7 @@ func (s *UsersStore) ListFollowings(ctx context.Context, userID int64, page, pag */ users := make([]*User, 0, pageSize) return users, s.db.WithContext(ctx). - Joins(dbutil.Quote("LEFT JOIN follow ON follow.follow_id = %s.id", "user")). + Joins(dbx.Quote("LEFT JOIN follow ON follow.follow_id = %s.id", "user")). Where("follow.user_id = ?", userID). Limit(pageSize).Offset((page - 1) * pageSize). Order("follow.id DESC"). @@ -926,16 +926,16 @@ func (s *UsersStore) Update(ctx context.Context, userID int64, opts UpdateUserOp } if opts.Password != nil { - salt, err := userutil.RandomSalt() + salt, err := userx.RandomSalt() if err != nil { return errors.Wrap(err, "generate salt") } updates["salt"] = salt - updates["passwd"] = userutil.EncodePassword(*opts.Password, salt) + updates["passwd"] = userx.EncodePassword(*opts.Password, salt) opts.GenerateNewRands = true } if opts.GenerateNewRands { - rands, err := userutil.RandomSalt() + rands, err := userx.RandomSalt() if err != nil { 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 { - updates["full_name"] = strutil.Truncate(*opts.FullName, 255) + updates["full_name"] = strx.Truncate(*opts.FullName, 255) } if opts.Email != nil { _, err := s.GetByEmail(ctx, *opts.Email) if err == nil { - return ErrEmailAlreadyUsed{args: errutil.Args{"email": *opts.Email}} + return ErrEmailAlreadyUsed{args: errx.Args{"email": *opts.Email}} } else if !IsErrUserNotExist(err) { return errors.Wrap(err, "check email") } updates["email"] = *opts.Email } if opts.Website != nil { - updates["website"] = strutil.Truncate(*opts.Website, 255) + updates["website"] = strx.Truncate(*opts.Website, 255) } if opts.Location != nil { - updates["location"] = strutil.Truncate(*opts.Location, 255) + updates["location"] = strx.Truncate(*opts.Location, 255) } if opts.Description != nil { - updates["description"] = strutil.Truncate(*opts.Description, 255) + updates["description"] = strx.Truncate(*opts.Description, 255) } if opts.MaxRepoCreation != nil { @@ -991,10 +991,10 @@ func (s *UsersStore) Update(ctx context.Context, userID int64, opts UpdateUserOp } if opts.Avatar != nil { - updates["avatar"] = strutil.Truncate(*opts.Avatar, 2048) + updates["avatar"] = strx.Truncate(*opts.Avatar, 2048) } if opts.AvatarEmail != nil { - updates["avatar_email"] = strutil.Truncate(*opts.AvatarEmail, 255) + updates["avatar_email"] = strx.Truncate(*opts.AvatarEmail, 255) } 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. func (s *UsersStore) UseCustomAvatar(ctx context.Context, userID int64, avatar []byte) error { - err := userutil.SaveAvatar(userID, avatar) + err := userx.SaveAvatar(userID, avatar) if err != nil { 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) if err == nil { return ErrEmailAlreadyUsed{ - args: errutil.Args{ + args: errx.Args{ "email": email, }, } @@ -1041,10 +1041,10 @@ func (s *UsersStore) AddEmail(ctx context.Context, userID int64, email string, i ).Error } -var _ errutil.NotFound = (*ErrEmailNotExist)(nil) +var _ errx.NotFound = (*ErrEmailNotExist)(nil) type ErrEmailNotExist struct { - args errutil.Args + args errx.Args } // 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 errors.Is(err, gorm.ErrRecordNotFound) { return nil, ErrEmailNotExist{ - args: errutil.Args{ + args: errx.Args{ "email": email, }, } @@ -1140,7 +1140,7 @@ func (s *UsersStore) MarkEmailActivated(ctx context.Context, userID int64, email } type ErrEmailNotVerified struct { - args errutil.Args + args errx.Args } // 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 if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { - return ErrEmailNotExist{args: errutil.Args{"email": email}} + return ErrEmailNotExist{args: errx.Args{"email": email}} } return errors.Wrap(err, "get email address") } if !emailAddress.IsActivated { - return ErrEmailNotVerified{args: errutil.Args{"email": email}} + return ErrEmailNotVerified{args: errx.Args{"email": email}} } 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. // // TODO(unknwon): This is also used in templates, which should be fixed by -// having a dedicated type `template.User` and move this to the "userutil" +// having a dedicated type `template.User` and move this to the "userx" // package. func (u *User) HomeURLPath() string { 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. // // TODO(unknwon): This is also used in templates, which should be fixed by -// having a dedicated type `template.User` and move this to the "userutil" +// having a dedicated type `template.User` and move this to the "userx" // package. func (u *User) HTMLURL() string { 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. // // TODO(unknwon): This is also used in templates, which should be fixed by -// having a dedicated type `template.User` and move this to the "userutil" +// having a dedicated type `template.User` and move this to the "userx" // package. func (u *User) AvatarURLPath() string { defaultURLPath := conf.UserDefaultAvatarURLPath() @@ -1376,7 +1376,7 @@ func (u *User) AvatarURLPath() string { return defaultURLPath } - hasCustomAvatar := osutil.IsFile(userutil.CustomAvatarPath(u.ID)) + hasCustomAvatar := osx.IsFile(userx.CustomAvatarPath(u.ID)) switch { case u.UseCustomAvatar: if !hasCustomAvatar { @@ -1385,7 +1385,7 @@ func (u *User) AvatarURLPath() string { return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, conf.UsersAvatarPathPrefix, u.ID) case conf.Picture.DisableGravatar: if !hasCustomAvatar { - if err := userutil.GenerateRandomAvatar(u.ID, u.Name, u.Email); err != nil { + if err := userx.GenerateRandomAvatar(u.ID, u.Name, u.Email); err != nil { 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. // // TODO(unknwon): This is also used in templates, which should be fixed by -// having a dedicated type `template.User` and move this to the "userutil" +// having a dedicated type `template.User` and move this to the "userx" // package. func (u *User) AvatarURL() string { 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 // having a dedicated type `template.User`. func (u *User) ShortName(length int) string { - return strutil.Ellipsis(u.Name, length) + return strx.Ellipsis(u.Name, length) } // NewGhostUser creates and returns a fake user for people who has deleted their @@ -1498,7 +1498,7 @@ var ( ) type ErrNameNotAllowed struct { - args errutil.Args + args errx.Args } // 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)) if utf8.RuneCountInString(name) == 0 { return ErrNameNotAllowed{ - args: errutil.Args{ + args: errx.Args{ "reason": "empty name", }, } @@ -1541,7 +1541,7 @@ func isNameAllowed(names map[string]struct{}, patterns []string, name string) er if _, ok := names[name]; ok { return ErrNameNotAllowed{ - args: errutil.Args{ + args: errx.Args{ "reason": "reserved", "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:]) || (pattern[len(pattern)-1] == '*' && strings.HasPrefix(name, pattern[:len(pattern)-1])) { return ErrNameNotAllowed{ - args: errutil.Args{ + args: errx.Args{ "reason": "reserved", "pattern": pattern, }, diff --git a/internal/database/users_test.go b/internal/database/users_test.go index b66a9d440..99dfc3479 100644 --- a/internal/database/users_test.go +++ b/internal/database/users_test.go @@ -15,11 +15,11 @@ import ( "gogs.io/gogs/internal/auth" "gogs.io/gogs/internal/conf" - "gogs.io/gogs/internal/dbutil" - "gogs.io/gogs/internal/errutil" - "gogs.io/gogs/internal/osutil" - "gogs.io/gogs/internal/repoutil" - "gogs.io/gogs/internal/userutil" + "gogs.io/gogs/internal/dbx" + "gogs.io/gogs/internal/errx" + "gogs.io/gogs/internal/osx" + "gogs.io/gogs/internal/repox" + "gogs.io/gogs/internal/userx" "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) { err := s.ChangeUsername(ctx, alice.ID, "-") wantErr := ErrNameNotAllowed{ - args: errutil.Args{ + args: errx.Args{ "reason": "reserved", "name": "-", }, @@ -261,7 +261,7 @@ func usersChangeUsername(t *testing.T, ctx context.Context, s *UsersStore) { err = s.ChangeUsername(ctx, alice.ID, bob.Name) wantErr := ErrUserAlreadyExist{ - args: errutil.Args{ + args: errx.Args{ "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 require.NoError(t, err) - err = os.MkdirAll(repoutil.UserPath(alice.Name), os.ModePerm) + err = os.MkdirAll(repox.UserPath(alice.Name), os.ModePerm) require.NoError(t, err) - err = os.MkdirAll(repoutil.RepositoryLocalPath(repo.ID), os.ModePerm) + err = os.MkdirAll(repox.RepositoryLocalPath(repo.ID), os.ModePerm) require.NoError(t, err) - err = os.MkdirAll(repoutil.RepositoryLocalWikiPath(repo.ID), os.ModePerm) + err = os.MkdirAll(repox.RepositoryLocalWikiPath(repo.ID), os.ModePerm) require.NoError(t, err) // 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) assert.Equal(t, int64(0), updatedUnix) - assert.True(t, osutil.Exist(repoutil.UserPath(alice.Name))) - assert.True(t, osutil.Exist(repoutil.RepositoryLocalPath(repo.ID))) - assert.True(t, osutil.Exist(repoutil.RepositoryLocalWikiPath(repo.ID))) + assert.True(t, osx.Exist(repox.UserPath(alice.Name))) + assert.True(t, osx.Exist(repox.RepositoryLocalPath(repo.ID))) + assert.True(t, osx.Exist(repox.RepositoryLocalWikiPath(repo.ID))) const newUsername = "alice-new" 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) assert.Equal(t, headUserName, newUsername) - assert.True(t, osutil.Exist(repoutil.UserPath(newUsername))) - assert.False(t, osutil.Exist(repoutil.UserPath(alice.Name))) - assert.False(t, osutil.Exist(repoutil.RepositoryLocalPath(repo.ID))) - assert.False(t, osutil.Exist(repoutil.RepositoryLocalWikiPath(repo.ID))) + assert.True(t, osx.Exist(repox.UserPath(newUsername))) + assert.False(t, osx.Exist(repox.UserPath(alice.Name))) + assert.False(t, osx.Exist(repox.RepositoryLocalPath(repo.ID))) + assert.False(t, osx.Exist(repox.RepositoryLocalWikiPath(repo.ID))) alice, err = s.GetByID(ctx, alice.ID) 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{}) require.NoError(t, err) err = s.db.Exec( - dbutil.Quote("UPDATE %s SET type = ? WHERE id = ?", "user"), + dbx.Quote("UPDATE %s SET type = ? WHERE id = ?", "user"), UserTypeOrganization, org1.ID, ).Error 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) { _, err := s.Create(ctx, "-", "", CreateUserOptions{}) wantErr := ErrNameNotAllowed{ - args: errutil.Args{ + args: errx.Args{ "reason": "reserved", "name": "-", }, @@ -404,7 +404,7 @@ func usersCreate(t *testing.T, ctx context.Context, s *UsersStore) { t.Run("name already exists", func(t *testing.T) { _, err := s.Create(ctx, alice.Name, "", CreateUserOptions{}) wantErr := ErrUserAlreadyExist{ - args: errutil.Args{ + args: errx.Args{ "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) { _, err := s.Create(ctx, "bob", alice.Email, CreateUserOptions{}) wantErr := ErrEmailAlreadyUsed{ - args: errutil.Args{ + args: errx.Args{ "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") require.NoError(t, err) - avatarPath := userutil.CustomAvatarPath(alice.ID) + avatarPath := userx.CustomAvatarPath(alice.ID) _ = 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) // Make sure avatar is saved and the user flag is updated. - got := osutil.IsFile(avatarPath) + got := osx.IsFile(avatarPath) assert.True(t, got) 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) require.NoError(t, err) - got = osutil.IsFile(avatarPath) + got = osx.IsFile(avatarPath) assert.False(t, got) 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) err = s.DeleteByID(ctx, alice.ID, false) - wantErr := ErrUserOwnRepos{errutil.Args{"userID": alice.ID}} + wantErr := ErrUserOwnRepos{errx.Args{"userID": alice.ID}} 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{}) require.NoError(t, err) err = s.db.Exec( - dbutil.Quote("UPDATE %s SET type = ? WHERE id IN (?)", "user"), + dbx.Quote("UPDATE %s SET type = ? WHERE id IN (?)", "user"), UserTypeOrganization, org1.ID, ).Error require.NoError(t, err) @@ -494,7 +494,7 @@ func usersDeleteByID(t *testing.T, ctx context.Context, s *UsersStore) { require.NoError(t, err) err = s.DeleteByID(ctx, bob.ID, false) - wantErr := ErrUserHasOrgs{errutil.Args{"userID": bob.ID}} + wantErr := ErrUserHasOrgs{errx.Args{"userID": bob.ID}} assert.Equal(t, wantErr, err) }) @@ -561,7 +561,7 @@ func usersDeleteByID(t *testing.T, ctx context.Context, s *UsersStore) { // Mock user directory tempRepositoryRoot := filepath.Join(os.TempDir(), "usersDeleteByID-tempRepositoryRoot") conf.SetMockRepository(t, conf.RepositoryOpts{Root: tempRepositoryRoot}) - tempUserPath := repoutil.UserPath(testUser.Name) + tempUserPath := repox.UserPath(testUser.Name) err = os.MkdirAll(tempUserPath, os.ModePerm) 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}) err = os.MkdirAll(tempPictureAvatarUploadPath, os.ModePerm) require.NoError(t, err) - tempCustomAvatarPath := userutil.CustomAvatarPath(testUser.ID) + tempCustomAvatarPath := userx.CustomAvatarPath(testUser.ID) err = os.WriteFile(tempCustomAvatarPath, []byte("test"), 0o600) 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.True(t, osutil.Exist(tempUserPath)) - assert.True(t, osutil.Exist(tempCustomAvatarPath)) + assert.True(t, osx.Exist(tempUserPath)) + assert.True(t, osx.Exist(tempCustomAvatarPath)) // Pull the trigger 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.False(t, osutil.Exist(tempUserPath)) - assert.False(t, osutil.Exist(tempCustomAvatarPath)) + assert.False(t, osx.Exist(tempUserPath)) + assert.False(t, osx.Exist(tempCustomAvatarPath)) _, err = s.GetByID(ctx, testUser.ID) - wantErr := ErrUserNotExist{errutil.Args{"userID": testUser.ID}} + wantErr := ErrUserNotExist{errx.Args{"userID": testUser.ID}} 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{}) require.NoError(t, err) err = s.db.Exec( - dbutil.Quote("UPDATE %s SET type = ? WHERE id IN (?)", "user"), + dbx.Quote("UPDATE %s SET type = ? WHERE id IN (?)", "user"), UserTypeOrganization, org1.ID, ).Error require.NoError(t, err) @@ -709,7 +709,7 @@ func usersDeleteInactivated(t *testing.T, ctx context.Context, s *UsersStore) { require.NoError(t, err) _, err = s.GetByID(ctx, david.ID) - wantErr := ErrUserNotExist{errutil.Args{"userID": david.ID}} + wantErr := ErrUserNotExist{errx.Args{"userID": david.ID}} assert.Equal(t, wantErr, err) 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) { t.Run("empty email", func(t *testing.T) { _, err := s.GetByEmail(ctx, "") - wantErr := ErrUserNotExist{args: errutil.Args{"email": ""}} + wantErr := ErrUserNotExist{args: errx.Args{"email": ""}} assert.Equal(t, wantErr, err) }) @@ -733,7 +733,7 @@ func usersGetByEmail(t *testing.T, ctx context.Context, s *UsersStore) { require.NoError(t, err) _, err = s.GetByEmail(ctx, org.Email) - wantErr := ErrUserNotExist{args: errutil.Args{"email": org.Email}} + wantErr := ErrUserNotExist{args: errx.Args{"email": org.Email}} assert.Equal(t, wantErr, err) }) @@ -742,7 +742,7 @@ func usersGetByEmail(t *testing.T, ctx context.Context, s *UsersStore) { require.NoError(t, err) _, err = s.GetByEmail(ctx, alice.Email) - wantErr := ErrUserNotExist{args: errutil.Args{"email": alice.Email}} + wantErr := ErrUserNotExist{args: errx.Args{"email": alice.Email}} assert.Equal(t, wantErr, err) // Mark user as activated @@ -765,7 +765,7 @@ func usersGetByEmail(t *testing.T, ctx context.Context, s *UsersStore) { require.NoError(t, err) _, err = s.GetByEmail(ctx, email2) - wantErr := ErrUserNotExist{args: errutil.Args{"email": email2}} + wantErr := ErrUserNotExist{args: errx.Args{"email": email2}} assert.Equal(t, wantErr, err) // 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) _, err = s.GetByID(ctx, 404) - wantErr := ErrUserNotExist{args: errutil.Args{"userID": int64(404)}} + wantErr := ErrUserNotExist{args: errx.Args{"userID": int64(404)}} 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) _, err = s.GetByUsername(ctx, "bad_username") - wantErr := ErrUserNotExist{args: errutil.Args{"name": "bad_username"}} + wantErr := ErrUserNotExist{args: errx.Args{"name": "bad_username"}} 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) _, err = s.GetByKeyID(ctx, publicKey.ID+1) - wantErr := ErrUserNotExist{args: errutil.Args{"keyID": publicKey.ID + 1}} + wantErr := ErrUserNotExist{args: errx.Args{"keyID": publicKey.ID + 1}} 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{}) require.NoError(t, err) err = s.db.Exec( - dbutil.Quote("UPDATE %s SET type = ? WHERE id = ?", "user"), + dbx.Quote("UPDATE %s SET type = ? WHERE id = ?", "user"), UserTypeOrganization, org1.ID, ).Error require.NoError(t, err) @@ -1046,7 +1046,7 @@ func usersUpdate(t *testing.T, ctx context.Context, s *UsersStore) { require.NoError(t, err) t.Run("update password", func(t *testing.T) { - got := userutil.ValidatePassword(alice.Password, alice.Salt, oldPassword) + got := userx.ValidatePassword(alice.Password, alice.Salt, oldPassword) require.True(t, got) newPassword := "NewPassword" @@ -1055,10 +1055,10 @@ func usersUpdate(t *testing.T, ctx context.Context, s *UsersStore) { alice, err = s.GetByID(ctx, alice.ID) require.NoError(t, err) - got = userutil.ValidatePassword(alice.Password, alice.Salt, oldPassword) + got = userx.ValidatePassword(alice.Password, alice.Salt, oldPassword) assert.False(t, got, "Old password should stop working") - got = userutil.ValidatePassword(alice.Password, alice.Salt, newPassword) + got = userx.ValidatePassword(alice.Password, alice.Salt, newPassword) 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) got := s.Update(ctx, alice.ID, UpdateUserOptions{Email: &bob.Email}) - want := ErrEmailAlreadyUsed{args: errutil.Args{"email": bob.Email}} + want := ErrEmailAlreadyUsed{args: errx.Args{"email": bob.Email}} 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") require.NoError(t, err) - avatarPath := userutil.CustomAvatarPath(alice.ID) + avatarPath := userx.CustomAvatarPath(alice.ID) _ = 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) // Make sure avatar is saved and the user flag is updated. - got := osutil.IsFile(avatarPath) + got := osx.IsFile(avatarPath) assert.True(t, got) 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}) require.NoError(t, err) got := s.AddEmail(ctx, bob.ID+1, "verified@example.com", true) - want := ErrEmailAlreadyUsed{args: errutil.Args{"email": "verified@example.com"}} + want := ErrEmailAlreadyUsed{args: errx.Args{"email": "verified@example.com"}} require.Equal(t, want, got) }) } @@ -1199,7 +1199,7 @@ func usersGetEmail(t *testing.T, ctx context.Context, s *UsersStore) { const testEmail = "alice@example.com" _, err := s.GetEmail(ctx, testUserID, testEmail, false) wantErr := ErrEmailNotExist{ - args: errutil.Args{ + args: errx.Args{ "email": testEmail, }, } @@ -1288,7 +1288,7 @@ func usersMarkEmailPrimary(t *testing.T, ctx context.Context, s *UsersStore) { // Should fail because email not verified gotError := s.MarkEmailPrimary(ctx, alice.ID, "alice2@example.com") - wantError := ErrEmailNotVerified{args: errutil.Args{"email": "alice2@example.com"}} + wantError := ErrEmailNotVerified{args: errx.Args{"email": "alice2@example.com"}} assert.Equal(t, wantError, gotError) // 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") require.NoError(t, err) _, got := s.GetEmail(ctx, alice.ID, "alice2@example.com", false) - want := ErrEmailNotExist{args: errutil.Args{"email": "alice2@example.com"}} + want := ErrEmailNotExist{args: errx.Args{"email": "alice2@example.com"}} require.Equal(t, want, got) } diff --git a/internal/database/webhook.go b/internal/database/webhook.go index f604f78b0..ccf9b6033 100644 --- a/internal/database/webhook.go +++ b/internal/database/webhook.go @@ -18,12 +18,12 @@ import ( "xorm.io/xorm" "gogs.io/gogs/internal/conf" - "gogs.io/gogs/internal/errutil" + "gogs.io/gogs/internal/errx" "gogs.io/gogs/internal/httplib" - "gogs.io/gogs/internal/netutil" + "gogs.io/gogs/internal/netx" apiv1types "gogs.io/gogs/internal/route/api/v1/types" "gogs.io/gogs/internal/sync" - "gogs.io/gogs/internal/testutil" + "gogs.io/gogs/internal/testx" ) var HookQueue = sync.NewUniqueQueue(1000) @@ -234,7 +234,7 @@ func CreateWebhook(w *Webhook) error { return err } -var _ errutil.NotFound = (*ErrWebhookNotExist)(nil) +var _ errx.NotFound = (*ErrWebhookNotExist)(nil) type ErrWebhookNotExist struct { args map[string]any @@ -517,7 +517,7 @@ func createHookTask(e Engine, t *HookTask) error { return err } -var _ errutil.NotFound = (*ErrHookTaskNotExist)(nil) +var _ errx.NotFound = (*ErrHookTaskNotExist)(nil) type ErrHookTaskNotExist struct { 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 { // NOTE: To prevent too many cascading changes in a single refactoring PR, we // choose to ignore this function in tests. - if x == nil && testutil.InTest { + if x == nil && testx.InTest { return nil } 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) return } - if netutil.IsBlockedLocalHostname(payloadURL.Hostname(), conf.Security.LocalNetworkAllowlist) { + if netx.IsBlockedLocalHostname(payloadURL.Hostname(), conf.Security.LocalNetworkAllowlist) { t.ResponseContent = `{"body": "Payload URL resolved to a local network address that is implicitly blocked."}` return } diff --git a/internal/database/wiki.go b/internal/database/wiki.go index 428585d76..a050e4a40 100644 --- a/internal/database/wiki.go +++ b/internal/database/wiki.go @@ -14,9 +14,9 @@ import ( "github.com/gogs/git-module" "gogs.io/gogs/internal/conf" - "gogs.io/gogs/internal/osutil" - "gogs.io/gogs/internal/pathutil" - "gogs.io/gogs/internal/repoutil" + "gogs.io/gogs/internal/osx" + "gogs.io/gogs/internal/pathx" + "gogs.io/gogs/internal/repox" "gogs.io/gogs/internal/sync" ) @@ -40,20 +40,20 @@ func ToWikiPageURL(name string) string { // single-level hierarchy by replacing all "/" with spaces. func ToWikiPageName(urlString string) string { name, _ := url.QueryUnescape(urlString) - name = pathutil.Clean(name) + name = pathx.Clean(name) return strings.ReplaceAll(name, "/", " ") } // WikiCloneLink returns clone URLs of repository wiki. // -// Deprecated: Use repoutil.NewCloneLink instead. -func (r *Repository) WikiCloneLink() (cl *repoutil.CloneLink) { +// Deprecated: Use repox.NewCloneLink instead. +func (r *Repository) WikiCloneLink() (cl *repox.CloneLink) { return r.cloneLink(true) } // WikiPath returns wiki data path by given user and repository name. func WikiPath(userName, repoName string) string { - return filepath.Join(repoutil.UserPath(userName), strings.ToLower(repoName)+".wiki.git") + return filepath.Join(repox.UserPath(userName), strings.ToLower(repoName)+".wiki.git") } func (r *Repository) WikiPath() string { @@ -62,7 +62,7 @@ func (r *Repository) WikiPath() string { // HasWiki returns true if repository has wiki. func (r *Repository) HasWiki() bool { - return osutil.IsDir(r.WikiPath()) + return osx.IsDir(r.WikiPath()) } // 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 isNew { - if osutil.Exist(filename) { + if osx.Exist(filename) { return ErrWikiAlreadyExist{filename} } } else { diff --git a/internal/dbtest/dbtest.go b/internal/dbtest/dbtest.go index 8bb2b05a7..481c316bb 100644 --- a/internal/dbtest/dbtest.go +++ b/internal/dbtest/dbtest.go @@ -13,7 +13,7 @@ import ( "gorm.io/gorm/schema" "gogs.io/gogs/internal/conf" - "gogs.io/gogs/internal/dbutil" + "gogs.io/gogs/internal/dbx" ) // 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"), } - dsn, err := dbutil.NewDSN(dbOpts) + dsn, err := dbx.NewDSN(dbOpts) require.NoError(t, err) 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"), } - dsn, err := dbutil.NewDSN(dbOpts) + dsn, err := dbx.NewDSN(dbOpts) require.NoError(t, err) 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) - db, err := dbutil.OpenDB( + db, err := dbx.OpenDB( dbOpts, &gorm.Config{ SkipDefaultTransaction: true, diff --git a/internal/dbutil/dsn.go b/internal/dbx/dsn.go similarity index 99% rename from internal/dbutil/dsn.go rename to internal/dbx/dsn.go index 32300875e..1f736f01c 100644 --- a/internal/dbutil/dsn.go +++ b/internal/dbx/dsn.go @@ -1,4 +1,4 @@ -package dbutil +package dbx import ( "fmt" diff --git a/internal/dbutil/dsn_test.go b/internal/dbx/dsn_test.go similarity index 99% rename from internal/dbutil/dsn_test.go rename to internal/dbx/dsn_test.go index e05a59981..01d80c0b0 100644 --- a/internal/dbutil/dsn_test.go +++ b/internal/dbx/dsn_test.go @@ -1,4 +1,4 @@ -package dbutil +package dbx import ( "fmt" diff --git a/internal/dbutil/logger.go b/internal/dbx/logger.go similarity index 93% rename from internal/dbutil/logger.go rename to internal/dbx/logger.go index 377029fec..867d15849 100644 --- a/internal/dbutil/logger.go +++ b/internal/dbx/logger.go @@ -1,4 +1,4 @@ -package dbutil +package dbx import ( "fmt" diff --git a/internal/dbutil/string.go b/internal/dbx/string.go similarity index 96% rename from internal/dbutil/string.go rename to internal/dbx/string.go index 72a93feb9..8be399a77 100644 --- a/internal/dbutil/string.go +++ b/internal/dbx/string.go @@ -1,4 +1,4 @@ -package dbutil +package dbx import ( "fmt" diff --git a/internal/dbutil/string_test.go b/internal/dbx/string_test.go similarity index 96% rename from internal/dbutil/string_test.go rename to internal/dbx/string_test.go index f49d5af2c..e15be4ce4 100644 --- a/internal/dbutil/string_test.go +++ b/internal/dbx/string_test.go @@ -1,4 +1,4 @@ -package dbutil +package dbx import ( "testing" diff --git a/internal/errutil/errutil.go b/internal/errx/errx.go similarity index 95% rename from internal/errutil/errutil.go rename to internal/errx/errx.go index 49d476309..30e984792 100644 --- a/internal/errutil/errutil.go +++ b/internal/errx/errx.go @@ -1,4 +1,4 @@ -package errutil +package errx // NotFound represents a not found error. type NotFound interface { diff --git a/internal/errutil/errutil_test.go b/internal/errx/errx_test.go similarity index 98% rename from internal/errutil/errutil_test.go rename to internal/errx/errx_test.go index 34e42f19c..721ba4684 100644 --- a/internal/errutil/errutil_test.go +++ b/internal/errx/errx_test.go @@ -1,4 +1,4 @@ -package errutil +package errx import ( "testing" diff --git a/internal/form/repo.go b/internal/form/repo.go index f0fffe3fd..4a82a5b89 100644 --- a/internal/form/repo.go +++ b/internal/form/repo.go @@ -9,8 +9,8 @@ import ( "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/database" - "gogs.io/gogs/internal/netutil" - "gogs.io/gogs/internal/osutil" + "gogs.io/gogs/internal/netx" + "gogs.io/gogs/internal/osx" ) // _______________________________________ _________.______________________ _______________.___. @@ -68,7 +68,7 @@ func (f MigrateRepo) ParseRemoteAddr(user *database.User) (string, error) { return "", database.ErrInvalidCloneAddr{IsURLError: true} } - if netutil.IsBlockedLocalHostname(u.Hostname(), conf.Security.LocalNetworkAllowlist) { + if netx.IsBlockedLocalHostname(u.Hostname(), conf.Security.LocalNetworkAllowlist) { return "", database.ErrInvalidCloneAddr{IsBlockedLocalAddress: true} } @@ -82,7 +82,7 @@ func (f MigrateRepo) ParseRemoteAddr(user *database.User) (string, error) { remoteAddr = u.String() } else if !user.CanImportLocal() { return "", database.ErrInvalidCloneAddr{IsPermissionDenied: true} - } else if !osutil.IsDir(remoteAddr) { + } else if !osx.IsDir(remoteAddr) { return "", database.ErrInvalidCloneAddr{IsInvalidPath: true} } diff --git a/internal/gitutil/diff.go b/internal/gitx/diff.go similarity index 99% rename from internal/gitutil/diff.go rename to internal/gitx/diff.go index e0ffcd79e..38f90b19c 100644 --- a/internal/gitutil/diff.go +++ b/internal/gitx/diff.go @@ -1,4 +1,4 @@ -package gitutil +package gitx import ( "bytes" diff --git a/internal/gitutil/diff_test.go b/internal/gitx/diff_test.go similarity index 98% rename from internal/gitutil/diff_test.go rename to internal/gitx/diff_test.go index 0661318f3..b07fd25a6 100644 --- a/internal/gitutil/diff_test.go +++ b/internal/gitx/diff_test.go @@ -1,4 +1,4 @@ -package gitutil +package gitx import ( "html/template" diff --git a/internal/gitutil/error.go b/internal/gitx/error.go similarity index 91% rename from internal/gitutil/error.go rename to internal/gitx/error.go index 566c50a65..cbef9a4bd 100644 --- a/internal/gitutil/error.go +++ b/internal/gitx/error.go @@ -1,13 +1,13 @@ -package gitutil +package gitx import ( "github.com/cockroachdb/errors" "github.com/gogs/git-module" - "gogs.io/gogs/internal/errutil" + "gogs.io/gogs/internal/errx" ) -var _ errutil.NotFound = (*Error)(nil) +var _ errx.NotFound = (*Error)(nil) // Error is a wrapper of a Git error, which handles not found. type Error struct { diff --git a/internal/gitutil/error_test.go b/internal/gitx/error_test.go similarity index 85% rename from internal/gitutil/error_test.go rename to internal/gitx/error_test.go index 73bfb874c..0019e4cb9 100644 --- a/internal/gitutil/error_test.go +++ b/internal/gitx/error_test.go @@ -1,4 +1,4 @@ -package gitutil +package gitx import ( "os" @@ -7,7 +7,7 @@ import ( "github.com/gogs/git-module" "github.com/stretchr/testify/assert" - "gogs.io/gogs/internal/errutil" + "gogs.io/gogs/internal/errx" ) func TestError_NotFound(t *testing.T) { @@ -21,7 +21,7 @@ func TestError_NotFound(t *testing.T) { } for _, test := range tests { t.Run("", func(t *testing.T) { - assert.Equal(t, test.expVal, errutil.IsNotFound(NewError(test.err))) + assert.Equal(t, test.expVal, errx.IsNotFound(NewError(test.err))) }) } } diff --git a/internal/gitutil/mocks.go b/internal/gitx/mocks.go similarity index 99% rename from internal/gitutil/mocks.go rename to internal/gitx/mocks.go index 11ae61716..adefb9801 100644 --- a/internal/gitutil/mocks.go +++ b/internal/gitx/mocks.go @@ -1,4 +1,4 @@ -package gitutil +package gitx import ( "testing" diff --git a/internal/gitutil/module.go b/internal/gitx/module.go similarity index 99% rename from internal/gitutil/module.go rename to internal/gitx/module.go index 1af7566f3..0f0e7cf1b 100644 --- a/internal/gitutil/module.go +++ b/internal/gitx/module.go @@ -1,4 +1,4 @@ -package gitutil +package gitx import ( "github.com/gogs/git-module" diff --git a/internal/gitutil/pull_request.go b/internal/gitx/pull_request.go similarity index 99% rename from internal/gitutil/pull_request.go rename to internal/gitx/pull_request.go index 90d8b3d49..bcd1b8c9d 100644 --- a/internal/gitutil/pull_request.go +++ b/internal/gitx/pull_request.go @@ -1,4 +1,4 @@ -package gitutil +package gitx import ( "strconv" diff --git a/internal/gitutil/pull_request_test.go b/internal/gitx/pull_request_test.go similarity index 99% rename from internal/gitutil/pull_request_test.go rename to internal/gitx/pull_request_test.go index 743107b3d..ca3b125e3 100644 --- a/internal/gitutil/pull_request_test.go +++ b/internal/gitx/pull_request_test.go @@ -1,4 +1,4 @@ -package gitutil +package gitx import ( "testing" diff --git a/internal/gitutil/submodule.go b/internal/gitx/submodule.go similarity index 98% rename from internal/gitutil/submodule.go rename to internal/gitx/submodule.go index 501d5647b..6ef264637 100644 --- a/internal/gitutil/submodule.go +++ b/internal/gitx/submodule.go @@ -1,4 +1,4 @@ -package gitutil +package gitx import ( "fmt" diff --git a/internal/gitutil/submodule_test.go b/internal/gitx/submodule_test.go similarity index 99% rename from internal/gitutil/submodule_test.go rename to internal/gitx/submodule_test.go index 93ae35176..c225b3dea 100644 --- a/internal/gitutil/submodule_test.go +++ b/internal/gitx/submodule_test.go @@ -1,4 +1,4 @@ -package gitutil +package gitx import ( "testing" diff --git a/internal/gitutil/tag.go b/internal/gitx/tag.go similarity index 99% rename from internal/gitutil/tag.go rename to internal/gitx/tag.go index d55d48e75..e4bb6f2a7 100644 --- a/internal/gitutil/tag.go +++ b/internal/gitx/tag.go @@ -1,4 +1,4 @@ -package gitutil +package gitx import ( "github.com/cockroachdb/errors" diff --git a/internal/gitutil/tag_test.go b/internal/gitx/tag_test.go similarity index 99% rename from internal/gitutil/tag_test.go rename to internal/gitx/tag_test.go index 4e97e48b4..a69c1da6f 100644 --- a/internal/gitutil/tag_test.go +++ b/internal/gitx/tag_test.go @@ -1,4 +1,4 @@ -package gitutil +package gitx import ( "testing" diff --git a/internal/ioutil/ioutil.go b/internal/iox/iox.go similarity index 98% rename from internal/ioutil/ioutil.go rename to internal/iox/iox.go index 3876fc776..c8603d504 100644 --- a/internal/ioutil/ioutil.go +++ b/internal/iox/iox.go @@ -1,4 +1,4 @@ -package ioutil +package iox import ( "io" diff --git a/internal/lazyregexp/lazyre.go b/internal/lazyregexp/lazyre.go index e4c9f7ead..923acf93f 100644 --- a/internal/lazyregexp/lazyre.go +++ b/internal/lazyregexp/lazyre.go @@ -10,7 +10,7 @@ import ( "regexp" "sync" - "gogs.io/gogs/internal/testutil" + "gogs.io/gogs/internal/testx" ) // 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. func New(str string) *Regexp { lr := &Regexp{str: str} - if testutil.InTest { + if testx.InTest { // In tests, always compile the regexps early. lr.Regexp() } diff --git a/internal/lfsutil/oid.go b/internal/lfsx/oid.go similarity index 96% rename from internal/lfsutil/oid.go rename to internal/lfsx/oid.go index cfb308783..733a9df9d 100644 --- a/internal/lfsutil/oid.go +++ b/internal/lfsx/oid.go @@ -1,4 +1,4 @@ -package lfsutil +package lfsx import ( "github.com/cockroachdb/errors" diff --git a/internal/lfsutil/oid_test.go b/internal/lfsx/oid_test.go similarity index 97% rename from internal/lfsutil/oid_test.go rename to internal/lfsx/oid_test.go index 6a1210280..3773ca678 100644 --- a/internal/lfsutil/oid_test.go +++ b/internal/lfsx/oid_test.go @@ -1,4 +1,4 @@ -package lfsutil +package lfsx import ( "testing" diff --git a/internal/lfsutil/storage.go b/internal/lfsx/storage.go similarity index 97% rename from internal/lfsutil/storage.go rename to internal/lfsx/storage.go index b53522f10..c63610e3e 100644 --- a/internal/lfsutil/storage.go +++ b/internal/lfsx/storage.go @@ -1,4 +1,4 @@ -package lfsutil +package lfsx import ( "crypto/sha256" @@ -9,7 +9,7 @@ import ( "github.com/cockroachdb/errors" - "gogs.io/gogs/internal/osutil" + "gogs.io/gogs/internal/osx" ) var ( @@ -115,7 +115,7 @@ func (s *LocalStorage) Upload(oid OID, rc io.ReadCloser) (int64, error) { func (s *LocalStorage) Download(oid OID, w io.Writer) error { fpath := s.storagePath(oid) - if !osutil.IsFile(fpath) { + if !osx.IsFile(fpath) { return ErrObjectNotExist } diff --git a/internal/lfsutil/storage_test.go b/internal/lfsx/storage_test.go similarity index 96% rename from internal/lfsutil/storage_test.go rename to internal/lfsx/storage_test.go index 479e0d414..e14836d00 100644 --- a/internal/lfsutil/storage_test.go +++ b/internal/lfsx/storage_test.go @@ -1,4 +1,4 @@ -package lfsutil +package lfsx import ( "bytes" @@ -12,7 +12,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "gogs.io/gogs/internal/osutil" + "gogs.io/gogs/internal/osx" ) func TestLocalStorage_storagePath(t *testing.T) { @@ -76,7 +76,7 @@ func TestLocalStorage_Upload(t *testing.T) { assert.Equal(t, ErrOIDMismatch, err) // File should have been cleaned up. - assert.False(t, osutil.IsFile(s.storagePath(oid))) + assert.False(t, osx.IsFile(s.storagePath(oid))) }) t.Run("duplicate upload returns existing size", func(t *testing.T) { diff --git a/internal/netutil/netutil.go b/internal/netx/netx.go similarity index 99% rename from internal/netutil/netutil.go rename to internal/netx/netx.go index 82e366e4a..9aa76fe79 100644 --- a/internal/netutil/netutil.go +++ b/internal/netx/netx.go @@ -1,4 +1,4 @@ -package netutil +package netx import ( "fmt" diff --git a/internal/netutil/netutil_test.go b/internal/netx/netx_test.go similarity index 98% rename from internal/netutil/netutil_test.go rename to internal/netx/netx_test.go index a658c269a..595986fab 100644 --- a/internal/netutil/netutil_test.go +++ b/internal/netx/netx_test.go @@ -1,4 +1,4 @@ -package netutil +package netx import ( "testing" diff --git a/internal/osutil/error.go b/internal/osx/error.go similarity index 76% rename from internal/osutil/error.go rename to internal/osx/error.go index 13f215c3e..92b1666ab 100644 --- a/internal/osutil/error.go +++ b/internal/osx/error.go @@ -1,12 +1,12 @@ -package osutil +package osx import ( "os" - "gogs.io/gogs/internal/errutil" + "gogs.io/gogs/internal/errx" ) -var _ errutil.NotFound = (*Error)(nil) +var _ errx.NotFound = (*Error)(nil) // Error is a wrapper of an OS error, which handles not found. type Error struct { diff --git a/internal/osutil/error_test.go b/internal/osx/error_test.go similarity index 72% rename from internal/osutil/error_test.go rename to internal/osx/error_test.go index ad1a9701f..d57b13db9 100644 --- a/internal/osutil/error_test.go +++ b/internal/osx/error_test.go @@ -1,4 +1,4 @@ -package osutil +package osx import ( "os" @@ -6,7 +6,7 @@ import ( "github.com/stretchr/testify/assert" - "gogs.io/gogs/internal/errutil" + "gogs.io/gogs/internal/errx" ) func TestError_NotFound(t *testing.T) { @@ -19,7 +19,7 @@ func TestError_NotFound(t *testing.T) { } for _, test := range tests { t.Run("", func(t *testing.T) { - assert.Equal(t, test.expVal, errutil.IsNotFound(NewError(test.err))) + assert.Equal(t, test.expVal, errx.IsNotFound(NewError(test.err))) }) } } diff --git a/internal/osutil/osutil.go b/internal/osx/osx.go similarity index 98% rename from internal/osutil/osutil.go rename to internal/osx/osx.go index 34dd90f9e..58db0885a 100644 --- a/internal/osutil/osutil.go +++ b/internal/osx/osx.go @@ -1,4 +1,4 @@ -package osutil +package osx import ( "os" diff --git a/internal/osutil/osutil_test.go b/internal/osx/osx_test.go similarity index 93% rename from internal/osutil/osutil_test.go rename to internal/osx/osx_test.go index 60262d119..7254665b6 100644 --- a/internal/osutil/osutil_test.go +++ b/internal/osx/osx_test.go @@ -1,4 +1,4 @@ -package osutil +package osx import ( "os" @@ -14,10 +14,10 @@ func TestIsFile(t *testing.T) { want bool }{ { - path: "osutil.go", + path: "osx.go", want: true, }, { - path: "../osutil", + path: "../osx", want: false, }, { path: "not_found", @@ -37,10 +37,10 @@ func TestIsDir(t *testing.T) { want bool }{ { - path: "osutil.go", + path: "osx.go", want: false, }, { - path: "../osutil", + path: "../osx", want: true, }, { path: "not_found", @@ -60,10 +60,10 @@ func TestExist(t *testing.T) { expVal bool }{ { - path: "osutil.go", + path: "osx.go", expVal: true, }, { - path: "../osutil", + path: "../osx", expVal: true, }, { path: "not_found", diff --git a/internal/pathutil/pathutil.go b/internal/pathx/pathx.go similarity index 95% rename from internal/pathutil/pathutil.go rename to internal/pathx/pathx.go index 836da6554..aa552ecfb 100644 --- a/internal/pathutil/pathutil.go +++ b/internal/pathx/pathx.go @@ -1,4 +1,4 @@ -package pathutil +package pathx import ( "path" diff --git a/internal/pathutil/pathutil_test.go b/internal/pathx/pathx_test.go similarity index 98% rename from internal/pathutil/pathutil_test.go rename to internal/pathx/pathx_test.go index 88958149f..a69ac8905 100644 --- a/internal/pathutil/pathutil_test.go +++ b/internal/pathx/pathx_test.go @@ -1,4 +1,4 @@ -package pathutil +package pathx import ( "testing" diff --git a/internal/repoutil/repoutil.go b/internal/repox/repox.go similarity index 99% rename from internal/repoutil/repoutil.go rename to internal/repox/repox.go index e35312c32..c044bdaeb 100644 --- a/internal/repoutil/repoutil.go +++ b/internal/repox/repox.go @@ -1,4 +1,4 @@ -package repoutil +package repox import ( "fmt" diff --git a/internal/repoutil/repoutil_test.go b/internal/repox/repox_test.go similarity index 99% rename from internal/repoutil/repoutil_test.go rename to internal/repox/repox_test.go index 4b02b8884..e5919625c 100644 --- a/internal/repoutil/repoutil_test.go +++ b/internal/repox/repox_test.go @@ -1,4 +1,4 @@ -package repoutil +package repox import ( "runtime" diff --git a/internal/route/api/v1/repo_blob.go b/internal/route/api/v1/repo_blob.go index c4dff83a6..50f04be30 100644 --- a/internal/route/api/v1/repo_blob.go +++ b/internal/route/api/v1/repo_blob.go @@ -7,12 +7,12 @@ import ( "github.com/gogs/git-module" "gogs.io/gogs/internal/context" - "gogs.io/gogs/internal/gitutil" - "gogs.io/gogs/internal/repoutil" + "gogs.io/gogs/internal/gitx" + "gogs.io/gogs/internal/repox" ) func repoGitBlob(c *context.APIContext) { - gitRepo, err := git.Open(repoutil.RepositoryPath(c.Params(":username"), c.Params(":reponame"))) + gitRepo, err := git.Open(repox.RepositoryPath(c.Params(":username"), c.Params(":reponame"))) if err != nil { c.Error(err, "open repository") return @@ -21,7 +21,7 @@ func repoGitBlob(c *context.APIContext) { sha := c.Params(":sha") blob, err := gitRepo.CatFileBlob(sha) if err != nil { - c.NotFoundOrError(gitutil.NewError(err), "get blob") + c.NotFoundOrError(gitx.NewError(err), "get blob") return } @@ -35,7 +35,7 @@ func repoGitBlob(c *context.APIContext) { content, err := blob.Blob().Bytes() if err != nil { - c.NotFoundOrError(gitutil.NewError(err), "get blob content") + c.NotFoundOrError(gitx.NewError(err), "get blob content") return } diff --git a/internal/route/api/v1/repo_commits.go b/internal/route/api/v1/repo_commits.go index 8bc348e8d..7bbcf8b6a 100644 --- a/internal/route/api/v1/repo_commits.go +++ b/internal/route/api/v1/repo_commits.go @@ -10,7 +10,7 @@ import ( "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" - "gogs.io/gogs/internal/gitutil" + "gogs.io/gogs/internal/gitx" "gogs.io/gogs/internal/route/api/v1/types" ) @@ -64,7 +64,7 @@ func getSingleCommit(c *context.APIContext) { } commit, err := gitRepo.CatFileCommit(c.Params(":sha")) if err != nil { - c.NotFoundOrError(gitutil.NewError(err), "get commit") + c.NotFoundOrError(gitx.NewError(err), "get commit") return } @@ -109,7 +109,7 @@ func getReferenceSHA(c *context.APIContext) { sha, err = gitRepo.TagCommitID(ref) } if err != nil { - c.NotFoundOrError(gitutil.NewError(err), "get reference commit ID") + c.NotFoundOrError(gitx.NewError(err), "get reference commit ID") return } c.PlainText(http.StatusOK, sha) diff --git a/internal/route/api/v1/repo_contents.go b/internal/route/api/v1/repo_contents.go index 03a8fcc55..aa3defd64 100644 --- a/internal/route/api/v1/repo_contents.go +++ b/internal/route/api/v1/repo_contents.go @@ -11,9 +11,9 @@ import ( "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" - "gogs.io/gogs/internal/gitutil" - "gogs.io/gogs/internal/pathutil" - "gogs.io/gogs/internal/repoutil" + "gogs.io/gogs/internal/gitx" + "gogs.io/gogs/internal/pathx" + "gogs.io/gogs/internal/repox" ) type links struct { @@ -42,8 +42,8 @@ type repoContent struct { func toRepoContent(c *context.APIContext, ref, subpath string, commit *git.Commit, entry *git.TreeEntry) (*repoContent, error) { repoURL := fmt.Sprintf("%s/repos/%s/%s", c.BaseURL, c.Params(":username"), c.Params(":reponame")) selfURL := fmt.Sprintf("%s/contents/%s", repoURL, subpath) - htmlURL := fmt.Sprintf("%s/src/%s/%s", repoutil.HTMLURL(c.Repo.Owner.Name, c.Repo.Repository.Name), ref, entry.Name()) - downloadURL := fmt.Sprintf("%s/raw/%s/%s", repoutil.HTMLURL(c.Repo.Owner.Name, c.Repo.Repository.Name), ref, entry.Name()) + htmlURL := fmt.Sprintf("%s/src/%s/%s", repox.HTMLURL(c.Repo.Owner.Name, c.Repo.Repository.Name), ref, entry.Name()) + downloadURL := fmt.Sprintf("%s/raw/%s/%s", repox.HTMLURL(c.Repo.Owner.Name, c.Repo.Repository.Name), ref, entry.Name()) content := &repoContent{ Size: entry.Size(), @@ -99,7 +99,7 @@ func toRepoContent(c *context.APIContext, ref, subpath string, commit *git.Commi } func getContents(c *context.APIContext) { - repoPath := repoutil.RepositoryPath(c.Params(":username"), c.Params(":reponame")) + repoPath := repox.RepositoryPath(c.Params(":username"), c.Params(":reponame")) gitRepo, err := git.Open(repoPath) if err != nil { c.Error(err, "open repository") @@ -113,15 +113,15 @@ func getContents(c *context.APIContext) { commit, err := gitRepo.CatFileCommit(ref) if err != nil { - c.NotFoundOrError(gitutil.NewError(err), "get commit") + c.NotFoundOrError(gitx.NewError(err), "get commit") return } // 🚨 SECURITY: Prevent path traversal. - treePath := pathutil.Clean(c.Params("*")) + treePath := pathx.Clean(c.Params("*")) entry, err := commit.TreeEntry(treePath) if err != nil { - c.NotFoundOrError(gitutil.NewError(err), "get tree entry") + c.NotFoundOrError(gitx.NewError(err), "get tree entry") return } @@ -139,13 +139,13 @@ func getContents(c *context.APIContext) { // The entry is a directory dir, err := gitRepo.LsTree(entry.ID().String(), git.LsTreeOptions{Verbatim: true}) if err != nil { - c.NotFoundOrError(gitutil.NewError(err), "get tree") + c.NotFoundOrError(gitx.NewError(err), "get tree") return } entries, err := dir.Entries(git.LsTreeOptions{Verbatim: true}) if err != nil { - c.NotFoundOrError(gitutil.NewError(err), "list entries") + c.NotFoundOrError(gitx.NewError(err), "list entries") return } @@ -188,7 +188,7 @@ func putContents(c *context.APIContext, r putContentsRequest) { } // 🚨 SECURITY: Prevent path traversal. - treePath := pathutil.Clean(c.Params("*")) + treePath := pathx.Clean(c.Params("*")) err = c.Repo.Repository.UpdateRepoFile( c.User, @@ -206,7 +206,7 @@ func putContents(c *context.APIContext, r putContentsRequest) { return } - repoPath := repoutil.RepositoryPath(c.Params(":username"), c.Params(":reponame")) + repoPath := repox.RepositoryPath(c.Params(":username"), c.Params(":reponame")) gitRepo, err := git.Open(repoPath) if err != nil { c.Error(err, "open repository") diff --git a/internal/route/api/v1/repo_file.go b/internal/route/api/v1/repo_file.go index ca76ca47f..5e3e4ea5e 100644 --- a/internal/route/api/v1/repo_file.go +++ b/internal/route/api/v1/repo_file.go @@ -5,7 +5,7 @@ import ( "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" - "gogs.io/gogs/internal/gitutil" + "gogs.io/gogs/internal/gitx" routerepo "gogs.io/gogs/internal/route/repo" ) @@ -22,7 +22,7 @@ func getRawFile(c *context.APIContext) { blob, err := c.Repo.Commit.Blob(c.Repo.TreePath) if err != nil { - c.NotFoundOrError(gitutil.NewError(err), "get blob") + c.NotFoundOrError(gitx.NewError(err), "get blob") return } if err = routerepo.ServeBlob(c.Context, blob); err != nil { @@ -45,7 +45,7 @@ func getArchive(c *context.APIContext) { func getEditorconfig(c *context.APIContext) { ec, err := c.Repo.Editorconfig() if err != nil { - c.NotFoundOrError(gitutil.NewError(err), "get .editorconfig") + c.NotFoundOrError(gitx.NewError(err), "get .editorconfig") return } diff --git a/internal/route/api/v1/repo_tree.go b/internal/route/api/v1/repo_tree.go index 46214104b..3004cf5c1 100644 --- a/internal/route/api/v1/repo_tree.go +++ b/internal/route/api/v1/repo_tree.go @@ -6,7 +6,7 @@ import ( "github.com/gogs/git-module" "gogs.io/gogs/internal/context" - "gogs.io/gogs/internal/gitutil" + "gogs.io/gogs/internal/gitx" ) func getRepoGitTree(c *context.APIContext) { @@ -19,7 +19,7 @@ func getRepoGitTree(c *context.APIContext) { sha := c.Params(":sha") tree, err := gitRepo.LsTree(sha, git.LsTreeOptions{Verbatim: true}) if err != nil { - c.NotFoundOrError(gitutil.NewError(err), "get tree") + c.NotFoundOrError(gitx.NewError(err), "get tree") return } diff --git a/internal/route/install.go b/internal/route/install.go index 98f9a6683..b054ea0b0 100644 --- a/internal/route/install.go +++ b/internal/route/install.go @@ -22,9 +22,9 @@ import ( "gogs.io/gogs/internal/email" "gogs.io/gogs/internal/form" "gogs.io/gogs/internal/markup" - "gogs.io/gogs/internal/osutil" + "gogs.io/gogs/internal/osx" "gogs.io/gogs/internal/ssh" - "gogs.io/gogs/internal/strutil" + "gogs.io/gogs/internal/strx" "gogs.io/gogs/internal/template/highlight" ) @@ -149,7 +149,7 @@ func Install(c *context.Context) { // Note(unknwon): it's hard for Windows users change a running user, // so just use current one if config says default. if conf.IsWindowsRuntime() && conf.App.RunUser == "git" { - f.RunUser = osutil.CurrentUsername() + f.RunUser = osx.CurrentUsername() } else { f.RunUser = conf.App.RunUser } @@ -298,7 +298,7 @@ func InstallPost(c *context.Context, f form.Install) { // Save settings. cfg := ini.Empty() - if osutil.IsFile(conf.CustomConf) { + if osx.IsFile(conf.CustomConf) { // Keeps custom settings if there is already something. if err := cfg.Append(conf.CustomConf); err != nil { log.Error("Failed to load custom conf %q: %v", conf.CustomConf, err) @@ -360,7 +360,7 @@ func InstallPost(c *context.Context, f form.Install) { cfg.Section("log").Key("ROOT_PATH").SetValue(f.LogRootPath) cfg.Section("security").Key("INSTALL_LOCK").SetValue("true") - secretKey, err := strutil.RandomChars(15) + secretKey, err := strx.RandomChars(15) if err != nil { c.RenderWithErr(c.Tr("install.secret_key_failed", err), http.StatusInternalServerError, INSTALL, &f) return diff --git a/internal/route/lfs/basic.go b/internal/route/lfs/basic.go index 70920ab07..b64e233ca 100644 --- a/internal/route/lfs/basic.go +++ b/internal/route/lfs/basic.go @@ -10,8 +10,8 @@ import ( log "unknwon.dev/clog/v2" "gogs.io/gogs/internal/database" - "gogs.io/gogs/internal/lfsutil" - "gogs.io/gogs/internal/strutil" + "gogs.io/gogs/internal/lfsx" + "gogs.io/gogs/internal/strx" ) const transferBasic = "basic" @@ -23,23 +23,23 @@ const ( type basicHandler struct { store Store // The default storage backend for uploading new objects. - defaultStorage lfsutil.Storage + defaultStorage lfsx.Storage // The list of available storage backends to access objects. - storagers map[lfsutil.Storage]lfsutil.Storager + storagers map[lfsx.Storage]lfsx.Storager } // DefaultStorager returns the default storage backend. -func (h *basicHandler) DefaultStorager() lfsutil.Storager { +func (h *basicHandler) DefaultStorager() lfsx.Storager { return h.storagers[h.defaultStorage] } // Storager returns the given storage backend. -func (h *basicHandler) Storager(storage lfsutil.Storage) lfsutil.Storager { +func (h *basicHandler) Storager(storage lfsx.Storage) lfsx.Storager { return h.storagers[storage] } // GET /{owner}/{repo}.git/info/lfs/object/basic/{oid} -func (h *basicHandler) serveDownload(c *macaron.Context, repo *database.Repository, oid lfsutil.OID) { +func (h *basicHandler) serveDownload(c *macaron.Context, repo *database.Repository, oid lfsx.OID) { object, err := h.store.GetLFSObjectByOID(c.Req.Context(), repo.ID, oid) if err != nil { if database.IsErrLFSObjectNotExist(err) { @@ -72,7 +72,7 @@ func (h *basicHandler) serveDownload(c *macaron.Context, repo *database.Reposito } // PUT /{owner}/{repo}.git/info/lfs/object/basic/{oid} -func (h *basicHandler) serveUpload(c *macaron.Context, repo *database.Repository, oid lfsutil.OID) { +func (h *basicHandler) serveUpload(c *macaron.Context, repo *database.Repository, oid lfsx.OID) { // NOTE: LFS client will retry upload the same object if there was a partial failure, // therefore we would like to skip ones that already exist. _, err := h.store.GetLFSObjectByOID(c.Req.Context(), repo.ID, oid) @@ -91,7 +91,7 @@ func (h *basicHandler) serveUpload(c *macaron.Context, repo *database.Repository s := h.DefaultStorager() written, err := s.Upload(oid, c.Req.Request.Body) if err != nil { - if err == lfsutil.ErrInvalidOID || err == lfsutil.ErrOIDMismatch { + if err == lfsx.ErrInvalidOID || err == lfsx.ErrOIDMismatch { responseJSON(c.Resp, http.StatusBadRequest, responseError{ Message: err.Error(), }) @@ -124,12 +124,12 @@ func (h *basicHandler) serveVerify(c *macaron.Context, repo *database.Repository err := json.NewDecoder(c.Req.Request.Body).Decode(&request) if err != nil { responseJSON(c.Resp, http.StatusBadRequest, responseError{ - Message: strutil.ToUpperFirst(err.Error()), + Message: strx.ToUpperFirst(err.Error()), }) return } - if !lfsutil.ValidOID(request.Oid) { + if !lfsx.ValidOID(request.Oid) { responseJSON(c.Resp, http.StatusBadRequest, responseError{ Message: "Invalid oid", }) @@ -159,6 +159,6 @@ func (h *basicHandler) serveVerify(c *macaron.Context, repo *database.Repository } type basicVerifyRequest struct { - Oid lfsutil.OID `json:"oid"` - Size int64 `json:"size"` + Oid lfsx.OID `json:"oid"` + Size int64 `json:"size"` } diff --git a/internal/route/lfs/basic_test.go b/internal/route/lfs/basic_test.go index e1b03e940..3a860077f 100644 --- a/internal/route/lfs/basic_test.go +++ b/internal/route/lfs/basic_test.go @@ -13,26 +13,26 @@ import ( "gopkg.in/macaron.v1" "gogs.io/gogs/internal/database" - "gogs.io/gogs/internal/lfsutil" + "gogs.io/gogs/internal/lfsx" ) -var _ lfsutil.Storager = (*mockStorage)(nil) +var _ lfsx.Storager = (*mockStorage)(nil) // mockStorage is an in-memory storage for LFS objects. type mockStorage struct { buf *bytes.Buffer } -func (*mockStorage) Storage() lfsutil.Storage { +func (*mockStorage) Storage() lfsx.Storage { return "memory" } -func (s *mockStorage) Upload(_ lfsutil.OID, rc io.ReadCloser) (int64, error) { +func (s *mockStorage) Upload(_ lfsx.OID, rc io.ReadCloser) (int64, error) { defer func() { _ = rc.Close() }() return io.Copy(s.buf, rc) } -func (s *mockStorage) Download(_ lfsutil.OID, w io.Writer) error { +func (s *mockStorage) Download(_ lfsx.OID, w io.Writer) error { _, err := io.Copy(w, s.buf) return err } @@ -41,7 +41,7 @@ func TestBasicHandler_serveDownload(t *testing.T) { s := &mockStorage{} basic := &basicHandler{ defaultStorage: s.Storage(), - storagers: map[lfsutil.Storage]lfsutil.Storager{ + storagers: map[lfsx.Storage]lfsx.Storager{ s.Storage(): s, }, } @@ -50,7 +50,7 @@ func TestBasicHandler_serveDownload(t *testing.T) { m.Use(macaron.Renderer()) m.Use(func(c *macaron.Context) { c.Map(&database.Repository{Name: "repo"}) - c.Map(lfsutil.OID("ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f")) + c.Map(lfsx.OID("ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f")) }) m.Get("/", basic.serveDownload) @@ -138,7 +138,7 @@ func TestBasicHandler_serveUpload(t *testing.T) { s := &mockStorage{buf: &bytes.Buffer{}} basic := &basicHandler{ defaultStorage: s.Storage(), - storagers: map[lfsutil.Storage]lfsutil.Storager{ + storagers: map[lfsx.Storage]lfsx.Storager{ s.Storage(): s, }, } @@ -147,7 +147,7 @@ func TestBasicHandler_serveUpload(t *testing.T) { m.Use(macaron.Renderer()) m.Use(func(c *macaron.Context) { c.Map(&database.Repository{Name: "repo"}) - c.Map(lfsutil.OID("ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f")) + c.Map(lfsx.OID("ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f")) }) m.Put("/", basic.serveUpload) diff --git a/internal/route/lfs/batch.go b/internal/route/lfs/batch.go index b67f25a64..a64ab8bc1 100644 --- a/internal/route/lfs/batch.go +++ b/internal/route/lfs/batch.go @@ -10,8 +10,8 @@ import ( "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/database" - "gogs.io/gogs/internal/lfsutil" - "gogs.io/gogs/internal/strutil" + "gogs.io/gogs/internal/lfsx" + "gogs.io/gogs/internal/strx" ) // POST /{owner}/{repo}.git/info/lfs/object/batch @@ -22,7 +22,7 @@ func serveBatch(store Store) macaron.Handler { err := json.NewDecoder(c.Req.Request.Body).Decode(&request) if err != nil { responseJSON(c.Resp, http.StatusBadRequest, responseError{ - Message: strutil.ToUpperFirst(err.Error()), + Message: strx.ToUpperFirst(err.Error()), }) return } @@ -37,7 +37,7 @@ func serveBatch(store Store) macaron.Handler { case basicOperationUpload: for _, obj := range request.Objects { var actions batchActions - if lfsutil.ValidOID(obj.Oid) { + if lfsx.ValidOID(obj.Oid) { actions = batchActions{ Upload: &batchAction{ Href: fmt.Sprintf("%s/%s", baseHref, obj.Oid), @@ -68,7 +68,7 @@ func serveBatch(store Store) macaron.Handler { } case basicOperationDownload: - oids := make([]lfsutil.OID, 0, len(request.Objects)) + oids := make([]lfsx.OID, 0, len(request.Objects)) for _, obj := range request.Objects { oids = append(oids, obj.Oid) } @@ -78,7 +78,7 @@ func serveBatch(store Store) macaron.Handler { log.Error("Failed to get objects [repo_id: %d, oids: %v]: %v", repo.ID, oids, err) return } - storedSet := make(map[lfsutil.OID]*database.LFSObject, len(stored)) + storedSet := make(map[lfsx.OID]*database.LFSObject, len(stored)) for _, obj := range stored { storedSet[obj.OID] = obj } @@ -128,8 +128,8 @@ func serveBatch(store Store) macaron.Handler { type batchRequest struct { Operation string `json:"operation"` Objects []struct { - Oid lfsutil.OID `json:"oid"` - Size int64 `json:"size"` + Oid lfsx.OID `json:"oid"` + Size int64 `json:"size"` } `json:"objects"` } @@ -151,7 +151,7 @@ type batchActions struct { } type batchObject struct { - Oid lfsutil.OID `json:"oid"` + Oid lfsx.OID `json:"oid"` Size int64 `json:"size"` Actions batchActions `json:"actions"` } diff --git a/internal/route/lfs/main_test.go b/internal/route/lfs/main_test.go index b317df2da..939968188 100644 --- a/internal/route/lfs/main_test.go +++ b/internal/route/lfs/main_test.go @@ -8,7 +8,7 @@ import ( log "unknwon.dev/clog/v2" - "gogs.io/gogs/internal/testutil" + "gogs.io/gogs/internal/testx" ) func TestMain(m *testing.M) { @@ -16,7 +16,7 @@ func TestMain(m *testing.M) { if !testing.Verbose() { // Remove the primary logger and register a noop logger. log.Remove(log.DefaultConsoleName) - err := log.New("noop", testutil.InitNoopLogger) + err := log.New("noop", testx.InitNoopLogger) if err != nil { fmt.Println(err) os.Exit(1) diff --git a/internal/route/lfs/mocks_test.go b/internal/route/lfs/mocks_test.go index 5c593cc89..c4f6f7190 100644 --- a/internal/route/lfs/mocks_test.go +++ b/internal/route/lfs/mocks_test.go @@ -11,7 +11,7 @@ import ( "sync" database "gogs.io/gogs/internal/database" - lfsutil "gogs.io/gogs/internal/lfsutil" + lfsx "gogs.io/gogs/internal/lfsx" ) // MockStore is a mock implementation of the Store interface (from the @@ -71,7 +71,7 @@ func NewMockStore() *MockStore { }, }, CreateLFSObjectFunc: &StoreCreateLFSObjectFunc{ - defaultHook: func(context.Context, int64, lfsutil.OID, int64, lfsutil.Storage) (r0 error) { + defaultHook: func(context.Context, int64, lfsx.OID, int64, lfsx.Storage) (r0 error) { return }, }, @@ -86,12 +86,12 @@ func NewMockStore() *MockStore { }, }, GetLFSObjectByOIDFunc: &StoreGetLFSObjectByOIDFunc{ - defaultHook: func(context.Context, int64, lfsutil.OID) (r0 *database.LFSObject, r1 error) { + defaultHook: func(context.Context, int64, lfsx.OID) (r0 *database.LFSObject, r1 error) { return }, }, GetLFSObjectsByOIDsFunc: &StoreGetLFSObjectsByOIDsFunc{ - defaultHook: func(context.Context, int64, ...lfsutil.OID) (r0 []*database.LFSObject, r1 error) { + defaultHook: func(context.Context, int64, ...lfsx.OID) (r0 []*database.LFSObject, r1 error) { return }, }, @@ -138,7 +138,7 @@ func NewStrictMockStore() *MockStore { }, }, CreateLFSObjectFunc: &StoreCreateLFSObjectFunc{ - defaultHook: func(context.Context, int64, lfsutil.OID, int64, lfsutil.Storage) error { + defaultHook: func(context.Context, int64, lfsx.OID, int64, lfsx.Storage) error { panic("unexpected invocation of MockStore.CreateLFSObject") }, }, @@ -153,12 +153,12 @@ func NewStrictMockStore() *MockStore { }, }, GetLFSObjectByOIDFunc: &StoreGetLFSObjectByOIDFunc{ - defaultHook: func(context.Context, int64, lfsutil.OID) (*database.LFSObject, error) { + defaultHook: func(context.Context, int64, lfsx.OID) (*database.LFSObject, error) { panic("unexpected invocation of MockStore.GetLFSObjectByOID") }, }, GetLFSObjectsByOIDsFunc: &StoreGetLFSObjectsByOIDsFunc{ - defaultHook: func(context.Context, int64, ...lfsutil.OID) ([]*database.LFSObject, error) { + defaultHook: func(context.Context, int64, ...lfsx.OID) ([]*database.LFSObject, error) { panic("unexpected invocation of MockStore.GetLFSObjectsByOIDs") }, }, @@ -466,15 +466,15 @@ func (c StoreAuthorizeRepositoryAccessFuncCall) Results() []interface{} { // StoreCreateLFSObjectFunc describes the behavior when the CreateLFSObject // method of the parent MockStore instance is invoked. type StoreCreateLFSObjectFunc struct { - defaultHook func(context.Context, int64, lfsutil.OID, int64, lfsutil.Storage) error - hooks []func(context.Context, int64, lfsutil.OID, int64, lfsutil.Storage) error + defaultHook func(context.Context, int64, lfsx.OID, int64, lfsx.Storage) error + hooks []func(context.Context, int64, lfsx.OID, int64, lfsx.Storage) error history []StoreCreateLFSObjectFuncCall mutex sync.Mutex } // CreateLFSObject delegates to the next hook function in the queue and // stores the parameter and result values of this invocation. -func (m *MockStore) CreateLFSObject(v0 context.Context, v1 int64, v2 lfsutil.OID, v3 int64, v4 lfsutil.Storage) error { +func (m *MockStore) CreateLFSObject(v0 context.Context, v1 int64, v2 lfsx.OID, v3 int64, v4 lfsx.Storage) error { r0 := m.CreateLFSObjectFunc.nextHook()(v0, v1, v2, v3, v4) m.CreateLFSObjectFunc.appendCall(StoreCreateLFSObjectFuncCall{v0, v1, v2, v3, v4, r0}) return r0 @@ -483,7 +483,7 @@ func (m *MockStore) CreateLFSObject(v0 context.Context, v1 int64, v2 lfsutil.OID // SetDefaultHook sets function that is called when the CreateLFSObject // method of the parent MockStore instance is invoked and the hook queue is // empty. -func (f *StoreCreateLFSObjectFunc) SetDefaultHook(hook func(context.Context, int64, lfsutil.OID, int64, lfsutil.Storage) error) { +func (f *StoreCreateLFSObjectFunc) SetDefaultHook(hook func(context.Context, int64, lfsx.OID, int64, lfsx.Storage) error) { f.defaultHook = hook } @@ -491,7 +491,7 @@ func (f *StoreCreateLFSObjectFunc) SetDefaultHook(hook func(context.Context, int // CreateLFSObject method of the parent MockStore instance invokes the hook // at the front of the queue and discards it. After the queue is empty, the // default hook function is invoked for any future action. -func (f *StoreCreateLFSObjectFunc) PushHook(hook func(context.Context, int64, lfsutil.OID, int64, lfsutil.Storage) error) { +func (f *StoreCreateLFSObjectFunc) PushHook(hook func(context.Context, int64, lfsx.OID, int64, lfsx.Storage) error) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() @@ -500,19 +500,19 @@ func (f *StoreCreateLFSObjectFunc) PushHook(hook func(context.Context, int64, lf // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. func (f *StoreCreateLFSObjectFunc) SetDefaultReturn(r0 error) { - f.SetDefaultHook(func(context.Context, int64, lfsutil.OID, int64, lfsutil.Storage) error { + f.SetDefaultHook(func(context.Context, int64, lfsx.OID, int64, lfsx.Storage) error { return r0 }) } // PushReturn calls PushHook with a function that returns the given values. func (f *StoreCreateLFSObjectFunc) PushReturn(r0 error) { - f.PushHook(func(context.Context, int64, lfsutil.OID, int64, lfsutil.Storage) error { + f.PushHook(func(context.Context, int64, lfsx.OID, int64, lfsx.Storage) error { return r0 }) } -func (f *StoreCreateLFSObjectFunc) nextHook() func(context.Context, int64, lfsutil.OID, int64, lfsutil.Storage) error { +func (f *StoreCreateLFSObjectFunc) nextHook() func(context.Context, int64, lfsx.OID, int64, lfsx.Storage) error { f.mutex.Lock() defer f.mutex.Unlock() @@ -553,13 +553,13 @@ type StoreCreateLFSObjectFuncCall struct { Arg1 int64 // Arg2 is the value of the 3rd argument passed to this method // invocation. - Arg2 lfsutil.OID + Arg2 lfsx.OID // Arg3 is the value of the 4th argument passed to this method // invocation. Arg3 int64 // Arg4 is the value of the 5th argument passed to this method // invocation. - Arg4 lfsutil.Storage + Arg4 lfsx.Storage // Result0 is the value of the 1st result returned from this method // invocation. Result0 error @@ -801,15 +801,15 @@ func (c StoreGetAccessTokenBySHA1FuncCall) Results() []interface{} { // StoreGetLFSObjectByOIDFunc describes the behavior when the // GetLFSObjectByOID method of the parent MockStore instance is invoked. type StoreGetLFSObjectByOIDFunc struct { - defaultHook func(context.Context, int64, lfsutil.OID) (*database.LFSObject, error) - hooks []func(context.Context, int64, lfsutil.OID) (*database.LFSObject, error) + defaultHook func(context.Context, int64, lfsx.OID) (*database.LFSObject, error) + hooks []func(context.Context, int64, lfsx.OID) (*database.LFSObject, error) history []StoreGetLFSObjectByOIDFuncCall mutex sync.Mutex } // GetLFSObjectByOID delegates to the next hook function in the queue and // stores the parameter and result values of this invocation. -func (m *MockStore) GetLFSObjectByOID(v0 context.Context, v1 int64, v2 lfsutil.OID) (*database.LFSObject, error) { +func (m *MockStore) GetLFSObjectByOID(v0 context.Context, v1 int64, v2 lfsx.OID) (*database.LFSObject, error) { r0, r1 := m.GetLFSObjectByOIDFunc.nextHook()(v0, v1, v2) m.GetLFSObjectByOIDFunc.appendCall(StoreGetLFSObjectByOIDFuncCall{v0, v1, v2, r0, r1}) return r0, r1 @@ -818,7 +818,7 @@ func (m *MockStore) GetLFSObjectByOID(v0 context.Context, v1 int64, v2 lfsutil.O // SetDefaultHook sets function that is called when the GetLFSObjectByOID // method of the parent MockStore instance is invoked and the hook queue is // empty. -func (f *StoreGetLFSObjectByOIDFunc) SetDefaultHook(hook func(context.Context, int64, lfsutil.OID) (*database.LFSObject, error)) { +func (f *StoreGetLFSObjectByOIDFunc) SetDefaultHook(hook func(context.Context, int64, lfsx.OID) (*database.LFSObject, error)) { f.defaultHook = hook } @@ -826,7 +826,7 @@ func (f *StoreGetLFSObjectByOIDFunc) SetDefaultHook(hook func(context.Context, i // GetLFSObjectByOID method of the parent MockStore instance invokes the // hook at the front of the queue and discards it. After the queue is empty, // the default hook function is invoked for any future action. -func (f *StoreGetLFSObjectByOIDFunc) PushHook(hook func(context.Context, int64, lfsutil.OID) (*database.LFSObject, error)) { +func (f *StoreGetLFSObjectByOIDFunc) PushHook(hook func(context.Context, int64, lfsx.OID) (*database.LFSObject, error)) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() @@ -835,19 +835,19 @@ func (f *StoreGetLFSObjectByOIDFunc) PushHook(hook func(context.Context, int64, // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. func (f *StoreGetLFSObjectByOIDFunc) SetDefaultReturn(r0 *database.LFSObject, r1 error) { - f.SetDefaultHook(func(context.Context, int64, lfsutil.OID) (*database.LFSObject, error) { + f.SetDefaultHook(func(context.Context, int64, lfsx.OID) (*database.LFSObject, error) { return r0, r1 }) } // PushReturn calls PushHook with a function that returns the given values. func (f *StoreGetLFSObjectByOIDFunc) PushReturn(r0 *database.LFSObject, r1 error) { - f.PushHook(func(context.Context, int64, lfsutil.OID) (*database.LFSObject, error) { + f.PushHook(func(context.Context, int64, lfsx.OID) (*database.LFSObject, error) { return r0, r1 }) } -func (f *StoreGetLFSObjectByOIDFunc) nextHook() func(context.Context, int64, lfsutil.OID) (*database.LFSObject, error) { +func (f *StoreGetLFSObjectByOIDFunc) nextHook() func(context.Context, int64, lfsx.OID) (*database.LFSObject, error) { f.mutex.Lock() defer f.mutex.Unlock() @@ -888,7 +888,7 @@ type StoreGetLFSObjectByOIDFuncCall struct { Arg1 int64 // Arg2 is the value of the 3rd argument passed to this method // invocation. - Arg2 lfsutil.OID + Arg2 lfsx.OID // Result0 is the value of the 1st result returned from this method // invocation. Result0 *database.LFSObject @@ -912,15 +912,15 @@ func (c StoreGetLFSObjectByOIDFuncCall) Results() []interface{} { // StoreGetLFSObjectsByOIDsFunc describes the behavior when the // GetLFSObjectsByOIDs method of the parent MockStore instance is invoked. type StoreGetLFSObjectsByOIDsFunc struct { - defaultHook func(context.Context, int64, ...lfsutil.OID) ([]*database.LFSObject, error) - hooks []func(context.Context, int64, ...lfsutil.OID) ([]*database.LFSObject, error) + defaultHook func(context.Context, int64, ...lfsx.OID) ([]*database.LFSObject, error) + hooks []func(context.Context, int64, ...lfsx.OID) ([]*database.LFSObject, error) history []StoreGetLFSObjectsByOIDsFuncCall mutex sync.Mutex } // GetLFSObjectsByOIDs delegates to the next hook function in the queue and // stores the parameter and result values of this invocation. -func (m *MockStore) GetLFSObjectsByOIDs(v0 context.Context, v1 int64, v2 ...lfsutil.OID) ([]*database.LFSObject, error) { +func (m *MockStore) GetLFSObjectsByOIDs(v0 context.Context, v1 int64, v2 ...lfsx.OID) ([]*database.LFSObject, error) { r0, r1 := m.GetLFSObjectsByOIDsFunc.nextHook()(v0, v1, v2...) m.GetLFSObjectsByOIDsFunc.appendCall(StoreGetLFSObjectsByOIDsFuncCall{v0, v1, v2, r0, r1}) return r0, r1 @@ -929,7 +929,7 @@ func (m *MockStore) GetLFSObjectsByOIDs(v0 context.Context, v1 int64, v2 ...lfsu // SetDefaultHook sets function that is called when the GetLFSObjectsByOIDs // method of the parent MockStore instance is invoked and the hook queue is // empty. -func (f *StoreGetLFSObjectsByOIDsFunc) SetDefaultHook(hook func(context.Context, int64, ...lfsutil.OID) ([]*database.LFSObject, error)) { +func (f *StoreGetLFSObjectsByOIDsFunc) SetDefaultHook(hook func(context.Context, int64, ...lfsx.OID) ([]*database.LFSObject, error)) { f.defaultHook = hook } @@ -937,7 +937,7 @@ func (f *StoreGetLFSObjectsByOIDsFunc) SetDefaultHook(hook func(context.Context, // GetLFSObjectsByOIDs method of the parent MockStore instance invokes the // hook at the front of the queue and discards it. After the queue is empty, // the default hook function is invoked for any future action. -func (f *StoreGetLFSObjectsByOIDsFunc) PushHook(hook func(context.Context, int64, ...lfsutil.OID) ([]*database.LFSObject, error)) { +func (f *StoreGetLFSObjectsByOIDsFunc) PushHook(hook func(context.Context, int64, ...lfsx.OID) ([]*database.LFSObject, error)) { f.mutex.Lock() f.hooks = append(f.hooks, hook) f.mutex.Unlock() @@ -946,19 +946,19 @@ func (f *StoreGetLFSObjectsByOIDsFunc) PushHook(hook func(context.Context, int64 // SetDefaultReturn calls SetDefaultHook with a function that returns the // given values. func (f *StoreGetLFSObjectsByOIDsFunc) SetDefaultReturn(r0 []*database.LFSObject, r1 error) { - f.SetDefaultHook(func(context.Context, int64, ...lfsutil.OID) ([]*database.LFSObject, error) { + f.SetDefaultHook(func(context.Context, int64, ...lfsx.OID) ([]*database.LFSObject, error) { return r0, r1 }) } // PushReturn calls PushHook with a function that returns the given values. func (f *StoreGetLFSObjectsByOIDsFunc) PushReturn(r0 []*database.LFSObject, r1 error) { - f.PushHook(func(context.Context, int64, ...lfsutil.OID) ([]*database.LFSObject, error) { + f.PushHook(func(context.Context, int64, ...lfsx.OID) ([]*database.LFSObject, error) { return r0, r1 }) } -func (f *StoreGetLFSObjectsByOIDsFunc) nextHook() func(context.Context, int64, ...lfsutil.OID) ([]*database.LFSObject, error) { +func (f *StoreGetLFSObjectsByOIDsFunc) nextHook() func(context.Context, int64, ...lfsx.OID) ([]*database.LFSObject, error) { f.mutex.Lock() defer f.mutex.Unlock() @@ -999,7 +999,7 @@ type StoreGetLFSObjectsByOIDsFuncCall struct { Arg1 int64 // Arg2 is a slice containing the values of the variadic arguments // passed to this method invocation. - Arg2 []lfsutil.OID + Arg2 []lfsx.OID // Result0 is the value of the 1st result returned from this method // invocation. Result0 []*database.LFSObject diff --git a/internal/route/lfs/route.go b/internal/route/lfs/route.go index cf32ab369..b885ba445 100644 --- a/internal/route/lfs/route.go +++ b/internal/route/lfs/route.go @@ -8,11 +8,11 @@ import ( log "unknwon.dev/clog/v2" "gogs.io/gogs/internal/auth" - "gogs.io/gogs/internal/authutil" + "gogs.io/gogs/internal/authx" "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" - "gogs.io/gogs/internal/lfsutil" + "gogs.io/gogs/internal/lfsx" ) // RegisterRoutes registers LFS routes using given router, and inherits all @@ -28,9 +28,9 @@ func RegisterRoutes(r *macaron.Router) { r.Group("/objects/basic", func() { basic := &basicHandler{ store: store, - defaultStorage: lfsutil.Storage(conf.LFS.Storage), - storagers: map[lfsutil.Storage]lfsutil.Storager{ - lfsutil.StorageLocal: &lfsutil.LocalStorage{Root: conf.LFS.ObjectsPath, TempDir: conf.LFS.ObjectsTempPath}, + defaultStorage: lfsx.Storage(conf.LFS.Storage), + storagers: map[lfsx.Storage]lfsx.Storager{ + lfsx.StorageLocal: &lfsx.LocalStorage{Root: conf.LFS.ObjectsPath, TempDir: conf.LFS.ObjectsTempPath}, }, } r.Combo("/:oid", verifyOID()). @@ -52,7 +52,7 @@ func authenticate(store Store) macaron.Handler { } return func(c *macaron.Context) { - username, password := authutil.DecodeBasic(c.Req.Header) + username, password := authx.DecodeBasic(c.Req.Header) if username == "" { askCredentials(c.Resp) return @@ -163,8 +163,8 @@ func verifyHeader(key, value string, failCode int) macaron.Handler { // verifyOID checks if the ":oid" URL parameter is valid. func verifyOID() macaron.Handler { return func(c *macaron.Context) { - oid := lfsutil.OID(c.Params(":oid")) - if !lfsutil.ValidOID(oid) { + oid := lfsx.OID(c.Params(":oid")) + if !lfsx.ValidOID(oid) { responseJSON(c.Resp, http.StatusBadRequest, responseError{ Message: "Invalid oid", }) diff --git a/internal/route/lfs/route_test.go b/internal/route/lfs/route_test.go index 400fd0a8d..46fcb6125 100644 --- a/internal/route/lfs/route_test.go +++ b/internal/route/lfs/route_test.go @@ -13,7 +13,7 @@ import ( "gogs.io/gogs/internal/auth" "gogs.io/gogs/internal/database" - "gogs.io/gogs/internal/lfsutil" + "gogs.io/gogs/internal/lfsx" ) func TestAuthenticate(t *testing.T) { @@ -310,7 +310,7 @@ func Test_verifyHeader(t *testing.T) { func Test_verifyOID(t *testing.T) { m := macaron.New() - m.Get("/:oid", verifyOID(), func(w http.ResponseWriter, oid lfsutil.OID) { + m.Get("/:oid", verifyOID(), func(w http.ResponseWriter, oid lfsx.OID) { fmt.Fprintf(w, "oid: %s", oid) }) diff --git a/internal/route/lfs/store.go b/internal/route/lfs/store.go index 054041798..3977cadc3 100644 --- a/internal/route/lfs/store.go +++ b/internal/route/lfs/store.go @@ -4,7 +4,7 @@ import ( "context" "gogs.io/gogs/internal/database" - "gogs.io/gogs/internal/lfsutil" + "gogs.io/gogs/internal/lfsx" ) // Store is the data layer carrier for LFS endpoints. This interface is meant to @@ -19,13 +19,13 @@ type Store interface { TouchAccessTokenByID(ctx context.Context, id int64) error // CreateLFSObject creates an LFS object record in database. - CreateLFSObject(ctx context.Context, repoID int64, oid lfsutil.OID, size int64, storage lfsutil.Storage) error + CreateLFSObject(ctx context.Context, repoID int64, oid lfsx.OID, size int64, storage lfsx.Storage) error // GetLFSObjectByOID returns the LFS object with given OID. It returns // database.ErrLFSObjectNotExist when not found. - GetLFSObjectByOID(ctx context.Context, repoID int64, oid lfsutil.OID) (*database.LFSObject, error) + GetLFSObjectByOID(ctx context.Context, repoID int64, oid lfsx.OID) (*database.LFSObject, error) // GetLFSObjectsByOIDs returns LFS objects found within "oids". The returned // list could have fewer elements if some oids were not found. - GetLFSObjectsByOIDs(ctx context.Context, repoID int64, oids ...lfsutil.OID) ([]*database.LFSObject, error) + GetLFSObjectsByOIDs(ctx context.Context, repoID int64, oids ...lfsx.OID) ([]*database.LFSObject, error) // AuthorizeRepositoryAccess returns true if the user has as good as desired // access mode to the repository. @@ -80,15 +80,15 @@ func (*store) TouchAccessTokenByID(ctx context.Context, id int64) error { return database.Handle.AccessTokens().Touch(ctx, id) } -func (*store) CreateLFSObject(ctx context.Context, repoID int64, oid lfsutil.OID, size int64, storage lfsutil.Storage) error { +func (*store) CreateLFSObject(ctx context.Context, repoID int64, oid lfsx.OID, size int64, storage lfsx.Storage) error { return database.Handle.LFS().CreateObject(ctx, repoID, oid, size, storage) } -func (*store) GetLFSObjectByOID(ctx context.Context, repoID int64, oid lfsutil.OID) (*database.LFSObject, error) { +func (*store) GetLFSObjectByOID(ctx context.Context, repoID int64, oid lfsx.OID) (*database.LFSObject, error) { return database.Handle.LFS().GetObjectByOID(ctx, repoID, oid) } -func (*store) GetLFSObjectsByOIDs(ctx context.Context, repoID int64, oids ...lfsutil.OID) ([]*database.LFSObject, error) { +func (*store) GetLFSObjectsByOIDs(ctx context.Context, repoID int64, oids ...lfsx.OID) ([]*database.LFSObject, error) { return database.Handle.LFS().GetObjectsByOIDs(ctx, repoID, oids...) } diff --git a/internal/route/repo/branch.go b/internal/route/repo/branch.go index 52f7f4c50..c242cb2db 100644 --- a/internal/route/repo/branch.go +++ b/internal/route/repo/branch.go @@ -10,7 +10,7 @@ import ( "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" apiv1types "gogs.io/gogs/internal/route/api/v1/types" - "gogs.io/gogs/internal/urlutil" + "gogs.io/gogs/internal/urlx" ) const ( @@ -109,7 +109,7 @@ func DeleteBranchPost(c *context.Context) { defer func() { redirectTo := c.Query("redirect_to") - if !urlutil.IsSameSite(redirectTo) { + if !urlx.IsSameSite(redirectTo) { redirectTo = c.Repo.RepoLink } c.Redirect(redirectTo) diff --git a/internal/route/repo/commit.go b/internal/route/repo/commit.go index 18652b57d..ffda0482b 100644 --- a/internal/route/repo/commit.go +++ b/internal/route/repo/commit.go @@ -10,7 +10,7 @@ import ( "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" - "gogs.io/gogs/internal/gitutil" + "gogs.io/gogs/internal/gitx" "gogs.io/gogs/internal/tool" ) @@ -121,16 +121,16 @@ func Diff(c *context.Context) { commit, err := c.Repo.GitRepo.CatFileCommit(commitID) if err != nil { - c.NotFoundOrError(gitutil.NewError(err), "get commit by ID") + c.NotFoundOrError(gitx.NewError(err), "get commit by ID") return } - diff, err := gitutil.RepoDiff(c.Repo.GitRepo, + diff, err := gitx.RepoDiff(c.Repo.GitRepo, commitID, conf.Git.MaxDiffFiles, conf.Git.MaxDiffLines, conf.Git.MaxDiffLineChars, git.DiffOptions{Timeout: time.Duration(conf.Git.Timeout.Diff) * time.Second}, ) if err != nil { - c.NotFoundOrError(gitutil.NewError(err), "get diff") + c.NotFoundOrError(gitx.NewError(err), "get diff") return } @@ -176,7 +176,7 @@ func RawDiff(c *context.Context) { git.RawDiffFormat(c.Params(":ext")), c.Resp, ); err != nil { - c.NotFoundOrError(gitutil.NewError(err), "get raw diff") + c.NotFoundOrError(gitx.NewError(err), "get raw diff") return } } @@ -217,22 +217,22 @@ func CompareDiff(c *context.Context) { commit, err := c.Repo.GitRepo.CatFileCommit(afterCommitID) if err != nil { - c.NotFoundOrError(gitutil.NewError(err), "get head commit") + c.NotFoundOrError(gitx.NewError(err), "get head commit") return } - diff, err := gitutil.RepoDiff(c.Repo.GitRepo, + diff, err := gitx.RepoDiff(c.Repo.GitRepo, afterCommitID, conf.Git.MaxDiffFiles, conf.Git.MaxDiffLines, conf.Git.MaxDiffLineChars, git.DiffOptions{Base: beforeCommitID, Timeout: time.Duration(conf.Git.Timeout.Diff) * time.Second}, ) if err != nil { - c.NotFoundOrError(gitutil.NewError(err), "get diff") + c.NotFoundOrError(gitx.NewError(err), "get diff") return } commits, err := commit.CommitsAfter(beforeCommitID) if err != nil { - c.NotFoundOrError(gitutil.NewError(err), "get commits after") + c.NotFoundOrError(gitx.NewError(err), "get commits after") return } diff --git a/internal/route/repo/download.go b/internal/route/repo/download.go index bed8214bf..3d8fff424 100644 --- a/internal/route/repo/download.go +++ b/internal/route/repo/download.go @@ -9,7 +9,7 @@ import ( "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/context" - "gogs.io/gogs/internal/gitutil" + "gogs.io/gogs/internal/gitx" "gogs.io/gogs/internal/tool" ) @@ -47,7 +47,7 @@ func ServeBlob(c *context.Context, blob *git.Blob) error { func SingleDownload(c *context.Context) { blob, err := c.Repo.Commit.Blob(c.Repo.TreePath) if err != nil { - c.NotFoundOrError(gitutil.NewError(err), "get blob") + c.NotFoundOrError(gitx.NewError(err), "get blob") return } diff --git a/internal/route/repo/editor.go b/internal/route/repo/editor.go index ceccb3025..bef2c4d50 100644 --- a/internal/route/repo/editor.go +++ b/internal/route/repo/editor.go @@ -14,8 +14,8 @@ import ( "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/form" - "gogs.io/gogs/internal/gitutil" - "gogs.io/gogs/internal/pathutil" + "gogs.io/gogs/internal/gitx" + "gogs.io/gogs/internal/pathx" "gogs.io/gogs/internal/template" "gogs.io/gogs/internal/tool" ) @@ -55,7 +55,7 @@ func editFile(c *context.Context, isNewFile bool) { if !isNewFile { entry, err := c.Repo.Commit.TreeEntry(c.Repo.TreePath) if err != nil { - c.NotFoundOrError(gitutil.NewError(err), "get tree entry") + c.NotFoundOrError(gitx.NewError(err), "get tree entry") return } @@ -135,7 +135,7 @@ func editFilePost(c *context.Context, f form.EditRepoFile, isNewFile bool) { } // 🚨 SECURITY: Prevent path traversal. - f.TreePath = pathutil.Clean(f.TreePath) + f.TreePath = pathx.Clean(f.TreePath) treeNames, treePaths := getParentTreeFields(f.TreePath) c.Data["ParentTreePath"] = path.Dir(c.Repo.TreePath) @@ -177,7 +177,7 @@ func editFilePost(c *context.Context, f form.EditRepoFile, isNewFile bool) { newTreePath = path.Join(newTreePath, part) entry, err := c.Repo.Commit.TreeEntry(newTreePath) if err != nil { - if gitutil.IsErrRevisionNotExist(err) { + if gitx.IsErrRevisionNotExist(err) { // Means there is no item with that name, so we're good break } @@ -208,7 +208,7 @@ func editFilePost(c *context.Context, f form.EditRepoFile, isNewFile bool) { if !isNewFile { entry, err := c.Repo.Commit.TreeEntry(oldTreePath) if err != nil { - if gitutil.IsErrRevisionNotExist(err) { + if gitx.IsErrRevisionNotExist(err) { c.FormErr("TreePath") c.RenderWithErr(c.Tr("repo.editor.file_editing_no_longer_exists", oldTreePath), http.StatusNotFound, tmplEditorEdit, &f) } else { @@ -242,7 +242,7 @@ func editFilePost(c *context.Context, f form.EditRepoFile, isNewFile bool) { // We have a new filename (rename or completely new file) so we need to make sure it doesn't already exist, can't clobber. entry, err := c.Repo.Commit.TreeEntry(f.TreePath) if err != nil { - if !gitutil.IsErrRevisionNotExist(err) { + if !gitx.IsErrRevisionNotExist(err) { c.Error(err, "get tree entry") return } @@ -300,7 +300,7 @@ func NewFilePost(c *context.Context, f form.EditRepoFile) { func DiffPreviewPost(c *context.Context, f form.EditPreviewDiff) { // 🚨 SECURITY: Prevent path traversal. - treePath := pathutil.Clean(c.Repo.TreePath) + treePath := pathx.Clean(c.Repo.TreePath) entry, err := c.Repo.Commit.TreeEntry(treePath) if err != nil { @@ -342,7 +342,7 @@ func DeleteFilePost(c *context.Context, f form.DeleteRepoFile) { c.Data["BranchLink"] = c.Repo.RepoLink + "/src/" + c.Repo.BranchName // 🚨 SECURITY: Prevent path traversal. - c.Repo.TreePath = pathutil.Clean(c.Repo.TreePath) + c.Repo.TreePath = pathx.Clean(c.Repo.TreePath) c.Data["TreePath"] = c.Repo.TreePath oldBranchName := c.Repo.BranchName @@ -438,7 +438,7 @@ func UploadFilePost(c *context.Context, f form.UploadRepoFile) { } // 🚨 SECURITY: Prevent path traversal. - f.TreePath = pathutil.Clean(f.TreePath) + f.TreePath = pathx.Clean(f.TreePath) treeNames, treePaths := getParentTreeFields(f.TreePath) if len(treeNames) == 0 { // We must at least have one element for user to input. @@ -472,7 +472,7 @@ func UploadFilePost(c *context.Context, f form.UploadRepoFile) { newTreePath = path.Join(newTreePath, part) entry, err := c.Repo.Commit.TreeEntry(newTreePath) if err != nil { - if gitutil.IsErrRevisionNotExist(err) { + if gitx.IsErrRevisionNotExist(err) { // Means there is no item with that name, so we're good break } diff --git a/internal/route/repo/http.go b/internal/route/repo/http.go index 79c6cc343..72fb7fba4 100644 --- a/internal/route/repo/http.go +++ b/internal/route/repo/http.go @@ -21,7 +21,7 @@ import ( "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/lazyregexp" - "gogs.io/gogs/internal/pathutil" + "gogs.io/gogs/internal/pathx" "gogs.io/gogs/internal/tool" ) @@ -408,7 +408,7 @@ func HTTP(c *HTTPContext) { } // 🚨 SECURITY: Prevent path traversal. - cleaned := pathutil.Clean(m[1]) + cleaned := pathx.Clean(m[1]) if m[1] != "/"+cleaned { c.Error(http.StatusBadRequest, "Request path contains suspicious characters") return diff --git a/internal/route/repo/pull.go b/internal/route/repo/pull.go index 068e336fa..a606f850c 100644 --- a/internal/route/repo/pull.go +++ b/internal/route/repo/pull.go @@ -15,7 +15,7 @@ import ( "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/form" - "gogs.io/gogs/internal/gitutil" + "gogs.io/gogs/internal/gitx" ) const ( @@ -199,7 +199,7 @@ func PrepareMergedViewPullInfo(c *context.Context, issue *database.Issue) { } } -func PrepareViewPullInfo(c *context.Context, issue *database.Issue) *gitutil.PullRequestMeta { +func PrepareViewPullInfo(c *context.Context, issue *database.Issue) *gitx.PullRequestMeta { repo := c.Repo.Repository pull := issue.PullRequest @@ -228,7 +228,7 @@ func PrepareViewPullInfo(c *context.Context, issue *database.Issue) *gitutil.Pul } baseRepoPath := database.RepoPath(repo.Owner.Name, repo.Name) - prMeta, err := gitutil.Module.PullRequestMeta(headGitRepo.Path(), baseRepoPath, pull.HeadBranch, pull.BaseBranch) + prMeta, err := gitx.Module.PullRequestMeta(headGitRepo.Path(), baseRepoPath, pull.HeadBranch, pull.BaseBranch) if err != nil { if strings.Contains(err.Error(), "fatal: Not a valid object name") { c.Data["IsPullReuqestBroken"] = true @@ -356,7 +356,7 @@ func ViewPullFiles(c *context.Context) { gitRepo = headGitRepo } - diff, err := gitutil.RepoDiff(diffGitRepo, + diff, err := gitx.RepoDiff(diffGitRepo, endCommitID, conf.Git.MaxDiffFiles, conf.Git.MaxDiffLines, conf.Git.MaxDiffLineChars, git.DiffOptions{Base: startCommitID, Timeout: time.Duration(conf.Git.Timeout.Diff) * time.Second}, ) @@ -430,7 +430,7 @@ func MergePullRequest(c *context.Context) { c.Redirect(c.Repo.RepoLink + "/pulls/" + strconv.FormatInt(pr.Index, 10)) } -func ParseCompareInfo(c *context.Context) (*database.User, *database.Repository, *git.Repository, *gitutil.PullRequestMeta, string, string) { +func ParseCompareInfo(c *context.Context) (*database.User, *database.Repository, *git.Repository, *gitx.PullRequestMeta, string, string) { baseRepo := c.Repo.Repository // Get compared refs information @@ -542,9 +542,9 @@ func ParseCompareInfo(c *context.Context) (*database.User, *database.Repository, c.Data["HeadBranches"] = headBranches baseRepoPath := database.RepoPath(baseRepo.Owner.Name, baseRepo.Name) - meta, err := gitutil.Module.PullRequestMeta(headGitRepo.Path(), baseRepoPath, headRef, baseRef) + meta, err := gitx.Module.PullRequestMeta(headGitRepo.Path(), baseRepoPath, headRef, baseRef) if err != nil { - if gitutil.IsErrNoMergeBase(err) { + if gitx.IsErrNoMergeBase(err) { c.Data["IsNoMergeBase"] = true c.Success(tmplRepoPullsCompare) } else { @@ -562,7 +562,7 @@ func PrepareCompareDiff( headUser *database.User, headRepo *database.Repository, headGitRepo *git.Repository, - meta *gitutil.PullRequestMeta, + meta *gitx.PullRequestMeta, headRef string, ) bool { var ( @@ -585,7 +585,7 @@ func PrepareCompareDiff( return true } - diff, err := gitutil.RepoDiff(headGitRepo, + diff, err := gitx.RepoDiff(headGitRepo, headCommitID, conf.Git.MaxDiffFiles, conf.Git.MaxDiffLines, conf.Git.MaxDiffLineChars, git.DiffOptions{Base: meta.MergeBase, Timeout: time.Duration(conf.Git.Timeout.Diff) * time.Second}, ) diff --git a/internal/route/repo/release.go b/internal/route/repo/release.go index 4682f5ace..ac28e72fd 100644 --- a/internal/route/repo/release.go +++ b/internal/route/repo/release.go @@ -12,7 +12,7 @@ import ( "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/form" - "gogs.io/gogs/internal/gitutil" + "gogs.io/gogs/internal/gitx" "gogs.io/gogs/internal/markup" ) @@ -48,7 +48,7 @@ func Releases(c *context.Context) { c.Data["PageIsViewFiles"] = true c.Data["PageIsReleaseList"] = true - tagsPage, err := gitutil.Module.ListTagsAfter(c.Repo.GitRepo.Path(), c.Query("after"), 10) + tagsPage, err := gitx.Module.ListTagsAfter(c.Repo.GitRepo.Path(), c.Query("after"), 10) if err != nil { c.Error(err, "get tags") return diff --git a/internal/route/repo/repo.go b/internal/route/repo/repo.go index d023dfba2..4280b3ec9 100644 --- a/internal/route/repo/repo.go +++ b/internal/route/repo/repo.go @@ -15,9 +15,9 @@ import ( "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/form" - "gogs.io/gogs/internal/osutil" + "gogs.io/gogs/internal/osx" "gogs.io/gogs/internal/tool" - "gogs.io/gogs/internal/urlutil" + "gogs.io/gogs/internal/urlx" ) const ( @@ -261,7 +261,7 @@ func Action(c *context.Context) { } redirectTo := c.Query("redirect_to") - if !urlutil.IsSameSite(redirectTo) { + if !urlx.IsSameSite(redirectTo) { redirectTo = c.Repo.RepoLink } c.Redirect(redirectTo) @@ -292,7 +292,7 @@ func Download(c *context.Context) { } refName = strings.TrimSuffix(uri, ext) - if !osutil.IsDir(archivePath) { + if !osx.IsDir(archivePath) { if err := os.MkdirAll(archivePath, os.ModePerm); err != nil { c.Error(err, "create archive directory") return @@ -329,7 +329,7 @@ func Download(c *context.Context) { } archivePath = path.Join(archivePath, tool.ShortSHA1(commit.ID.String())+ext) - if !osutil.IsFile(archivePath) { + if !osx.IsFile(archivePath) { if err := commit.CreateArchive(archiveFormat, archivePath); err != nil { c.Error(err, "creates archive") return diff --git a/internal/route/repo/setting.go b/internal/route/repo/setting.go index d6e5f8676..549e26e6e 100644 --- a/internal/route/repo/setting.go +++ b/internal/route/repo/setting.go @@ -17,9 +17,9 @@ import ( "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/email" "gogs.io/gogs/internal/form" - "gogs.io/gogs/internal/osutil" + "gogs.io/gogs/internal/osx" "gogs.io/gogs/internal/tool" - "gogs.io/gogs/internal/userutil" + "gogs.io/gogs/internal/userx" ) const ( @@ -263,7 +263,7 @@ func SettingsPost(c *context.Context, f form.RepoSetting) { log.Trace("Repository deleted: %s/%s", c.Repo.Owner.Name, repo.Name) c.Flash.Success(c.Tr("repo.settings.deletion_success")) - c.Redirect(userutil.DashboardURLPath(c.Repo.Owner.Name, c.Repo.Owner.IsOrganization())) + c.Redirect(userx.DashboardURLPath(c.Repo.Owner.Name, c.Repo.Owner.IsOrganization())) case "delete-wiki": if !c.Repo.IsOwner() { @@ -344,7 +344,7 @@ func UpdateAvatarSetting(c *context.Context, f form.Avatar, ctxRepo *database.Re } } else { // No avatar is uploaded and reset setting back. - if !osutil.IsFile(ctxRepo.CustomAvatarPath()) { + if !osx.IsFile(ctxRepo.CustomAvatarPath()) { ctxRepo.UseCustomAvatar = false } } @@ -598,7 +598,7 @@ func SettingsGitHooksEdit(c *context.Context) { hook, err := c.Repo.GitRepo.Hook("custom_hooks", name) if err != nil { - c.NotFoundOrError(osutil.NewError(err), "get hook") + c.NotFoundOrError(osx.NewError(err), "get hook") return } c.Data["Hook"] = hook @@ -614,7 +614,7 @@ func SettingsGitHooksEditPost(c *context.Context) { hook, err := c.Repo.GitRepo.Hook("custom_hooks", name) if err != nil { - c.NotFoundOrError(osutil.NewError(err), "get hook") + c.NotFoundOrError(osx.NewError(err), "get hook") return } if err = hook.Update(c.Query("content")); err != nil { diff --git a/internal/route/repo/tasks.go b/internal/route/repo/tasks.go index a743866a8..c0c1d9535 100644 --- a/internal/route/repo/tasks.go +++ b/internal/route/repo/tasks.go @@ -6,7 +6,7 @@ import ( "gopkg.in/macaron.v1" log "unknwon.dev/clog/v2" - "gogs.io/gogs/internal/cryptoutil" + "gogs.io/gogs/internal/cryptox" "gogs.io/gogs/internal/database" ) @@ -35,7 +35,7 @@ func TriggerTask(c *macaron.Context) { // 🚨 SECURITY: No need to check existence of the repository if the client // can't even get the valid secret. Mostly likely not a legitimate request. - if secret != cryptoutil.MD5(owner.Salt) { + if secret != cryptox.MD5(owner.Salt) { c.Error(http.StatusBadRequest, "Invalid secret") return } diff --git a/internal/route/repo/view.go b/internal/route/repo/view.go index 6d554e282..8edc6cbf1 100644 --- a/internal/route/repo/view.go +++ b/internal/route/repo/view.go @@ -15,7 +15,7 @@ import ( "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" - "gogs.io/gogs/internal/gitutil" + "gogs.io/gogs/internal/gitx" "gogs.io/gogs/internal/markup" "gogs.io/gogs/internal/template" "gogs.io/gogs/internal/template/highlight" @@ -32,7 +32,7 @@ const ( func renderDirectory(c *context.Context, treeLink string) { tree, err := c.Repo.Commit.Subtree(c.Repo.TreePath) if err != nil { - c.NotFoundOrError(gitutil.NewError(err), "get subtree") + c.NotFoundOrError(gitx.NewError(err), "get subtree") return } @@ -215,7 +215,7 @@ func renderFile(c *context.Context, entry *git.TreeEntry, treeLink, rawLink stri func setEditorconfigIfExists(c *context.Context) { ec, err := c.Repo.Editorconfig() - if err != nil && !gitutil.IsErrRevisionNotExist(err) { + if err != nil && !gitx.IsErrRevisionNotExist(err) { log.Warn("setEditorconfigIfExists.Editorconfig [repo_id: %d]: %v", c.Repo.Repository.ID, err) return } @@ -264,7 +264,7 @@ func Home(c *context.Context) { // Get current entry user currently looking at. entry, err := c.Repo.Commit.TreeEntry(c.Repo.TreePath) if err != nil { - c.NotFoundOrError(gitutil.NewError(err), "get tree entry") + c.NotFoundOrError(gitx.NewError(err), "get tree entry") return } diff --git a/internal/route/repo/webhook.go b/internal/route/repo/webhook.go index 0946c8b2b..51ae3d5ac 100644 --- a/internal/route/repo/webhook.go +++ b/internal/route/repo/webhook.go @@ -16,7 +16,7 @@ import ( "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/form" - "gogs.io/gogs/internal/netutil" + "gogs.io/gogs/internal/netx" apiv1types "gogs.io/gogs/internal/route/api/v1/types" ) @@ -124,7 +124,7 @@ func validateWebhook(l macaron.Locale, w *database.Webhook) (field, msg string, return "PayloadURL", l.Tr("repo.settings.webhook.err_cannot_parse_payload_url", err), http.StatusBadRequest } - if netutil.IsBlockedLocalHostname(payloadURL.Hostname(), conf.Security.LocalNetworkAllowlist) { + if netx.IsBlockedLocalHostname(payloadURL.Hostname(), conf.Security.LocalNetworkAllowlist) { return "PayloadURL", l.Tr("repo.settings.webhook.url_resolved_to_blocked_local_address"), http.StatusForbidden } return "", "", http.StatusOK diff --git a/internal/route/repo/wiki.go b/internal/route/repo/wiki.go index 42626d9c8..3e9d5e7a4 100644 --- a/internal/route/repo/wiki.go +++ b/internal/route/repo/wiki.go @@ -10,7 +10,7 @@ import ( "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/form" - "gogs.io/gogs/internal/gitutil" + "gogs.io/gogs/internal/gitx" "gogs.io/gogs/internal/markup" ) @@ -86,7 +86,7 @@ func renderWikiPage(c *context.Context, isViewPage bool) (*git.Repository, strin blob, err := commit.Blob(pageName + ".md") if err != nil { - if gitutil.IsErrRevisionNotExist(err) { + if gitx.IsErrRevisionNotExist(err) { c.Redirect(c.Repo.RepoLink + "/wiki/_pages") } else { c.Error(err, "get blob") diff --git a/internal/route/user/auth.go b/internal/route/user/auth.go index 125b568c1..adf2c1c95 100644 --- a/internal/route/user/auth.go +++ b/internal/route/user/auth.go @@ -18,8 +18,8 @@ import ( "gogs.io/gogs/internal/email" "gogs.io/gogs/internal/form" "gogs.io/gogs/internal/tool" - "gogs.io/gogs/internal/urlutil" - "gogs.io/gogs/internal/userutil" + "gogs.io/gogs/internal/urlx" + "gogs.io/gogs/internal/userx" ) const ( @@ -93,7 +93,7 @@ func Login(c *context.Context) { } if isSucceed { - if urlutil.IsSameSite(redirectTo) { + if urlx.IsSameSite(redirectTo) { c.Redirect(redirectTo) } else { c.RedirectSubpath("/") @@ -139,7 +139,7 @@ func afterLogin(c *context.Context, u *database.User, remember bool) { redirectTo, _ := url.QueryUnescape(c.GetCookie("redirect_to")) c.SetCookie("redirect_to", "", -1, conf.Server.Subpath) - if urlutil.IsSameSite(redirectTo) { + if urlx.IsSameSite(redirectTo) { c.Redirect(redirectTo) return } @@ -235,12 +235,12 @@ func LoginTwoFactorPost(c *context.Context) { } // Prevent same passcode from being reused - if c.Cache.IsExist(userutil.TwoFactorCacheKey(u.ID, passcode)) { + if c.Cache.IsExist(userx.TwoFactorCacheKey(u.ID, passcode)) { c.Flash.Error(c.Tr("settings.two_factor_reused_passcode")) c.RedirectSubpath("/user/login/two_factor") return } - if err = c.Cache.Put(userutil.TwoFactorCacheKey(u.ID, passcode), 1, 60); err != nil { + if err = c.Cache.Put(userx.TwoFactorCacheKey(u.ID, passcode), 1, 60); err != nil { log.Error("Failed to put cache 'two factor passcode': %v", err) } @@ -393,7 +393,7 @@ func SignUpPost(c *context.Context, cpt *captcha.Captcha, f form.Register) { c.Data["Hours"] = conf.Auth.ActivateCodeLives / 60 c.Success(TmplUserAuthActivate) - if err := c.Cache.Put(userutil.MailResendCacheKey(user.ID), 1, 180); err != nil { + if err := c.Cache.Put(userx.MailResendCacheKey(user.ID), 1, 180); err != nil { log.Error("Failed to put cache key 'mail resend': %v", err) } return @@ -467,7 +467,7 @@ func Activate(c *context.Context) { } // Resend confirmation email. if conf.Auth.RequireEmailConfirmation { - if c.Cache.IsExist(userutil.MailResendCacheKey(c.User.ID)) { + if c.Cache.IsExist(userx.MailResendCacheKey(c.User.ID)) { c.Data["ResendLimited"] = true } else { c.Data["Hours"] = conf.Auth.ActivateCodeLives / 60 @@ -475,7 +475,7 @@ func Activate(c *context.Context) { log.Error("Failed to send activate account mail: %v", err) } - if err := c.Cache.Put(userutil.MailResendCacheKey(c.User.ID), 1, 180); err != nil { + if err := c.Cache.Put(userx.MailResendCacheKey(c.User.ID), 1, 180); err != nil { log.Error("Failed to put cache key 'mail resend': %v", err) } } @@ -577,7 +577,7 @@ func ForgotPasswdPost(c *context.Context) { return } - if c.Cache.IsExist(userutil.MailResendCacheKey(u.ID)) { + if c.Cache.IsExist(userx.MailResendCacheKey(u.ID)) { c.Data["ResendLimited"] = true c.Success(tmplUserAuthForgotPassword) return @@ -586,7 +586,7 @@ func ForgotPasswdPost(c *context.Context) { if err = email.SendResetPasswordMail(c.Context, database.NewMailerUser(u)); err != nil { log.Error("Failed to send reset password mail: %v", err) } - if err = c.Cache.Put(userutil.MailResendCacheKey(u.ID), 1, 180); err != nil { + if err = c.Cache.Put(userx.MailResendCacheKey(u.ID), 1, 180); err != nil { log.Error("Failed to put cache key 'mail resend': %v", err) } diff --git a/internal/route/user/profile.go b/internal/route/user/profile.go index cb461d598..9da40a0ed 100644 --- a/internal/route/user/profile.go +++ b/internal/route/user/profile.go @@ -9,7 +9,7 @@ import ( "gogs.io/gogs/internal/context" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/route/repo" - "gogs.io/gogs/internal/urlutil" + "gogs.io/gogs/internal/urlx" ) const ( @@ -122,7 +122,7 @@ func Action(c *context.Context, puser *context.ParamsUser) { } redirectTo := c.Query("redirect_to") - if !urlutil.IsSameSite(redirectTo) { + if !urlx.IsSameSite(redirectTo) { redirectTo = puser.HomeURLPath() } c.Redirect(redirectTo) diff --git a/internal/route/user/setting.go b/internal/route/user/setting.go index 8e635490f..b642047ab 100644 --- a/internal/route/user/setting.go +++ b/internal/route/user/setting.go @@ -19,12 +19,12 @@ import ( "gogs.io/gogs/internal/auth" "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/context" - "gogs.io/gogs/internal/cryptoutil" + "gogs.io/gogs/internal/cryptox" "gogs.io/gogs/internal/database" "gogs.io/gogs/internal/email" "gogs.io/gogs/internal/form" "gogs.io/gogs/internal/tool" - "gogs.io/gogs/internal/userutil" + "gogs.io/gogs/internal/userx" ) // SettingsHandler is the handler for users settings endpoints. @@ -120,7 +120,7 @@ func SettingsPost(c *context.Context, f form.UpdateProfile) { // FIXME: limit upload size func UpdateAvatarSetting(c *context.Context, f form.Avatar, ctxUser *database.User) error { if f.Source == form.AvatarLookup && f.Gravatar != "" { - avatar := cryptoutil.MD5(f.Gravatar) + avatar := cryptox.MD5(f.Gravatar) err := database.Handle.Users().Update( c.Req.Context(), ctxUser.ID, @@ -204,7 +204,7 @@ func SettingsPasswordPost(c *context.Context, f form.ChangePassword) { return } - if !userutil.ValidatePassword(c.User.Password, c.User.Salt, f.OldPassword) { + if !userx.ValidatePassword(c.User.Password, c.User.Salt, f.OldPassword) { c.Flash.Error(c.Tr("settings.password_incorrect")) } else if f.Password != f.Retype { c.Flash.Error(c.Tr("form.password_not_match")) diff --git a/internal/semverutil/semverutil.go b/internal/semverx/semverx.go similarity index 97% rename from internal/semverutil/semverutil.go rename to internal/semverx/semverx.go index b2857c358..053c18fec 100644 --- a/internal/semverutil/semverutil.go +++ b/internal/semverx/semverx.go @@ -1,4 +1,4 @@ -package semverutil +package semverx import ( "strings" diff --git a/internal/semverutil/semverutil_test.go b/internal/semverx/semverx_test.go similarity index 97% rename from internal/semverutil/semverutil_test.go rename to internal/semverx/semverx_test.go index 01bc20707..9dfeb355b 100644 --- a/internal/semverutil/semverutil_test.go +++ b/internal/semverx/semverx_test.go @@ -1,4 +1,4 @@ -package semverutil +package semverx import ( "testing" diff --git a/internal/ssh/ssh.go b/internal/ssh/ssh.go index 6497681c5..20cf95a16 100644 --- a/internal/ssh/ssh.go +++ b/internal/ssh/ssh.go @@ -18,7 +18,7 @@ import ( "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/database" - "gogs.io/gogs/internal/osutil" + "gogs.io/gogs/internal/osx" ) func cleanCommand(cmd string) string { @@ -183,7 +183,7 @@ func setupHostKeys(appDataPath string, algorithms []string) ([]ssh.Signer, error var hostKeys []ssh.Signer for _, algo := range algorithms { keyPath := filepath.Join(dir, "gogs."+algo) - if !osutil.Exist(keyPath) { + if !osx.Exist(keyPath) { args := []string{ conf.SSH.KeygenPath, "-t", algo, diff --git a/internal/strutil/strutil.go b/internal/strx/strx.go similarity index 99% rename from internal/strutil/strutil.go rename to internal/strx/strx.go index 8cf2c739d..dd425278c 100644 --- a/internal/strutil/strutil.go +++ b/internal/strx/strx.go @@ -1,4 +1,4 @@ -package strutil +package strx import ( "crypto/rand" diff --git a/internal/strutil/strutil_test.go b/internal/strx/strx_test.go similarity index 99% rename from internal/strutil/strutil_test.go rename to internal/strx/strx_test.go index 79bade950..ed64acdb0 100644 --- a/internal/strutil/strutil_test.go +++ b/internal/strx/strx_test.go @@ -1,4 +1,4 @@ -package strutil +package strx import ( "testing" diff --git a/internal/template/template.go b/internal/template/template.go index eec2a1538..89a082d9c 100644 --- a/internal/template/template.go +++ b/internal/template/template.go @@ -20,11 +20,11 @@ import ( "github.com/gogs/git-module" "gogs.io/gogs/internal/conf" - "gogs.io/gogs/internal/cryptoutil" + "gogs.io/gogs/internal/cryptox" "gogs.io/gogs/internal/database" - "gogs.io/gogs/internal/gitutil" + "gogs.io/gogs/internal/gitx" "gogs.io/gogs/internal/markup" - "gogs.io/gogs/internal/strutil" + "gogs.io/gogs/internal/strx" "gogs.io/gogs/internal/tool" ) @@ -104,7 +104,7 @@ func FuncMap() []template.FuncMap { return str[start:end] }, "Join": strings.Join, - "EllipsisString": strutil.Ellipsis, + "EllipsisString": strx.Ellipsis, "DiffFileTypeToStr": DiffFileTypeToStr, "DiffLineTypeToStr": DiffLineTypeToStr, "Sha1": Sha1, @@ -128,7 +128,7 @@ func FuncMap() []template.FuncMap { } return "tab-size-8" }, - "InferSubmoduleURL": gitutil.InferSubmoduleURL, + "InferSubmoduleURL": gitx.InferSubmoduleURL, }} }) return funcMap @@ -148,7 +148,7 @@ func NewLine2br(raw string) string { } func Sha1(str string) string { - return cryptoutil.SHA1(str) + return cryptox.SHA1(str) } func ToUTF8WithErr(content []byte) (string, error) { diff --git a/internal/testutil/exec.go b/internal/testx/exec.go similarity index 98% rename from internal/testutil/exec.go rename to internal/testx/exec.go index 367100e7c..d4814dffb 100644 --- a/internal/testutil/exec.go +++ b/internal/testx/exec.go @@ -1,4 +1,4 @@ -package testutil +package testx import ( "os" diff --git a/internal/testutil/exec_test.go b/internal/testx/exec_test.go similarity index 98% rename from internal/testutil/exec_test.go rename to internal/testx/exec_test.go index 51ef5884e..1a290b22b 100644 --- a/internal/testutil/exec_test.go +++ b/internal/testx/exec_test.go @@ -1,4 +1,4 @@ -package testutil +package testx import ( "fmt" diff --git a/internal/testutil/golden.go b/internal/testx/golden.go similarity index 98% rename from internal/testutil/golden.go rename to internal/testx/golden.go index 3a9893c26..a469b00a4 100644 --- a/internal/testutil/golden.go +++ b/internal/testx/golden.go @@ -1,4 +1,4 @@ -package testutil +package testx import ( "encoding/json" diff --git a/internal/testutil/golden_test.go b/internal/testx/golden_test.go similarity index 98% rename from internal/testutil/golden_test.go rename to internal/testx/golden_test.go index 6e518b96d..73ea18891 100644 --- a/internal/testutil/golden_test.go +++ b/internal/testx/golden_test.go @@ -1,4 +1,4 @@ -package testutil +package testx import ( "path/filepath" diff --git a/internal/testutil/noop_logger.go b/internal/testx/noop_logger.go similarity index 96% rename from internal/testutil/noop_logger.go rename to internal/testx/noop_logger.go index 363a6d97e..ae6adc80c 100644 --- a/internal/testutil/noop_logger.go +++ b/internal/testx/noop_logger.go @@ -1,4 +1,4 @@ -package testutil +package testx import ( log "unknwon.dev/clog/v2" diff --git a/internal/testutil/testdata/golden b/internal/testx/testdata/golden similarity index 100% rename from internal/testutil/testdata/golden rename to internal/testx/testdata/golden diff --git a/internal/testutil/testutil.go b/internal/testx/testx.go similarity index 92% rename from internal/testutil/testutil.go rename to internal/testx/testx.go index 5c6992a24..9e55c18e6 100644 --- a/internal/testutil/testutil.go +++ b/internal/testx/testx.go @@ -1,4 +1,4 @@ -package testutil +package testx import ( "os" diff --git a/internal/testutil/testutil_test.go b/internal/testx/testx_test.go similarity index 87% rename from internal/testutil/testutil_test.go rename to internal/testx/testx_test.go index df424bef2..03ac74e01 100644 --- a/internal/testutil/testutil_test.go +++ b/internal/testx/testx_test.go @@ -1,4 +1,4 @@ -package testutil +package testx import ( "testing" diff --git a/internal/tool/tool.go b/internal/tool/tool.go index de6874d28..a1f42d3c7 100644 --- a/internal/tool/tool.go +++ b/internal/tool/tool.go @@ -18,7 +18,7 @@ import ( "github.com/gogs/chardet" "gogs.io/gogs/internal/conf" - "gogs.io/gogs/internal/cryptoutil" + "gogs.io/gogs/internal/cryptox" ) // ShortSHA1 truncates SHA1 string length to at most 10. @@ -121,7 +121,7 @@ func CreateTimeLimitCode(data string, minutes int, startInf any) string { // HashEmail hashes email address to MD5 string. // https://en.gravatar.com/site/implement/hash/ func HashEmail(email string) string { - return cryptoutil.MD5(strings.ToLower(strings.TrimSpace(email))) + return cryptox.MD5(strings.ToLower(strings.TrimSpace(email))) } // AvatarLink returns relative avatar link to the site domain by given email, diff --git a/internal/urlutil/urlutil.go b/internal/urlx/urlx.go similarity index 91% rename from internal/urlutil/urlutil.go rename to internal/urlx/urlx.go index afd378d82..e54ab2a92 100644 --- a/internal/urlutil/urlutil.go +++ b/internal/urlx/urlx.go @@ -1,4 +1,4 @@ -package urlutil +package urlx // IsSameSite returns true if the URL path belongs to the same site. func IsSameSite(url string) bool { diff --git a/internal/urlutil/urlutil_test.go b/internal/urlx/urlx_test.go similarity index 96% rename from internal/urlutil/urlutil_test.go rename to internal/urlx/urlx_test.go index f93843981..e4d9b6103 100644 --- a/internal/urlutil/urlutil_test.go +++ b/internal/urlx/urlx_test.go @@ -1,4 +1,4 @@ -package urlutil +package urlx import ( "testing" diff --git a/internal/userutil/userutil.go b/internal/userx/userx.go similarity index 97% rename from internal/userutil/userutil.go rename to internal/userx/userx.go index 91aa655e4..3a39b5cea 100644 --- a/internal/userutil/userutil.go +++ b/internal/userx/userx.go @@ -1,4 +1,4 @@ -package userutil +package userx import ( "bytes" @@ -19,7 +19,7 @@ import ( "gogs.io/gogs/internal/avatar" "gogs.io/gogs/internal/conf" - "gogs.io/gogs/internal/strutil" + "gogs.io/gogs/internal/strx" "gogs.io/gogs/internal/tool" ) @@ -134,5 +134,5 @@ func TwoFactorCacheKey(userID int64, passcode string) string { // RandomSalt returns randomly generated 10-character string that can be used as // the user salt. func RandomSalt() (string, error) { - return strutil.RandomChars(10) + return strx.RandomChars(10) } diff --git a/internal/userutil/userutil_test.go b/internal/userx/userx_test.go similarity index 97% rename from internal/userutil/userutil_test.go rename to internal/userx/userx_test.go index e30eea583..4d622079e 100644 --- a/internal/userutil/userutil_test.go +++ b/internal/userx/userx_test.go @@ -1,4 +1,4 @@ -package userutil +package userx import ( "os" @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/require" "gogs.io/gogs/internal/conf" - "gogs.io/gogs/internal/osutil" + "gogs.io/gogs/internal/osx" "gogs.io/gogs/internal/tool" "gogs.io/gogs/public" ) @@ -74,7 +74,7 @@ func TestGenerateRandomAvatar(t *testing.T) { err := GenerateRandomAvatar(1, "alice", "alice@example.com") require.NoError(t, err) - got := osutil.IsFile(avatarPath) + got := osx.IsFile(avatarPath) assert.True(t, got) } @@ -98,7 +98,7 @@ func TestSaveAvatar(t *testing.T) { err = SaveAvatar(1, avatar) require.NoError(t, err) - got := osutil.IsFile(avatarPath) + got := osx.IsFile(avatarPath) assert.True(t, got) } diff --git a/templates/embed.go b/templates/embed.go index 44b8277c2..945b17d0b 100644 --- a/templates/embed.go +++ b/templates/embed.go @@ -12,7 +12,7 @@ import ( "github.com/cockroachdb/errors" "gopkg.in/macaron.v1" - "gogs.io/gogs/internal/osutil" + "gogs.io/gogs/internal/osx" ) //go:embed *.tmpl **/* @@ -68,7 +68,7 @@ func NewTemplateFileSystem(dir, customDir string) macaron.TemplateFileSystem { // Check if corresponding custom file exists var data []byte fpath := path.Join(customDir, name) - if osutil.IsFile(fpath) { + if osx.IsFile(fpath) { data, err = os.ReadFile(fpath) } else { data, err = files.ReadFile(name)