Skip to content

Commit 4f27c28

Browse files
authored
Remove legacy unknwon/com package (#19298)
Follows: #19284 * The `CopyDir` is only used inside test code * Rewrite `ToSnakeCase` with more test cases * The `RedisCacher` only put strings into cache, here we use internal `toStr` to replace the legacy `ToStr` * The `UniqueQueue` can use string as ID directly, no need to call `ToStr`
1 parent 4c5cb1e commit 4f27c28

File tree

17 files changed

+353
-58
lines changed

17 files changed

+353
-58
lines changed

cmd/manager_logging.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111

1212
"code.gitea.io/gitea/modules/log"
1313
"code.gitea.io/gitea/modules/private"
14+
1415
"github.com/urfave/cli"
1516
)
1617

contrib/pr/checkout.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ func runPR() {
112112
unittest.LoadFixtures()
113113
util.RemoveAll(setting.RepoRootPath)
114114
util.RemoveAll(models.LocalCopyPath())
115-
util.CopyDir(path.Join(curDir, "integrations/gitea-repositories-meta"), setting.RepoRootPath)
115+
unittest.CopyDir(path.Join(curDir, "integrations/gitea-repositories-meta"), setting.RepoRootPath)
116116

117117
log.Printf("[PR] Setting up router\n")
118118
// routers.GlobalInit()

go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,6 @@ require (
7878
github.com/stretchr/testify v1.7.0
7979
github.com/syndtr/goleveldb v1.0.0
8080
github.com/tstranex/u2f v1.0.0
81-
github.com/unknwon/com v1.0.1
8281
github.com/unknwon/i18n v0.0.0-20210904045753-ff3a8617e361
8382
github.com/unknwon/paginater v0.0.0-20200328080006-042474bd0eae
8483
github.com/unrolled/render v1.4.1
@@ -251,6 +250,7 @@ require (
251250
github.com/tmc/grpc-websocket-proxy v0.0.0-20201229170055-e5319fda7802 // indirect
252251
github.com/toqueteos/webbrowser v1.2.0 // indirect
253252
github.com/ulikunitz/xz v0.5.10 // indirect
253+
github.com/unknwon/com v1.0.1 // indirect
254254
github.com/x448/float16 v0.8.4 // indirect
255255
github.com/xanzy/ssh-agent v0.3.1 // indirect
256256
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8 // indirect

integrations/integration_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -254,7 +254,7 @@ func prepareTestEnv(t testing.TB, skip ...int) func() {
254254
assert.NoError(t, unittest.LoadFixtures())
255255
assert.NoError(t, util.RemoveAll(setting.RepoRootPath))
256256

257-
assert.NoError(t, util.CopyDir(path.Join(filepath.Dir(setting.AppPath), "integrations/gitea-repositories-meta"), setting.RepoRootPath))
257+
assert.NoError(t, unittest.CopyDir(path.Join(filepath.Dir(setting.AppPath), "integrations/gitea-repositories-meta"), setting.RepoRootPath))
258258
ownerDirs, err := os.ReadDir(setting.RepoRootPath)
259259
if err != nil {
260260
assert.NoError(t, err, "unable to read the new repo root: %v\n", err)
@@ -550,7 +550,7 @@ func resetFixtures(t *testing.T) {
550550
assert.NoError(t, queue.GetManager().FlushAll(context.Background(), -1))
551551
assert.NoError(t, unittest.LoadFixtures())
552552
assert.NoError(t, util.RemoveAll(setting.RepoRootPath))
553-
assert.NoError(t, util.CopyDir(path.Join(filepath.Dir(setting.AppPath), "integrations/gitea-repositories-meta"), setting.RepoRootPath))
553+
assert.NoError(t, unittest.CopyDir(path.Join(filepath.Dir(setting.AppPath), "integrations/gitea-repositories-meta"), setting.RepoRootPath))
554554
ownerDirs, err := os.ReadDir(setting.RepoRootPath)
555555
if err != nil {
556556
assert.NoError(t, err, "unable to read the new repo root: %v\n", err)

integrations/migration-test/migration_test.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import (
2121
"code.gitea.io/gitea/integrations"
2222
"code.gitea.io/gitea/models/db"
2323
"code.gitea.io/gitea/models/migrations"
24+
"code.gitea.io/gitea/models/unittest"
2425
"code.gitea.io/gitea/modules/base"
2526
"code.gitea.io/gitea/modules/charset"
2627
"code.gitea.io/gitea/modules/git"
@@ -60,7 +61,7 @@ func initMigrationTest(t *testing.T) func() {
6061

6162
assert.True(t, len(setting.RepoRootPath) != 0)
6263
assert.NoError(t, util.RemoveAll(setting.RepoRootPath))
63-
assert.NoError(t, util.CopyDir(path.Join(filepath.Dir(setting.AppPath), "integrations/gitea-repositories-meta"), setting.RepoRootPath))
64+
assert.NoError(t, unittest.CopyDir(path.Join(filepath.Dir(setting.AppPath), "integrations/gitea-repositories-meta"), setting.RepoRootPath))
6465
ownerDirs, err := os.ReadDir(setting.RepoRootPath)
6566
if err != nil {
6667
assert.NoError(t, err, "unable to read the new repo root: %v\n", err)

models/migrations/migrations_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,7 @@ func prepareTestEnv(t *testing.T, skip int, syncModels ...interface{}) (*xorm.En
203203
deferFn := PrintCurrentTest(t, ourSkip)
204204
assert.NoError(t, os.RemoveAll(setting.RepoRootPath))
205205

206-
assert.NoError(t, util.CopyDir(path.Join(filepath.Dir(setting.AppPath), "integrations/gitea-repositories-meta"),
206+
assert.NoError(t, unittest.CopyDir(path.Join(filepath.Dir(setting.AppPath), "integrations/gitea-repositories-meta"),
207207
setting.RepoRootPath))
208208
ownerDirs, err := os.ReadDir(setting.RepoRootPath)
209209
if err != nil {

models/unittest/fscopy.go

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
// Copyright 2022 The Gitea Authors. All rights reserved.
2+
// Use of this source code is governed by a MIT-style
3+
// license that can be found in the LICENSE file.
4+
5+
package unittest
6+
7+
import (
8+
"errors"
9+
"io"
10+
"os"
11+
"path"
12+
"strings"
13+
14+
"code.gitea.io/gitea/modules/util"
15+
)
16+
17+
// Copy copies file from source to target path.
18+
func Copy(src, dest string) error {
19+
// Gather file information to set back later.
20+
si, err := os.Lstat(src)
21+
if err != nil {
22+
return err
23+
}
24+
25+
// Handle symbolic link.
26+
if si.Mode()&os.ModeSymlink != 0 {
27+
target, err := os.Readlink(src)
28+
if err != nil {
29+
return err
30+
}
31+
// NOTE: os.Chmod and os.Chtimes don't recognize symbolic link,
32+
// which will lead "no such file or directory" error.
33+
return os.Symlink(target, dest)
34+
}
35+
36+
sr, err := os.Open(src)
37+
if err != nil {
38+
return err
39+
}
40+
defer sr.Close()
41+
42+
dw, err := os.Create(dest)
43+
if err != nil {
44+
return err
45+
}
46+
defer dw.Close()
47+
48+
if _, err = io.Copy(dw, sr); err != nil {
49+
return err
50+
}
51+
52+
// Set back file information.
53+
if err = os.Chtimes(dest, si.ModTime(), si.ModTime()); err != nil {
54+
return err
55+
}
56+
return os.Chmod(dest, si.Mode())
57+
}
58+
59+
// CopyDir copy files recursively from source to target directory.
60+
//
61+
// The filter accepts a function that process the path info.
62+
// and should return true for need to filter.
63+
//
64+
// It returns error when error occurs in underlying functions.
65+
func CopyDir(srcPath, destPath string, filters ...func(filePath string) bool) error {
66+
// Check if target directory exists.
67+
if _, err := os.Stat(destPath); !errors.Is(err, os.ErrNotExist) {
68+
return errors.New("file or directory already exists: " + destPath)
69+
}
70+
71+
err := os.MkdirAll(destPath, os.ModePerm)
72+
if err != nil {
73+
return err
74+
}
75+
76+
// Gather directory info.
77+
infos, err := util.StatDir(srcPath, true)
78+
if err != nil {
79+
return err
80+
}
81+
82+
var filter func(filePath string) bool
83+
if len(filters) > 0 {
84+
filter = filters[0]
85+
}
86+
87+
for _, info := range infos {
88+
if filter != nil && filter(info) {
89+
continue
90+
}
91+
92+
curPath := path.Join(destPath, info)
93+
if strings.HasSuffix(info, "/") {
94+
err = os.MkdirAll(curPath, os.ModePerm)
95+
} else {
96+
err = Copy(path.Join(srcPath, info), curPath)
97+
}
98+
if err != nil {
99+
return err
100+
}
101+
}
102+
return nil
103+
}

models/unittest/testdb.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ func MainTest(m *testing.M, pathToGiteaRoot string, fixtureFiles ...string) {
104104
if err = util.RemoveAll(repoRootPath); err != nil {
105105
fatalTestError("util.RemoveAll: %v\n", err)
106106
}
107-
if err = util.CopyDir(filepath.Join(pathToGiteaRoot, "integrations", "gitea-repositories-meta"), setting.RepoRootPath); err != nil {
107+
if err = CopyDir(filepath.Join(pathToGiteaRoot, "integrations", "gitea-repositories-meta"), setting.RepoRootPath); err != nil {
108108
fatalTestError("util.CopyDir: %v\n", err)
109109
}
110110

@@ -175,7 +175,7 @@ func PrepareTestEnv(t testing.TB) {
175175
assert.NoError(t, PrepareTestDatabase())
176176
assert.NoError(t, util.RemoveAll(setting.RepoRootPath))
177177
metaPath := filepath.Join(giteaRoot, "integrations", "gitea-repositories-meta")
178-
assert.NoError(t, util.CopyDir(metaPath, setting.RepoRootPath))
178+
assert.NoError(t, CopyDir(metaPath, setting.RepoRootPath))
179179

180180
ownerDirs, err := os.ReadDir(setting.RepoRootPath)
181181
assert.NoError(t, err)

modules/cache/cache_redis.go

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,11 @@ package cache
66

77
import (
88
"fmt"
9+
"strconv"
910
"time"
1011

1112
"code.gitea.io/gitea/modules/graceful"
1213
"code.gitea.io/gitea/modules/nosql"
13-
"code.gitea.io/gitea/modules/util"
1414

1515
"gitea.com/go-chi/cache"
1616
"github.com/go-redis/redis/v8"
@@ -24,20 +24,37 @@ type RedisCacher struct {
2424
occupyMode bool
2525
}
2626

27-
// Put puts value into cache with key and expire time.
27+
// toStr convert string/int/int64 interface to string. it's only used by the RedisCacher.Put internally
28+
func toStr(v interface{}) string {
29+
if v == nil {
30+
return ""
31+
}
32+
switch v := v.(type) {
33+
case string:
34+
return v
35+
case []byte:
36+
return string(v)
37+
case int:
38+
return strconv.FormatInt(int64(v), 10)
39+
case int64:
40+
return strconv.FormatInt(v, 10)
41+
default:
42+
return fmt.Sprint(v) // as what the old com.ToStr does in most cases
43+
}
44+
}
45+
46+
// Put puts value (string type) into cache with key and expire time.
2847
// If expired is 0, it lives forever.
2948
func (c *RedisCacher) Put(key string, val interface{}, expire int64) error {
49+
// this function is not well-designed, it only puts string values into cache
3050
key = c.prefix + key
3151
if expire == 0 {
32-
if err := c.c.Set(graceful.GetManager().HammerContext(), key, util.ToStr(val), 0).Err(); err != nil {
52+
if err := c.c.Set(graceful.GetManager().HammerContext(), key, toStr(val), 0).Err(); err != nil {
3353
return err
3454
}
3555
} else {
36-
dur, err := time.ParseDuration(util.ToStr(expire) + "s")
37-
if err != nil {
38-
return err
39-
}
40-
if err = c.c.Set(graceful.GetManager().HammerContext(), key, util.ToStr(val), dur).Err(); err != nil {
56+
dur := time.Duration(expire) * time.Second
57+
if err := c.c.Set(graceful.GetManager().HammerContext(), key, toStr(val), dur).Err(); err != nil {
4158
return err
4259
}
4360
}

modules/context/csrf.go

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,10 @@ import (
2222
"encoding/base32"
2323
"fmt"
2424
"net/http"
25+
"strconv"
2526
"time"
2627

28+
"code.gitea.io/gitea/modules/log"
2729
"code.gitea.io/gitea/modules/setting"
2830
"code.gitea.io/gitea/modules/util"
2931
"code.gitea.io/gitea/modules/web/middleware"
@@ -215,9 +217,16 @@ func Csrfer(opt CsrfOptions, ctx *Context) CSRF {
215217
}
216218

217219
x.ID = "0"
218-
uid := ctx.Session.Get(opt.SessionKey)
219-
if uid != nil {
220-
x.ID = util.ToStr(uid)
220+
uidAny := ctx.Session.Get(opt.SessionKey)
221+
if uidAny != nil {
222+
switch uidVal := uidAny.(type) {
223+
case string:
224+
x.ID = uidVal
225+
case int64:
226+
x.ID = strconv.FormatInt(uidVal, 10)
227+
default:
228+
log.Error("invalid uid type in session: %T", uidAny)
229+
}
221230
}
222231

223232
needsNew := false

modules/nosql/manager.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
"time"
1212

1313
"code.gitea.io/gitea/modules/process"
14+
1415
"github.com/go-redis/redis/v8"
1516
"github.com/syndtr/goleveldb/leveldb"
1617
)

modules/sync/unique_queue.go

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,6 @@
55

66
package sync
77

8-
import "code.gitea.io/gitea/modules/util"
9-
108
// UniqueQueue is a queue which guarantees only one instance of same
119
// identity is in the line. Instances with same identity will be
1210
// discarded if there is already one in the line.
@@ -53,10 +51,10 @@ func (q *UniqueQueue) IsClosed() <-chan struct{} {
5351
}
5452

5553
// IDs returns the current ids in the pool
56-
func (q *UniqueQueue) IDs() []interface{} {
54+
func (q *UniqueQueue) IDs() []string {
5755
q.table.lock.Lock()
5856
defer q.table.lock.Unlock()
59-
ids := make([]interface{}, 0, len(q.table.pool))
57+
ids := make([]string, 0, len(q.table.pool))
6058
for id := range q.table.pool {
6159
ids = append(ids, id)
6260
}
@@ -70,38 +68,37 @@ func (q *UniqueQueue) Queue() <-chan string {
7068

7169
// Exist returns true if there is an instance with given identity
7270
// exists in the queue.
73-
func (q *UniqueQueue) Exist(id interface{}) bool {
74-
return q.table.IsRunning(util.ToStr(id))
71+
func (q *UniqueQueue) Exist(id string) bool {
72+
return q.table.IsRunning(id)
7573
}
7674

7775
// AddFunc adds new instance to the queue with a custom runnable function,
7876
// the queue is blocked until the function exits.
79-
func (q *UniqueQueue) AddFunc(id interface{}, fn func()) {
80-
idStr := util.ToStr(id)
77+
func (q *UniqueQueue) AddFunc(id string, fn func()) {
8178
q.table.lock.Lock()
82-
if _, ok := q.table.pool[idStr]; ok {
79+
if _, ok := q.table.pool[id]; ok {
8380
q.table.lock.Unlock()
8481
return
8582
}
86-
q.table.pool[idStr] = struct{}{}
83+
q.table.pool[id] = struct{}{}
8784
if fn != nil {
8885
fn()
8986
}
9087
q.table.lock.Unlock()
9188
select {
9289
case <-q.closed:
9390
return
94-
case q.queue <- idStr:
91+
case q.queue <- id:
9592
return
9693
}
9794
}
9895

9996
// Add adds new instance to the queue.
100-
func (q *UniqueQueue) Add(id interface{}) {
97+
func (q *UniqueQueue) Add(id string) {
10198
q.AddFunc(id, nil)
10299
}
103100

104101
// Remove removes instance from the queue.
105-
func (q *UniqueQueue) Remove(id interface{}) {
106-
q.table.Stop(util.ToStr(id))
102+
func (q *UniqueQueue) Remove(id string) {
103+
q.table.Stop(id)
107104
}

0 commit comments

Comments
 (0)