Skip to content

Modernize #6118

New issue

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

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

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Apr 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions chroot/run_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"os"
"os/exec"
"path/filepath"
"slices"
"strings"
"syscall"
"time"
Expand Down Expand Up @@ -61,14 +62,14 @@ func setPlatformUnshareOptions(spec *specs.Spec, cmd *unshare.Cmd) error {
uidmap, gidmap := spec.Linux.UIDMappings, spec.Linux.GIDMappings
if len(uidmap) == 0 {
// No UID mappings are configured for the container. Borrow our parent's mappings.
uidmap = append([]specs.LinuxIDMapping{}, hostUidmap...)
uidmap = slices.Clone(hostUidmap)
for i := range uidmap {
uidmap[i].HostID = uidmap[i].ContainerID
}
}
if len(gidmap) == 0 {
// No GID mappings are configured for the container. Borrow our parent's mappings.
gidmap = append([]specs.LinuxIDMapping{}, hostGidmap...)
gidmap = slices.Clone(hostGidmap)
for i := range gidmap {
gidmap[i].HostID = gidmap[i].ContainerID
}
Expand Down
6 changes: 2 additions & 4 deletions chroot/run_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -221,10 +221,8 @@ func TestProcessEnv(t *testing.T) {
g.AddProcessEnv("PARENT_TEST_PID", strconv.Itoa(unix.Getpid()))
},
func(t *testing.T, report *types.TestReport) {
for _, ev := range report.Spec.Process.Env {
if ev == e {
return
}
if slices.Contains(report.Spec.Process.Env, e) {
return
}
t.Fatalf("expected environment variable %q", e)
},
Expand Down
2 changes: 1 addition & 1 deletion cmd/buildah/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ func updateEntrypoint(builder *buildah.Builder, entrypoint string) {
builder.SetEntrypoint(entrypointSpec)
}

func conditionallyAddHistory(builder *buildah.Builder, c *cobra.Command, createdByFmt string, args ...interface{}) {
func conditionallyAddHistory(builder *buildah.Builder, c *cobra.Command, createdByFmt string, args ...any) {
history := buildahcli.DefaultHistory()
if c.Flag("add-history").Changed {
history, _ = c.Flags().GetBool("add-history")
Expand Down
4 changes: 2 additions & 2 deletions cmd/buildah/containers.go
Original file line number Diff line number Diff line change
Expand Up @@ -250,10 +250,10 @@ func outputContainers(store storage.Store, opts containerOptions, params *contai
return nil
}

func containersToGeneric(templParams []containerOutputParams) (genericParams []interface{}) {
func containersToGeneric(templParams []containerOutputParams) (genericParams []any) {
if len(templParams) > 0 {
for _, v := range templParams {
genericParams = append(genericParams, interface{}(v))
genericParams = append(genericParams, any(v))
}
}
return genericParams
Expand Down
4 changes: 2 additions & 2 deletions cmd/buildah/images.go
Original file line number Diff line number Diff line change
Expand Up @@ -327,10 +327,10 @@ func truncateID(id string, truncate bool) string {
return id
}

func imagesToGeneric(templParams []imageOutputParams) (genericParams []interface{}) {
func imagesToGeneric(templParams []imageOutputParams) (genericParams []any) {
if len(templParams) > 0 {
for _, v := range templParams {
genericParams = append(genericParams, interface{}(v))
genericParams = append(genericParams, any(v))
}
}
return genericParams
Expand Down
6 changes: 3 additions & 3 deletions cmd/buildah/info.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func init() {
}

func infoCmd(c *cobra.Command, iopts infoResults) error {
info := map[string]interface{}{}
info := map[string]any{}

store, err := getStore(c)
if err != nil {
Expand Down Expand Up @@ -92,8 +92,8 @@ func infoCmd(c *cobra.Command, iopts infoResults) error {
}

// top-level "debug" info
func debugInfo() map[string]interface{} {
info := map[string]interface{}{}
func debugInfo() map[string]any {
info := map[string]any{}
info["compiler"] = runtime.Compiler
info["go version"] = runtime.Version()
info["buildah version"] = define.Version
Expand Down
6 changes: 2 additions & 4 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import (
// unmarshalConvertedConfig obtains the config blob of img valid for the wantedManifestMIMEType format
// (either as it exists, or converting the image if necessary), and unmarshals it into dest.
// NOTE: The MIME type is of the _manifest_, not of the _config_ that is returned.
func unmarshalConvertedConfig(ctx context.Context, dest interface{}, img types.Image, wantedManifestMIMEType string) error {
func unmarshalConvertedConfig(ctx context.Context, dest any, img types.Image, wantedManifestMIMEType string) error {
_, actualManifestMIMEType, err := img.Manifest(ctx)
if err != nil {
return fmt.Errorf("getting manifest MIME type for %q: %w", transports.ImageName(img.Reference()), err)
Expand Down Expand Up @@ -96,9 +96,7 @@ func (b *Builder) initConfig(ctx context.Context, sys *types.SystemContext, img
if b.ImageAnnotations == nil {
b.ImageAnnotations = make(map[string]string, len(v1Manifest.Annotations))
}
for k, v := range v1Manifest.Annotations {
b.ImageAnnotations[k] = v
}
maps.Copy(b.ImageAnnotations, v1Manifest.Annotations)
}
}
} else {
Expand Down
20 changes: 10 additions & 10 deletions copier/copier.go
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ func Stat(root string, directory string, options StatOptions, globs []string) ([
Request: requestStat,
Root: root,
Directory: directory,
Globs: append([]string{}, globs...),
Globs: slices.Clone(globs),
StatOptions: options,
}
resp, err := copier(nil, nil, req)
Expand Down Expand Up @@ -382,7 +382,7 @@ func Get(root string, directory string, options GetOptions, globs []string, bulk
Request: requestGet,
Root: root,
Directory: directory,
Globs: append([]string{}, globs...),
Globs: slices.Clone(globs),
StatOptions: StatOptions{
CheckForArchives: options.ExpandArchives,
},
Expand Down Expand Up @@ -598,7 +598,7 @@ func copierWithoutSubprocess(bulkReader io.Reader, bulkWriter io.Writer, req req
req.preservedRoot = req.Root
req.rootPrefix = string(os.PathSeparator)
req.preservedDirectory = req.Directory
req.preservedGlobs = append([]string{}, req.Globs...)
req.preservedGlobs = slices.Clone(req.Globs)
if !filepath.IsAbs(req.Directory) {
req.Directory = filepath.Join(req.Root, cleanerReldirectory(req.Directory))
}
Expand Down Expand Up @@ -850,7 +850,7 @@ func copierMain() {
req.preservedRoot = req.Root
req.rootPrefix = string(os.PathSeparator)
req.preservedDirectory = req.Directory
req.preservedGlobs = append([]string{}, req.Globs...)
req.preservedGlobs = slices.Clone(req.Globs)
if chrooted {
// We'll need to adjust some things now that the root
// directory isn't what it was. Make the directory and
Expand Down Expand Up @@ -1052,7 +1052,7 @@ func resolvePath(root, path string, evaluateFinalComponent bool, pm *fileutils.P
}

func copierHandlerEval(req request) *response {
errorResponse := func(fmtspec string, args ...interface{}) *response {
errorResponse := func(fmtspec string, args ...any) *response {
return &response{Error: fmt.Sprintf(fmtspec, args...), Eval: evalResponse{}}
}
resolvedTarget, err := resolvePath(req.Root, req.Directory, true, nil)
Expand All @@ -1063,7 +1063,7 @@ func copierHandlerEval(req request) *response {
}

func copierHandlerStat(req request, pm *fileutils.PatternMatcher) *response {
errorResponse := func(fmtspec string, args ...interface{}) *response {
errorResponse := func(fmtspec string, args ...any) *response {
return &response{Error: fmt.Sprintf(fmtspec, args...), Stat: statResponse{}}
}
if len(req.Globs) == 0 {
Expand Down Expand Up @@ -1233,7 +1233,7 @@ func copierHandlerGet(bulkWriter io.Writer, req request, pm *fileutils.PatternMa
statRequest := req
statRequest.Request = requestStat
statResponse := copierHandlerStat(req, pm)
errorResponse := func(fmtspec string, args ...interface{}) (*response, func() error, error) {
errorResponse := func(fmtspec string, args ...any) (*response, func() error, error) {
return &response{Error: fmt.Sprintf(fmtspec, args...), Stat: statResponse.Stat, Get: getResponse{}}, nil, nil
}
if statResponse.Error != "" {
Expand Down Expand Up @@ -1696,7 +1696,7 @@ func copierHandlerGetOne(srcfi os.FileInfo, symlinkTarget, name, contentPath str
}

func copierHandlerPut(bulkReader io.Reader, req request, idMappings *idtools.IDMappings) (*response, func() error, error) {
errorResponse := func(fmtspec string, args ...interface{}) (*response, func() error, error) {
errorResponse := func(fmtspec string, args ...any) (*response, func() error, error) {
return &response{Error: fmt.Sprintf(fmtspec, args...), Put: putResponse{}}, nil, nil
}
dirUID, dirGID, defaultDirUID, defaultDirGID := 0, 0, 0, 0
Expand Down Expand Up @@ -2110,7 +2110,7 @@ func copierHandlerPut(bulkReader io.Reader, req request, idMappings *idtools.IDM
}

func copierHandlerMkdir(req request, idMappings *idtools.IDMappings) (*response, func() error, error) {
errorResponse := func(fmtspec string, args ...interface{}) (*response, func() error, error) {
errorResponse := func(fmtspec string, args ...any) (*response, func() error, error) {
return &response{Error: fmt.Sprintf(fmtspec, args...), Mkdir: mkdirResponse{}}, nil, nil
}
dirUID, dirGID := 0, 0
Expand Down Expand Up @@ -2164,7 +2164,7 @@ func copierHandlerMkdir(req request, idMappings *idtools.IDMappings) (*response,
}

func copierHandlerRemove(req request) *response {
errorResponse := func(fmtspec string, args ...interface{}) *response {
errorResponse := func(fmtspec string, args ...any) *response {
return &response{Error: fmt.Sprintf(fmtspec, args...), Remove: removeResponse{}}
}
resolvedTarget, err := resolvePath(req.Root, req.Directory, false, nil)
Expand Down
3 changes: 2 additions & 1 deletion copier/copier_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"path"
"path/filepath"
"reflect"
"slices"
"sort"
"strconv"
"strings"
Expand Down Expand Up @@ -1753,7 +1754,7 @@ func testMkdir(t *testing.T) {
return nil
})
require.NoErrorf(t, err, "error walking directory to catalog post-Mkdir contents: %v", err)
expected := append([]string{}, beforeNames...)
expected := slices.Clone(beforeNames)
for _, expect := range testCase.expect {
expected = append(expected, filepath.FromSlash(expect))
}
Expand Down
2 changes: 1 addition & 1 deletion define/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ type BuildOptions struct {
// Log is a callback that will print a progress message. If no value
// is supplied, the message will be sent to Err (or os.Stderr, if Err
// is nil) by default.
Log func(format string, args ...interface{})
Log func(format string, args ...any)
// In is connected to stdin for RUN instructions.
In io.Reader
// Out is a place where non-error log messages are sent.
Expand Down
4 changes: 1 addition & 3 deletions imagebuildah/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -435,9 +435,7 @@ func buildDockerfilesOnce(ctx context.Context, store storage.Store, logger *logr
return "", nil, fmt.Errorf("creating build executor: %w", err)
}
b := imagebuilder.NewBuilder(options.Args)
for k, v := range builtinArgDefaults {
b.BuiltinArgDefaults[k] = v
}
maps.Copy(b.BuiltinArgDefaults, builtinArgDefaults)

defaultContainerConfig, err := config.Default()
if err != nil {
Expand Down
6 changes: 3 additions & 3 deletions imagebuildah/executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ type Executor struct {
output string
outputFormat string
additionalTags []string
log func(format string, args ...interface{}) // can be nil
log func(format string, args ...any) // can be nil
in io.Reader
out io.Writer
err io.Writer
Expand Down Expand Up @@ -511,7 +511,7 @@ func (b *Executor) buildStage(ctx context.Context, cleanupStages map[int]*StageE
// layers, its easier to reuse cached layers.
if len(b.labels) > 0 {
var labelLine string
labels := append([]string{}, b.labels...)
labels := slices.Clone(b.labels)
for _, labelSpec := range labels {
key, value, _ := strings.Cut(labelSpec, "=")
// check only for an empty key since docker allows empty values
Expand Down Expand Up @@ -556,7 +556,7 @@ func (b *Executor) buildStage(ctx context.Context, cleanupStages map[int]*StageE
stageExecutor := b.startStage(ctx, &stage, stages, output)
if stageExecutor.log == nil {
stepCounter := 0
stageExecutor.log = func(format string, args ...interface{}) {
stageExecutor.log = func(format string, args ...any) {
prefix := b.logPrefix
if len(stages) > 1 {
prefix += fmt.Sprintf("[%d/%d] ", stageIndex+1, len(stages))
Expand Down
17 changes: 5 additions & 12 deletions imagebuildah/stage_executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ type StageExecutor struct {
ctx context.Context
systemContext *types.SystemContext
executor *Executor
log func(format string, args ...interface{})
log func(format string, args ...any)
index int
stages imagebuilder.Stages
name string
Expand Down Expand Up @@ -173,14 +173,7 @@ func (s *StageExecutor) Preserve(path string) error {
for cachedPath := range s.volumeCache {
// Walk our list of cached volumes, and check that they're
// still in the list of locations that we need to cache.
found := false
for _, volume := range s.volumes {
if volume == cachedPath {
// We need to keep this volume's cache.
found = true
break
}
}
found := slices.Contains(s.volumes, cachedPath)
if !found {
// We don't need to keep this volume's cache. Make a
// note to remove it.
Expand Down Expand Up @@ -815,7 +808,7 @@ func (s *StageExecutor) Run(run imagebuilder.Run, config docker.Config) error {
defer devNull.Close()
stdin = devNull
}
namespaceOptions := append([]define.NamespaceOption{}, s.executor.namespaceOptions...)
namespaceOptions := slices.Clone(s.executor.namespaceOptions)
options := buildah.RunOptions{
Args: s.executor.runtimeArgs,
Cmd: config.Cmd,
Expand Down Expand Up @@ -2117,7 +2110,7 @@ func (s *StageExecutor) generateCacheKey(ctx context.Context, currNode *parser.N
if err != nil {
return "", fmt.Errorf("getting history of base image %q: %w", s.builder.FromImageID, err)
}
for i := 0; i < len(diffIDs); i++ {
for i := range len(diffIDs) {
fmt.Fprintln(hash, diffIDs[i].String())
}
}
Expand Down Expand Up @@ -2382,7 +2375,7 @@ func (s *StageExecutor) commit(ctx context.Context, createdBy string, emptyLayer
s.builder.SetStopSignal(config.StopSignal)
if config.Healthcheck != nil {
s.builder.SetHealthcheck(&buildahdocker.HealthConfig{
Test: append([]string{}, config.Healthcheck.Test...),
Test: slices.Clone(config.Healthcheck.Test),
Interval: config.Healthcheck.Interval,
Timeout: config.Healthcheck.Timeout,
StartPeriod: config.Healthcheck.StartPeriod,
Expand Down
16 changes: 8 additions & 8 deletions info.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import (
// 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
}

// Info returns the store and host information
Expand All @@ -42,8 +42,8 @@ func Info(store storage.Store) ([]InfoData, error) {
return info, nil
}

func hostInfo() map[string]interface{} {
info := map[string]interface{}{}
func hostInfo() map[string]any {
info := map[string]any{}
ps := internalUtil.NormalizePlatform(v1.Platform{OS: runtime.GOOS, Architecture: runtime.GOARCH})
info["os"] = ps.OS
info["arch"] = ps.Architecture
Expand Down Expand Up @@ -77,7 +77,7 @@ func hostInfo() map[string]interface{} {
info["SwapFree"] = mi.SwapFree
}
hostDistributionInfo := getHostDistributionInfo()
info["Distribution"] = map[string]interface{}{
info["Distribution"] = map[string]any{
"distribution": hostDistributionInfo["Distribution"],
"version": hostDistributionInfo["Version"],
}
Expand Down Expand Up @@ -128,9 +128,9 @@ func hostInfo() map[string]interface{} {
}

// top-level "store" info
func storeInfo(store storage.Store) (map[string]interface{}, error) {
func storeInfo(store storage.Store) (map[string]any, error) {
// lets say storage driver in use, number of images, number of containers
info := map[string]interface{}{}
info := map[string]any{}
info["GraphRoot"] = store.GraphRoot()
info["RunRoot"] = store.RunRoot()
info["GraphDriverName"] = store.GraphDriverName()
Expand All @@ -148,15 +148,15 @@ func storeInfo(store storage.Store) (map[string]interface{}, error) {
if err != nil {
logrus.Error(err, "error getting number of images")
}
info["ImageStore"] = map[string]interface{}{
info["ImageStore"] = map[string]any{
"number": len(images),
}

containers, err := store.Containers()
if err != nil {
logrus.Error(err, "error getting number of containers")
}
info["ContainerStore"] = map[string]interface{}{
info["ContainerStore"] = map[string]any{
"number": len(containers),
}

Expand Down
Loading