Skip to content

Commit b9f1896

Browse files
authored
Merge pull request sipeed#861 from p3ddd/refactor/modernize
refactor(modernize): apply safe modernize fixes
2 parents 8bc76a4 + 50539eb commit b9f1896

27 files changed

Lines changed: 88 additions & 119 deletions

pkg/agent/context.go

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"os"
88
"path/filepath"
99
"runtime"
10+
"slices"
1011
"strings"
1112
"sync"
1213
"time"
@@ -249,10 +250,8 @@ func (cb *ContextBuilder) sourceFilesChangedLocked() bool {
249250
}
250251

251252
// Check tracked source files (bootstrap + memory).
252-
for _, p := range cb.sourcePaths() {
253-
if cb.fileChangedSince(p) {
254-
return true
255-
}
253+
if slices.ContainsFunc(cb.sourcePaths(), cb.fileChangedSince) {
254+
return true
256255
}
257256

258257
// --- Skills directory (handled separately from sourcePaths) ---

pkg/agent/context_cache_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -404,11 +404,11 @@ func TestConcurrentBuildSystemPromptWithCache(t *testing.T) {
404404
var wg sync.WaitGroup
405405
errs := make(chan string, goroutines*iterations)
406406

407-
for g := 0; g < goroutines; g++ {
407+
for g := range goroutines {
408408
wg.Add(1)
409409
go func(id int) {
410410
defer wg.Done()
411-
for i := 0; i < iterations; i++ {
411+
for i := range iterations {
412412
result := cb.BuildSystemPromptWithCache()
413413
if result == "" {
414414
errs <- "empty prompt returned"

pkg/agent/loop_test.go

Lines changed: 3 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"fmt"
66
"os"
77
"path/filepath"
8+
"slices"
89
"testing"
910
"time"
1011

@@ -187,13 +188,7 @@ func TestToolRegistry_ToolRegistration(t *testing.T) {
187188
toolsList := toolsInfo["names"].([]string)
188189

189190
// Check that our custom tool name is in the list
190-
found := false
191-
for _, name := range toolsList {
192-
if name == "mock_custom" {
193-
found = true
194-
break
195-
}
196-
}
191+
found := slices.Contains(toolsList, "mock_custom")
197192
if !found {
198193
t.Error("Expected custom tool to be registered")
199194
}
@@ -262,13 +257,7 @@ func TestToolRegistry_GetDefinitions(t *testing.T) {
262257
toolsList := toolsInfo["names"].([]string)
263258

264259
// Check that our custom tool name is in the list
265-
found := false
266-
for _, name := range toolsList {
267-
if name == "mock_custom" {
268-
found = true
269-
break
270-
}
271-
}
260+
found := slices.Contains(toolsList, "mock_custom")
272261
if !found {
273262
t.Error("Expected custom tool to be registered")
274263
}

pkg/agent/memory.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ func (ms *MemoryStore) GetRecentDailyNotes(days int) string {
111111
var sb strings.Builder
112112
first := true
113113

114-
for i := 0; i < days; i++ {
114+
for i := range days {
115115
date := time.Now().AddDate(0, 0, -i)
116116
dateStr := date.Format("20060102") // YYYYMMDD
117117
monthDir := dateStr[:6] // YYYYMM

pkg/bus/bus_test.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ func TestPublishInbound_ContextCancel(t *testing.T) {
6767

6868
// Fill the buffer
6969
ctx := context.Background()
70-
for i := 0; i < defaultBusBufferSize; i++ {
70+
for i := range defaultBusBufferSize {
7171
if err := mb.PublishInbound(ctx, InboundMessage{Content: "fill"}); err != nil {
7272
t.Fatalf("fill failed at %d: %v", i, err)
7373
}
@@ -154,7 +154,7 @@ func TestConcurrentPublishClose(t *testing.T) {
154154
wg.Add(numGoroutines + 1)
155155

156156
// Spawn many goroutines trying to publish
157-
for i := 0; i < numGoroutines; i++ {
157+
for range numGoroutines {
158158
go func() {
159159
defer wg.Done()
160160
// Use a short timeout context so we don't block forever after close
@@ -194,7 +194,7 @@ func TestPublishInbound_FullBuffer(t *testing.T) {
194194
ctx := context.Background()
195195

196196
// Fill the buffer
197-
for i := 0; i < defaultBusBufferSize; i++ {
197+
for i := range defaultBusBufferSize {
198198
if err := mb.PublishInbound(ctx, InboundMessage{Content: "fill"}); err != nil {
199199
t.Fatalf("fill failed at %d: %v", i, err)
200200
}

pkg/channels/manager_test.go

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -274,13 +274,12 @@ func TestWorkerRateLimiter(t *testing.T) {
274274
limiter: rate.NewLimiter(2, 1),
275275
}
276276

277-
ctx, cancel := context.WithCancel(context.Background())
278-
defer cancel()
277+
ctx := t.Context()
279278

280279
go m.runWorker(ctx, "test", w)
281280

282281
// Enqueue 4 messages
283-
for i := 0; i < 4; i++ {
282+
for i := range 4 {
284283
w.queue <- bus.OutboundMessage{Channel: "test", ChatID: "1", Content: fmt.Sprintf("msg%d", i)}
285284
}
286285

@@ -352,8 +351,7 @@ func TestRunWorker_MessageSplitting(t *testing.T) {
352351
limiter: rate.NewLimiter(rate.Inf, 1),
353352
}
354353

355-
ctx, cancel := context.WithCancel(context.Background())
356-
defer cancel()
354+
ctx := t.Context()
357355

358356
go m.runWorker(ctx, "test", w)
359357

@@ -576,7 +574,7 @@ func TestRecordPlaceholder_ConcurrentSafe(t *testing.T) {
576574
m := newTestManager()
577575

578576
var wg sync.WaitGroup
579-
for i := 0; i < 100; i++ {
577+
for i := range 100 {
580578
wg.Add(1)
581579
go func(i int) {
582580
defer wg.Done()
@@ -591,7 +589,7 @@ func TestRecordTypingStop_ConcurrentSafe(t *testing.T) {
591589
m := newTestManager()
592590

593591
var wg sync.WaitGroup
594-
for i := 0; i < 100; i++ {
592+
for i := range 100 {
595593
wg.Add(1)
596594
go func(i int) {
597595
defer wg.Done()
@@ -834,7 +832,7 @@ func TestLazyWorkerCreation(t *testing.T) {
834832
func TestBuildMediaScope_FastIDUniqueness(t *testing.T) {
835833
seen := make(map[string]bool)
836834

837-
for i := 0; i < 1000; i++ {
835+
for range 1000 {
838836
scope := BuildMediaScope("test", "chat1", "")
839837
if seen[scope] {
840838
t.Fatalf("duplicate scope generated: %s", scope)

pkg/channels/onebot/onebot.go

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -337,10 +337,7 @@ func (c *OneBotChannel) sendAPIRequest(action string, params any, timeout time.D
337337
}
338338

339339
func (c *OneBotChannel) reconnectLoop() {
340-
interval := time.Duration(c.config.ReconnectInterval) * time.Second
341-
if interval < 5*time.Second {
342-
interval = 5 * time.Second
343-
}
340+
interval := max(time.Duration(c.config.ReconnectInterval)*time.Second, 5*time.Second)
344341

345342
for {
346343
select {

pkg/channels/pico/pico.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -292,8 +292,8 @@ func (c *PicoChannel) authenticate(r *http.Request) bool {
292292

293293
// Check Authorization header
294294
auth := r.Header.Get("Authorization")
295-
if strings.HasPrefix(auth, "Bearer ") {
296-
if strings.TrimPrefix(auth, "Bearer ") == token {
295+
if after, ok := strings.CutPrefix(auth, "Bearer "); ok {
296+
if after == token {
297297
return true
298298
}
299299
}

pkg/channels/split.go

Lines changed: 8 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,7 @@ func SplitMessage(content string, maxLen int) []string {
2323
var messages []string
2424

2525
// Dynamic buffer: 10% of maxLen, but at least 50 chars if possible
26-
codeBlockBuffer := maxLen / 10
27-
if codeBlockBuffer < 50 {
28-
codeBlockBuffer = 50
29-
}
26+
codeBlockBuffer := max(maxLen/10, 50)
3027
if codeBlockBuffer > maxLen/2 {
3128
codeBlockBuffer = maxLen / 2
3229
}
@@ -40,10 +37,7 @@ func SplitMessage(content string, maxLen int) []string {
4037
}
4138

4239
// Effective split point: maxLen minus buffer, to leave room for code blocks
43-
effectiveLimit := maxLen - codeBlockBuffer
44-
if effectiveLimit < maxLen/2 {
45-
effectiveLimit = maxLen / 2
46-
}
40+
effectiveLimit := max(maxLen-codeBlockBuffer, maxLen/2)
4741

4842
end := start + effectiveLimit
4943

@@ -85,10 +79,9 @@ func SplitMessage(content string, maxLen int) []string {
8579
// If we have a reasonable amount of content after the header, split inside
8680
if msgEnd > headerEndIdx+20 {
8781
// Find a better split point closer to maxLen
88-
innerLimit := start + maxLen - 5 // Leave room for "\n```"
89-
if innerLimit > totalLen {
90-
innerLimit = totalLen
91-
}
82+
innerLimit := min(
83+
// Leave room for "\n```"
84+
start+maxLen-5, totalLen)
9285
betterEnd := findLastNewlineInRange(runes, start, innerLimit, 200)
9386
if betterEnd > headerEndIdx {
9487
msgEnd = betterEnd
@@ -117,10 +110,7 @@ func SplitMessage(content string, maxLen int) []string {
117110
if unclosedIdx-start > 20 {
118111
msgEnd = unclosedIdx
119112
} else {
120-
splitAt := start + maxLen - 5
121-
if splitAt > totalLen {
122-
splitAt = totalLen
123-
}
113+
splitAt := min(start+maxLen-5, totalLen)
124114
chunk := strings.TrimRight(string(runes[start:splitAt]), " \t\n\r") + "\n```"
125115
messages = append(messages, chunk)
126116
remaining := strings.TrimSpace(header + "\n" + string(runes[splitAt:totalLen]))
@@ -196,10 +186,7 @@ func findNewlineFrom(runes []rune, from int) int {
196186
// findLastNewlineInRange finds the last newline within the last searchWindow runes
197187
// of the range runes[start:end]. Returns the absolute index or start-1 (indicating not found).
198188
func findLastNewlineInRange(runes []rune, start, end, searchWindow int) int {
199-
searchStart := end - searchWindow
200-
if searchStart < start {
201-
searchStart = start
202-
}
189+
searchStart := max(end-searchWindow, start)
203190
for i := end - 1; i >= searchStart; i-- {
204191
if runes[i] == '\n' {
205192
return i
@@ -211,10 +198,7 @@ func findLastNewlineInRange(runes []rune, start, end, searchWindow int) int {
211198
// findLastSpaceInRange finds the last space/tab within the last searchWindow runes
212199
// of the range runes[start:end]. Returns the absolute index or start-1 (indicating not found).
213200
func findLastSpaceInRange(runes []rune, start, end, searchWindow int) int {
214-
searchStart := end - searchWindow
215-
if searchStart < start {
216-
searchStart = start
217-
}
201+
searchStart := max(end-searchWindow, start)
218202
for i := end - 1; i >= searchStart; i-- {
219203
if runes[i] == ' ' || runes[i] == '\t' {
220204
return i

pkg/channels/wecom/app_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ func encryptTestMessageApp(message, aesKey string) (string, error) {
4343

4444
// Prepare message: random(16) + msg_len(4) + msg + corp_id
4545
random := make([]byte, 0, 16)
46-
for i := 0; i < 16; i++ {
46+
for i := range 16 {
4747
random = append(random, byte(i+1))
4848
}
4949

0 commit comments

Comments
 (0)