Debian Codegraph @

shoutrrr/cmd/docs/docs.go

raw
1 // Package docs provides the "docs" CLI command for generating documentation
2 // for Shoutrrr notification services.
3 package docs
4
5 import (
6 "fmt"
7 "log"
8 "net/url"
9 "os"
10 "strings"
11
12 "github.com/spf13/cobra"
13
14 "github.com/nicholas-fedor/shoutrrr/pkg/format"
15 "github.com/nicholas-fedor/shoutrrr/pkg/router"
16 "github.com/nicholas-fedor/shoutrrr/shoutrrr/cmd"
17 )
18
19 var (
20 // serviceRouter manages the creation and initialization of notification services.
21 serviceRouter router.ServiceRouter
22 // services contains the list of available service schemes.
23 services = serviceRouter.ListServices()
24
25 // Cmd is the cobra command for generating service documentation.
26 // It displays configuration options and documentation for specified services.
27 Cmd = &cobra.Command{
28 Use: "docs",
29 Short: "Print documentation for services",
30 Run: Run,
31 Args: func(cmd *cobra.Command, args []string) error {
32 serviceList := strings.Join(services, ", ")
33 cmd.SetUsageTemplate(
34 cmd.UsageTemplate() + "\nAvailable services: \n " + serviceList + "\n",
35 )
36
37 return cobra.MinimumNArgs(1)(cmd, args)
38 },
39 ValidArgs: services,
40 }
41 )
42
43 // init initializes the command flags for the docs command.
44 func init() {
45 Cmd.Flags().StringP("format", "f", "console", "Output format (console or markdown)")
46 }
47
48 // Run executes the docs command, generating and displaying service documentation.
49 //
50 // Parameters:
51 // - rootCmd: The cobra command containing the parsed flags.
52 // - args: The list of service schemes to document.
53 func Run(rootCmd *cobra.Command, args []string) {
54 res := runDocs(rootCmd, args)
55 if res.ExitCode != 0 {
56 fmt.Fprintf(os.Stderr, "%s", res.Message)
57 }
58
59 os.Exit(res.ExitCode)
60 }
61
62 // runDocs contains the core logic for the docs command.
63 // It is extracted from Run to enable unit testing without calling os.Exit.
64 //
65 // Parameters:
66 // - rootCmd: The cobra command containing the parsed flags.
67 // - args: The list of service schemes to document.
68 //
69 // Returns:
70 // - cmd.ExitError: An ExitError indicating success or failure with an appropriate exit code.
71 func runDocs(rootCmd *cobra.Command, args []string) cmd.ExitError {
72 formatType, err := rootCmd.Flags().GetString("format")
73 if err != nil {
74 return cmd.ExitError{
75 ExitCode: 1,
76 Message: fmt.Sprintf("Error getting format flag: %v\n", err),
77 }
78 }
79
80 return printDocs(formatType, args)
81 }
82
83 // printDocs generates documentation for the specified services in the requested format.
84 //
85 // Parameters:
86 // - docFormat: The output format ("console" or "markdown").
87 // - services: The list of service schemes to document.
88 //
89 // Returns:
90 // - cmd.ExitError: An ExitError indicating success or failure with an appropriate exit code.
91 func printDocs(docFormat string, services []string) cmd.ExitError {
92 var renderer format.TreeRenderer
93
94 // Select the appropriate renderer based on the requested format.
95 switch docFormat {
96 case "console":
97 renderer = format.ConsoleTreeRenderer{WithValues: false}
98 case "markdown":
99 renderer = format.MarkdownTreeRenderer{
100 HeaderPrefix: "### ",
101 PropsDescription: "Props can be either supplied using the params argument or through the URL using\n`?key=value&key=value` etc.\n",
102 PropsEmptyMessage: "*The services does not support any query/param props*\n",
103 }
104 default:
105 return cmd.InvalidUsage("invalid format")
106 }
107
108 // Create a logger for service initialization.
109 logger := log.New(os.Stderr, "", 0)
110
111 // Generate documentation for each requested service.
112 for _, scheme := range services {
113 service, err := serviceRouter.NewService(scheme)
114 if err != nil {
115 return cmd.InvalidUsage("failed to init service: " + err.Error())
116 }
117
118 // Initialize the service to populate Config.
119 dummyURL, err := url.Parse(scheme + "://[email protected]")
120 if err != nil {
121 return cmd.InvalidUsage("failed to parse URL: " + err.Error())
122 }
123
124 if err := service.Initialize(dummyURL, logger); err != nil {
125 return cmd.InvalidUsage(
126 fmt.Sprintf("failed to initialize service %q: %v\n", scheme, err),
127 )
128 }
129
130 config := format.GetServiceConfig(service)
131 configNode := format.GetConfigFormat(config)
132 _, _ = fmt.Fprint(os.Stdout, renderer.RenderTree(configNode, scheme))
133 }
134
135 return cmd.ErrNil
136 }