tree.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. # Copyright 2003 Dave Abrahams
  2. # Copyright 2001, 2002 Vladimir Prus
  3. # Copyright 2012 Jurko Gospodnetic
  4. # Distributed under the Boost Software License, Version 1.0.
  5. # (See accompanying file LICENSE.txt or copy at
  6. # https://www.bfgroup.xyz/b2/LICENSE.txt)
  7. ###############################################################################
  8. #
  9. # Based in part on an old Subversion tree.py source file (tools for comparing
  10. # directory trees). See http://subversion.tigris.org for more information.
  11. #
  12. # Copyright (c) 2001 Sam Tobin-Hochstadt. All rights reserved.
  13. #
  14. # This software is licensed as described in the file COPYING, which you should
  15. # have received as part of this distribution. The terms are also available at
  16. # http://subversion.tigris.org/license-1.html. If newer versions of this
  17. # license are posted there, you may use a newer version instead, at your
  18. # option.
  19. #
  20. ###############################################################################
  21. from __future__ import print_function
  22. import os
  23. import os.path
  24. import stat
  25. import sys
  26. class TreeNode:
  27. """
  28. Fundamental data type used to build file system tree structures.
  29. If CHILDREN is None, then the node represents a file. Otherwise, CHILDREN
  30. is a list of the nodes representing that directory's children.
  31. NAME is simply the name of the file or directory. CONTENTS is a string
  32. holding the file's contents (if a file).
  33. """
  34. def __init__(self, name, children=None, contents=None):
  35. assert children is None or contents is None
  36. self.name = name
  37. self.mtime = 0
  38. self.children = children
  39. self.contents = contents
  40. self.path = name
  41. def add_child(self, newchild):
  42. assert not self.is_file()
  43. for a in self.children:
  44. if a.name == newchild.name:
  45. if newchild.is_file():
  46. a.contents = newchild.contents
  47. a.path = os.path.join(self.path, newchild.name)
  48. else:
  49. for i in newchild.children:
  50. a.add_child(i)
  51. break
  52. else:
  53. self.children.append(newchild)
  54. newchild.path = os.path.join(self.path, newchild.name)
  55. def get_child(self, name):
  56. """
  57. If the given TreeNode directory NODE contains a child named NAME,
  58. return the child; else, return None.
  59. """
  60. for n in self.children:
  61. if n.name == name:
  62. return n
  63. def is_file(self):
  64. return self.children is None
  65. def pprint(self):
  66. print(" * Node name: %s" % self.name)
  67. print(" Path: %s" % self.path)
  68. print(" Contents: %s" % self.contents)
  69. if self.is_file():
  70. print(" Children: is a file.")
  71. else:
  72. print(" Children: %d" % len(self.children))
  73. class TreeDifference:
  74. def __init__(self):
  75. self.added_files = []
  76. self.removed_files = []
  77. self.modified_files = []
  78. self.touched_files = []
  79. def append(self, other):
  80. self.added_files.extend(other.added_files)
  81. self.removed_files.extend(other.removed_files)
  82. self.modified_files.extend(other.modified_files)
  83. self.touched_files.extend(other.touched_files)
  84. def ignore_directories(self):
  85. """Removes directories from our lists of found differences."""
  86. not_dir = lambda x : x[-1] != "/"
  87. self.added_files = list(filter(not_dir, self.added_files))
  88. self.removed_files = list(filter(not_dir, self.removed_files))
  89. self.modified_files = list(filter(not_dir, self.modified_files))
  90. self.touched_files = list(filter(not_dir, self.touched_files))
  91. def pprint(self, file=sys.stdout):
  92. file.write("Added files : %s\n" % self.added_files)
  93. file.write("Removed files : %s\n" % self.removed_files)
  94. file.write("Modified files: %s\n" % self.modified_files)
  95. file.write("Touched files : %s\n" % self.touched_files)
  96. def empty(self):
  97. return not (self.added_files or self.removed_files or
  98. self.modified_files or self.touched_files)
  99. def build_tree(path):
  100. """
  101. Takes PATH as the folder path, walks the file system below that path, and
  102. creates a tree structure based on any files and folders found there.
  103. Returns the prepared tree structure plus the maximum file modification
  104. timestamp under the given folder.
  105. """
  106. return _handle_dir(os.path.normpath(path))
  107. def tree_difference(a, b):
  108. """Compare TreeNodes A and B, and create a TreeDifference instance."""
  109. return _do_tree_difference(a, b, "", True)
  110. def _do_tree_difference(a, b, parent_path, root=False):
  111. """Internal recursive worker function for tree_difference()."""
  112. # We do not want to list root node names.
  113. if root:
  114. assert not parent_path
  115. assert not a.is_file()
  116. assert not b.is_file()
  117. full_path = ""
  118. else:
  119. assert a.name == b.name
  120. full_path = parent_path + a.name
  121. result = TreeDifference()
  122. # A and B are both files.
  123. if a.is_file() and b.is_file():
  124. if a.contents != b.contents:
  125. result.modified_files.append(full_path)
  126. elif a.mtime != b.mtime:
  127. result.touched_files.append(full_path)
  128. return result
  129. # Directory converted to file.
  130. if not a.is_file() and b.is_file():
  131. result.removed_files.extend(_traverse_tree(a, parent_path))
  132. result.added_files.append(full_path)
  133. # File converted to directory.
  134. elif a.is_file() and not b.is_file():
  135. result.removed_files.append(full_path)
  136. result.added_files.extend(_traverse_tree(b, parent_path))
  137. # A and B are both directories.
  138. else:
  139. if full_path:
  140. full_path += "/"
  141. accounted_for = [] # Children present in both trees.
  142. for a_child in a.children:
  143. b_child = b.get_child(a_child.name)
  144. if b_child:
  145. accounted_for.append(b_child)
  146. result.append(_do_tree_difference(a_child, b_child, full_path))
  147. else:
  148. result.removed_files.append(full_path + a_child.name)
  149. for b_child in b.children:
  150. if b_child not in accounted_for:
  151. result.added_files.extend(_traverse_tree(b_child, full_path))
  152. return result
  153. def _traverse_tree(t, parent_path):
  154. """Returns a list of all names in a tree."""
  155. assert not parent_path or parent_path[-1] == "/"
  156. full_node_name = parent_path + t.name
  157. if t.is_file():
  158. result = [full_node_name]
  159. else:
  160. name_prefix = full_node_name + "/"
  161. result = [name_prefix]
  162. for i in t.children:
  163. result.extend(_traverse_tree(i, name_prefix))
  164. return result
  165. def _get_text(path):
  166. """Return a string with the textual contents of a file at PATH."""
  167. fp = open(path, 'rb')
  168. try:
  169. return fp.read()
  170. finally:
  171. fp.close()
  172. def _handle_dir(path):
  173. """
  174. Main recursive worker function for build_tree(). Returns a newly created
  175. tree node representing the given normalized folder path as well as the
  176. maximum file/folder modification time detected under the same path.
  177. """
  178. files = []
  179. dirs = []
  180. node = TreeNode(os.path.basename(path), children=[])
  181. max_mtime = node.mtime = os.stat(path).st_mtime
  182. # List files & folders.
  183. for f in os.listdir(path):
  184. f = os.path.join(path, f)
  185. if os.path.isdir(f):
  186. dirs.append(f)
  187. elif os.path.isfile(f):
  188. files.append(f)
  189. # Add a child node for each file.
  190. for f in files:
  191. fcontents = _get_text(f)
  192. new_file_node = TreeNode(os.path.basename(f), contents=fcontents)
  193. new_file_node.mtime = os.stat(f).st_mtime
  194. max_mtime = max(max_mtime, new_file_node.mtime)
  195. node.add_child(new_file_node)
  196. # For each subdir, create a node, walk its tree, add it as a child.
  197. for d in dirs:
  198. new_dir_node, new_max_mtime = _handle_dir(d)
  199. max_mtime = max(max_mtime, new_max_mtime)
  200. node.add_child(new_dir_node)
  201. return node, max_mtime