File: create_test_script_from_dependency_tree.py

package info (click to toggle)
python-ruffus 2.6.3%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 20,828 kB
  • ctags: 2,843
  • sloc: python: 15,745; makefile: 180; sh: 14
file content (333 lines) | stat: -rwxr-xr-x 10,651 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
#!/usr/bin/env python
from __future__ import print_function
"""

    draw_specified_dependency_tree.py

"""


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   options


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

from optparse import OptionParser
import sys, os
import os.path
try:
    import StringIO as io
except:
    import io as io

# add self to search path for testing
exe_path = os.path.split(os.path.abspath(sys.argv[0]))[0]
if __name__ == '__main__':
    module_name = os.path.split(sys.argv[0])[1]
    module_name = os.path.splitext(module_name)[0];
else:
    module_name = __name__

# graph, task etc are one directory down
if __name__ == '__main__':
    sys.path.append(os.path.abspath(os.path.join(exe_path,"..", "..")))
from ruffus import *



parser = OptionParser(version="%prog 1.0")
parser.add_option("-i", "--input_dot_file", dest="dot_file",
                  metavar="FILE",
                  default = os.path.join(exe_path, "dependency_data", "simple.dag"),
                  type="string",
                  help="name and path of tree file in modified DOT format used to generate "
                        "test script dependencies.")
parser.add_option("-o", "--output_file", dest="output_file",
                  metavar="FILE",
                  default = os.path.join(exe_path, "pipelines", "simple.py"),
                  type="string",
                  help="name and path of output python test script.")
parser.add_option("-v", "--verbose", dest = "verbose",
                  action="count", default=0,
                  help="Print more verbose messages for each additional verbose level.")
parser.add_option(  "-J", "--jumble_task_order", dest = "jumble_task_order",
                    action="store_true", default=False,
                    help="Do not define task functions in order of dependency.")

parameters = [
                ]

mandatory_parameters = ["dot_file"]






#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   imports


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

import re
import operator
import sys
from collections import defaultdict

import random

# use simplejson in place of json for python < 2.6
try:
    import json
except ImportError:
    import simplejson
    json = simplejson

dumps = json.dumps

#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   Functions


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888


#_________________________________________________________________________________________

#   make_tree_from_dotfile

#_________________________________________________________________________________________
from adjacent_pairs_iterate import adjacent_pairs_iterate





#_________________________________________________________________________________________

#   task_dependencies_from_dotfile

#_________________________________________________________________________________________
def task_dependencies_from_dotfile(stream):
    """
    Read programme task specified in dot file format
    """

    decorator_regex  = re.compile(r"([a-z_]+) *(\(.*)")
    attributes_regex = re.compile(r"\[.*\]")

    which_task_follows = defaultdict(list)
    task_decorators    = defaultdict(list)
    task_descriptions  = dict()

    #
    #   remember node
    #

    all_tasks = dict()
    io_tasks   = set()
    for linenum, line in enumerate(stream):
        # remove heading and trailing spaces
        line = line.strip()

        if "digraph" in line:
            continue;
        if not len(line):
            continue

        #
        #   decorators
        #
        if line[0:2] == '#@':
            fields = line[2:].split('::', 2)
            if len(fields) != 3:
                raise Exception("Unexpected task specification on line# %d\n(%s)" %
                                    (linenum, line))
            task_name, decorators, description = fields
            if decorators[0] != '@':
                raise Exception("Task decorator missing starting ampersand '@' on line# %d\n(%s)" %
                                    (linenum, line))
            for d in decorators[1:].split("@"):
                m = decorator_regex.match(d)
                if not m:
                    raise Exception("Task decorator (%s) missing parentheses on line# %d\n(%s)" %
                                    (d, linenum, line))
                task_decorators[task_name].append((m.group(1), m.group(2)))
                if m.group(1)[0:5] == "files" or m.group(1) == "parallel":
                    io_tasks.add(task_name)

            task_descriptions[task_name] = description
            continue

        #
        #   other comments
        #
        if line[0] in '#{}/':
            continue;
        line = line.strip(';')
        line = attributes_regex.sub("", line)

        #
        #   ignore assignments
        #
        if "=" in line:
            continue;
        nodes = [x.strip() for x in line.split('->')]
        for name1, name2 in adjacent_pairs_iterate(nodes):
            which_task_follows[name2].append(name1)
            all_tasks[name1] = 1
            all_tasks[name2] = 1

    for task in task_decorators:
        if task not in all_tasks:
            raise Exception("Decorated task %s not in dependencies")


    # order tasks by precedence the dump way: iterating until true
    disordered = True
    while (disordered):
        disordered = False
        for to_task, from_tasks in which_task_follows.items():
            for f in from_tasks:
                if all_tasks[to_task] <= all_tasks[f]:
                    all_tasks[to_task] += all_tasks[f]
                    disordered = True

    sorted_task_names =  list(sorted(list(all_tasks.keys()), key=lambda x:all_tasks[x]))
    return which_task_follows, sorted_task_names, task_decorators, io_tasks, task_descriptions




