json.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. Copyright 2024 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 display
  14. import (
  15. "context"
  16. "encoding/json"
  17. "fmt"
  18. "io"
  19. "github.com/docker/compose/v5/pkg/api"
  20. )
  21. func JSON(out io.Writer) api.EventProcessor {
  22. return &jsonWriter{
  23. out: out,
  24. }
  25. }
  26. type jsonWriter struct {
  27. out io.Writer
  28. dryRun bool
  29. }
  30. type jsonMessage struct {
  31. DryRun bool `json:"dry-run,omitempty"`
  32. Tail bool `json:"tail,omitempty"`
  33. ID string `json:"id,omitempty"`
  34. ParentID string `json:"parent_id,omitempty"`
  35. Status string `json:"status,omitempty"`
  36. Text string `json:"text,omitempty"`
  37. Details string `json:"details,omitempty"`
  38. Current int64 `json:"current,omitempty"`
  39. Total int64 `json:"total,omitempty"`
  40. Percent int `json:"percent,omitempty"`
  41. }
  42. func (p *jsonWriter) Start(ctx context.Context, operation string) {
  43. }
  44. func (p *jsonWriter) Event(e api.Resource) {
  45. message := &jsonMessage{
  46. DryRun: p.dryRun,
  47. Tail: false,
  48. ID: e.ID,
  49. Status: e.StatusText(),
  50. Text: e.Text,
  51. Details: e.Details,
  52. ParentID: e.ParentID,
  53. Current: e.Current,
  54. Total: e.Total,
  55. Percent: e.Percent,
  56. }
  57. marshal, err := json.Marshal(message)
  58. if err == nil {
  59. _, _ = fmt.Fprintln(p.out, string(marshal))
  60. }
  61. }
  62. func (p *jsonWriter) On(events ...api.Resource) {
  63. for _, e := range events {
  64. p.Event(e)
  65. }
  66. }
  67. func (p *jsonWriter) Done(_ string, _ bool) {
  68. }