helpers.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. """
  2. Put into Public Domain, by Nicolas Sebrecht.
  3. Helpers for maintenance scripts.
  4. """
  5. from os import chdir, makedirs, system, getcwd
  6. from os.path import expanduser
  7. import shlex
  8. from subprocess import check_output, check_call, CalledProcessError
  9. import yaml
  10. FS_ENCODING = 'UTF-8'
  11. ENCODING = 'UTF-8'
  12. MAILING_LIST = 'offlineimap-project@lists.alioth.debian.org'
  13. CACHEDIR = '.git/offlineimap-release'
  14. EDITOR = 'vim'
  15. MAILALIASES_FILE = expanduser('~/.mutt/mail_aliases')
  16. TESTERS_FILE = "{}/testers.yml".format(CACHEDIR)
  17. ME = "Nicolas Sebrecht <nicolas.s-dev@laposte.net>"
  18. def run(cmd):
  19. return check_output(cmd, timeout=5).rstrip()
  20. def goTo(path):
  21. try:
  22. chdir(path)
  23. return True
  24. except FileNotFoundError:
  25. print(("Could not find the '{}' directory in '{}'...".format(
  26. path, getcwd())
  27. ))
  28. return False
  29. class Author():
  30. def __init__(self, name, count, email):
  31. self.name = name
  32. self.count = count
  33. self.email = email
  34. def getName(self):
  35. return self.name
  36. def getCount(self):
  37. return self.count
  38. def getEmail(self):
  39. return self.email
  40. class Git():
  41. @staticmethod
  42. def getShortlog(ref):
  43. shortlog = ""
  44. cmd = shlex.split("git shortlog --no-merges -n v{}..".format(ref))
  45. output = run(cmd).decode(ENCODING)
  46. for line in output.split("\n"):
  47. if len(line) > 0:
  48. if line[0] != " ":
  49. line = " {}\n".format(line)
  50. else:
  51. line = " {}\n".format(line.lstrip())
  52. else:
  53. line = "\n"
  54. shortlog += line
  55. return shortlog
  56. @staticmethod
  57. def add(files):
  58. cmd = shlex.split("git add -- {}".format(files))
  59. return run(cmd).decode(ENCODING)
  60. @staticmethod
  61. def commit(msg):
  62. cmd = shlex.split("git commit -s -m '{}'".format(msg))
  63. return run(cmd).decode(ENCODING)
  64. @staticmethod
  65. def tag(version):
  66. cmd = shlex.split("git tag -a 'v{}' -m 'v{}'".format(version, version))
  67. return run(cmd).decode(ENCODING)
  68. @staticmethod
  69. def stash(msg):
  70. cmd = shlex.split("git stash create '{}'".format(msg))
  71. return run(cmd).decode(ENCODING)
  72. @staticmethod
  73. def mergeFF(ref):
  74. cmd = shlex.split("git merge --ff '{}'".format(ref))
  75. return run(cmd).decode(ENCODING)
  76. @staticmethod
  77. def getDiffstat(ref):
  78. cmd = shlex.split("git diff --stat v{}..".format(ref))
  79. return run(cmd).decode(ENCODING)
  80. @staticmethod
  81. def isClean():
  82. try:
  83. check_call(shlex.split("git diff --quiet"))
  84. check_call(shlex.split("git diff --cached --quiet"))
  85. except CalledProcessError:
  86. return False
  87. return True
  88. @staticmethod
  89. def buildMessageId():
  90. cmd = shlex.split(
  91. "git log HEAD~1.. --oneline --pretty='%H.%t.upcoming.%ce'")
  92. return run(cmd).decode(ENCODING)
  93. @staticmethod
  94. def resetKeep(ref):
  95. return run(shlex.split("git reset --keep {}".format(ref)))
  96. @staticmethod
  97. def getRef(ref):
  98. return run(shlex.split("git rev-parse {}".format(ref))).rstrip()
  99. @staticmethod
  100. def rmTag(tag):
  101. return run(shlex.split("git tag -d {}".format(tag)))
  102. @staticmethod
  103. def checkout(ref, create=False):
  104. if create:
  105. create = "-b"
  106. else:
  107. create = ""
  108. cmd = shlex.split("git checkout {} {}".format(create, ref))
  109. run(cmd)
  110. head = shlex.split("git rev-parse HEAD")
  111. revparseRef = shlex.split("git rev-parse {}".format(ref))
  112. if run(head) != run(revparseRef):
  113. raise Exception("checkout to '{}' did not work".format(ref))
  114. @staticmethod
  115. def makeCacheDir():
  116. try:
  117. makedirs(CACHEDIR)
  118. except FileExistsError:
  119. pass
  120. @staticmethod
  121. def getLocalUser():
  122. cmd = shlex.split("git config --get user.name")
  123. name = run(cmd).decode(ENCODING)
  124. cmd = shlex.split("git config --get user.email")
  125. email = run(cmd).decode(ENCODING)
  126. return name, email
  127. @staticmethod
  128. def buildDate():
  129. cmd = shlex.split("git log HEAD~1.. --oneline --pretty='%cD'")
  130. return run(cmd).decode(ENCODING)
  131. @staticmethod
  132. def getAuthorsList(sinceRef):
  133. authors = []
  134. cmd = shlex.split("git shortlog --no-merges -sne v{}..".format(sinceRef))
  135. output = run(cmd).decode(ENCODING)
  136. for line in output.split("\n"):
  137. count, full = line.strip().split("\t")
  138. full = full.split(' ')
  139. name = ' '.join(full[:-1])
  140. email = full[-1]
  141. authors.append(Author(name, count, email))
  142. return authors
  143. @staticmethod
  144. def getCommitsList(sinceRef):
  145. cmd = shlex.split(
  146. "git log --no-merges --format='- %h %s. [%aN]' v{}..".format(sinceRef)
  147. )
  148. return run(cmd).decode(ENCODING)
  149. @staticmethod
  150. def chdirToRepositoryTopLevel():
  151. cmd = shlex.split("git rev-parse --show-toplevel")
  152. topLevel = run(cmd)
  153. chdir(topLevel)
  154. class OfflineimapInfo():
  155. def getVersion(self):
  156. cmd = shlex.split("./offlineimap.py --version")
  157. return run(cmd).rstrip().decode(FS_ENCODING)
  158. def editInit(self):
  159. return system("{} ./offlineimap/__init__.py".format(EDITOR))
  160. class User():
  161. """Interact with the user."""
  162. @staticmethod
  163. def request(msg, prompt='--> '):
  164. print(msg)
  165. return eval(input(prompt))
  166. @staticmethod
  167. def pause(msg=False):
  168. return User.request(msg, prompt="Press Enter to continue..")
  169. @staticmethod
  170. def yesNo(msg, defaultToYes=False, prompt='--> '):
  171. endMsg = " [y/N]: No"
  172. if defaultToYes:
  173. endMsg = " [Y/n]: Yes"
  174. msg += endMsg
  175. answer = User.request(msg, prompt).lower()
  176. if answer in ['y', 'yes']:
  177. return True
  178. if defaultToYes is not False and answer not in ['n', 'no']:
  179. return True
  180. return False
  181. class Tester():
  182. def __init__(self, name, email, feedback):
  183. self.name = name
  184. self.email = email
  185. self.feedback = feedback
  186. def __str__(self):
  187. return "{} {}".format(self.name, self.email)
  188. def getName(self):
  189. return self.name
  190. def getEmail(self):
  191. return self.email
  192. def getFeedback(self):
  193. return self.feedback
  194. def positiveFeedback(self):
  195. return self.feedback is True
  196. def setFeedback(self, feedback):
  197. assert feedback in [True, False, None]
  198. self.feedback = feedback
  199. def switchFeedback(self):
  200. self.feedback = not self.feedback
  201. class Testers():
  202. def __init__(self):
  203. self.testers = None
  204. self._read()
  205. def _read(self):
  206. self.testers = []
  207. with open(TESTERS_FILE, 'r') as fd:
  208. testers = yaml.load(fd)
  209. for tester in testers:
  210. name = tester['name']
  211. email = tester['email']
  212. feedback = tester['feedback']
  213. self.testers.append(Tester(name, email, feedback))
  214. self.testers.sort(key=lambda x: x.getName().lower())
  215. @staticmethod
  216. def listTestersInTeam():
  217. """Returns a list of emails extracted from my mailaliases file."""
  218. cmd = shlex.split("grep offlineimap-testers {}".format(MAILALIASES_FILE))
  219. output = run(cmd).decode(ENCODING)
  220. emails = output.lstrip("alias offlineimap-testers ").split(', ')
  221. return emails
  222. def add(self, name, email, feedback=None):
  223. self.testers.append(Tester(name, email, feedback))
  224. def remove(self, tester):
  225. self.testers.remove(tester)
  226. def get(self):
  227. return self.testers
  228. def getList(self):
  229. testersList = ""
  230. for tester in self.testers:
  231. testersList += "- {}\n".format(tester.getName())
  232. return testersList
  233. def getListOk(self):
  234. testersOk = []
  235. for tester in self.testers:
  236. if tester.positiveFeedback():
  237. testersOk.append(tester)
  238. return testersOk
  239. def reset(self):
  240. for tester in self.testers:
  241. tester.setFeedback(None)
  242. def write(self):
  243. testers = []
  244. for tester in self.testers:
  245. testers.append({
  246. 'name': tester.getName(),
  247. 'email': tester.getEmail(),
  248. 'feedback': tester.getFeedback(),
  249. })
  250. with open(TESTERS_FILE, 'w') as fd:
  251. fd.write(yaml.dump(testers))