forked from imjerrybao/apex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
121 lines (96 loc) · 2.38 KB
/
utils.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package utils
import (
"bytes"
"crypto/sha256"
"encoding/base64"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"github.com/Unknwon/goconfig"
"github.com/mitchellh/go-homedir"
"github.com/rliebling/gitignorer"
)
// Sha256 returns a base64 encoded SHA256 hash of `b`.
func Sha256(b []byte) string {
h := sha256.New()
h.Write(b)
return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
// LoadFiles return filtered map of relative to 'root' file paths;
// for filtering it uses shell file name pattern matching
func LoadFiles(root string, ignoreFile []byte) (files []string, err error) {
err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
mode := info.Mode()
if !(mode.IsRegular() || mode&os.ModeSymlink == os.ModeSymlink) {
return nil
}
rel, err := filepath.Rel(root, path)
if err != nil {
return err
}
matched, err := gitignorer.GitIgnore(bytes.NewReader(ignoreFile), rel)
if err != nil {
return err
}
if matched {
return nil
}
files = append(files, rel)
return nil
})
return
}
// GetProfile attempts to load the profile from AWS_PROFILE otherwise defaults to "default"
func GetProfile() string {
profile := os.Getenv("AWS_PROFILE")
if profile == "" {
return "default"
}
return profile
}
// GetRegion attempts loading the AWS region from ~/.aws/config.
func GetRegion(profile string) (string, error) {
home, err := homedir.Dir()
if err != nil {
return "", err
}
path := filepath.Join(home, ".aws", "config")
cfg, err := goconfig.LoadConfigFile(path)
if err != nil {
return "", err
}
sectionName := "default"
if profile != "" && profile != "default" {
sectionName = fmt.Sprintf("profile %s", profile)
}
section, err := cfg.GetSection(sectionName)
if err != nil {
return "", fmt.Errorf("Could not find AWS region in %s", path)
}
return section["region"], nil
}
// ReadIgnoreFile reads .apexignore in `dir` when present and returns a list of patterns.
func ReadIgnoreFile(dir string) ([]byte, error) {
path := filepath.Join(dir, ".apexignore")
b, err := ioutil.ReadFile(path)
if os.IsNotExist(err) {
return nil, nil
}
if err != nil {
return nil, err
}
return b, nil
}
// ContainsString checks if array contains string
func ContainsString(array []string, element string) bool {
for _, e := range array {
if element == e {
return true
}
}
return false
}