#_________________________________________________________________________________________

#   generate_program_task_file

#_________________________________________________________________________________________
def generate_program_task_file(stream, task_dependencies, task_names,
                                task_decorators, io_tasks, task_descriptions):

    print("task_decorators   = ", dumps(task_decorators, indent = 4), file=sys.stderr)
    print("task_names        = ", dumps(task_names), file=sys.stderr)
    print("task_dependencies = ", dumps(task_dependencies), file=sys.stderr)
    print("io_tasks          = ", dumps(list(io_tasks)), file=sys.stderr)


    if options.jumble_task_order:
        random.shuffle(task_names)
    defined_tasks = set()

    #
    #   iterate through tasks
    #
    for task_name in task_names:
        defined_tasks.add(task_name)
        stream.write("\n#\n#    %s\n#\n" % task_name)
        #
        #   write task decorators
        #
        if task_name in task_decorators:
            for decorator, decorator_parameters in task_decorators[task_name]:
                stream.write("@" + decorator + decorator_parameters + "\n")

        #
        #   write task dependencies
        #
        if task_name in task_dependencies:
            params = ", ".join(t if t in defined_tasks else '"%s"' % t
                                                    for t in task_dependencies[task_name])
            stream.write("@follows(%s)\n" % params)


        #
        #   Function body
        #
        #if task_name in io_tasks:
        if 1:
            stream.write("def %s(infiles, outfiles, *extra_params):\n" % task_name)
            stream.write('    """\n')
            description = task_descriptions[task_name]
            description = description.replace("\n", "    \n")
            stream.write('    %s\n' % description)
            stream.write('    """\n')

            stream.write("    test_job_io(infiles, outfiles, extra_params)\n")
        #else:
        #    stream.write("def %s(*params):\n" % task_name)


        stream.write("\n\n")

    stream.write(
    """
#
#   Necessary to protect the "entry point" of the program under windows.
#       see: http://docs.python.org/library/multiprocessing.html#multiprocessing-programming
#
if __name__ == '__main__':
    try:
        if options.just_print:
            pipeline_printout(sys.stdout, options.target_tasks, options.forced_tasks,
                                long_winded=True,
                                gnu_make_maximal_rebuild_mode = not options.minimal_rebuild_mode)

        elif options.dependency_file:
            pipeline_printout_graph (     open(options.dependency_file, "w"),
                                 options.dependency_graph_format,
                                 options.target_tasks,
                                 options.forced_tasks,
                                 draw_vertically = not options.draw_horizontally,
                                 gnu_make_maximal_rebuild_mode  = not options.minimal_rebuild_mode,
                                 no_key_legend  = options.no_key_legend_in_graph)
        else:
            pipeline_run(options.target_tasks, options.forced_tasks, multiprocess = options.jobs,
                            gnu_make_maximal_rebuild_mode  = not options.minimal_rebuild_mode,
                            pipeline= "main")
except Exception, e:
    print e.args
    \n""")




#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   Main logic


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888




# get help string
f =io.StringIO()
parser.print_help(f)
helpstr = f.getvalue()
(options, remaining_args) = parser.parse_args()
# mandatory options
for parameter in mandatory_parameters:
    if options.__dict__[parameter] is None:
        die_error("Please specify a file in --%s.\n\n" % parameter + helpstr)



(task_dependencies, task_names,
    task_decorators, io_tasks,
    task_descriptions) =  task_dependencies_from_dotfile(open(options.dot_file))

output_file = open(options.output_file, "w")

#
#   print template for python file output
#
output_file.write(open(os.path.join(exe_path,"test_script.py_template")).read().
                    replace("PYPER_PATH",
                    os.path.abspath(os.path.join(exe_path, "..", ".."))))
generate_program_task_file(output_file, task_dependencies, task_names,
                                task_decorators, io_tasks, task_descriptions)