github.com/josephspurrier/go-swagger@v0.2.1-0.20221129144919-1f672a142a00/cmd/swagger/commands/expand.go (about)

     1  package commands
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  	"fmt"
     7  	"log"
     8  	"os"
     9  
    10  	"github.com/go-openapi/loads"
    11  	"github.com/go-openapi/spec"
    12  	"github.com/go-openapi/swag"
    13  	flags "github.com/jessevdk/go-flags"
    14  )
    15  
    16  // ExpandSpec is a command that expands the $refs in a swagger document.
    17  //
    18  // There are no specific options for this expansion.
    19  type ExpandSpec struct {
    20  	Compact bool           `long:"compact" description:"applies to JSON formatted specs. When present, doesn't prettify the json"`
    21  	Output  flags.Filename `long:"output" short:"o" description:"the file to write to"`
    22  	Format  string         `long:"format" description:"the format for the spec document" default:"json" choice:"yaml" choice:"json"`
    23  }
    24  
    25  // Execute expands the spec
    26  func (c *ExpandSpec) Execute(args []string) error {
    27  	if len(args) != 1 {
    28  		return errors.New("expand command requires the single swagger document url to be specified")
    29  	}
    30  
    31  	swaggerDoc := args[0]
    32  	specDoc, err := loads.Spec(swaggerDoc)
    33  	if err != nil {
    34  		return err
    35  	}
    36  
    37  	exp, err := specDoc.Expanded()
    38  	if err != nil {
    39  		return err
    40  	}
    41  
    42  	return writeToFile(exp.Spec(), !c.Compact, c.Format, string(c.Output))
    43  }
    44  
    45  func writeToFile(swspec *spec.Swagger, pretty bool, format string, output string) error {
    46  	var b []byte
    47  	var err error
    48  	asJSON := format == "json"
    49  
    50  	log.Println("format = ", format)
    51  	switch {
    52  	case pretty && asJSON:
    53  		b, err = json.MarshalIndent(swspec, "", "  ")
    54  	case asJSON:
    55  		b, err = json.Marshal(swspec)
    56  	default:
    57  		// marshals as YAML
    58  		b, err = json.Marshal(swspec)
    59  		if err == nil {
    60  			var data swag.JSONMapSlice
    61  			if erg := json.Unmarshal(b, &data); erg != nil {
    62  				log.Fatalln(erg)
    63  			}
    64  			var bb interface{}
    65  			bb, err = data.MarshalYAML()
    66  			b = bb.([]byte)
    67  		}
    68  
    69  	}
    70  
    71  	if err != nil {
    72  		return err
    73  	}
    74  
    75  	if output == "" {
    76  		fmt.Println(string(b))
    77  		return nil
    78  	}
    79  
    80  	return os.WriteFile(output, b, 0644) // #nosec
    81  }