diffstat.py 13 KB

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