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 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
|
package argp
import (
"bufio"
"database/sql"
"fmt"
"os"
"reflect"
"strings"
"github.com/jmoiron/sqlx"
)
type DictSource interface {
Has(string) (bool, error)
Get(string) (string, error)
Close() error
}
type DictSourceFunc func([]string) (DictSource, error)
// Dict is an option that loads key-value map from a source (such as mysql).
type Dict struct {
DictSource
Sources map[string]DictSourceFunc
Values []string
}
func NewDict(values []string) *Dict {
return &Dict{
Sources: map[string]DictSourceFunc{
"static": NewStaticDict,
"inline": NewInlineDict,
"file": NewFileDict,
},
Values: values,
}
}
func (dict *Dict) Valid() bool {
return dict.DictSource != nil
}
func (dict *Dict) AddSource(typ string, f DictSourceFunc) {
dict.Sources[typ] = f
}
func (dict *Dict) Help() (string, string) {
return strings.Join(dict.Values, " "), "type:dict"
}
func (dict *Dict) Scan(name string, s []string) (int, error) {
if len(s) == 0 {
return 0, fmt.Errorf("missing value")
}
vals, _, split := truncEnd(s)
if len(vals) == 0 || split {
return 0, fmt.Errorf("invalid value")
}
colon := strings.IndexByte(vals[0], ':')
if colon == -1 || (vals[0][0] < 'a' || 'z' < vals[0][0]) && (vals[0][0] < 'A' || 'Z' < vals[0][0]) {
return 0, fmt.Errorf("invalid value, expected type:dict where type is e.g. inline")
}
dict.Values = vals
var err error
typ := vals[0][:colon]
vals[0] = vals[0][colon+1:]
if ts, ok := dict.Sources[typ]; !ok {
return 0, fmt.Errorf("unknown dict type: %s", typ)
} else if dict.DictSource, err = ts(vals); err != nil {
return 0, err
}
return len(vals), nil
}
func (dict *Dict) Close() error {
if dict.DictSource != nil {
return dict.DictSource.Close()
}
return nil
}
type StaticDict struct {
value string
}
func NewStaticDict(s []string) (DictSource, error) {
return &StaticDict{strings.Join(s, " ")}, nil
}
func (t *StaticDict) Has(key string) (bool, error) {
return true, nil
}
func (t *StaticDict) Get(key string) (string, error) {
return t.value, nil
}
func (t *StaticDict) Close() error {
return nil
}
type InlineDict struct {
dict map[string]string
}
func NewInlineDict(s []string) (DictSource, error) {
dict := map[string]string{}
if 0 < len(s) {
if _, err := scanValue(reflect.ValueOf(&dict).Elem(), s); err != nil {
return nil, err
}
}
return &InlineDict{dict}, nil
}
func (t *InlineDict) Has(key string) (bool, error) {
_, ok := t.dict[key]
return ok, nil
}
func (t *InlineDict) Get(key string) (string, error) {
v, ok := t.dict[key]
if !ok {
return key, nil
}
return v, nil
}
func (t *InlineDict) Close() error {
return nil
}
type FileDict struct {
InlineDict
}
func NewFileDict(s []string) (DictSource, error) {
if len(s) == 0 {
return nil, fmt.Errorf("missing filename")
} else if 1 < len(s) {
return nil, fmt.Errorf("expected single filename")
}
r, err := os.Open(s[0])
if err != nil {
return nil, err
}
defer r.Close()
dict := map[string]string{}
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := scanner.Text()
if is := strings.IndexByte(line, '='); is != -1 {
dict[strings.TrimSpace(line[:is])] = strings.TrimSpace(line[is+1:])
}
}
if err := scanner.Err(); err != nil {
return nil, err
}
return &FileDict{InlineDict{dict}}, nil
}
type SQLDict struct {
db *sqlx.DB
query string
}
func NewSQLDict(db *sqlx.DB, query string) (*SQLDict, error) {
return &SQLDict{
db: db,
query: query,
}, nil
}
func (t *SQLDict) Has(key string) (bool, error) {
if t.query == "" {
return false, nil
} else if err := t.db.QueryRow(t.query, key).Err(); err != nil && err != sql.ErrNoRows {
return false, err
}
return true, nil
}
func (t *SQLDict) Get(key string) (string, error) {
var val string // TODO: does this work for ints? Or should we use interface{}?
if t.query == "" {
return key, nil
} else if err := t.db.Get(&val, t.query, key); err != nil && err != sql.ErrNoRows {
return "", err
} else if err == sql.ErrNoRows {
return key, nil
} else {
return val, nil
}
}
func (t *SQLDict) Close() error {
return t.db.Close()
}
//type sqliteDict struct {
// Path string // can be :memory:
// Query string
//}
//
//func newSQLiteDict(s []string) (DictSource, error) {
// if len(s) != 1 {
// return nil, fmt.Errorf("invalid path")
// }
//
// t := sqliteDict{}
// if err := LoadConfigFile(&t, s[0]); err != nil {
// return nil, err
// }
//
// db, err := sqlx.Open("sqlite", t.Path)
// if err != nil {
// return nil, err
// }
// return &sqlDict{db, t.Query}, nil
//}
//
//type mysqlDict struct {
// Host string
// User string
// Password string
// Dbname string
// Query string
//}
//
//func newMySQLDict(s []string) (DictSource, error) {
// if len(s) != 1 {
// return nil, fmt.Errorf("invalid path")
// }
//
// t := mysqlDict{}
// if err := LoadConfigFile(&t, s[0]); err != nil {
// return nil, err
// }
//
// uri := fmt.Sprintf("%s:%s@%s/%s", t.User, t.Password, t.Host, t.Dbname)
// db, err := sqlx.Open("mysql", uri)
// if err != nil {
// return nil, err
// }
// db.SetConnMaxLifetime(time.Minute)
// db.SetConnMaxIdleTime(time.Minute)
// db.SetMaxOpenConns(10)
// db.SetMaxIdleConns(10)
// return &sqlDict{db, t.Query}, nil
//}
|