http://scons.tigris.org/issues/show_bug.cgi?id=2329
[scons.git] / bin / import-test.py
1 #!/usr/bin/env python
2 #
3 # __COPYRIGHT__
4 #
5 # tree2test.py - turn a directory tree into TestSCons code
6 #
7 # A quick script for importing directory hierarchies containing test
8 # cases that people supply (typically in a .zip or .tar.gz file) into a
9 # TestSCons.py script.  No error checking or options yet, it just walks
10 # the first command-line argument (assumed to be the directory containing
11 # the test case) and spits out code looking like the following:
12 #
13 #       test.subdir(['sub1'],
14 #                   ['sub1', 'sub2'])
15 #
16 #       test.write(['sub1', 'file1'], """\
17 #       contents of file1
18 #       """)
19 #
20 #       test.write(['sub1', 'sub2', 'file2'], """\
21 #       contents of file2
22 #       """)
23 #
24 # There's no massaging of contents, so any files that themselves contain
25 # """ triple-quotes will need to have their contents edited by hand.
26 #
27
28 __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
29
30 import os.path
31 import sys
32
33 directory = sys.argv[1]
34
35 Top = None
36 TopPath = None
37
38 class Dir:
39     def __init__(self, path):
40         self.path = path
41         self.entries = {}
42     def call_for_each_entry(self, func):
43         for name in sorted(self.entries.keys()):
44             func(name, self.entries[name])
45
46 def lookup(dirname):
47     global Top, TopPath
48     if not Top:
49         Top = Dir([])
50         TopPath = dirname + os.sep
51         return Top
52     dirname = dirname.replace(TopPath, '')
53     dirs = dirname.split(os.sep)
54     t = Top
55     for d in dirs[:-1]:
56         t = t.entries[d]
57     node = t.entries[dirs[-1]] = Dir(dirs)
58     return node
59
60 def make_nodes(arg, dirname, fnames):
61     dir = lookup(dirname)
62     for f in fnames:
63         dir.entries[f] = None
64
65 def collect_dirs(l, dir):
66     if dir.path:
67         l.append(dir.path)
68     def recurse(n, d):
69         if d:
70             collect_dirs(l, d)
71     dir.call_for_each_entry(recurse)
72
73 def print_files(dir):
74     def print_a_file(n, d):
75         if not d:
76             l = dir.path + [n]
77             sys.stdout.write('\ntest.write(%s, """\\\n' % l)
78             p = os.path.join(directory, *l)
79             sys.stdout.write(open(p, 'r').read())
80             sys.stdout.write('""")\n')
81     dir.call_for_each_entry(print_a_file)
82
83     def recurse(n, d):
84         if d:
85             print_files(d)
86     dir.call_for_each_entry(recurse)
87
88 os.path.walk(directory, make_nodes, None)
89
90 subdir_list = []
91 collect_dirs(subdir_list, Top)
92 subdir_list = [ str(l) for l in subdir_list ]
93 sys.stdout.write('test.subdir(' + ',\n            '.join(subdir_list) + ')\n')
94
95 print_files(Top)
96
97 # Local Variables:
98 # tab-width:4
99 # indent-tabs-mode:nil
100 # End:
101 # vim: set expandtab tabstop=4 shiftwidth=4: