Merge pull request #43169 from thaJeztah/use_gofumpt

Format code with gofumpt
This commit is contained in:
Bjorn Neergaard 2023-06-29 06:23:52 -06:00 committed by GitHub
commit 46cf8cecc8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
350 changed files with 1473 additions and 1363 deletions

View file

@ -76,7 +76,7 @@ func (b *Backend) Build(ctx context.Context, config backend.BuildConfig) (string
return "", nil
}
var imageID = build.ImageID
imageID := build.ImageID
if options.Squash {
if imageID, err = squashBuild(build, b.imageComponent); err != nil {
return "", err

View file

@ -15,7 +15,6 @@ type Backend interface {
// Prune build cache
PruneCache(context.Context, types.BuildCachePruneOptions) (*types.BuildCachePruneReport, error)
Cancel(context.Context, string) error
}

View file

@ -107,7 +107,7 @@ func newImageBuildOptions(ctx context.Context, r *http.Request) (*types.ImageBui
}
if ulimitsJSON := r.FormValue("ulimits"); ulimitsJSON != "" {
var buildUlimits = []*units.Ulimit{}
buildUlimits := []*units.Ulimit{}
if err := json.Unmarshal([]byte(ulimitsJSON), &buildUlimits); err != nil {
return nil, invalidParam{errors.Wrap(err, "error reading ulimit settings")}
}
@ -127,7 +127,7 @@ func newImageBuildOptions(ctx context.Context, r *http.Request) (*types.ImageBui
// so that it can print a warning about "foo" being unused if there is
// no "ARG foo" in the Dockerfile.
if buildArgsJSON := r.FormValue("buildargs"); buildArgsJSON != "" {
var buildArgs = map[string]*string{}
buildArgs := map[string]*string{}
if err := json.Unmarshal([]byte(buildArgsJSON), &buildArgs); err != nil {
return nil, invalidParam{errors.Wrap(err, "error reading build args")}
}
@ -135,7 +135,7 @@ func newImageBuildOptions(ctx context.Context, r *http.Request) (*types.ImageBui
}
if labelsJSON := r.FormValue("labels"); labelsJSON != "" {
var labels = map[string]string{}
labels := map[string]string{}
if err := json.Unmarshal([]byte(labelsJSON), &labels); err != nil {
return nil, invalidParam{errors.Wrap(err, "error reading labels")}
}
@ -143,7 +143,7 @@ func newImageBuildOptions(ctx context.Context, r *http.Request) (*types.ImageBui
}
if cacheFromJSON := r.FormValue("cachefrom"); cacheFromJSON != "" {
var cacheFrom = []string{}
cacheFrom := []string{}
if err := json.Unmarshal([]byte(cacheFromJSON), &cacheFrom); err != nil {
return nil, invalidParam{errors.Wrap(err, "error reading cache-from")}
}

View file

@ -35,7 +35,6 @@ func (s *checkpointRouter) getContainerCheckpoints(ctx context.Context, w http.R
checkpoints, err := s.backend.CheckpointList(vars["name"], types.CheckpointListOptions{
CheckpointDir: r.Form.Get("dir"),
})
if err != nil {
return err
}
@ -52,7 +51,6 @@ func (s *checkpointRouter) deleteContainerCheckpoint(ctx context.Context, w http
CheckpointDir: r.Form.Get("dir"),
CheckpointID: vars["checkpoint"],
})
if err != nil {
return err
}

View file

@ -53,7 +53,6 @@ type monitorBackend interface {
ContainerLogs(ctx context.Context, name string, config *types.ContainerLogsOptions) (msgs <-chan *backend.LogMessage, tty bool, err error)
ContainerStats(ctx context.Context, name string, config *backend.ContainerStatsConfig) error
ContainerTop(name string, psArgs string) (*container.ContainerTopOKBody, error)
Containers(ctx context.Context, config *types.ContainerListOptions) ([]*types.Container, error)
}

View file

@ -449,7 +449,7 @@ func (ir *imageRouter) getImagesSearch(ctx context.Context, w http.ResponseWrite
// AuthConfig to increase compatibility with the existing API.
authConfig, _ := registry.DecodeAuthConfig(r.Header.Get(registry.AuthHeader))
var headers = http.Header{}
headers := http.Header{}
for k, v := range r.Header {
k = http.CanonicalHeaderKey(k)
if strings.HasPrefix(k, "X-Meta-") {

View file

@ -186,7 +186,8 @@ func (pr *pluginRouter) createPlugin(ctx context.Context, w http.ResponseWriter,
}
options := &types.PluginCreateOptions{
RepoName: r.FormValue("name")}
RepoName: r.FormValue("name"),
}
if err := pr.backend.CreateFromContext(ctx, r.Body, options); err != nil {
return err

View file

@ -17,29 +17,23 @@ type Backend interface {
Update(uint64, types.Spec, types.UpdateFlags) error
GetUnlockKey() (string, error)
UnlockSwarm(req types.UnlockRequest) error
GetServices(basictypes.ServiceListOptions) ([]types.Service, error)
GetService(idOrName string, insertDefaults bool) (types.Service, error)
CreateService(types.ServiceSpec, string, bool) (*basictypes.ServiceCreateResponse, error)
UpdateService(string, uint64, types.ServiceSpec, basictypes.ServiceUpdateOptions, bool) (*basictypes.ServiceUpdateResponse, error)
RemoveService(string) error
ServiceLogs(context.Context, *backend.LogSelector, *basictypes.ContainerLogsOptions) (<-chan *backend.LogMessage, error)
GetNodes(basictypes.NodeListOptions) ([]types.Node, error)
GetNode(string) (types.Node, error)
UpdateNode(string, uint64, types.NodeSpec) error
RemoveNode(string, bool) error
GetTasks(basictypes.TaskListOptions) ([]types.Task, error)
GetTask(string) (types.Task, error)
GetSecrets(opts basictypes.SecretListOptions) ([]types.Secret, error)
CreateSecret(s types.SecretSpec) (string, error)
RemoveSecret(idOrName string) error
GetSecret(id string) (types.Secret, error)
UpdateSecret(idOrName string, version uint64, spec types.SecretSpec) error
GetConfigs(opts basictypes.ConfigListOptions) ([]types.Config, error)
CreateConfig(s types.ConfigSpec) (string, error)
RemoveConfig(id string) error

View file

@ -9,9 +9,7 @@ import (
)
func TestAdjustForAPIVersion(t *testing.T) {
var (
expectedSysctls = map[string]string{"foo": "bar"}
)
expectedSysctls := map[string]string{"foo": "bar"}
// testing the negative -- does this leave everything else alone? -- is
// prohibitively time-consuming to write, because it would need an object
// with literally every field filled in.

View file

@ -78,7 +78,6 @@ func TestGetVolumeByNameFoundRegular(t *testing.T) {
v := &volumeRouter{
backend: &fakeVolumeBackend{
volumes: map[string]*volume.Volume{
"volume1": {
Name: "volume1",
},
@ -108,6 +107,7 @@ func TestGetVolumeByNameFoundSwarm(t *testing.T) {
_, err := callGetVolume(v, "volume1")
assert.NilError(t, err)
}
func TestListVolumes(t *testing.T) {
v := &volumeRouter{
backend: &fakeVolumeBackend{

View file

@ -155,7 +155,6 @@ func TestUTSMode(t *testing.T) {
assert.Check(t, is.Equal(mode.IsHost(), expected.host))
assert.Check(t, is.Equal(mode.Valid(), expected.valid))
})
}
}

View file

@ -164,13 +164,17 @@ func TestArgsMatchKVList(t *testing.T) {
matches := map[*Args]string{
{}: "field",
{map[string]map[string]bool{
"created": {"today": true},
"labels": {"key1": true}},
{
map[string]map[string]bool{
"created": {"today": true},
"labels": {"key1": true},
},
}: "labels",
{map[string]map[string]bool{
"created": {"today": true},
"labels": {"key1=value1": true}},
{
map[string]map[string]bool{
"created": {"today": true},
"labels": {"key1=value1": true},
},
}: "labels",
}
@ -181,16 +185,22 @@ func TestArgsMatchKVList(t *testing.T) {
}
differs := map[*Args]string{
{map[string]map[string]bool{
"created": {"today": true}},
{
map[string]map[string]bool{
"created": {"today": true},
},
}: "created",
{map[string]map[string]bool{
"created": {"today": true},
"labels": {"key4": true}},
{
map[string]map[string]bool{
"created": {"today": true},
"labels": {"key4": true},
},
}: "labels",
{map[string]map[string]bool{
"created": {"today": true},
"labels": {"key1=value3": true}},
{
map[string]map[string]bool{
"created": {"today": true},
"labels": {"key1=value3": true},
},
}: "labels",
}
@ -206,20 +216,30 @@ func TestArgsMatch(t *testing.T) {
matches := map[*Args]string{
{}: "field",
{map[string]map[string]bool{
"created": {"today": true}},
{
map[string]map[string]bool{
"created": {"today": true},
},
}: "today",
{map[string]map[string]bool{
"created": {"to*": true}},
{
map[string]map[string]bool{
"created": {"to*": true},
},
}: "created",
{map[string]map[string]bool{
"created": {"to(.*)": true}},
{
map[string]map[string]bool{
"created": {"to(.*)": true},
},
}: "created",
{map[string]map[string]bool{
"created": {"tod": true}},
{
map[string]map[string]bool{
"created": {"tod": true},
},
}: "created",
{map[string]map[string]bool{
"created": {"anything": true, "to*": true}},
{
map[string]map[string]bool{
"created": {"anything": true, "to*": true},
},
}: "created",
}
@ -229,21 +249,31 @@ func TestArgsMatch(t *testing.T) {
}
differs := map[*Args]string{
{map[string]map[string]bool{
"created": {"tomorrow": true}},
{
map[string]map[string]bool{
"created": {"tomorrow": true},
},
}: "created",
{map[string]map[string]bool{
"created": {"to(day": true}},
{
map[string]map[string]bool{
"created": {"to(day": true},
},
}: "created",
{map[string]map[string]bool{
"created": {"tom(.*)": true}},
{
map[string]map[string]bool{
"created": {"tom(.*)": true},
},
}: "created",
{map[string]map[string]bool{
"created": {"tom": true}},
{
map[string]map[string]bool{
"created": {"tom": true},
},
}: "created",
{map[string]map[string]bool{
"created": {"today1": true},
"labels": {"today": true}},
{
map[string]map[string]bool{
"created": {"today1": true},
"labels": {"today": true},
},
}: "created",
}
@ -532,5 +562,4 @@ func TestGetBoolOrDefault(t *testing.T) {
assert.Check(t, is.Equal(tC.expectedValue, value))
})
}
}

View file

@ -154,8 +154,7 @@ func parseCreatedLayerInfo(img image) ([]string, []string, error) {
return dates, createdBy, nil
}
type emptyProvider struct {
}
type emptyProvider struct{}
func (p *emptyProvider) ReaderAt(ctx context.Context, dec ocispec.Descriptor) (content.ReaderAt, error) {
return nil, errors.Errorf("ReaderAt not implemented for empty provider")

View file

@ -21,11 +21,13 @@ import (
bolt "go.etcd.io/bbolt"
)
var keyParent = []byte("parent")
var keyCommitted = []byte("committed")
var keyIsCommitted = []byte("iscommitted")
var keyChainID = []byte("chainid")
var keySize = []byte("size")
var (
keyParent = []byte("parent")
keyCommitted = []byte("committed")
keyIsCommitted = []byte("iscommitted")
keyChainID = []byte("chainid")
keySize = []byte("size")
)
// Opt defines options for creating the snapshotter
type Opt struct {
@ -57,7 +59,7 @@ type snapshotter struct {
// NewSnapshotter creates a new snapshotter
func NewSnapshotter(opt Opt, prevLM leases.Manager) (snapshot.Snapshotter, leases.Manager, error) {
dbPath := filepath.Join(opt.Root, "snapshots.db")
db, err := bolt.Open(dbPath, 0600, nil)
db, err := bolt.Open(dbPath, 0o600, nil)
if err != nil {
return nil, nil, errors.Wrapf(err, "failed to open database file %s", dbPath)
}

View file

@ -224,7 +224,7 @@ func (b *Builder) Build(ctx context.Context, opt backend.BuildConfig) (*builder.
return nil, errors.Errorf("multiple outputs not supported")
}
var rc = opt.Source
rc := opt.Source
if buildID := opt.Options.BuildID; buildID != "" {
b.mu.Lock()
@ -466,6 +466,7 @@ func (sp *streamProxy) SetTrailer(_ grpcmetadata.MD) {
func (sp *streamProxy) Context() context.Context {
return sp.ctx
}
func (sp *streamProxy) RecvMsg(m interface{}) error {
return io.EOF
}
@ -478,6 +479,7 @@ type statusProxy struct {
func (sp *statusProxy) Send(resp *controlapi.StatusResponse) error {
return sp.SendMsg(resp)
}
func (sp *statusProxy) SendMsg(m interface{}) error {
if sr, ok := m.(*controlapi.StatusResponse); ok {
sp.ch <- sr
@ -493,6 +495,7 @@ type pruneProxy struct {
func (sp *pruneProxy) Send(resp *controlapi.UsageRecord) error {
return sp.SendMsg(resp)
}
func (sp *pruneProxy) SendMsg(m interface{}) error {
if sr, ok := m.(*controlapi.UsageRecord); ok {
sp.ch <- sr

View file

@ -195,7 +195,7 @@ func newGraphDriverController(ctx context.Context, rt http.RoundTripper, opt Opt
return nil, err
}
db, err := bolt.Open(filepath.Join(root, "containerdmeta.db"), 0644, nil)
db, err := bolt.Open(filepath.Join(root, "containerdmeta.db"), 0o644, nil)
if err != nil {
return nil, errors.WithStack(err)
}

View file

@ -15,8 +15,7 @@ func newExecutor(_, _ string, _ *libnetwork.Controller, _ *oci.DNSConfig, _ bool
return &winExecutor{}, nil
}
type winExecutor struct {
}
type winExecutor struct{}
func (w *winExecutor) Run(ctx context.Context, id string, root executor.Mount, mounts []executor.Mount, process executor.ProcessInfo, started chan<- struct{}) (err error) {
return errors.New("buildkit executor not implemented for windows")

View file

@ -520,8 +520,7 @@ func oneOffProgress(ctx context.Context, id string) func(err error) error {
}
}
type emptyProvider struct {
}
type emptyProvider struct{}
func (p *emptyProvider) ReaderAt(ctx context.Context, dec ocispec.Descriptor) (content.ReaderAt, error) {
return nil, errors.Errorf("ReaderAt not implemented for empty provider")

View file

@ -45,7 +45,6 @@ type Backend interface {
CommitBuildStep(context.Context, backend.CommitConfig) (image.ID, error)
// ContainerCreateWorkdir creates the workdir
ContainerCreateWorkdir(containerID string) error
CreateImage(ctx context.Context, config []byte, parent string, contentStoreDigest digest.Digest) (Image, error)
ImageCacheBuilder

View file

@ -406,7 +406,7 @@ func downloadSource(output io.Writer, stdout io.Writer, srcURL string) (remote b
tmpFileName = unnamedFilename
}
tmpFileName = filepath.Join(tmpDir, tmpFileName)
tmpFile, err := os.OpenFile(tmpFileName, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
tmpFile, err := os.OpenFile(tmpFileName, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
return
}
@ -510,11 +510,11 @@ func copyFile(archiver *archive.Archiver, source, dest string, identity *idtools
// modified for use on Windows to handle volume GUID paths. These paths
// are of the form \\?\Volume{<GUID>}\<path>. An example would be:
// \\?\Volume{dae8d3ac-b9a1-11e9-88eb-e8554b2ba1db}\bin\busybox.exe
if err := system.MkdirAll(filepath.Dir(dest), 0755); err != nil {
if err := system.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
return err
}
} else {
if err := idtools.MkdirAllAndChownNew(filepath.Dir(dest), 0755, *identity); err != nil {
if err := idtools.MkdirAllAndChownNew(filepath.Dir(dest), 0o755, *identity); err != nil {
return errors.Wrapf(err, "failed to create new directory")
}
}

View file

@ -15,7 +15,7 @@ func TestIsExistingDirectory(t *testing.T) {
tmpdir := fs.NewDir(t, "dir-exists-test")
defer tmpdir.Remove()
var testcases = []struct {
testcases := []struct {
doc string
path string
expected bool
@ -47,7 +47,7 @@ func TestIsExistingDirectory(t *testing.T) {
}
func TestGetFilenameForDownload(t *testing.T) {
var testcases = []struct {
testcases := []struct {
path string
disposition string
expected string

View file

@ -430,7 +430,8 @@ func TestPrependEnvOnCmd(t *testing.T) {
cmd := []string{"foo", "bar"}
cmdWithEnv := prependEnvOnCmd(buildArgs, args, cmd)
expected := strslice.StrSlice([]string{
"|3", "NO_PROXY=YA", "args=not", "sorted=nope", "foo", "bar"})
"|3", "NO_PROXY=YA", "args=not", "sorted=nope", "foo", "bar",
})
assert.Check(t, is.DeepEqual(expected, cmdWithEnv))
}

View file

@ -108,7 +108,6 @@ func normalizeWorkdirWindows(current string, requested string) (string, error) {
//
// The commands when this function is called are RUN, ENTRYPOINT and CMD.
func resolveCmdLine(cmd instructions.ShellDependantCmdLine, runConfig *container.Config, os, command, original string) ([]string, bool) {
// Make sure we return an empty array if there is no cmd.CmdLine
if len(cmd.CmdLine) == 0 {
return []string{}, runConfig.ArgsEscaped

View file

@ -104,11 +104,10 @@ func TestDispatch(t *testing.T) {
defer cleanup()
for filename, content := range tc.files {
createTestTempFile(t, contextDir, filename, content, 0777)
createTestTempFile(t, contextDir, filename, content, 0o777)
}
tarStream, err := archive.Tar(contextDir, archive.Uncompressed)
if err != nil {
t.Fatalf("Error when creating tar stream: %s", err)
}
@ -120,7 +119,6 @@ func TestDispatch(t *testing.T) {
}()
buildContext, err := remotecontext.FromArchive(tarStream)
if err != nil {
t.Fatalf("Error when creating tar context: %s", err)
}

View file

@ -41,12 +41,12 @@ othergrp:x:6666:
contextDir, cleanup := createTestTempDir(t, "", "builder-chown-parse-test")
defer cleanup()
if err := os.Mkdir(filepath.Join(contextDir, "etc"), 0755); err != nil {
if err := os.Mkdir(filepath.Join(contextDir, "etc"), 0o755); err != nil {
t.Fatalf("error creating test directory: %v", err)
}
for filename, content := range testFiles {
createTestTempFile(t, filepath.Join(contextDir, "etc"), filename, content, 0644)
createTestTempFile(t, filepath.Join(contextDir, "etc"), filename, content, 0o644)
}
// positive tests

View file

@ -26,7 +26,7 @@ func TestEmptyDockerfile(t *testing.T) {
contextDir, cleanup := createTestTempDir(t, "", "builder-dockerfile-test")
defer cleanup()
createTestTempFile(t, contextDir, builder.DefaultDockerfileName, "", 0777)
createTestTempFile(t, contextDir, builder.DefaultDockerfileName, "", 0o777)
readAndCheckDockerfile(t, "emptyDockerfile", contextDir, "", "the Dockerfile (Dockerfile) cannot be empty")
}
@ -96,7 +96,7 @@ func TestCopyRunConfig(t *testing.T) {
defaultEnv := []string{"foo=1"}
defaultCmd := []string{"old"}
var testcases = []struct {
testcases := []struct {
doc string
modifiers []runConfigModifier
expected *container.Config

View file

@ -45,7 +45,6 @@ func getAccountIdentity(ctx context.Context, builder *Builder, accountName strin
// Check if the account name is one unique to containers.
if strings.EqualFold(accountName, "ContainerAdministrator") {
return idtools.Identity{SID: idtools.ContainerAdministratorSidString}, nil
} else if strings.EqualFold(accountName, "ContainerUser") {
return idtools.Identity{SID: idtools.ContainerUserSidString}, nil
}
@ -56,7 +55,6 @@ func getAccountIdentity(ctx context.Context, builder *Builder, accountName strin
}
func lookupNTAccount(ctx context.Context, builder *Builder, accountName string, state *dispatchState) (idtools.Identity, error) {
source, _ := filepath.Split(os.Args[0])
target := "C:\\Docker"
@ -72,14 +70,15 @@ func lookupNTAccount(ctx context.Context, builder *Builder, accountName string,
runConfig.Cmd = []string{targetExecutable, "getaccountsid", accountName}
hostConfig := &container.HostConfig{Mounts: []mount.Mount{
{
Type: mount.TypeBind,
Source: source,
Target: target,
ReadOnly: true,
hostConfig := &container.HostConfig{
Mounts: []mount.Mount{
{
Type: mount.TypeBind,
Source: source,
Target: target,
ReadOnly: true,
},
},
},
}
container, err := builder.containerManager.Create(ctx, runConfig, hostConfig)

View file

@ -136,8 +136,7 @@ func (l *mockLayer) DiffID() layer.DiffID {
return "abcdef"
}
type mockRWLayer struct {
}
type mockRWLayer struct{}
func (l *mockRWLayer) Release() error {
return nil

View file

@ -11,7 +11,6 @@ import (
// When an error occurs, it terminates the test.
func createTestTempDir(t *testing.T, dir, prefix string) (string, func()) {
path, err := os.MkdirTemp(dir, prefix)
if err != nil {
t.Fatalf("Error when creating directory %s with prefix %s: %s", dir, prefix, err)
}
@ -30,7 +29,6 @@ func createTestTempDir(t *testing.T, dir, prefix string) (string, func()) {
func createTestTempFile(t *testing.T, dir, filename, contents string, perm os.FileMode) string {
filePath := filepath.Join(dir, filename)
err := os.WriteFile(filePath, []byte(contents), perm)
if err != nil {
t.Fatalf("Error when creating %s file: %s", filename, err)
}

View file

@ -31,7 +31,6 @@ func extractFilenames(files []os.DirEntry) []string {
func checkDirectory(t *testing.T, dir string, expectedFiles []string) {
files, err := os.ReadDir(dir)
if err != nil {
t.Fatalf("Could not read directory: %s", err)
}
@ -55,7 +54,6 @@ func executeProcess(t *testing.T, contextDir string) {
modifiableCtx := &stubRemote{root: contextDir}
err := removeDockerfile(modifiableCtx, builder.DefaultDockerfileName)
if err != nil {
t.Fatalf("Error when executing Process: %s", err)
}
@ -65,9 +63,9 @@ func TestProcessShouldRemoveDockerfileDockerignore(t *testing.T) {
contextDir, cleanup := createTestTempDir(t, "", "builder-dockerignore-process-test")
defer cleanup()
createTestTempFile(t, contextDir, shouldStayFilename, testfileContents, 0777)
createTestTempFile(t, contextDir, dockerignoreFilename, "Dockerfile\n.dockerignore", 0777)
createTestTempFile(t, contextDir, builder.DefaultDockerfileName, dockerfileContents, 0777)
createTestTempFile(t, contextDir, shouldStayFilename, testfileContents, 0o777)
createTestTempFile(t, contextDir, dockerignoreFilename, "Dockerfile\n.dockerignore", 0o777)
createTestTempFile(t, contextDir, builder.DefaultDockerfileName, dockerfileContents, 0o777)
executeProcess(t, contextDir)
@ -78,8 +76,8 @@ func TestProcessNoDockerignore(t *testing.T) {
contextDir, cleanup := createTestTempDir(t, "", "builder-dockerignore-process-test")
defer cleanup()
createTestTempFile(t, contextDir, shouldStayFilename, testfileContents, 0777)
createTestTempFile(t, contextDir, builder.DefaultDockerfileName, dockerfileContents, 0777)
createTestTempFile(t, contextDir, shouldStayFilename, testfileContents, 0o777)
createTestTempFile(t, contextDir, builder.DefaultDockerfileName, dockerfileContents, 0o777)
executeProcess(t, contextDir)
@ -90,9 +88,9 @@ func TestProcessShouldLeaveAllFiles(t *testing.T) {
contextDir, cleanup := createTestTempDir(t, "", "builder-dockerignore-process-test")
defer cleanup()
createTestTempFile(t, contextDir, shouldStayFilename, testfileContents, 0777)
createTestTempFile(t, contextDir, builder.DefaultDockerfileName, dockerfileContents, 0777)
createTestTempFile(t, contextDir, dockerignoreFilename, "input1\ninput2", 0777)
createTestTempFile(t, contextDir, shouldStayFilename, testfileContents, 0o777)
createTestTempFile(t, contextDir, builder.DefaultDockerfileName, dockerfileContents, 0o777)
createTestTempFile(t, contextDir, dockerignoreFilename, "input1\ninput2", 0o777)
executeProcess(t, contextDir)
@ -111,9 +109,11 @@ func (r *stubRemote) Hash(path string) (string, error) {
func (r *stubRemote) Root() string {
return r.root
}
func (r *stubRemote) Close() error {
return errors.New("not implemented")
}
func (r *stubRemote) Remove(p string) error {
return os.Remove(filepath.Join(r.root, p))
}

View file

@ -35,7 +35,6 @@ func WithIsolatedConfig(v bool) CloneOption {
// will be under "docker-build-git"
func Clone(remoteURL string, opts ...CloneOption) (string, error) {
repo, err := parseRemoteURL(remoteURL)
if err != nil {
return "", err
}

View file

@ -239,11 +239,11 @@ func TestCheckoutGit(t *testing.T) {
must(gitRepo{}.gitWithinDir(root, "-c", "init.defaultBranch=master", "init", gitDir))
must(gitRepo{}.gitWithinDir(gitDir, "config", "user.email", "test@docker.com"))
must(gitRepo{}.gitWithinDir(gitDir, "config", "user.name", "Docker test"))
assert.NilError(t, os.WriteFile(filepath.Join(gitDir, "Dockerfile"), []byte("FROM scratch"), 0644))
assert.NilError(t, os.WriteFile(filepath.Join(gitDir, "Dockerfile"), []byte("FROM scratch"), 0o644))
subDir := filepath.Join(gitDir, "subdir")
assert.NilError(t, os.Mkdir(subDir, 0755))
assert.NilError(t, os.WriteFile(filepath.Join(subDir, "Dockerfile"), []byte("FROM scratch\nEXPOSE 5000"), 0644))
assert.NilError(t, os.Mkdir(subDir, 0o755))
assert.NilError(t, os.WriteFile(filepath.Join(subDir, "Dockerfile"), []byte("FROM scratch\nEXPOSE 5000"), 0o644))
if runtime.GOOS != "windows" {
assert.NilError(t, os.Symlink("../subdir", filepath.Join(gitDir, "parentlink")))
@ -254,8 +254,8 @@ func TestCheckoutGit(t *testing.T) {
must(gitRepo{}.gitWithinDir(gitDir, "commit", "-am", "First commit"))
must(gitRepo{}.gitWithinDir(gitDir, "checkout", "-b", "test"))
assert.NilError(t, os.WriteFile(filepath.Join(gitDir, "Dockerfile"), []byte("FROM scratch\nEXPOSE 3000"), 0644))
assert.NilError(t, os.WriteFile(filepath.Join(subDir, "Dockerfile"), []byte("FROM busybox\nEXPOSE 5000"), 0644))
assert.NilError(t, os.WriteFile(filepath.Join(gitDir, "Dockerfile"), []byte("FROM scratch\nEXPOSE 3000"), 0o644))
assert.NilError(t, os.WriteFile(filepath.Join(subDir, "Dockerfile"), []byte("FROM busybox\nEXPOSE 5000"), 0o644))
must(gitRepo{}.gitWithinDir(gitDir, "add", "-A"))
must(gitRepo{}.gitWithinDir(gitDir, "commit", "-am", "Branch commit"))
@ -267,7 +267,7 @@ func TestCheckoutGit(t *testing.T) {
must(gitRepo{}.gitWithinDir(subrepoDir, "config", "user.email", "test@docker.com"))
must(gitRepo{}.gitWithinDir(subrepoDir, "config", "user.name", "Docker test"))
assert.NilError(t, os.WriteFile(filepath.Join(subrepoDir, "subfile"), []byte("subcontents"), 0644))
assert.NilError(t, os.WriteFile(filepath.Join(subrepoDir, "subfile"), []byte("subcontents"), 0o644))
must(gitRepo{}.gitWithinDir(subrepoDir, "add", "-A"))
must(gitRepo{}.gitWithinDir(subrepoDir, "commit", "-am", "Subrepo initial"))

View file

@ -196,7 +196,7 @@ func TestDownloadRemote(t *testing.T) {
}
func TestGetWithStatusError(t *testing.T) {
var testcases = []struct {
testcases := []struct {
err error
statusCode int
expectedErr string

View file

@ -49,12 +49,11 @@ func TestHashFile(t *testing.T) {
contextDir, cleanup := createTestTempDir(t, "", "builder-tarsum-test")
defer cleanup()
createTestTempFile(t, contextDir, filename, contents, 0755)
createTestTempFile(t, contextDir, filename, contents, 0o755)
tarSum := makeTestArchiveContext(t, contextDir)
sum, err := tarSum.Hash(filename)
if err != nil {
t.Fatalf("Error when executing Stat: %s", err)
}
@ -75,23 +74,21 @@ func TestHashSubdir(t *testing.T) {
defer cleanup()
contextSubdir := filepath.Join(contextDir, "builder-tarsum-test-subdir")
err := os.Mkdir(contextSubdir, 0755)
err := os.Mkdir(contextSubdir, 0o755)
if err != nil {
t.Fatalf("Failed to make directory: %s", contextSubdir)
}
testFilename := createTestTempFile(t, contextSubdir, filename, contents, 0755)
testFilename := createTestTempFile(t, contextSubdir, filename, contents, 0o755)
tarSum := makeTestArchiveContext(t, contextDir)
relativePath, err := filepath.Rel(contextDir, testFilename)
if err != nil {
t.Fatalf("Error when getting relative path: %s", err)
}
sum, err := tarSum.Hash(relativePath)
if err != nil {
t.Fatalf("Error when executing Stat: %s", err)
}
@ -114,7 +111,6 @@ func TestRemoveDirectory(t *testing.T) {
contextSubdir := createTestTempSubdir(t, contextDir, "builder-tarsum-test-subdir")
relativePath, err := filepath.Rel(contextDir, contextSubdir)
if err != nil {
t.Fatalf("Error when getting relative path: %s", err)
}

View file

@ -11,7 +11,6 @@ import (
// When an error occurs, it terminates the test.
func createTestTempDir(t *testing.T, dir, prefix string) (string, func()) {
path, err := os.MkdirTemp(dir, prefix)
if err != nil {
t.Fatalf("Error when creating directory %s with prefix %s: %s", dir, prefix, err)
}
@ -32,7 +31,6 @@ func createTestTempDir(t *testing.T, dir, prefix string) (string, func()) {
// When an error occurs, it terminates the test.
func createTestTempSubdir(t *testing.T, dir, prefix string) string {
path, err := os.MkdirTemp(dir, prefix)
if err != nil {
t.Fatalf("Error when creating directory %s with prefix %s: %s", dir, prefix, err)
}
@ -45,7 +43,6 @@ func createTestTempSubdir(t *testing.T, dir, prefix string) string {
func createTestTempFile(t *testing.T, dir, filename, contents string, perm os.FileMode) string {
filePath := filepath.Join(dir, filename)
err := os.WriteFile(filePath, []byte(contents), perm)
if err != nil {
t.Fatalf("Error when creating %s file: %s", filename, err)
}

View file

@ -67,7 +67,6 @@ func TestCheckpointCreate(t *testing.T) {
CheckpointID: expectedCheckpointID,
Exit: true,
})
if err != nil {
t.Fatal(err)
}

View file

@ -48,7 +48,6 @@ func TestCheckpointDelete(t *testing.T) {
err := client.CheckpointDelete(context.Background(), "container_id", types.CheckpointDeleteOptions{
CheckpointID: "checkpoint_id",
})
if err != nil {
t.Fatal(err)
}

View file

@ -66,7 +66,7 @@ func TestContainerStatPath(t *testing.T) {
}
content, err := json.Marshal(types.ContainerPathStat{
Name: "name",
Mode: 0700,
Mode: 0o700,
})
if err != nil {
return nil, err
@ -88,7 +88,7 @@ func TestContainerStatPath(t *testing.T) {
if stat.Name != "name" {
t.Fatalf("expected container path stat name to be 'name', got '%s'", stat.Name)
}
if stat.Mode != 0700 {
if stat.Mode != 0o700 {
t.Fatalf("expected container path stat mode to be 0700, got '%v'", stat.Mode)
}
}
@ -190,7 +190,7 @@ func TestCopyFromContainerEmptyResponse(t *testing.T) {
client: newMockClient(func(req *http.Request) (*http.Response, error) {
content, err := json.Marshal(types.ContainerPathStat{
Name: "path/to/file",
Mode: 0700,
Mode: 0o700,
})
if err != nil {
return nil, err
@ -244,7 +244,7 @@ func TestCopyFromContainer(t *testing.T) {
headercontent, err := json.Marshal(types.ContainerPathStat{
Name: "name",
Mode: 0700,
Mode: 0o700,
})
if err != nil {
return nil, err
@ -267,7 +267,7 @@ func TestCopyFromContainer(t *testing.T) {
if stat.Name != "name" {
t.Fatalf("expected container path stat name to be 'name', got '%s'", stat.Name)
}
if stat.Mode != 0700 {
if stat.Mode != 0o700 {
t.Fatalf("expected container path stat mode to be 0700, got '%v'", stat.Mode)
}
content, err := io.ReadAll(r)

View file

@ -37,7 +37,6 @@ func (cli *Client) ContainerList(ctx context.Context, options types.ContainerLis
if options.Filters.Len() > 0 {
//nolint:staticcheck // ignore SA1019 for old code
filterJSON, err := filters.ToParamWithVersion(cli.version, options.Filters)
if err != nil {
return nil, err
}

View file

@ -16,7 +16,6 @@ func (cli *Client) NodeList(ctx context.Context, options types.NodeListOptions)
if options.Filters.Len() > 0 {
filterJSON, err := filters.ToJSON(options.Filters)
if err != nil {
return nil, err
}

View file

@ -194,7 +194,6 @@ func TestServiceCreateDigestPinning(t *testing.T) {
},
},
}, types.ServiceCreateOptions{QueryRegistry: true})
if err != nil {
t.Fatal(err)
}

View file

@ -14,8 +14,10 @@ import (
"gotest.tools/v3/skip"
)
var testBuf = []byte("Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo")
var testBufSize = len(testBuf)
var (
testBuf = []byte("Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo")
testBufSize = len(testBuf)
)
type EchoServer interface {
Run()

View file

@ -48,7 +48,7 @@ func (proxy *SCTPProxy) clientLoop(client *sctp.SCTPConn, quit chan bool) {
backendC := sctp.NewSCTPSndRcvInfoWrappedConn(backend)
var wg sync.WaitGroup
var broker = func(to, from net.Conn) {
broker := func(to, from net.Conn) {
io.Copy(to, from)
from.Close()
to.Close()

View file

@ -44,7 +44,7 @@ func (proxy *TCPProxy) clientLoop(client *net.TCPConn, quit chan bool) {
}
var wg sync.WaitGroup
var broker = func(to, from *net.TCPConn) {
broker := func(to, from *net.TCPConn) {
io.Copy(to, from)
from.CloseRead()
to.CloseWrite()

View file

@ -142,7 +142,7 @@ func (cli *DaemonCli) start(opts *daemonOptions) (err error) {
return err
}
if err := system.MkdirAll(cli.Config.ExecRoot, 0700); err != nil {
if err := system.MkdirAll(cli.Config.ExecRoot, 0o700); err != nil {
return err
}

View file

@ -46,7 +46,7 @@ func getDefaultDaemonConfigFile() (string, error) {
// setDefaultUmask sets the umask to 0022 to avoid problems
// caused by custom umask
func setDefaultUmask() error {
desiredUmask := 0022
desiredUmask := 0o022
unix.Umask(desiredUmask)
if umask := unix.Umask(desiredUmask); umask != desiredUmask {
return errors.Errorf("failed to set umask: expected %#o, got %#o", desiredUmask, umask)

View file

@ -6,9 +6,9 @@ import (
"os"
"time"
"github.com/containerd/containerd/log"
"github.com/docker/docker/daemon/config"
"github.com/docker/docker/pkg/system"
"github.com/containerd/containerd/log"
"golang.org/x/sys/windows"
)

View file

@ -17,9 +17,7 @@ import (
"github.com/spf13/cobra"
)
var (
honorXDG bool
)
var honorXDG bool
func newDaemonCommand() (*cobra.Command, error) {
cfg, err := config.New()

View file

@ -1,10 +1,11 @@
package main
import (
"github.com/Microsoft/go-winio/pkg/etwlogrus"
"github.com/sirupsen/logrus"
"io"
"path/filepath"
"github.com/Microsoft/go-winio/pkg/etwlogrus"
"github.com/sirupsen/logrus"
)
func runDaemon(opts *daemonOptions) error {

View file

@ -26,7 +26,7 @@ func buildTestBinary(t *testing.T, tmpdir string, prefix string) (string, string
}
func TestTrap(t *testing.T) {
var sigmap = []struct {
sigmap := []struct {
name string
signal os.Signal
multiple bool

View file

@ -31,7 +31,7 @@ func getCheckpointDir(checkDir, checkpointID, ctrName, ctrID, ctrCheckpointDir s
case err == nil && stat.IsDir():
err2 = fmt.Errorf("checkpoint with name %s already exists for container %s", checkpointID, ctrName)
case err != nil && os.IsNotExist(err):
err2 = os.MkdirAll(checkpointAbsDir, 0700)
err2 = os.MkdirAll(checkpointAbsDir, 0o700)
case err != nil:
err2 = err
default:
@ -111,7 +111,7 @@ func (daemon *Daemon) CheckpointList(name string, config types.CheckpointListOpt
return nil, err
}
if err := os.MkdirAll(checkpointDir, 0755); err != nil {
if err := os.MkdirAll(checkpointDir, 0o755); err != nil {
return nil, err
}

View file

@ -140,7 +140,7 @@ type attacher struct {
// New creates a new Cluster instance using provided config.
func New(config Config) (*Cluster, error) {
root := filepath.Join(config.Root, swarmDirName)
if err := os.MkdirAll(root, 0700); err != nil {
if err := os.MkdirAll(root, 0o700); err != nil {
return nil, err
}
if config.RuntimeRoot == "" {
@ -154,7 +154,7 @@ func New(config Config) (*Cluster, error) {
config.RaftElectionTick = 10 * config.RaftHeartbeatTick
}
if err := os.MkdirAll(config.RuntimeRoot, 0700); err != nil {
if err := os.MkdirAll(config.RuntimeRoot, 0o700); err != nil {
return nil, err
}
c := &Cluster{

View file

@ -66,7 +66,8 @@ func NewController(backend Backend, t *api.Task) (*Controller, error) {
"controller": "plugin",
"task": t.ID,
"plugin": spec.Name,
})}, nil
}),
}, nil
}
func readSpec(t *api.Task) (runtime.PluginSpec, error) {

View file

@ -118,7 +118,8 @@ func endpointFromGRPC(e *swarmapi.Endpoint) types.Endpoint {
for _, v := range e.VirtualIPs {
endpoint.VirtualIPs = append(endpoint.VirtualIPs, types.EndpointVirtualIP{
NetworkID: v.NetworkID,
Addr: v.Addr})
Addr: v.Addr,
})
}
}

View file

@ -15,12 +15,12 @@ func TestNodeCSIInfoFromGRPC(t *testing.T) {
ID: "someID",
Description: &swarmapi.NodeDescription{
CSIInfo: []*swarmapi.NodeCSIInfo{
&swarmapi.NodeCSIInfo{
{
PluginName: "plugin1",
NodeID: "p1n1",
MaxVolumesPerNode: 1,
},
&swarmapi.NodeCSIInfo{
{
PluginName: "plugin2",
NodeID: "p2n1",
MaxVolumesPerNode: 2,

View file

@ -412,7 +412,7 @@ func (c *containerAdapter) wait(ctx context.Context) (<-chan containerpkg.StateS
}
func (c *containerAdapter) shutdown(ctx context.Context) error {
var options = containertypes.StopOptions{}
options := containertypes.StopOptions{}
// Default stop grace period to nil (daemon will use the stopTimeout of the container)
if spec := c.container.spec(); spec.StopGracePeriod != nil {
timeout := int(spec.StopGracePeriod.Seconds)

View file

@ -1,9 +1,8 @@
package container // import "github.com/docker/docker/daemon/cluster/executor/container"
import (
"testing"
"context"
"testing"
"time"
"github.com/docker/docker/daemon"

View file

@ -142,6 +142,7 @@ func getDataPathPort(portNum uint32) (uint32, error) {
}
return portNum, nil
}
func resolveDataPathAddr(dataPathAddr string) (string, error) {
if dataPathAddr == "" {
// dataPathAddr is not defined

View file

@ -32,7 +32,7 @@ func savePersistentState(root string, config nodeStartConfig) error {
if err != nil {
return err
}
return ioutils.AtomicWriteFile(filepath.Join(root, stateFile), dt, 0600)
return ioutils.AtomicWriteFile(filepath.Join(root, stateFile), dt, 0o600)
}
func clearPersistentState(root string) error {

View file

@ -158,7 +158,7 @@ func TestDaemonConfigurationMergeDefaultAddressPools(t *testing.T) {
expected := []*ipamutils.NetworkToSplit{{Base: "10.123.0.0/16", Size: 24}}
t.Run("empty config file", func(t *testing.T) {
var conf = Config{}
conf := Config{}
flags := pflag.NewFlagSet("test", pflag.ContinueOnError)
flags.Var(&conf.NetworkConfig.DefaultAddressPools, "default-address-pool", "")
assert.Check(t, flags.Set("default-address-pool", "base=10.123.0.0/16,size=24"))
@ -169,7 +169,7 @@ func TestDaemonConfigurationMergeDefaultAddressPools(t *testing.T) {
})
t.Run("config file", func(t *testing.T) {
var conf = Config{}
conf := Config{}
flags := pflag.NewFlagSet("test", pflag.ContinueOnError)
flags.Var(&conf.NetworkConfig.DefaultAddressPools, "default-address-pool", "")
@ -179,7 +179,7 @@ func TestDaemonConfigurationMergeDefaultAddressPools(t *testing.T) {
})
t.Run("with conflicting options", func(t *testing.T) {
var conf = Config{}
conf := Config{}
flags := pflag.NewFlagSet("test", pflag.ContinueOnError)
flags.Var(&conf.NetworkConfig.DefaultAddressPools, "default-address-pool", "")
assert.Check(t, flags.Set("default-address-pool", "base=10.123.0.0/16,size=24"))

View file

@ -685,7 +685,6 @@ func cleanOperationalData(es *network.EndpointSettings) {
}
func (daemon *Daemon) updateNetworkConfig(container *container.Container, n libnetwork.Network, endpointConfig *networktypes.EndpointSettings, updateSettings bool) error {
if containertypes.NetworkMode(n.Name()).IsUserDefined() {
addShortID := true
shortID := stringid.TruncateID(container.ID)

View file

@ -141,7 +141,7 @@ func (daemon *Daemon) setupIpcDirs(c *container.Container) error {
return err
}
if err := idtools.MkdirAllAndChown(shmPath, 0700, rootIDs); err != nil {
if err := idtools.MkdirAllAndChown(shmPath, 0o700, rootIDs); err != nil {
return err
}
@ -196,7 +196,7 @@ func (daemon *Daemon) setupSecretDir(c *container.Container) (setupErr error) {
if err != nil {
return errors.Wrap(err, "error getting secret file path")
}
if err := idtools.MkdirAllAndChown(filepath.Dir(fPath), 0700, rootIDs); err != nil {
if err := idtools.MkdirAllAndChown(filepath.Dir(fPath), 0o700, rootIDs); err != nil {
return errors.Wrap(err, "error creating secret mount path")
}
@ -247,7 +247,7 @@ func (daemon *Daemon) setupSecretDir(c *container.Container) (setupErr error) {
if err != nil {
return errors.Wrap(err, "error getting config file path for container")
}
if err := idtools.MkdirAllAndChown(filepath.Dir(fPath), 0700, rootIDs); err != nil {
if err := idtools.MkdirAllAndChown(filepath.Dir(fPath), 0o700, rootIDs); err != nil {
return errors.Wrap(err, "error creating config mount path")
}
@ -294,7 +294,7 @@ func (daemon *Daemon) createSecretsDir(c *container.Container) error {
}
// create tmpfs
if err := idtools.MkdirAllAndChown(dir, 0700, rootIDs); err != nil {
if err := idtools.MkdirAllAndChown(dir, 0o700, rootIDs); err != nil {
return errors.Wrap(err, "error creating secret local mount path")
}
@ -461,5 +461,5 @@ func (daemon *Daemon) setupContainerMountsRoot(c *container.Container) error {
if err != nil {
return err
}
return idtools.MkdirAllAndChown(p, 0710, idtools.Identity{UID: idtools.CurrentIdentity().UID, GID: daemon.IdentityMapping().RootPair().GID})
return idtools.MkdirAllAndChown(p, 0o710, idtools.Identity{UID: idtools.CurrentIdentity().UID, GID: daemon.IdentityMapping().RootPair().GID})
}

View file

@ -169,7 +169,6 @@ func (daemon *Daemon) setupPathsAndSandboxOptions(container *container.Container
}
func (daemon *Daemon) initializeNetworkingPaths(container *container.Container, nc *container.Container) error {
if nc.HostConfig.Isolation.IsHyperV() {
return fmt.Errorf("sharing of hyperv containers network is not supported")
}

View file

@ -76,7 +76,6 @@ func (i *ImageService) Children(ctx context.Context, id image.ID) ([]image.ID, e
}
}
}
}
return children, nil

View file

@ -120,7 +120,6 @@ func (i *ImageService) Images(ctx context.Context, opts types.ImageListOptions)
return nil
})
if err != nil {
return nil, err
}
@ -235,9 +234,7 @@ type imageFilterFunc func(image images.Image) bool
// containerdListFilters is a slice of filters which should be passed to ImageService.List()
// filterFunc is a function that checks whether given image matches the filters.
// TODO(thaJeztah): reimplement filters using containerd filters: see https://github.com/moby/moby/issues/43845
func (i *ImageService) setupFilters(ctx context.Context, imageFilters filters.Args) (
containerdListFilters []string, filterFunc imageFilterFunc, outErr error) {
func (i *ImageService) setupFilters(ctx context.Context, imageFilters filters.Args) (containerdListFilters []string, filterFunc imageFilterFunc, outErr error) {
var fltrs []imageFilterFunc
err := imageFilters.WalkValues("before", func(value string) error {
ref, err := reference.ParseDockerRef(value)

View file

@ -17,10 +17,10 @@ import (
)
func (daemon *Daemon) configureLocalContentStore(ns string) (content.Store, leases.Manager, error) {
if err := os.MkdirAll(filepath.Join(daemon.root, "content"), 0700); err != nil {
if err := os.MkdirAll(filepath.Join(daemon.root, "content"), 0o700); err != nil {
return nil, nil, errors.Wrap(err, "error creating dir for content store")
}
db, err := bbolt.Open(filepath.Join(daemon.root, "content", "metadata.db"), 0600, nil)
db, err := bbolt.Open(filepath.Join(daemon.root, "content", "metadata.db"), 0o600, nil)
if err != nil {
return nil, nil, errors.Wrap(err, "error opening bolt db for content metadata store")
}

View file

@ -197,10 +197,10 @@ func (daemon *Daemon) create(ctx context.Context, daemonCfg *config.Config, opts
}
current := idtools.CurrentIdentity()
if err := idtools.MkdirAndChown(ctr.Root, 0710, idtools.Identity{UID: current.UID, GID: daemon.IdentityMapping().RootPair().GID}); err != nil {
if err := idtools.MkdirAndChown(ctr.Root, 0o710, idtools.Identity{UID: current.UID, GID: daemon.IdentityMapping().RootPair().GID}); err != nil {
return nil, err
}
if err := idtools.MkdirAndChown(ctr.CheckpointDir(), 0700, current); err != nil {
if err := idtools.MkdirAndChown(ctr.CheckpointDir(), 0o700, current); err != nil {
return nil, err
}

View file

@ -258,9 +258,9 @@ func TestRootMountCleanup(t *testing.T) {
cfg.ExecRoot = filepath.Join(testRoot, "exec")
cfg.Root = filepath.Join(testRoot, "daemon")
err = os.Mkdir(cfg.ExecRoot, 0755)
err = os.Mkdir(cfg.ExecRoot, 0o755)
assert.NilError(t, err)
err = os.Mkdir(cfg.Root, 0755)
err = os.Mkdir(cfg.Root, 0o755)
assert.NilError(t, err)
d := &Daemon{root: cfg.Root}
@ -319,7 +319,7 @@ func TestRootMountCleanup(t *testing.T) {
err = mount.MakeShared(testRoot)
assert.NilError(t, err)
defer mount.MakePrivate(testRoot)
err = os.WriteFile(unmountFile, nil, 0644)
err = os.WriteFile(unmountFile, nil, 0o644)
assert.NilError(t, err)
err = setupDaemonRootPropagation(&cfg.Config)

View file

@ -150,7 +150,7 @@ func TestContainerInitDNS(t *testing.T) {
containerID := "d59df5276e7b219d510fe70565e0404bc06350e0d4b43fe961f22f339980170e"
containerPath := filepath.Join(tmp, containerID)
if err := os.MkdirAll(containerPath, 0755); err != nil {
if err := os.MkdirAll(containerPath, 0o755); err != nil {
t.Fatal(err)
}
@ -176,7 +176,7 @@ func TestContainerInitDNS(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if err = os.WriteFile(configPath, []byte(config), 0644); err != nil {
if err = os.WriteFile(configPath, []byte(config), 0o644); err != nil {
t.Fatal(err)
}
@ -189,7 +189,7 @@ func TestContainerInitDNS(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if err = os.WriteFile(hostConfigPath, []byte(hostConfig), 0644); err != nil {
if err = os.WriteFile(hostConfigPath, []byte(hostConfig), 0o644); err != nil {
t.Fatal(err)
}

View file

@ -1213,19 +1213,19 @@ func setupDaemonRoot(config *config.Config, rootDir string, remappedRoot idtools
// layer content subtrees.
if _, err := os.Stat(rootDir); err == nil {
// root current exists; verify the access bits are correct by setting them
if err = os.Chmod(rootDir, 0711); err != nil {
if err = os.Chmod(rootDir, 0o711); err != nil {
return err
}
} else if os.IsNotExist(err) {
// no root exists yet, create it 0711 with root:root ownership
if err := os.MkdirAll(rootDir, 0711); err != nil {
if err := os.MkdirAll(rootDir, 0o711); err != nil {
return err
}
}
id := idtools.Identity{UID: idtools.CurrentIdentity().UID, GID: remappedRoot.GID}
// First make sure the current root dir has the correct perms.
if err := idtools.MkdirAllAndChown(config.Root, 0710, id); err != nil {
if err := idtools.MkdirAllAndChown(config.Root, 0o710, id); err != nil {
return errors.Wrapf(err, "could not create or set daemon root permissions: %s", config.Root)
}
@ -1237,7 +1237,7 @@ func setupDaemonRoot(config *config.Config, rootDir string, remappedRoot idtools
config.Root = filepath.Join(rootDir, fmt.Sprintf("%d.%d", remappedRoot.UID, remappedRoot.GID))
log.G(context.TODO()).Debugf("Creating user namespaced daemon root: %s", config.Root)
// Create the root directory if it doesn't exist
if err := idtools.MkdirAllAndChown(config.Root, 0710, id); err != nil {
if err := idtools.MkdirAllAndChown(config.Root, 0o710, id); err != nil {
return fmt.Errorf("Cannot create daemon root: %s: %v", config.Root, err)
}
// we also need to verify that any pre-existing directories in the path to
@ -1323,11 +1323,11 @@ func setupDaemonRootPropagation(cfg *config.Config) error {
return nil
}
if err := os.MkdirAll(filepath.Dir(cleanupFile), 0700); err != nil {
if err := os.MkdirAll(filepath.Dir(cleanupFile), 0o700); err != nil {
return errors.Wrap(err, "error creating dir to store mount cleanup file")
}
if err := os.WriteFile(cleanupFile, nil, 0600); err != nil {
if err := os.WriteFile(cleanupFile, nil, 0o600); err != nil {
return errors.Wrap(err, "error writing file to signal mount cleanup on shutdown")
}
return nil
@ -1446,7 +1446,7 @@ func (daemon *Daemon) initCPURtController(cfg *config.Config, mnt, path string)
}
path = filepath.Join(mnt, path)
if err := os.MkdirAll(path, 0755); err != nil {
if err := os.MkdirAll(path, 0o755); err != nil {
return err
}
if err := maybeCreateCPURealTimeFile(cfg.CPURealtimePeriod, "cpu.rt_period_us", path); err != nil {
@ -1459,7 +1459,7 @@ func maybeCreateCPURealTimeFile(configValue int64, file string, path string) err
if configValue == 0 {
return nil
}
return os.WriteFile(filepath.Join(path, file), []byte(strconv.FormatInt(configValue, 10)), 0700)
return os.WriteFile(filepath.Join(path, file), []byte(strconv.FormatInt(configValue, 10)), 0o700)
}
func (daemon *Daemon) setupSeccompProfile(cfg *config.Config) error {

View file

@ -10,6 +10,7 @@ import (
"github.com/Microsoft/hcsshim"
"github.com/Microsoft/hcsshim/osversion"
"github.com/containerd/containerd/log"
containertypes "github.com/docker/docker/api/types/container"
"github.com/docker/docker/container"
"github.com/docker/docker/daemon/config"
@ -28,7 +29,6 @@ import (
"github.com/docker/docker/pkg/system"
"github.com/docker/docker/runconfig"
"github.com/pkg/errors"
"github.com/containerd/containerd/log"
"golang.org/x/sys/windows"
"golang.org/x/sys/windows/svc/mgr"
)
@ -198,7 +198,7 @@ func checkSystem() error {
// Ensure that the required Host Network Service and vmcompute services
// are running. Docker will fail in unexpected ways if this is not present.
var requiredServices = []string{"hns", "vmcompute"}
requiredServices := []string{"hns", "vmcompute"}
if err := ensureServicesInstalled(requiredServices); err != nil {
return errors.Wrap(err, "a required service is not installed, ensure the Containers feature is installed")
}
@ -390,7 +390,6 @@ func (daemon *Daemon) initNetworkController(daemonCfg *config.Config, activeSand
}),
libnetwork.NetworkOptionIpam("default", "", v4Conf, v6Conf, nil),
)
if err != nil {
log.G(context.TODO()).Errorf("Error occurred when creating network %v", err)
}
@ -482,7 +481,6 @@ func (daemon *Daemon) runAsHyperVContainer(hostConfig *containertypes.HostConfig
// Container is requesting an isolation mode. Honour it.
return hostConfig.Isolation.IsHyperV()
}
// conditionalMountOnStart is a platform specific helper function during the

View file

@ -116,7 +116,7 @@ func (daemon *Daemon) cleanupContainer(container *container.Container, config ty
//
// If you arrived here and know the answer, you earned yourself a picture
// of a cute animal of your own choosing.
var stopTimeout = 3
stopTimeout := 3
if err := daemon.containerStop(context.TODO(), container, containertypes.StopOptions{Timeout: &stopTimeout}); err != nil {
return err
}

View file

@ -45,7 +45,8 @@ func TestContainerDelete(t *testing.T) {
fixMsg: "Unpause and then stop the container before attempting removal or force remove",
initContainer: func() *container.Container {
return newContainerWithState(&container.State{Paused: true, Running: true})
}},
},
},
// a restarting container
{
errMsg: "cannot remove a restarting container",
@ -55,14 +56,16 @@ func TestContainerDelete(t *testing.T) {
c.SetRunning(nil, nil, true)
c.SetRestarting(&container.ExitStatus{})
return c
}},
},
},
// a running container
{
errMsg: "cannot remove a running container",
fixMsg: "Stop the container before attempting removal or force remove",
initContainer: func() *container.Container {
return newContainerWithState(&container.State{Running: true})
}},
},
},
}
for _, te := range tt {

View file

@ -16,13 +16,11 @@ import (
swarmapi "github.com/moby/swarmkit/v2/api"
)
var (
clusterEventAction = map[swarmapi.WatchActionKind]string{
swarmapi.WatchActionKindCreate: "create",
swarmapi.WatchActionKindUpdate: "update",
swarmapi.WatchActionKindRemove: "remove",
}
)
var clusterEventAction = map[swarmapi.WatchActionKind]string{
swarmapi.WatchActionKindCreate: "create",
swarmapi.WatchActionKindUpdate: "update",
swarmapi.WatchActionKindRemove: "remove",
}
// LogContainerEvent generates an event related to a container with only the default attributes.
func (daemon *Daemon) LogContainerEvent(container *container.Container, action string) {

View file

@ -83,7 +83,7 @@ func Init(home string, options []string, idMap idtools.IdentityMapping) (graphdr
GID: idMap.RootPair().GID,
}
if err := idtools.MkdirAllAndChown(home, 0710, dirID); err != nil {
if err := idtools.MkdirAllAndChown(home, 0o710, dirID); err != nil {
return nil, err
}
@ -237,7 +237,7 @@ func subvolSnapshot(src, dest, name string) error {
var args C.struct_btrfs_ioctl_vol_args_v2
args.fd = C.__s64(getDirFd(srcDir))
var cs = C.CString(name)
cs := C.CString(name)
C.set_name_btrfs_ioctl_vol_args_v2(&args, cs)
free(cs)
@ -495,7 +495,7 @@ func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) error {
GID: root.GID,
}
if err := idtools.MkdirAllAndChown(subvolumes, 0710, dirID); err != nil {
if err := idtools.MkdirAllAndChown(subvolumes, 0o710, dirID); err != nil {
return err
}
if parent == "" {
@ -530,10 +530,10 @@ func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) error {
if err := d.setStorageSize(path.Join(subvolumes, id), driver); err != nil {
return err
}
if err := idtools.MkdirAllAndChown(quotas, 0700, idtools.CurrentIdentity()); err != nil {
if err := idtools.MkdirAllAndChown(quotas, 0o700, idtools.CurrentIdentity()); err != nil {
return err
}
if err := os.WriteFile(path.Join(quotas, id), []byte(fmt.Sprint(driver.options.size)), 0644); err != nil {
if err := os.WriteFile(path.Join(quotas, id), []byte(fmt.Sprint(driver.options.size)), 0o644); err != nil {
return err
}
}

View file

@ -94,7 +94,7 @@ func populateSrcDir(t *testing.T, srcDir string, remainingDepth int) {
for i := 0; i < 10; i++ {
dirName := filepath.Join(srcDir, fmt.Sprintf("srcdir-%d", i))
// Owner all bits set
assert.NilError(t, os.Mkdir(dirName, randomMode(0700)))
assert.NilError(t, os.Mkdir(dirName, randomMode(0o700)))
populateSrcDir(t, dirName, remainingDepth-1)
assert.NilError(t, system.Chtimes(dirName, aTime, mTime))
}
@ -102,7 +102,7 @@ func populateSrcDir(t *testing.T, srcDir string, remainingDepth int) {
for i := 0; i < 10; i++ {
fileName := filepath.Join(srcDir, fmt.Sprintf("srcfile-%d", i))
// Owner read bit set
assert.NilError(t, os.WriteFile(fileName, []byte{}, randomMode(0400)))
assert.NilError(t, os.WriteFile(fileName, []byte{}, randomMode(0o400)))
assert.NilError(t, system.Chtimes(fileName, aTime, mTime))
}
}
@ -118,7 +118,7 @@ func doCopyTest(t *testing.T, copyWithFileRange, copyWithFileClone *bool) {
buf := make([]byte, 1024)
_, err = r.Read(buf)
assert.NilError(t, err)
assert.NilError(t, os.WriteFile(srcFilename, buf, 0777))
assert.NilError(t, os.WriteFile(srcFilename, buf, 0o777))
fileinfo, err := os.Stat(srcFilename)
assert.NilError(t, err)
@ -143,7 +143,7 @@ func TestCopyHardlink(t *testing.T) {
srcFile2 := filepath.Join(srcDir, "file2")
dstFile1 := filepath.Join(dstDir, "file1")
dstFile2 := filepath.Join(dstDir, "file2")
assert.NilError(t, os.WriteFile(srcFile1, []byte{}, 0777))
assert.NilError(t, os.WriteFile(srcFile1, []byte{}, 0o777))
assert.NilError(t, os.Link(srcFile1, srcFile2))
assert.Check(t, DirCopy(srcDir, dstDir, Content, false))

View file

@ -24,10 +24,8 @@ const (
FsMagicUnsupported = FsMagic(0x00000000)
)
var (
// All registered drivers
drivers map[string]InitFunc
)
// All registered drivers
var drivers map[string]InitFunc
// CreateOpts contains optional arguments for Create() and CreateReadWrite()
// methods.

View file

@ -6,10 +6,8 @@ import (
"golang.org/x/sys/unix"
)
var (
// List of drivers that should be used in an order
priority = "zfs"
)
// List of drivers that should be used in an order
var priority = "zfs"
// Mounted checks if the given path is mounted as the fs type
func Mounted(fsType FsMagic, mountPath string) (bool, error) {

View file

@ -109,8 +109,7 @@ func NewDefaultChecker() Checker {
return &defaultChecker{}
}
type defaultChecker struct {
}
type defaultChecker struct{}
func (c *defaultChecker) IsMounted(path string) bool {
m, _ := mountinfo.Mounted(path)

View file

@ -14,19 +14,19 @@ func TestIsEmptyDir(t *testing.T) {
defer os.RemoveAll(tmp)
d := filepath.Join(tmp, "empty-dir")
err = os.Mkdir(d, 0755)
err = os.Mkdir(d, 0o755)
assert.NilError(t, err)
empty := isEmptyDir(d)
assert.Check(t, empty)
d = filepath.Join(tmp, "dir-with-subdir")
err = os.MkdirAll(filepath.Join(d, "subdir"), 0755)
err = os.MkdirAll(filepath.Join(d, "subdir"), 0o755)
assert.NilError(t, err)
empty = isEmptyDir(d)
assert.Check(t, !empty)
d = filepath.Join(tmp, "dir-with-empty-file")
err = os.Mkdir(d, 0755)
err = os.Mkdir(d, 0o755)
assert.NilError(t, err)
f, err := os.CreateTemp(d, "file")
assert.NilError(t, err)

View file

@ -2,10 +2,8 @@
package graphdriver // import "github.com/docker/docker/daemon/graphdriver"
var (
// List of drivers that should be used in an order
priority = "unsupported"
)
// List of drivers that should be used in an order
var priority = "unsupported"
// GetFSMagic returns the filesystem id given the path.
func GetFSMagic(rootpath string) (FsMagic, error) {

View file

@ -1,9 +1,7 @@
package graphdriver // import "github.com/docker/docker/daemon/graphdriver"
var (
// List of drivers that should be used in order
priority = "windowsfilter"
)
// List of drivers that should be used in order
var priority = "windowsfilter"
// GetFSMagic returns the filesystem id given the path.
func GetFSMagic(rootpath string) (FsMagic, error) {

View file

@ -12,11 +12,9 @@ import (
"github.com/docker/docker/pkg/ioutils"
)
var (
// ApplyUncompressedLayer defines the unpack method used by the graph
// driver.
ApplyUncompressedLayer = chrootarchive.ApplyUncompressedLayer
)
// ApplyUncompressedLayer defines the unpack method used by the graph
// driver.
var ApplyUncompressedLayer = chrootarchive.ApplyUncompressedLayer
// NaiveDiffDriver takes a ProtoDriver and adds the
// capability of the Diffing methods on the local file system,
@ -41,8 +39,10 @@ type NaiveDiffDriver struct {
// ApplyDiff(id, parent string, diff archive.Reader) (size int64, err error)
// DiffSize(id, parent string) (size int64, err error)
func NewNaiveDiffDriver(driver ProtoDriver, idMap idtools.IdentityMapping) Driver {
return &NaiveDiffDriver{ProtoDriver: driver,
IDMap: idMap}
return &NaiveDiffDriver{
ProtoDriver: driver,
IDMap: idMap,
}
}
// Diff produces an archive of the changes between the specified

View file

@ -30,10 +30,8 @@ import (
"golang.org/x/sys/unix"
)
var (
// untar defines the untar method
untar = chrootarchive.UntarUncompressed
)
// untar defines the untar method
var untar = chrootarchive.UntarUncompressed
const (
driverName = "fuse-overlayfs"
@ -65,9 +63,7 @@ type Driver struct {
locker *locker.Locker
}
var (
logger = log.G(context.TODO()).WithField("storage-driver", driverName)
)
var logger = log.G(context.TODO()).WithField("storage-driver", driverName)
func init() {
graphdriver.Register(driverName, Init)
@ -91,10 +87,10 @@ func Init(home string, options []string, idMap idtools.IdentityMapping) (graphdr
GID: idMap.RootPair().GID,
}
if err := idtools.MkdirAllAndChown(home, 0710, dirID); err != nil {
if err := idtools.MkdirAllAndChown(home, 0o710, dirID); err != nil {
return nil, err
}
if err := idtools.MkdirAllAndChown(path.Join(home, linkDir), 0700, currentID); err != nil {
if err := idtools.MkdirAllAndChown(path.Join(home, linkDir), 0o700, currentID); err != nil {
return nil, err
}
@ -173,10 +169,10 @@ func (d *Driver) create(id, parent string, opts *graphdriver.CreateOpts) (retErr
dir := d.dir(id)
root := d.idMap.RootPair()
if err := idtools.MkdirAllAndChown(path.Dir(dir), 0710, root); err != nil {
if err := idtools.MkdirAllAndChown(path.Dir(dir), 0o710, root); err != nil {
return err
}
if err := idtools.MkdirAndChown(dir, 0710, root); err != nil {
if err := idtools.MkdirAndChown(dir, 0o710, root); err != nil {
return err
}
@ -191,7 +187,7 @@ func (d *Driver) create(id, parent string, opts *graphdriver.CreateOpts) (retErr
return fmt.Errorf("--storage-opt is not supported")
}
if err := idtools.MkdirAndChown(path.Join(dir, diffDirName), 0755, root); err != nil {
if err := idtools.MkdirAndChown(path.Join(dir, diffDirName), 0o755, root); err != nil {
return err
}
@ -201,7 +197,7 @@ func (d *Driver) create(id, parent string, opts *graphdriver.CreateOpts) (retErr
}
// Write link id to link file
if err := os.WriteFile(path.Join(dir, "link"), []byte(lid), 0644); err != nil {
if err := os.WriteFile(path.Join(dir, "link"), []byte(lid), 0o644); err != nil {
return err
}
@ -210,11 +206,11 @@ func (d *Driver) create(id, parent string, opts *graphdriver.CreateOpts) (retErr
return nil
}
if err := idtools.MkdirAndChown(path.Join(dir, workDirName), 0710, root); err != nil {
if err := idtools.MkdirAndChown(path.Join(dir, workDirName), 0o710, root); err != nil {
return err
}
if err := os.WriteFile(path.Join(d.dir(parent), "committed"), []byte{}, 0600); err != nil {
if err := os.WriteFile(path.Join(d.dir(parent), "committed"), []byte{}, 0o600); err != nil {
return err
}
@ -223,7 +219,7 @@ func (d *Driver) create(id, parent string, opts *graphdriver.CreateOpts) (retErr
return err
}
if lower != "" {
if err := os.WriteFile(path.Join(dir, lowerFile), []byte(lower), 0666); err != nil {
if err := os.WriteFile(path.Join(dir, lowerFile), []byte(lower), 0o666); err != nil {
return err
}
}
@ -363,7 +359,7 @@ func (d *Driver) Get(id, mountLabel string) (_ string, retErr error) {
mountData := label.FormatMountLabel(opts, mountLabel)
mountTarget := mergedDir
if err := idtools.MkdirAndChown(mergedDir, 0700, d.idMap.RootPair()); err != nil {
if err := idtools.MkdirAndChown(mergedDir, 0o700, d.idMap.RootPair()); err != nil {
return "", err
}

View file

@ -18,9 +18,7 @@ import (
is "gotest.tools/v3/assert/cmp"
)
var (
drv *Driver
)
var drv *Driver
// Driver conforms to graphdriver.Driver interface and
// contains information such as root and reference count of the number of clients using it.
@ -35,7 +33,7 @@ func newDriver(t testing.TB, name string, options []string) *Driver {
root, err := os.MkdirTemp("", "docker-graphtest-")
assert.NilError(t, err)
assert.NilError(t, os.MkdirAll(root, 0755))
assert.NilError(t, os.MkdirAll(root, 0o755))
d, err := graphdriver.GetDriver(name, nil, graphdriver.Options{DriverOptions: options, Root: root})
if err != nil {
t.Logf("graphdriver: %v\n", err)
@ -95,7 +93,7 @@ func DriverTestCreateEmpty(t testing.TB, drivername string, driverOptions ...str
dir, err := driver.Get("empty", "")
assert.NilError(t, err)
verifyFile(t, dir, 0755|os.ModeDir, 0, 0)
verifyFile(t, dir, 0o755|os.ModeDir, 0, 0)
// Verify that the directory is empty
fis, err := readDir(dir)
@ -296,7 +294,7 @@ func writeRandomFile(path string, size uint64) error {
if err != nil {
return err
}
return os.WriteFile(path, data, 0700)
return os.WriteFile(path, data, 0o700)
}
// DriverTestSetQuota Create a driver and test setting quota.

View file

@ -36,17 +36,17 @@ func addFiles(drv graphdriver.Driver, layer string, seed int64) error {
}
defer drv.Put(layer)
if err := os.WriteFile(filepath.Join(root, "file-a"), randomContent(64, seed), 0755); err != nil {
if err := os.WriteFile(filepath.Join(root, "file-a"), randomContent(64, seed), 0o755); err != nil {
return err
}
if err := os.MkdirAll(filepath.Join(root, "dir-b"), 0755); err != nil {
if err := os.MkdirAll(filepath.Join(root, "dir-b"), 0o755); err != nil {
return err
}
if err := os.WriteFile(filepath.Join(root, "dir-b", "file-b"), randomContent(128, seed+1), 0755); err != nil {
if err := os.WriteFile(filepath.Join(root, "dir-b", "file-b"), randomContent(128, seed+1), 0o755); err != nil {
return err
}
return os.WriteFile(filepath.Join(root, "file-c"), randomContent(128*128, seed+2), 0755)
return os.WriteFile(filepath.Join(root, "file-c"), randomContent(128*128, seed+2), 0o755)
}
func checkFile(drv graphdriver.Driver, layer, filename string, content []byte) error {
@ -75,7 +75,7 @@ func addFile(drv graphdriver.Driver, layer, filename string, content []byte) err
}
defer drv.Put(layer)
return os.WriteFile(filepath.Join(root, filename), content, 0755)
return os.WriteFile(filepath.Join(root, filename), content, 0o755)
}
func addDirectory(drv graphdriver.Driver, layer, dir string) error {
@ -85,7 +85,7 @@ func addDirectory(drv graphdriver.Driver, layer, dir string) error {
}
defer drv.Put(layer)
return os.MkdirAll(filepath.Join(root, dir), 0755)
return os.MkdirAll(filepath.Join(root, dir), 0o755)
}
func removeAll(drv graphdriver.Driver, layer string, names ...string) error {
@ -128,12 +128,12 @@ func addManyFiles(drv graphdriver.Driver, layer string, count int, seed int64) e
for i := 0; i < count; i += 100 {
dir := filepath.Join(root, fmt.Sprintf("directory-%d", i))
if err := os.MkdirAll(dir, 0755); err != nil {
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
for j := 0; i+j < count && j < 100; j++ {
file := filepath.Join(dir, fmt.Sprintf("file-%d", i+j))
if err := os.WriteFile(file, randomContent(64, seed+int64(i+j)), 0755); err != nil {
if err := os.WriteFile(file, randomContent(64, seed+int64(i+j)), 0o755); err != nil {
return err
}
}
@ -152,7 +152,7 @@ func changeManyFiles(drv graphdriver.Driver, layer string, count int, seed int64
var changes []archive.Change
for i := 0; i < count; i += 100 {
archiveRoot := fmt.Sprintf("/directory-%d", i)
if err := os.MkdirAll(filepath.Join(root, archiveRoot), 0755); err != nil {
if err := os.MkdirAll(filepath.Join(root, archiveRoot), 0o755); err != nil {
return nil, err
}
for j := 0; i+j < count && j < 100; j++ {
@ -168,14 +168,14 @@ func changeManyFiles(drv graphdriver.Driver, layer string, count int, seed int64
case 0:
change.Path = filepath.Join(archiveRoot, fmt.Sprintf("file-%d", i+j))
change.Kind = archive.ChangeModify
if err := os.WriteFile(filepath.Join(root, change.Path), randomContent(64, seed+int64(i+j)), 0755); err != nil {
if err := os.WriteFile(filepath.Join(root, change.Path), randomContent(64, seed+int64(i+j)), 0o755); err != nil {
return nil, err
}
// Add file
case 1:
change.Path = filepath.Join(archiveRoot, fmt.Sprintf("file-%d-%d", seed, i+j))
change.Kind = archive.ChangeAdd
if err := os.WriteFile(filepath.Join(root, change.Path), randomContent(64, seed+int64(i+j)), 0755); err != nil {
if err := os.WriteFile(filepath.Join(root, change.Path), randomContent(64, seed+int64(i+j)), 0o755); err != nil {
return nil, err
}
// Remove file
@ -254,17 +254,17 @@ func addLayerFiles(drv graphdriver.Driver, layer, parent string, i int) error {
}
defer drv.Put(layer)
if err := os.WriteFile(filepath.Join(root, "top-id"), []byte(layer), 0755); err != nil {
if err := os.WriteFile(filepath.Join(root, "top-id"), []byte(layer), 0o755); err != nil {
return err
}
layerDir := filepath.Join(root, fmt.Sprintf("layer-%d", i))
if err := os.MkdirAll(layerDir, 0755); err != nil {
if err := os.MkdirAll(layerDir, 0o755); err != nil {
return err
}
if err := os.WriteFile(filepath.Join(layerDir, "layer-id"), []byte(layer), 0755); err != nil {
if err := os.WriteFile(filepath.Join(layerDir, "layer-id"), []byte(layer), 0o755); err != nil {
return err
}
return os.WriteFile(filepath.Join(layerDir, "parent-id"), []byte(parent), 0755)
return os.WriteFile(filepath.Join(layerDir, "parent-id"), []byte(parent), 0o755)
}
func addManyLayers(drv graphdriver.Driver, baseLayer string, count int) (string, error) {

View file

@ -45,11 +45,11 @@ func createBase(t testing.TB, driver graphdriver.Driver, name string) {
defer driver.Put(name)
subdir := filepath.Join(dirFS, "a subdir")
assert.NilError(t, os.Mkdir(subdir, 0705|os.ModeSticky))
assert.NilError(t, os.Mkdir(subdir, 0o705|os.ModeSticky))
assert.NilError(t, contdriver.LocalDriver.Lchown(subdir, 1, 2))
file := filepath.Join(dirFS, "a file")
err = os.WriteFile(file, []byte("Some data"), 0222|os.ModeSetuid)
err = os.WriteFile(file, []byte("Some data"), 0o222|os.ModeSetuid)
assert.NilError(t, err)
}
@ -59,10 +59,10 @@ func verifyBase(t testing.TB, driver graphdriver.Driver, name string) {
defer driver.Put(name)
subdir := filepath.Join(dirFS, "a subdir")
verifyFile(t, subdir, 0705|os.ModeDir|os.ModeSticky, 1, 2)
verifyFile(t, subdir, 0o705|os.ModeDir|os.ModeSticky, 1, 2)
file := filepath.Join(dirFS, "a file")
verifyFile(t, file, 0222|os.ModeSetuid, 0, 0)
verifyFile(t, file, 0o222|os.ModeSetuid, 0, 0)
files, err := readDir(dirFS)
assert.NilError(t, err)

View file

@ -40,22 +40,22 @@ func doesSupportNativeDiff(d string) error {
}()
// Make directories l1/d, l1/d1, l2/d, l3, work, merged
if err := os.MkdirAll(filepath.Join(td, "l1", "d"), 0755); err != nil {
if err := os.MkdirAll(filepath.Join(td, "l1", "d"), 0o755); err != nil {
return err
}
if err := os.MkdirAll(filepath.Join(td, "l1", "d1"), 0755); err != nil {
if err := os.MkdirAll(filepath.Join(td, "l1", "d1"), 0o755); err != nil {
return err
}
if err := os.MkdirAll(filepath.Join(td, "l2", "d"), 0755); err != nil {
if err := os.MkdirAll(filepath.Join(td, "l2", "d"), 0o755); err != nil {
return err
}
if err := os.Mkdir(filepath.Join(td, "l3"), 0755); err != nil {
if err := os.Mkdir(filepath.Join(td, "l3"), 0o755); err != nil {
return err
}
if err := os.Mkdir(filepath.Join(td, workDirName), 0755); err != nil {
if err := os.Mkdir(filepath.Join(td, workDirName), 0o755); err != nil {
return err
}
if err := os.Mkdir(filepath.Join(td, mergedDirName), 0755); err != nil {
if err := os.Mkdir(filepath.Join(td, mergedDirName), 0o755); err != nil {
return err
}
@ -75,7 +75,7 @@ func doesSupportNativeDiff(d string) error {
}()
// Touch file in d to force copy up of opaque directory "d" from "l2" to "l3"
if err := os.WriteFile(filepath.Join(td, mergedDirName, "d", "f"), []byte{}, 0644); err != nil {
if err := os.WriteFile(filepath.Join(td, mergedDirName, "d", "f"), []byte{}, 0o644); err != nil {
return errors.Wrap(err, "failed to write to merged directory")
}
@ -149,13 +149,13 @@ func usingMetacopy(d string) (bool, error) {
l1, l2, work, merged := filepath.Join(td, "l1"), filepath.Join(td, "l2"), filepath.Join(td, "work"), filepath.Join(td, "merged")
for _, dir := range []string{l1, l2, work, merged} {
if err := os.Mkdir(dir, 0755); err != nil {
if err := os.Mkdir(dir, 0o755); err != nil {
return false, err
}
}
// Create empty file in l1 with 0700 permissions for metacopy test
if err := os.WriteFile(filepath.Join(l1, "f"), []byte{}, 0700); err != nil {
if err := os.WriteFile(filepath.Join(l1, "f"), []byte{}, 0o700); err != nil {
return false, err
}
@ -180,7 +180,7 @@ func usingMetacopy(d string) (bool, error) {
}()
// Make a change that only impacts the inode, in the upperdir
if err := os.Chmod(filepath.Join(merged, "f"), 0600); err != nil {
if err := os.Chmod(filepath.Join(merged, "f"), 0o600); err != nil {
return false, errors.Wrap(err, "error changing permissions on file for metacopy check")
}

View file

@ -32,10 +32,8 @@ import (
"golang.org/x/sys/unix"
)
var (
// untar defines the untar method
untar = chrootarchive.UntarUncompressed
)
// untar defines the untar method
var untar = chrootarchive.UntarUncompressed
// This backend uses the overlay union filesystem for containers
// with diff directories for each layer.
@ -168,10 +166,10 @@ func Init(home string, options []string, idMap idtools.IdentityMapping) (graphdr
UID: cur.UID,
GID: idMap.RootPair().GID,
}
if err := idtools.MkdirAllAndChown(home, 0710, dirID); err != nil {
if err := idtools.MkdirAllAndChown(home, 0o710, dirID); err != nil {
return nil, err
}
if err := idtools.MkdirAllAndChown(path.Join(home, linkDir), 0700, cur); err != nil {
if err := idtools.MkdirAllAndChown(path.Join(home, linkDir), 0o700, cur); err != nil {
return nil, err
}
@ -347,10 +345,10 @@ func (d *Driver) create(id, parent string, opts *graphdriver.CreateOpts) (retErr
GID: root.GID,
}
if err := idtools.MkdirAllAndChown(path.Dir(dir), 0710, dirID); err != nil {
if err := idtools.MkdirAllAndChown(path.Dir(dir), 0o710, dirID); err != nil {
return err
}
if err := idtools.MkdirAndChown(dir, 0710, dirID); err != nil {
if err := idtools.MkdirAndChown(dir, 0o710, dirID); err != nil {
return err
}
@ -375,7 +373,7 @@ func (d *Driver) create(id, parent string, opts *graphdriver.CreateOpts) (retErr
}
}
if err := idtools.MkdirAndChown(path.Join(dir, diffDirName), 0755, root); err != nil {
if err := idtools.MkdirAndChown(path.Join(dir, diffDirName), 0o755, root); err != nil {
return err
}
@ -385,7 +383,7 @@ func (d *Driver) create(id, parent string, opts *graphdriver.CreateOpts) (retErr
}
// Write link id to link file
if err := os.WriteFile(path.Join(dir, "link"), []byte(lid), 0644); err != nil {
if err := os.WriteFile(path.Join(dir, "link"), []byte(lid), 0o644); err != nil {
return err
}
@ -394,11 +392,11 @@ func (d *Driver) create(id, parent string, opts *graphdriver.CreateOpts) (retErr
return nil
}
if err := idtools.MkdirAndChown(path.Join(dir, workDirName), 0700, root); err != nil {
if err := idtools.MkdirAndChown(path.Join(dir, workDirName), 0o700, root); err != nil {
return err
}
if err := os.WriteFile(path.Join(d.dir(parent), "committed"), []byte{}, 0600); err != nil {
if err := os.WriteFile(path.Join(d.dir(parent), "committed"), []byte{}, 0o600); err != nil {
return err
}
@ -407,7 +405,7 @@ func (d *Driver) create(id, parent string, opts *graphdriver.CreateOpts) (retErr
return err
}
if lower != "" {
if err := os.WriteFile(path.Join(dir, lowerFile), []byte(lower), 0666); err != nil {
if err := os.WriteFile(path.Join(dir, lowerFile), []byte(lower), 0o666); err != nil {
return err
}
}
@ -567,7 +565,7 @@ func (d *Driver) Get(id, mountLabel string) (_ string, retErr error) {
mountTarget := mergedDir
root := d.idMap.RootPair()
if err := idtools.MkdirAndChown(mergedDir, 0700, root); err != nil {
if err := idtools.MkdirAndChown(mergedDir, 0o700, root); err != nil {
return "", err
}

View file

@ -60,7 +60,7 @@ func SupportsOverlay(d string, checkMultipleLowers bool) error {
}()
for _, dir := range []string{"lower1", "lower2", "upper", "work", "merged"} {
if err := os.Mkdir(filepath.Join(td, dir), 0755); err != nil {
if err := os.Mkdir(filepath.Join(td, dir), 0o755); err != nil {
return err
}
}

View file

@ -71,7 +71,7 @@ func NeedsUserXAttr(d string) (bool, error) {
log.G(context.TODO()).WithError(err).Warnf("Failed to remove check directory %v", tdRoot)
}
if err := os.MkdirAll(tdRoot, 0700); err != nil {
if err := os.MkdirAll(tdRoot, 0o700); err != nil {
return false, err
}
@ -87,7 +87,7 @@ func NeedsUserXAttr(d string) (bool, error) {
}
for _, dir := range []string{"lower1", "lower2", "upper", "work", "merged"} {
if err := os.Mkdir(filepath.Join(td, dir), 0755); err != nil {
if err := os.Mkdir(filepath.Join(td, dir), 0o755); err != nil {
return false, err
}
}

View file

@ -21,10 +21,8 @@ const (
bestEffortXattrsOptValue = "i_want_broken_containers"
)
var (
// CopyDir defines the copy method to use.
CopyDir = dirCopy
)
// CopyDir defines the copy method to use.
var CopyDir = dirCopy
func init() {
graphdriver.Register("vfs", Init)
@ -46,7 +44,7 @@ func Init(home string, options []string, idMap idtools.IdentityMapping) (graphdr
UID: idtools.CurrentIdentity().UID,
GID: d.idMapping.RootPair().GID,
}
if err := idtools.MkdirAllAndChown(home, 0710, dirID); err != nil {
if err := idtools.MkdirAllAndChown(home, 0o710, dirID); err != nil {
return nil, err
}
@ -170,10 +168,10 @@ func (d *Driver) create(id, parent string, size uint64) error {
UID: idtools.CurrentIdentity().UID,
GID: rootIDs.GID,
}
if err := idtools.MkdirAllAndChown(filepath.Dir(dir), 0710, dirID); err != nil {
if err := idtools.MkdirAllAndChown(filepath.Dir(dir), 0o710, dirID); err != nil {
return err
}
if err := idtools.MkdirAndChown(dir, 0755, rootIDs); err != nil {
if err := idtools.MkdirAndChown(dir, 0o755, rootIDs); err != nil {
return err
}

View file

@ -4,8 +4,7 @@ package vfs // import "github.com/docker/docker/daemon/graphdriver/vfs"
import "github.com/docker/docker/quota"
type driverQuota struct {
}
type driverQuota struct{}
func setupDriverQuota(driver *Driver) error {
return nil

View file

@ -73,8 +73,7 @@ func init() {
}
}
type checker struct {
}
type checker struct{}
func (c *checker) IsMounted(path string) bool {
return false
@ -846,7 +845,7 @@ func (d *Driver) resolveID(id string) (string, error) {
// setID stores the layerId in disk.
func (d *Driver) setID(id, altID string) error {
return os.WriteFile(filepath.Join(d.dir(id), "layerId"), []byte(altID), 0600)
return os.WriteFile(filepath.Join(d.dir(id), "layerId"), []byte(altID), 0o600)
}
// getLayerChain returns the layer chain information.

View file

@ -56,7 +56,7 @@ func Init(base string, opt []string, idMap idtools.IdentityMapping) (graphdriver
return nil, graphdriver.ErrPrerequisites
}
file, err := os.OpenFile("/dev/zfs", os.O_RDWR, 0600)
file, err := os.OpenFile("/dev/zfs", os.O_RDWR, 0o600)
if err != nil {
logger.Debugf("cannot open /dev/zfs: %v", err)
return nil, graphdriver.ErrPrerequisites
@ -109,7 +109,7 @@ func Init(base string, opt []string, idMap idtools.IdentityMapping) (graphdriver
UID: idtools.CurrentIdentity().UID,
GID: idMap.RootPair().GID,
}
if err := idtools.MkdirAllAndChown(base, 0710, dirID); err != nil {
if err := idtools.MkdirAllAndChown(base, 0o710, dirID); err != nil {
return nil, fmt.Errorf("Failed to create '%s': %v", base, err)
}
@ -388,7 +388,7 @@ func (d *Driver) Get(id, mountLabel string) (_ string, retErr error) {
root := d.idMap.RootPair()
// Create the target directories if they don't exist
if err := idtools.MkdirAllAndChown(mountpoint, 0755, root); err != nil {
if err := idtools.MkdirAllAndChown(mountpoint, 0o755, root); err != nil {
return "", err
}

View file

@ -3,8 +3,8 @@ package zfs // import "github.com/docker/docker/daemon/graphdriver/zfs"
import (
"strings"
"github.com/docker/docker/daemon/graphdriver"
"github.com/containerd/containerd/log"
"github.com/docker/docker/daemon/graphdriver"
"golang.org/x/sys/unix"
)

View file

@ -20,7 +20,7 @@ func loadOrCreateID(idPath string) (string, error) {
idb, err := os.ReadFile(idPath)
if os.IsNotExist(err) {
id = uuid.New().String()
if err := ioutils.AtomicWriteFile(idPath, []byte(id), os.FileMode(0600)); err != nil {
if err := ioutils.AtomicWriteFile(idPath, []byte(id), os.FileMode(0o600)); err != nil {
return "", errors.Wrap(err, "error saving ID file")
}
} else if err != nil {

View file

@ -43,9 +43,7 @@ func (i *ImageService) Images(ctx context.Context, opts types.ImageListOptions)
return nil, err
}
var (
beforeFilter, sinceFilter time.Time
)
var beforeFilter, sinceFilter time.Time
err = opts.Filters.WalkValues("before", func(value string) error {
img, err := i.GetImage(ctx, value, imagetypes.GetImageOpts{})
if err != nil {

View file

@ -29,7 +29,7 @@ func setupTestStores(t *testing.T) (context.Context, content.Store, *imageStoreW
is, err := image.NewImageStore(backend, nil)
assert.NilError(t, err)
db, err := bbolt.Open(filepath.Join(dir, "metadata.db"), 0600, nil)
db, err := bbolt.Open(filepath.Join(dir, "metadata.db"), 0o600, nil)
assert.NilError(t, err)
cs, err := local.NewStore(filepath.Join(dir, "content"))

View file

@ -42,16 +42,16 @@ func Setup(initLayerFs string, rootIdentity idtools.Identity) error {
if _, err := os.Stat(filepath.Join(initLayer, pth)); err != nil {
if os.IsNotExist(err) {
if err := idtools.MkdirAllAndChownNew(filepath.Join(initLayer, filepath.Dir(pth)), 0755, rootIdentity); err != nil {
if err := idtools.MkdirAllAndChownNew(filepath.Join(initLayer, filepath.Dir(pth)), 0o755, rootIdentity); err != nil {
return err
}
switch typ {
case "dir":
if err := idtools.MkdirAllAndChownNew(filepath.Join(initLayer, pth), 0755, rootIdentity); err != nil {
if err := idtools.MkdirAllAndChownNew(filepath.Join(initLayer, pth), 0o755, rootIdentity); err != nil {
return err
}
case "file":
f, err := os.OpenFile(filepath.Join(initLayer, pth), os.O_CREATE, 0755)
f, err := os.OpenFile(filepath.Join(initLayer, pth), os.O_CREATE, 0o755)
if err != nil {
return err
}

Some files were not shown because too many files have changed in this diff Show more