...

Source file src/github.com/sigstore/timestamp-authority/cmd/timestamp-cli/app/format/wrap.go

Documentation: github.com/sigstore/timestamp-authority/cmd/timestamp-cli/app/format

     1  //
     2  // Copyright 2022 The Sigstore 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  package format
    17  
    18  import (
    19  	"encoding/json"
    20  	"fmt"
    21  
    22  	"github.com/sigstore/timestamp-authority/pkg/log"
    23  	"github.com/spf13/cobra"
    24  	"github.com/spf13/viper"
    25  )
    26  
    27  type CobraCmd func(cmd *cobra.Command, args []string)
    28  
    29  type formatCmd func(args []string) (interface{}, error)
    30  
    31  func WrapCmd(f formatCmd) CobraCmd {
    32  	return func(cmd *cobra.Command, args []string) {
    33  		obj, err := f(args)
    34  		if err != nil {
    35  			log.CliLogger.Fatal(err)
    36  		}
    37  
    38  		// TODO: add flags to control output formatting (JSON, plaintext, etc.)
    39  		format := viper.GetString("format")
    40  		switch format {
    41  		case "default":
    42  			if s, ok := obj.(fmt.Stringer); ok {
    43  				fmt.Print(s.String())
    44  			} else {
    45  				fmt.Println(toJSON(s))
    46  			}
    47  		case "json":
    48  			fmt.Println(toJSON(obj))
    49  		}
    50  	}
    51  }
    52  
    53  func toJSON(i interface{}) string {
    54  	b, err := json.Marshal(i)
    55  	if err != nil {
    56  		log.CliLogger.Fatal(err)
    57  	}
    58  	return string(b)
    59  }
    60  

View as plain text