github.com/kaisawind/go-swagger@v0.19.0/cmd/swagger/commands/expand.go (about)

     1  package commands
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  	"fmt"
     7  	"io/ioutil"
     8  
     9  	"github.com/go-openapi/loads"
    10  	"github.com/go-openapi/spec"
    11  	"github.com/go-openapi/swag"
    12  	flags "github.com/jessevdk/go-flags"
    13  	yaml "gopkg.in/yaml.v2"
    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("The 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  	if pretty && asJSON {
    51  		b, err = json.MarshalIndent(swspec, "", "  ")
    52  	} else if asJSON {
    53  		b, err = json.Marshal(swspec)
    54  	} else {
    55  		// marshals as YAML
    56  		b, err = json.Marshal(swspec)
    57  		if err == nil {
    58  			d, ery := swag.BytesToYAMLDoc(b)
    59  			if ery != nil {
    60  				return ery
    61  			}
    62  			b, err = yaml.Marshal(d)
    63  		}
    64  	}
    65  	if err != nil {
    66  		return err
    67  	}
    68  	if output == "" {
    69  		fmt.Println(string(b))
    70  		return nil
    71  	}
    72  	return ioutil.WriteFile(output, b, 0644)
    73  }