util.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. # -*- coding: utf-8 -*-
  2. """
  3. # Simple password manager
  4. # Copyright (c) 2011-2023 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. "uniq",
  16. "stdout",
  17. "clearScreen",
  18. "readPassphrase",
  19. ]
  20. osIsWindows = os.name == "nt" or os.name == "ce"
  21. osIsPosix = os.name == "posix"
  22. def str2bool(string, default=False):
  23. s = string.lower().strip()
  24. if not s:
  25. return default
  26. if s in ("true", "yes", "on", "1"):
  27. return True
  28. if s in ("false", "no", "off", "0"):
  29. return False
  30. try:
  31. return bool(int(s))
  32. except ValueError:
  33. return default
  34. def uniq(l, sort=True):
  35. l = list(set(l))
  36. if sort:
  37. l.sort()
  38. return l
  39. def stdout(text, flush=True):
  40. if isinstance(text, str):
  41. stream = sys.stdout
  42. else:
  43. stream = getattr(sys.stdout, "buffer", None)
  44. if stream is None:
  45. stream = sys.stdout
  46. text = text.decode("UTF-8", "ignore")
  47. stream.write(text)
  48. if flush:
  49. stream.flush()
  50. def clearScreen():
  51. try:
  52. stdscr = curses.initscr()
  53. stdscr.clear()
  54. finally:
  55. curses.endwin()
  56. stdout("\x1B[2J\x1B[0;0f")
  57. def _do_getpass(prompt):
  58. if str2bool(os.getenv("PWMAN_RAWGETPASS", "")):
  59. return input(prompt)
  60. else:
  61. return getpass.getpass(prompt)
  62. def readPassphrase(prompt, verify=False):
  63. if verify:
  64. prompt = "[New] " + prompt
  65. try:
  66. while True:
  67. p0 = _do_getpass(prompt + ": ")
  68. if not p0:
  69. continue
  70. if not verify:
  71. return p0
  72. p1 = _do_getpass(prompt + " (verify): ")
  73. if p0 == p1:
  74. return p0
  75. print("Passwords don't match. Try again...",
  76. file=sys.stderr)
  77. except (EOFError, KeyboardInterrupt) as e:
  78. print("")
  79. return None
  80. except (getpass.GetPassWarning) as e:
  81. print(str(e), file=sys.stderr)
  82. return None