github.com/devcamcar/cli@v0.0.0-20181107134215-706a05759d18/common/appfile.go (about) 1 package common 2 3 import ( 4 "encoding/json" 5 "errors" 6 "fmt" 7 "io/ioutil" 8 "os" 9 "path/filepath" 10 11 yaml "gopkg.in/yaml.v2" 12 ) 13 14 var ( 15 validAppfileNames = [...]string{ 16 "app.yaml", 17 "app.yml", 18 "app.json", 19 } 20 21 errUnexpectedFileFormat = errors.New("Unexpected file format for function file") 22 ) 23 24 // AppFile defines the internal structure of a app.yaml/json/yml 25 type AppFile struct { 26 Name string `yaml:"name,omitempty" json:"name,omitempty"` 27 // TODO: Config here is not yet used 28 Config map[string]string `yaml:"config,omitempty" json:"config,omitempty"` 29 Annotations map[string]interface{} `yaml:"annotations,omitempty" json:"annotations,omitempty"` 30 } 31 32 func findAppfile(path string) (string, error) { 33 for _, fn := range validAppfileNames { 34 fullfn := filepath.Join(path, fn) 35 if Exists(fullfn) { 36 return fullfn, nil 37 } 38 } 39 return "", NewNotFoundError("Could not find app file") 40 } 41 42 // LoadAppfile returns a parsed appfile. 43 func LoadAppfile(path string) (*AppFile, error) { 44 fn, err := findAppfile(path) 45 if err != nil { 46 return nil, err 47 } 48 return parseAppfile(fn) 49 } 50 51 func parseAppfile(path string) (*AppFile, error) { 52 ext := filepath.Ext(path) 53 switch ext { 54 case ".json": 55 return decodeAppfileJSON(path) 56 case ".yaml", ".yml": 57 return decodeAppfileYAML(path) 58 } 59 return nil, errUnexpectedFileFormat 60 } 61 62 func decodeAppfileJSON(path string) (*AppFile, error) { 63 f, err := os.Open(path) 64 if err != nil { 65 return nil, fmt.Errorf("Could not open %s for parsing. Error: %v", path, err) 66 } 67 ff := &AppFile{} 68 err = json.NewDecoder(f).Decode(ff) 69 return ff, err 70 } 71 72 func decodeAppfileYAML(path string) (*AppFile, error) { 73 b, err := ioutil.ReadFile(path) 74 if err != nil { 75 return nil, fmt.Errorf("Could not open %s for parsing. Error: %v", path, err) 76 } 77 ff := &AppFile{} 78 err = yaml.Unmarshal(b, ff) 79 return ff, err 80 }