Mercurial > hg > config
annotate python/tree.py @ 429:9b7f5e31b465
python/tree.py
author | Jeff Hammel <jhammel@mozilla.com> |
---|---|
date | Wed, 07 Aug 2013 06:33:16 -0700 |
parents | 866c5b1bc4e8 |
children | fbb5b143349a |
rev | line source |
---|---|
382 | 1 #!/usr/bin/env python |
2 # -*- coding: utf-8 -*- | |
3 | |
4 """ | |
5 tree in python | |
6 """ | |
7 | |
425 | 8 # TODO: script2package |
9 | |
382 | 10 import optparse |
11 import os | |
12 import sys | |
13 | |
387 | 14 # ASCII delimeters |
388 | 15 ascii_delimeters = { |
389 | 16 'vertical_line' : '|', |
17 'item_marker' : '+', | |
18 'last_child' : '\\' | |
388 | 19 } |
387 | 20 |
21 # unicode delimiters | |
389 | 22 unicode_delimeters = { |
23 'vertical_line' : '│', | |
24 'item_marker' : '├', | |
25 'last_child' : '└' | |
26 } | |
382 | 27 |
425 | 28 |
382 | 29 def depth(directory): |
387 | 30 """returns the integer depth of a directory or path relative to '/' """ |
31 | |
382 | 32 directory = os.path.abspath(directory) |
33 level = 0 | |
34 while True: | |
35 directory, remainder = os.path.split(directory) | |
36 level += 1 | |
37 if not remainder: | |
38 break | |
39 return level | |
40 | |
425 | 41 |
42 ### stuff for tree generalization | |
43 | |
44 class Tree(object): | |
45 """tree structure in python""" | |
46 | |
47 def __init__(self, parent=None): | |
48 self.parent = parent | |
426 | 49 self._children = [] |
425 | 50 |
51 def children(self): | |
52 """returns children of the tree""" | |
426 | 53 return self._children # base implementation |
425 | 54 |
55 def add(self, item): | |
56 """add a child to the tree root""" | |
57 | |
58 def update(self, tree): | |
59 """add a subtree to the tree""" | |
60 self.add(tree) | |
61 tree.parent = self # XXX .add should probably do this for scary reasons | |
62 | |
63 def output(self, serializer): | |
64 """output the tree via the given serializer""" | |
65 # XXX or should this method exist at all and instead the | |
66 # __call__ method of serializers take a Tree object? | |
67 | |
68 class DirectoryTree(Tree): | |
69 """directory structure as a tree""" | |
70 | |
429 | 71 def __init__(self, directory): |
72 self.directory = directory | |
73 self._return_type = os.path.abspath | |
74 | |
75 def children(self): | |
76 return os.listdir(self.directory) # -> self._return_type | |
77 | |
78 ## Serializers | |
79 | |
80 # How to serialize a tree -> JSON? | |
81 | |
425 | 82 ### |
83 | |
388 | 84 def tree(directory, |
389 | 85 item_marker=unicode_delimeters['item_marker'], |
86 vertical_line=unicode_delimeters['vertical_line'], | |
87 last_child=unicode_delimeters['last_child'], | |
388 | 88 sort_key=lambda x: x.lower()): |
89 """ | |
90 display tree directory structure for `directory` | |
91 """ | |
383
8d1ad56761b0
this still, somehow, eludes my tired brain
Jeff Hammel <jhammel@mozilla.com>
parents:
382
diff
changeset
|
92 |
385 | 93 retval = [] |
383
8d1ad56761b0
this still, somehow, eludes my tired brain
Jeff Hammel <jhammel@mozilla.com>
parents:
382
diff
changeset
|
94 indent = [] |
384 | 95 last = {} |
386 | 96 top = depth(directory) |
97 | |
382 | 98 for dirpath, dirnames, filenames in os.walk(directory, topdown=True): |
383
8d1ad56761b0
this still, somehow, eludes my tired brain
Jeff Hammel <jhammel@mozilla.com>
parents:
382
diff
changeset
|
99 |
8d1ad56761b0
this still, somehow, eludes my tired brain
Jeff Hammel <jhammel@mozilla.com>
parents:
382
diff
changeset
|
100 abspath = os.path.abspath(dirpath) |
384 | 101 basename = os.path.basename(abspath) |
102 parent = os.path.dirname(abspath) | |
383
8d1ad56761b0
this still, somehow, eludes my tired brain
Jeff Hammel <jhammel@mozilla.com>
parents:
382
diff
changeset
|
103 level = depth(abspath) - top |
8d1ad56761b0
this still, somehow, eludes my tired brain
Jeff Hammel <jhammel@mozilla.com>
parents:
382
diff
changeset
|
104 |
8d1ad56761b0
this still, somehow, eludes my tired brain
Jeff Hammel <jhammel@mozilla.com>
parents:
382
diff
changeset
|
105 # sort articles of interest |
8d1ad56761b0
this still, somehow, eludes my tired brain
Jeff Hammel <jhammel@mozilla.com>
parents:
382
diff
changeset
|
106 for resource in (dirnames, filenames): |
8d1ad56761b0
this still, somehow, eludes my tired brain
Jeff Hammel <jhammel@mozilla.com>
parents:
382
diff
changeset
|
107 resource[:] = sorted(resource, key=sort_key) |
382 | 108 |
389 | 109 files_end = item_marker |
110 dirpath_marker = item_marker | |
385 | 111 |
112 if level > len(indent): | |
389 | 113 indent.append(vertical_line) |
385 | 114 indent = indent[:level] |
115 | |
383
8d1ad56761b0
this still, somehow, eludes my tired brain
Jeff Hammel <jhammel@mozilla.com>
parents:
382
diff
changeset
|
116 if dirnames: |
389 | 117 files_end = item_marker |
385 | 118 last[abspath] = dirnames[-1] |
119 else: | |
389 | 120 files_end = last_child |
384 | 121 |
385 | 122 if last.get(parent) == os.path.basename(abspath): |
123 # last directory of parent | |
389 | 124 dirpath_mark = last_child |
385 | 125 indent[-1] = ' ' |
126 elif not indent: | |
127 dirpath_mark = '' | |
128 else: | |
389 | 129 dirpath_mark = item_marker |
385 | 130 |
388 | 131 # append the directory and piece of tree structure |
132 # if the top-level entry directory, print as passed | |
133 retval.append('%s%s%s'% (''.join(indent[:-1]), | |
134 dirpath_mark, | |
135 basename if retval else directory)) | |
136 # add the files | |
385 | 137 if filenames: |
138 last_file = filenames[-1] | |
387 | 139 retval.extend([('%s%s%s' % (''.join(indent), |
389 | 140 files_end if filename == last_file else item_marker, |
385 | 141 filename)) |
142 for index, filename in enumerate(filenames)]) | |
143 | |
382 | 144 return '\n'.join(retval) |
145 | |
146 def main(args=sys.argv[1:]): | |
147 | |
390
9d02187611ae
make delimeters CLI switchable
Jeff Hammel <jhammel@mozilla.com>
parents:
389
diff
changeset
|
148 # parse command line options |
382 | 149 usage = '%prog [options]' |
150 parser = optparse.OptionParser(usage=usage, description=__doc__) | |
390
9d02187611ae
make delimeters CLI switchable
Jeff Hammel <jhammel@mozilla.com>
parents:
389
diff
changeset
|
151 parser.add_option('-a', '--ascii', dest='use_ascii', |
9d02187611ae
make delimeters CLI switchable
Jeff Hammel <jhammel@mozilla.com>
parents:
389
diff
changeset
|
152 action='store_true', default=False, |
9d02187611ae
make delimeters CLI switchable
Jeff Hammel <jhammel@mozilla.com>
parents:
389
diff
changeset
|
153 help="use ascii delimeters (%s)" % ascii_delimeters) |
382 | 154 options, args = parser.parse_args(args) |
155 if not args: | |
156 args = ['.'] | |
157 | |
390
9d02187611ae
make delimeters CLI switchable
Jeff Hammel <jhammel@mozilla.com>
parents:
389
diff
changeset
|
158 # sanity check |
382 | 159 not_directory = [arg for arg in args |
160 if not os.path.isdir(arg)] | |
161 if not_directory: | |
162 parser.error("Not a directory: %s" % (', '.join(not_directory))) | |
163 | |
390
9d02187611ae
make delimeters CLI switchable
Jeff Hammel <jhammel@mozilla.com>
parents:
389
diff
changeset
|
164 delimeters = unicode_delimeters |
9d02187611ae
make delimeters CLI switchable
Jeff Hammel <jhammel@mozilla.com>
parents:
389
diff
changeset
|
165 if options.use_ascii: |
9d02187611ae
make delimeters CLI switchable
Jeff Hammel <jhammel@mozilla.com>
parents:
389
diff
changeset
|
166 delimeters = ascii_delimeters |
9d02187611ae
make delimeters CLI switchable
Jeff Hammel <jhammel@mozilla.com>
parents:
389
diff
changeset
|
167 |
9d02187611ae
make delimeters CLI switchable
Jeff Hammel <jhammel@mozilla.com>
parents:
389
diff
changeset
|
168 # print the tree |
382 | 169 for arg in args: |
390
9d02187611ae
make delimeters CLI switchable
Jeff Hammel <jhammel@mozilla.com>
parents:
389
diff
changeset
|
170 print (tree(arg, **delimeters)) |
382 | 171 |
172 if __name__ == '__main__': | |
173 main() |