Fundamental data type used to build file system tree structures. If CHILDREN is None, then the node represents a file. Otherwise, CHILDREN is a list of the nodes representing that directory's children. NAME is simply the name of the file or directory. CONTENTS is a string
| 27 | |
| 28 | |
| 29 | class TreeNode: |
| 30 | """ |
| 31 | Fundamental data type used to build file system tree structures. |
| 32 | |
| 33 | If CHILDREN is None, then the node represents a file. Otherwise, CHILDREN |
| 34 | is a list of the nodes representing that directory's children. |
| 35 | |
| 36 | NAME is simply the name of the file or directory. CONTENTS is a string |
| 37 | holding the file's contents (if a file). |
| 38 | |
| 39 | """ |
| 40 | |
| 41 | def __init__(self, name, children=None, contents=None): |
| 42 | assert children is None or contents is None |
| 43 | self.name = name |
| 44 | self.mtime = 0 |
| 45 | self.children = children |
| 46 | self.contents = contents |
| 47 | self.path = name |
| 48 | |
| 49 | def add_child(self, newchild): |
| 50 | assert not self.is_file() |
| 51 | for a in self.children: |
| 52 | if a.name == newchild.name: |
| 53 | if newchild.is_file(): |
| 54 | a.contents = newchild.contents |
| 55 | a.path = os.path.join(self.path, newchild.name) |
| 56 | else: |
| 57 | for i in newchild.children: |
| 58 | a.add_child(i) |
| 59 | break |
| 60 | else: |
| 61 | self.children.append(newchild) |
| 62 | newchild.path = os.path.join(self.path, newchild.name) |
| 63 | |
| 64 | def get_child(self, name): |
| 65 | """ |
| 66 | If the given TreeNode directory NODE contains a child named NAME, |
| 67 | return the child; else, return None. |
| 68 | |
| 69 | """ |
| 70 | for n in self.children: |
| 71 | if n.name == name: |
| 72 | return n |
| 73 | |
| 74 | def is_file(self): |
| 75 | return self.children is None |
| 76 | |
| 77 | def pprint(self): |
| 78 | print(" * Node name: %s" % self.name) |
| 79 | print(" Path: %s" % self.path) |
| 80 | print(" Contents: %s" % self.contents) |
| 81 | if self.is_file(): |
| 82 | print(" Children: is a file.") |
| 83 | else: |
| 84 | print(" Children: %d" % len(self.children)) |
| 85 | |
| 86 |