github.com/keltia/go-ipfs@v0.3.8-0.20150909044612-210793031c63/namesys/base.go (about)

     1  package namesys
     2  
     3  import (
     4  	"strings"
     5  
     6  	context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
     7  
     8  	path "github.com/ipfs/go-ipfs/path"
     9  )
    10  
    11  type resolver interface {
    12  	// resolveOnce looks up a name once (without recursion).
    13  	resolveOnce(ctx context.Context, name string) (value path.Path, err error)
    14  }
    15  
    16  // resolve is a helper for implementing Resolver.ResolveN using resolveOnce.
    17  func resolve(ctx context.Context, r resolver, name string, depth int, prefixes ...string) (path.Path, error) {
    18  	for {
    19  		p, err := r.resolveOnce(ctx, name)
    20  		if err != nil {
    21  			log.Warningf("Could not resolve %s", name)
    22  			return "", err
    23  		}
    24  		log.Debugf("Resolved %s to %s", name, p.String())
    25  
    26  		if strings.HasPrefix(p.String(), "/ipfs/") {
    27  			// we've bottomed out with an IPFS path
    28  			return p, nil
    29  		}
    30  
    31  		if depth == 1 {
    32  			return p, ErrResolveRecursion
    33  		}
    34  
    35  		matched := false
    36  		for _, prefix := range prefixes {
    37  			if strings.HasPrefix(p.String(), prefix) {
    38  				matched = true
    39  				if len(prefixes) == 1 {
    40  					name = strings.TrimPrefix(p.String(), prefix)
    41  				}
    42  				break
    43  			}
    44  		}
    45  
    46  		if !matched {
    47  			return p, nil
    48  		}
    49  
    50  		if depth > 1 {
    51  			depth--
    52  		}
    53  	}
    54  }