|
| 1 | +//go:build docs |
| 2 | + |
| 3 | +package cli |
| 4 | + |
| 5 | +import ( |
| 6 | + "bytes" |
| 7 | + "os" |
| 8 | + "path" |
| 9 | + "strings" |
| 10 | + |
| 11 | + "github.com/spf13/cobra" |
| 12 | + "github.com/spf13/cobra/doc" |
| 13 | +) |
| 14 | + |
| 15 | +const DispatchCmdLong = "This is the main command for Dispatch CLI. Add a subcommand to make it useful." |
| 16 | + |
| 17 | +const RunExampleText = "```\ndispatch run [options] -- <command>\n```" |
| 18 | + |
| 19 | +func generateDocs(cmd *cobra.Command, title string) { |
| 20 | + cmd.DisableAutoGenTag = true |
| 21 | + |
| 22 | + // create docs directory |
| 23 | + _ = os.Mkdir("./docs", 0755) |
| 24 | + |
| 25 | + out := new(bytes.Buffer) |
| 26 | + |
| 27 | + err := doc.GenMarkdownCustom(cmd, out, func(name string) string { |
| 28 | + // err := doc.GenMarkdownCustom(cmd, out, func(name string) string { |
| 29 | + base := strings.TrimSuffix(name, path.Ext(name)) |
| 30 | + return "/cli/" + strings.ToLower(base) + "/" |
| 31 | + }) |
| 32 | + if err != nil { |
| 33 | + panic(err) |
| 34 | + } |
| 35 | + |
| 36 | + // Define the text to be replaced and the replacement text |
| 37 | + oldText := []byte("## " + title) |
| 38 | + newText := []byte("---\ntitle: " + title + "\n---") |
| 39 | + |
| 40 | + // Perform the replacement on the buffer's content |
| 41 | + updatedContent := bytes.Replace(out.Bytes(), oldText, newText, 1) |
| 42 | + |
| 43 | + // Reset the buffer and write the updated content back to it |
| 44 | + out.Reset() |
| 45 | + out.Write(updatedContent) |
| 46 | + |
| 47 | + // write markdown to file |
| 48 | + file, err := os.Create("./docs/" + strings.ReplaceAll(title, " ", "_") + ".md") |
| 49 | + if err != nil { |
| 50 | + panic(err) |
| 51 | + } |
| 52 | + |
| 53 | + _, err = file.Write(out.Bytes()) |
| 54 | + if err != nil { |
| 55 | + panic(err) |
| 56 | + } |
| 57 | + |
| 58 | + defer file.Close() |
| 59 | + |
| 60 | + // if command has subcommands, generate markdown for each subcommand |
| 61 | + if cmd.HasSubCommands() { |
| 62 | + for _, c := range cmd.Commands() { |
| 63 | + // if c.Use starts with "help", skip it |
| 64 | + if c.Name() == "help" { |
| 65 | + continue |
| 66 | + } |
| 67 | + generateDocs(c, title+" "+c.Name()) |
| 68 | + } |
| 69 | + } |
| 70 | +} |
0 commit comments