...

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

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

     1  //
     2  // Copyright 2021 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  	rekor_pb "github.com/sigstore/protobuf-specs/gen/pb-go/rekor/v1"
    23  
    24  	"github.com/sigstore/rekor/pkg/log"
    25  	tleutils "github.com/sigstore/rekor/pkg/tle"
    26  	"github.com/spf13/cobra"
    27  	"github.com/spf13/viper"
    28  )
    29  
    30  type CobraCmd func(cmd *cobra.Command, args []string)
    31  
    32  type formatCmd func(args []string) (interface{}, error)
    33  
    34  func WrapCmd(f formatCmd) CobraCmd {
    35  	return func(_ *cobra.Command, args []string) {
    36  		obj, err := f(args)
    37  		if err != nil {
    38  			log.CliLogger.Fatal(err)
    39  		}
    40  
    41  		// TODO: add flags to control output formatting (JSON, plaintext, etc.)
    42  		format := viper.GetString("format")
    43  		switch format {
    44  		case "default":
    45  			if s, ok := obj.(fmt.Stringer); ok {
    46  				fmt.Print(s.String())
    47  			} else {
    48  				fmt.Println(toJSON(s))
    49  			}
    50  		case "json":
    51  			fmt.Println(toJSON(obj))
    52  		case "tle":
    53  			if tle, ok := obj.(*rekor_pb.TransparencyLogEntry); ok {
    54  				json, err := tleutils.MarshalTLEToJSON(tle)
    55  				if err != nil {
    56  					log.CliLogger.Fatalf("error converting to transparency log entry: %v", err)
    57  				}
    58  				fmt.Println(string(json))
    59  			} else {
    60  				log.CliLogger.Fatal("unable to print transparency log entry")
    61  			}
    62  		}
    63  	}
    64  }
    65  
    66  func toJSON(i interface{}) string {
    67  	b, err := json.Marshal(i)
    68  	if err != nil {
    69  		log.CliLogger.Fatal(err)
    70  	}
    71  	return string(b)
    72  }
    73  

View as plain text