errors handling

This commit is contained in:
alessio 2016-07-13 12:32:54 +02:00
parent 86ba7a0aef
commit e4fe6f4758
2 changed files with 21 additions and 15 deletions

13
main.go
View File

@ -9,6 +9,13 @@ import (
func main() {
handle := func(err error) error{
if err != nil {
return cli.Exit(err, 86)
}
return nil
}
app := &cli.App{
Name: "realize",
Version: "1.0",
@ -28,9 +35,9 @@ func main() {
Usage: "create the initial config file",
Action: func(c *cli.Context) error {
t := realize.Init()
t.Create()
fmt.Printf("Hello %q", c.String("run"))
return nil
_, err := t.Create()
return handle(err)
},
},
},

View File

@ -3,6 +3,7 @@ package realize
import (
"os"
"gopkg.in/yaml.v2"
"errors"
)
type Config struct {
@ -20,17 +21,15 @@ type Watchers struct{
Ext []string `yaml:"app_ext,omitempty"`
}
// Check files exists
func Check(files ...string) []bool{
var result []bool
func Check(files ...string) (result []bool, err error){
for _, val := range files {
if _, err := os.Stat(val); err == nil {
result = append(result,true)
}
result = append(result, false)
}
return result
return
}
// Default value
@ -49,22 +48,22 @@ func Init() Config{
}
// Create config yaml file
func (h *Config) Create() bool{
var config = Check(h.File)
func (h *Config) Create() (result bool, err error){
config, err := Check(h.File)
if config[0] == false {
if w, err := os.Create(h.File); err == nil {
defer w.Close()
y, err := yaml.Marshal(h)
_, err = w.WriteString(string(y))
if err != nil {
panic(err)
os.Remove(h.File)
return false, err
}
w.WriteString(string(y))
return true
}else{
panic(err)
return true, nil
}
return false, err
}
return false
return false, errors.New("already exist")
}
// Read config file