out.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package command
  2. import (
  3. "io"
  4. "os"
  5. "github.com/Sirupsen/logrus"
  6. "github.com/docker/docker/pkg/term"
  7. )
  8. // OutStream is an output stream used by the DockerCli to write normal program
  9. // output.
  10. type OutStream struct {
  11. out io.Writer
  12. fd uintptr
  13. isTerminal bool
  14. state *term.State
  15. }
  16. func (o *OutStream) Write(p []byte) (int, error) {
  17. return o.out.Write(p)
  18. }
  19. // FD returns the file descriptor number for this stream
  20. func (o *OutStream) FD() uintptr {
  21. return o.fd
  22. }
  23. // IsTerminal returns true if this stream is connected to a terminal
  24. func (o *OutStream) IsTerminal() bool {
  25. return o.isTerminal
  26. }
  27. // SetRawTerminal sets raw mode on the output terminal
  28. func (o *OutStream) SetRawTerminal() (err error) {
  29. if os.Getenv("NORAW") != "" || !o.isTerminal {
  30. return nil
  31. }
  32. o.state, err = term.SetRawTerminalOutput(o.fd)
  33. return err
  34. }
  35. // RestoreTerminal restores normal mode to the terminal
  36. func (o *OutStream) RestoreTerminal() {
  37. if o.state != nil {
  38. term.RestoreTerminal(o.fd, o.state)
  39. }
  40. }
  41. // GetTtySize returns the height and width in characters of the tty
  42. func (o *OutStream) GetTtySize() (uint, uint) {
  43. if !o.isTerminal {
  44. return 0, 0
  45. }
  46. ws, err := term.GetWinsize(o.fd)
  47. if err != nil {
  48. logrus.Debugf("Error getting size: %s", err)
  49. if ws == nil {
  50. return 0, 0
  51. }
  52. }
  53. return uint(ws.Height), uint(ws.Width)
  54. }
  55. // NewOutStream returns a new OutStream object from a Writer
  56. func NewOutStream(out io.Writer) *OutStream {
  57. fd, isTerminal := term.GetFdInfo(out)
  58. return &OutStream{out: out, fd: fd, isTerminal: isTerminal}
  59. }