diffstat.py 13 KB

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