/
data_handle.go
130 lines (106 loc) · 2.33 KB
/
data_handle.go
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package data
import (
"fmt"
"path"
"strings"
)
// <author>/<name>[.<format>][@<tag>]
type Handle struct {
Author string
Name string
Format string
Version string
}
// There are problems with goyaml setters/getters.
// Unmarshaling fails.
//
// func (d Handle) GetYAML() (string, interface{}) {
// pOut("GetYAML\n")
// return "", d.string
// }
//
// func (d Handle) SetYAML(tag string, value interface{}) bool {
// s, ok := value.(string)
// d.string = s
// pOut("SetYAML %s %s\n", d.string, &d)
// return ok
// }
func NewHandle(s string) *Handle {
d := new(Handle)
d.SetDataset(s)
return d
}
func (d *Handle) Dataset() string {
s := d.Path()
if len(d.Format) > 0 {
s = fmt.Sprintf("%s.%s", s, d.Format)
}
if len(d.Version) > 0 {
s = fmt.Sprintf("%s@%s", s, d.Version)
}
return s
}
func (d *Handle) Path() string {
return path.Join(d.Author, d.Name)
}
func (d *Handle) InstallPath() string {
return path.Join(DatasetDir, d.Dataset())
}
// order: rsplit @, split /, rsplit .
func (d *Handle) SetDataset(s string) {
// no / is invalid
if strings.Index(s, "/") == 0 {
return
}
nam_idx := strings.Index(s, "/")
if nam_idx < 0 {
nam_idx = 0
}
ver_idx := strings.LastIndex(s, "@")
if ver_idx < 0 {
ver_idx = len(s) // no version in handle.
}
// this precludes names that have periods... use different delimiter?
fmt_idx := strings.LastIndex(s[nam_idx+1:ver_idx], ".")
if fmt_idx < 0 {
fmt_idx = ver_idx // no format in handle.
} else {
fmt_idx += nam_idx + 1
}
// parts
d.Author = slice(s, 0, nam_idx)
d.Name = slice(s, nam_idx+1, fmt_idx)
d.Format = slice(s, fmt_idx+1, ver_idx)
d.Version = slice(s, ver_idx+1, len(s))
}
func (d *Handle) GoString() string {
return d.Dataset()
}
func (d *Handle) Valid() bool {
return IsDatasetHandle(d.Dataset())
}
// utils
func slice(s string, from int, to int) string {
from = maxInt(from, 0)
to = minInt(to, len(s))
return s[minInt(from, to):to]
}
// https://groups.google.com/forum/#!topic/golang-nuts/dbyqx_LGUxM is silly.
func minInt(x, y int) (r int) {
if x < y {
return x
}
return y
}
func maxInt(x, y int) (r int) {
if x > y {
return x
}
return y
}
func handleError(handle string, problem string) error {
return fmt.Errorf("Invalid handle (%s): %s", problem, handle)
}
func IsDatasetHandle(str string) bool {
return HandleRegexp.MatchString(str)
}