mirror of
https://github.com/go-sigma/sigma.git
synced 2026-10-28 15:34:34 +08:00
refactor: apply go fix modernizations
Adopt modern Go and stdlib idioms surfaced by the modernize analyzer: promote embedded fields in struct literals, and replace hand-written equivalents with maps.Copy, min, atomic.Int64, new(expr) and slices.SortStableFunc. Verification: - go fix -diff ./... (no remaining changes) - go vet ./...
This commit is contained in:
1 parent
e7df1342b5
commit
c6b0f93ff4
18 files changed
+60
-80
No files matched your search
@@ -19,6 +19,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"maps"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
@@ -80,9 +81,7 @@ type testRunnerRepository struct {
|
||||
|
||||
func (r *testRunnerRepository) UpdateRunner(_ context.Context, _, _ string, updates map[string]any) error {
|
||||
clone := make(map[string]any, len(updates))
|
||||
for key, value := range updates {
|
||||
clone[key] = value
|
||||
}
|
||||
maps.Copy(clone, updates)
|
||||
r.updates = append(r.updates, clone)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -93,13 +93,11 @@ func (i instance) Start(ctx context.Context, builderConfig runtime.Config) error
|
||||
return err
|
||||
}
|
||||
_, err = i.client.CoreV1().Pods(i.config.Daemon.Builder.Kubernetes.Namespace).Create(ctx, &corev1.Pod{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: runtime.GenContainerID(builderConfig.BuilderID, builderConfig.RunnerID),
|
||||
Labels: map[string]string{
|
||||
"oci-image-builder": consts.AppName,
|
||||
"builder-id": builderConfig.BuilderID,
|
||||
"runner-id": builderConfig.RunnerID,
|
||||
},
|
||||
Name: runtime.GenContainerID(builderConfig.BuilderID, builderConfig.RunnerID),
|
||||
Labels: map[string]string{
|
||||
"oci-image-builder": consts.AppName,
|
||||
"builder-id": builderConfig.BuilderID,
|
||||
"runner-id": builderConfig.RunnerID,
|
||||
},
|
||||
Spec: corev1.PodSpec{
|
||||
HostAliases: buildHostAliases(builderConfig.ExtraHosts),
|
||||
|
||||
@@ -37,7 +37,7 @@ func (cr codeRepository) gitea(ctx context.Context, user3rdPartyObj *models.User
|
||||
|
||||
page := 1
|
||||
for {
|
||||
rs, _, err := client.ListMyRepos(gitea.ListReposOptions{ListOptions: gitea.ListOptions{Page: page, PageSize: perPage}})
|
||||
rs, _, err := client.ListMyRepos(gitea.ListReposOptions{Page: page, PageSize: perPage})
|
||||
if err != nil {
|
||||
slog.Error("list repositories failed", "err", err)
|
||||
return fmt.Errorf("list repositories failed: %v", err)
|
||||
@@ -53,7 +53,7 @@ func (cr codeRepository) gitea(ctx context.Context, user3rdPartyObj *models.User
|
||||
|
||||
page = 1
|
||||
for {
|
||||
os, _, err := client.ListMyOrgs(gitea.ListOrgsOptions{ListOptions: gitea.ListOptions{Page: page, PageSize: perPage}})
|
||||
os, _, err := client.ListMyOrgs(gitea.ListOrgsOptions{Page: page, PageSize: perPage})
|
||||
if err != nil {
|
||||
slog.Error("list organizations failed", "err", err)
|
||||
return fmt.Errorf("list organizations failed: %v", err)
|
||||
@@ -68,7 +68,7 @@ func (cr codeRepository) gitea(ctx context.Context, user3rdPartyObj *models.User
|
||||
for _, o := range orgs {
|
||||
page = 1
|
||||
for {
|
||||
rs, _, err := client.ListOrgRepos(o.Name, gitea.ListOrgReposOptions{ListOptions: gitea.ListOptions{Page: page, PageSize: perPage}})
|
||||
rs, _, err := client.ListOrgRepos(o.Name, gitea.ListOrgReposOptions{Page: page, PageSize: perPage})
|
||||
if err != nil {
|
||||
slog.Error("list repositories failed", "err", err)
|
||||
return fmt.Errorf("list repositories failed: %v", err)
|
||||
|
||||
@@ -42,7 +42,7 @@ func (cr codeRepository) github(ctx context.Context, user3rdPartyObj *models.Use
|
||||
|
||||
page := 1
|
||||
for {
|
||||
rs, _, err := client.Repositories.List(ctx, "", &github.RepositoryListOptions{ListOptions: github.ListOptions{Page: page, PerPage: perPage}}) // nolint: staticcheck
|
||||
rs, _, err := client.Repositories.List(ctx, "", &github.RepositoryListOptions{Page: page, PerPage: perPage}) // nolint: staticcheck
|
||||
if err != nil {
|
||||
slog.Error("list repositories failed", "err", err)
|
||||
return fmt.Errorf("list repositories failed: %v", err)
|
||||
@@ -78,7 +78,7 @@ func (cr codeRepository) github(ctx context.Context, user3rdPartyObj *models.Use
|
||||
page = 1
|
||||
for {
|
||||
rs, _, err := client.Repositories.ListByOrg(ctx, ptr.To(o.Login),
|
||||
&github.RepositoryListByOrgOptions{ListOptions: github.ListOptions{Page: page, PerPage: perPage}})
|
||||
&github.RepositoryListByOrgOptions{Page: page, PerPage: perPage})
|
||||
if err != nil {
|
||||
slog.Error("list repositories for orgs failed", "err", err)
|
||||
return fmt.Errorf("list repositories for orgs failed: %v", err)
|
||||
@@ -116,7 +116,7 @@ func (cr codeRepository) github(ctx context.Context, user3rdPartyObj *models.Use
|
||||
var branches []*models.CodeRepositoryBranch
|
||||
page = 1
|
||||
for {
|
||||
bs, _, err := client.Repositories.ListBranches(ctx, r.Owner, r.Name, &github.BranchListOptions{ListOptions: github.ListOptions{Page: page, PerPage: perPage}})
|
||||
bs, _, err := client.Repositories.ListBranches(ctx, r.Owner, r.Name, &github.BranchListOptions{Page: page, PerPage: perPage})
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "Repository access blocked") {
|
||||
blockedRepo.Insert(r.RepositoryID)
|
||||
|
||||
@@ -50,8 +50,8 @@ func (cr codeRepository) gitlab(ctx context.Context, user3rdPartyObj *models.Use
|
||||
page := int64(1)
|
||||
for {
|
||||
rs, _, err := client.Projects.ListProjects(&gitlab.ListProjectsOptions{
|
||||
Owned: new(true),
|
||||
ListOptions: gitlab.ListOptions{Page: page, PerPage: perPage}})
|
||||
Owned: new(true),
|
||||
Page: page, PerPage: perPage})
|
||||
if err != nil {
|
||||
slog.Error("list projects from gitlab failed", "err", err)
|
||||
return fmt.Errorf("list projects from gitlab failed: %w", err)
|
||||
@@ -75,7 +75,7 @@ func (cr codeRepository) gitlab(ctx context.Context, user3rdPartyObj *models.Use
|
||||
gs, _, err := client.Groups.ListGroups(&gitlab.ListGroupsOptions{
|
||||
AllAvailable: new(true),
|
||||
MinAccessLevel: &minAccessLevel,
|
||||
ListOptions: gitlab.ListOptions{Page: page, PerPage: perPage}})
|
||||
Page: page, PerPage: perPage})
|
||||
if err != nil {
|
||||
slog.Error("list groups from gitlab failed", "err", err)
|
||||
return fmt.Errorf("list groups from gitlab failed: %w", err)
|
||||
@@ -93,7 +93,7 @@ func (cr codeRepository) gitlab(ctx context.Context, user3rdPartyObj *models.Use
|
||||
minAccessLevel := gitlab.ReporterPermissions
|
||||
rs, _, err := client.Groups.ListGroupProjects(g.ID, &gitlab.ListGroupProjectsOptions{
|
||||
MinAccessLevel: &minAccessLevel,
|
||||
ListOptions: gitlab.ListOptions{Page: page, PerPage: perPage}})
|
||||
Page: page, PerPage: perPage})
|
||||
if err != nil {
|
||||
slog.Error("list projects from gitlab failed", "err", err)
|
||||
return fmt.Errorf("list projects from gitlab failed: %w", err)
|
||||
@@ -129,7 +129,7 @@ func (cr codeRepository) gitlab(ctx context.Context, user3rdPartyObj *models.Use
|
||||
var branches []*models.CodeRepositoryBranch
|
||||
page = 1
|
||||
for {
|
||||
bs, _, err := client.Branches.ListBranches(r.RepositoryID, &gitlab.ListBranchesOptions{ListOptions: gitlab.ListOptions{Page: page, PerPage: perPage}})
|
||||
bs, _, err := client.Branches.ListBranches(r.RepositoryID, &gitlab.ListBranchesOptions{Page: page, PerPage: perPage})
|
||||
if err != nil {
|
||||
slog.Error("list branches failed", "err", err, "owner", r.Owner, "repo", r.Name)
|
||||
return fmt.Errorf("list branches for repo(%s/%s) failed: %v", r.Owner, r.Name, err)
|
||||
|
||||
@@ -199,10 +199,8 @@ func (g *gcArtifact) deleteArtifactsInRepository(ctx context.Context, daemonRepo
|
||||
|
||||
func (g *gcArtifact) packWebhookObj(action enums.WebhookAction) api.WebhookPayloadGcArtifact {
|
||||
payload := api.WebhookPayloadGcArtifact{
|
||||
WebhookPayload: api.WebhookPayload{
|
||||
ResourceType: enums.WebhookResourceTypeDaemonTaskGcArtifactRunner,
|
||||
Action: action,
|
||||
},
|
||||
ResourceType: enums.WebhookResourceTypeDaemonTaskGcArtifactRunner,
|
||||
Action: action,
|
||||
OperateType: g.runnerObj.OperateType,
|
||||
SuccessCount: g.successCount,
|
||||
FailedCount: g.failedCount,
|
||||
|
||||
@@ -182,10 +182,8 @@ func (g *gcBlob) deleteBlobObject(ctx context.Context, runner models.DaemonGcBlo
|
||||
|
||||
func (g *gcBlob) packWebhookObj(action enums.WebhookAction) api.WebhookPayloadGcBlob {
|
||||
payload := api.WebhookPayloadGcBlob{
|
||||
WebhookPayload: api.WebhookPayload{
|
||||
ResourceType: enums.WebhookResourceTypeDaemonTaskGcBlobRunner,
|
||||
Action: action,
|
||||
},
|
||||
ResourceType: enums.WebhookResourceTypeDaemonTaskGcBlobRunner,
|
||||
Action: action,
|
||||
OperateType: g.runnerObj.OperateType,
|
||||
SuccessCount: g.successCount,
|
||||
FailedCount: g.failedCount,
|
||||
|
||||
@@ -156,10 +156,8 @@ func (g *gcRepository) deleteRepositoriesInNamespace(ctx context.Context, daemon
|
||||
|
||||
func (g *gcRepository) packWebhookObj(action enums.WebhookAction) api.WebhookPayloadGcRepository {
|
||||
payload := api.WebhookPayloadGcRepository{
|
||||
WebhookPayload: api.WebhookPayload{
|
||||
ResourceType: enums.WebhookResourceTypeDaemonTaskGcRepositoryRunner,
|
||||
Action: action,
|
||||
},
|
||||
ResourceType: enums.WebhookResourceTypeDaemonTaskGcRepositoryRunner,
|
||||
Action: action,
|
||||
OperateType: g.runnerObj.OperateType,
|
||||
SuccessCount: g.successCount,
|
||||
FailedCount: g.failedCount,
|
||||
|
||||
@@ -203,10 +203,8 @@ func (g *gcTag) deleteTagsInRepository(ctx context.Context, daemonRepository rep
|
||||
|
||||
func (g *gcTag) packWebhookObj(action enums.WebhookAction) api.WebhookPayloadGcTag {
|
||||
payload := api.WebhookPayloadGcTag{
|
||||
WebhookPayload: api.WebhookPayload{
|
||||
ResourceType: enums.WebhookResourceTypeDaemonTaskGcTagRunner,
|
||||
Action: action,
|
||||
},
|
||||
ResourceType: enums.WebhookResourceTypeDaemonTaskGcTagRunner,
|
||||
Action: action,
|
||||
OperateType: g.runnerObj.OperateType,
|
||||
SuccessCount: g.successCount,
|
||||
FailedCount: g.failedCount,
|
||||
|
||||
@@ -179,7 +179,7 @@ func TestArtifactRepository(t *testing.T) {
|
||||
|
||||
limit := 10
|
||||
listed, err := artifactRepository.ListArtifact(ctx, api.ListArtifactRequest{
|
||||
Pagination: api.Pagination{Limit: &limit},
|
||||
Limit: &limit,
|
||||
Namespace: fixture.Namespace.Name,
|
||||
Repository: fixture.Repository.Name,
|
||||
})
|
||||
|
||||
@@ -72,9 +72,9 @@ func TestAcquireSerializesConcurrentAccess(t *testing.T) {
|
||||
key = "test-redis-lock-concurrent"
|
||||
concurrent = 10
|
||||
)
|
||||
var active int64
|
||||
var maxActive int64
|
||||
var entered int64
|
||||
var active atomic.Int64
|
||||
var maxActive atomic.Int64
|
||||
var entered atomic.Int64
|
||||
var wg sync.WaitGroup
|
||||
start := make(chan struct{})
|
||||
|
||||
@@ -84,25 +84,25 @@ func TestAcquireSerializesConcurrentAccess(t *testing.T) {
|
||||
heldLock, err := lockerInst.Acquire(t.Context(), key, 500*time.Millisecond, 5*time.Second)
|
||||
require.NoError(t, err)
|
||||
|
||||
current := atomic.AddInt64(&active, 1)
|
||||
current := active.Add(1)
|
||||
for {
|
||||
observed := atomic.LoadInt64(&maxActive)
|
||||
if current <= observed || atomic.CompareAndSwapInt64(&maxActive, observed, current) {
|
||||
observed := maxActive.Load()
|
||||
if current <= observed || maxActive.CompareAndSwap(observed, current) {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
atomic.AddInt64(&active, -1)
|
||||
active.Add(-1)
|
||||
require.NoError(t, heldLock.Unlock(t.Context()))
|
||||
atomic.AddInt64(&entered, 1)
|
||||
entered.Add(1)
|
||||
})
|
||||
}
|
||||
close(start)
|
||||
wg.Wait()
|
||||
|
||||
require.EqualValues(t, concurrent, entered)
|
||||
require.EqualValues(t, 1, maxActive)
|
||||
require.EqualValues(t, concurrent, entered.Load())
|
||||
require.EqualValues(t, 1, maxActive.Load())
|
||||
}
|
||||
|
||||
func TestAcquireTimesOutWhenLockIsHeld(t *testing.T) {
|
||||
|
||||
@@ -17,6 +17,7 @@ package workq
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"maps"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -118,9 +119,7 @@ func (r *handlerRegistry) Handlers() map[enums.Daemon]Consumer {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
handlers := make(map[enums.Daemon]Consumer, len(r.handlers))
|
||||
for topic, consumer := range r.handlers {
|
||||
handlers[topic] = consumer
|
||||
}
|
||||
maps.Copy(handlers, r.handlers)
|
||||
return handlers
|
||||
}
|
||||
|
||||
|
||||
@@ -15,11 +15,12 @@
|
||||
package distribution
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sort"
|
||||
"slices"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/dig"
|
||||
@@ -72,8 +73,8 @@ func RegisterRouterFactory(factory Factory, index int) error {
|
||||
}
|
||||
}
|
||||
routerFactories = append(routerFactories, Item{Key: index, Value: factory})
|
||||
sort.SliceStable(routerFactories, func(i, j int) bool {
|
||||
return routerFactories[i].Key < routerFactories[j].Key
|
||||
slices.SortStableFunc(routerFactories, func(a, b Item) int {
|
||||
return cmp.Compare(a.Key, b.Key)
|
||||
})
|
||||
return nil
|
||||
}
|
||||
@@ -30,9 +30,9 @@ type toolFunc func(context.Context, mcp.CallToolRequest) (any, error)
|
||||
func (s *Server) addTool(mcpServer *mcpsdk.MCPServer, name, description string, write bool, handler toolFunc) {
|
||||
tool := mcp.NewTool(name, mcp.WithDescription(description), mcp.WithSchemaAdditionalProperties(true))
|
||||
tool.Annotations = mcp.ToolAnnotation{
|
||||
ReadOnlyHint: mcp.ToBoolPtr(!write),
|
||||
DestructiveHint: mcp.ToBoolPtr(write),
|
||||
OpenWorldHint: mcp.ToBoolPtr(false),
|
||||
ReadOnlyHint: new(!write),
|
||||
DestructiveHint: new(write),
|
||||
OpenWorldHint: new(false),
|
||||
}
|
||||
mcpServer.AddTool(tool, s.wrapTool(name, write, handler))
|
||||
}
|
||||
|
||||
@@ -234,10 +234,7 @@ func (c *Config) loginRateLimitDelay(ctx context.Context, username string) {
|
||||
if count < int64(cfg.MaxFailures) {
|
||||
return
|
||||
}
|
||||
delay := cfg.Delay
|
||||
if delay > maxLoginRateLimitDelay {
|
||||
delay = maxLoginRateLimitDelay
|
||||
}
|
||||
delay := min(cfg.Delay, maxLoginRateLimitDelay)
|
||||
ratelimit.RecordDelayed()
|
||||
timer := time.NewTimer(delay)
|
||||
defer timer.Stop()
|
||||
|
||||
@@ -30,15 +30,11 @@ func TestCreateBuilderValidator(t *testing.T) {
|
||||
dockerfile := base64.StdEncoding.EncodeToString([]byte("FROM scratch"))
|
||||
|
||||
require.NoError(t, createBuilderValidator(api.CreateBuilderRequest{
|
||||
PostOrPutBuilderRequest: api.PostOrPutBuilderRequest{
|
||||
Source: enums.BuilderSourceDockerfile,
|
||||
Dockerfile: &dockerfile,
|
||||
},
|
||||
Source: enums.BuilderSourceDockerfile,
|
||||
Dockerfile: &dockerfile,
|
||||
}))
|
||||
require.Error(t, createBuilderValidator(api.CreateBuilderRequest{
|
||||
PostOrPutBuilderRequest: api.PostOrPutBuilderRequest{
|
||||
Source: enums.BuilderSourceDockerfile,
|
||||
},
|
||||
Source: enums.BuilderSourceDockerfile,
|
||||
}))
|
||||
require.Error(t, createBuilderValidator(api.CreateBuilderRequest{}))
|
||||
}
|
||||
|
||||
@@ -924,10 +924,10 @@ func (s *service) GetReferrer(ctx context.Context, repository string, dgst strin
|
||||
}
|
||||
|
||||
result := imgspecv1.Index{
|
||||
MediaType: imgspecv1.MediaTypeImageIndex,
|
||||
Manifests: make([]imgspecv1.Descriptor, 0, len(artifactObjs)),
|
||||
MediaType: imgspecv1.MediaTypeImageIndex,
|
||||
Manifests: make([]imgspecv1.Descriptor, 0, len(artifactObjs)),
|
||||
SchemaVersion: 2,
|
||||
}
|
||||
result.SchemaVersion = 2
|
||||
for _, artifactObj := range artifactObjs {
|
||||
raw, readErr := s.readManifest(ctx, artifactObj.Digest)
|
||||
if readErr != nil {
|
||||
|
||||
@@ -117,15 +117,13 @@ func NewWithConfig(configuration *config.Configuration, redisClientFactory dalre
|
||||
func (s *service) New(id string, expire time.Duration) (string, error) {
|
||||
now := time.Now()
|
||||
claims := JWTClaims{
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
Subject: id,
|
||||
Issuer: consts.AppName,
|
||||
ExpiresAt: jwt.NewNumericDate(now.Add(expire)),
|
||||
NotBefore: jwt.NewNumericDate(now),
|
||||
IssuedAt: jwt.NewNumericDate(now),
|
||||
ID: uuid.NewV7String(),
|
||||
},
|
||||
UID: id,
|
||||
Subject: id,
|
||||
Issuer: consts.AppName,
|
||||
ExpiresAt: jwt.NewNumericDate(now.Add(expire)),
|
||||
NotBefore: jwt.NewNumericDate(now),
|
||||
IssuedAt: jwt.NewNumericDate(now),
|
||||
ID: uuid.NewV7String(),
|
||||
UID: id,
|
||||
}
|
||||
token, err := jwt.NewWithClaims(jwt.SigningMethodEdDSA, claims).SignedString(s.privateKey)
|
||||
if err != nil {
|
||||
|
||||
Reference in new issue
Block a user