aboutsummaryrefslogtreecommitdiff
path: root/s3/path.go
blob: b1a981bec5de8d904bc94e029d92348e79ad7e7d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
56
57
58
59
60
61
62
63
64
65
66
67
68
package s3

import (
	"path"
	"strings"

	"github.com/minio/minio-go/v7"
)

type S3Class int

const (
	ROOT S3Class = 1 << iota
	BUCKET
	COMMON_PREFIX
	OBJECT
	OPAQUE_KEY

	KEY = COMMON_PREFIX | OBJECT | OPAQUE_KEY
)

type S3Path struct {
	Path   string
	Class  S3Class
	Bucket string
	Key    string
}

func NewS3Path(p string) S3Path {
	// Remove first dot, eq. relative directory == "/"
	if len(p) > 0 && p[0] == '.' {
		p = p[1:]
	}

	// Add the first slash if missing
	p = "/" + p

	// Clean path using golang tools
	p = path.Clean(p)

	exploded_path := strings.SplitN(p, "/", 3)

	// If there is no bucket name (eg. "/")
	if len(exploded_path) < 2 || exploded_path[1] == "" {
		return S3Path{p, ROOT, "", ""}
	}

	// If there is no key
	if len(exploded_path) < 3 || exploded_path[2] == "" {
		return S3Path{p, BUCKET, exploded_path[1], ""}
	}

	return S3Path{p, OPAQUE_KEY, exploded_path[1], exploded_path[2]}
}

func NewTrustedS3Path(bucket string, obj minio.ObjectInfo) S3Path {
	cl := OBJECT
	if obj.Key[len(obj.Key)-1:] == "/" {
		cl = COMMON_PREFIX
	}

	return S3Path{
		Path:   path.Join("/", bucket, obj.Key),
		Bucket: bucket,
		Key:    obj.Key,
		Class:  cl,
	}
}