-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
docgen.go
256 lines (213 loc) · 7.1 KB
/
docgen.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
/*
Copyright 2022 The Vitess Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package docgen provides common logic for generating markdown doctrees from
// a root cobra.Command for the vitessio/website repository.
//
// Example usage:
//
// package main
//
// import (
// "github.com/spf13/cobra"
//
// "vitess.io/vitess/go/cmd/internal/docgen"
// vtctldclient "vitess.io/vitess/go/cmd/vtctldclient/command"
// )
//
// func main() {
// cmd := &cobra.Command{
// RunE: func(cmd *cobra.Command, args []string) error {
// dir := cmd.Flags().Arg(0)
// return docgen.GenerateMarkdownTree(vtctldclient.Root, dir)
// }
// Args: cobra.ExactArgs(1),
// }
//
// cmd.Execute()
// }
package docgen
import (
"errors"
"fmt"
"io/fs"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"github.com/spf13/cobra"
"github.com/spf13/cobra/doc"
)
// GenerateMarkdownTree generates a markdown doctree for the root cobra.Command
// written to `dir`. The root command is also renamed to _index.md to remain
// compatible with the vitessio/website content structure expectations.
func GenerateMarkdownTree(cmd *cobra.Command, dir string) error {
sha, err := getCommitID("HEAD")
if err != nil {
return fmt.Errorf("failed to get commit id for HEAD: %w", err)
}
switch fi, err := os.Stat(dir); {
case errors.Is(err, fs.ErrNotExist):
if err := os.MkdirAll(dir, 0755); err != nil {
return err
}
case err != nil:
return err
case !fi.IsDir():
return fmt.Errorf("%s exists but is not a directory", dir)
}
recursivelyDisableAutoGenTags(cmd)
if err := doc.GenMarkdownTreeCustom(cmd, dir, frontmatterFilePrepender(sha), linkHandler); err != nil {
return err
}
rootDocPath := filepath.Join(dir, cmd.Name()+".md")
indexDocPath := filepath.Join(dir, "_index.md")
if err := os.Rename(rootDocPath, indexDocPath); err != nil {
return fmt.Errorf("failed to index doc (generated at %s) into proper position (%s): %w", rootDocPath, indexDocPath, err)
}
if err := anonymizeHomedir(indexDocPath); err != nil {
return fmt.Errorf("failed to anonymize homedir in help text for command %s: %w", indexDocPath, err)
}
if err := restructure(dir, dir, cmd.Name(), cmd.Commands()); err != nil {
return err
}
return nil
}
/*
_index.md (aka vtctldclient.md)
vtctldclient_AddCellInfo.md
vtctldclient_movetables.md
vtctldclient_movetables_show.md
becomes
_index.md
vtctldclient_AddCellInfo.md
vtctldclient_movetables/
_index.md
vtctldclient_movetables_show.md
*/
func restructure(rootDir string, dir string, name string, commands []*cobra.Command) error {
for _, cmd := range commands {
fullCmdFilename := strings.Join([]string{name, cmd.Name()}, "_")
children := cmd.Commands()
switch {
case len(children) > 0:
// Command (top-level or not) with children.
// 1. Set up a directory for its children.
// 2. Move its doc into that dir as "_index.md"
// 3. Restructure its children.
cmdDir := filepath.Join(dir, fullCmdFilename)
if err := os.MkdirAll(cmdDir, 0755); err != nil {
return fmt.Errorf("failed to create subdir for %s: %w", fullCmdFilename, err)
}
indexFile := filepath.Join(cmdDir, "_index.md")
if err := os.Rename(filepath.Join(rootDir, fullCmdFilename+".md"), indexFile); err != nil {
return fmt.Errorf("failed to move index doc for command %s with children: %w", fullCmdFilename, err)
}
if err := anonymizeHomedir(indexFile); err != nil {
return fmt.Errorf("failed to anonymize homedir in help text for command %s: %w", indexFile, err)
}
if err := restructure(rootDir, cmdDir, fullCmdFilename, children); err != nil {
return fmt.Errorf("failed to restructure child commands for %s: %w", fullCmdFilename, err)
}
case rootDir != dir:
// Sub-command without children.
// 1. Move its doc into the directory for its parent, name unchanged.
if cmd.Name() == "help" {
// all commands with children have their own "help" subcommand,
// which we do not generate docs for
continue
}
oldName := filepath.Join(rootDir, fullCmdFilename+".md")
newName := filepath.Join(dir, fullCmdFilename+".md")
if err := os.Rename(oldName, newName); err != nil {
return fmt.Errorf("failed to move child command %s to its parent's dir: %w", fullCmdFilename, err)
}
sed := newParentLinkSedCommand(name, newName)
if out, err := sed.CombinedOutput(); err != nil {
return fmt.Errorf("failed to rewrite links to parent command in child %s: %w (extra: %s)", newName, err, out)
}
if err := anonymizeHomedir(newName); err != nil {
return fmt.Errorf("failed to anonymize homedir in help text for command %s: %w", newName, err)
}
default:
// Top-level command without children. Nothing to restructure.
continue
}
}
return nil
}
func newParentLinkSedCommand(parent string, file string) *exec.Cmd {
return exec.Command("sed", "-i", "", "-e", fmt.Sprintf("s:(./%s/):(../):i", parent), file)
}
var (
wd string
once sync.Once
)
func anonymizeHomedir(file string) (err error) {
once.Do(func() {
// Only do this once per run.
wd, err = os.Getwd()
})
if err != nil {
return err
}
// We're replacing the stuff inside the square brackets in the example sed
// below:
// 's:Paths to search for config files in. (default \[.*\])$:Paths to search for config files in. (default \[<WORKDIR>\]):'
sed := exec.Command("sed", "-i", "", "-e", fmt.Sprintf("s:%s:<WORKDIR>:i", wd), file)
if out, err := sed.CombinedOutput(); err != nil {
return fmt.Errorf("%w: %s", err, out)
}
return nil
}
func recursivelyDisableAutoGenTags(root *cobra.Command) {
commands := []*cobra.Command{root}
for cmd := commands[0]; len(commands) > 0; cmd, commands = commands[0], commands[1:] {
cmd.DisableAutoGenTag = true
commands = append(commands, cmd.Commands()...)
}
}
func getCommitID(ref string) (string, error) {
gitShow := exec.Command("git", "show", "--pretty=format:%H", "--no-patch", ref)
out, err := gitShow.Output()
if err != nil {
return "", err
}
return string(out), nil
}
const frontmatter = `---
title: %s
series: %s
commit: %s
---
`
func frontmatterFilePrepender(sha string) func(filename string) string {
return func(filename string) string {
name := filepath.Base(filename)
base := strings.TrimSuffix(name, filepath.Ext(name))
root, cmdName, ok := strings.Cut(base, "_")
if !ok { // no `_`, so not a subcommand
cmdName = root
}
cmdName = strings.ReplaceAll(cmdName, "_", " ")
return fmt.Sprintf(frontmatter, cmdName, root, sha)
}
}
func linkHandler(filename string) string {
name := filepath.Base(filename)
base := strings.TrimSuffix(name, filepath.Ext(name))
if _, _, ok := strings.Cut(base, "_"); !ok {
return "../"
}
return fmt.Sprintf("./%s/", strings.ToLower(base))
}