path.go 1.82 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3
package path

import (
4
	"errors"
5 6
	"path"
	"strings"
7 8 9 10 11

	u "github.com/ipfs/go-ipfs/util"

	b58 "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-base58"
	mh "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multihash"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
12 13
)

14 15 16
// ErrBadPath is returned when a given path is incorrectly formatted
var ErrBadPath = errors.New("invalid ipfs ref path")

Jeromy's avatar
Jeromy committed
17 18 19
// TODO: debate making this a private struct wrapped in a public interface
// would allow us to control creation, and cache segments.
type Path string
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
20

21 22 23 24 25 26 27
// FromString safely converts a string type to a Path type
func FromString(s string) Path {
	return Path(s)
}

// FromKey safely converts a Key type to a Path type
func FromKey(k u.Key) Path {
28
	return Path("/ipfs/" + k.String())
29 30
}

Jeromy's avatar
Jeromy committed
31 32 33
func (p Path) Segments() []string {
	cleaned := path.Clean(string(p))
	segments := strings.Split(cleaned, "/")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
34

Jeromy's avatar
Jeromy committed
35 36 37
	// Ignore leading slash
	if len(segments[0]) == 0 {
		segments = segments[1:]
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
38 39
	}

Jeromy's avatar
Jeromy committed
40
	return segments
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
41 42
}

Jeromy's avatar
Jeromy committed
43 44
func (p Path) String() string {
	return string(p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
45
}
46 47 48 49

func FromSegments(seg ...string) Path {
	return Path(strings.Join(seg, "/"))
}
50 51 52

func ParsePath(txt string) (Path, error) {
	parts := strings.Split(txt, "/")
Jeromy's avatar
Jeromy committed
53 54 55 56 57 58
	if len(parts) == 1 {
		kp, err := ParseKeyToPath(txt)
		if err == nil {
			return kp, nil
		}
	}
59 60 61 62 63 64 65 66 67 68 69 70
	if len(parts) < 3 {
		return "", ErrBadPath
	}

	if parts[0] != "" {
		return "", ErrBadPath
	}

	if parts[1] != "ipfs" && parts[1] != "ipns" {
		return "", ErrBadPath
	}

Jeromy's avatar
Jeromy committed
71
	_, err := ParseKeyToPath(parts[2])
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
	if err != nil {
		return "", err
	}

	return Path(txt), nil
}

func ParseKeyToPath(txt string) (Path, error) {
	chk := b58.Decode(txt)
	if len(chk) == 0 {
		return "", errors.New("not a key")
	}

	_, err := mh.Cast(chk)
	if err != nil {
		return "", err
	}
	return FromKey(u.Key(chk)), nil
}
Jeromy's avatar
Jeromy committed
91 92 93 94 95

func (p *Path) IsValid() error {
	_, err := ParsePath(p.String())
	return err
}