fix source/file relative paths, ref #178 thanks @matyunin

This commit is contained in:
Matthias Kadenbach 2017-03-03 12:02:32 -08:00
parent 1f37f41ee8
commit cecce18c51
No known key found for this signature in database
GPG Key ID: DC1F4DC6D31A7031
2 changed files with 70 additions and 6 deletions

View File

@ -7,6 +7,7 @@ import (
nurl "net/url"
"os"
"path"
"path/filepath"
"github.com/mattes/migrate/source"
)
@ -27,24 +28,36 @@ func (f *File) Open(url string) (source.Driver, error) {
return nil, err
}
// default to current directory if empty
if u.Path == "" {
// concat host and path to restore full path
// host might be `.`
p := u.Host + u.Path
if len(p) == 0 {
// default to current directory if no path
wd, err := os.Getwd()
if err != nil {
return nil, err
}
u.Path = wd
p = wd
} else if p[0:1] == "." || p[0:1] != "/" {
// make path absolute if relative
abs, err := filepath.Abs(p)
if err != nil {
return nil, err
}
p = abs
}
// scan directory
files, err := ioutil.ReadDir(u.Path)
files, err := ioutil.ReadDir(p)
if err != nil {
return nil, err
}
nf := &File{
url: url,
path: u.Path,
path: p,
migrations: source.NewMigrations(),
}

View File

@ -5,6 +5,7 @@ import (
"io/ioutil"
"os"
"path"
"path/filepath"
"testing"
st "github.com/mattes/migrate/source/testing"
@ -50,13 +51,63 @@ func TestOpen(t *testing.T) {
mustWriteFile(t, tmpDir, "1_foobar.up.sql", "")
mustWriteFile(t, tmpDir, "1_foobar.down.sql", "")
if !filepath.IsAbs(tmpDir) {
t.Fatal("expected tmpDir to be absolute path")
}
f := &File{}
_, err = f.Open("file://" + tmpDir)
_, err = f.Open("file://" + tmpDir) // absolute path
if err != nil {
t.Fatal(err)
}
}
func TestOpenWithRelativePath(t *testing.T) {
tmpDir, err := ioutil.TempDir("", "TestOpen")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpDir)
wd, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
defer os.Chdir(wd) // rescue working dir after we are done
if err := os.Chdir(tmpDir); err != nil {
t.Fatal(err)
}
if err := os.Mkdir(filepath.Join(tmpDir, "foo"), os.ModePerm); err != nil {
t.Fatal(err)
}
mustWriteFile(t, filepath.Join(tmpDir, "foo"), "1_foobar.up.sql", "")
f := &File{}
// dir: foo
d, err := f.Open("file://foo")
if err != nil {
t.Fatal(err)
}
_, err = d.First()
if err != nil {
t.Fatalf("expected first file in working dir %v for foo", tmpDir)
}
// dir: ./foo
d, err = f.Open("file://./foo")
if err != nil {
t.Fatal(err)
}
_, err = d.First()
if err != nil {
t.Fatalf("expected first file in working dir %v for ./foo", tmpDir)
}
}
func TestOpenDefaultsToCurrentDirectory(t *testing.T) {
wd, err := os.Getwd()
if err != nil {