1package getter
2
3import (
4	"io/ioutil"
5	"os"
6	"path/filepath"
7	"testing"
8)
9
10func TestSourceDirSubdir(t *testing.T) {
11	cases := []struct {
12		Input    string
13		Dir, Sub string
14	}{
15		{
16			"hashicorp.com",
17			"hashicorp.com", "",
18		},
19		{
20			"hashicorp.com//foo",
21			"hashicorp.com", "foo",
22		},
23		{
24			"hashicorp.com//foo?bar=baz",
25			"hashicorp.com?bar=baz", "foo",
26		},
27		{
28			"https://hashicorp.com/path//*?archive=foo",
29			"https://hashicorp.com/path?archive=foo", "*",
30		},
31		{
32			"https://hashicorp.com/path?checksum=file:http://url.com/....iso.sha256",
33			"https://hashicorp.com/path?checksum=file:http://url.com/....iso.sha256", "",
34		},
35		{
36			"https://hashicorp.com/path//*?checksum=file:http://url.com/....iso.sha256",
37			"https://hashicorp.com/path?checksum=file:http://url.com/....iso.sha256", "*",
38		},
39		{
40			"file://foo//bar",
41			"file://foo", "bar",
42		},
43	}
44
45	for i, tc := range cases {
46		adir, asub := SourceDirSubdir(tc.Input)
47		if adir != tc.Dir {
48			t.Fatalf("%d: bad dir: %#v", i, adir)
49		}
50		if asub != tc.Sub {
51			t.Fatalf("%d: bad sub: %#v", i, asub)
52		}
53	}
54}
55
56func TestSourceSubdirGlob(t *testing.T) {
57	td, err := ioutil.TempDir("", "subdir-glob")
58	if err != nil {
59		t.Fatal(err)
60	}
61	defer os.RemoveAll(td)
62
63	if err := os.Mkdir(filepath.Join(td, "subdir"), 0755); err != nil {
64		t.Fatal(err)
65	}
66
67	if err := os.Mkdir(filepath.Join(td, "subdir/one"), 0755); err != nil {
68		t.Fatal(err)
69	}
70
71	if err := os.Mkdir(filepath.Join(td, "subdir/two"), 0755); err != nil {
72		t.Fatal(err)
73	}
74
75	subdir := filepath.Join(td, "subdir")
76
77	// match the exact directory
78	res, err := SubdirGlob(td, "subdir")
79	if err != nil {
80		t.Fatal(err)
81	}
82	if res != subdir {
83		t.Fatalf(`expected "subdir", got: %q`, subdir)
84	}
85
86	// single match from a wildcard
87	res, err = SubdirGlob(td, "*")
88	if err != nil {
89		t.Fatal(err)
90	}
91	if res != subdir {
92		t.Fatalf(`expected "subdir", got: %q`, subdir)
93	}
94
95	// multiple matches
96	res, err = SubdirGlob(td, "subdir/*")
97	if err == nil {
98		t.Fatalf("expected multiple matches, got %q", res)
99	}
100
101	// non-existent
102	res, err = SubdirGlob(td, "foo")
103	if err == nil {
104		t.Fatalf("expected no matches, got %q", res)
105	}
106}
107