Skip to content

Commit

Permalink
refactor: kill "nonil" and "die"
Browse files Browse the repository at this point in the history
- When os.Exit stops process, defer functions are not called.
  - If the f.Write fails, file will not be closed
- Error reporting should be once.
  - Make 'main' func simple: calls `run` and if it fails, put it on
    stderr and exit(1)
- `nonil` is complecated
  • Loading branch information
kyoh86 committed Nov 3, 2020
1 parent 90242d9 commit 66ca483
Showing 1 changed file with 15 additions and 23 deletions.
38 changes: 15 additions & 23 deletions cmd/interfacer/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,39 +42,32 @@ type vars struct {
Interface interfaces.Interface
}

func nonil(err ...error) error {
for _, e := range err {
if e != nil {
return e
}
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
return nil
}

func die(v interface{}) {
fmt.Fprintln(os.Stderr, v)
os.Exit(1)
}

func main() {
func run() error {
flag.Parse()
if *query == "" {
die("empty -for flag value; see -help for details")
return errors.New("empty -for flag value; see -help for details")
}
if *output == "" {
die("empty -o flag value; see -help for details")
return errors.New("empty -o flag value; see -help for details")
}
q, err := interfaces.ParseQuery(*query)
if err != nil {
die(err)
return err
}
opts := &interfaces.Options{
Query: q,
Unexported: *all,
}
i, err := interfaces.NewWithOptions(opts)
if err != nil {
die(err)
return err
}
v := &vars{
Type: fmt.Sprintf(`"%s"`, *query),
Expand All @@ -89,23 +82,22 @@ func main() {
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, v); err != nil {
die(err)
return err
}
formatted, err := format.Source(buf.Bytes())
if err != nil {
die(err)
return err
}
f := os.Stdout
if *output != "-" {
f, err = os.OpenFile(*output, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
die(err)
return err
}
defer f.Close()
}
if _, err := f.Write(formatted); err != nil {
die(err)
}
if err := f.Close(); err != nil {
die(err)
return err
}
return nil
}

0 comments on commit 66ca483

Please sign in to comment.