vendor: update moby/buildkit

Update modules:

  go mod edit -require github.com/moby/buildkit@master
  go mod tidy -compat=1.17 && ./hack/update-vendor

Signed-off-by: Justin Chadwell <me@jedevc.com>
This commit is contained in:
Justin Chadwell
2022-05-17 16:11:41 +01:00
parent 66a764f9c1
commit 22ac3271d2
113 changed files with 2667 additions and 662 deletions

View File

@ -1,3 +1,4 @@
//go:build windows
// +build windows
package winio
@ -143,6 +144,11 @@ func (f *win32File) Close() error {
return nil
}
// IsClosed checks if the file has been closed
func (f *win32File) IsClosed() bool {
return f.closing.isSet()
}
// prepareIo prepares for a new IO operation.
// The caller must call f.wg.Done() when the IO is finished, prior to Close() returning.
func (f *win32File) prepareIo() (*ioOperation, error) {

View File

@ -1,3 +1,4 @@
//go:build windows
// +build windows
package winio
@ -252,15 +253,23 @@ func (conn *HvsockConn) Close() error {
return conn.sock.Close()
}
func (conn *HvsockConn) IsClosed() bool {
return conn.sock.IsClosed()
}
func (conn *HvsockConn) shutdown(how int) error {
err := syscall.Shutdown(conn.sock.handle, syscall.SHUT_RD)
if conn.IsClosed() {
return ErrFileClosed
}
err := syscall.Shutdown(conn.sock.handle, how)
if err != nil {
return os.NewSyscallError("shutdown", err)
}
return nil
}
// CloseRead shuts down the read end of the socket.
// CloseRead shuts down the read end of the socket, preventing future read operations.
func (conn *HvsockConn) CloseRead() error {
err := conn.shutdown(syscall.SHUT_RD)
if err != nil {
@ -269,8 +278,8 @@ func (conn *HvsockConn) CloseRead() error {
return nil
}
// CloseWrite shuts down the write end of the socket, notifying the other endpoint that
// no more data will be written.
// CloseWrite shuts down the write end of the socket, preventing future write operations and
// notifying the other endpoint that no more data will be written.
func (conn *HvsockConn) CloseWrite() error {
err := conn.shutdown(syscall.SHUT_WR)
if err != nil {

View File

@ -14,8 +14,6 @@ import (
"encoding/binary"
"fmt"
"strconv"
"golang.org/x/sys/windows"
)
// Variant specifies which GUID variant (or "type") of the GUID. It determines
@ -41,13 +39,6 @@ type Version uint8
var _ = (encoding.TextMarshaler)(GUID{})
var _ = (encoding.TextUnmarshaler)(&GUID{})
// GUID represents a GUID/UUID. It has the same structure as
// golang.org/x/sys/windows.GUID so that it can be used with functions expecting
// that type. It is defined as its own type so that stringification and
// marshaling can be supported. The representation matches that used by native
// Windows code.
type GUID windows.GUID
// NewV4 returns a new version 4 (pseudorandom) GUID, as defined by RFC 4122.
func NewV4() (GUID, error) {
var b [16]byte

View File

@ -0,0 +1,15 @@
// +build !windows
package guid
// GUID represents a GUID/UUID. It has the same structure as
// golang.org/x/sys/windows.GUID so that it can be used with functions expecting
// that type. It is defined as its own type as that is only available to builds
// targeted at `windows`. The representation matches that used by native Windows
// code.
type GUID struct {
Data1 uint32
Data2 uint16
Data3 uint16
Data4 [8]byte
}

View File

@ -0,0 +1,10 @@
package guid
import "golang.org/x/sys/windows"
// GUID represents a GUID/UUID. It has the same structure as
// golang.org/x/sys/windows.GUID so that it can be used with functions expecting
// that type. It is defined as its own type so that stringification and
// marshaling can be supported. The representation matches that used by native
// Windows code.
type GUID windows.GUID

View File

@ -23,7 +23,7 @@ var (
Package = "github.com/containerd/containerd"
// Version holds the complete version number. Filled in at linking time.
Version = "1.6.2+unknown"
Version = "1.6.4+unknown"
// Revision is filled with the VCS (e.g. git) revision being used to build
// the program at linking time.

View File

@ -1,8 +1,6 @@
Aaron Lehmann <aaron.lehmann@docker.com>
Aaron Lehmann <alehmann@netflix.com>
Akash Gupta <akagup@microsoft.com>
Akihiro Suda <akihiro.suda.cz@hco.ntt.co.jp>
Akihiro Suda <suda.akihiro@lab.ntt.co.jp>
Akihiro Suda <suda.kyoto@gmail.com>
Andrew Pennebaker <apennebaker@datapipe.com>
Brandon Philips <brandon.philips@coreos.com>
Brian Goff <cpuguy83@gmail.com>
@ -10,9 +8,9 @@ Christopher Jones <tophj@linux.vnet.ibm.com>
Daniel, Dao Quang Minh <dqminh89@gmail.com>
Darren Stahl <darst@microsoft.com>
Derek McGowan <derek@mcg.dev>
Derek McGowan <derek@mcgstyle.net>
Edward Pilatowicz <edward.pilatowicz@oracle.com>
Fu Wei <fuweid89@gmail.com>
Gabriel Adrian Samfira <gsamfira@cloudbasesolutions.com>
Hajime Tazaki <thehajime@gmail.com>
Ian Campbell <ijc@docker.com>
Ivan Markin <sw@nogoegst.net>
@ -20,20 +18,18 @@ Jacob Blain Christen <jacob@rancher.com>
Justin Cormack <justin.cormack@docker.com>
Justin Cummins <sul3n3t@gmail.com>
Kasper Fabæch Brandt <poizan@poizan.dk>
Kazuyoshi Kato <katokazu@amazon.com>
Kir Kolyshkin <kolyshkin@gmail.com>
Michael Crosby <crosbymichael@gmail.com>
Michael Crosby <michael@thepasture.io>
Michael Wan <zirenwan@gmail.com>
Mike Brown <brownwm@us.ibm.com>
Niels de Vos <ndevos@redhat.com>
Phil Estes <estesp@amazon.com>
Phil Estes <estesp@gmail.com>
Phil Estes <estesp@linux.vnet.ibm.com>
Sam Whited <sam@samwhited.com>
Samuel Karp <me@samuelkarp.com>
Sebastiaan van Stijn <github@gone.nl>
Shengjing Zhu <zhsj@debian.org>
Stephen J Day <stephen.day@docker.com>
Stephen J Day <stevvooe@gmail.com>
Tibor Vass <tibor@docker.com>
Tobias Klauser <tklauser@distanz.ch>
Tom Faulhaber <tffaulha@amazon.com>

View File

@ -1,52 +0,0 @@
#!/bin/bash
# Copyright The containerd Authors.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
set -e
mksyscall="$(go env GOROOT)/src/syscall/mksyscall.pl"
fix() {
sed 's,^package syscall$,package sysx,' \
| sed 's,^import "unsafe"$,import (\n\t"syscall"\n\t"unsafe"\n),' \
| gofmt -r='BytePtrFromString -> syscall.BytePtrFromString' \
| gofmt -r='Syscall6 -> syscall.Syscall6' \
| gofmt -r='Syscall -> syscall.Syscall' \
| gofmt -r='SYS_GETXATTR -> syscall.SYS_GETXATTR' \
| gofmt -r='SYS_LISTXATTR -> syscall.SYS_LISTXATTR' \
| gofmt -r='SYS_SETXATTR -> syscall.SYS_SETXATTR' \
| gofmt -r='SYS_REMOVEXATTR -> syscall.SYS_REMOVEXATTR' \
| gofmt -r='SYS_LGETXATTR -> syscall.SYS_LGETXATTR' \
| gofmt -r='SYS_LLISTXATTR -> syscall.SYS_LLISTXATTR' \
| gofmt -r='SYS_LSETXATTR -> syscall.SYS_LSETXATTR' \
| gofmt -r='SYS_LREMOVEXATTR -> syscall.SYS_LREMOVEXATTR'
}
if [ "$GOARCH" == "" ] || [ "$GOOS" == "" ]; then
echo "Must specify \$GOARCH and \$GOOS"
exit 1
fi
mkargs=""
if [ "$GOARCH" == "386" ] || [ "$GOARCH" == "arm" ]; then
mkargs="-l32"
fi
for f in "$@"; do
$mksyscall $mkargs "${f}_${GOOS}.go" | fix > "${f}_${GOOS}_${GOARCH}.go"
done

View File

@ -0,0 +1,56 @@
// Package dockercontainer provides connhelper for docker-container://<container>
package dockercontainer
import (
"context"
"net"
"net/url"
"github.com/docker/cli/cli/connhelper/commandconn"
"github.com/moby/buildkit/client/connhelper"
"github.com/pkg/errors"
)
func init() {
connhelper.Register("docker-container", Helper)
}
// Helper returns helper for connecting to a Docker container.
// Requires BuildKit v0.5.0 or later in the container.
func Helper(u *url.URL) (*connhelper.ConnectionHelper, error) {
sp, err := SpecFromURL(u)
if err != nil {
return nil, err
}
return &connhelper.ConnectionHelper{
ContextDialer: func(ctx context.Context, addr string) (net.Conn, error) {
ctxFlags := []string{}
if sp.Context != "" {
ctxFlags = append(ctxFlags, "--context="+sp.Context)
}
// using background context because context remains active for the duration of the process, after dial has completed
return commandconn.New(context.Background(), "docker", append(ctxFlags, []string{"exec", "-i", sp.Container, "buildctl", "dial-stdio"}...)...)
},
}, nil
}
// Spec
type Spec struct {
Context string
Container string
}
// SpecFromURL creates Spec from URL.
// URL is like docker-container://<container>?context=<context>
// Only <container> part is mandatory.
func SpecFromURL(u *url.URL) (*Spec, error) {
q := u.Query()
sp := Spec{
Context: q.Get("context"),
Container: u.Hostname(),
}
if sp.Container == "" {
return nil, errors.New("url lacks container name")
}
return &sp, nil
}

View File

@ -0,0 +1,78 @@
// Package kubepod provides connhelper for kube-pod://<pod>
package kubepod
import (
"context"
"net"
"net/url"
"regexp"
"github.com/docker/cli/cli/connhelper/commandconn"
"github.com/moby/buildkit/client/connhelper"
"github.com/pkg/errors"
)
func init() {
connhelper.Register("kube-pod", Helper)
}
// Helper returns helper for connecting to a Kubernetes pod.
// Requires BuildKit v0.5.0 or later in the pod.
func Helper(u *url.URL) (*connhelper.ConnectionHelper, error) {
sp, err := SpecFromURL(u)
if err != nil {
return nil, err
}
return &connhelper.ConnectionHelper{
ContextDialer: func(ctx context.Context, addr string) (net.Conn, error) {
// using background context because context remains active for the duration of the process, after dial has completed
return commandconn.New(context.Background(), "kubectl", "--context="+sp.Context, "--namespace="+sp.Namespace,
"exec", "--container="+sp.Container, "-i", sp.Pod, "--", "buildctl", "dial-stdio")
},
}, nil
}
// Spec
type Spec struct {
Context string
Namespace string
Pod string
Container string
}
// SpecFromURL creates Spec from URL.
// URL is like kube-pod://<pod>?context=<context>&namespace=<namespace>&container=<container> .
// Only <pod> part is mandatory.
func SpecFromURL(u *url.URL) (*Spec, error) {
q := u.Query()
sp := Spec{
Context: q.Get("context"),
Namespace: q.Get("namespace"),
Pod: u.Hostname(),
Container: q.Get("container"),
}
if sp.Context != "" && !validKubeIdentifier(sp.Context) {
return nil, errors.Errorf("unsupported context name: %q", sp.Context)
}
if sp.Namespace != "" && !validKubeIdentifier(sp.Namespace) {
return nil, errors.Errorf("unsupported namespace name: %q", sp.Namespace)
}
if sp.Pod == "" {
return nil, errors.New("url lacks pod name")
}
if !validKubeIdentifier(sp.Pod) {
return nil, errors.Errorf("unsupported pod name: %q", sp.Pod)
}
if sp.Container != "" && !validKubeIdentifier(sp.Container) {
return nil, errors.Errorf("unsupported container name: %q", sp.Container)
}
return &sp, nil
}
var kubeIdentifierRegexp = regexp.MustCompile(`^[-a-z0-9.]+$`)
// validKubeIdentifier: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names
// The length is not checked because future version of Kube may support longer identifiers.
func validKubeIdentifier(s string) bool {
return kubeIdentifierRegexp.MatchString(s)
}

View File

@ -0,0 +1,78 @@
// Package ssh provides connhelper for ssh://<SSH URL>
package ssh
import (
"context"
"net"
"net/url"
"github.com/docker/cli/cli/connhelper/commandconn"
"github.com/moby/buildkit/client/connhelper"
"github.com/pkg/errors"
)
func init() {
connhelper.Register("ssh", Helper)
}
// Helper returns helper for connecting through an SSH URL.
func Helper(u *url.URL) (*connhelper.ConnectionHelper, error) {
sp, err := SpecFromURL(u)
if err != nil {
return nil, err
}
return &connhelper.ConnectionHelper{
ContextDialer: func(ctx context.Context, addr string) (net.Conn, error) {
args := []string{}
if sp.User != "" {
args = append(args, "-l", sp.User)
}
if sp.Port != "" {
args = append(args, "-p", sp.Port)
}
args = append(args, "--", sp.Host)
args = append(args, "buildctl")
if socket := sp.Socket; socket != "" {
args = append(args, "--addr", "unix://"+socket)
}
args = append(args, "dial-stdio")
// using background context because context remains active for the duration of the process, after dial has completed
return commandconn.New(context.Background(), "ssh", args...)
},
}, nil
}
// Spec
type Spec struct {
User string
Host string
Port string
Socket string
}
// SpecFromURL creates Spec from URL.
// URL is like ssh://<user>@host:<port>
// Only <host> part is mandatory.
func SpecFromURL(u *url.URL) (*Spec, error) {
sp := Spec{
Host: u.Hostname(),
Port: u.Port(),
Socket: u.Path,
}
if user := u.User; user != nil {
sp.User = user.Username()
if _, ok := user.Password(); ok {
return nil, errors.New("plain-text password is not supported")
}
}
if sp.Host == "" {
return nil, errors.Errorf("no host specified")
}
if u.RawQuery != "" {
return nil, errors.Errorf("extra query after the host: %q", u.RawQuery)
}
if u.Fragment != "" {
return nil, errors.Errorf("extra fragment after the host: %q", u.Fragment)
}
return &sp, nil
}

View File

@ -87,10 +87,7 @@ func MarshalConstraints(base, override *Constraints) (*pb.Op, *pb.OpMetadata) {
c.Platform = p
}
for _, wc := range override.WorkerConstraints {
c.WorkerConstraints = append(c.WorkerConstraints, wc)
}
c.WorkerConstraints = append(c.WorkerConstraints, override.WorkerConstraints...)
c.Metadata = mergeMetadata(c.Metadata, override.Metadata)
if c.Platform == nil {

View File

@ -23,6 +23,12 @@ func ResolveDigest(v bool) ImageOption {
})
}
func WithLayerLimit(l int) ImageOption {
return imageOptionFunc(func(ii *ImageInfo) {
ii.layerLimit = &l
})
}
// ImageMetaResolver can resolve image config metadata from a reference
type ImageMetaResolver interface {
ResolveImageConfig(ctx context.Context, ref string, opt ResolveImageConfigOpt) (digest.Digest, []byte, error)

View File

@ -116,6 +116,11 @@ func Image(ref string, opts ...ImageOption) State {
attrs[pb.AttrImageRecordType] = info.RecordType
}
if ll := info.layerLimit; ll != nil {
attrs[pb.AttrImageLayerLimit] = strconv.FormatInt(int64(*ll), 10)
addCap(&info.Constraints, pb.CapSourceImageLayerLimit)
}
src := NewSource("docker-image://"+ref, attrs, info.Constraints) // controversial
if err != nil {
src.err = err
@ -204,6 +209,7 @@ type ImageInfo struct {
metaResolver ImageMetaResolver
resolveDigest bool
resolveMode ResolveMode
layerLimit *int
RecordType string
}

View File

@ -619,9 +619,7 @@ var (
func Require(filters ...string) ConstraintsOpt {
return constraintsOptFunc(func(c *Constraints) {
for _, f := range filters {
c.WorkerConstraints = append(c.WorkerConstraints, f)
}
c.WorkerConstraints = append(c.WorkerConstraints, filters...)
})
}

View File

@ -24,6 +24,7 @@ import (
"github.com/moby/buildkit/util/entitlements"
ocispecs "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/pkg/errors"
"github.com/tonistiigi/fsutil"
fstypes "github.com/tonistiigi/fsutil/types"
"go.opentelemetry.io/otel/trace"
"golang.org/x/sync/errgroup"
@ -342,10 +343,10 @@ func prepareSyncedDirs(def *llb.Definition, localDirs map[string]string) ([]file
return nil, errors.Errorf("%s not a directory", d)
}
}
resetUIDAndGID := func(p string, st *fstypes.Stat) bool {
resetUIDAndGID := func(p string, st *fstypes.Stat) fsutil.MapResult {
st.Uid = 0
st.Gid = 0
return true
return fsutil.MapResultKeep
}
dirs := make([]filesync.SyncedDir, 0, len(localDirs))

View File

@ -36,7 +36,7 @@ type SyncedDir struct {
Name string
Dir string
Excludes []string
Map func(string, *fstypes.Stat) bool
Map func(string, *fstypes.Stat) fsutil.MapResult
}
// NewFSSyncProvider creates a new provider for sending files from client

View File

@ -160,12 +160,10 @@ func (sm *Manager) Get(ctx context.Context, id string, noWait bool) (Caller, err
defer cancel()
go func() {
select {
case <-ctx.Done():
sm.mu.Lock()
sm.updateCondition.Broadcast()
sm.mu.Unlock()
}
<-ctx.Done()
sm.mu.Lock()
sm.updateCondition.Broadcast()
sm.mu.Unlock()
}()
var c *client

View File

@ -26,6 +26,7 @@ const AttrImageResolveModeDefault = "default"
const AttrImageResolveModeForcePull = "pull"
const AttrImageResolveModePreferLocal = "local"
const AttrImageRecordType = "image.recordtype"
const AttrImageLayerLimit = "image.layerlimit"
const AttrLocalDiffer = "local.differ"
const AttrLocalDifferNone = "none"

View File

@ -9,8 +9,10 @@ var Caps apicaps.CapList
// considered immutable. After a capability is marked stable it should not be disabled.
const (
CapSourceImage apicaps.CapID = "source.image"
CapSourceImageResolveMode apicaps.CapID = "source.image.resolvemode"
CapSourceImage apicaps.CapID = "source.image"
CapSourceImageResolveMode apicaps.CapID = "source.image.resolvemode"
CapSourceImageLayerLimit apicaps.CapID = "source.image.layerlimit"
CapSourceLocal apicaps.CapID = "source.local"
CapSourceLocalUnique apicaps.CapID = "source.local.unique"
CapSourceLocalSessionID apicaps.CapID = "source.local.sessionid"
@ -86,6 +88,12 @@ func init() {
Status: apicaps.CapStatusExperimental,
})
Caps.Init(apicaps.Cap{
ID: CapSourceImageLayerLimit,
Enabled: true,
Status: apicaps.CapStatusExperimental,
})
Caps.Init(apicaps.Cap{
ID: CapSourceLocal,
Enabled: true,

View File

@ -36,9 +36,7 @@ func (ps *MultiWriter) Add(pw Writer) {
}
ps.mu.Lock()
plist := make([]*Progress, 0, len(ps.items))
for _, p := range ps.items {
plist = append(plist, p)
}
plist = append(plist, ps.items...)
sort.Slice(plist, func(i, j int) bool {
return plist[i].Timestamp.Before(plist[j].Timestamp)
})

View File

@ -1,29 +1,30 @@
#syntax=docker/dockerfile:1.2
ARG GO_VERSION=1.16
#syntax=docker/dockerfile:1.4
ARG GO_VERSION=1.18
FROM --platform=amd64 tonistiigi/xx:golang AS goxx
FROM --platform=$BUILDPLATFORM tonistiigi/xx:1.1.0 AS xx
FROM --platform=$BUILDPLATFORM golang:${GO_VERSION}-alpine AS base
RUN apk add --no-cache gcc musl-dev
COPY --from=goxx / /
RUN apk add --no-cache git
COPY --from=xx / /
WORKDIR /src
FROM base AS build
ARG TARGETPLATFORM
RUN --mount=target=. \
RUN --mount=target=. --mount=target=/go/pkg/mod,type=cache \
--mount=target=/root/.cache,type=cache \
go build ./...
xx-go build ./...
FROM base AS test
RUN --mount=target=. \
ARG TESTFLAGS
RUN --mount=target=. --mount=target=/go/pkg/mod,type=cache \
--mount=target=/root/.cache,type=cache \
go test -test.v ./...
CGO_ENABLED=0 xx-go test -test.v ${TESTFLAGS} ./...
FROM base AS test-noroot
RUN mkdir /go/pkg && chmod 0777 /go/pkg
USER 1000:1000
RUN --mount=target=. \
--mount=target=/tmp/.cache,type=cache \
GOCACHE=/tmp/gocache go test -test.v ./...
CGO_ENABLED=0 GOCACHE=/tmp/gocache xx-go test -test.v ./...
FROM build

View File

@ -1,3 +1,4 @@
//go:build linux
// +build linux
package fsutil

View File

@ -323,10 +323,6 @@ func (lfw *lazyFileWriter) Close() error {
return err
}
func mkdev(major int64, minor int64) uint32 {
return uint32(((minor & 0xfff00) << 12) | ((major & 0xfff) << 8) | (minor & 0xff))
}
// Random number state.
// We generate random temporary file names so that there's a good
// chance the file doesn't exist yet - keeps the number of tries in

View File

@ -1,3 +1,4 @@
//go:build freebsd
// +build freebsd
package fsutil
@ -8,7 +9,9 @@ import (
)
func createSpecialFile(path string, mode uint32, stat *types.Stat) error {
dev := unix.Mkdev(uint32(stat.Devmajor), uint32(stat.Devminor))
return unix.Mknod(path, mode, dev)
return unix.Mknod(path, mode, mkdev(stat.Devmajor, stat.Devminor))
}
func mkdev(major int64, minor int64) uint64 {
return unix.Mkdev(uint32(major), uint32(minor))
}

View File

@ -1,3 +1,4 @@
//go:build !windows
// +build !windows
package fsutil

View File

@ -1,13 +1,17 @@
//go:build !windows && !freebsd
// +build !windows,!freebsd
package fsutil
import (
"syscall"
"github.com/tonistiigi/fsutil/types"
"golang.org/x/sys/unix"
)
func createSpecialFile(path string, mode uint32, stat *types.Stat) error {
return syscall.Mknod(path, mode, int(mkdev(stat.Devmajor, stat.Devminor)))
return unix.Mknod(path, mode, mkdev(stat.Devmajor, stat.Devminor))
}
func mkdev(major int64, minor int64) int {
return int(unix.Mkdev(uint32(major), uint32(minor)))
}

View File

@ -1,5 +1,5 @@
variable "GO_VERSION" {
default = "1.16"
default = "1.18"
}
group "default" {
@ -63,5 +63,5 @@ target "shfmt" {
target "cross" {
inherits = ["build"]
platforms = ["linux/amd64", "linux/386", "linux/arm64", "linux/arm", "linux/ppc64le", "linux/s390x", "darwin/amd64", "darwin/arm64", "windows/amd64", "freebsd/amd64", "freebsd/arm64"]
platforms = ["linux/amd64", "linux/386", "linux/arm64", "linux/arm", "linux/ppc64le", "linux/s390x", "darwin/amd64", "darwin/arm64", "windows/amd64", "windows/arm64", "freebsd/amd64", "freebsd/arm64"]
}

View File

@ -1,3 +1,4 @@
//go:build !windows
// +build !windows
package fsutil

View File

@ -19,9 +19,29 @@ type WalkOpt struct {
// FollowPaths contains symlinks that are resolved into include patterns
// before performing the fs walk
FollowPaths []string
Map FilterFunc
Map MapFunc
}
type MapFunc func(string, *types.Stat) MapResult
// The result of the walk function controls
// both how WalkDir continues and whether the path is kept.
type MapResult int
const (
// Keep the current path and continue.
MapResultKeep MapResult = iota
// Exclude the current path and continue.
MapResultExclude
// Exclude the current path, and skip the rest of the dir.
// If path is a dir, skip the current directory.
// If path is a file, skip the rest of the parent directory.
// (This matches the semantics of fs.SkipDir.)
MapResultSkipDir
)
func Walk(ctx context.Context, p string, opt *WalkOpt, fn filepath.WalkFunc) error {
root, err := filepath.EvalSymlinks(p)
if err != nil {
@ -258,7 +278,10 @@ func Walk(ctx context.Context, p string, opt *WalkOpt, fn filepath.WalkFunc) err
return ctx.Err()
default:
if opt != nil && opt.Map != nil {
if allowed := opt.Map(stat.Path, stat); !allowed {
result := opt.Map(stat.Path, stat)
if result == MapResultSkipDir {
return filepath.SkipDir
} else if result == MapResultExclude {
return nil
}
}
@ -277,7 +300,8 @@ func Walk(ctx context.Context, p string, opt *WalkOpt, fn filepath.WalkFunc) err
default:
}
if opt != nil && opt.Map != nil {
if allowed := opt.Map(parentStat.Path, parentStat); !allowed {
result := opt.Map(parentStat.Path, parentStat)
if result == MapResultSkipDir || result == MapResultExclude {
continue
}
}