progress_stream.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import json
  2. import six
  3. from compose import utils
  4. class StreamOutputError(Exception):
  5. pass
  6. def stream_output(output, stream):
  7. is_terminal = hasattr(stream, 'isatty') and stream.isatty()
  8. stream = utils.get_output_stream(stream)
  9. all_events = []
  10. lines = {}
  11. diff = 0
  12. for chunk in output:
  13. if six.PY3:
  14. chunk = chunk.decode('utf-8')
  15. event = json.loads(chunk)
  16. all_events.append(event)
  17. if 'progress' in event or 'progressDetail' in event:
  18. image_id = event.get('id')
  19. if not image_id:
  20. continue
  21. if image_id in lines:
  22. diff = len(lines) - lines[image_id]
  23. else:
  24. lines[image_id] = len(lines)
  25. stream.write("\n")
  26. diff = 0
  27. if is_terminal:
  28. # move cursor up `diff` rows
  29. stream.write("%c[%dA" % (27, diff))
  30. print_output_event(event, stream, is_terminal)
  31. if 'id' in event and is_terminal:
  32. # move cursor back down
  33. stream.write("%c[%dB" % (27, diff))
  34. stream.flush()
  35. return all_events
  36. def print_output_event(event, stream, is_terminal):
  37. if 'errorDetail' in event:
  38. raise StreamOutputError(event['errorDetail']['message'])
  39. terminator = ''
  40. if is_terminal and 'stream' not in event:
  41. # erase current line
  42. stream.write("%c[2K\r" % 27)
  43. terminator = "\r"
  44. elif 'progressDetail' in event:
  45. return
  46. if 'time' in event:
  47. stream.write("[%s] " % event['time'])
  48. if 'id' in event:
  49. stream.write("%s: " % event['id'])
  50. if 'from' in event:
  51. stream.write("(from %s) " % event['from'])
  52. status = event.get('status', '')
  53. if 'progress' in event:
  54. stream.write("%s %s%s" % (status, event['progress'], terminator))
  55. elif 'progressDetail' in event:
  56. detail = event['progressDetail']
  57. total = detail.get('total')
  58. if 'current' in detail and total:
  59. percentage = float(detail['current']) / float(total) * 100
  60. stream.write('%s (%.1f%%)%s' % (status, percentage, terminator))
  61. else:
  62. stream.write('%s%s' % (status, terminator))
  63. elif 'stream' in event:
  64. stream.write("%s%s" % (event['stream'], terminator))
  65. else:
  66. stream.write("%s%s\n" % (status, terminator))