diffstat.py 14 KB

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