From 4239e30618ffeb847f5e7dbd5483dae22627fc90 Mon Sep 17 00:00:00 2001 From: Kir Kolyshkin Date: Thu, 14 Aug 2025 14:57:59 -0700 Subject: [PATCH 01/10] pkg/machine/e2e: remove obsoleted comment The code which comment refers to was removed by commit 2e4e1bb97c ("podman machine ssh handling"), so the comment is no longer valid. Remove it. Signed-off-by: Kir Kolyshkin --- pkg/machine/e2e/basic_test.go | 2 -- 1 file changed, 2 deletions(-) diff --git a/pkg/machine/e2e/basic_test.go b/pkg/machine/e2e/basic_test.go index 499d2730b1..12ff7161c7 100644 --- a/pkg/machine/e2e/basic_test.go +++ b/pkg/machine/e2e/basic_test.go @@ -25,8 +25,6 @@ const TESTIMAGE = "quay.io/libpod/testimage:20241011" var _ = Describe("run basic podman commands", func() { It("Basic ops", func() { - // golangci-lint has trouble with actually skipping tests marked Skip - // so skip it on cirrus envs and where CIRRUS_CI isn't set. name := randomString() i := new(initMachine) session, err := mb.setName(name).setCmd(i.withImage(mb.imagePath).withNow()).run() From 7d4fdc2828f11ba0b51cfa0f95e41fc2d16565af Mon Sep 17 00:00:00 2001 From: Kir Kolyshkin Date: Thu, 14 Aug 2025 15:02:36 -0700 Subject: [PATCH 02/10] Replace interface{} with any Since Go 1.18, any is a type alias for interface{}. Brought to you by modernize -test -fix -category=efaceany ./... Signed-off-by: Kir Kolyshkin --- cmd/podman/common/completion.go | 4 ++-- cmd/podman/images/search.go | 2 +- cmd/podman/inspect/inspect.go | 8 +++---- cmd/podman/main.go | 4 ++-- cmd/podman/quadlet/quadlet.go | 4 ++-- cmd/podman/system/df.go | 2 +- cmd/podman/utils/utils.go | 2 +- cmd/quadlet/main.go | 8 +++---- libpod/container_internal.go | 2 +- libpod/define/config.go | 2 +- libpod/define/container_inspect.go | 6 ++--- libpod/define/info.go | 24 +++++++++---------- libpod/define/volume_inspect.go | 2 +- libpod/info.go | 6 ++--- libpod/plugin/volume_api.go | 2 +- libpod/util.go | 2 +- .../handlers/compat/containers_stats_linux.go | 2 +- pkg/api/handlers/utils/handler.go | 4 ++-- pkg/api/handlers/utils/handler_test.go | 4 ++-- pkg/auth/auth_test.go | 8 +++---- pkg/bindings/connection.go | 2 +- pkg/bindings/errors.go | 6 ++--- pkg/bindings/internal/util/util.go | 6 ++--- pkg/domain/infra/abi/generate.go | 2 +- pkg/domain/infra/abi/play.go | 2 +- pkg/domain/utils/utils.go | 2 +- pkg/k8s.io/api/core/v1/types.go | 2 +- .../apimachinery/pkg/api/resource/quantity.go | 2 +- .../pkg/api/resource/scale_int.go | 2 +- .../apimachinery/pkg/apis/meta/v1/duration.go | 2 +- .../apimachinery/pkg/apis/meta/v1/time.go | 2 +- .../apimachinery/pkg/apis/meta/v1/types.go | 2 +- pkg/logiface/logiface.go | 8 +++---- pkg/machine/e2e/config_test.go | 8 +++---- pkg/specgen/generate/security_linux.go | 4 ++-- pkg/systemd/dbus.go | 4 ++-- pkg/systemd/quadlet/podmancmdline.go | 2 +- pkg/trust/policy_test.go | 4 ++-- pkg/util/utils_linux.go | 2 +- test/e2e/login_logout_test.go | 6 ++--- test/e2e/play_kube_test.go | 4 ++-- test/utils/matchers.go | 22 ++++++++--------- test/utils/utils.go | 4 ++-- 43 files changed, 99 insertions(+), 99 deletions(-) diff --git a/cmd/podman/common/completion.go b/cmd/podman/common/completion.go index 90c0c69210..b630512144 100644 --- a/cmd/podman/common/completion.go +++ b/cmd/podman/common/completion.go @@ -1365,7 +1365,7 @@ func convertFormatSuggestions(suggestions []formatSuggestion) []string { // This function will only work for pointer to structs other types are not supported. // When "{{." is typed the field and method names of the given struct will be completed. // This also works recursive for nested structs. -func AutocompleteFormat(o interface{}) func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { +func AutocompleteFormat(o any) func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { // this function provides shell completion for go templates return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { // autocomplete json when nothing or json is typed @@ -1454,7 +1454,7 @@ func AutocompleteFormat(o interface{}) func(cmd *cobra.Command, args []string, t } } -func getEntityType(cmd *cobra.Command, args []string, o interface{}) interface{} { +func getEntityType(cmd *cobra.Command, args []string, o any) any { // container logic if containers, _ := getContainers(cmd, args[0], completeDefault); len(containers) > 0 { return &define.InspectContainerData{} diff --git a/cmd/podman/images/search.go b/cmd/podman/images/search.go index 763ead10ab..681ada079e 100644 --- a/cmd/podman/images/search.go +++ b/cmd/podman/images/search.go @@ -212,7 +212,7 @@ func imageSearch(cmd *cobra.Command, args []string) error { return rpt.Execute(searchReport) } -func printArbitraryJSON(v interface{}) error { +func printArbitraryJSON(v any) error { prettyJSON, err := json.MarshalIndent(v, "", " ") if err != nil { return err diff --git a/cmd/podman/inspect/inspect.go b/cmd/podman/inspect/inspect.go index 7fd5db8195..157653fca6 100644 --- a/cmd/podman/inspect/inspect.go +++ b/cmd/podman/inspect/inspect.go @@ -76,7 +76,7 @@ func newInspector(options entities.InspectOptions) (*inspector, error) { // inspect inspects the specified container/image names or IDs. func (i *inspector) inspect(namesOrIDs []string) error { // data - dumping place for inspection results. - var data []interface{} + var data []any var errs []error ctx := context.Background() @@ -157,7 +157,7 @@ func (i *inspector) inspect(namesOrIDs []string) error { } // Always print an empty array if data == nil { - data = []interface{}{} + data = []any{} } var err error @@ -191,8 +191,8 @@ func (i *inspector) inspect(namesOrIDs []string) error { return nil } -func (i *inspector) inspectAll(ctx context.Context, namesOrIDs []string) ([]interface{}, []error, error) { - var data []interface{} +func (i *inspector) inspectAll(ctx context.Context, namesOrIDs []string) ([]any, []error, error) { + var data []any allErrs := []error{} for _, name := range namesOrIDs { ctrData, errs, err := i.containerEngine.ContainerInspect(ctx, []string{name}, i.options) diff --git a/cmd/podman/main.go b/cmd/podman/main.go index 80ce600bf9..bcf45b130b 100644 --- a/cmd/podman/main.go +++ b/cmd/podman/main.go @@ -38,10 +38,10 @@ import ( type logrusLogger struct{} -func (l logrusLogger) Errorf(format string, args ...interface{}) { +func (l logrusLogger) Errorf(format string, args ...any) { logrus.Errorf(format, args...) } -func (l logrusLogger) Debugf(format string, args ...interface{}) { +func (l logrusLogger) Debugf(format string, args ...any) { logrus.Debugf(format, args...) } diff --git a/cmd/podman/quadlet/quadlet.go b/cmd/podman/quadlet/quadlet.go index ae49ed4fe4..8fa4e2fcc0 100644 --- a/cmd/podman/quadlet/quadlet.go +++ b/cmd/podman/quadlet/quadlet.go @@ -11,11 +11,11 @@ import ( // logrusLogger implements the logiface.Logger interface using logrus type logrusLogger struct{} -func (l logrusLogger) Errorf(format string, args ...interface{}) { +func (l logrusLogger) Errorf(format string, args ...any) { logrus.Errorf(format, args...) } -func (l logrusLogger) Debugf(format string, args ...interface{}) { +func (l logrusLogger) Debugf(format string, args ...any) { logrus.Debugf(format, args...) } diff --git a/cmd/podman/system/df.go b/cmd/podman/system/df.go index c3553a5399..339ebfbe6b 100644 --- a/cmd/podman/system/df.go +++ b/cmd/podman/system/df.go @@ -233,7 +233,7 @@ func printVerbose(cmd *cobra.Command, reports *entities.SystemDfReport) error { return writeTemplate(rpt, hdrs, dfVolumes) } -func writeTemplate(rpt *report.Formatter, hdrs []map[string]string, output interface{}) error { +func writeTemplate(rpt *report.Formatter, hdrs []map[string]string, output any) error { if rpt.RenderHeaders { if err := rpt.Execute(hdrs); err != nil { return err diff --git a/cmd/podman/utils/utils.go b/cmd/podman/utils/utils.go index 5f4baae5c7..0b815ad6a8 100644 --- a/cmd/podman/utils/utils.go +++ b/cmd/podman/utils/utils.go @@ -150,7 +150,7 @@ func RemoveSlash(input []string) []string { return output } -func PrintGenericJSON(data interface{}) error { +func PrintGenericJSON(data any) error { enc := json.NewEncoder(os.Stdout) // by default, json marshallers will force utf=8 from // a string. diff --git a/cmd/quadlet/main.go b/cmd/quadlet/main.go index f2748175e5..dfd1260ff6 100644 --- a/cmd/quadlet/main.go +++ b/cmd/quadlet/main.go @@ -68,7 +68,7 @@ func logToKmsg(s string) bool { return true } -func Logf(format string, a ...interface{}) { +func Logf(format string, a ...any) { s := fmt.Sprintf(format, a...) line := fmt.Sprintf("quadlet-generator[%d]: %s", os.Getpid(), s) @@ -84,7 +84,7 @@ func enableDebug() { debugEnabled = true } -func Debugf(format string, a ...interface{}) { +func Debugf(format string, a ...any) { if debugEnabled { Logf(format, a...) } @@ -421,11 +421,11 @@ func generateUnitsInfoMap(units []*parser.UnitFile) map[string]*quadlet.UnitInfo // quadletLogger implements the logiface.Logger interface using quadlet's custom logging type quadletLogger struct{} -func (l quadletLogger) Errorf(format string, args ...interface{}) { +func (l quadletLogger) Errorf(format string, args ...any) { Logf(format, args...) } -func (l quadletLogger) Debugf(format string, args ...interface{}) { +func (l quadletLogger) Debugf(format string, args ...any) { Debugf(format, args...) } diff --git a/libpod/container_internal.go b/libpod/container_internal.go index aeedbf3f42..84280f7cce 100644 --- a/libpod/container_internal.go +++ b/libpod/container_internal.go @@ -476,7 +476,7 @@ func (c *Container) setupStorage(ctx context.Context) error { // privileged containers or '--ipc host' only ProcessLabel will // be set and so we will skip it for cases like that. if options.Flags == nil { - options.Flags = make(map[string]interface{}) + options.Flags = make(map[string]any) } options.Flags["ProcessLabel"] = c.config.ProcessLabel options.Flags["MountLabel"] = c.config.MountLabel diff --git a/libpod/define/config.go b/libpod/define/config.go index c76238e6dd..3d5835e345 100644 --- a/libpod/define/config.go +++ b/libpod/define/config.go @@ -30,7 +30,7 @@ const ( // InfoData holds the info type, i.e store, host etc and the data for each type type InfoData struct { Type string - Data map[string]interface{} + Data map[string]any } // VolumeDriverLocal is the "local" volume driver. It is managed by libpod diff --git a/libpod/define/container_inspect.go b/libpod/define/container_inspect.go index bd3492d3d4..3640a1d2e6 100644 --- a/libpod/define/container_inspect.go +++ b/libpod/define/container_inspect.go @@ -111,8 +111,8 @@ type InspectContainerConfig struct { func (insp *InspectContainerConfig) UnmarshalJSON(data []byte) error { type Alias InspectContainerConfig aux := &struct { - Entrypoint interface{} `json:"Entrypoint"` - StopSignal interface{} `json:"StopSignal"` + Entrypoint any `json:"Entrypoint"` + StopSignal any `json:"StopSignal"` *Alias }{ Alias: (*Alias)(insp), @@ -126,7 +126,7 @@ func (insp *InspectContainerConfig) UnmarshalJSON(data []byte) error { insp.Entrypoint = strings.Split(entrypoint, " ") case []string: insp.Entrypoint = entrypoint - case []interface{}: + case []any: insp.Entrypoint = []string{} for _, entry := range entrypoint { if str, ok := entry.(string); ok { diff --git a/libpod/define/info.go b/libpod/define/info.go index 967a664c99..35c62217ec 100644 --- a/libpod/define/info.go +++ b/libpod/define/info.go @@ -9,11 +9,11 @@ import ( // running libpod/podman // swagger:model LibpodInfo type Info struct { - Host *HostInfo `json:"host"` - Store *StoreInfo `json:"store"` - Registries map[string]interface{} `json:"registries"` - Plugins Plugins `json:"plugins"` - Version Version `json:"version"` + Host *HostInfo `json:"host"` + Store *StoreInfo `json:"store"` + Registries map[string]any `json:"registries"` + Plugins Plugins `json:"plugins"` + Version Version `json:"version"` } // SecurityInfo describes the libpod host @@ -53,8 +53,8 @@ type HostInfo struct { // RemoteSocket returns the UNIX domain socket the Podman service is listening on RemoteSocket *RemoteSocket `json:"remoteSocket,omitempty"` // RootlessNetworkCmd returns the default rootless network command (slirp4netns or pasta) - RootlessNetworkCmd string `json:"rootlessNetworkCmd"` - RuntimeInfo map[string]interface{} `json:"runtimeInfo,omitempty"` + RootlessNetworkCmd string `json:"rootlessNetworkCmd"` + RuntimeInfo map[string]any `json:"runtimeInfo,omitempty"` // ServiceIsRemote is true when the podman/libpod service is remote to the client ServiceIsRemote bool `json:"serviceIsRemote"` Security SecurityInfo `json:"security"` @@ -123,11 +123,11 @@ type OCIRuntimeInfo struct { // StoreInfo describes the container storage and its // attributes type StoreInfo struct { - ConfigFile string `json:"configFile"` - ContainerStore ContainerStore `json:"containerStore"` - GraphDriverName string `json:"graphDriverName"` - GraphOptions map[string]interface{} `json:"graphOptions"` - GraphRoot string `json:"graphRoot"` + ConfigFile string `json:"configFile"` + ContainerStore ContainerStore `json:"containerStore"` + GraphDriverName string `json:"graphDriverName"` + GraphOptions map[string]any `json:"graphOptions"` + GraphRoot string `json:"graphRoot"` // GraphRootAllocated is how much space the graphroot has in bytes GraphRootAllocated uint64 `json:"graphRootAllocated"` // GraphRootUsed is how much of graphroot is used in bytes diff --git a/libpod/define/volume_inspect.go b/libpod/define/volume_inspect.go index c4b45a04f5..fb6e0fda1b 100644 --- a/libpod/define/volume_inspect.go +++ b/libpod/define/volume_inspect.go @@ -25,7 +25,7 @@ type InspectVolumeData struct { // Status is provided to us by an external program, so no guarantees are // made about its format or contents. Further, it is an optional field, // so it may not be set even in cases where a volume plugin is in use. - Status map[string]interface{} `json:"Status,omitempty"` + Status map[string]any `json:"Status,omitempty"` // Labels includes the volume's configured labels, key:value pairs that // can be passed during volume creation to provide information for third // party tools. diff --git a/libpod/info.go b/libpod/info.go index 550b279ac0..028223c740 100644 --- a/libpod/info.go +++ b/libpod/info.go @@ -47,7 +47,7 @@ func (r *Runtime) info() (*define.Info, error) { return nil, fmt.Errorf("getting store info: %w", err) } info.Store = storeInfo - registries := make(map[string]interface{}) + registries := make(map[string]any) sys := r.SystemContext() data, err := sysregistriesv2.GetRegistries(sys) @@ -248,7 +248,7 @@ func (r *Runtime) storeInfo() (*define.StoreInfo, error) { TransientStore: r.store.TransientStore(), } - graphOptions := map[string]interface{}{} + graphOptions := map[string]any{} for _, o := range r.store.GraphOptions() { split := strings.SplitN(o, "=", 2) switch { @@ -257,7 +257,7 @@ func (r *Runtime) storeInfo() (*define.StoreInfo, error) { if err != nil { logrus.Warnf("Failed to retrieve program version for %s: %v", split[1], err) } - program := map[string]interface{}{} + program := map[string]any{} program["Executable"] = split[1] program["Version"] = ver program["Package"] = version.Package(split[1]) diff --git a/libpod/plugin/volume_api.go b/libpod/plugin/volume_api.go index 834d9c9800..09b5729ea5 100644 --- a/libpod/plugin/volume_api.go +++ b/libpod/plugin/volume_api.go @@ -204,7 +204,7 @@ func (p *VolumePlugin) verifyReachable() error { // Send a request to the volume plugin for handling. // Callers *MUST* close the response when they are done. -func (p *VolumePlugin) sendRequest(toJSON interface{}, endpoint string) (*http.Response, error) { +func (p *VolumePlugin) sendRequest(toJSON any, endpoint string) (*http.Response, error) { var ( reqJSON []byte err error diff --git a/libpod/util.go b/libpod/util.go index 6a860cfcb2..c7eb475b23 100644 --- a/libpod/util.go +++ b/libpod/util.go @@ -64,7 +64,7 @@ func sortMounts(m []spec.Mount) []spec.Mount { // JSONDeepCopy performs a deep copy by performing a JSON encode/decode of the // given structures. From and To should be identically typed structs. -func JSONDeepCopy(from, to interface{}) error { +func JSONDeepCopy(from, to any) error { tmp, err := json.Marshal(from) if err != nil { return err diff --git a/pkg/api/handlers/compat/containers_stats_linux.go b/pkg/api/handlers/compat/containers_stats_linux.go index e08e2bb1f7..f6d613dc55 100644 --- a/pkg/api/handlers/compat/containers_stats_linux.go +++ b/pkg/api/handlers/compat/containers_stats_linux.go @@ -205,7 +205,7 @@ streamLabel: // A label to flatten the scope Networks: net, } - var jsonOut interface{} + var jsonOut any if utils.IsLibpodRequest(r) { jsonOut = s } else { diff --git a/pkg/api/handlers/utils/handler.go b/pkg/api/handlers/utils/handler.go index 069010eada..845aa7a4b5 100644 --- a/pkg/api/handlers/utils/handler.go +++ b/pkg/api/handlers/utils/handler.go @@ -34,7 +34,7 @@ func SupportedVersion(r *http.Request, condition string) (semver.Version, error) } // WriteResponse encodes the given value as JSON or string and renders it for http client -func WriteResponse(w http.ResponseWriter, code int, value interface{}) { +func WriteResponse(w http.ResponseWriter, code int, value any) { // RFC2616 explicitly states that the following status codes "MUST NOT // include a message-body": switch code { @@ -114,7 +114,7 @@ func MarshalErrorSliceJSONIsEmpty(ptr unsafe.Pointer) bool { } // WriteJSON writes an interface value encoded as JSON to w -func WriteJSON(w http.ResponseWriter, code int, value interface{}) { +func WriteJSON(w http.ResponseWriter, code int, value any) { // FIXME: we don't need to write the header in all/some circumstances. w.Header().Set("Content-Type", "application/json") w.WriteHeader(code) diff --git a/pkg/api/handlers/utils/handler_test.go b/pkg/api/handlers/utils/handler_test.go index 1b2128656e..fd15d2e19d 100644 --- a/pkg/api/handlers/utils/handler_test.go +++ b/pkg/api/handlers/utils/handler_test.go @@ -18,7 +18,7 @@ func TestErrorEncoderFuncOmit(t *testing.T) { t.Fatal(err) } - dataAsMap := make(map[string]interface{}) + dataAsMap := make(map[string]any) err = json.Unmarshal(data, &dataAsMap) if err != nil { t.Fatal(err) @@ -33,7 +33,7 @@ func TestErrorEncoderFuncOmit(t *testing.T) { t.Errorf("the `errs` field should have been omitted") } - dataAsMap = make(map[string]interface{}) + dataAsMap = make(map[string]any) data, err = json.Marshal(struct { Err error `json:"err"` Errs []error `json:"errs"` diff --git a/pkg/auth/auth_test.go b/pkg/auth/auth_test.go index ccb205c18e..160737800b 100644 --- a/pkg/auth/auth_test.go +++ b/pkg/auth/auth_test.go @@ -220,8 +220,8 @@ func TestMakeXRegistryConfigHeader(t *testing.T) { decodedHeader, err := base64.URLEncoding.DecodeString(header[0]) require.NoError(t, err, tc.name) // Don't test for a specific JSON representation, just for the expected contents. - expected := map[string]interface{}{} - actual := map[string]interface{}{} + expected := map[string]any{} + actual := map[string]any{} err = json.Unmarshal([]byte(tc.expectedContents), &expected) require.NoError(t, err, tc.name) err = json.Unmarshal(decodedHeader, &actual) @@ -282,8 +282,8 @@ func TestMakeXRegistryAuthHeader(t *testing.T) { decodedHeader, err := base64.URLEncoding.DecodeString(header[0]) require.NoError(t, err, tc.name) // Don't test for a specific JSON representation, just for the expected contents. - expected := map[string]interface{}{} - actual := map[string]interface{}{} + expected := map[string]any{} + actual := map[string]any{} err = json.Unmarshal([]byte(tc.expectedContents), &expected) require.NoError(t, err, tc.name) err = json.Unmarshal(decodedHeader, &actual) diff --git a/pkg/bindings/connection.go b/pkg/bindings/connection.go index db69072f2a..58d4e4a93e 100644 --- a/pkg/bindings/connection.go +++ b/pkg/bindings/connection.go @@ -377,7 +377,7 @@ func (c *Connection) DoRequest(ctx context.Context, httpBody io.Reader, httpMeth response *http.Response ) - params := make([]interface{}, len(pathValues)+1) + params := make([]any, len(pathValues)+1) if v := headers.Values("API-Version"); len(v) > 0 { params[0] = v[0] diff --git a/pkg/bindings/errors.go b/pkg/bindings/errors.go index 0b68c04db8..9ed8dbba4f 100644 --- a/pkg/bindings/errors.go +++ b/pkg/bindings/errors.go @@ -14,7 +14,7 @@ var ( ErrNotImplemented = errors.New("function not implemented") ) -func handleError(data []byte, unmarshalErrorInto interface{}) error { +func handleError(data []byte, unmarshalErrorInto any) error { if err := json.Unmarshal(data, unmarshalErrorInto); err != nil { return fmt.Errorf("unmarshalling error into %#v, data %q: %w", unmarshalErrorInto, string(data), err) } @@ -23,13 +23,13 @@ func handleError(data []byte, unmarshalErrorInto interface{}) error { // Process drains the response body, and processes the HTTP status code // Note: Closing the response.Body is left to the caller -func (h *APIResponse) Process(unmarshalInto interface{}) error { +func (h *APIResponse) Process(unmarshalInto any) error { return h.ProcessWithError(unmarshalInto, &errorhandling.ErrorModel{}) } // ProcessWithError drains the response body, and processes the HTTP status code // Note: Closing the response.Body is left to the caller -func (h *APIResponse) ProcessWithError(unmarshalInto interface{}, unmarshalErrorInto interface{}) error { +func (h *APIResponse) ProcessWithError(unmarshalInto any, unmarshalErrorInto any) error { data, err := io.ReadAll(h.Response.Body) if err != nil { return fmt.Errorf("unable to process API response: %w", err) diff --git a/pkg/bindings/internal/util/util.go b/pkg/bindings/internal/util/util.go index 36d97e271e..9271d1df2c 100644 --- a/pkg/bindings/internal/util/util.go +++ b/pkg/bindings/internal/util/util.go @@ -45,13 +45,13 @@ func SimpleTypeToParam(f reflect.Value) string { panic("the input parameter is not a simple type") } -func Changed(o interface{}, fieldName string) bool { +func Changed(o any, fieldName string) bool { r := reflect.ValueOf(o) value := reflect.Indirect(r).FieldByName(fieldName) return !value.IsNil() } -func ToParams(o interface{}) (url.Values, error) { +func ToParams(o any) (url.Values, error) { params := url.Values{} if o == nil || reflect.ValueOf(o).IsNil() { return params, nil @@ -92,7 +92,7 @@ func ToParams(o interface{}) (url.Values, error) { } } case f.Kind() == reflect.Map: - lowerCaseKeys := make(map[string]interface{}) + lowerCaseKeys := make(map[string]any) iter := f.MapRange() for iter.Next() { lowerCaseKeys[iter.Key().Interface().(string)] = iter.Value().Interface() diff --git a/pkg/domain/infra/abi/generate.go b/pkg/domain/infra/abi/generate.go index dd07629ceb..bb6d2c3484 100644 --- a/pkg/domain/infra/abi/generate.go +++ b/pkg/domain/infra/abi/generate.go @@ -378,7 +378,7 @@ func getKubePVCs(volumes []*libpod.Volume) ([][]byte, error) { } // generateKubeYAML marshalls a kube kind into a YAML file. -func generateKubeYAML(kubeKind interface{}) ([]byte, error) { +func generateKubeYAML(kubeKind any) ([]byte, error) { b, err := yaml.Marshal(kubeKind) if err != nil { return nil, err diff --git a/pkg/domain/infra/abi/play.go b/pkg/domain/infra/abi/play.go index 9d22e88cdb..28c815291f 100644 --- a/pkg/domain/infra/abi/play.go +++ b/pkg/domain/infra/abi/play.go @@ -1549,7 +1549,7 @@ func splitMultiDocYAML(yamlContent []byte) ([][]byte, error) { d := yamlv3.NewDecoder(bytes.NewReader(yamlContent)) for { - var o interface{} + var o any // read individual document err := d.Decode(&o) if err == io.EOF { diff --git a/pkg/domain/utils/utils.go b/pkg/domain/utils/utils.go index e1bd488637..df0bd798fe 100644 --- a/pkg/domain/utils/utils.go +++ b/pkg/domain/utils/utils.go @@ -12,7 +12,7 @@ var json = jsoniter.ConfigCompatibleWithStandardLibrary // DeepCopy does a deep copy of a structure // Error checking of parameters delegated to json engine -var DeepCopy = func(dst interface{}, src interface{}) error { +var DeepCopy = func(dst any, src any) error { payload, err := json.Marshal(src) if err != nil { return err diff --git a/pkg/k8s.io/api/core/v1/types.go b/pkg/k8s.io/api/core/v1/types.go index faebe8d811..d803232064 100644 --- a/pkg/k8s.io/api/core/v1/types.go +++ b/pkg/k8s.io/api/core/v1/types.go @@ -4697,7 +4697,7 @@ type NamedExtension struct { // Name is the nickname for this Extension Name string `json:"name"` // Extension holds the extension information - Extension interface{} `json:"extension"` + Extension any `json:"extension"` } // AuthProviderConfig holds the configuration for a specified auth provider. diff --git a/pkg/k8s.io/apimachinery/pkg/api/resource/quantity.go b/pkg/k8s.io/apimachinery/pkg/api/resource/quantity.go index 64b536fe39..6e7f0c4761 100644 --- a/pkg/k8s.io/apimachinery/pkg/api/resource/quantity.go +++ b/pkg/k8s.io/apimachinery/pkg/api/resource/quantity.go @@ -595,7 +595,7 @@ func (q Quantity) MarshalJSON() ([]byte, error) { } // ToUnstructured implements the value.UnstructuredConverter interface. -func (q Quantity) ToUnstructured() interface{} { +func (q Quantity) ToUnstructured() any { return q.String() } diff --git a/pkg/k8s.io/apimachinery/pkg/api/resource/scale_int.go b/pkg/k8s.io/apimachinery/pkg/api/resource/scale_int.go index 55e177b0e9..0d72249021 100644 --- a/pkg/k8s.io/apimachinery/pkg/api/resource/scale_int.go +++ b/pkg/k8s.io/apimachinery/pkg/api/resource/scale_int.go @@ -29,7 +29,7 @@ var ( ) func init() { - intPool.New = func() interface{} { + intPool.New = func() any { return &big.Int{} } } diff --git a/pkg/k8s.io/apimachinery/pkg/apis/meta/v1/duration.go b/pkg/k8s.io/apimachinery/pkg/apis/meta/v1/duration.go index b07eca0482..2b195efc39 100644 --- a/pkg/k8s.io/apimachinery/pkg/apis/meta/v1/duration.go +++ b/pkg/k8s.io/apimachinery/pkg/apis/meta/v1/duration.go @@ -50,6 +50,6 @@ func (d Duration) MarshalJSON() ([]byte, error) { } // ToUnstructured implements the value.UnstructuredConverter interface. -func (d Duration) ToUnstructured() interface{} { +func (d Duration) ToUnstructured() any { return d.Duration.String() } diff --git a/pkg/k8s.io/apimachinery/pkg/apis/meta/v1/time.go b/pkg/k8s.io/apimachinery/pkg/apis/meta/v1/time.go index ae56d8c2b2..9ccedd8229 100644 --- a/pkg/k8s.io/apimachinery/pkg/apis/meta/v1/time.go +++ b/pkg/k8s.io/apimachinery/pkg/apis/meta/v1/time.go @@ -152,7 +152,7 @@ func (t Time) MarshalJSON() ([]byte, error) { } // ToUnstructured implements the value.UnstructuredConverter interface. -func (t Time) ToUnstructured() interface{} { +func (t Time) ToUnstructured() any { if t.IsZero() { return nil } diff --git a/pkg/k8s.io/apimachinery/pkg/apis/meta/v1/types.go b/pkg/k8s.io/apimachinery/pkg/apis/meta/v1/types.go index cb6838c062..b5bb234fde 100644 --- a/pkg/k8s.io/apimachinery/pkg/apis/meta/v1/types.go +++ b/pkg/k8s.io/apimachinery/pkg/apis/meta/v1/types.go @@ -938,7 +938,7 @@ type List struct { ListMeta `json:"metadata,omitempty"` // List of objects - Items []interface{} `json:"items"` + Items []any `json:"items"` } // APIVersions lists the versions that are available, to allow clients to diff --git a/pkg/logiface/logiface.go b/pkg/logiface/logiface.go index d236f74f95..5df7f0c54b 100644 --- a/pkg/logiface/logiface.go +++ b/pkg/logiface/logiface.go @@ -1,8 +1,8 @@ package logiface type Logger interface { - Errorf(format string, args ...interface{}) - Debugf(format string, args ...interface{}) + Errorf(format string, args ...any) + Debugf(format string, args ...any) } var logger Logger @@ -11,13 +11,13 @@ func SetLogger(l Logger) { logger = l } -func Errorf(format string, args ...interface{}) { +func Errorf(format string, args ...any) { if logger != nil { logger.Errorf(format, args...) } } -func Debugf(format string, args ...interface{}) { +func Debugf(format string, args ...any) { if logger != nil { logger.Debugf(format, args...) } diff --git a/pkg/machine/e2e/config_test.go b/pkg/machine/e2e/config_test.go index 77662a8485..7a1391e009 100644 --- a/pkg/machine/e2e/config_test.go +++ b/pkg/machine/e2e/config_test.go @@ -214,24 +214,24 @@ func BeValidJSON() *ValidJSONMatcher { return &ValidJSONMatcher{} } -func (matcher *ValidJSONMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *ValidJSONMatcher) Match(actual any) (success bool, err error) { s, ok := actual.(string) if !ok { return false, fmt.Errorf("ValidJSONMatcher expects a string, not %q", actual) } - var i interface{} + var i any if err := json.Unmarshal([]byte(s), &i); err != nil { return false, err } return true, nil } -func (matcher *ValidJSONMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *ValidJSONMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to be valid JSON") } -func (matcher *ValidJSONMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *ValidJSONMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "to _not_ be valid JSON") } diff --git a/pkg/specgen/generate/security_linux.go b/pkg/specgen/generate/security_linux.go index 39702f508d..9887b3bb06 100644 --- a/pkg/specgen/generate/security_linux.go +++ b/pkg/specgen/generate/security_linux.go @@ -105,7 +105,7 @@ func securityConfigureGenerator(s *specgen.SpecGenerator, g *generate.Generator, if err != nil { return err } - boundingCaps := make(map[string]interface{}) + boundingCaps := make(map[string]any) for _, b := range boundingSet { boundingCaps[b] = b } @@ -171,7 +171,7 @@ func securityConfigureGenerator(s *specgen.SpecGenerator, g *generate.Generator, if err != nil { return err } - boundingCaps := make(map[string]interface{}) + boundingCaps := make(map[string]any) for _, b := range boundingSet { boundingCaps[b] = b } diff --git a/pkg/systemd/dbus.go b/pkg/systemd/dbus.go index d5613bb859..21573fbd37 100644 --- a/pkg/systemd/dbus.go +++ b/pkg/systemd/dbus.go @@ -43,7 +43,7 @@ func IsSystemdSessionValid(uid int) bool { logrus.Debugf("systemd-logind: %s", err) return false } - activeSessionMap, ok := activeSession.Value().([]interface{}) + activeSessionMap, ok := activeSession.Value().([]any) if !ok || len(activeSessionMap) < 2 { // unable to get active session map. logrus.Debugf("systemd-logind: %s", err) @@ -62,7 +62,7 @@ func IsSystemdSessionValid(uid int) bool { logrus.Debugf("systemd-logind: %s", err) return false } - dbusUser, ok := sessionUser.Value().([]interface{}) + dbusUser, ok := sessionUser.Value().([]any) if !ok { // not a valid user. return false diff --git a/pkg/systemd/quadlet/podmancmdline.go b/pkg/systemd/quadlet/podmancmdline.go index 49c174ac47..6706b68bd9 100644 --- a/pkg/systemd/quadlet/podmancmdline.go +++ b/pkg/systemd/quadlet/podmancmdline.go @@ -29,7 +29,7 @@ func (c *PodmanCmdline) add(args ...string) { c.Args = append(c.Args, args...) } -func (c *PodmanCmdline) addf(format string, a ...interface{}) { +func (c *PodmanCmdline) addf(format string, a ...any) { c.add(fmt.Sprintf(format, a...)) } diff --git a/pkg/trust/policy_test.go b/pkg/trust/policy_test.go index 3952b72c39..02f546bc1f 100644 --- a/pkg/trust/policy_test.go +++ b/pkg/trust/policy_test.go @@ -140,8 +140,8 @@ func TestAddPolicyEntries(t *testing.T) { require.NoError(t, err) // Decode updatedJSONWithUnknownData so that this test does not depend on details of the encoding. // To reduce noise in the constants below: - type a = []interface{} - type m = map[string]interface{} + type a = []any + type m = map[string]any var parsedUpdatedJSON m err = json.Unmarshal(updatedJSONWithUnknownData, &parsedUpdatedJSON) require.NoError(t, err) diff --git a/pkg/util/utils_linux.go b/pkg/util/utils_linux.go index d113ad802a..258451d076 100644 --- a/pkg/util/utils_linux.go +++ b/pkg/util/utils_linux.go @@ -115,7 +115,7 @@ func AddPrivilegedDevices(g *generate.Generator, systemdMode bool) error { } if rootless.IsRootless() { - mounts := make(map[string]interface{}) + mounts := make(map[string]any) for _, m := range g.Mounts() { mounts[m.Destination] = true } diff --git a/test/e2e/login_logout_test.go b/test/e2e/login_logout_test.go index d0b5bb940e..60f84970c1 100644 --- a/test/e2e/login_logout_test.go +++ b/test/e2e/login_logout_test.go @@ -82,11 +82,11 @@ var _ = Describe("Podman login and logout", func() { os.RemoveAll(certDirPath) }) - readAuthInfo := func(filePath string) map[string]interface{} { + readAuthInfo := func(filePath string) map[string]any { authBytes, err := os.ReadFile(filePath) Expect(err).ToNot(HaveOccurred()) - var authInfo map[string]interface{} + var authInfo map[string]any err = json.Unmarshal(authBytes, &authInfo) Expect(err).ToNot(HaveOccurred()) GinkgoWriter.Println(authInfo) @@ -94,7 +94,7 @@ var _ = Describe("Podman login and logout", func() { const authsKey = "auths" Expect(authInfo).To(HaveKey(authsKey)) - auths, ok := authInfo[authsKey].(map[string]interface{}) + auths, ok := authInfo[authsKey].(map[string]any) Expect(ok).To(BeTrue(), "authInfo[%s]", authsKey) return auths diff --git a/test/e2e/play_kube_test.go b/test/e2e/play_kube_test.go index 8db7d3b4df..823df9bd23 100644 --- a/test/e2e/play_kube_test.go +++ b/test/e2e/play_kube_test.go @@ -1496,7 +1496,7 @@ var ( ) // getKubeYaml returns a kubernetes YAML document. -func getKubeYaml(kind string, object interface{}) (string, error) { +func getKubeYaml(kind string, object any) (string, error) { var yamlTemplate string templateBytes := &bytes.Buffer{} @@ -1532,7 +1532,7 @@ func getKubeYaml(kind string, object interface{}) (string, error) { } // generateKubeYaml writes a kubernetes YAML document. -func generateKubeYaml(kind string, object interface{}, pathname string) error { +func generateKubeYaml(kind string, object any, pathname string) error { k, err := getKubeYaml(kind, object) if err != nil { return err diff --git a/test/utils/matchers.go b/test/utils/matchers.go index bf9c31d4ad..2ce273dccb 100644 --- a/test/utils/matchers.go +++ b/test/utils/matchers.go @@ -38,7 +38,7 @@ func ExitWithErrorRegex(expectExitCode int, expectStderrRegex string) *ExitMatch } // Match follows gexec.Matcher interface. -func (matcher *ExitMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *ExitMatcher) Match(actual any) (success bool, err error) { session, ok := actual.(podmanSession) if !ok { return false, fmt.Errorf("ExitWithError must be passed a gexec.Exiter (Missing method ExitCode() int) Got:\n#{format.Object(actual, 1)}") @@ -83,15 +83,15 @@ func (matcher *ExitMatcher) Match(actual interface{}) (success bool, err error) return true, nil } -func (matcher *ExitMatcher) FailureMessage(_ interface{}) (message string) { +func (matcher *ExitMatcher) FailureMessage(_ any) (message string) { return matcher.msg } -func (matcher *ExitMatcher) NegatedFailureMessage(_ interface{}) (message string) { +func (matcher *ExitMatcher) NegatedFailureMessage(_ any) (message string) { panic("There is no conceivable reason to call Not(ExitWithError) !") } -func (matcher *ExitMatcher) MatchMayChangeInTheFuture(actual interface{}) bool { +func (matcher *ExitMatcher) MatchMayChangeInTheFuture(actual any) bool { session, ok := actual.(*gexec.Session) if ok { return session.ExitCode() == -1 @@ -109,7 +109,7 @@ type exitCleanlyMatcher struct { msg string } -func (matcher *exitCleanlyMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *exitCleanlyMatcher) Match(actual any) (success bool, err error) { session, ok := actual.(podmanSession) if !ok { return false, fmt.Errorf("ExitCleanly must be passed a PodmanSession; Got:\n %+v\n%q", actual, format.Object(actual, 1)) @@ -134,11 +134,11 @@ func (matcher *exitCleanlyMatcher) Match(actual interface{}) (success bool, err return true, nil } -func (matcher *exitCleanlyMatcher) FailureMessage(_ interface{}) (message string) { +func (matcher *exitCleanlyMatcher) FailureMessage(_ any) (message string) { return matcher.msg } -func (matcher *exitCleanlyMatcher) NegatedFailureMessage(_ interface{}) (message string) { +func (matcher *exitCleanlyMatcher) NegatedFailureMessage(_ any) (message string) { // FIXME - I see no situation in which we could ever want this? return matcher.msg + " (NOT!)" } @@ -151,23 +151,23 @@ func BeValidJSON() *ValidJSONMatcher { return &ValidJSONMatcher{} } -func (matcher *ValidJSONMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *ValidJSONMatcher) Match(actual any) (success bool, err error) { s, ok := actual.(string) if !ok { return false, fmt.Errorf("ValidJSONMatcher expects a string, not %q", actual) } - var i interface{} + var i any if err := json.Unmarshal([]byte(s), &i); err != nil { return false, err } return true, nil } -func (matcher *ValidJSONMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *ValidJSONMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to be valid JSON") } -func (matcher *ValidJSONMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *ValidJSONMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "to _not_ be valid JSON") } diff --git a/test/utils/utils.go b/test/utils/utils.go index 3643c86e75..812f1deeee 100644 --- a/test/utils/utils.go +++ b/test/utils/utils.go @@ -376,7 +376,7 @@ func (s *PodmanSession) LineInOutputContainsTag(repo, tag string) bool { // IsJSONOutputValid attempts to unmarshal the session buffer // and if successful, returns true, else false func (s *PodmanSession) IsJSONOutputValid() bool { - var i interface{} + var i any if err := json.Unmarshal(s.Out.Contents(), &i); err != nil { GinkgoWriter.Println(err) return false @@ -487,7 +487,7 @@ func IsCommandAvailable(command string) bool { // WriteJSONFile write json format data to a json file func WriteJSONFile(data []byte, filePath string) error { - var jsonData map[string]interface{} + var jsonData map[string]any if err := json.Unmarshal(data, &jsonData); err != nil { return err } From 55b49b464ffd351e292d86d8bc1396f23033e8f3 Mon Sep 17 00:00:00 2001 From: Kir Kolyshkin Date: Thu, 14 Aug 2025 15:04:22 -0700 Subject: [PATCH 03/10] Use for range with integers Replace a 3-clause for i := 0; i < n; i++ loop by for i := range n added in go1.22. Brought to you by modernize -test -fix -category=rangeint ./... (with some manual edits to libpod/lock/shm/shm_lock_test.go on top). Signed-off-by: Kir Kolyshkin --- cmd/podman/machine/client9p.go | 2 +- hack/podman-registry-go/registry_test.go | 2 +- libpod/container_exec.go | 2 +- libpod/lock/in_memory_locks.go | 2 +- libpod/lock/shm/shm_lock_test.go | 12 ++++-------- libpod/logs/log_test.go | 2 +- libpod/networking_common.go | 2 +- libpod/networking_linux_test.go | 2 +- libpod/oci_conmon_common.go | 2 +- pkg/bindings/test/common_test.go | 2 +- pkg/bindings/test/networks_test.go | 2 +- pkg/bindings/test/volumes_test.go | 2 +- pkg/k8s.io/apimachinery/pkg/api/resource/math.go | 4 ++-- pkg/machine/e2e/basic_test.go | 2 +- pkg/machine/e2e/inspect_test.go | 2 +- pkg/machine/e2e/list_test.go | 2 +- pkg/machine/gvproxy_unix.go | 2 +- pkg/machine/qemu/machine.go | 2 +- pkg/machine/shim/networking.go | 2 +- pkg/machine/sockets/sockets.go | 6 +++--- pkg/specgen/generate/ports.go | 2 +- pkg/specgen/generate/ports_bench_test.go | 6 +++--- pkg/specgenutil/util.go | 2 +- pkg/systemd/notifyproxy/notifyproxy_test.go | 2 +- pkg/systemd/parser/split.go | 4 ++-- pkg/util/utils.go | 4 ++-- test/e2e/checkpoint_test.go | 2 +- test/e2e/common_test.go | 8 ++++---- test/e2e/create_staticip_test.go | 2 +- test/e2e/create_test.go | 2 +- test/e2e/events_test.go | 2 +- test/e2e/exec_test.go | 2 +- test/e2e/healthcheck_run_test.go | 2 +- test/e2e/network_test.go | 4 ++-- test/e2e/pause_test.go | 4 ++-- test/e2e/play_kube_test.go | 4 ++-- test/e2e/pod_create_test.go | 4 ++-- test/e2e/pod_top_test.go | 2 +- test/e2e/rmi_test.go | 4 ++-- test/e2e/run_test.go | 8 ++++---- test/e2e/run_userns_test.go | 2 +- test/e2e/search_test.go | 6 +++--- test/e2e/stats_test.go | 2 +- test/e2e/system_connection_test.go | 2 +- test/goecho/goecho.go | 2 +- test/utils/utils.go | 2 +- 46 files changed, 69 insertions(+), 73 deletions(-) diff --git a/cmd/podman/machine/client9p.go b/cmd/podman/machine/client9p.go index 1153ecbd00..a8f99ea1f7 100644 --- a/cmd/podman/machine/client9p.go +++ b/cmd/podman/machine/client9p.go @@ -76,7 +76,7 @@ func client9p(portNum uint32, mountPath string) error { conn *vsock.Conn retries = 20 ) - for i := 0; i < retries; i++ { + for range retries { // Host connects to non-hypervisor processes on the host running the VM. conn, err = vsock.Dial(vsock.Host, portNum, nil) // If errors.Is worked on this error, we could detect non-timeout errors. diff --git a/hack/podman-registry-go/registry_test.go b/hack/podman-registry-go/registry_test.go index c00d98c6b6..5f9b7fb2a3 100644 --- a/hack/podman-registry-go/registry_test.go +++ b/hack/podman-registry-go/registry_test.go @@ -19,7 +19,7 @@ func TestStartAndStopMultipleRegistries(t *testing.T) { // Start registries. var errors *multierror.Error - for i := 0; i < 3; i++ { + for range 3 { reg, err := StartWithOptions(registryOptions) if err != nil { errors = multierror.Append(errors, err) diff --git a/libpod/container_exec.go b/libpod/container_exec.go index b7397b71b2..9346c3a70f 100644 --- a/libpod/container_exec.go +++ b/libpod/container_exec.go @@ -977,7 +977,7 @@ func (c *Container) exec(config *ExecConfig, streams *define.AttachStreams, resi // errors. func (c *Container) cleanupExecBundle(sessionID string) (err error) { path := c.execBundlePath(sessionID) - for attempts := 0; attempts < 50; attempts++ { + for range 50 { err = os.RemoveAll(path) if err == nil || os.IsNotExist(err) { return nil diff --git a/libpod/lock/in_memory_locks.go b/libpod/lock/in_memory_locks.go index e62b25ac15..9787d450b7 100644 --- a/libpod/lock/in_memory_locks.go +++ b/libpod/lock/in_memory_locks.go @@ -57,7 +57,7 @@ func NewInMemoryManager(numLocks uint32) (Manager, error) { manager.locks = make([]*Mutex, numLocks) var i uint32 - for i = 0; i < numLocks; i++ { + for i = range numLocks { lock := new(Mutex) lock.id = i manager.locks[i] = lock diff --git a/libpod/lock/shm/shm_lock_test.go b/libpod/lock/shm/shm_lock_test.go index 532d50aaef..5f0b708065 100644 --- a/libpod/lock/shm/shm_lock_test.go +++ b/libpod/lock/shm/shm_lock_test.go @@ -166,8 +166,7 @@ func TestAllocateTwoLocksGetsDifferentLocks(t *testing.T) { func TestAllocateAllLocksSucceeds(t *testing.T) { runLockTest(t, func(t *testing.T, locks *SHMLocks) { sems := make(map[uint32]bool) - var i uint32 - for i = 0; i < numLocks; i++ { + for range numLocks { sem, err := locks.AllocateSemaphore() assert.NoError(t, err) @@ -184,8 +183,7 @@ func TestAllocateAllLocksSucceeds(t *testing.T) { func TestAllocateTooManyLocksFails(t *testing.T) { runLockTest(t, func(t *testing.T, locks *SHMLocks) { // Allocate all locks - var i uint32 - for i = 0; i < numLocks; i++ { + for range numLocks { _, err := locks.AllocateSemaphore() assert.NoError(t, err) } @@ -200,8 +198,7 @@ func TestAllocateTooManyLocksFails(t *testing.T) { func TestAllocateDeallocateCycle(t *testing.T) { runLockTest(t, func(t *testing.T, locks *SHMLocks) { // Allocate all locks - var i uint32 - for i = 0; i < numLocks; i++ { + for range numLocks { _, err := locks.AllocateSemaphore() assert.NoError(t, err) } @@ -209,8 +206,7 @@ func TestAllocateDeallocateCycle(t *testing.T) { // Now loop through again, deallocating and reallocating. // Each time we free 1 semaphore, allocate again, and make sure // we get the same semaphore back. - var j uint32 - for j = 0; j < numLocks; j++ { + for j := range numLocks { err := locks.DeallocateSemaphore(j) assert.NoError(t, err) diff --git a/libpod/logs/log_test.go b/libpod/logs/log_test.go index 63d6135f74..da6ab22c3c 100644 --- a/libpod/logs/log_test.go +++ b/libpod/logs/log_test.go @@ -114,7 +114,7 @@ func TestGetTailLogBigFiles(t *testing.T) { f, err := os.Create(file) assert.NoError(t, err, "create log file") want := make([]*LogLine, 0, 2000) - for i := 0; i < 1000; i++ { + for range 1000 { _, err = f.WriteString(`2023-08-07T19:56:34.223758260-06:00 stdout P lin 2023-08-07T19:56:34.223758260-06:00 stdout F e2 `) diff --git a/libpod/networking_common.go b/libpod/networking_common.go index 8fbcacd66d..c45e653bc6 100644 --- a/libpod/networking_common.go +++ b/libpod/networking_common.go @@ -642,7 +642,7 @@ func getFreeInterfaceName(networks map[string]types.PerNetworkOptions) string { for _, opts := range networks { ifNames = append(ifNames, opts.InterfaceName) } - for i := 0; i < 100000; i++ { + for i := range 100000 { ifName := fmt.Sprintf("eth%d", i) if !slices.Contains(ifNames, ifName) { return ifName diff --git a/libpod/networking_linux_test.go b/libpod/networking_linux_test.go index 51f8bc724b..3d68fadd18 100644 --- a/libpod/networking_linux_test.go +++ b/libpod/networking_linux_test.go @@ -515,7 +515,7 @@ func Benchmark_ocicniPortsToNetTypesPorts10k(b *testing.B) { func Benchmark_ocicniPortsToNetTypesPorts1m(b *testing.B) { ports := make([]types.OCICNIPortMapping, 0, 1000000) - for j := 0; j < 20; j++ { + for j := range 20 { for i := int32(1); i <= 50000; i++ { ports = append(ports, types.OCICNIPortMapping{ HostPort: i, diff --git a/libpod/oci_conmon_common.go b/libpod/oci_conmon_common.go index 02fecd21f1..2cd531301c 100644 --- a/libpod/oci_conmon_common.go +++ b/libpod/oci_conmon_common.go @@ -691,7 +691,7 @@ func isRetryable(err error) bool { // openControlFile opens the terminal control file. func openControlFile(ctr *Container, parentDir string) (*os.File, error) { controlPath := filepath.Join(parentDir, "ctl") - for i := 0; i < 600; i++ { + for range 600 { controlFile, err := os.OpenFile(controlPath, unix.O_WRONLY|unix.O_NONBLOCK, 0) if err == nil { return controlFile, nil diff --git a/pkg/bindings/test/common_test.go b/pkg/bindings/test/common_test.go index e0e7cedc6c..c7963f53a6 100644 --- a/pkg/bindings/test/common_test.go +++ b/pkg/bindings/test/common_test.go @@ -154,7 +154,7 @@ func (b *bindingTest) startAPIService() *Session { session := b.runPodman(cmd) sock := strings.TrimPrefix(b.sock, "unix://") - for i := 0; i < 10; i++ { + for range 10 { if _, err := os.Stat(sock); err != nil { if !os.IsNotExist(err) { break diff --git a/pkg/bindings/test/networks_test.go b/pkg/bindings/test/networks_test.go index bcce82ce2a..aeb4b71c68 100644 --- a/pkg/bindings/test/networks_test.go +++ b/pkg/bindings/test/networks_test.go @@ -137,7 +137,7 @@ var _ = Describe("Podman networks", func() { It("list networks", func() { // create a bunch of named networks and make verify with list netNames := []string{"homer", "bart", "lisa", "maggie", "marge"} - for i := 0; i < 5; i++ { + for i := range 5 { net := types.Network{ Name: netNames[i], } diff --git a/pkg/bindings/test/volumes_test.go b/pkg/bindings/test/volumes_test.go index 255ad32f7d..cb7cc84bed 100644 --- a/pkg/bindings/test/volumes_test.go +++ b/pkg/bindings/test/volumes_test.go @@ -110,7 +110,7 @@ var _ = Describe("Podman volumes", func() { // create a bunch of named volumes and make verify with list volNames := []string{"homer", "bart", "lisa", "maggie", "marge"} - for i := 0; i < 5; i++ { + for i := range 5 { _, err = volumes.Create(connText, entities.VolumeCreateOptions{Name: volNames[i]}, nil) Expect(err).ToNot(HaveOccurred()) } diff --git a/pkg/k8s.io/apimachinery/pkg/api/resource/math.go b/pkg/k8s.io/apimachinery/pkg/api/resource/math.go index df17e605d8..5df189a175 100644 --- a/pkg/k8s.io/apimachinery/pkg/api/resource/math.go +++ b/pkg/k8s.io/apimachinery/pkg/api/resource/math.go @@ -148,7 +148,7 @@ func positiveScaleInt64(base int64, scale Scale) (int64, bool) { default: value := base var ok bool - for i := Scale(0); i < scale; i++ { + for range scale { if value, ok = int64MultiplyScale(value, 10); !ok { return 0, false } @@ -167,7 +167,7 @@ func negativeScaleInt64(base int64, scale Scale) (result int64, exact bool) { value := base var fraction bool - for i := Scale(0); i < scale; i++ { + for range scale { if !fraction && value%10 != 0 { fraction = true } diff --git a/pkg/machine/e2e/basic_test.go b/pkg/machine/e2e/basic_test.go index 12ff7161c7..45d525297d 100644 --- a/pkg/machine/e2e/basic_test.go +++ b/pkg/machine/e2e/basic_test.go @@ -331,7 +331,7 @@ func testHTTPServer(port string, shouldErr bool, expectedResponse string) { interval := 250 * time.Millisecond var err error var resp *http.Response - for i := 0; i < 6; i++ { + for range 6 { resp, err = http.Get(address.String() + "/testimage-id") if err != nil && shouldErr { Expect(err.Error()).To(ContainSubstring(expectedResponse)) diff --git a/pkg/machine/e2e/inspect_test.go b/pkg/machine/e2e/inspect_test.go index 5eea7909fa..7bc396a55d 100644 --- a/pkg/machine/e2e/inspect_test.go +++ b/pkg/machine/e2e/inspect_test.go @@ -80,7 +80,7 @@ var _ = Describe("podman inspect stop", func() { It("inspect shows a unique socket name per machine", func() { var socks []string - for c := 0; c < 2; c++ { + for range 2 { name := randomString() i := new(initMachine) session, err := mb.setName(name).setCmd(i.withImage(mb.imagePath)).run() diff --git a/pkg/machine/e2e/list_test.go b/pkg/machine/e2e/list_test.go index 4ae11064cc..226dadf400 100644 --- a/pkg/machine/e2e/list_test.go +++ b/pkg/machine/e2e/list_test.go @@ -91,7 +91,7 @@ var _ = Describe("podman machine list", func() { Expect(err).ToNot(HaveOccurred()) wait := 3 retries := (int)(mb.timeout/time.Second) / wait - for i := 0; i < retries; i++ { + for range retries { listSession, err := mb.setCmd(l).run() Expect(listSession).To(Exit(0)) Expect(err).ToNot(HaveOccurred()) diff --git a/pkg/machine/gvproxy_unix.go b/pkg/machine/gvproxy_unix.go index da76fc45c0..647572a7a0 100644 --- a/pkg/machine/gvproxy_unix.go +++ b/pkg/machine/gvproxy_unix.go @@ -24,7 +24,7 @@ const ( // an error is returned func backoffForProcess(p *psutil.Process) error { sleepInterval := sleepTime - for i := 0; i < loops; i++ { + for range loops { running, err := p.IsRunning() if err != nil { // It is possible that while in our loop, the PID vaporize triggering diff --git a/pkg/machine/qemu/machine.go b/pkg/machine/qemu/machine.go index 310b803c71..37b699bfed 100644 --- a/pkg/machine/qemu/machine.go +++ b/pkg/machine/qemu/machine.go @@ -94,7 +94,7 @@ func (q *QEMUStubber) checkStatus(monitor *qmp.SocketMonitor) (define.Status, er func (q *QEMUStubber) waitForMachineToStop(mc *vmconfigs.MachineConfig) error { fmt.Println("Waiting for VM to stop running...") waitInternal := 250 * time.Millisecond - for i := 0; i < 5; i++ { + for range 5 { state, err := q.State(mc, false) if err != nil { return err diff --git a/pkg/machine/shim/networking.go b/pkg/machine/shim/networking.go index 503a4030a4..23e69dc21b 100644 --- a/pkg/machine/shim/networking.go +++ b/pkg/machine/shim/networking.go @@ -124,7 +124,7 @@ func startNetworking(mc *vmconfigs.MachineConfig, provider vmconfigs.VMProvider) // conductVMReadinessCheck checks to make sure the machine is in the proper state // and that SSH is up and running func conductVMReadinessCheck(mc *vmconfigs.MachineConfig, maxBackoffs int, backoff time.Duration, stateF func() (define.Status, error)) (connected bool, sshError error, err error) { - for i := 0; i < maxBackoffs; i++ { + for i := range maxBackoffs { if i > 0 { time.Sleep(backoff) backoff *= 2 diff --git a/pkg/machine/sockets/sockets.go b/pkg/machine/sockets/sockets.go index 412db3aabc..83de8d6f28 100644 --- a/pkg/machine/sockets/sockets.go +++ b/pkg/machine/sockets/sockets.go @@ -37,7 +37,7 @@ func ListenAndWaitOnSocket(errChan chan<- error, listener net.Listener) { // DialSocketWithBackoffs attempts to connect to the socket in maxBackoffs attempts func DialSocketWithBackoffs(maxBackoffs int, backoff time.Duration, socketPath string) (conn net.Conn, err error) { - for i := 0; i < maxBackoffs; i++ { + for i := range maxBackoffs { if i > 0 { time.Sleep(backoff) backoff *= 2 @@ -62,7 +62,7 @@ func DialSocketWithBackoffsAndProcCheck( procPid int, errBuf *bytes.Buffer, ) (conn net.Conn, err error) { - for i := 0; i < maxBackoffs; i++ { + for i := range maxBackoffs { if i > 0 { time.Sleep(backoff) backoff *= 2 @@ -85,7 +85,7 @@ func DialSocketWithBackoffsAndProcCheck( func WaitForSocketWithBackoffs(maxBackoffs int, backoff time.Duration, socketPath string, name string) error { backoffWait := backoff logrus.Debugf("checking that %q socket is ready", name) - for i := 0; i < maxBackoffs; i++ { + for range maxBackoffs { err := fileutils.Exists(socketPath) if err == nil { return nil diff --git a/pkg/specgen/generate/ports.go b/pkg/specgen/generate/ports.go index 0ff3eadbe3..4e878f2e61 100644 --- a/pkg/specgen/generate/ports.go +++ b/pkg/specgen/generate/ports.go @@ -99,7 +99,7 @@ func addPortToUsedPorts(ports *[]types.PortMapping, allHostPorts, allContainerPo // the caller has to supply an array with the already used ports func getRandomHostPort(hostPorts *[65536]bool, port types.PortMapping) (types.PortMapping, error) { outer: - for i := 0; i < 15; i++ { + for range 15 { ranPort, err := utils.GetRandomPort() if err != nil { return port, err diff --git a/pkg/specgen/generate/ports_bench_test.go b/pkg/specgen/generate/ports_bench_test.go index 4a236de0eb..114d100c5f 100644 --- a/pkg/specgen/generate/ports_bench_test.go +++ b/pkg/specgen/generate/ports_bench_test.go @@ -70,7 +70,7 @@ func BenchmarkParsePortMapping10k(b *testing.B) { func BenchmarkParsePortMapping1m(b *testing.B) { ports := make([]types.PortMapping, 0, 1000000) - for j := 0; j < 20; j++ { + for j := range 20 { for i := uint16(1); i <= 50000; i++ { ports = append(ports, types.PortMapping{ HostPort: i, @@ -125,7 +125,7 @@ func BenchmarkParsePortMappingReverse10k(b *testing.B) { func BenchmarkParsePortMappingReverse1m(b *testing.B) { ports := make([]types.PortMapping, 0, 1000000) - for j := 0; j < 20; j++ { + for j := range 20 { for i := uint16(50000); i > 0; i-- { ports = append(ports, types.PortMapping{ HostPort: i, @@ -185,7 +185,7 @@ func BenchmarkParsePortMappingRange10k(b *testing.B) { func BenchmarkParsePortMappingRange1m(b *testing.B) { ports := make([]types.PortMapping, 0, 1000000) - for j := 0; j < 20; j++ { + for j := range 20 { ports = append(ports, types.PortMapping{ HostPort: 1, ContainerPort: 1, diff --git a/pkg/specgenutil/util.go b/pkg/specgenutil/util.go index ff152f7709..fc36c78181 100644 --- a/pkg/specgenutil/util.go +++ b/pkg/specgenutil/util.go @@ -62,7 +62,7 @@ func CreateExpose(expose []string) (map[uint16]string, error) { } var index uint16 - for index = 0; index < len; index++ { + for index = range len { portNum := start + index protocols, ok := toReturn[portNum] if !ok { diff --git a/pkg/systemd/notifyproxy/notifyproxy_test.go b/pkg/systemd/notifyproxy/notifyproxy_test.go index e6767ab34d..b5147bbec4 100644 --- a/pkg/systemd/notifyproxy/notifyproxy_test.go +++ b/pkg/systemd/notifyproxy/notifyproxy_test.go @@ -48,7 +48,7 @@ func TestWaitAndClose(t *testing.T) { sendMessage(t, proxy, daemon.SdNotifyReady+"\nsomething else\n") done := func() bool { - for i := 0; i < 10; i++ { + for i := range 10 { select { case err := <-ch: require.NoError(t, err, "Waiting should succeed") diff --git a/pkg/systemd/parser/split.go b/pkg/systemd/parser/split.go index cd2dfed221..5c62bc7fee 100644 --- a/pkg/systemd/parser/split.go +++ b/pkg/systemd/parser/split.go @@ -124,7 +124,7 @@ func cUnescapeOne(p string, acceptNul bool) (int, rune, bool) { } var a [4]int - for i := 0; i < 4; i++ { + for i := range 4 { a[i] = unhexchar(p[1+i]) if a[i] < 0 { return -1, 0, false @@ -148,7 +148,7 @@ func cUnescapeOne(p string, acceptNul bool) (int, rune, bool) { } var a [8]int - for i := 0; i < 8; i++ { + for i := range 8 { a[i] = unhexchar(p[1+i]) if a[i] < 0 { return -10, 0, false diff --git a/pkg/util/utils.go b/pkg/util/utils.go index c386474678..929beee351 100644 --- a/pkg/util/utils.go +++ b/pkg/util/utils.go @@ -392,7 +392,7 @@ func parseTriple(spec []string, parentMapping []ruser.IDMap, mapSetting string) if hidIsParent { if (mapSetting == "UID" && flags.UserMap) || (mapSetting == "GID" && flags.GroupMap) { - for i := uint64(0); i < sz; i++ { + for i := range sz { cids = append(cids, cid+i) mappedID, err := mapIDwithMapping(hid+i, parentMapping, mapSetting) if err != nil { @@ -844,7 +844,7 @@ func parseAutoTriple(spec []string, parentMapping []ruser.IDMap, mapSetting stri } if hidIsParent { - for i := uint64(0); i < sz; i++ { + for i := range sz { cids = append(cids, cid+i) mappedID, err := mapIDwithMapping(hid+i, parentMapping, mapSetting) if err != nil { diff --git a/test/e2e/checkpoint_test.go b/test/e2e/checkpoint_test.go index 57613d01ec..74c35629e4 100644 --- a/test/e2e/checkpoint_test.go +++ b/test/e2e/checkpoint_test.go @@ -730,7 +730,7 @@ var _ = Describe("Podman checkpoint", func() { Expect(result.OutputToString()).To(Equal(cid), "checkpoint output") // Allow a few seconds for --rm to take effect ncontainers := podmanTest.NumberOfContainers() - for try := 0; try < 4; try++ { + for range 4 { if ncontainers == 0 { break } diff --git a/test/e2e/common_test.go b/test/e2e/common_test.go index 9d081087a7..f3f6650ba2 100644 --- a/test/e2e/common_test.go +++ b/test/e2e/common_test.go @@ -447,7 +447,7 @@ func (p *PodmanTestIntegration) pullImage(image string, toCache bool) { p.Root = oldRoot }() } - for try := 0; try < 3; try++ { + for try := range 3 { podmanSession := p.PodmanExecBaseWithOptions([]string{"pull", image}, PodmanExecOptions{ NoEvents: toCache, NoCache: true, @@ -874,7 +874,7 @@ func (p *PodmanTestIntegration) RunTopContainerInPod(name, pod string) *PodmanSe } func (p *PodmanTestIntegration) RunHealthCheck(cid string) error { - for i := 0; i < 10; i++ { + for range 10 { hc := p.Podman([]string{"healthcheck", "run", cid}) hc.WaitWithDefaultTimeout() if hc.ExitCode() == 0 { @@ -1405,7 +1405,7 @@ func GetPort() int { nProcs := GinkgoT().ParallelTotal() myProc := GinkgoT().ParallelProcess() - 1 - for i := 0; i < 50; i++ { + for range 50 { // Random port within that range port := portMin + rng.Intn((portMax-portMin)/nProcs)*nProcs + myProc @@ -1451,7 +1451,7 @@ var IPRegex = `(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01 // format and iterates a string array for match func digShort(container, lookupName, expectedIP string, p *PodmanTestIntegration) { digInterval := time.Millisecond * 250 - for i := 0; i < 6; i++ { + for i := range 6 { time.Sleep(digInterval * time.Duration(i)) dig := p.Podman([]string{"exec", container, "dig", "+short", lookupName}) dig.WaitWithDefaultTimeout() diff --git a/test/e2e/create_staticip_test.go b/test/e2e/create_staticip_test.go index 32a72b7880..a3baecc360 100644 --- a/test/e2e/create_staticip_test.go +++ b/test/e2e/create_staticip_test.go @@ -62,7 +62,7 @@ var _ = Describe("Podman create with --ip flag", func() { // race prevention: wait until IP address is assigned and // container is running. - for i := 0; i < 5; i++ { + for range 5 { result = podmanTest.Podman([]string{"inspect", "--format", "{{.State.Status}} {{.NetworkSettings.IPAddress}}", "test1"}) result.WaitWithDefaultTimeout() Expect(result).Should(ExitCleanly()) diff --git a/test/e2e/create_test.go b/test/e2e/create_test.go index ca59962f96..c01acecdc0 100644 --- a/test/e2e/create_test.go +++ b/test/e2e/create_test.go @@ -465,7 +465,7 @@ var _ = Describe("Podman create", func() { // Create and replace 5 times in a row the "same" container. ctrName := "testCtr" - for i := 0; i < 5; i++ { + for range 5 { session = podmanTest.Podman([]string{"create", "--replace", "--name", ctrName, ALPINE, "/bin/sh"}) session.WaitWithDefaultTimeout() Expect(session).Should(ExitCleanly()) diff --git a/test/e2e/events_test.go b/test/e2e/events_test.go index c86ef9e78b..a37b7778c6 100644 --- a/test/e2e/events_test.go +++ b/test/e2e/events_test.go @@ -293,7 +293,7 @@ var _ = Describe("Podman events", func() { session.WaitWithDefaultTimeout() Expect(session).Should(ExitCleanly()) - for i := 0; i < 5; i++ { + for i := range 5 { hc := podmanTest.Podman([]string{"healthcheck", "run", "test-hc"}) hc.WaitWithDefaultTimeout() exitCode := hc.ExitCode() diff --git a/test/e2e/exec_test.go b/test/e2e/exec_test.go index 7850eadb84..128eab7695 100644 --- a/test/e2e/exec_test.go +++ b/test/e2e/exec_test.go @@ -348,7 +348,7 @@ var _ = Describe("Podman exec", func() { Expect(setup).Should(Exit(0)) Expect(setup.ErrorToString()).To(ContainSubstring("The input device is not a TTY. The --tty and --interactive flags might not work properly")) - for i := 0; i < 5; i++ { + for range 5 { session := podmanTest.Podman([]string{"exec", "-ti", "test1", "true"}) session.WaitWithDefaultTimeout() Expect(session).Should(ExitCleanly()) diff --git a/test/e2e/healthcheck_run_test.go b/test/e2e/healthcheck_run_test.go index c3397c494b..6d9a0c14ec 100644 --- a/test/e2e/healthcheck_run_test.go +++ b/test/e2e/healthcheck_run_test.go @@ -105,7 +105,7 @@ var _ = Describe("Podman healthcheck run", func() { exitCode := 999 // Buy a little time to get container running - for i := 0; i < 5; i++ { + for i := range 5 { hc := podmanTest.Podman([]string{"healthcheck", "run", "hc"}) hc.WaitWithDefaultTimeout() exitCode = hc.ExitCode() diff --git a/test/e2e/network_test.go b/test/e2e/network_test.go index 67f22aca67..288eb0a2e5 100644 --- a/test/e2e/network_test.go +++ b/test/e2e/network_test.go @@ -511,7 +511,7 @@ var _ = Describe("Podman network", func() { Expect(session).Should(ExitCleanly()) interval := 250 * time.Millisecond - for i := 0; i < 6; i++ { + for range 6 { n := podmanTest.Podman([]string{"network", "exists", netName}) n.WaitWithDefaultTimeout() worked = n.ExitCode() == 0 @@ -527,7 +527,7 @@ var _ = Describe("Podman network", func() { Expect(top).Should(ExitCleanly()) interval = 250 * time.Millisecond // Wait for the nginx service to be running - for i := 0; i < 6; i++ { + for range 6 { // Test curl against the container's name c1 := podmanTest.Podman([]string{"run", "--dns-search", "dns.podman", "--network=" + netName, NGINX_IMAGE, "curl", "web"}) c1.WaitWithDefaultTimeout() diff --git a/test/e2e/pause_test.go b/test/e2e/pause_test.go index bf9132a49a..e9451a897a 100644 --- a/test/e2e/pause_test.go +++ b/test/e2e/pause_test.go @@ -257,7 +257,7 @@ var _ = Describe("Podman pause", func() { }) It("Pause a bunch of running containers", func() { - for i := 0; i < 3; i++ { + for i := range 3 { name := fmt.Sprintf("test%d", i) run := podmanTest.Podman([]string{"run", "-dt", "--name", name, NGINX_IMAGE}) run.WaitWithDefaultTimeout() @@ -284,7 +284,7 @@ var _ = Describe("Podman pause", func() { }) It("Unpause a bunch of running containers", func() { - for i := 0; i < 3; i++ { + for i := range 3 { name := fmt.Sprintf("test%d", i) run := podmanTest.Podman([]string{"run", "-dt", "--name", name, NGINX_IMAGE}) run.WaitWithDefaultTimeout() diff --git a/test/e2e/play_kube_test.go b/test/e2e/play_kube_test.go index 823df9bd23..2cf648511a 100644 --- a/test/e2e/play_kube_test.go +++ b/test/e2e/play_kube_test.go @@ -2339,7 +2339,7 @@ func testHTTPServer(port string, shouldErr bool, expectedResponse string) { interval := 250 * time.Millisecond var err error var resp *http.Response - for i := 0; i < 6; i++ { + for range 6 { resp, err = http.Get(address.String()) if err != nil && shouldErr { Expect(err.Error()).To(ContainSubstring(expectedResponse)) @@ -4437,7 +4437,7 @@ spec: app: %s ` // generate services, pods and deployments - for i := 0; i < 2; i++ { + for i := range 2 { podName := fmt.Sprintf("testPod%d", i) deploymentName := fmt.Sprintf("testDeploy%d", i) deploymentPodName := fmt.Sprintf("%s-pod", deploymentName) diff --git a/test/e2e/pod_create_test.go b/test/e2e/pod_create_test.go index d18bb1f00e..17b2c38062 100644 --- a/test/e2e/pod_create_test.go +++ b/test/e2e/pod_create_test.go @@ -450,7 +450,7 @@ var _ = Describe("Podman pod create", func() { // Create and replace 5 times in a row the "same" pod. podName := "testCtr" - for i := 0; i < 5; i++ { + for range 5 { session = podmanTest.Podman([]string{"pod", "create", "--replace", "--name", podName}) session.WaitWithDefaultTimeout() Expect(session).Should(ExitCleanly()) @@ -862,7 +862,7 @@ ENTRYPOINT ["sleep","99999"] } m := make(map[string]string) - for i := 0; i < 5; i++ { + for i := range 5 { podName := "testPod" + strconv.Itoa(i) podCreate := podmanTest.Podman([]string{"pod", "create", "--userns=auto", "--name", podName}) podCreate.WaitWithDefaultTimeout() diff --git a/test/e2e/pod_top_test.go b/test/e2e/pod_top_test.go index b42b50720f..b41e67909a 100644 --- a/test/e2e/pod_top_test.go +++ b/test/e2e/pod_top_test.go @@ -121,7 +121,7 @@ var _ = Describe("Podman top", func() { session.WaitWithDefaultTimeout() Expect(session).Should(ExitCleanly()) - for i := 0; i < 10; i++ { + for range 10 { GinkgoWriter.Println("Waiting for containers to be running .... ") if podmanTest.NumberOfContainersRunning() == 2 { break diff --git a/test/e2e/rmi_test.go b/test/e2e/rmi_test.go index b4ed4bad11..fc764fd20b 100644 --- a/test/e2e/rmi_test.go +++ b/test/e2e/rmi_test.go @@ -263,7 +263,7 @@ RUN find $LOCAL // Prepare images wg.Add(10) - for i := 0; i < 10; i++ { + for i := range 10 { go func(i int) { defer GinkgoRecover() defer wg.Done() @@ -278,7 +278,7 @@ RUN find $LOCAL // A herd of concurrent removals wg.Add(10) - for i := 0; i < 10; i++ { + for i := range 10 { go func(i int) { defer GinkgoRecover() defer wg.Done() diff --git a/test/e2e/run_test.go b/test/e2e/run_test.go index 6681db9000..51c6e34880 100644 --- a/test/e2e/run_test.go +++ b/test/e2e/run_test.go @@ -761,7 +761,7 @@ USER bin`, BB) session.WaitWithDefaultTimeout() Expect(session).Should(ExitCleanly()) - for i := 0; i < 2; i++ { + for range 2 { session = podmanTest.Podman([]string{"start", "-a", name}) session.WaitWithDefaultTimeout() Expect(session).Should(ExitCleanly()) @@ -1681,7 +1681,7 @@ VOLUME %s`, ALPINE, volPath, volPath) found := false testFile := filepath.Join(testDir, "ran") - for i := 0; i < 30; i++ { + for range 30 { time.Sleep(1 * time.Second) if _, err := os.Stat(testFile); err == nil { found = true @@ -1699,7 +1699,7 @@ VOLUME %s`, ALPINE, volPath, volPath) // 10 seconds to restart the container found = false - for i := 0; i < 10; i++ { + for range 10 { time.Sleep(1 * time.Second) if _, err := os.Stat(testFile); err == nil { found = true @@ -1887,7 +1887,7 @@ VOLUME %s`, ALPINE, volPath, volPath) // Run and replace 5 times in a row the "same" container. ctrName := "testCtr" - for i := 0; i < 5; i++ { + for range 5 { session := podmanTest.Podman([]string{"run", "--detach", "--replace", "--name", ctrName, ALPINE, "top"}) session.WaitWithDefaultTimeout() // FIXME - #20196: Cannot use ExitCleanly() diff --git a/test/e2e/run_userns_test.go b/test/e2e/run_userns_test.go index 00fd5d53f0..ee4c5e7021 100644 --- a/test/e2e/run_userns_test.go +++ b/test/e2e/run_userns_test.go @@ -215,7 +215,7 @@ var _ = Describe("Podman UserNS support", func() { } m := make(map[string]string) - for i := 0; i < 5; i++ { + for range 5 { session := podmanTest.Podman([]string{"run", "--userns=auto", "alpine", "cat", "/proc/self/uid_map"}) session.WaitWithDefaultTimeout() Expect(session).Should(ExitCleanly()) diff --git a/test/e2e/search_test.go b/test/e2e/search_test.go index 4d9f296d0a..8815f1eecb 100644 --- a/test/e2e/search_test.go +++ b/test/e2e/search_test.go @@ -146,7 +146,7 @@ registries = []` search.WaitWithDefaultTimeout() Expect(search).Should(ExitCleanly()) output := search.OutputToStringArray() - for i := 0; i < len(output); i++ { + for i := range output { Expect(strconv.Atoi(output[i])).To(BeNumerically(">=", 10)) } }) @@ -156,7 +156,7 @@ registries = []` search.WaitWithDefaultTimeout() Expect(search).Should(ExitCleanly()) output := search.OutputToStringArray() - for i := 0; i < len(output); i++ { + for i := range output { Expect(output[i]).To(Equal("[OK]")) } }) @@ -166,7 +166,7 @@ registries = []` search.WaitWithDefaultTimeout() Expect(search).Should(ExitCleanly()) output := search.OutputToStringArray() - for i := 0; i < len(output); i++ { + for i := range output { Expect(output[i]).To(Equal("")) } }) diff --git a/test/e2e/stats_test.go b/test/e2e/stats_test.go index 4a4fc460c0..446cd21e8e 100644 --- a/test/e2e/stats_test.go +++ b/test/e2e/stats_test.go @@ -117,7 +117,7 @@ var _ = Describe("Podman stats", func() { session := podmanTest.RunTopContainer("") session.WaitWithDefaultTimeout() Expect(session).Should(ExitCleanly()) - for i := 0; i < 5; i++ { + for range 5 { ps := podmanTest.Podman([]string{"ps", "-q"}) ps.WaitWithDefaultTimeout() if len(ps.OutputToStringArray()) == 1 { diff --git a/test/e2e/system_connection_test.go b/test/e2e/system_connection_test.go index 1e53ccd0f2..ec07cf2140 100644 --- a/test/e2e/system_connection_test.go +++ b/test/e2e/system_connection_test.go @@ -245,7 +245,7 @@ QA-UDS1 unix:///run/user/podman/podman.sock false true Expect(session).Should(ExitCleanly()) // two passes to test that removing non-existent connection is not an error - for i := 0; i < 2; i++ { + for range 2 { session = podmanTest.Podman([]string{"system", "connection", "remove", "QA"}) session.WaitWithDefaultTimeout() Expect(session).Should(ExitCleanly()) diff --git a/test/goecho/goecho.go b/test/goecho/goecho.go index 1c8d2f586f..a44389b0b1 100644 --- a/test/goecho/goecho.go +++ b/test/goecho/goecho.go @@ -11,7 +11,7 @@ func main() { args := os.Args[1:] exitCode := 0 - for i := 0; i < len(args); i++ { + for i := range args { fmt.Fprintln(os.Stdout, args[i]) fmt.Fprintln(os.Stderr, args[i]) } diff --git a/test/utils/utils.go b/test/utils/utils.go index 812f1deeee..ed4da84690 100644 --- a/test/utils/utils.go +++ b/test/utils/utils.go @@ -165,7 +165,7 @@ func (p *PodmanTest) PodmanExecBaseWithOptions(args []string, options PodmanExec // WaitForContainer waits on a started container func (p *PodmanTest) WaitForContainer() bool { - for i := 0; i < 10; i++ { + for range 10 { if p.NumberOfContainersRunning() > 0 { return true } From 01821856f8e70a0082169c6895e12eefa2c51c2b Mon Sep 17 00:00:00 2001 From: Kir Kolyshkin Date: Thu, 14 Aug 2025 15:23:07 -0700 Subject: [PATCH 04/10] Use strings.CutPrefix where appropriate Replace some uses of HasPrefix followed by TrimPrefix with CutPrefix, added to the strings package in go1.20. Brought to you by modernize -test -fix -category stringscutprefix ./... Signed-off-by: Kir Kolyshkin --- cmd/podman/machine/os/manager.go | 8 ++++---- libpod/info.go | 16 ++++++++-------- pkg/bindings/images/build.go | 4 ++-- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/cmd/podman/machine/os/manager.go b/cmd/podman/machine/os/manager.go index 234246cf1d..8c56c35697 100644 --- a/cmd/podman/machine/os/manager.go +++ b/cmd/podman/machine/os/manager.go @@ -89,11 +89,11 @@ func GetDistribution() Distribution { l := bufio.NewScanner(f) for l.Scan() { - if strings.HasPrefix(l.Text(), "ID=") { - dist.Name = strings.TrimPrefix(l.Text(), "ID=") + if after, ok := strings.CutPrefix(l.Text(), "ID="); ok { + dist.Name = after } - if strings.HasPrefix(l.Text(), "VARIANT_ID=") { - dist.Variant = strings.Trim(strings.TrimPrefix(l.Text(), "VARIANT_ID="), "\"") + if after, ok := strings.CutPrefix(l.Text(), "VARIANT_ID="); ok { + dist.Variant = strings.Trim(after, "\"") } } return dist diff --git a/libpod/info.go b/libpod/info.go index 028223c740..e951b8710b 100644 --- a/libpod/info.go +++ b/libpod/info.go @@ -306,17 +306,17 @@ func (r *Runtime) GetHostDistributionInfo() define.DistributionInfo { l := bufio.NewScanner(f) for l.Scan() { - if strings.HasPrefix(l.Text(), "ID=") { - dist.Distribution = strings.Trim(strings.TrimPrefix(l.Text(), "ID="), "\"") + if after, ok := strings.CutPrefix(l.Text(), "ID="); ok { + dist.Distribution = strings.Trim(after, "\"") } - if strings.HasPrefix(l.Text(), "VARIANT_ID=") { - dist.Variant = strings.Trim(strings.TrimPrefix(l.Text(), "VARIANT_ID="), "\"") + if after, ok := strings.CutPrefix(l.Text(), "VARIANT_ID="); ok { + dist.Variant = strings.Trim(after, "\"") } - if strings.HasPrefix(l.Text(), "VERSION_ID=") { - dist.Version = strings.Trim(strings.TrimPrefix(l.Text(), "VERSION_ID="), "\"") + if after, ok := strings.CutPrefix(l.Text(), "VERSION_ID="); ok { + dist.Version = strings.Trim(after, "\"") } - if strings.HasPrefix(l.Text(), "VERSION_CODENAME=") { - dist.Codename = strings.Trim(strings.TrimPrefix(l.Text(), "VERSION_CODENAME="), "\"") + if after, ok := strings.CutPrefix(l.Text(), "VERSION_CODENAME="); ok { + dist.Codename = strings.Trim(after, "\"") } } return dist diff --git a/pkg/bindings/images/build.go b/pkg/bindings/images/build.go index cff4ed3f05..5ad6b224e9 100644 --- a/pkg/bindings/images/build.go +++ b/pkg/bindings/images/build.go @@ -555,8 +555,8 @@ func Build(ctx context.Context, containerFiles []string, options types.BuildOpti // Check if Containerfile is in the context directory, if so truncate the context directory off path // Do NOT add to tarfile - if strings.HasPrefix(containerfile, contextDir+string(filepath.Separator)) { - containerfile = strings.TrimPrefix(containerfile, contextDir+string(filepath.Separator)) + if after, ok := strings.CutPrefix(containerfile, contextDir+string(filepath.Separator)); ok { + containerfile = after dontexcludes = append(dontexcludes, "!"+containerfile) dontexcludes = append(dontexcludes, "!"+containerfile+".dockerignore") dontexcludes = append(dontexcludes, "!"+containerfile+".containerignore") From d3a0b2cc3ba91d6a65f5dd18213e42eb48f0375b Mon Sep 17 00:00:00 2001 From: Kir Kolyshkin Date: Thu, 14 Aug 2025 15:24:57 -0700 Subject: [PATCH 05/10] pkg/api/handlers/compat: use strings.CutPrefix This way we don't check the string twice. Signed-off-by: Kir Kolyshkin --- pkg/api/handlers/compat/images_build.go | 23 ++++++++--------------- 1 file changed, 8 insertions(+), 15 deletions(-) diff --git a/pkg/api/handlers/compat/images_build.go b/pkg/api/handlers/compat/images_build.go index e3dd422c37..01d53cac2b 100644 --- a/pkg/api/handlers/compat/images_build.go +++ b/pkg/api/handlers/compat/images_build.go @@ -964,10 +964,8 @@ func handleBuildContexts(anchorDir string, r *http.Request, multipart bool) (con logrus.Debugf("name: %q, context: %q", name, value) - switch { - case strings.HasPrefix(value, "url:"): - value = strings.TrimPrefix(value, "url:") - tempDir, subdir, err := buildahDefine.TempDirForURL(anchorDir, "buildah", value) + if urlValue, ok := strings.CutPrefix(value, "url:"); ok { + tempDir, subdir, err := buildahDefine.TempDirForURL(anchorDir, "buildah", urlValue) if err != nil { return "", nil, fmt.Errorf("downloading URL %q: %w", name, err) } @@ -981,15 +979,14 @@ func handleBuildContexts(anchorDir string, r *http.Request, multipart bool) (con } logrus.Debugf("Downloaded URL context %q to %q", name, contextPath) - case strings.HasPrefix(value, "image:"): - value = strings.TrimPrefix(value, "image:") + } else if imageValue, ok := strings.CutPrefix(value, "image:"); ok { additionalContexts[name] = &buildahDefine.AdditionalBuildContext{ IsURL: false, IsImage: true, - Value: value, + Value: imageValue, } - logrus.Debugf("Using image context %q: %q", name, value) + logrus.Debugf("Using image context %q: %q", name, imageValue) } } @@ -1012,8 +1009,7 @@ func handleBuildContexts(anchorDir string, r *http.Request, multipart bool) (con fieldName := part.FormName() - switch { - case fieldName == "MainContext": + if fieldName == "MainContext" { mainDir, err := extractTarFile(anchorDir, part) if err != nil { part.Close() @@ -1025,10 +1021,7 @@ func handleBuildContexts(anchorDir string, r *http.Request, multipart bool) (con } contextDir = mainDir part.Close() - - case strings.HasPrefix(fieldName, "build-context-"): - contextName := strings.TrimPrefix(fieldName, "build-context-") - + } else if contextName, ok := strings.CutPrefix(fieldName, "build-context-"); ok { // Create temp directory directly under anchorDir additionalAnchor, err := os.MkdirTemp(anchorDir, contextName+"-*") if err != nil { @@ -1079,7 +1072,7 @@ func handleBuildContexts(anchorDir string, r *http.Request, multipart bool) (con Value: additionalAnchor, } part.Close() - default: + } else { logrus.Debugf("Ignoring unknown multipart field: %s", fieldName) part.Close() } From 1168a3391f094fe8aa6f5075fee60b044f2f194c Mon Sep 17 00:00:00 2001 From: Kir Kolyshkin Date: Thu, 14 Aug 2025 15:32:48 -0700 Subject: [PATCH 06/10] Use min and max functions where appropriate Brought to you by modernize -test -fix -category=minmax ./... Signed-off-by: Kir Kolyshkin --- libpod/logs/reversereader/reversereader.go | 5 +---- pkg/machine/compression/sparse_file_writer_test.go | 5 +---- 2 files changed, 2 insertions(+), 8 deletions(-) diff --git a/libpod/logs/reversereader/reversereader.go b/libpod/logs/reversereader/reversereader.go index ba33e8366b..409be32fbf 100644 --- a/libpod/logs/reversereader/reversereader.go +++ b/libpod/logs/reversereader/reversereader.go @@ -33,10 +33,7 @@ func NewReverseReader(reader *os.File) (*ReverseReader, error) { } // set offset (starting position) to the last page boundary or // zero if fits in one page - startOffset := end - remainder - if startOffset < 0 { - startOffset = 0 - } + startOffset := max(end-remainder, 0) rr := ReverseReader{ reader: reader, offset: startOffset, diff --git a/pkg/machine/compression/sparse_file_writer_test.go b/pkg/machine/compression/sparse_file_writer_test.go index d4a06625b4..a47a5417ce 100644 --- a/pkg/machine/compression/sparse_file_writer_test.go +++ b/pkg/machine/compression/sparse_file_writer_test.go @@ -63,10 +63,7 @@ func testInputWithWriteLen(t *testing.T, input []byte, minSparse int64, chunkSiz sparseWriter := NewSparseWriter(m) for i := 0; i < len(input); i += chunkSize { - end := i + chunkSize - if end > len(input) { - end = len(input) - } + end := min(i+chunkSize, len(input)) _, err := sparseWriter.Write(input[i:end]) if err != nil { t.Fatalf("Expected no error, got %v", err) From 846686bf913dfe9ec131f73bcc214889facd2e31 Mon Sep 17 00:00:00 2001 From: Kir Kolyshkin Date: Thu, 14 Aug 2025 15:33:56 -0700 Subject: [PATCH 07/10] Use fmt.Appendf where []byte is needed Replace []byte(fmt.Sprintf...) by fmt.Appendf(nil, ...), added in go1.19. Brought to you by modernize -test -fix -category=fmtappendf ./... Signed-off-by: Kir Kolyshkin --- libpod/util.go | 2 +- pkg/api/handlers/compat/images_build.go | 2 +- pkg/domain/infra/abi/generate.go | 2 +- test/e2e/build_test.go | 4 ++-- test/e2e/containers_conf_test.go | 8 ++++---- test/e2e/info_test.go | 2 +- test/e2e/login_logout_test.go | 10 +++++----- test/e2e/play_kube_test.go | 2 +- test/e2e/pod_create_test.go | 2 +- test/e2e/pull_chunked_test.go | 2 +- test/e2e/pull_test.go | 2 +- test/e2e/run_device_test.go | 4 ++-- test/e2e/run_test.go | 2 +- test/e2e/run_userns_test.go | 2 +- 14 files changed, 23 insertions(+), 23 deletions(-) diff --git a/libpod/util.go b/libpod/util.go index c7eb475b23..59479f5312 100644 --- a/libpod/util.go +++ b/libpod/util.go @@ -128,7 +128,7 @@ func checkDependencyContainer(depCtr, ctr *Container) error { // hijackWriteError writes an error to a hijacked HTTP session. func hijackWriteError(toWrite error, cid string, terminal bool, httpBuf *bufio.ReadWriter) { if toWrite != nil && !errors.Is(toWrite, define.ErrDetach) { - errString := []byte(fmt.Sprintf("Error: %v\n", toWrite)) + errString := fmt.Appendf(nil, "Error: %v\n", toWrite) if !terminal { // We need a header. header := makeHTTPAttachHeader(2, uint32(len(errString))) diff --git a/pkg/api/handlers/compat/images_build.go b/pkg/api/handlers/compat/images_build.go index 01d53cac2b..c13054587a 100644 --- a/pkg/api/handlers/compat/images_build.go +++ b/pkg/api/handlers/compat/images_build.go @@ -922,7 +922,7 @@ func BuildImage(w http.ResponseWriter, r *http.Request) { case <-runCtx.Done(): if success { if !utils.IsLibpodRequest(r) && !query.Quiet { - m.Aux = []byte(fmt.Sprintf(`{"ID":"sha256:%s"}`, imageID)) + m.Aux = fmt.Appendf(nil, `{"ID":"sha256:%s"}`, imageID) if err := enc.Encode(m); err != nil { logrus.Warnf("failed to json encode error %v", err) } diff --git a/pkg/domain/infra/abi/generate.go b/pkg/domain/infra/abi/generate.go index bb6d2c3484..06c677842f 100644 --- a/pkg/domain/infra/abi/generate.go +++ b/pkg/domain/infra/abi/generate.go @@ -402,7 +402,7 @@ func generateKubeOutput(content [][]byte) ([]byte, error) { } // Add header to kube YAML file. - output = append(output, []byte(fmt.Sprintf(header, podmanVersion.Version))...) + output = append(output, fmt.Appendf(nil, header, podmanVersion.Version)...) // kube generate order is based on helm install order (secret, persistentVolume, service, pod...). // Add kube kinds. diff --git a/test/e2e/build_test.go b/test/e2e/build_test.go index a1f8375fad..95458142ce 100644 --- a/test/e2e/build_test.go +++ b/test/e2e/build_test.go @@ -258,7 +258,7 @@ var _ = Describe("Podman build", func() { defer Expect(os.Chdir(cwd)).To(BeNil()) fakeFile := filepath.Join(os.TempDir(), "Containerfile") - Expect(os.WriteFile(fakeFile, []byte(fmt.Sprintf("FROM %s", CITEST_IMAGE)), 0755)).To(Succeed()) + Expect(os.WriteFile(fakeFile, fmt.Appendf(nil, "FROM %s", CITEST_IMAGE), 0755)).To(Succeed()) targetFile := filepath.Join(podmanTest.TempDir, "Containerfile") Expect(os.WriteFile(targetFile, []byte("FROM scratch"), 0755)).To(Succeed()) @@ -795,7 +795,7 @@ RUN grep CapEff /proc/self/status` It("podman build --isolation && --arch", func() { targetPath := podmanTest.TempDir containerFile := filepath.Join(targetPath, "Containerfile") - Expect(os.WriteFile(containerFile, []byte(fmt.Sprintf("FROM %s", CITEST_IMAGE)), 0755)).To(Succeed()) + Expect(os.WriteFile(containerFile, fmt.Appendf(nil, "FROM %s", CITEST_IMAGE), 0755)).To(Succeed()) defer func() { Expect(os.RemoveAll(containerFile)).To(Succeed()) diff --git a/test/e2e/containers_conf_test.go b/test/e2e/containers_conf_test.go index fac038e096..62a52c9b6b 100644 --- a/test/e2e/containers_conf_test.go +++ b/test/e2e/containers_conf_test.go @@ -296,7 +296,7 @@ var _ = Describe("Verify podman containers.conf usage", func() { volume := filepath.Join(podmanTest.TempDir, "vol") err = os.MkdirAll(volume, os.ModePerm) Expect(err).ToNot(HaveOccurred()) - err := os.WriteFile(conffile, []byte(fmt.Sprintf("[containers]\nvolumes=[\"%s:%s:Z\",]\n", volume, volume)), 0755) + err := os.WriteFile(conffile, fmt.Appendf(nil, "[containers]\nvolumes=[\"%s:%s:Z\",]\n", volume, volume), 0755) Expect(err).ToNot(HaveOccurred()) os.Setenv("CONTAINERS_CONF", conffile) @@ -494,7 +494,7 @@ var _ = Describe("Verify podman containers.conf usage", func() { JustBeforeEach(func() { conffile := filepath.Join(podmanTest.TempDir, "containers.conf") - err = os.WriteFile(conffile, []byte(fmt.Sprintf("[containers]\nbase_hosts_file=\"%s\"\nno_hosts=false\n", baseHostsFile)), 0755) + err = os.WriteFile(conffile, fmt.Appendf(nil, "[containers]\nbase_hosts_file=\"%s\"\nno_hosts=false\n", baseHostsFile), 0755) Expect(err).ToNot(HaveOccurred()) os.Setenv("CONTAINERS_CONF_OVERRIDE", conffile) if IsRemote() { @@ -566,7 +566,7 @@ var _ = Describe("Verify podman containers.conf usage", func() { os.Setenv("CONTAINERS_CONF", configPath) profile := filepath.Join(podmanTest.TempDir, "seccomp.json") - containersConf := []byte(fmt.Sprintf("[containers]\nseccomp_profile=\"%s\"", profile)) + containersConf := fmt.Appendf(nil, "[containers]\nseccomp_profile=\"%s\"", profile) err = os.WriteFile(configPath, containersConf, os.ModePerm) Expect(err).ToNot(HaveOccurred()) @@ -614,7 +614,7 @@ var _ = Describe("Verify podman containers.conf usage", func() { Expect(session).Should(ExitCleanly()) Expect(session.OutputToString()).To(Equal("/foobar")) - containersConf = []byte(fmt.Sprintf("[engine]\nimage_copy_tmp_dir=%q", storagePath)) + containersConf = fmt.Appendf(nil, "[engine]\nimage_copy_tmp_dir=%q", storagePath) err = os.WriteFile(configPath, containersConf, os.ModePerm) Expect(err).ToNot(HaveOccurred()) if IsRemote() { diff --git a/test/e2e/info_test.go b/test/e2e/info_test.go index 028ee8a6a1..bffc40a639 100644 --- a/test/e2e/info_test.go +++ b/test/e2e/info_test.go @@ -85,7 +85,7 @@ var _ = Describe("Podman Info", func() { rootlessStoragePath := `"/tmp/$HOME/$USER/$UID/storage"` driver := `"overlay"` - storageConf := []byte(fmt.Sprintf("[storage]\ndriver=%s\nrootless_storage_path=%s\n[storage.options]\n", driver, rootlessStoragePath)) + storageConf := fmt.Appendf(nil, "[storage]\ndriver=%s\nrootless_storage_path=%s\n[storage.options]\n", driver, rootlessStoragePath) err = os.WriteFile(configPath, storageConf, os.ModePerm) Expect(err).ToNot(HaveOccurred()) // Failures in this test are impossible to debug without breadcrumbs diff --git a/test/e2e/login_logout_test.go b/test/e2e/login_logout_test.go index 60f84970c1..d94366c78b 100644 --- a/test/e2e/login_logout_test.go +++ b/test/e2e/login_logout_test.go @@ -46,7 +46,7 @@ var _ = Describe("Podman login and logout", func() { port := GetPort() server = strings.Join([]string{"localhost", strconv.Itoa(port)}, ":") - registriesConfWithSearch = []byte(fmt.Sprintf("[registries.search]\nregistries = ['%s']", server)) + registriesConfWithSearch = fmt.Appendf(nil, "[registries.search]\nregistries = ['%s']", server) testImg = strings.Join([]string{server, "test-alpine"}, "/") @@ -511,10 +511,10 @@ var _ = Describe("Podman login and logout", func() { It("podman login and logout with repository push with invalid auth.json credentials", func() { authFile := filepath.Join(podmanTest.TempDir, "auth.json") // only `server` contains the correct login data - err := os.WriteFile(authFile, []byte(fmt.Sprintf(`{"auths": { + err := os.WriteFile(authFile, fmt.Appendf(nil, `{"auths": { "%s/podmantest": { "auth": "cG9kbWFudGVzdDp3cm9uZw==" }, "%s": { "auth": "cG9kbWFudGVzdDp0ZXN0" } - }}`, server, server)), 0644) + }}`, server, server), 0644) Expect(err).ToNot(HaveOccurred()) session := podmanTest.Podman([]string{ @@ -557,11 +557,11 @@ var _ = Describe("Podman login and logout", func() { Expect(session).Should(ExitCleanly()) // only `server + /podmantest` and `server` have the correct login data - err := os.WriteFile(authFile, []byte(fmt.Sprintf(`{"auths": { + err := os.WriteFile(authFile, fmt.Appendf(nil, `{"auths": { "%s/podmantest/test-alpine": { "auth": "cG9kbWFudGVzdDp3cm9uZw==" }, "%s/podmantest": { "auth": "cG9kbWFudGVzdDp0ZXN0" }, "%s": { "auth": "cG9kbWFudGVzdDp0ZXN0" } - }}`, server, server, server)), 0644) + }}`, server, server, server), 0644) Expect(err).ToNot(HaveOccurred()) session = podmanTest.Podman([]string{ diff --git a/test/e2e/play_kube_test.go b/test/e2e/play_kube_test.go index 2cf648511a..6cd6e7c038 100644 --- a/test/e2e/play_kube_test.go +++ b/test/e2e/play_kube_test.go @@ -2481,7 +2481,7 @@ var _ = Describe("Podman kube play", func() { conffile := filepath.Join(podmanTest.TempDir, "container.conf") infraImage := INFRA_IMAGE - err := os.WriteFile(conffile, []byte(fmt.Sprintf("[engine]\ninfra_image=\"%s\"\n", infraImage)), 0644) + err := os.WriteFile(conffile, fmt.Appendf(nil, "[engine]\ninfra_image=\"%s\"\n", infraImage), 0644) Expect(err).ToNot(HaveOccurred()) os.Setenv("CONTAINERS_CONF", conffile) diff --git a/test/e2e/pod_create_test.go b/test/e2e/pod_create_test.go index 17b2c38062..7fc77503c8 100644 --- a/test/e2e/pod_create_test.go +++ b/test/e2e/pod_create_test.go @@ -184,7 +184,7 @@ var _ = Describe("Podman pod create", func() { Expect(err).ToNot(HaveOccurred()) confFile := filepath.Join(podmanTest.TempDir, "containers.conf") - err = os.WriteFile(confFile, []byte(fmt.Sprintf("[containers]\nbase_hosts_file=\"%s\"\n", configHosts)), 0755) + err = os.WriteFile(confFile, fmt.Appendf(nil, "[containers]\nbase_hosts_file=\"%s\"\n", configHosts), 0755) Expect(err).ToNot(HaveOccurred()) os.Setenv("CONTAINERS_CONF_OVERRIDE", confFile) if IsRemote() { diff --git a/test/e2e/pull_chunked_test.go b/test/e2e/pull_chunked_test.go index 2b430ff998..724ec9cc04 100644 --- a/test/e2e/pull_chunked_test.go +++ b/test/e2e/pull_chunked_test.go @@ -70,7 +70,7 @@ func pullChunkedTests() { // included in pull_test.go, must use a Ginkgo DSL at dirPath: filepath.Join(imageDir, "chunked-normal"), } chunkedNormalContentPath := "chunked-normal-image-content" - err := os.WriteFile(filepath.Join(podmanTest.TempDir, chunkedNormalContentPath), []byte(fmt.Sprintf("content-%d", rand.Int64())), 0o600) + err := os.WriteFile(filepath.Join(podmanTest.TempDir, chunkedNormalContentPath), fmt.Appendf(nil, "content-%d", rand.Int64()), 0o600) Expect(err).NotTo(HaveOccurred()) chunkedNormalContainerFile := fmt.Sprintf("FROM scratch\nADD %s /content", chunkedNormalContentPath) podmanTest.BuildImage(chunkedNormalContainerFile, chunkedNormal.localTag(), "true") diff --git a/test/e2e/pull_test.go b/test/e2e/pull_test.go index dbd0db0d20..0c0e9c4323 100644 --- a/test/e2e/pull_test.go +++ b/test/e2e/pull_test.go @@ -121,7 +121,7 @@ var _ = Describe("Podman pull", func() { err = os.MkdirAll(filepath.Dir(configPath), os.ModePerm) Expect(err).ToNot(HaveOccurred()) - storageConf := []byte(fmt.Sprintf("[storage]\nimagestore=\"%s\"", tmpDir)) + storageConf := fmt.Appendf(nil, "[storage]\nimagestore=\"%s\"", tmpDir) err = os.WriteFile(configPath, storageConf, os.ModePerm) Expect(err).ToNot(HaveOccurred()) diff --git a/test/e2e/run_device_test.go b/test/e2e/run_device_test.go index 71e6a48636..d41610de4b 100644 --- a/test/e2e/run_device_test.go +++ b/test/e2e/run_device_test.go @@ -18,13 +18,13 @@ import ( func createContainersConfFileWithDevices(pTest *PodmanTestIntegration, devices string, cdiSpecDirs []string) { configPath := filepath.Join(pTest.TempDir, "containers.conf") - containersConf := []byte(fmt.Sprintf("[containers]\ndevices = [%s]\n", devices)) + containersConf := fmt.Appendf(nil, "[containers]\ndevices = [%s]\n", devices) if len(cdiSpecDirs) > 0 { quoted := make([]string, len(cdiSpecDirs)) for i, dir := range cdiSpecDirs { quoted[i] = fmt.Sprintf("%q", dir) } - containersConf = append(containersConf, []byte(fmt.Sprintf("[engine]\ncdi_spec_dirs = [%s]\n", strings.Join(quoted, ", ")))...) + containersConf = append(containersConf, fmt.Appendf(nil, "[engine]\ncdi_spec_dirs = [%s]\n", strings.Join(quoted, ", "))...) } err := os.WriteFile(configPath, containersConf, os.ModePerm) Expect(err).ToNot(HaveOccurred()) diff --git a/test/e2e/run_test.go b/test/e2e/run_test.go index 51c6e34880..0ca062154b 100644 --- a/test/e2e/run_test.go +++ b/test/e2e/run_test.go @@ -1568,7 +1568,7 @@ VOLUME %s`, ALPINE, volPath, volPath) Expect(err).ToNot(HaveOccurred()) confFile := filepath.Join(podmanTest.TempDir, "containers.conf") - err = os.WriteFile(confFile, []byte(fmt.Sprintf("[containers]\nbase_hosts_file=\"%s\"\n", configHosts)), 0755) + err = os.WriteFile(confFile, fmt.Appendf(nil, "[containers]\nbase_hosts_file=\"%s\"\n", configHosts), 0755) Expect(err).ToNot(HaveOccurred()) os.Setenv("CONTAINERS_CONF_OVERRIDE", confFile) if IsRemote() { diff --git a/test/e2e/run_userns_test.go b/test/e2e/run_userns_test.go index ee4c5e7021..ead99d8ff3 100644 --- a/test/e2e/run_userns_test.go +++ b/test/e2e/run_userns_test.go @@ -18,7 +18,7 @@ import ( func createContainersConfFileWithCustomUserns(pTest *PodmanTestIntegration, userns string) { configPath := filepath.Join(pTest.TempDir, "containers.conf") - containersConf := []byte(fmt.Sprintf("[containers]\nuserns = \"%s\"\n", userns)) + containersConf := fmt.Appendf(nil, "[containers]\nuserns = \"%s\"\n", userns) err := os.WriteFile(configPath, containersConf, os.ModePerm) Expect(err).ToNot(HaveOccurred()) From 947642294b58f2345724bae6a03772b8f84a389b Mon Sep 17 00:00:00 2001 From: Kir Kolyshkin Date: Thu, 14 Aug 2025 19:22:10 -0700 Subject: [PATCH 08/10] Use maps.Copy / maps.Clone more In general, changes where maps.Copy is now used are always safe, and cases where maps.Clone are used are safe as long as the original copying code was conditional to srcMap != nil or len(srcMap) != 0. Signed-off-by: Kir Kolyshkin --- cmd/podman/common/build.go | 5 ++--- libpod/container_inspect.go | 15 +++------------ libpod/container_internal.go | 5 ++--- libpod/kube.go | 9 +++------ libpod/options.go | 8 ++------ libpod/runtime_ctr.go | 13 ++++--------- pkg/api/handlers/libpod/volumes.go | 9 +++------ pkg/domain/infra/abi/containers.go | 5 ++--- pkg/domain/infra/abi/play.go | 11 +++++------ pkg/env/env.go | 4 +--- pkg/specgen/generate/container.go | 5 ++--- pkg/specgen/generate/kube/kube.go | 17 +++++------------ pkg/specgen/generate/kube/volume.go | 9 +++------ pkg/specgen/generate/storage.go | 9 +++------ test/testvol/main.go | 1 + 15 files changed, 41 insertions(+), 84 deletions(-) diff --git a/cmd/podman/common/build.go b/cmd/podman/common/build.go index 4b5aaa06f9..d47f8dd735 100644 --- a/cmd/podman/common/build.go +++ b/cmd/podman/common/build.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "io" + "maps" "os" "path/filepath" "strconv" @@ -337,9 +338,7 @@ func buildFlagsWrapperToOptions(c *cobra.Command, contextDir string, flags *Buil if err != nil { return nil, err } - for name, val := range fargs { - args[name] = val - } + maps.Copy(args, fargs) } } if c.Flag("build-arg").Changed { diff --git a/libpod/container_inspect.go b/libpod/container_inspect.go index 735d626abb..3505af680e 100644 --- a/libpod/container_inspect.go +++ b/libpod/container_inspect.go @@ -5,6 +5,7 @@ package libpod import ( "errors" "fmt" + "maps" "strings" "github.com/containers/podman/v5/libpod/define" @@ -414,19 +415,9 @@ func (c *Container) generateInspectContainerConfig(spec *spec.Spec) *define.Insp ctrConfig.Entrypoint = c.config.Entrypoint } - if len(c.config.Labels) != 0 { - ctrConfig.Labels = make(map[string]string) - for k, v := range c.config.Labels { - ctrConfig.Labels[k] = v - } - } + ctrConfig.Labels = maps.Clone(c.config.Labels) + ctrConfig.Annotations = maps.Clone(spec.Annotations) - if len(spec.Annotations) != 0 { - ctrConfig.Annotations = make(map[string]string) - for k, v := range spec.Annotations { - ctrConfig.Annotations[k] = v - } - } ctrConfig.StopSignal = signal.ToDockerFormat(c.config.StopSignal) // TODO: should JSON deep copy this to ensure internal pointers don't // leak. diff --git a/libpod/container_internal.go b/libpod/container_internal.go index 84280f7cce..30de908666 100644 --- a/libpod/container_internal.go +++ b/libpod/container_internal.go @@ -9,6 +9,7 @@ import ( "fmt" "io" "io/fs" + "maps" "os" "path/filepath" "slices" @@ -2479,9 +2480,7 @@ func (c *Container) setupOCIHooks(ctx context.Context, config *spec.Spec) (map[s if len(ociHooks) > 0 || config.Hooks != nil { logrus.Warnf("Implicit hook directories are deprecated; set --ociHooks-dir=%q explicitly to continue to load ociHooks from this directory", hDir) } - for i, hook := range ociHooks { - allHooks[i] = hook - } + maps.Copy(allHooks, ociHooks) } } else { manager, err := hooks.New(ctx, c.runtime.config.Engine.HooksDir.Get(), []string{"precreate", "poststop"}) diff --git a/libpod/kube.go b/libpod/kube.go index 76433e67f4..40efa3619c 100644 --- a/libpod/kube.go +++ b/libpod/kube.go @@ -6,6 +6,7 @@ import ( "context" "errors" "fmt" + "maps" "math/rand" "os" "reflect" @@ -620,9 +621,7 @@ func (p *Pod) podWithContainers(ctx context.Context, containers []*Container, po podAnnotations[fmt.Sprintf("%s/%s", k, removeUnderscores(ctr.Name()))] = v } // Convert auto-update labels into kube annotations - for k, v := range getAutoUpdateAnnotations(ctr.Name(), ctr.Labels()) { - podAnnotations[k] = v - } + maps.Copy(podAnnotations, getAutoUpdateAnnotations(ctr.Name(), ctr.Labels())) isInit := ctr.IsInitCtr() // Since hostname is only set at pod level, set the hostname to the hostname of the first container we encounter if hostname == "" { @@ -769,9 +768,7 @@ func simplePodWithV1Containers(ctx context.Context, ctrs []*Container, getServic } // Convert auto-update labels into kube annotations - for k, v := range getAutoUpdateAnnotations(ctr.Name(), ctr.Labels()) { - kubeAnnotations[k] = v - } + maps.Copy(kubeAnnotations, getAutoUpdateAnnotations(ctr.Name(), ctr.Labels())) isInit := ctr.IsInitCtr() // Since hostname is only set at pod level, set the hostname to the hostname of the first container we encounter diff --git a/libpod/options.go b/libpod/options.go index 5a24d89015..e10c2b4469 100644 --- a/libpod/options.go +++ b/libpod/options.go @@ -5,6 +5,7 @@ package libpod import ( "errors" "fmt" + "maps" "net" "os" "path/filepath" @@ -84,12 +85,7 @@ func WithStorageConfig(config storage.StoreOptions) RuntimeOption { copy(rt.storageConfig.GIDMap, config.GIDMap) } - if config.PullOptions != nil { - rt.storageConfig.PullOptions = make(map[string]string) - for k, v := range config.PullOptions { - rt.storageConfig.PullOptions[k] = v - } - } + rt.storageConfig.PullOptions = maps.Clone(config.PullOptions) // If any one of runroot, graphroot, graphdrivername, // or graphdriveroptions are set, then GraphRoot and RunRoot diff --git a/libpod/runtime_ctr.go b/libpod/runtime_ctr.go index 941d3e048c..e446a92d4c 100644 --- a/libpod/runtime_ctr.go +++ b/libpod/runtime_ctr.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "io/fs" + "maps" "os" "path" "path/filepath" @@ -811,9 +812,7 @@ func (r *Runtime) removeContainer(ctx context.Context, c *Container, opts ctrRmO } logrus.Infof("Removing pod %s as container %s is its service container", depPod.ID(), c.ID()) podRemovedCtrs, err := r.RemovePod(ctx, depPod, true, opts.Force, opts.Timeout) - for ctr, err := range podRemovedCtrs { - removedCtrs[ctr] = err - } + maps.Copy(removedCtrs, podRemovedCtrs) if err != nil && !errors.Is(err, define.ErrNoSuchPod) && !errors.Is(err, define.ErrPodRemoved) { removedPods[depPod.ID()] = err retErr = fmt.Errorf("error removing container %s dependency pods: %w", c.ID(), err) @@ -833,9 +832,7 @@ func (r *Runtime) removeContainer(ctx context.Context, c *Container, opts ctrRmO logrus.Infof("Removing pod %s (dependency of container %s)", pod.ID(), c.ID()) podRemovedCtrs, err := r.removePod(ctx, pod, true, opts.Force, opts.Timeout) - for ctr, err := range podRemovedCtrs { - removedCtrs[ctr] = err - } + maps.Copy(removedCtrs, podRemovedCtrs) if err != nil && !errors.Is(err, define.ErrNoSuchPod) && !errors.Is(err, define.ErrPodRemoved) { removedPods[pod.ID()] = err retErr = fmt.Errorf("error removing container %s pod: %w", c.ID(), err) @@ -916,9 +913,7 @@ func (r *Runtime) removeContainer(ctx context.Context, c *Container, opts ctrRmO removedCtrs[rmCtr] = err } } - for rmPod, err := range pods { - removedPods[rmPod] = err - } + maps.Copy(removedPods, pods) if err != nil && !errors.Is(err, define.ErrNoSuchCtr) && !errors.Is(err, define.ErrCtrRemoved) { retErr = err return diff --git a/pkg/api/handlers/libpod/volumes.go b/pkg/api/handlers/libpod/volumes.go index 5f9d5e3376..43efb73ff7 100644 --- a/pkg/api/handlers/libpod/volumes.go +++ b/pkg/api/handlers/libpod/volumes.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "fmt" + "maps" "net/http" "net/url" @@ -53,12 +54,8 @@ func CreateVolume(w http.ResponseWriter, r *http.Request) { // Label provided for compatibility. labels := make(map[string]string, len(input.Label)+len(input.Labels)) - for k, v := range input.Label { - labels[k] = v - } - for k, v := range input.Labels { - labels[k] = v - } + maps.Copy(labels, input.Label) + maps.Copy(labels, input.Labels) if len(labels) > 0 { volumeOptions = append(volumeOptions, libpod.WithVolumeLabels(labels)) } diff --git a/pkg/domain/infra/abi/containers.go b/pkg/domain/infra/abi/containers.go index 8b29821132..10781b0519 100644 --- a/pkg/domain/infra/abi/containers.go +++ b/pkg/domain/infra/abi/containers.go @@ -7,6 +7,7 @@ import ( "context" "errors" "fmt" + "maps" "os" "reflect" "strconv" @@ -478,9 +479,7 @@ func (ic *ContainerEngine) ContainerRm(ctx context.Context, namesOrIds []string, mapMutex.Lock() defer mapMutex.Unlock() - for ctr, err := range ctrs { - ctrsMap[ctr] = err - } + maps.Copy(ctrsMap, ctrs) return err }) diff --git a/pkg/domain/infra/abi/play.go b/pkg/domain/infra/abi/play.go index 28c815291f..c7d435f70c 100644 --- a/pkg/domain/infra/abi/play.go +++ b/pkg/domain/infra/abi/play.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "io" + "maps" "os" "path/filepath" "strconv" @@ -957,9 +958,8 @@ func (ic *ContainerEngine) playKubePod(ctx context.Context, podName string, podY return nil, nil, err } - for k, v := range podSpec.PodSpecGen.Labels { // add podYAML labels - labels[k] = v - } + // add podYAML labels + maps.Copy(labels, podSpec.PodSpecGen.Labels) initCtrType := annotations[define.InitContainerType] if initCtrType == "" { initCtrType = define.OneShotInitContainer @@ -1051,9 +1051,8 @@ func (ic *ContainerEngine) playKubePod(ctx context.Context, podName string, podY return nil, nil, err } - for k, v := range podSpec.PodSpecGen.Labels { // add podYAML labels - labels[k] = v - } + // add podYAML labels + maps.Copy(labels, podSpec.PodSpecGen.Labels) automountImages, err := ic.prepareAutomountImages(ctx, container.Name, annotations) if err != nil { diff --git a/pkg/env/env.go b/pkg/env/env.go index 31ec789593..7770d194b2 100644 --- a/pkg/env/env.go +++ b/pkg/env/env.go @@ -54,9 +54,7 @@ func Join(base map[string]string, override map[string]string) map[string]string return maps.Clone(override) } base = maps.Clone(base) - for k, v := range override { - base[k] = v - } + maps.Copy(base, override) return base } diff --git a/pkg/specgen/generate/container.go b/pkg/specgen/generate/container.go index 9ec81cf4fe..7b9520a989 100644 --- a/pkg/specgen/generate/container.go +++ b/pkg/specgen/generate/container.go @@ -7,6 +7,7 @@ import ( "encoding/json" "errors" "fmt" + "maps" "os" "strconv" "strings" @@ -294,9 +295,7 @@ func CompleteSpec(ctx context.Context, r *libpod.Runtime, s *specgen.SpecGenerat annotations[k] = v } // now pass in the values from client - for k, v := range s.Annotations { - annotations[k] = v - } + maps.Copy(annotations, s.Annotations) s.Annotations = annotations if len(s.SeccompProfilePath) < 1 { diff --git a/pkg/specgen/generate/kube/kube.go b/pkg/specgen/generate/kube/kube.go index 6a357f98a6..0a179f3d84 100644 --- a/pkg/specgen/generate/kube/kube.go +++ b/pkg/specgen/generate/kube/kube.go @@ -7,6 +7,7 @@ import ( "encoding/json" "errors" "fmt" + "maps" "math" "net" "os" @@ -329,9 +330,7 @@ func ToSpecGen(ctx context.Context, opts *CtrSpecGenOptions) (*specgen.SpecGener return nil, err } - for k, v := range s.Expose { - exposed[k] = v - } + maps.Copy(exposed, s.Expose) s.Expose = exposed // Pull entrypoint and cmd from image s.Entrypoint = imageData.Config.Entrypoint @@ -490,9 +489,7 @@ func ToSpecGen(ctx context.Context, opts *CtrSpecGenOptions) (*specgen.SpecGener return nil, err } - for k, v := range cmEnvs { - envs[k] = v - } + maps.Copy(envs, cmEnvs) } s.Env = envs @@ -635,9 +632,7 @@ func ToSpecGen(ctx context.Context, opts *CtrSpecGenOptions) (*specgen.SpecGener } else { // If there are already labels in the map, append the ones // obtained from kube - for k, v := range opts.Labels { - s.Labels[k] = v - } + maps.Copy(s.Labels, opts.Labels) } if ro := opts.ReadOnly; ro != itypes.OptionalBoolUndefined { @@ -1055,9 +1050,7 @@ func k8sSecretFromSecretManager(name string, secretsManager *secrets.SecretsMana return nil, fmt.Errorf("secret %v is not valid JSON/YAML: %v", name, err) } - for key, val := range secret.Data { - secrets[key] = val - } + maps.Copy(secrets, secret.Data) for key, val := range secret.StringData { secrets[key] = []byte(val) diff --git a/pkg/specgen/generate/kube/volume.go b/pkg/specgen/generate/kube/volume.go index 65e8e2d182..41ff255430 100644 --- a/pkg/specgen/generate/kube/volume.go +++ b/pkg/specgen/generate/kube/volume.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "io/fs" + "maps" "os" "github.com/containers/common/pkg/parse" @@ -182,9 +183,7 @@ func VolumeFromSecret(secretSource *v1.SecretVolumeSource, secretsManager *secre } } else { // add key: value pairs to the items array - for key, entry := range secret.Data { - kv.Items[key] = entry - } + maps.Copy(kv.Items, secret.Data) for key, entry := range secret.StringData { kv.Items[key] = []byte(entry) @@ -257,9 +256,7 @@ func VolumeFromConfigMap(configMapVolumeSource *v1.ConfigMapVolumeSource, config for k, v := range configMap.Data { kv.Items[k] = []byte(v) } - for k, v := range configMap.BinaryData { - kv.Items[k] = v - } + maps.Copy(kv.Items, configMap.BinaryData) } return kv, nil } diff --git a/pkg/specgen/generate/storage.go b/pkg/specgen/generate/storage.go index a79a6cf6b2..3fc9ffd642 100644 --- a/pkg/specgen/generate/storage.go +++ b/pkg/specgen/generate/storage.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "io/fs" + "maps" "path" "path/filepath" "strings" @@ -165,12 +166,8 @@ func finalizeMounts(ctx context.Context, s *specgen.SpecGenerator, rt *libpod.Ru // Supersede volumes-from/image volumes with unified volumes from above. // This is an unconditional replacement. - for dest, mount := range unifiedMounts { - baseMounts[dest] = mount - } - for dest, volume := range unifiedVolumes { - baseVolumes[dest] = volume - } + maps.Copy(baseMounts, unifiedMounts) + maps.Copy(baseVolumes, unifiedVolumes) // TODO: Investigate moving readonlyTmpfs into here. Would be more // correct. diff --git a/test/testvol/main.go b/test/testvol/main.go index cbbf7e4b02..88358598d5 100644 --- a/test/testvol/main.go +++ b/test/testvol/main.go @@ -2,6 +2,7 @@ package main import ( "fmt" + "maps" "os" "path/filepath" "sync" From 32916c2eafa2a485922eb12e959674075e1f8b09 Mon Sep 17 00:00:00 2001 From: Kir Kolyshkin Date: Thu, 14 Aug 2025 19:46:42 -0700 Subject: [PATCH 09/10] Use maps.Clone more (unsafe cases) There is a slight functional change here that may not be safe: - before this patch, if the source map is nil, the destination map will be empty (but non-nil); - after this patch, the destination map is nil if the source one is. Practically, it may or may not matter, as reading from the nil map is ok, and only changing it is not (will result in panic). Signed-off-by: Kir Kolyshkin --- libpod/container.go | 17 ++++------------- libpod/options.go | 22 +++++----------------- libpod/pod.go | 8 ++------ libpod/volume.go | 17 +++++------------ libpod/volume_inspect.go | 11 +++-------- test/testvol/main.go | 5 +---- 6 files changed, 20 insertions(+), 60 deletions(-) diff --git a/libpod/container.go b/libpod/container.go index a6a509ae6c..8bb495de25 100644 --- a/libpod/container.go +++ b/libpod/container.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "io" + "maps" "net" "os" "strings" @@ -624,13 +625,9 @@ func (c *Container) Stdin() bool { return c.config.Stdin } -// Labels returns the container's labels +// Labels returns the container's labels. func (c *Container) Labels() map[string]string { - labels := make(map[string]string) - for key, value := range c.config.Labels { - labels[key] = value - } - return labels + return maps.Clone(c.config.Labels) } // StopSignal is the signal that will be used to stop the container @@ -1038,13 +1035,7 @@ func (c *Container) BindMounts() (map[string]string, error) { } } - newMap := make(map[string]string, len(c.state.BindMounts)) - - for key, val := range c.state.BindMounts { - newMap[key] = val - } - - return newMap, nil + return maps.Clone(c.state.BindMounts), nil } // StoppedByUser returns whether the container was last stopped by an explicit diff --git a/libpod/options.go b/libpod/options.go index e10c2b4469..c79d44aa23 100644 --- a/libpod/options.go +++ b/libpod/options.go @@ -694,17 +694,14 @@ func (r *Runtime) WithPod(pod *Pod) CtrCreateOption { } } -// WithLabels adds labels to the container. +// WithLabels sets the container's labels. func WithLabels(labels map[string]string) CtrCreateOption { return func(ctr *Container) error { if ctr.valid { return define.ErrCtrFinalized } - ctr.config.Labels = make(map[string]string) - for key, value := range labels { - ctr.config.Labels[key] = value - } + ctr.config.Labels = maps.Clone(labels) return nil } @@ -1619,10 +1616,7 @@ func WithVolumeLabels(labels map[string]string) VolumeCreateOption { return define.ErrVolumeFinalized } - volume.config.Labels = make(map[string]string) - for key, value := range labels { - volume.config.Labels[key] = value - } + volume.config.Labels = maps.Clone(labels) return nil } @@ -1647,10 +1641,7 @@ func WithVolumeOptions(options map[string]string) VolumeCreateOption { return define.ErrVolumeFinalized } - volume.config.Options = make(map[string]string) - for key, value := range options { - volume.config.Options[key] = value - } + volume.config.Options = maps.Clone(options) return nil } @@ -2018,10 +2009,7 @@ func WithPodLabels(labels map[string]string) PodCreateOption { return define.ErrPodFinalized } - pod.config.Labels = make(map[string]string) - for key, value := range labels { - pod.config.Labels[key] = value - } + pod.config.Labels = maps.Clone(labels) return nil } diff --git a/libpod/pod.go b/libpod/pod.go index 1a3ee3cb42..75c421c64e 100644 --- a/libpod/pod.go +++ b/libpod/pod.go @@ -5,6 +5,7 @@ package libpod import ( "errors" "fmt" + "maps" "sort" "strings" "time" @@ -285,12 +286,7 @@ func (p *Pod) VolumesFrom() []string { // Labels returns the pod's labels func (p *Pod) Labels() map[string]string { - labels := make(map[string]string) - for key, value := range p.config.Labels { - labels[key] = value - } - - return labels + return maps.Clone(p.config.Labels) } // CreatedTime gets the time when the pod was created diff --git a/libpod/volume.go b/libpod/volume.go index 68c15009c3..1fdebf595c 100644 --- a/libpod/volume.go +++ b/libpod/volume.go @@ -5,6 +5,7 @@ package libpod import ( "fmt" "io" + "maps" "time" "github.com/containers/podman/v5/libpod/define" @@ -136,13 +137,9 @@ func (v *Volume) Scope() string { return "local" } -// Labels returns the volume's labels +// Labels returns the volume's labels. func (v *Volume) Labels() map[string]string { - labels := make(map[string]string) - for key, value := range v.config.Labels { - labels[key] = value - } - return labels + return maps.Clone(v.config.Labels) } // MountPoint returns the volume's mountpoint on the host @@ -180,13 +177,9 @@ func (v *Volume) mountPoint() string { return v.config.MountPoint } -// Options return the volume's options +// Options return the volume's options. func (v *Volume) Options() map[string]string { - options := make(map[string]string) - for k, v := range v.config.Options { - options[k] = v - } - return options + return maps.Clone(v.config.Options) } // Anonymous returns whether this volume is anonymous. Anonymous volumes were diff --git a/libpod/volume_inspect.go b/libpod/volume_inspect.go index f4a3cc889d..62774e4fb4 100644 --- a/libpod/volume_inspect.go +++ b/libpod/volume_inspect.go @@ -4,6 +4,7 @@ package libpod import ( "fmt" + "maps" "github.com/containers/podman/v5/libpod/define" pluginapi "github.com/docker/go-plugins-helpers/volume" @@ -51,15 +52,9 @@ func (v *Volume) Inspect() (*define.InspectVolumeData, error) { data.Name = v.config.Name data.Driver = v.config.Driver data.CreatedAt = v.config.CreatedTime - data.Labels = make(map[string]string) - for k, v := range v.config.Labels { - data.Labels[k] = v - } + data.Labels = maps.Clone(v.config.Labels) data.Scope = v.Scope() - data.Options = make(map[string]string) - for k, v := range v.config.Options { - data.Options[k] = v - } + data.Options = maps.Clone(v.config.Options) data.UID = v.uid() data.GID = v.gid() data.Anonymous = v.config.IsAnon diff --git a/test/testvol/main.go b/test/testvol/main.go index 88358598d5..8fd164dd1b 100644 --- a/test/testvol/main.go +++ b/test/testvol/main.go @@ -153,11 +153,8 @@ func (d *DirDriver) Create(opts *volume.CreateRequest) error { newVol := new(dirVol) newVol.name = opts.Name newVol.mounts = make(map[string]bool) - newVol.options = make(map[string]string) + newVol.options = maps.Clone(opts.Options) newVol.createTime = time.Now() - for k, v := range opts.Options { - newVol.options[k] = v - } volPath := filepath.Join(d.volumesPath, opts.Name) if err := os.Mkdir(volPath, 0755); err != nil { From b4e6ebb33165f9fa07a8b5a4ac2475b318b27557 Mon Sep 17 00:00:00 2001 From: Kir Kolyshkin Date: Thu, 14 Aug 2025 19:56:16 -0700 Subject: [PATCH 10/10] Use slices.Contains more Replace 'for i, elem := range s { if elem == needle { ...; break }' by a call to slices.Contains, added in go1.21. Brought to you by modernize -fix -test -category slicescontains ./... Signed-off-by: Kir Kolyshkin --- cmd/podman/root.go | 8 +++----- cmd/podman/validate/choice.go | 9 ++++----- libpod/container_commit.go | 9 ++------- libpod/container_internal.go | 14 ++------------ libpod/container_internal_common.go | 7 ++----- libpod/options.go | 7 +++---- libpod/plugin/volume_api.go | 9 ++------- libpod/runtime_pod.go | 7 +------ pkg/domain/filters/containers.go | 19 +++++-------------- pkg/domain/filters/pods.go | 7 +------ pkg/domain/filters/volumes.go | 15 +++------------ pkg/systemd/generate/common.go | 7 +++---- test/e2e/checkpoint_test.go | 8 +++----- test/e2e/containers_conf_test.go | 8 +++----- 14 files changed, 37 insertions(+), 97 deletions(-) diff --git a/cmd/podman/root.go b/cmd/podman/root.go index 00dd6a20b7..c0302ca5bf 100644 --- a/cmd/podman/root.go +++ b/cmd/podman/root.go @@ -8,6 +8,7 @@ import ( "path/filepath" "runtime" "runtime/pprof" + "slices" "strconv" "strings" @@ -452,11 +453,8 @@ func loggingHook() { } logLevel = "debug" } - for _, l := range common.LogLevels { - if l == strings.ToLower(logLevel) { - found = true - break - } + if slices.Contains(common.LogLevels, strings.ToLower(logLevel)) { + found = true } if !found { fmt.Fprintf(os.Stderr, "Log Level %q is not supported, choose from: %s\n", logLevel, strings.Join(common.LogLevels, ", ")) diff --git a/cmd/podman/validate/choice.go b/cmd/podman/validate/choice.go index 5a2e6f4cc4..f7a5d98bc9 100644 --- a/cmd/podman/validate/choice.go +++ b/cmd/podman/validate/choice.go @@ -2,6 +2,7 @@ package validate import ( "fmt" + "slices" "strings" ) @@ -29,11 +30,9 @@ func (c *ChoiceValue) String() string { } func (c *ChoiceValue) Set(value string) error { - for _, v := range c.choices { - if v == value { - *c.value = value - return nil - } + if slices.Contains(c.choices, value) { + *c.value = value + return nil } return fmt.Errorf("%q is not a valid value. Choose from: %q", value, c.Choices()) } diff --git a/libpod/container_commit.go b/libpod/container_commit.go index 642556995e..451014794f 100644 --- a/libpod/container_commit.go +++ b/libpod/container_commit.go @@ -6,6 +6,7 @@ import ( "context" "errors" "fmt" + "slices" "strings" "github.com/containers/buildah" @@ -130,13 +131,7 @@ func (c *Container) Commit(ctx context.Context, destImage string, options Contai // Only include anonymous named volumes added by the user by // default. for _, v := range c.config.NamedVolumes { - include := false - for _, userVol := range c.config.UserVolumes { - if userVol == v.Dest { - include = true - break - } - } + include := slices.Contains(c.config.UserVolumes, v.Dest) if include { vol, err := c.runtime.GetVolume(v.Name) if err != nil { diff --git a/libpod/container_internal.go b/libpod/container_internal.go index 30de908666..d29bc63c44 100644 --- a/libpod/container_internal.go +++ b/libpod/container_internal.go @@ -351,12 +351,7 @@ func (c *Container) handleRestartPolicy(ctx context.Context) (_ bool, retErr err // Returns true if the container is in one of the given states, // or false otherwise. func (c *Container) ensureState(states ...define.ContainerStatus) bool { - for _, state := range states { - if state == c.state.State { - return true - } - } - return false + return slices.Contains(states, c.state.State) } // Sync this container with on-disk state and runtime status @@ -484,12 +479,7 @@ func (c *Container) setupStorage(ctx context.Context) error { } if c.config.Privileged { privOpt := func(opt string) bool { - for _, privopt := range []string{"nodev", "nosuid", "noexec"} { - if opt == privopt { - return true - } - } - return false + return slices.Contains([]string{"nodev", "nosuid", "noexec"}, opt) } defOptions, err := storage.GetMountOptions(c.runtime.store.GraphDriverName(), c.runtime.store.GraphOptions()) diff --git a/libpod/container_internal_common.go b/libpod/container_internal_common.go index efb6074d72..2dd7cc6a8a 100644 --- a/libpod/container_internal_common.go +++ b/libpod/container_internal_common.go @@ -2730,11 +2730,8 @@ func (c *Container) userPasswdEntry(u *user.User) (string, error) { hDir = filepath.Dir(hDir) } if homeDir != u.HomeDir { - for _, hDir := range c.UserVolumes() { - if hDir == u.HomeDir { - homeDir = u.HomeDir - break - } + if slices.Contains(c.UserVolumes(), u.HomeDir) { + homeDir = u.HomeDir } } diff --git a/libpod/options.go b/libpod/options.go index c79d44aa23..eef7cbec32 100644 --- a/libpod/options.go +++ b/libpod/options.go @@ -9,6 +9,7 @@ import ( "net" "os" "path/filepath" + "slices" "strings" "syscall" "time" @@ -274,10 +275,8 @@ func WithHooksDir(hooksDirs ...string) RuntimeOption { return define.ErrRuntimeFinalized } - for _, hooksDir := range hooksDirs { - if hooksDir == "" { - return fmt.Errorf("empty-string hook directories are not supported: %w", define.ErrInvalidArg) - } + if slices.Contains(hooksDirs, "") { + return fmt.Errorf("empty-string hook directories are not supported: %w", define.ErrInvalidArg) } rt.config.Engine.HooksDir.Set(hooksDirs) diff --git a/libpod/plugin/volume_api.go b/libpod/plugin/volume_api.go index 09b5729ea5..ae5dd57fbc 100644 --- a/libpod/plugin/volume_api.go +++ b/libpod/plugin/volume_api.go @@ -10,6 +10,7 @@ import ( "net/http" "os" "path/filepath" + "slices" "strings" "sync" "time" @@ -106,13 +107,7 @@ func validatePlugin(newPlugin *VolumePlugin) error { return fmt.Errorf("unmarshalling plugin %s activation response: %w", newPlugin.Name, err) } - foundVolume := false - for _, pluginType := range respStruct.Implements { - if pluginType == volumePluginType { - foundVolume = true - break - } - } + foundVolume := slices.Contains(respStruct.Implements, volumePluginType) if !foundVolume { return fmt.Errorf("plugin %s does not implement volume plugin, instead provides %s: %w", newPlugin.Name, strings.Join(respStruct.Implements, ", "), ErrNotVolumePlugin) diff --git a/libpod/runtime_pod.go b/libpod/runtime_pod.go index 086dba0bdb..67506c4992 100644 --- a/libpod/runtime_pod.go +++ b/libpod/runtime_pod.go @@ -166,12 +166,7 @@ func (r *Runtime) PrunePods(ctx context.Context) (map[string]error, error) { states := []string{define.PodStateStopped, define.PodStateExited} filterFunc := func(p *Pod) bool { state, _ := p.GetPodStatus() - for _, status := range states { - if state == status { - return true - } - } - return false + return slices.Contains(states, state) } pods, err := r.Pods(filterFunc) if err != nil { diff --git a/pkg/domain/filters/containers.go b/pkg/domain/filters/containers.go index 5d694e76d1..15216e8d5a 100644 --- a/pkg/domain/filters/containers.go +++ b/pkg/domain/filters/containers.go @@ -55,10 +55,8 @@ func GenerateContainerFilterFuncs(filter string, filterValues []string, r *libpo return func(c *libpod.Container) bool { ec, exited, err := c.ExitCode() if err == nil && exited { - for _, exitCode := range exitCodes { - if ec == exitCode { - return true - } + if slices.Contains(exitCodes, ec) { + return true } } return false @@ -179,12 +177,7 @@ func GenerateContainerFilterFuncs(filter string, filterValues []string, r *libpo if err != nil { return false } - for _, filterValue := range filterValues { - if hcStatus == filterValue { - return true - } - } - return false + return slices.Contains(filterValues, hcStatus) }, nil case "until": return prepareUntilFilterFunc(filterValues) @@ -470,10 +463,8 @@ func GenerateExternalContainerFilterFuncs(filter string, filterValues []string, ec := listContainer.ExitCode exited := listContainer.Exited if exited { - for _, exitCode := range exitCodes { - if ec == exitCode { - return true - } + if slices.Contains(exitCodes, ec) { + return true } } return false diff --git a/pkg/domain/filters/pods.go b/pkg/domain/filters/pods.go index b52be1339a..6dc53713d8 100644 --- a/pkg/domain/filters/pods.go +++ b/pkg/domain/filters/pods.go @@ -111,12 +111,7 @@ func GeneratePodFilterFunc(filter string, filterValues []string, r *libpod.Runti if err != nil { return false } - for _, filterValue := range filterValues { - if strings.ToLower(status) == filterValue { - return true - } - } - return false + return slices.Contains(filterValues, strings.ToLower(status)) }, nil case "label": return func(p *libpod.Pod) bool { diff --git a/pkg/domain/filters/volumes.go b/pkg/domain/filters/volumes.go index 07e2cac86c..2935abd94f 100644 --- a/pkg/domain/filters/volumes.go +++ b/pkg/domain/filters/volumes.go @@ -4,6 +4,7 @@ package filters import ( "fmt" + "slices" "strings" "time" @@ -22,21 +23,11 @@ func GenerateVolumeFilters(filter string, filterValues []string, runtime *libpod }, nil case "driver": return func(v *libpod.Volume) bool { - for _, val := range filterValues { - if v.Driver() == val { - return true - } - } - return false + return slices.Contains(filterValues, v.Driver()) }, nil case "scope": return func(v *libpod.Volume) bool { - for _, val := range filterValues { - if v.Scope() == val { - return true - } - } - return false + return slices.Contains(filterValues, v.Scope()) }, nil case "label": return func(v *libpod.Volume) bool { diff --git a/pkg/systemd/generate/common.go b/pkg/systemd/generate/common.go index ded78aab37..6b67bf15ab 100644 --- a/pkg/systemd/generate/common.go +++ b/pkg/systemd/generate/common.go @@ -4,6 +4,7 @@ package generate import ( "fmt" + "slices" "strconv" "strings" @@ -17,10 +18,8 @@ const minTimeoutStopSec = 60 // validateRestartPolicy checks that the user-provided policy is valid. func validateRestartPolicy(restart string) error { - for _, i := range define.RestartPolicies { - if i == restart { - return nil - } + if slices.Contains(define.RestartPolicies, restart) { + return nil } return fmt.Errorf("%s is not a valid restart policy", restart) } diff --git a/test/e2e/checkpoint_test.go b/test/e2e/checkpoint_test.go index 74c35629e4..15924da695 100644 --- a/test/e2e/checkpoint_test.go +++ b/test/e2e/checkpoint_test.go @@ -9,6 +9,7 @@ import ( "os" "os/exec" "path/filepath" + "slices" "strings" "time" @@ -1571,11 +1572,8 @@ var _ = Describe("Podman checkpoint", func() { preservedMakeOptions := podmanTest.PodmanMakeOptions podmanTest.PodmanMakeOptions = func(args []string, options PodmanExecOptions) []string { defaultArgs := preservedMakeOptions(args, options) - for i := range args { - // Runtime is set explicitly, so we should keep --runtime arg. - if args[i] == "--runtime" { - return defaultArgs - } + if slices.Contains(args, "--runtime") { + return defaultArgs } updatedArgs := make([]string, 0) for i := 0; i < len(defaultArgs); i++ { diff --git a/test/e2e/containers_conf_test.go b/test/e2e/containers_conf_test.go index 62a52c9b6b..76645b853c 100644 --- a/test/e2e/containers_conf_test.go +++ b/test/e2e/containers_conf_test.go @@ -7,6 +7,7 @@ import ( "os" "os/exec" "path/filepath" + "slices" "strings" "time" @@ -789,11 +790,8 @@ var _ = Describe("Verify podman containers.conf usage", func() { startContainer := func(params ...string) string { args := []string{"create"} - for _, param := range params { - if param == "--name" { - args = append(args, "--replace") - break - } + if slices.Contains(params, "--name") { + args = append(args, "--replace") } args = append(args, params...) args = append(args, ALPINE, "true")