github.com/tonto/cli@v0.0.0-20180104210444-aec958fa47db/appfile.go (about) 1 package main 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 type appfile struct { 25 Name string `yaml:"name,omitempty" json:"name,omitempty"` 26 // TODO: Config here is not yet used 27 Config map[string]string `yaml:"config,omitempty" json:"config,omitempty"` 28 } 29 30 func findAppfile(path string) (string, error) { 31 for _, fn := range validAppfileNames { 32 fullfn := filepath.Join(path, fn) 33 if exists(fullfn) { 34 return fullfn, nil 35 } 36 } 37 return "", newNotFoundError("could not find app file") 38 } 39 40 func loadAppfile() (*appfile, error) { 41 fn, err := findAppfile(".") 42 if err != nil { 43 return nil, err 44 } 45 return parseAppfile(fn) 46 } 47 48 func parseAppfile(path string) (*appfile, error) { 49 ext := filepath.Ext(path) 50 switch ext { 51 case ".json": 52 return decodeAppfileJSON(path) 53 case ".yaml", ".yml": 54 return decodeAppfileYAML(path) 55 } 56 return nil, errUnexpectedFileFormat 57 } 58 59 func decodeAppfileJSON(path string) (*appfile, error) { 60 f, err := os.Open(path) 61 if err != nil { 62 return nil, fmt.Errorf("could not open %s for parsing. Error: %v", path, err) 63 } 64 ff := &appfile{} 65 err = json.NewDecoder(f).Decode(ff) 66 return ff, err 67 } 68 69 func decodeAppfileYAML(path string) (*appfile, error) { 70 b, err := ioutil.ReadFile(path) 71 if err != nil { 72 return nil, fmt.Errorf("could not open %s for parsing. Error: %v", path, err) 73 } 74 ff := &appfile{} 75 err = yaml.Unmarshal(b, ff) 76 return ff, err 77 }