Skip to content

internal: Simplify code by using modern constructs #2113

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
May 17, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion internal/filter/value.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func ValueOf(obj any, field string) any {
}
}

for i := 0; i < value.NumField(); i++ {
for i := range value.NumField() {
fieldValue := value.Field(i)
fieldType := typ.Field(i)
yaml := fieldType.Tag.Get("yaml")
Expand Down
2 changes: 1 addition & 1 deletion internal/linux/kernel.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ func Uname() (*Utsname, error) {
func intArrayToString(arr any) string {
slice := reflect.ValueOf(arr)
s := ""
for i := 0; i < slice.Len(); i++ {
for i := range slice.Len() {
val := slice.Index(i)
valInt := int64(-1)

Expand Down
4 changes: 2 additions & 2 deletions internal/server/apparmor/qemuimg_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ func TestHandleWriter(t *testing.T) {
status = append(status, percent)
})}

for i := 0; i < 101; i++ {
for j := 0; j < 100; j++ {
for i := range 101 {
for j := range 100 {
n, err := fmt.Fprintf(out, "\t (%02d.%02d/100%s)\r", i, j, "%")
if err != nil {
t.Fatal(err, n)
Expand Down
60 changes: 24 additions & 36 deletions internal/server/auth/driver_tls.go
Original file line number Diff line number Diff line change
Expand Up @@ -242,15 +242,12 @@ func (t *TLS) GetInstanceAccess(ctx context.Context, projectName string, instanc
}

// Restricted
for _, proj := range certificateProjects {
if proj == projectName {
access = append(access, api.AccessEntry{
Identifier: fingerprint,
Role: "operator",
Provider: "tls",
})
break
}
if slices.Contains(certificateProjects, projectName) {
access = append(access, api.AccessEntry{
Identifier: fingerprint,
Role: "operator",
Provider: "tls",
})
}
}

Expand All @@ -270,15 +267,12 @@ func (t *TLS) GetInstanceAccess(ctx context.Context, projectName string, instanc
}

// Restricted
for _, proj := range certificateProjects {
if proj == projectName {
access = append(access, api.AccessEntry{
Identifier: fingerprint,
Role: "view",
Provider: "tls",
})
break
}
if slices.Contains(certificateProjects, projectName) {
access = append(access, api.AccessEntry{
Identifier: fingerprint,
Role: "view",
Provider: "tls",
})
}
}

Expand All @@ -304,15 +298,12 @@ func (t *TLS) GetProjectAccess(ctx context.Context, projectName string) (*api.Ac
})
}

for _, project := range certificateProjects {
if project == projectName {
access = append(access, api.AccessEntry{
Identifier: fingerprint,
Role: "operator",
Provider: "tls",
})
break
}
if slices.Contains(certificateProjects, projectName) {
access = append(access, api.AccessEntry{
Identifier: fingerprint,
Role: "operator",
Provider: "tls",
})
}
}

Expand All @@ -327,15 +318,12 @@ func (t *TLS) GetProjectAccess(ctx context.Context, projectName string) (*api.Ac
})
}

for _, project := range certificateProjects {
if project == projectName {
access = append(access, api.AccessEntry{
Identifier: fingerprint,
Role: "view",
Provider: "tls",
})
break
}
if slices.Contains(certificateProjects, projectName) {
access = append(access, api.AccessEntry{
Identifier: fingerprint,
Role: "view",
Provider: "tls",
})
}
}

Expand Down
17 changes: 5 additions & 12 deletions internal/server/bgp/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package bgp
import (
"context"
"fmt"
"maps"
"net"
"strconv"
"sync"
Expand Down Expand Up @@ -113,9 +114,7 @@ func (s *Server) start(address string, asn uint32, routerID net.IP) error {

// Copy the path list
oldPaths := map[string]path{}
for pathUUID, path := range s.paths {
oldPaths[pathUUID] = path
}
maps.Copy(oldPaths, s.paths)

// Add existing paths.
s.paths = map[string]path{}
Expand All @@ -128,9 +127,7 @@ func (s *Server) start(address string, asn uint32, routerID net.IP) error {

// Copy the peer list.
oldPeers := map[string]peer{}
for peerUUID, peer := range s.peers {
oldPeers[peerUUID] = peer
}
maps.Copy(oldPeers, s.peers)

// Add existing peers.
s.peers = map[string]peer{}
Expand Down Expand Up @@ -158,9 +155,7 @@ func (s *Server) stop() error {

// Save the peer list.
oldPeers := map[string]peer{}
for peerUUID, peer := range s.peers {
oldPeers[peerUUID] = peer
}
maps.Copy(oldPeers, s.peers)

// Remove all the peers.
for _, peer := range s.peers {
Expand Down Expand Up @@ -332,9 +327,7 @@ func (s *Server) RemovePrefixByOwner(owner string) error {

// Make a copy of the paths dict to safely iterate (path removal mutates it).
paths := map[string]path{}
for pathUUID, path := range s.paths {
paths[pathUUID] = path
}
maps.Copy(paths, s.paths)

// Iterate through the paths and remove them from the server.
for pathUUID, path := range paths {
Expand Down
9 changes: 3 additions & 6 deletions internal/server/certificate/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package certificate

import (
"crypto/x509"
"maps"
"sync"
)

Expand Down Expand Up @@ -50,9 +51,7 @@ func (c *Cache) GetCertificatesAndProjects() (map[Type]map[string]x509.Certifica
certificates := make(map[Type]map[string]x509.Certificate, len(c.certificates))
for t, m := range c.certificates {
certificates[t] = make(map[string]x509.Certificate, len(m))
for f, cert := range m {
certificates[t][f] = cert
}
maps.Copy(certificates[t], m)
}

projects := make(map[string][]string, len(c.projects))
Expand All @@ -73,9 +72,7 @@ func (c *Cache) GetCertificates() map[Type]map[string]x509.Certificate {
certificates := make(map[Type]map[string]x509.Certificate, len(c.certificates))
for t, m := range c.certificates {
certificates[t] = make(map[string]x509.Certificate, len(m))
for f, cert := range m {
certificates[t][f] = cert
}
maps.Copy(certificates[t], m)
}

return certificates
Expand Down
5 changes: 2 additions & 3 deletions internal/server/cgroup/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bufio"
"errors"
"io/fs"
"maps"
"os"
"path/filepath"
"strings"
Expand Down Expand Up @@ -407,9 +408,7 @@ func Init() {
hasV2Root = true
break
} else {
for k, v := range unifiedControllers {
cgControllers[k] = v
}
maps.Copy(cgControllers, unifiedControllers)
}
}

Expand Down
5 changes: 2 additions & 3 deletions internal/server/cluster/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package config
import (
"context"
"fmt"
"maps"
"strconv"
"strings"
"time"
Expand Down Expand Up @@ -418,9 +419,7 @@ func (c *Config) Replace(values map[string]string) (map[string]string, error) {
// Return what has actually changed.
func (c *Config) Patch(patch map[string]string) (map[string]string, error) {
values := c.Dump() // Use current values as defaults
for name, value := range patch {
values[name] = value
}
maps.Copy(values, patch)

return c.update(values)
}
Expand Down
8 changes: 1 addition & 7 deletions internal/server/cluster/events.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,13 +133,7 @@ func ServerEventMode() EventMode {

// RoleInSlice returns whether or not the rule is within the roles list.
func RoleInSlice(role db.ClusterRole, roles []db.ClusterRole) bool {
for _, r := range roles {
if r == role {
return true
}
}

return false
return slices.Contains(roles, role)
}

// EventListenerWait waits for there to be listener connected to the specified address, or one of the event hubs
Expand Down
2 changes: 1 addition & 1 deletion internal/server/cluster/gateway.go
Original file line number Diff line number Diff line change
Expand Up @@ -865,7 +865,7 @@ func (g *Gateway) init(bootstrap bool) error {
func (g *Gateway) WaitLeadership() error {
n := 80
sleep := 250 * time.Millisecond
for i := 0; i < n; i++ {
for range n {
g.lock.RLock()
isLeader, err := g.isLeader()
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion internal/server/cluster/membership.go
Original file line number Diff line number Diff line change
Expand Up @@ -843,7 +843,7 @@ assign:
}

notified := false
for i := 0; i < 10; i++ {
for range 10 {
time.Sleep(500 * time.Millisecond)
servers, err := local.Cluster(context.Background())
if err != nil {
Expand Down
4 changes: 2 additions & 2 deletions internal/server/cluster/notify_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,13 +151,13 @@ type notifyFixtures struct {
// cluster.https_address.
func (h *notifyFixtures) Nodes(cert *localtls.CertInfo, n int) func() {
servers := make([]*httptest.Server, n)
for i := 0; i < n; i++ {
for i := range n {
servers[i] = newRestServer(cert)
}

// Insert new entries in the nodes table of the cluster database.
err := h.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
for i := 0; i < n; i++ {
for i := range n {
name := strconv.Itoa(i)
address := servers[i].Listener.Addr().String()
var err error
Expand Down
4 changes: 2 additions & 2 deletions internal/server/cluster/upgrade_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ func TestMaybeUpdate_Upgrade(t *testing.T) {
// Create a stub upgrade script that just touches a stamp file.
stamp := filepath.Join(dir, "stamp")
script := filepath.Join(dir, "cluster-upgrade")
data := []byte(fmt.Sprintf("#!/bin/sh\ntouch %s\n", stamp))
data := fmt.Appendf(nil, "#!/bin/sh\ntouch %s\n", stamp)
err = os.WriteFile(script, data, 0o755)
require.NoError(t, err)

Expand Down Expand Up @@ -126,7 +126,7 @@ func TestMaybeUpdate_NothingToDo(t *testing.T) {
// Create a stub upgrade script that just touches a stamp file.
stamp := filepath.Join(dir, "stamp")
script := filepath.Join(dir, "cluster-upgrade")
data := []byte(fmt.Sprintf("#!/bin/sh\ntouch %s\n", stamp))
data := fmt.Appendf(nil, "#!/bin/sh\ntouch %s\n", stamp)
err = os.WriteFile(script, data, 0o755)
require.NoError(t, err)

Expand Down
2 changes: 1 addition & 1 deletion internal/server/db/cluster/entities.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ func URLToEntityType(rawURL string) (int, string, string, []string, error) {
// Make an []any for the number of expected path arguments and set each value in the slice to a *string.
nPathArgs := strings.Count(spaceSeparatedEntityPath, "%s")
pathArgsAny := make([]any, 0, nPathArgs)
for i := 0; i < nPathArgs; i++ {
for range nPathArgs {
var pathComponentStr string
pathArgsAny = append(pathArgsAny, &pathComponentStr)
}
Expand Down
17 changes: 5 additions & 12 deletions internal/server/db/cluster/profiles.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package cluster
import (
"context"
"database/sql"
"maps"

"github.com/lxc/incus/v6/internal/server/device/config"
"github.com/lxc/incus/v6/shared/api"
Expand Down Expand Up @@ -132,15 +133,11 @@ func ExpandInstanceConfig(config map[string]string, profiles []api.Profile) map[
}

for i := range profileConfigs {
for k, v := range profileConfigs[i] {
expandedConfig[k] = v
}
maps.Copy(expandedConfig, profileConfigs[i])
}

// Stick the given config on top
for k, v := range config {
expandedConfig[k] = v
}
maps.Copy(expandedConfig, config)

return expandedConfig
}
Expand All @@ -157,15 +154,11 @@ func ExpandInstanceDevices(devices config.Devices, profiles []api.Profile) confi
}

for i := range profileDevices {
for k, v := range profileDevices[i] {
expandedDevices[k] = v
}
maps.Copy(expandedDevices, profileDevices[i])
}

// Stick the given devices on top
for k, v := range devices {
expandedDevices[k] = v
}
maps.Copy(expandedDevices, devices)

return expandedDevices
}
Expand Down
4 changes: 2 additions & 2 deletions internal/server/db/cluster/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -2147,7 +2147,7 @@ func updateFromV42(ctx context.Context, tx *sql.Tx) error {
rowIDs := strings.Split(r.dupeRowIDs, ",")

// Iterate and delete all but 1 of the rowIDs so we leave just one left.
for i := 0; i < len(rowIDs)-1; i++ {
for i := range len(rowIDs) - 1 {
rowID, err := strconv.Atoi(rowIDs[i])
if err != nil {
return fmt.Errorf("Failed converting row ID: %w", err)
Expand Down Expand Up @@ -2213,7 +2213,7 @@ func updateFromV41(ctx context.Context, tx *sql.Tx) error {
rowIDs := strings.Split(r.dupeRowIDs, ",")

// Iterate and delete all but 1 of the rowIDs so we leave just one left.
for i := 0; i < len(rowIDs)-1; i++ {
for i := range len(rowIDs) - 1 {
rowID, err := strconv.Atoi(rowIDs[i])
if err != nil {
return fmt.Errorf("Failed converting row ID: %w", err)
Expand Down
2 changes: 1 addition & 1 deletion internal/server/db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -390,7 +390,7 @@ func (c *Cluster) Begin() (*sql.Tx, error) {
}

func begin(db *sql.DB) (*sql.Tx, error) {
for i := 0; i < 1000; i++ {
for range 1000 {
tx, err := db.Begin()
if err == nil {
return tx, nil
Expand Down
Loading