| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
package main |
| 9 |
|
| 10 |
import ( |
| 11 |
"bytes" |
| 12 |
"errors" |
| 13 |
"flag" |
| 14 |
"fmt" |
| 15 |
"io" |
| 16 |
"log" |
| 17 |
"os" |
| 18 |
"strings" |
| 19 |
|
| 20 |
"go.yaml.in/yaml/v4" |
| 21 |
) |
| 22 |
|
| 23 |
|
| 24 |
const version = "4.0.0.1" |
| 25 |
|
| 26 |
|
| 27 |
type stringSlice []string |
| 28 |
|
| 29 |
|
| 30 |
func (s *stringSlice) String() string { |
| 31 |
if s == nil { |
| 32 |
return "" |
| 33 |
} |
| 34 |
return fmt.Sprint(*s) |
| 35 |
} |
| 36 |
|
| 37 |
|
| 38 |
func (s *stringSlice) Set(value string) error { |
| 39 |
|
| 40 |
if value == "" || value == "help" || value == "?" { |
| 41 |
printAvailableOptions() |
| 42 |
os.Exit(0) |
| 43 |
} |
| 44 |
*s = append(*s, value) |
| 45 |
return nil |
| 46 |
} |
| 47 |
|
| 48 |
|
| 49 |
type optionSpec struct { |
| 50 |
typ string |
| 51 |
handler func(value string) ([]yaml.Option, error) |
| 52 |
} |
| 53 |
|
| 54 |
|
| 55 |
var optionRegistry map[string]optionSpec |
| 56 |
|
| 57 |
|
| 58 |
func initOptionRegistry() { |
| 59 |
optionRegistry = map[string]optionSpec{ |
| 60 |
|
| 61 |
"v2": {typ: "preset", handler: func(string) ([]yaml.Option, error) { |
| 62 |
return []yaml.Option{yaml.WithV2Defaults()}, nil |
| 63 |
}}, |
| 64 |
"v3": {typ: "preset", handler: func(string) ([]yaml.Option, error) { |
| 65 |
return []yaml.Option{yaml.WithV3Defaults()}, nil |
| 66 |
}}, |
| 67 |
"v4": {typ: "preset", handler: func(string) ([]yaml.Option, error) { |
| 68 |
return []yaml.Option{yaml.WithV4Defaults()}, nil |
| 69 |
}}, |
| 70 |
|
| 71 |
|
| 72 |
"indent": {typ: "int", handler: func(value string) ([]yaml.Option, error) { |
| 73 |
var val int |
| 74 |
if _, err := fmt.Sscanf(value, "%d", &val); err != nil { |
| 75 |
return nil, fmt.Errorf("indent requires integer value (2-9)") |
| 76 |
} |
| 77 |
if val < 2 || val > 9 { |
| 78 |
return nil, fmt.Errorf("indent must be between 2 and 9") |
| 79 |
} |
| 80 |
return []yaml.Option{yaml.WithIndent(val)}, nil |
| 81 |
}}, |
| 82 |
"compact-seq-indent": {typ: "bool", handler: func(value string) ([]yaml.Option, error) { |
| 83 |
val := value == "true" |
| 84 |
return []yaml.Option{yaml.WithCompactSeqIndent(val)}, nil |
| 85 |
}}, |
| 86 |
"compact": {typ: "bool", handler: func(value string) ([]yaml.Option, error) { |
| 87 |
val := value == "true" |
| 88 |
return []yaml.Option{yaml.WithCompactSeqIndent(val)}, nil |
| 89 |
}}, |
| 90 |
"line-width": {typ: "int", handler: func(value string) ([]yaml.Option, error) { |
| 91 |
var val int |
| 92 |
if _, err := fmt.Sscanf(value, "%d", &val); err != nil { |
| 93 |
return nil, fmt.Errorf("line-width requires integer value") |
| 94 |
} |
| 95 |
return []yaml.Option{yaml.WithLineWidth(val)}, nil |
| 96 |
}}, |
| 97 |
"width": {typ: "int", handler: func(value string) ([]yaml.Option, error) { |
| 98 |
var val int |
| 99 |
if _, err := fmt.Sscanf(value, "%d", &val); err != nil { |
| 100 |
return nil, fmt.Errorf("width requires integer value") |
| 101 |
} |
| 102 |
return []yaml.Option{yaml.WithLineWidth(val)}, nil |
| 103 |
}}, |
| 104 |
"unicode": {typ: "bool", handler: func(value string) ([]yaml.Option, error) { |
| 105 |
val := value == "true" |
| 106 |
return []yaml.Option{yaml.WithUnicode(val)}, nil |
| 107 |
}}, |
| 108 |
"unique-keys": {typ: "bool", handler: func(value string) ([]yaml.Option, error) { |
| 109 |
val := value == "true" |
| 110 |
return []yaml.Option{yaml.WithUniqueKeys(val)}, nil |
| 111 |
}}, |
| 112 |
"unique": {typ: "bool", handler: func(value string) ([]yaml.Option, error) { |
| 113 |
val := value == "true" |
| 114 |
return []yaml.Option{yaml.WithUniqueKeys(val)}, nil |
| 115 |
}}, |
| 116 |
"canonical": {typ: "bool", handler: func(value string) ([]yaml.Option, error) { |
| 117 |
val := value == "true" |
| 118 |
return []yaml.Option{yaml.WithCanonical(val)}, nil |
| 119 |
}}, |
| 120 |
"line-break": {typ: "string", handler: func(value string) ([]yaml.Option, error) { |
| 121 |
var lb yaml.LineBreak |
| 122 |
switch value { |
| 123 |
case "ln": |
| 124 |
lb = yaml.LineBreakLN |
| 125 |
case "cr": |
| 126 |
lb = yaml.LineBreakCR |
| 127 |
case "crln": |
| 128 |
lb = yaml.LineBreakCRLN |
| 129 |
default: |
| 130 |
return nil, fmt.Errorf("line-break must be ln, cr, or crln") |
| 131 |
} |
| 132 |
return []yaml.Option{yaml.WithLineBreak(lb)}, nil |
| 133 |
}}, |
| 134 |
"explicit-start": {typ: "bool", handler: func(value string) ([]yaml.Option, error) { |
| 135 |
val := value == "true" |
| 136 |
return []yaml.Option{yaml.WithExplicitStart(val)}, nil |
| 137 |
}}, |
| 138 |
"explicit-end": {typ: "bool", handler: func(value string) ([]yaml.Option, error) { |
| 139 |
val := value == "true" |
| 140 |
return []yaml.Option{yaml.WithExplicitEnd(val)}, nil |
| 141 |
}}, |
| 142 |
"explicit": {typ: "multi", handler: func(value string) ([]yaml.Option, error) { |
| 143 |
val := value == "true" |
| 144 |
return []yaml.Option{yaml.WithExplicitStart(val), yaml.WithExplicitEnd(val)}, nil |
| 145 |
}}, |
| 146 |
"flow-simple-coll": {typ: "bool", handler: func(value string) ([]yaml.Option, error) { |
| 147 |
val := value == "true" |
| 148 |
return []yaml.Option{yaml.WithFlowSimpleCollections(val)}, nil |
| 149 |
}}, |
| 150 |
"known-fields": {typ: "bool", handler: func(value string) ([]yaml.Option, error) { |
| 151 |
val := value == "true" |
| 152 |
return []yaml.Option{yaml.WithKnownFields(val)}, nil |
| 153 |
}}, |
| 154 |
"single-document": {typ: "bool", handler: func(value string) ([]yaml.Option, error) { |
| 155 |
val := value == "true" |
| 156 |
return []yaml.Option{yaml.WithSingleDocument(val)}, nil |
| 157 |
}}, |
| 158 |
"single": {typ: "bool", handler: func(value string) ([]yaml.Option, error) { |
| 159 |
val := value == "true" |
| 160 |
return []yaml.Option{yaml.WithSingleDocument(val)}, nil |
| 161 |
}}, |
| 162 |
"all-documents": {typ: "bool", handler: func(value string) ([]yaml.Option, error) { |
| 163 |
val := value == "true" |
| 164 |
return []yaml.Option{yaml.WithAllDocuments(val)}, nil |
| 165 |
}}, |
| 166 |
"all": {typ: "bool", handler: func(value string) ([]yaml.Option, error) { |
| 167 |
val := value == "true" |
| 168 |
return []yaml.Option{yaml.WithAllDocuments(val)}, nil |
| 169 |
}}, |
| 170 |
"stream-nodes": {typ: "bool", handler: func(value string) ([]yaml.Option, error) { |
| 171 |
val := value == "true" |
| 172 |
return []yaml.Option{yaml.WithStreamNodes(val)}, nil |
| 173 |
}}, |
| 174 |
"stream": {typ: "bool", handler: func(value string) ([]yaml.Option, error) { |
| 175 |
val := value == "true" |
| 176 |
return []yaml.Option{yaml.WithStreamNodes(val)}, nil |
| 177 |
}}, |
| 178 |
} |
| 179 |
} |
| 180 |
|
| 181 |
|
| 182 |
func parseOneOption(s string) ([]yaml.Option, error) { |
| 183 |
|
| 184 |
if s == "help" || s == "?" { |
| 185 |
printAvailableOptions() |
| 186 |
os.Exit(0) |
| 187 |
} |
| 188 |
|
| 189 |
|
| 190 |
if s == "v2" || s == "v3" || s == "v4" { |
| 191 |
spec, ok := optionRegistry[s] |
| 192 |
if !ok { |
| 193 |
return nil, fmt.Errorf("unknown option: %s", s) |
| 194 |
} |
| 195 |
return spec.handler("") |
| 196 |
} |
| 197 |
|
| 198 |
|
| 199 |
if len(s) > 3 && s[:3] == "no-" { |
| 200 |
name := s[3:] |
| 201 |
spec, ok := optionRegistry[name] |
| 202 |
if !ok { |
| 203 |
return nil, fmt.Errorf("unknown option: %s", name) |
| 204 |
} |
| 205 |
if spec.typ != "bool" && spec.typ != "multi" { |
| 206 |
return nil, fmt.Errorf("option %s is not boolean, cannot use no- prefix", name) |
| 207 |
} |
| 208 |
return spec.handler("false") |
| 209 |
} |
| 210 |
|
| 211 |
|
| 212 |
if name, value, found := strings.Cut(s, "="); found { |
| 213 |
spec, ok := optionRegistry[name] |
| 214 |
if !ok { |
| 215 |
return nil, fmt.Errorf("unknown option: %s", name) |
| 216 |
} |
| 217 |
if spec.typ == "bool" || spec.typ == "multi" { |
| 218 |
|
| 219 |
if value != "true" && value != "false" { |
| 220 |
return nil, fmt.Errorf("option %s requires true or false value", name) |
| 221 |
} |
| 222 |
} |
| 223 |
return spec.handler(value) |
| 224 |
} |
| 225 |
|
| 226 |
|
| 227 |
spec, ok := optionRegistry[s] |
| 228 |
if !ok { |
| 229 |
return nil, fmt.Errorf("unknown option: %s", s) |
| 230 |
} |
| 231 |
if spec.typ != "bool" && spec.typ != "multi" && spec.typ != "preset" { |
| 232 |
return nil, fmt.Errorf("option %s requires a value (use %s=value)", s, s) |
| 233 |
} |
| 234 |
return spec.handler("true") |
| 235 |
} |
| 236 |
|
| 237 |
|
| 238 |
func parseOptionFlags(s string) ([]yaml.Option, error) { |
| 239 |
parts := strings.Split(s, ",") |
| 240 |
var opts []yaml.Option |
| 241 |
for _, part := range parts { |
| 242 |
trimmed := strings.TrimSpace(part) |
| 243 |
if trimmed == "" { |
| 244 |
continue |
| 245 |
} |
| 246 |
opt, err := parseOneOption(trimmed) |
| 247 |
if err != nil { |
| 248 |
return nil, err |
| 249 |
} |
| 250 |
opts = append(opts, opt...) |
| 251 |
} |
| 252 |
return opts, nil |
| 253 |
} |
| 254 |
|
| 255 |
|
| 256 |
func printAvailableOptions() { |
| 257 |
fmt.Print(`Available options for -o/--option: |
| 258 |
|
| 259 |
Version presets: |
| 260 |
v2 V2 defaults (indent:2, no compact-seq-indent) |
| 261 |
v3 V3 defaults (indent:4, no compact-seq-indent) |
| 262 |
v4 V4 defaults (indent:2, compact-seq-indent) [default] |
| 263 |
|
| 264 |
Formatting options: |
| 265 |
indent=NUM Indentation spaces (2-9) |
| 266 |
compact-seq-indent '- ' counts as indentation (short: compact) |
| 267 |
line-width=NUM Preferred line width, -1=unlimited (short: width) |
| 268 |
unicode Allow non-ASCII in output |
| 269 |
canonical Canonical YAML output format |
| 270 |
line-break=TYPE Line ending: ln, cr, or crln |
| 271 |
explicit-start Always emit '---' marker |
| 272 |
explicit-end Always emit '...' marker |
| 273 |
explicit Both explicit-start and explicit-end |
| 274 |
flow-simple-coll Flow style for simple collections |
| 275 |
|
| 276 |
Loading options: |
| 277 |
unique-keys Duplicate key detection (short: unique) |
| 278 |
known-fields Strict field checking |
| 279 |
single-document Only process first document (short: single) |
| 280 |
all-documents Multi-document mode (short: all) |
| 281 |
stream-nodes Enable stream boundary nodes (short: stream) |
| 282 |
|
| 283 |
Boolean options: use 'name' for true, 'no-name' for false |
| 284 |
Multiple options: comma-separated or repeat -o flag |
| 285 |
|
| 286 |
Examples: |
| 287 |
go-yaml -y -o indent=4,canonical |
| 288 |
go-yaml -y -o v3,width=120,explicit |
| 289 |
go-yaml -y -o no-unicode,no-compact |
| 290 |
`) |
| 291 |
} |
| 292 |
|
| 293 |
|
| 294 |
func buildOptions(configFile string, optionFlags []string) ([]yaml.Option, error) { |
| 295 |
var opts []yaml.Option |
| 296 |
|
| 297 |
|
| 298 |
opts = append(opts, yaml.WithV4Defaults()) |
| 299 |
|
| 300 |
|
| 301 |
if configFile != "" { |
| 302 |
configData, err := os.ReadFile(configFile) |
| 303 |
if err != nil { |
| 304 |
return nil, fmt.Errorf("failed to read config file: %w", err) |
| 305 |
} |
| 306 |
configOpts, err := yaml.OptsYAML(string(configData)) |
| 307 |
if err != nil { |
| 308 |
return nil, fmt.Errorf("failed to parse config file: %w", err) |
| 309 |
} |
| 310 |
opts = append(opts, configOpts) |
| 311 |
} |
| 312 |
|
| 313 |
|
| 314 |
for _, optStr := range optionFlags { |
| 315 |
parsedOpts, err := parseOptionFlags(optStr) |
| 316 |
if err != nil { |
| 317 |
return nil, err |
| 318 |
} |
| 319 |
opts = append(opts, parsedOpts...) |
| 320 |
} |
| 321 |
|
| 322 |
return opts, nil |
| 323 |
} |
| 324 |
|
| 325 |
|
| 326 |
func main() { |
| 327 |
|
| 328 |
initOptionRegistry() |
| 329 |
|
| 330 |
|
| 331 |
showHelp := flag.Bool("h", false, "Show this help information") |
| 332 |
|
| 333 |
|
| 334 |
yamlMode := flag.Bool("y", false, "YAML encoding output") |
| 335 |
yamlPreserveMode := flag.Bool("Y", false, "YAML style and comments preserved") |
| 336 |
|
| 337 |
|
| 338 |
jsonMode := flag.Bool("j", false, "JSON compact output") |
| 339 |
jsonPrettyMode := flag.Bool("J", false, "JSON pretty output") |
| 340 |
|
| 341 |
|
| 342 |
tokenMode := flag.Bool("t", false, "Token output") |
| 343 |
tokenProfuseMode := flag.Bool("T", false, "Token with line info") |
| 344 |
|
| 345 |
|
| 346 |
eventMode := flag.Bool("e", false, "Event output") |
| 347 |
eventProfuseMode := flag.Bool("E", false, "Event with line info") |
| 348 |
|
| 349 |
|
| 350 |
nodeMode := flag.Bool("n", false, "Node representation output") |
| 351 |
nodeProfuseMode := flag.Bool("N", false, "Node with tag and style for all scalars") |
| 352 |
|
| 353 |
|
| 354 |
longMode := flag.Bool("l", false, "Long (block) formatted output") |
| 355 |
|
| 356 |
|
| 357 |
configFile := flag.String("C", "", "Load options from YAML config file") |
| 358 |
|
| 359 |
|
| 360 |
var optionFlags stringSlice |
| 361 |
flag.Var(&optionFlags, "o", "Set option (name=value, name, no-name)") |
| 362 |
flag.Var(&optionFlags, "option", "Set option (name=value, name, no-name)") |
| 363 |
|
| 364 |
|
| 365 |
var unmarshalMode bool |
| 366 |
var decodeMode bool |
| 367 |
var marshalMode bool |
| 368 |
var encodeMode bool |
| 369 |
|
| 370 |
|
| 371 |
flag.BoolVar(showHelp, "help", false, "Show this help information") |
| 372 |
flag.BoolVar(yamlMode, "yaml", false, "YAML encoding output") |
| 373 |
flag.BoolVar(yamlPreserveMode, "YAML", false, "YAML style and comments preserved") |
| 374 |
flag.BoolVar(jsonMode, "json", false, "JSON compact output") |
| 375 |
flag.BoolVar(jsonPrettyMode, "JSON", false, "JSON pretty output") |
| 376 |
flag.BoolVar(tokenMode, "token", false, "Token output") |
| 377 |
flag.BoolVar(tokenProfuseMode, "TOKEN", false, "Token with line info") |
| 378 |
flag.BoolVar(eventMode, "event", false, "Event output") |
| 379 |
flag.BoolVar(eventProfuseMode, "EVENT", false, "Event with line info") |
| 380 |
flag.BoolVar(nodeMode, "node", false, "Node representation output") |
| 381 |
flag.BoolVar(nodeProfuseMode, "NODE", false, "Node with tag and style for all scalars") |
| 382 |
flag.BoolVar(longMode, "long", false, "Long (block) formatted output") |
| 383 |
flag.StringVar(configFile, "config", "", "Load options from YAML config file") |
| 384 |
|
| 385 |
|
| 386 |
flag.BoolVar(&unmarshalMode, "unmarshal", false, "Use Unmarshal API for input") |
| 387 |
flag.BoolVar(&decodeMode, "decode", false, "Use Decode API for input") |
| 388 |
flag.BoolVar(&marshalMode, "marshal", false, "Use Marshal API for output") |
| 389 |
flag.BoolVar(&encodeMode, "encode", false, "Use Encode API for output") |
| 390 |
|
| 391 |
|
| 392 |
flag.Usage = func() { |
| 393 |
|
| 394 |
if len(os.Args) > 1 { |
| 395 |
for i, arg := range os.Args[1:] { |
| 396 |
if (arg == "-o" || arg == "--option") && (i+2 >= len(os.Args) || os.Args[i+2][0] == '-') { |
| 397 |
fmt.Fprintf(os.Stderr, "The -o flag requires a value.\n") |
| 398 |
fmt.Fprintf(os.Stderr, "Use '-o help' or '-o ?' to see available options.\n\n") |
| 399 |
printAvailableOptions() |
| 400 |
return |
| 401 |
} |
| 402 |
} |
| 403 |
} |
| 404 |
|
| 405 |
fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]) |
| 406 |
flag.PrintDefaults() |
| 407 |
} |
| 408 |
|
| 409 |
flag.Parse() |
| 410 |
|
| 411 |
|
| 412 |
|
| 413 |
|
| 414 |
if (marshalMode || encodeMode) && !*yamlMode && !*yamlPreserveMode { |
| 415 |
fmt.Fprintf(os.Stderr, "Error: --marshal/--encode flags only make sense with YAML output modes (-y/--yaml or -Y/--YAML)\n") |
| 416 |
os.Exit(1) |
| 417 |
} |
| 418 |
|
| 419 |
|
| 420 |
if unmarshalMode && *yamlPreserveMode { |
| 421 |
fmt.Fprintf(os.Stderr, "Error: --unmarshal flag doesn't make sense with preserving mode (-Y/--YAML) since unmarshal mode strips comments and styles\n") |
| 422 |
os.Exit(1) |
| 423 |
} |
| 424 |
|
| 425 |
|
| 426 |
var opts []yaml.Option |
| 427 |
if !unmarshalMode && !decodeMode { |
| 428 |
var err error |
| 429 |
opts, err = buildOptions(*configFile, optionFlags) |
| 430 |
if err != nil { |
| 431 |
fmt.Fprintf(os.Stderr, "Error: %v\n\n", err) |
| 432 |
printAvailableOptions() |
| 433 |
os.Exit(1) |
| 434 |
} |
| 435 |
} |
| 436 |
|
| 437 |
|
| 438 |
if *showHelp { |
| 439 |
printHelp() |
| 440 |
return |
| 441 |
} |
| 442 |
|
| 443 |
|
| 444 |
args := flag.Args() |
| 445 |
var input io.Reader |
| 446 |
var inputFile *os.File |
| 447 |
|
| 448 |
if len(args) == 0 || (len(args) == 1 && args[0] == "-") { |
| 449 |
|
| 450 |
input = os.Stdin |
| 451 |
|
| 452 |
|
| 453 |
stat, err := os.Stdin.Stat() |
| 454 |
if err != nil { |
| 455 |
log.Fatal("Failed to stat stdin:", err) |
| 456 |
} |
| 457 |
|
| 458 |
|
| 459 |
if (stat.Mode()&os.ModeCharDevice) != 0 && !*nodeMode && !*nodeProfuseMode && !*eventMode && !*eventProfuseMode && !*tokenMode && !*tokenProfuseMode && !*jsonMode && !*jsonPrettyMode && !*yamlMode && !*yamlPreserveMode && !*longMode { |
| 460 |
printHelp() |
| 461 |
return |
| 462 |
} |
| 463 |
|
| 464 |
|
| 465 |
if (stat.Mode()&os.ModeCharDevice) == 0 && !*nodeMode && !*nodeProfuseMode && !*eventMode && !*eventProfuseMode && !*tokenMode && !*tokenProfuseMode && !*jsonMode && !*jsonPrettyMode && !*yamlMode && !*yamlPreserveMode && !*longMode { |
| 466 |
fmt.Fprintf(os.Stderr, "Error: stdin has data but no mode specified. Use -n/--node, -N/--NODE, -e/--event, -E/--EVENT, -t/--token, -T/--TOKEN, -j/--json, -J/--JSON, -y/--yaml, -Y/--YAML flag.\n") |
| 467 |
os.Exit(1) |
| 468 |
} |
| 469 |
} else if len(args) == 1 { |
| 470 |
|
| 471 |
var err error |
| 472 |
inputFile, err = os.Open(args[0]) |
| 473 |
if err != nil { |
| 474 |
log.Fatal("Failed to open file:", err) |
| 475 |
} |
| 476 |
defer inputFile.Close() |
| 477 |
input = inputFile |
| 478 |
} else { |
| 479 |
|
| 480 |
fmt.Fprintf(os.Stderr, "Error: only one file argument supported\n") |
| 481 |
os.Exit(1) |
| 482 |
} |
| 483 |
|
| 484 |
|
| 485 |
if *eventMode { |
| 486 |
|
| 487 |
compact := !*longMode |
| 488 |
if err := ProcessEvents(input, false, compact, unmarshalMode); err != nil { |
| 489 |
log.Fatal("Failed to process events:", err) |
| 490 |
} |
| 491 |
} else if *eventProfuseMode { |
| 492 |
|
| 493 |
compact := !*longMode |
| 494 |
if err := ProcessEvents(input, true, compact, unmarshalMode); err != nil { |
| 495 |
log.Fatal("Failed to process events:", err) |
| 496 |
} |
| 497 |
} else if *tokenMode { |
| 498 |
|
| 499 |
compact := !*longMode |
| 500 |
if err := ProcessTokens(input, false, compact, unmarshalMode); err != nil { |
| 501 |
log.Fatal("Failed to process tokens:", err) |
| 502 |
} |
| 503 |
} else if *tokenProfuseMode { |
| 504 |
|
| 505 |
compact := !*longMode |
| 506 |
if err := ProcessTokens(input, true, compact, unmarshalMode); err != nil { |
| 507 |
log.Fatal("Failed to process tokens:", err) |
| 508 |
} |
| 509 |
} else if *jsonMode { |
| 510 |
|
| 511 |
if err := ProcessJSON(input, false, unmarshalMode, decodeMode, opts...); err != nil { |
| 512 |
log.Fatal("Failed to process JSON:", err) |
| 513 |
} |
| 514 |
} else if *jsonPrettyMode { |
| 515 |
|
| 516 |
if err := ProcessJSON(input, true, unmarshalMode, decodeMode, opts...); err != nil { |
| 517 |
log.Fatal("Failed to process JSON:", err) |
| 518 |
} |
| 519 |
} else if *yamlMode { |
| 520 |
|
| 521 |
if err := ProcessYAML(input, false, unmarshalMode, decodeMode, marshalMode, encodeMode, opts); err != nil { |
| 522 |
log.Fatal("Failed to process YAML:", err) |
| 523 |
} |
| 524 |
} else if *yamlPreserveMode { |
| 525 |
|
| 526 |
if err := ProcessYAML(input, true, unmarshalMode, decodeMode, marshalMode, encodeMode, opts); err != nil { |
| 527 |
log.Fatal("Failed to process YAML:", err) |
| 528 |
} |
| 529 |
} else { |
| 530 |
|
| 531 |
profuse := *nodeProfuseMode |
| 532 |
if unmarshalMode { |
| 533 |
|
| 534 |
if err := ProcessNodeUnmarshal(input, profuse); err != nil { |
| 535 |
log.Fatal("Failed to process YAML node:", err) |
| 536 |
} |
| 537 |
} else { |
| 538 |
|
| 539 |
loader, err := yaml.NewLoader(input, opts...) |
| 540 |
if err != nil { |
| 541 |
log.Fatal("Failed to create loader:", err) |
| 542 |
} |
| 543 |
|
| 544 |
|
| 545 |
var docs []any |
| 546 |
|
| 547 |
for { |
| 548 |
var node yaml.Node |
| 549 |
err := loader.Load(&node) |
| 550 |
if errors.Is(err, io.EOF) { |
| 551 |
break |
| 552 |
} |
| 553 |
if err != nil { |
| 554 |
log.Fatal("Failed to load YAML node:", err) |
| 555 |
} |
| 556 |
|
| 557 |
var info any |
| 558 |
if profuse { |
| 559 |
info = FormatNode(node, profuse) |
| 560 |
} else { |
| 561 |
info = FormatNodeCompact(node) |
| 562 |
} |
| 563 |
docs = append(docs, info) |
| 564 |
} |
| 565 |
|
| 566 |
|
| 567 |
var output any |
| 568 |
if len(docs) == 1 { |
| 569 |
output = docs[0] |
| 570 |
} else { |
| 571 |
output = docs |
| 572 |
} |
| 573 |
|
| 574 |
|
| 575 |
var buf bytes.Buffer |
| 576 |
enc, err := yaml.NewDumper(&buf) |
| 577 |
if err != nil { |
| 578 |
log.Fatal("Failed to create dumper:", err) |
| 579 |
} |
| 580 |
if err := enc.Dump(output); err != nil { |
| 581 |
log.Fatal("Failed to dump node info:", err) |
| 582 |
} |
| 583 |
if err := enc.Close(); err != nil { |
| 584 |
log.Fatal("Failed to close dumper:", err) |
| 585 |
} |
| 586 |
fmt.Print(buf.String()) |
| 587 |
} |
| 588 |
} |
| 589 |
} |
| 590 |
|
| 591 |
|
| 592 |
func ProcessNodeUnmarshal(reader io.Reader, profuse bool) error { |
| 593 |
|
| 594 |
input, err := io.ReadAll(reader) |
| 595 |
if err != nil { |
| 596 |
return fmt.Errorf("failed to read input: %w", err) |
| 597 |
} |
| 598 |
|
| 599 |
|
| 600 |
documents := bytes.Split(input, []byte("---")) |
| 601 |
|
| 602 |
|
| 603 |
var docs []any |
| 604 |
|
| 605 |
for _, doc := range documents { |
| 606 |
|
| 607 |
if len(bytes.TrimSpace(doc)) == 0 { |
| 608 |
continue |
| 609 |
} |
| 610 |
|
| 611 |
|
| 612 |
var data any |
| 613 |
if err := yaml.Load(doc, &data); err != nil { |
| 614 |
return fmt.Errorf("failed to load YAML: %w", err) |
| 615 |
} |
| 616 |
|
| 617 |
|
| 618 |
var node yaml.Node |
| 619 |
if err := yaml.Load(doc, &node); err != nil { |
| 620 |
return fmt.Errorf("failed to load YAML to node: %w", err) |
| 621 |
} |
| 622 |
|
| 623 |
var info any |
| 624 |
if profuse { |
| 625 |
info = FormatNode(node, profuse) |
| 626 |
} else { |
| 627 |
info = FormatNodeCompact(node) |
| 628 |
} |
| 629 |
docs = append(docs, info) |
| 630 |
} |
| 631 |
|
| 632 |
|
| 633 |
var output any |
| 634 |
if len(docs) == 1 { |
| 635 |
output = docs[0] |
| 636 |
} else { |
| 637 |
output = docs |
| 638 |
} |
| 639 |
|
| 640 |
|
| 641 |
var buf bytes.Buffer |
| 642 |
enc, err := yaml.NewDumper(&buf) |
| 643 |
if err != nil { |
| 644 |
return fmt.Errorf("failed to create dumper: %w", err) |
| 645 |
} |
| 646 |
if err := enc.Dump(output); err != nil { |
| 647 |
enc.Close() |
| 648 |
return fmt.Errorf("failed to dump node info: %w", err) |
| 649 |
} |
| 650 |
if err := enc.Close(); err != nil { |
| 651 |
return fmt.Errorf("failed to close dumper: %w", err) |
| 652 |
} |
| 653 |
fmt.Print(buf.String()) |
| 654 |
|
| 655 |
return nil |
| 656 |
} |
| 657 |
|
| 658 |
|
| 659 |
func printHelp() { |
| 660 |
fmt.Printf(`go-yaml version %s |
| 661 |
|
| 662 |
The 'go-yaml' tool shows how the go.yaml.in/yaml/v4 library handles YAML both |
| 663 |
internally and externally. It is a tool for testing and debugging the library. |
| 664 |
|
| 665 |
It reads YAML input text from stdin or a file and writes results to stdout. |
| 666 |
|
| 667 |
The go-yaml API has three sets of functions for reading/writing YAML: |
| 668 |
- Load/Dump (default, new API with options support - v4 defaults) |
| 669 |
- Decode/Encode (deprecated, no options) |
| 670 |
- Unmarshal/Marshal (deprecated, no options) |
| 671 |
|
| 672 |
|
| 673 |
Usage: |
| 674 |
go-yaml [options] [file] |
| 675 |
|
| 676 |
Output Mode Options: |
| 677 |
-y, --yaml YAML encoding output |
| 678 |
-Y, --YAML YAML w/ style and comments preserved |
| 679 |
|
| 680 |
-j, --json JSON compact output |
| 681 |
-J, --JSON JSON pretty output |
| 682 |
|
| 683 |
-t, --token Token output |
| 684 |
-T, --TOKEN Token with line info |
| 685 |
|
| 686 |
-e, --event Event output |
| 687 |
-E, --EVENT Event with line info |
| 688 |
|
| 689 |
-n, --node Node representation output |
| 690 |
-N, --NODE Node with tag and style for all scalars |
| 691 |
|
| 692 |
-l, --long Long (block) formatted output |
| 693 |
|
| 694 |
Formatting Options: |
| 695 |
-o, --option OPT Set option (use without value to see all options) |
| 696 |
Multiple: -o opt1,opt2 or -o opt1 -o opt2 |
| 697 |
Booleans: name (true) or no-name (false) |
| 698 |
Presets: v2, v3, v4 (default: v4) |
| 699 |
|
| 700 |
API Selection Options: |
| 701 |
--unmarshal Use Unmarshal API for input (deprecated, v3 defaults) |
| 702 |
--decode Use Decode API for input (deprecated) |
| 703 |
--marshal Use Marshal API for output (deprecated) |
| 704 |
--encode Use Encode API for output (deprecated) |
| 705 |
|
| 706 |
Configuration: |
| 707 |
-C, --config Load options from YAML config file |
| 708 |
|
| 709 |
Other Options: |
| 710 |
-h, --help Show this help information |
| 711 |
|
| 712 |
`, version) |
| 713 |
} |