2
0

diffstat.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
  4. # Copyright (c) 2020 Kevin B. Hendricks, Stratford Ontario Canada
  5. # All rights reserved.
  6. #
  7. # This diffstat code was extracted and heavily modified from:
  8. #
  9. # https://github.com/techtonik/python-patch
  10. # Under the following license:
  11. #
  12. # Patch utility to apply unified diffs
  13. # Brute-force line-by-line non-recursive parsing
  14. #
  15. # Copyright (c) 2008-2016 anatoly techtonik
  16. #
  17. # Permission is hereby granted, free of charge, to any person obtaining a copy
  18. # of this software and associated documentation files (the "Software"), to deal
  19. # in the Software without restriction, including without limitation the rights
  20. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  21. # copies of the Software, and to permit persons to whom the Software is
  22. # furnished to do so, subject to the following conditions:
  23. #
  24. # The above copyright notice and this permission notice shall be included in
  25. # all copies or substantial portions of the Software.
  26. #
  27. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  28. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  29. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  30. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  31. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  32. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  33. # THE SOFTWARE.
  34. import sys
  35. import re
  36. # only needs to detect git style diffs as this is for
  37. # use with dulwich
  38. _git_header_name = re.compile(br'diff --git a/(.*) b/(.*)')
  39. _GIT_HEADER_START = b'diff --git a/'
  40. _GIT_BINARY_START = b'Binary file'
  41. _GIT_RENAMEFROM_START = b'rename from'
  42. _GIT_RENAMETO_START = b'rename to'
  43. _GIT_CHUNK_START = b'@@'
  44. _GIT_ADDED_START = b'+'
  45. _GIT_DELETED_START = b'-'
  46. _GIT_UNCHANGED_START = b' '
  47. # emulate original full Patch class by just extracting
  48. # filename and minimal chunk added/deleted information to
  49. # properly interface with diffstat routine
  50. def _parse_patch(lines):
  51. """An internal routine to parse a git style diff or patch to generate
  52. diff stats
  53. Args:
  54. lines: list of byte strings "lines" from the diff to be parsed
  55. Returns: A tuple (names, nametypes, counts) of three lists:
  56. names = list of repo relative file paths
  57. nametypes - list of booolean values indicating if file
  58. is binary (True means binary file)
  59. counts = list of tuples of (added, deleted) counts for that file
  60. """
  61. names = []
  62. nametypes = []
  63. counts = []
  64. in_patch_chunk = in_git_header = binaryfile = False
  65. currentfile = None
  66. added = deleted = 0
  67. for line in lines:
  68. if line.startswith(_GIT_HEADER_START):
  69. if currentfile is not None:
  70. names.append(currentfile)
  71. nametypes.append(binaryfile)
  72. counts.append((added, deleted))
  73. currentfile = _git_header_name.search(line).group(2)
  74. binaryfile = False
  75. added = deleted = 0
  76. in_git_header = True
  77. in_patch_chunk = False
  78. elif line.startswith(_GIT_BINARY_START) and in_git_header:
  79. binaryfile = True
  80. in_git_header = False
  81. elif line.startswith(_GIT_RENAMEFROM_START) and in_git_header:
  82. currentfile = line[12:]
  83. elif line.startswith(_GIT_RENAMETO_START) and in_git_header:
  84. currentfile += b' => %s' % line[10:]
  85. elif line.startswith(_GIT_CHUNK_START) and \
  86. (in_patch_chunk or in_git_header):
  87. in_patch_chunk = True
  88. in_git_header = False
  89. elif line.startswith(_GIT_ADDED_START) and in_patch_chunk:
  90. added += 1
  91. elif line.startswith(_GIT_DELETED_START) and in_patch_chunk:
  92. deleted += 1
  93. elif not line.startswith(_GIT_UNCHANGED_START) and in_patch_chunk:
  94. in_patch_chunk = False
  95. # handle end of input
  96. if currentfile is not None:
  97. names.append(currentfile)
  98. nametypes.append(binaryfile)
  99. counts.append((added, deleted))
  100. return names, nametypes, counts
  101. # note must all done using bytes not string because on linux filenames
  102. # may not be encodable even to utf-8
  103. def diffstat(lines, max_width=80):
  104. """Generate summary statistics from a git style diff ala
  105. (git diff tag1 tag2 --stat)
  106. Args:
  107. lines: list of byte string "lines" from the diff to be parsed
  108. max_width: maximum line length for generating the summary
  109. statistics (default 80)
  110. Returns: A byte string that lists the changed files with change
  111. counts and histogram
  112. """
  113. names, nametypes, counts = _parse_patch(lines)
  114. insert = []
  115. delete = []
  116. namelen = 0
  117. maxdiff = 0 # max changes for any file used for histogram width calc
  118. for i, filename in enumerate(names):
  119. i, d = counts[i]
  120. insert.append(i)
  121. delete.append(d)
  122. namelen = max(namelen, len(filename))
  123. maxdiff = max(maxdiff, i+d)
  124. output = b''
  125. statlen = len(str(maxdiff)) # stats column width
  126. for i, n in enumerate(names):
  127. binaryfile = nametypes[i]
  128. # %-19s | %-4d %s
  129. # note b'%d' % namelen is not supported until Python 3.5
  130. # To convert an int to a format width specifier for byte
  131. # strings use str(namelen).encode('ascii')
  132. format = b' %-' + str(namelen).encode('ascii') + \
  133. b's | %' + str(statlen).encode('ascii') + b's %s\n'
  134. binformat = b' %-' + str(namelen).encode('ascii') + b's | %s\n'
  135. if not binaryfile:
  136. hist = b''
  137. # -- calculating histogram --
  138. width = len(format % (b'', b'', b''))
  139. histwidth = max(2, max_width - width)
  140. if maxdiff < histwidth:
  141. hist = b'+'*insert[i] + b'-'*delete[i]
  142. else:
  143. iratio = (float(insert[i]) / maxdiff) * histwidth
  144. dratio = (float(delete[i]) / maxdiff) * histwidth
  145. iwidth = dwidth = 0
  146. # make sure every entry that had actual insertions gets
  147. # at least one +
  148. if insert[i] > 0:
  149. iwidth = int(iratio)
  150. if iwidth == 0 and 0 < iratio < 1:
  151. iwidth = 1
  152. # make sure every entry that had actual deletions gets
  153. # at least one -
  154. if delete[i] > 0:
  155. dwidth = int(dratio)
  156. if dwidth == 0 and 0 < dratio < 1:
  157. dwidth = 1
  158. hist = b'+'*int(iwidth) + b'-'*int(dwidth)
  159. output += (format % (bytes(names[i]),
  160. str(insert[i] + delete[i]).encode('ascii'),
  161. hist))
  162. else:
  163. output += (binformat % (bytes(names[i]), b'Bin'))
  164. output += (b' %d files changed, %d insertions(+), %d deletions(-)'
  165. % (len(names), sum(insert), sum(delete)))
  166. return output
  167. def main():
  168. argv = sys.argv
  169. # allow diffstat.py to also be used from the comand line
  170. if len(sys.argv) > 1:
  171. diffpath = argv[1]
  172. data = b''
  173. with open(diffpath, 'rb') as f:
  174. data = f.read()
  175. lines = data.split(b'\n')
  176. result = diffstat(lines)
  177. print(result.decode('utf-8'))
  178. return 0
  179. # if no path argument to a diff file is passed in, run
  180. # a self test. The test case includes tricky things like
  181. # a diff of diff, binary files, renames with futher changes
  182. # added files and removed files.
  183. # All extracted from Sigil-Ebook/Sigil's github repo with
  184. # full permission to use under this license.
  185. selftest = b"""
  186. diff --git a/docs/qt512.7_remove_bad_workaround.patch b/docs/qt512.7_remove_bad_workaround.patch
  187. new file mode 100644
  188. index 00000000..64e34192
  189. --- /dev/null
  190. +++ b/docs/qt512.7_remove_bad_workaround.patch
  191. @@ -0,0 +1,15 @@
  192. +--- qtbase/src/gui/kernel/qwindow.cpp.orig 2019-12-12 09:15:59.000000000 -0500
  193. ++++ qtbase/src/gui/kernel/qwindow.cpp 2020-01-10 10:36:53.000000000 -0500
  194. +@@ -218,12 +218,6 @@
  195. + QGuiApplicationPrivate::window_list.removeAll(this);
  196. + if (!QGuiApplicationPrivate::is_app_closing)
  197. + QGuiApplicationPrivate::instance()->modalWindowList.removeOne(this);
  198. +-
  199. +- // focus_window is normally cleared in destroy(), but the window may in
  200. +- // some cases end up becoming the focus window again. Clear it again
  201. +- // here as a workaround. See QTBUG-75326.
  202. +- if (QGuiApplicationPrivate::focus_window == this)
  203. +- QGuiApplicationPrivate::focus_window = 0;
  204. + }
  205. +
  206. + void QWindowPrivate::init(QScreen *targetScreen)
  207. diff --git a/docs/testplugin_v017.zip b/docs/testplugin_v017.zip
  208. new file mode 100644
  209. index 00000000..a4cf4c4c
  210. Binary files /dev/null and b/docs/testplugin_v017.zip differ
  211. diff --git a/ci_scripts/macgddeploy.py b/ci_scripts/gddeploy.py
  212. similarity index 73%
  213. rename from ci_scripts/macgddeploy.py
  214. rename to ci_scripts/gddeploy.py
  215. index a512d075..f9dacd33 100644
  216. --- a/ci_scripts/macgddeploy.py
  217. +++ b/ci_scripts/gddeploy.py
  218. @@ -1,19 +1,32 @@
  219. #!/usr/bin/env python3
  220. import os
  221. +import sys
  222. import subprocess
  223. import datetime
  224. import shutil
  225. +import glob
  226. gparent = os.path.expandvars('$GDRIVE_DIR')
  227. grefresh_token = os.path.expandvars('$GDRIVE_REFRESH_TOKEN')
  228. -travis_branch = os.path.expandvars('$TRAVIS_BRANCH')
  229. -travis_commit = os.path.expandvars('$TRAVIS_COMMIT')
  230. -travis_build_number = os.path.expandvars('$TRAVIS_BUILD_NUMBER')
  231. +if sys.platform.lower().startswith('darwin'):
  232. + travis_branch = os.path.expandvars('$TRAVIS_BRANCH')
  233. + travis_commit = os.path.expandvars('$TRAVIS_COMMIT')
  234. + travis_build_number = os.path.expandvars('$TRAVIS_BUILD_NUMBER')
  235. +
  236. + origfilename = './bin/Sigil.tar.xz'
  237. + newfilename = './bin/Sigil-{}-{}-build_num-{}.tar.xz'.format(travis_branch, travis_commit[:7],travis_build_numbe\
  238. r)
  239. +else:
  240. + appveyor_branch = os.path.expandvars('$APPVEYOR_REPO_BRANCH')
  241. + appveyor_commit = os.path.expandvars('$APPVEYOR_REPO_COMMIT')
  242. + appveyor_build_number = os.path.expandvars('$APPVEYOR_BUILD_NUMBER')
  243. + names = glob.glob('.\\installer\\Sigil-*-Setup.exe')
  244. + if not names:
  245. + exit(1)
  246. + origfilename = names[0]
  247. + newfilename = '.\\installer\\Sigil-{}-{}-build_num-{}-Setup.exe'.format(appveyor_branch, appveyor_commit[:7], ap\
  248. pveyor_build_number)
  249. -origfilename = './bin/Sigil.tar.xz'
  250. -newfilename = './bin/Sigil-{}-{}-build_num-{}.tar.xz'.format(travis_branch, travis_commit[:7],travis_build_number)
  251. shutil.copy2(origfilename, newfilename)
  252. folder_name = datetime.date.today()
  253. diff --git a/docs/qt512.6_backport_009abcd_fix.patch b/docs/qt512.6_backport_009abcd_fix.patch
  254. deleted file mode 100644
  255. index f4724347..00000000
  256. --- a/docs/qt512.6_backport_009abcd_fix.patch
  257. +++ /dev/null
  258. @@ -1,26 +0,0 @@
  259. ---- qtbase/src/widgets/kernel/qwidget.cpp.orig 2019-11-08 10:57:07.000000000 -0500
  260. -+++ qtbase/src/widgets/kernel/qwidget.cpp 2019-12-11 12:32:24.000000000 -0500
  261. -@@ -8934,6 +8934,23 @@
  262. - }
  263. - }
  264. - switch (event->type()) {
  265. -+ case QEvent::PlatformSurface: {
  266. -+ // Sync up QWidget's view of whether or not the widget has been created
  267. -+ switch (static_cast<QPlatformSurfaceEvent*>(event)->surfaceEventType()) {
  268. -+ case QPlatformSurfaceEvent::SurfaceCreated:
  269. -+ if (!testAttribute(Qt::WA_WState_Created))
  270. -+ create();
  271. -+ break;
  272. -+ case QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed:
  273. -+ if (testAttribute(Qt::WA_WState_Created)) {
  274. -+ // Child windows have already been destroyed by QWindow,
  275. -+ // so we skip them here.
  276. -+ destroy(false, false);
  277. -+ }
  278. -+ break;
  279. -+ }
  280. -+ break;
  281. -+ }
  282. - case QEvent::MouseMove:
  283. - mouseMoveEvent((QMouseEvent*)event);
  284. - break;
  285. diff --git a/docs/Building_Sigil_On_MacOSX.txt b/docs/Building_Sigil_On_MacOSX.txt
  286. index 3b41fd80..64914c78 100644
  287. --- a/docs/Building_Sigil_On_MacOSX.txt
  288. +++ b/docs/Building_Sigil_On_MacOSX.txt
  289. @@ -113,7 +113,7 @@ install_name_tool -add_rpath @loader_path/../../Frameworks ./bin/Sigil.app/Content
  290. # To test if the newly bundled python 3 version of Sigil is working properly ypou can do the following:
  291. -1. download testplugin_v014.zip from https://github.com/Sigil-Ebook/Sigil/tree/master/docs
  292. +1. download testplugin_v017.zip from https://github.com/Sigil-Ebook/Sigil/tree/master/docs
  293. 2. open Sigil.app to the normal nearly blank template epub it generates when opened
  294. 3. use Plugins->Manage Plugins menu and make sure the "Use Bundled Python" checkbox is checked
  295. 4. use the "Add Plugin" button to navigate to and add testplugin.zip and then hit "Okay" to exit the Manage Plugins Dialog
  296. """ # noqa: E501 W293
  297. testoutput = b""" docs/qt512.7_remove_bad_workaround.patch | 15 ++++++++++++
  298. docs/testplugin_v017.zip | Bin
  299. ci_scripts/macgddeploy.py => ci_scripts/gddeploy.py | 0
  300. docs/qt512.6_backport_009abcd_fix.patch | 26 ---------------------
  301. docs/Building_Sigil_On_MacOSX.txt | 2 +-
  302. 5 files changed, 16 insertions(+), 27 deletions(-)""" # noqa: W291
  303. # return 0 on success otherwise return -1
  304. result = diffstat(selftest.split(b'\n'))
  305. if result == testoutput:
  306. print("self test passed")
  307. return 0
  308. print("self test failed")
  309. print("Received:")
  310. print(result.decode('utf-8'))
  311. print("Expected:")
  312. print(testoutput.decode('utf-8'))
  313. return -1
  314. if __name__ == '__main__':
  315. sys.exit(main())