1
0

dl_cleanup.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. #!/usr/bin/env python3
  2. """
  3. # OpenWrt download directory cleanup utility.
  4. # Delete all but the very last version of the program tarballs.
  5. #
  6. # Copyright (C) 2010-2015 Michael Buesch <m@bues.ch>
  7. # Copyright (C) 2013-2015 OpenWrt.org
  8. """
  9. from __future__ import print_function
  10. import sys
  11. import os
  12. import re
  13. import getopt
  14. # Commandline options
  15. opt_dryrun = False
  16. def parseVer_1234(match, filepath):
  17. progname = match.group(1)
  18. progversion = (int(match.group(2)) << 64) |\
  19. (int(match.group(3)) << 48) |\
  20. (int(match.group(4)) << 32) |\
  21. (int(match.group(5)) << 16)
  22. return (progname, progversion)
  23. def parseVer_123(match, filepath):
  24. progname = match.group(1)
  25. try:
  26. patchlevel = match.group(5)
  27. except IndexError as e:
  28. patchlevel = None
  29. if patchlevel:
  30. patchlevel = ord(patchlevel[0])
  31. else:
  32. patchlevel = 0
  33. progversion = (int(match.group(2)) << 64) |\
  34. (int(match.group(3)) << 48) |\
  35. (int(match.group(4)) << 32) |\
  36. patchlevel
  37. return (progname, progversion)
  38. def parseVer_12(match, filepath):
  39. progname = match.group(1)
  40. try:
  41. patchlevel = match.group(4)
  42. except IndexError as e:
  43. patchlevel = None
  44. if patchlevel:
  45. patchlevel = ord(patchlevel[0])
  46. else:
  47. patchlevel = 0
  48. progversion = (int(match.group(2)) << 64) |\
  49. (int(match.group(3)) << 48) |\
  50. patchlevel
  51. return (progname, progversion)
  52. def parseVer_r(match, filepath):
  53. progname = match.group(1)
  54. progversion = (int(match.group(2)) << 64)
  55. return (progname, progversion)
  56. def parseVer_ymd(match, filepath):
  57. progname = match.group(1)
  58. progversion = (int(match.group(2)) << 64) |\
  59. (int(match.group(3)) << 48) |\
  60. (int(match.group(4)) << 32)
  61. return (progname, progversion)
  62. def parseVer_GIT(match, filepath):
  63. progname = match.group(1)
  64. st = os.stat(filepath)
  65. progversion = int(st.st_mtime) << 64
  66. return (progname, progversion)
  67. extensions = (
  68. ".tar.gz",
  69. ".tar.bz2",
  70. ".tar.xz",
  71. ".orig.tar.gz",
  72. ".orig.tar.bz2",
  73. ".orig.tar.xz",
  74. ".zip",
  75. ".tgz",
  76. ".tbz",
  77. ".txz",
  78. )
  79. versionRegex = (
  80. (re.compile(r"(.+)[-_](\d+)\.(\d+)\.(\d+)\.(\d+)"), parseVer_1234), # xxx-1.2.3.4
  81. (re.compile(r"(.+)[-_](\d\d\d\d)-?(\d\d)-?(\d\d)"), parseVer_ymd), # xxx-YYYY-MM-DD
  82. (re.compile(r"(.+)[-_]([0-9a-fA-F]{40,40})"), parseVer_GIT), # xxx-GIT_SHASUM
  83. (re.compile(r"(.+)[-_](\d+)\.(\d+)\.(\d+)(\w?)"), parseVer_123), # xxx-1.2.3a
  84. (re.compile(r"(.+)[-_](\d+)_(\d+)_(\d+)"), parseVer_123), # xxx-1_2_3
  85. (re.compile(r"(.+)[-_](\d+)\.(\d+)(\w?)"), parseVer_12), # xxx-1.2a
  86. (re.compile(r"(.+)[-_]r?(\d+)"), parseVer_r), # xxx-r1111
  87. )
  88. blacklist = [
  89. ("linux", re.compile(r"linux-\d.*")),
  90. ("gcc", re.compile(r"gcc-.*")),
  91. ("wl_apsta", re.compile(r"wl_apsta.*")),
  92. (".fw", re.compile(r".*\.fw")),
  93. (".arm", re.compile(r".*\.arm")),
  94. (".bin", re.compile(r".*\.bin")),
  95. ("rt-firmware", re.compile(r"RT[\d\w]+_Firmware.*")),
  96. ]
  97. class EntryParseError(Exception): pass
  98. class Entry:
  99. def __init__(self, directory, filename):
  100. self.directory = directory
  101. self.filename = filename
  102. self.progname = ""
  103. self.fileext = ""
  104. for ext in extensions:
  105. if filename.endswith(ext):
  106. filename = filename[0:0-len(ext)]
  107. self.fileext = ext
  108. break
  109. else:
  110. print(self.filename, "has an unknown file-extension")
  111. raise EntryParseError("ext")
  112. for (regex, parseVersion) in versionRegex:
  113. match = regex.match(filename)
  114. if match:
  115. (self.progname, self.version) = parseVersion(
  116. match, directory + "/" + filename + self.fileext)
  117. break
  118. else:
  119. print(self.filename, "has an unknown version pattern")
  120. raise EntryParseError("ver")
  121. def getPath(self):
  122. return (self.directory + "/" + self.filename).replace("//", "/")
  123. def deleteFile(self):
  124. path = self.getPath()
  125. print("Deleting", path)
  126. if not opt_dryrun:
  127. os.unlink(path)
  128. def __ge__(self, y):
  129. return self.version >= y.version
  130. def usage():
  131. print("OpenWrt download directory cleanup utility")
  132. print("Usage: " + sys.argv[0] + " [OPTIONS] <path/to/dl>")
  133. print("")
  134. print(" -d|--dry-run Do a dry-run. Don't delete any files")
  135. print(" -B|--show-blacklist Show the blacklist and exit")
  136. print(" -w|--whitelist ITEM Remove ITEM from blacklist")
  137. def main(argv):
  138. global opt_dryrun
  139. try:
  140. (opts, args) = getopt.getopt(argv[1:],
  141. "hdBw:",
  142. [ "help", "dry-run", "show-blacklist", "whitelist=", ])
  143. if len(args) != 1:
  144. usage()
  145. return 1
  146. except getopt.GetoptError as e:
  147. usage()
  148. return 1
  149. directory = args[0]
  150. for (o, v) in opts:
  151. if o in ("-h", "--help"):
  152. usage()
  153. return 0
  154. if o in ("-d", "--dry-run"):
  155. opt_dryrun = True
  156. if o in ("-w", "--whitelist"):
  157. for i in range(0, len(blacklist)):
  158. (name, regex) = blacklist[i]
  159. if name == v:
  160. del blacklist[i]
  161. break
  162. else:
  163. print("Whitelist error: Item", v,\
  164. "is not in blacklist")
  165. return 1
  166. if o in ("-B", "--show-blacklist"):
  167. for (name, regex) in blacklist:
  168. sep = "\t\t"
  169. if len(name) >= 8:
  170. sep = "\t"
  171. print("%s%s(%s)" % (name, sep, regex.pattern))
  172. return 0
  173. # Create a directory listing and parse the file names.
  174. entries = []
  175. for filename in os.listdir(directory):
  176. if filename == "." or filename == "..":
  177. continue
  178. for (name, regex) in blacklist:
  179. if regex.match(filename):
  180. if opt_dryrun:
  181. print(filename, "is blacklisted")
  182. break
  183. else:
  184. try:
  185. entries.append(Entry(directory, filename))
  186. except EntryParseError as e:
  187. pass
  188. # Create a map of programs
  189. progmap = {}
  190. for entry in entries:
  191. if entry.progname in progmap.keys():
  192. progmap[entry.progname].append(entry)
  193. else:
  194. progmap[entry.progname] = [entry,]
  195. # Traverse the program map and delete everything but the last version
  196. for prog in progmap:
  197. lastVersion = None
  198. versions = progmap[prog]
  199. for version in versions:
  200. if lastVersion is None or version >= lastVersion:
  201. lastVersion = version
  202. if lastVersion:
  203. for version in versions:
  204. if version is not lastVersion:
  205. version.deleteFile()
  206. if opt_dryrun:
  207. print("Keeping", lastVersion.getPath())
  208. return 0
  209. if __name__ == "__main__":
  210. sys.exit(main(sys.argv))