github.com/axw/juju@v0.0.0-20161005053422-4bd6544d08d4/cmd/helpers.go (about) 1 // Copyright 2014 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package cmd 5 6 import ( 7 "bufio" 8 "io" 9 "strings" 10 11 "github.com/juju/cmd" 12 "github.com/juju/errors" 13 ) 14 15 // This file contains helper functions for generic operations commonly needed 16 // when implementing a command. 17 18 type userAbortedError string 19 20 func (e userAbortedError) Error() string { 21 return string(e) 22 } 23 24 // IsUserAbortedError returns true if err is of type userAbortedError. 25 func IsUserAbortedError(err error) bool { 26 _, ok := errors.Cause(err).(userAbortedError) 27 return ok 28 } 29 30 // UserConfirmYes returns an error if we do not read a "y" or "yes" from user 31 // input. 32 func UserConfirmYes(ctx *cmd.Context) error { 33 scanner := bufio.NewScanner(ctx.Stdin) 34 scanner.Scan() 35 err := scanner.Err() 36 if err != nil && err != io.EOF { 37 return errors.Trace(err) 38 } 39 answer := strings.ToLower(scanner.Text()) 40 if answer != "y" && answer != "yes" { 41 return errors.Trace(userAbortedError("aborted")) 42 } 43 return nil 44 }