-
-
Notifications
You must be signed in to change notification settings - Fork 580
/
appimport.go
56 lines (44 loc) · 1.63 KB
/
appimport.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
package appimport
import (
"errors"
"fmt"
"os"
"strings"
"path/filepath"
homedir "github.com/mitchellh/go-homedir"
)
// ValidateAsset determines if a given asset matches the required criteria for a given asset type
// and returns the aboslute path to the asset, whether or not the asset is an archive type, and an error.
func ValidateAsset(unexpandedAssetPath string, assetType string) (string, bool, error) {
var invalidAssetError = "invalid asset: %v"
extensions := []string{"tar", "gz", "tgz", "zip"}
// Input provided via prompt or "--flag=value" is not expanded by shell. This will help ensure ~ is expanded to the user home directory.
assetPath, err := homedir.Expand(unexpandedAssetPath)
if err != nil {
return "", false, fmt.Errorf(invalidAssetError, err)
}
// ensure we are working w/ an absolute path
assetPath, err = filepath.Abs(assetPath)
if err != nil {
return "", false, fmt.Errorf(invalidAssetError, err)
}
info, err := os.Stat(assetPath)
if os.IsNotExist(err) {
return "", false, fmt.Errorf(invalidAssetError, errors.New("file not found"))
}
if err != nil {
return "", false, fmt.Errorf(invalidAssetError, err)
}
for _, ext := range extensions {
if strings.HasSuffix(assetPath, ext) {
return assetPath, true, nil
}
}
if assetType == "files" && !info.IsDir() {
return "", false, fmt.Errorf(invalidAssetError, errors.New("provided path is not a directory or archive"))
}
if assetType == "db" && assetPath != "" && !strings.HasSuffix(assetPath, "sql") {
return "", false, fmt.Errorf(invalidAssetError, errors.New("provided path is not a .sql file or archive"))
}
return assetPath, false, nil
}