github.com/kristofferahl/go-centry@v1.5.0/cmd/centry/docs.go (about)

     1  package main
     2  
     3  import (
     4  	"bufio"
     5  	"fmt"
     6  	"os"
     7  
     8  	"github.com/kristofferahl/go-centry/internal/pkg/config"
     9  	"github.com/sirupsen/logrus"
    10  	"github.com/urfave/cli/v2"
    11  )
    12  
    13  // GenerateMarkdownCommand is a Command implementation that generates markdown documentation
    14  type GenerateMarkdownCommand struct {
    15  	CLI      *cli.App
    16  	Manifest *config.Manifest
    17  	Log      *logrus.Entry
    18  }
    19  
    20  // ToCLICommand returns a CLI command
    21  func (sc *GenerateMarkdownCommand) ToCLICommand() *cli.Command {
    22  	return withCommandDefaults(&cli.Command{
    23  		Name:      "generate-markdown",
    24  		Usage:     "Generate markdown documentation",
    25  		UsageText: "",
    26  		Hidden:    false,
    27  		Action: func(c *cli.Context) error {
    28  			ec := sc.Run(c.Path("file"))
    29  			if ec > 0 {
    30  				return cli.Exit("failed to generate markdown documentation", ec)
    31  			}
    32  			return nil
    33  		},
    34  		Flags: []cli.Flag{
    35  			&cli.PathFlag{
    36  				Name:    "file",
    37  				Aliases: []string{"f"},
    38  				Usage:   "Outputs the generated markedown to the specified file",
    39  			},
    40  		},
    41  	})
    42  }
    43  
    44  // Run generates markdown documentation
    45  func (sc *GenerateMarkdownCommand) Run(path string) int {
    46  	sc.Log.Debugf("generating markdown documenation")
    47  
    48  	md, err := sc.CLI.ToMarkdown()
    49  	if err != nil {
    50  		sc.Log.Error(err)
    51  		return 1
    52  	}
    53  
    54  	if path == "" {
    55  		fmt.Print(md)
    56  		sc.Log.Debugf("generated markdown documenation to stdout")
    57  	} else {
    58  		file, err := os.Create(path)
    59  		if err != nil {
    60  			sc.Log.Error(err)
    61  			return 1
    62  		}
    63  		defer file.Close()
    64  
    65  		w := bufio.NewWriter(file)
    66  		bc, err := w.WriteString(md)
    67  		if err != nil {
    68  			sc.Log.Error(err)
    69  			return 1
    70  		}
    71  		sc.Log.Tracef("wrote %d bytes", bc)
    72  
    73  		err = w.Flush()
    74  		if err != nil {
    75  			sc.Log.Error(err)
    76  			return 1
    77  		}
    78  
    79  		sc.Log.Infof("generated markdown documenation to file (path=%s)", path)
    80  	}
    81  
    82  	return 0
    83  }