base.go 1.15 KB
Newer Older
1 2 3 4 5
package namesys

import (
	"strings"

6
	context "context"
7

Dirk McCormick's avatar
Dirk McCormick committed
8
	opts "github.com/ipfs/go-ipfs/namesys/opts"
9 10 11 12 13
	path "github.com/ipfs/go-ipfs/path"
)

type resolver interface {
	// resolveOnce looks up a name once (without recursion).
Dirk McCormick's avatar
Dirk McCormick committed
14
	resolveOnce(ctx context.Context, name string, options *opts.ResolveOpts) (value path.Path, err error)
15 16 17
}

// resolve is a helper for implementing Resolver.ResolveN using resolveOnce.
Dirk McCormick's avatar
Dirk McCormick committed
18 19
func resolve(ctx context.Context, r resolver, name string, options *opts.ResolveOpts, prefixes ...string) (path.Path, error) {
	depth := options.Depth
20
	for {
Dirk McCormick's avatar
Dirk McCormick committed
21
		p, err := r.resolveOnce(ctx, name, options)
22 23 24
		if err != nil {
			return "", err
		}
25
		log.Debugf("resolved %s to %s", name, p.String())
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55

		if strings.HasPrefix(p.String(), "/ipfs/") {
			// we've bottomed out with an IPFS path
			return p, nil
		}

		if depth == 1 {
			return p, ErrResolveRecursion
		}

		matched := false
		for _, prefix := range prefixes {
			if strings.HasPrefix(p.String(), prefix) {
				matched = true
				if len(prefixes) == 1 {
					name = strings.TrimPrefix(p.String(), prefix)
				}
				break
			}
		}

		if !matched {
			return p, nil
		}

		if depth > 1 {
			depth--
		}
	}
}