formatter.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package formatter
  14. import (
  15. "fmt"
  16. "io"
  17. "reflect"
  18. "strings"
  19. "github.com/docker/compose/v2/pkg/api"
  20. "github.com/pkg/errors"
  21. )
  22. // Print prints formatted lists in different formats
  23. func Print(toJSON interface{}, format string, outWriter io.Writer, writerFn func(w io.Writer), headers ...string) error {
  24. switch strings.ToLower(format) {
  25. case PRETTY, "":
  26. return PrintPrettySection(outWriter, writerFn, headers...)
  27. case TemplateLegacyJSON:
  28. switch reflect.TypeOf(toJSON).Kind() {
  29. case reflect.Slice:
  30. s := reflect.ValueOf(toJSON)
  31. for i := 0; i < s.Len(); i++ {
  32. obj := s.Index(i).Interface()
  33. outJSON, err := ToJSON(obj, "", "")
  34. if err != nil {
  35. return err
  36. }
  37. _, _ = fmt.Fprint(outWriter, outJSON)
  38. }
  39. default:
  40. outJSON, err := ToStandardJSON(toJSON)
  41. if err != nil {
  42. return err
  43. }
  44. _, _ = fmt.Fprintln(outWriter, outJSON)
  45. }
  46. case JSON:
  47. switch reflect.TypeOf(toJSON).Kind() {
  48. case reflect.Slice:
  49. outJSON, err := ToJSON(toJSON, "", "")
  50. if err != nil {
  51. return err
  52. }
  53. _, _ = fmt.Fprint(outWriter, outJSON)
  54. default:
  55. outJSON, err := ToStandardJSON(toJSON)
  56. if err != nil {
  57. return err
  58. }
  59. _, _ = fmt.Fprintln(outWriter, outJSON)
  60. }
  61. default:
  62. return errors.Wrapf(api.ErrParsingFailed, "format value %q could not be parsed", format)
  63. }
  64. return nil
  65. }