2018-06-24 16:40:48 +03:00
|
|
|
package source
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
2018-07-20 13:31:33 +03:00
|
|
|
"io/ioutil"
|
|
|
|
"path/filepath"
|
2018-06-24 16:40:48 +03:00
|
|
|
"regexp"
|
|
|
|
"strconv"
|
2018-07-20 13:31:33 +03:00
|
|
|
|
|
|
|
yaml "github.com/ghodss/yaml"
|
2018-06-24 16:40:48 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
ErrParse = fmt.Errorf("no match")
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
DefaultParse = Parse
|
|
|
|
DefaultRegex = Regex
|
|
|
|
)
|
|
|
|
|
|
|
|
// Regex matches the following pattern:
|
|
|
|
// 123_name.up.ext
|
|
|
|
// 123_name.down.ext
|
|
|
|
var Regex = regexp.MustCompile(`^([0-9]+)_(.*)\.(` + string(Down) + `|` + string(Up) + `)\.(.*)$`)
|
|
|
|
|
|
|
|
// Parse returns Migration for matching Regex pattern.
|
2018-07-20 13:31:33 +03:00
|
|
|
func Parse(raw string, directory string) (*Migration, error) {
|
2018-06-24 16:40:48 +03:00
|
|
|
var direction Direction
|
|
|
|
m := Regex.FindStringSubmatch(raw)
|
|
|
|
if len(m) == 5 {
|
|
|
|
versionUint64, err := strconv.ParseUint(m[1], 10, 64)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Have different direction type for yaml and sql
|
|
|
|
if m[4] == "yaml" {
|
|
|
|
if m[3] == "up" {
|
|
|
|
direction = MetaUp
|
|
|
|
} else if m[3] == "down" {
|
|
|
|
direction = MetaDown
|
|
|
|
} else {
|
|
|
|
return nil, errors.New("Invalid Direction type")
|
|
|
|
}
|
2018-07-20 13:31:33 +03:00
|
|
|
data, err := ioutil.ReadFile(filepath.Join(directory, raw))
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
var t []interface{}
|
|
|
|
err = yaml.Unmarshal(data, &t)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if len(t) == 0 {
|
|
|
|
return nil, errors.New("Empty metadata file")
|
|
|
|
}
|
2018-06-24 16:40:48 +03:00
|
|
|
} else if m[4] == "sql" {
|
|
|
|
if m[3] == "up" {
|
|
|
|
direction = Up
|
|
|
|
} else if m[3] == "down" {
|
|
|
|
direction = Down
|
|
|
|
} else {
|
|
|
|
return nil, errors.New("Invalid Direction type")
|
|
|
|
}
|
2018-07-20 13:31:33 +03:00
|
|
|
data, err := ioutil.ReadFile(filepath.Join(directory, raw))
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if string(data[:]) == "" {
|
|
|
|
return nil, errors.New("Empty SQL file")
|
|
|
|
}
|
2018-06-24 16:40:48 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return &Migration{
|
|
|
|
Version: versionUint64,
|
|
|
|
Identifier: m[2],
|
|
|
|
Direction: direction,
|
|
|
|
Raw: raw,
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
return nil, ErrParse
|
|
|
|
}
|