github.com/GoogleContainerTools/skaffold@v1.39.18/pkg/skaffold/output/format/format.go (about)

     1  /*
     2  Copyright 2021 The Skaffold Authors
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package format
    18  
    19  import (
    20  	"encoding/json"
    21  	"errors"
    22  	"io"
    23  
    24  	sErrors "github.com/GoogleContainerTools/skaffold/pkg/skaffold/errors"
    25  	"github.com/GoogleContainerTools/skaffold/proto/v1"
    26  )
    27  
    28  type Formatter interface {
    29  	Write(interface{}) error
    30  	WriteErr(error) error
    31  }
    32  
    33  type JSONFormatter struct {
    34  	Out io.Writer
    35  }
    36  
    37  func (j JSONFormatter) Write(data interface{}) error {
    38  	return json.NewEncoder(j.Out).Encode(data)
    39  }
    40  
    41  type jsonErrorOutput struct {
    42  	ErrorCode    string `json:"errorCode"`
    43  	ErrorMessage string `json:"errorMessage"`
    44  }
    45  
    46  func (j JSONFormatter) WriteErr(err error) error {
    47  	var sErr sErrors.Error
    48  	var jsonErr jsonErrorOutput
    49  	if errors.As(err, &sErr) {
    50  		jsonErr = jsonErrorOutput{ErrorCode: sErr.StatusCode().String(), ErrorMessage: sErr.Error()}
    51  	} else {
    52  		jsonErr = jsonErrorOutput{ErrorCode: proto.StatusCode_INSPECT_UNKNOWN_ERR.String(), ErrorMessage: err.Error()}
    53  	}
    54  	return json.NewEncoder(j.Out).Encode(jsonErr)
    55  }