2018-08-01 15:15:38 +01:00
|
|
|
// Copyright (C) 2018 Storj Labs, Inc.
|
|
|
|
// See LICENSE for copying information.
|
|
|
|
|
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/gob"
|
2018-08-23 08:05:56 +01:00
|
|
|
"net/url"
|
|
|
|
"strings"
|
2018-08-01 15:15:38 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
// GetBytes transforms an empty interface type into a byte slice
|
|
|
|
func GetBytes(key interface{}) ([]byte, error) {
|
|
|
|
var buf bytes.Buffer
|
|
|
|
enc := gob.NewEncoder(&buf)
|
|
|
|
err := enc.Encode(key)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return buf.Bytes(), nil
|
|
|
|
}
|
2018-08-23 08:05:56 +01:00
|
|
|
|
2018-08-27 18:28:16 +01:00
|
|
|
// ParseURL extracts database parameters from a string as a URL
|
|
|
|
// bolt://storj.db
|
|
|
|
// bolt://C:\storj.db
|
|
|
|
// redis://hostname
|
2018-08-23 08:05:56 +01:00
|
|
|
func ParseURL(s string) (*url.URL, error) {
|
|
|
|
if strings.HasPrefix(s, "bolt://") {
|
|
|
|
return &url.URL{
|
|
|
|
Scheme: "bolt",
|
|
|
|
Path: strings.TrimPrefix(s, "bolt://"),
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return url.Parse(s)
|
|
|
|
}
|
2018-09-05 17:10:35 +01:00
|
|
|
|
|
|
|
// CombineErrors combines multiple errors to a single error
|
2018-09-11 14:57:12 +01:00
|
|
|
func CombineErrors(errs ...error) error {
|
|
|
|
var errlist combinedError
|
|
|
|
for _, err := range errs {
|
|
|
|
if err != nil {
|
|
|
|
errlist = append(errlist, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if len(errlist) == 0 {
|
|
|
|
return nil
|
|
|
|
} else if len(errlist) == 1 {
|
|
|
|
return errlist[0]
|
|
|
|
}
|
|
|
|
return errlist
|
|
|
|
}
|
2018-09-05 17:10:35 +01:00
|
|
|
|
|
|
|
type combinedError []error
|
|
|
|
|
|
|
|
func (errs combinedError) Cause() error {
|
|
|
|
if len(errs) > 0 {
|
|
|
|
return errs[0]
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (errs combinedError) Error() string {
|
|
|
|
if len(errs) > 0 {
|
|
|
|
limit := 5
|
|
|
|
if len(errs) < limit {
|
|
|
|
limit = len(errs)
|
|
|
|
}
|
|
|
|
allErrors := errs[0].Error()
|
|
|
|
for _, err := range errs[1:limit] {
|
|
|
|
allErrors += "\n" + err.Error()
|
|
|
|
}
|
|
|
|
return allErrors
|
|
|
|
}
|
|
|
|
return ""
|
|
|
|
}
|