get.porter.sh/porter@v1.3.0/pkg/docs/generator.go (about) 1 package docs 2 3 import ( 4 "fmt" 5 "os" 6 "path" 7 "path/filepath" 8 "strings" 9 10 "get.porter.sh/porter/pkg/portercontext" 11 "github.com/spf13/cobra" 12 "github.com/spf13/cobra/doc" 13 ) 14 15 type DocsOptions struct { 16 RootCommand *cobra.Command 17 Destination string 18 } 19 20 const DefaultDestination = "./docs/content/docs/references/cli" 21 22 func (o *DocsOptions) Validate(cxt *portercontext.Context) error { 23 if o.Destination == "" { 24 o.Destination = DefaultDestination 25 } 26 27 exists, err := cxt.FileSystem.Exists(o.Destination) 28 if err != nil { 29 return fmt.Errorf("error checking if --destination exists: %q: %w", o.Destination, err) 30 } 31 if !exists { 32 return fmt.Errorf("--destination %q doesn't exist", o.Destination) 33 } 34 35 return nil 36 } 37 38 func GenerateCliDocs(opts *DocsOptions) error { 39 opts.RootCommand.DisableAutoGenTag = true 40 41 err := doc.GenMarkdownTreeCustom(opts.RootCommand, opts.Destination, docfileHandler(), doclinkHandler()) 42 if err != nil { 43 return fmt.Errorf("error generating the markdown documentation from the cli: %w", err) 44 } 45 46 // Strip off the leading porter_ from every file 47 items, err := filepath.Glob(filepath.Join(opts.Destination, "porter_*.md")) 48 if err != nil { 49 return fmt.Errorf("unable to list generated cli docs directory %q: %w", opts.Destination, err) 50 } 51 52 for _, i := range items { 53 inew := strings.Replace(i, "porter_", "", -1) 54 err := os.Rename(i, inew) 55 if err != nil { 56 return fmt.Errorf("unable to rename markdown file: %w", err) 57 } 58 } 59 return nil 60 } 61 62 func docfileHandler() func(string) string { 63 const fmTemplate = `--- 64 title: "%s" 65 slug: %s 66 url: %s 67 --- 68 ` 69 70 filePrepender := func(filename string) string { 71 name := filepath.Base(filename) 72 base := strings.TrimSuffix(name, path.Ext(name)) 73 url := "/cli/" + strings.ToLower(base) + "/" 74 return fmt.Sprintf(fmTemplate, strings.Replace(base, "_", " ", -1), base, url) 75 } 76 return filePrepender 77 } 78 79 func doclinkHandler() func(string) string { 80 linkHandler := func(name string) string { 81 base := strings.TrimSuffix(name, path.Ext(name)) 82 return "/cli/" + strings.ToLower(base) + "/" 83 } 84 return linkHandler 85 }