1/* 2Copyright 2018 The Doctl Authors All rights reserved. 3Licensed under the Apache License, Version 2.0 (the "License"); 4you may not use this file except in compliance with the License. 5You may obtain a copy of the License at 6 http://www.apache.org/licenses/LICENSE-2.0 7Unless required by applicable law or agreed to in writing, software 8distributed under the License is distributed on an "AS IS" BASIS, 9WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10See the License for the specific language governing permissions and 11limitations under the License. 12*/ 13 14package commands 15 16import ( 17 "encoding/json" 18 "fmt" 19 "os" 20 21 "github.com/digitalocean/doctl" 22 "github.com/fatih/color" 23 "github.com/shiena/ansicolor" 24 "github.com/spf13/viper" 25) 26 27var ( 28 errOperationAborted = fmt.Errorf("Operation aborted.") 29 30 colorErr = color.RedString("Error") 31 colorWarn = color.YellowString("Warning") 32 colorNotice = color.GreenString("Notice") 33 34 // errAction specifies what should happen when an error occurs 35 errAction = func() { 36 os.Exit(1) 37 } 38) 39 40func init() { 41 color.Output = ansicolor.NewAnsiColorWriter(os.Stderr) 42} 43 44type outputErrors struct { 45 Errors []outputError `json:"errors"` 46} 47 48type outputError struct { 49 Detail string `json:"detail"` 50} 51 52func checkErr(err error) { 53 if err == nil { 54 return 55 } 56 57 output := viper.GetString("output") 58 59 switch output { 60 default: 61 fmt.Fprintf(color.Output, "%s: %v\n", colorErr, err) 62 case "json": 63 es := outputErrors{ 64 Errors: []outputError{ 65 {Detail: err.Error()}, 66 }, 67 } 68 69 b, _ := json.Marshal(&es) 70 fmt.Println(string(b)) 71 } 72 73 errAction() 74} 75 76func ensureOneArg(c *CmdConfig) error { 77 switch count := len(c.Args); { 78 case count == 0: 79 return doctl.NewMissingArgsErr(c.NS) 80 case count > 1: 81 return doctl.NewTooManyArgsErr(c.NS) 82 default: 83 return nil 84 } 85} 86 87func warn(msg string, args ...interface{}) { 88 fmt.Fprintf(color.Output, "%s: %s\n", colorWarn, fmt.Sprintf(msg, args...)) 89} 90func warnConfirm(msg string, args ...interface{}) { 91 fmt.Fprintf(color.Output, "%s: %s", colorWarn, fmt.Sprintf(msg, args...)) 92} 93 94func notice(msg string, args ...interface{}) { 95 fmt.Fprintf(color.Output, "%s: %s\n", colorNotice, fmt.Sprintf(msg, args...)) 96} 97