util.go 960 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package term
  2. import (
  3. "io"
  4. "runtime"
  5. )
  6. // readPasswordLine reads from reader until it finds \n or io.EOF.
  7. // The slice returned does not include the \n.
  8. // readPasswordLine also ignores any \r it finds.
  9. // Windows uses \r as end of line. So, on Windows, readPasswordLine
  10. // reads until it finds \r and ignores any \n it finds during processing.
  11. func readPasswordLine(reader io.Reader) ([]byte, error) {
  12. var buf [1]byte
  13. var ret []byte
  14. for {
  15. n, err := reader.Read(buf[:])
  16. if n > 0 {
  17. switch buf[0] {
  18. case '\b':
  19. if len(ret) > 0 {
  20. ret = ret[:len(ret)-1]
  21. }
  22. case '\n':
  23. if runtime.GOOS != "windows" {
  24. return ret, nil
  25. }
  26. // otherwise ignore \n
  27. case '\r':
  28. if runtime.GOOS == "windows" {
  29. return ret, nil
  30. }
  31. // otherwise ignore \r
  32. default:
  33. ret = append(ret, buf[0])
  34. }
  35. continue
  36. }
  37. if err != nil {
  38. if err == io.EOF && len(ret) > 0 {
  39. return ret, nil
  40. }
  41. return ret, err
  42. }
  43. }
  44. }