parseExamplesFromLong extracts the indented invocation lines that follow an "Examples:" header in a cobra Long string. Returns nil when no such section exists or no example lines are found. The block ends at: - a blank line after at least one example was collected, OR - an unindented line after at
(long string)
| 198 | // Comment lines (starting with `#`) inside the block are dropped. |
| 199 | // Used as a fallback in buildCommand when cmd.Example is empty. |
| 200 | func parseExamplesFromLong(long string) []Example { |
| 201 | if long == "" { |
| 202 | return nil |
| 203 | } |
| 204 | lines := strings.Split(long, "\n") |
| 205 | |
| 206 | startIdx := -1 |
| 207 | for i, line := range lines { |
| 208 | if examplesHeaderRE.MatchString(line) { |
| 209 | startIdx = i + 1 |
| 210 | break |
| 211 | } |
| 212 | } |
| 213 | if startIdx < 0 { |
| 214 | return nil |
| 215 | } |
| 216 | |
| 217 | var examples []Example |
| 218 | for i := startIdx; i < len(lines); i++ { |
| 219 | line := lines[i] |
| 220 | trimmed := strings.TrimSpace(line) |
| 221 | |
| 222 | // Blank line: end of block if we already collected something. |
| 223 | // Skip otherwise (the section may start with a blank line). |
| 224 | if trimmed == "" { |
| 225 | if len(examples) > 0 { |
| 226 | break |
| 227 | } |
| 228 | continue |
| 229 | } |
| 230 | // Comment lines are dropped from the example set. |
| 231 | if strings.HasPrefix(trimmed, "#") { |
| 232 | continue |
| 233 | } |
| 234 | // Unindented line after we started collecting → end of block. |
| 235 | // Detected as: the trimmed text equals the original (no leading |
| 236 | // whitespace was stripped). |
| 237 | if line == trimmed && len(examples) > 0 { |
| 238 | break |
| 239 | } |
| 240 | // Strip a trailing same-line comment (" # blah") so it doesn't |
| 241 | // pollute the recorded example. Pad's existing Long blocks use |
| 242 | // this idiom occasionally, e.g. |
| 243 | // pad attachment list --item TASK-5 # one item's attachments |
| 244 | if hashIdx := stripCommentIndex(trimmed); hashIdx >= 0 { |
| 245 | trimmed = strings.TrimRight(trimmed[:hashIdx], " \t") |
| 246 | } |
| 247 | if trimmed == "" { |
| 248 | continue |
| 249 | } |
| 250 | examples = append(examples, Example{Cmd: trimmed}) |
| 251 | } |
| 252 | if len(examples) == 0 { |
| 253 | return nil |
| 254 | } |
| 255 | return examples |
| 256 | } |
| 257 |