json.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 progress
  14. import (
  15. "context"
  16. "encoding/json"
  17. "fmt"
  18. "io"
  19. )
  20. type jsonWriter struct {
  21. out io.Writer
  22. done chan bool
  23. dryRun bool
  24. }
  25. type jsonMessage struct {
  26. DryRun bool `json:"dry-run,omitempty"`
  27. Tail bool `json:"tail,omitempty"`
  28. ID string `json:"id,omitempty"`
  29. Text string `json:"text,omitempty"`
  30. Status string `json:"status,omitempty"`
  31. }
  32. func (p *jsonWriter) Start(ctx context.Context) error {
  33. select {
  34. case <-ctx.Done():
  35. return ctx.Err()
  36. case <-p.done:
  37. return nil
  38. }
  39. }
  40. func (p *jsonWriter) Event(e Event) {
  41. var message = &jsonMessage{
  42. DryRun: p.dryRun,
  43. Tail: false,
  44. ID: e.ID,
  45. Text: e.Text,
  46. Status: e.StatusText,
  47. }
  48. marshal, err := json.Marshal(message)
  49. if err == nil {
  50. fmt.Fprintln(p.out, string(marshal))
  51. }
  52. }
  53. func (p *jsonWriter) Events(events []Event) {
  54. for _, e := range events {
  55. p.Event(e)
  56. }
  57. }
  58. func (p *jsonWriter) TailMsgf(msg string, args ...interface{}) {
  59. var message = &jsonMessage{
  60. DryRun: p.dryRun,
  61. Tail: true,
  62. ID: "",
  63. Text: fmt.Sprintf(msg, args...),
  64. Status: "",
  65. }
  66. marshal, err := json.Marshal(message)
  67. if err == nil {
  68. fmt.Fprintln(p.out, string(marshal))
  69. }
  70. }
  71. func (p *jsonWriter) Stop() {
  72. p.done <- true
  73. }
  74. func (p *jsonWriter) HasMore(bool) {
  75. }