forked from infobloxopen/migrate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
66 lines (58 loc) · 1.06 KB
/
file.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
package file
import (
nurl "net/url"
"os"
"path/filepath"
"github.com/golang-migrate/migrate/v4/source"
"github.com/golang-migrate/migrate/v4/source/iofs"
)
func init() {
source.Register("file", &File{})
}
type File struct {
iofs.PartialDriver
url string
path string
}
func (f *File) Open(url string) (source.Driver, error) {
p, err := parseURL(url)
if err != nil {
return nil, err
}
nf := &File{
url: url,
path: p,
}
if err := nf.Init(os.DirFS(p), "."); err != nil {
return nil, err
}
return nf, nil
}
func parseURL(url string) (string, error) {
u, err := nurl.Parse(url)
if err != nil {
return "", err
}
// concat host and path to restore full path
// host might be `.`
p := u.Opaque
if len(p) == 0 {
p = u.Host + u.Path
}
if len(p) == 0 {
// default to current directory if no path
wd, err := os.Getwd()
if err != nil {
return "", err
}
p = wd
} else if p[0:1] == "." || p[0:1] != "/" {
// make path absolute if relative
abs, err := filepath.Abs(p)
if err != nil {
return "", err
}
p = abs
}
return p, nil
}