| 28 | } |
| 29 | |
| 30 | func run(o runOpts) ([]byte, error) { |
| 31 | cfg, err := LoadConfig(o.ConfigPath) |
| 32 | if err != nil { |
| 33 | return nil, fmt.Errorf("error loading config: %w", err) |
| 34 | } |
| 35 | |
| 36 | var opts []execution.ExecuteOptionFn |
| 37 | |
| 38 | if o.OutFormat == "" && o.InFormat != "" { |
| 39 | o.OutFormat = o.InFormat |
| 40 | } else if o.OutFormat != "" && o.InFormat == "" { |
| 41 | o.InFormat = o.OutFormat |
| 42 | } else if o.OutFormat == "" { |
| 43 | o.OutFormat = cfg.DefaultFormat |
| 44 | } |
| 45 | |
| 46 | readerOptions := parsing.DefaultReaderOptions() |
| 47 | applyReaderFlags(&readerOptions, o.ExtReadFlags, o.ExtReadWriteFlags) |
| 48 | |
| 49 | var reader parsing.Reader |
| 50 | if len(o.InFormat) > 0 { |
| 51 | reader, err = parsing.Format(o.InFormat).NewReader(readerOptions) |
| 52 | if err != nil { |
| 53 | return nil, fmt.Errorf("failed to get input reader: %w", err) |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | writerOptions := parsing.DefaultWriterOptions() |
| 58 | writerOptions.Compact = o.Compact |
| 59 | applyWriterFlags(&writerOptions, o.ExtWriteFlags, o.ExtReadWriteFlags) |
| 60 | |
| 61 | writer, err := parsing.Format(o.OutFormat).NewWriter(writerOptions) |
| 62 | if err != nil { |
| 63 | return nil, fmt.Errorf("failed to get output writer: %w", err) |
| 64 | } |
| 65 | |
| 66 | opts = append(opts, variableOptions(o.Vars)...) |
| 67 | |
| 68 | // Default to null. If stdin is being read then this will be overwritten. |
| 69 | inputData := model.NewNullValue() |
| 70 | |
| 71 | var inputBytes []byte |
| 72 | if o.Stdin != nil { |
| 73 | inputBytes, err = io.ReadAll(o.Stdin) |
| 74 | if err != nil { |
| 75 | return nil, fmt.Errorf("error reading stdin: %w", err) |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | if len(inputBytes) > 0 { |
| 80 | if reader == nil { |
| 81 | return nil, fmt.Errorf("input format is required when reading stdin") |
| 82 | } |
| 83 | inputData, err = reader.Read(inputBytes) |
| 84 | if err != nil { |
| 85 | return nil, fmt.Errorf("error reading input: %w", err) |
| 86 | } |
| 87 | } |