// FormatJSONSyntaxError generates a pretty printed json syntax error since
// golang doesn't provide an easy way to report the location of the error
481953
func FormatJSONSyntaxError(data io.Reader, offset int64) (highlight string) {
	var readLine bytes.Buffer
	var errLine = 1
	var readBytes int64

	bio := bufio.NewReader(data)

	// termWidth is set to a default one to use when we are
	// not able to calculate terminal width via OS syscalls
	termWidth := 25

	// errorShift is the length of the minimum needed place for
	// error msg accessories, like <--, etc.. We calculate it
	// dynamically to avoid an eventual bug after modifying errorFmt
	errorShift := len(fmt.Sprintf(errorFmt, 1, ""))

	if width, err := pb.GetTerminalWidth(); err == nil {
		termWidth = width
	}

	for {
		b, err := bio.ReadByte()
		if err != nil {
			break
		}
		readBytes++
		if readBytes > offset {
			break
		}
		if b == '\n' {
			readLine.Reset()
			errLine++
			continue
		} else if b == '\t' {
			readLine.WriteByte(' ')
		} else if b == '\r' {
			break
		}
		readLine.WriteByte(b)
	}

	lineLen := readLine.Len()
	idx := lineLen - termWidth + errorShift
	if idx < 0 || idx > lineLen-1 {
		idx = 0
	}

	return fmt.Sprintf(errorFmt, errLine, readLine.String()[idx:])
}
7507
func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
	data := make(Fields, len(entry.Data)+4)
	for k, v := range entry.Data {
		switch v := v.(type) {
		case error:
			// Otherwise errors are ignored by `encoding/json`
			// https://github.com/sirupsen/logrus/issues/137
			data[k] = v.Error()
		default:
			data[k] = v
		}
	}

	if f.DataKey != "" {
		newData := make(Fields, 4)
		newData[f.DataKey] = data
		data = newData
	}

	prefixFieldClashes(data, f.FieldMap, entry.HasCaller())

	timestampFormat := f.TimestampFormat
	if timestampFormat == "" {
		timestampFormat = defaultTimestampFormat
	}

	if entry.err != "" {
		data[f.FieldMap.resolve(FieldKeyLogrusError)] = entry.err
	}
	if !f.DisableTimestamp {
		data[f.FieldMap.resolve(FieldKeyTime)] = entry.Time.Format(timestampFormat)
	}
	data[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message
	data[f.FieldMap.resolve(FieldKeyLevel)] = entry.Level.String()
	if entry.HasCaller() {
		funcVal := entry.Caller.Function
		fileVal := fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line)
		if f.CallerPrettyfier != nil {
			funcVal, fileVal = f.CallerPrettyfier(entry.Caller)
		}
		if funcVal != "" {
			data[f.FieldMap.resolve(FieldKeyFunc)] = funcVal
		}
		if fileVal != "" {
			data[f.FieldMap.resolve(FieldKeyFile)] = fileVal
		}
	}

	var b *bytes.Buffer
	if entry.Buffer != nil {
		b = entry.Buffer
	} else {
		b = &bytes.Buffer{}
	}

	encoder := json.NewEncoder(b)
	if f.PrettyPrint {
		encoder.SetIndent("", "  ")
	}
	if err := encoder.Encode(data); err != nil {
		return nil, fmt.Errorf("failed to marshal fields to JSON, %v", err)
	}

	return b.Bytes(), nil
}
1171086
func (f *PrintFlags) AllowedFormats() []string {
	formats := f.JSONYamlPrintFlags.AllowedFormats()
	formats = append(formats, f.NamePrintFlags.AllowedFormats()...)
	formats = append(formats, f.TemplateFlags.AllowedFormats()...)
	formats = append(formats, f.CustomColumnsFlags.AllowedFormats()...)
	formats = append(formats, f.HumanReadableFlags.AllowedFormats()...)
	return formats
}
1372373
func JSONStringSimple(object *jsonw.Wrapper) (string, error) {
	x, err := object.GetInt()
	if err == nil {
		return fmt.Sprintf("%d", x), nil
	}
	y, err := object.GetString()
	if err == nil {
		return y, nil
	}
	z, err := object.GetBool()
	if err == nil {
		if z {
			return "true", nil
		}
		return "false", nil
	}

	return "", fmt.Errorf("Non-simple object: %v", object)
}
837999
func (t *ConsoleFormatter) FormatSkip(errin error, skip int) (errtext string, err error) {
	errobj := castErrorObject(nil, skip+1, errin)
	if errobj == nil {
		return "", nil
	}

	buffer := &bytes.Buffer{}

	if t.TimeFormat != "" {
		if _, errio := buffer.WriteString(time.Now().Format(t.TimeFormat)); errio != nil {
			return buffer.String(), errio
		}
	}

	if t.LongFile || t.ShortFile {
		if _, errio := WriteCallInfo(buffer, errobj, t.LongFile, t.Line, t.ReplacePackages); errio != nil {
			return buffer.String(), errio
		}
		if _, errio := buffer.WriteString(" "); errio != nil {
			return buffer.String(), errio
		}
	}

	if t.Seperator == "" {
		if _, errio := buffer.WriteString(getErrorText(errin)); errio != nil {
			return buffer.String(), errio
		}
		return buffer.String(), nil
	}

	firstError := true
	if walkerr := WalkErrors(errobj, func(errloop ErrorObject) (stop bool, walkerr error) {
		if !firstError {
			if _, errio := buffer.WriteString(t.Seperator); errio != nil {
				return true, errio
			}
		}
		firstError = false

		if _, errio := buffer.WriteString(getErrorText(errloop)); errio != nil {
			return true, errio
		}
		return false, nil
	}); walkerr != nil {
		return buffer.String(), walkerr
	}

	return buffer.String(), nil
}
459995
func (errs Errors) MarshalJSON() ([]byte, error) {
	var tmpErrs struct {
		Errors []Error `json:"errors,omitempty"`
	}

	for _, daErr := range errs {
		var err Error

		switch daErr := daErr.(type) {
		case ErrorCode:
			err = daErr.WithDetail(nil)
		case Error:
			err = daErr
		default:
			err = ErrorCodeUnknown.WithDetail(daErr)

		}

		// If the Error struct was setup and they forgot to set the
		// Message field (meaning its "") then grab it from the ErrCode
		msg := err.Message
		if msg == "" {
			msg = err.Code.Message()
		}

		tmpErrs.Errors = append(tmpErrs.Errors, Error{
			Code:    err.Code,
			Message: msg,
			Detail:  err.Detail,
		})
	}

	return json.Marshal(tmpErrs)
}
1333982
func (t *ConsoleFormatter) Format(errin error) (errtext string, err error) {
	return t.FormatSkip(errin, 1)
}
854785
func PrintJSON(v interface{}) {
	body, err := json.MarshalIndent(v, "", "  ")
	if err != nil {
		panic(err)
	}
	fmt.Printf("%s\n", body)
}
563056
func RenderErrorJSON(render render.Render, status int, err error, errs ...error) {
	errConcat := append([]error{err}, errs...)
	errjson, err := errutil.NewJSON(errutil.NewErrorsSkip(1, errConcat...))
	errutil.Trace(err)
	reserr := responseError{
		Status:    status,
		ErrorJSON: errjson,
	}
	render.JSON(status, reserr)
}
167853
func jsonError(err error) *btcjson.RPCError {
	if err == nil {
		return nil
	}

	code := btcjson.ErrRPCWallet
	switch e := err.(type) {
	case btcjson.RPCError:
		return &e
	case *btcjson.RPCError:
		return e
	case DeserializationError:
		code = btcjson.ErrRPCDeserialization
	case InvalidParameterError:
		code = btcjson.ErrRPCInvalidParameter
	case ParseError:
		code = btcjson.ErrRPCParse.Code
	case waddrmgr.ManagerError:
		switch e.ErrorCode {
		case waddrmgr.ErrWrongPassphrase:
			code = btcjson.ErrRPCWalletPassphraseIncorrect
		}
	}
	return &btcjson.RPCError{
		Code:    code,
		Message: err.Error(),
	}
}
1246770
func ErrorToJSONAPIError(ctx context.Context, err error) (app.JSONAPIError, int) {
	cause := errs.Cause(err)
	detail := cause.Error()
	var title, code string
	var statusCode int
	var id *string
	log.Error(ctx, map[string]interface{}{"err": cause, "error_message": cause.Error(), "err_type": reflect.TypeOf(cause)}, "an error occurred in our api")
	switch cause.(type) {
	case errors.NotFoundError:
		code = ErrorCodeNotFound
		title = "Not found error"
		statusCode = http.StatusNotFound
	case errors.ConversionError:
		code = ErrorCodeConversionError
		title = "Conversion error"
		statusCode = http.StatusBadRequest
	case errors.BadParameterError:
		code = ErrorCodeBadParameter
		title = "Bad parameter error"
		statusCode = http.StatusBadRequest
	case errors.VersionConflictError:
		code = ErrorCodeVersionConflict
		title = "Version conflict error"
		statusCode = http.StatusConflict
	case errors.DataConflictError:
		code = ErrorCodeDataConflict
		title = "Data conflict error"
		statusCode = http.StatusConflict
	case errors.InternalError:
		code = ErrorCodeInternalError
		title = "Internal error"
		statusCode = http.StatusInternalServerError
	case errors.UnauthorizedError:
		code = ErrorCodeUnauthorizedError
		title = "Unauthorized error"
		statusCode = http.StatusUnauthorized
	case errors.ForbiddenError:
		code = ErrorCodeForbiddenError
		title = "Forbidden error"
		statusCode = http.StatusForbidden
	default:
		code = ErrorCodeUnknownError
		title = "Unknown error"
		statusCode = http.StatusInternalServerError

		cause := errs.Cause(err)
		if err, ok := cause.(goa.ServiceError); ok {
			statusCode = err.ResponseStatus()
			idStr := err.Token()
			id = &idStr
			title = http.StatusText(statusCode)
		}
		if errResp, ok := cause.(*goa.ErrorResponse); ok {
			code = errResp.Code
			detail = errResp.Detail
		}
	}
	statusCodeStr := strconv.Itoa(statusCode)
	jerr := app.JSONAPIError{
		ID:     id,
		Code:   &code,
		Status: &statusCodeStr,
		Title:  &title,
		Detail: detail,
	}
	return jerr, statusCode
}
545961
func InvalidFormatError(ctx, target string, format Format, formatError error) error {
	msg := fmt.Sprintf("%s must be formatted as a %s but got value %#v, %s", ctx, format, target, formatError.Error())
	return ErrInvalidRequest(msg, "attribute", ctx, "value", target, "expected", format, "error", formatError.Error())
}
598613
func ValidateJSONFormat(logLine string) error {
	var kayveeData map[string]interface{}

	err := json.Unmarshal([]byte(strings.TrimSpace(logLine)), &kayveeData)
	if err != nil {
		return &InvalidJSONError{jsonError: err}
	}

	return validateKayveeData(kayveeData)
}
578707
func printJSON(logger logutil.Logger, val interface{}) error {
	data, err := MarshalJSON(val)
	if err != nil {
		return fmt.Errorf("cannot marshal data: %v", err)
	}
	logger.Printf("%v\n", string(data))
	return nil
}
545687
func StringJson(v interface{}, unq bool) (ret string) {
	ret = simplejson.MustDumpString(v)
	if unq {
		ret, _ = unquote(strings.TrimSpace(ret), '"')
	}

	return
}
479713
func formatData(value interface{}) (formatted interface{}) {
	switch value := value.(type) {
	case json.Marshaler:
		return value
	case error:
		return value.Error()
	case fmt.Stringer:
		return value.String()
	default:
		return value
	}
}
448268
func ParseHTTPFormOptions(r *http.Request) (bool, *JSONOutput) {
	_, unsafe := r.Form["unsafe"]
	v, json := r.Form["json"]
	var pretty bool
	if len(v) > 0 {
		pretty = v[0] == "pretty"
	}
	return unsafe, &JSONOutput{enable: json, prettyPrint: pretty}
}