generate.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package main
  14. import (
  15. "fmt"
  16. "os"
  17. "path/filepath"
  18. clidocstool "github.com/docker/cli-docs-tool"
  19. "github.com/docker/cli/cli/command"
  20. "github.com/docker/compose/v2/cmd/compose"
  21. "github.com/spf13/cobra"
  22. )
  23. func generateDocs(opts *options) error {
  24. dockerCLI, err := command.NewDockerCli()
  25. if err != nil {
  26. return err
  27. }
  28. cmd := &cobra.Command{
  29. Use: "docker",
  30. DisableAutoGenTag: true,
  31. }
  32. cmd.AddCommand(compose.RootCommand(dockerCLI, nil))
  33. disableFlagsInUseLine(cmd)
  34. tool, err := clidocstool.New(clidocstool.Options{
  35. Root: cmd,
  36. SourceDir: opts.source,
  37. TargetDir: opts.target,
  38. Plugin: true,
  39. })
  40. if err != nil {
  41. return err
  42. }
  43. return tool.GenAllTree()
  44. }
  45. func disableFlagsInUseLine(cmd *cobra.Command) {
  46. visitAll(cmd, func(ccmd *cobra.Command) {
  47. // do not add a `[flags]` to the end of the usage line.
  48. ccmd.DisableFlagsInUseLine = true
  49. })
  50. }
  51. // visitAll will traverse all commands from the root.
  52. // This is different from the VisitAll of cobra.Command where only parents
  53. // are checked.
  54. func visitAll(root *cobra.Command, fn func(*cobra.Command)) {
  55. for _, cmd := range root.Commands() {
  56. visitAll(cmd, fn)
  57. }
  58. fn(root)
  59. }
  60. type options struct {
  61. source string
  62. target string
  63. }
  64. func main() {
  65. cwd, _ := os.Getwd()
  66. opts := &options{
  67. source: filepath.Join(cwd, "docs", "reference"),
  68. target: filepath.Join(cwd, "docs", "reference"),
  69. }
  70. fmt.Printf("Project root: %s\n", opts.source)
  71. fmt.Printf("Generating yaml files into %s\n", opts.target)
  72. if err := generateDocs(opts); err != nil {
  73. _, _ = fmt.Fprintf(os.Stderr, "Failed to generate documentation: %s\n", err.Error())
  74. }
  75. }