|
| 1 | +/* |
| 2 | +Copyright 2026 The Crossplane Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +// examples-gen fills the outputs of the examples of markdown files, see docs/contributing/examples-gen.md. |
| 18 | +package main |
| 19 | + |
| 20 | +import ( |
| 21 | + "errors" |
| 22 | + "fmt" |
| 23 | + "os" |
| 24 | + "os/exec" |
| 25 | + "strings" |
| 26 | + |
| 27 | + "github.com/alecthomas/kong" |
| 28 | +) |
| 29 | + |
| 30 | +const ( |
| 31 | + prompt = "➜ " |
| 32 | + placeholder = "<output>" |
| 33 | + codeBlock = "```" |
| 34 | + tagPrefix = "<!-- examples-gen: " |
| 35 | + tagSuffix = " -->" |
| 36 | +) |
| 37 | + |
| 38 | +// cli is the command line of the tool. |
| 39 | +type cli struct { |
| 40 | + Files []string `arg:"" help:"Markdown files whose examples are filled." type:"existingfile"` |
| 41 | + RegenerateAll bool `help:"Regenerate the outputs of every command, not only the ones that have a placeholder." name:"regenerate-all" xor:"regenerate"` |
| 42 | + RegenerateMatch string `help:"Regenerate the outputs of the commands that contain this text." name:"regenerate-match" xor:"regenerate"` |
| 43 | + Tag string `help:"Fill the code blocks that have this tag, instead of the ones that have none." name:"tag"` |
| 44 | +} |
| 45 | + |
| 46 | +func main() { |
| 47 | + var args cli |
| 48 | + |
| 49 | + kong.Parse(&args, |
| 50 | + kong.Name("examples-gen"), |
| 51 | + kong.Description("Fill the outputs of the examples of markdown files."), |
| 52 | + kong.UsageOnError(), |
| 53 | + ) |
| 54 | + |
| 55 | + update := func(content string) (string, error) { |
| 56 | + // To regenerate an output, the placeholder goes in its place first |
| 57 | + if args.RegenerateAll || args.RegenerateMatch != "" { |
| 58 | + content = clearOutputs(content, args.RegenerateMatch, args.Tag) |
| 59 | + } |
| 60 | + |
| 61 | + return fill(content, args.Tag, runCommand) |
| 62 | + } |
| 63 | + |
| 64 | + for _, path := range args.Files { |
| 65 | + if err := updateFile(path, update); err != nil { |
| 66 | + fmt.Fprintf(os.Stderr, "examples-gen: %s: %v\n", path, err) |
| 67 | + os.Exit(1) |
| 68 | + } |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +// updateFile replaces the content of the file with what update returns for it. |
| 73 | +func updateFile(path string, update func(content string) (string, error)) error { |
| 74 | + data, err := os.ReadFile(path) //nolint:gosec // G304 - the path is an argument of the maintainer who runs the tool |
| 75 | + if err != nil { |
| 76 | + return fmt.Errorf("read: %w", err) |
| 77 | + } |
| 78 | + |
| 79 | + filled, err := update(string(data)) |
| 80 | + if err != nil { |
| 81 | + return err |
| 82 | + } |
| 83 | + |
| 84 | + info, err := os.Stat(path) |
| 85 | + if err != nil { |
| 86 | + return fmt.Errorf("stat: %w", err) |
| 87 | + } |
| 88 | + |
| 89 | + if err := os.WriteFile(path, []byte(filled), info.Mode().Perm()); err != nil { |
| 90 | + return fmt.Errorf("write: %w", err) |
| 91 | + } |
| 92 | + |
| 93 | + return nil |
| 94 | +} |
| 95 | + |
| 96 | +// fill puts the output of run in place of the placeholder after each command, in the code blocks that have the tag. |
| 97 | +func fill(content, tag string, run func(command string) (string, error)) (string, error) { |
| 98 | + lines := strings.Split(content, "\n") |
| 99 | + filled := make([]string, 0, len(lines)) |
| 100 | + inFence := false |
| 101 | + tagged := false |
| 102 | + |
| 103 | + for i := 0; i < len(lines); i++ { |
| 104 | + line := lines[i] |
| 105 | + filled = append(filled, line) |
| 106 | + |
| 107 | + if strings.HasPrefix(line, codeBlock) { |
| 108 | + inFence = !inFence |
| 109 | + tagged = inFence && i > 0 && blockTag(lines[i-1]) == tag |
| 110 | + |
| 111 | + continue |
| 112 | + } |
| 113 | + |
| 114 | + command, isCommand := strings.CutPrefix(line, prompt) |
| 115 | + if !inFence || !tagged || !isCommand || i+1 >= len(lines) || lines[i+1] != placeholder { |
| 116 | + continue |
| 117 | + } |
| 118 | + |
| 119 | + fmt.Fprintf(os.Stderr, "running: %s\n", command) |
| 120 | + |
| 121 | + output, err := run(command) |
| 122 | + if err != nil { |
| 123 | + return "", fmt.Errorf("%q: %w", command, err) |
| 124 | + } |
| 125 | + |
| 126 | + if output != "" { |
| 127 | + filled = append(filled, strings.Split(output, "\n")...) |
| 128 | + } |
| 129 | + |
| 130 | + // The placeholder is replaced by the output |
| 131 | + i++ |
| 132 | + } |
| 133 | + |
| 134 | + return strings.Join(filled, "\n"), nil |
| 135 | +} |
| 136 | + |
| 137 | +// clearOutputs puts the placeholder in place of the outputs of the commands that contain match, in the tagged blocks. |
| 138 | +func clearOutputs(content, match, tag string) string { |
| 139 | + lines := strings.Split(content, "\n") |
| 140 | + cleared := make([]string, 0, len(lines)) |
| 141 | + inFence := false |
| 142 | + tagged := false |
| 143 | + |
| 144 | + for i := 0; i < len(lines); i++ { |
| 145 | + line := lines[i] |
| 146 | + cleared = append(cleared, line) |
| 147 | + |
| 148 | + if strings.HasPrefix(line, codeBlock) { |
| 149 | + inFence = !inFence |
| 150 | + tagged = inFence && i > 0 && blockTag(lines[i-1]) == tag |
| 151 | + |
| 152 | + continue |
| 153 | + } |
| 154 | + |
| 155 | + command, isCommand := strings.CutPrefix(line, prompt) |
| 156 | + if !inFence || !tagged || !isCommand || !strings.Contains(command, match) { |
| 157 | + continue |
| 158 | + } |
| 159 | + |
| 160 | + cleared = append(cleared, placeholder) |
| 161 | + |
| 162 | + // The output goes on until the next command, or the end of the block |
| 163 | + next := i + 1 |
| 164 | + for next < len(lines) && !strings.HasPrefix(lines[next], prompt) && !strings.HasPrefix(lines[next], codeBlock) { |
| 165 | + next++ |
| 166 | + } |
| 167 | + |
| 168 | + if next < len(lines) && strings.HasPrefix(lines[next], prompt) && next > i+1 && lines[next-1] == "" { |
| 169 | + cleared = append(cleared, "") |
| 170 | + } |
| 171 | + |
| 172 | + i = next - 1 |
| 173 | + } |
| 174 | + |
| 175 | + return strings.Join(cleared, "\n") |
| 176 | +} |
| 177 | + |
| 178 | +// blockTag returns the tag of the line before a code block, or an empty string when the line is not a tag. |
| 179 | +func blockTag(line string) string { |
| 180 | + tag, found := strings.CutPrefix(line, tagPrefix) |
| 181 | + if !found { |
| 182 | + return "" |
| 183 | + } |
| 184 | + |
| 185 | + return strings.TrimSuffix(tag, tagSuffix) |
| 186 | +} |
| 187 | + |
| 188 | +// runCommand returns the output of the command in a shell, ignoring its exit status: a failing test is a valid example. |
| 189 | +func runCommand(command string) (string, error) { |
| 190 | + cmd := exec.Command("sh", "-c", command) //nolint:gosec // The commands are the ones of the examples, written by the maintainers |
| 191 | + |
| 192 | + output, err := cmd.CombinedOutput() |
| 193 | + |
| 194 | + var exitErr *exec.ExitError |
| 195 | + if err != nil && !errors.As(err, &exitErr) { |
| 196 | + return "", err |
| 197 | + } |
| 198 | + |
| 199 | + return strings.TrimRight(string(output), "\n"), nil |
| 200 | +} |
0 commit comments