util.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. # -*- coding: utf-8 -*-
  2. """
  3. # Simple password manager
  4. # Copyright (c) 2011-2024 Michael Büsch <m@bues.ch>
  5. # Licensed under the GNU/GPL version 2 or later.
  6. """
  7. import curses
  8. import getpass
  9. import os
  10. import sys
  11. __all__ = [
  12. "str2bool",
  13. "osIsWindows",
  14. "osIsPosix",
  15. "stdout",
  16. "clearScreen",
  17. "readPassphrase",
  18. ]
  19. osIsWindows = os.name == "nt" or os.name == "ce"
  20. osIsPosix = os.name == "posix"
  21. def str2bool(string, default=False):
  22. s = string.lower().strip()
  23. if not s:
  24. return default
  25. if s in ("true", "yes", "on", "1"):
  26. return True
  27. if s in ("false", "no", "off", "0"):
  28. return False
  29. try:
  30. return bool(int(s))
  31. except ValueError:
  32. return default
  33. def stdout(text, flush=True):
  34. if isinstance(text, str):
  35. stream = sys.stdout
  36. else:
  37. stream = getattr(sys.stdout, "buffer", None)
  38. if stream is None:
  39. stream = sys.stdout
  40. text = text.decode("UTF-8", "ignore")
  41. stream.write(text)
  42. if flush:
  43. stream.flush()
  44. def clearScreen():
  45. try:
  46. stdscr = curses.initscr()
  47. stdscr.clear()
  48. finally:
  49. curses.endwin()
  50. stdout("\x1B[2J\x1B[0;0f")
  51. def _do_getpass(prompt):
  52. if str2bool(os.getenv("PWMAN_RAWGETPASS", "")):
  53. return input(prompt)
  54. else:
  55. return getpass.getpass(prompt)
  56. def readPassphrase(prompt, verify=False):
  57. if verify:
  58. prompt = "[New] " + prompt
  59. try:
  60. while True:
  61. p0 = _do_getpass(prompt + ": ")
  62. if not p0:
  63. continue
  64. if not verify:
  65. return p0
  66. p1 = _do_getpass(prompt + " (verify): ")
  67. if p0 == p1:
  68. return p0
  69. print("Passwords don't match. Try again...",
  70. file=sys.stderr)
  71. except (EOFError, KeyboardInterrupt) as e:
  72. print("")
  73. return None
  74. except (getpass.GetPassWarning) as e:
  75. print(str(e), file=sys.stderr)
  76. return None