parameter.py 43.8 KB
Newer Older
Jerome Mariette's avatar
Jerome Mariette committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#
# Copyright (C) 2012 INRA
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

Frédéric Escudié's avatar
Frédéric Escudié committed
18
import re
19
import sys
Jerome Mariette's avatar
Jerome Mariette committed
20
import types
Jerome Mariette's avatar
Jerome Mariette committed
21
import datetime
Jerome Mariette's avatar
Jerome Mariette committed
22
import logging
Jerome Mariette's avatar
Jerome Mariette committed
23
import argparse
Jerome Mariette's avatar
Jerome Mariette committed
24
import os
25
import fnmatch
Jerome Mariette's avatar
Jerome Mariette committed
26
import tempfile
27
from argparse import _ensure_value
Jerome Mariette's avatar
Jerome Mariette committed
28
import urllib2
29
import copy as _copy
Jerome Mariette's avatar
Jerome Mariette committed
30
from urlparse import urlparse
31

Jerome Mariette's avatar
Jerome Mariette committed
32
from jflow.config_reader import JFlowConfigReader
Jerome Mariette's avatar
Jerome Mariette committed
33
from jflow.utils import get_octet_string_representation, get_nb_octet, display_error_message
Jerome Mariette's avatar
Jerome Mariette committed
34

Jerome Mariette's avatar
Jerome Mariette committed
35
# import custom types and custom formats
Jerome Mariette's avatar
Jerome Mariette committed
36
from workflows.types import *
Jerome Mariette's avatar
Jerome Mariette committed
37
from workflows.formats import *
Jerome Mariette's avatar
Jerome Mariette committed
38

Jerome Mariette's avatar
Jerome Mariette committed
39
40

# define all input type available
Frédéric Escudié's avatar
Frédéric Escudié committed
41
INPUTFILE_TYPES = ["inputfile", "localfile", "urlfile", "browsefile"]
42
INPUTFILES_TYPES = ["inputfiles", "localfile", "urlfile", "browsefile", "regexpfiles"]
Jerome Mariette's avatar
Jerome Mariette committed
43
44
45
46
47
48
49
50

def browsefile(file):
    # browsefile are not available from command line, considere it as a localfile
    # from the gui, this will not been tested this way
    return localfile(file)

def localfile(file):
    if os.path.isfile(file):
Frédéric Escudié's avatar
Frédéric Escudié committed
51
        return file
Jerome Mariette's avatar
Jerome Mariette committed
52
    else:
Jerome Mariette's avatar
Jerome Mariette committed
53
        raise argparse.ArgumentTypeError("File '" + file + "' does not exists! Please provide a valid file path!")
54

Jerome Mariette's avatar
Jerome Mariette committed
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def urlfile(file):
    uri_object = urlparse(file)
    try:
        opener = urllib2.urlopen(file)
    except:
        raise argparse.ArgumentTypeError("URL '" + file + "' is invalid!")
    file_name = os.path.basename(uri_object.path)
    if file_name is not None and file_name != "":
        metadata = opener.info()
        file_size = int(metadata.getheaders("Content-Length")[0])
        if file_size == 0:
            raise argparse.ArgumentTypeError("The URL file '" + file + "' is empty!")
        return file
    else:
        raise argparse.ArgumentTypeError("URL '" + file + "' does not contain any file name!")
70

Jerome Mariette's avatar
Jerome Mariette committed
71
def inputfile(file):
72
73
74
75
76
77
78
79
80
    # test the format
    uri_object = urlparse(file)
    # check the file
    if uri_object.scheme == '':
        return localfile(file)
    else:
        return urlfile(file)

def inputfiles(file):
Jerome Mariette's avatar
Jerome Mariette committed
81
82
83
84
    # test the format
    uri_object = urlparse(file)
    # check the file
    if uri_object.scheme == '':
Frédéric Escudié's avatar
Frédéric Escudié committed
85
86
87
88
89
        try:
            regexpfiles(file)
            return file
        except:
            return localfile(file)
Jerome Mariette's avatar
Jerome Mariette committed
90
91
    else:
        return urlfile(file)
92

Frédéric Escudié's avatar
Frédéric Escudié committed
93
def regexpfiles(files_pattern):
94
95
96
97
98
99
    try:
        if ':' in files_pattern:
            folder, pattern = files_pattern.rsplit(':')
        else:
            folder, pattern = os.path.split(files_pattern)
    except:
100
101
102
        raise argparse.ArgumentTypeError("Regexp '" + files_pattern + "' is invalid!")
    if not pattern:
        raise argparse.ArgumentTypeError("Regexp '" + files_pattern + "' is invalid!")
Frédéric Escudié's avatar
Frédéric Escudié committed
103
104
105
106
    if not os.path.exists(folder):
        raise argparse.ArgumentTypeError("The folder '" + folder + "' doesn't exist!")
    if not os.access(folder, os.R_OK):
        raise argparse.ArgumentTypeError("You do not have permission to read '" + folder + "'!")
107
108
109
110
111
112
    nb_files = 0
    for item in sorted(os.listdir(folder)):
        if os.path.isfile(os.path.join(folder, item)) and fnmatch.fnmatch(item, pattern):
            nb_files += 1
    if nb_files == 0:
        raise argparse.ArgumentTypeError("0 file selected by the regexp!")
Frédéric Escudié's avatar
Frédéric Escudié committed
113
    return files_pattern
114

115
116
def create_test_function(itype):
    try: itype = itype.encode('ascii','ignore')
Jerome Mariette's avatar
Jerome Mariette committed
117
    except: pass
118
    try:
119
        ctype, csizel = itype.split(AbstractInputFile.SIZE_LIMIT_SPLITER)
120
        def inner_function(ifile):
Jerome Mariette's avatar
Jerome Mariette committed
121
122
            # first eval the asked type
            returned_value = eval(ctype)(ifile)
123
124
125
126
127
            # if 0 unlimited size
            if csizel != "0":
                # first test the size of the file
                uri_object = urlparse(ifile)
                if uri_object.scheme == '':
Frédéric Escudié's avatar
Frédéric Escudié committed
128
129
130
131
132
133
134
135
136
137
138
139
                    isize = 0
                    try:
                        regexpfiles(ifile)
                        if ':' in returned_value:
                            folder, pattern = returned_value.rsplit(':')
                        else:
                            folder, pattern = os.path.split(returned_value)
                        for item in os.listdir(folder):
                            if os.path.isfile(os.path.join(folder, item)) and fnmatch.fnmatch(item, pattern):
                                isize += os.path.getsize(os.path.abspath(os.path.join(folder, item)))
                    except:
                        isize = os.path.getsize(ifile)
140
141
                    if isize > int(get_nb_octet(csizel)):
                        raise argparse.ArgumentTypeError("File '" + ifile + "' (size=" + get_octet_string_representation(isize) + ") exceeds size limits: " + csizel + ".")
142
143
                else:
                    try:
Frédéric Escudié's avatar
Frédéric Escudié committed
144
                        opener = urllib2.urlopen(ifile)
145
146
147
148
149
150
                        metadata = opener.info()
                        isize = int(metadata.getheaders("Content-Length")[0])
                        if isize > int(get_nb_octet(csizel)):
                            raise argparse.ArgumentTypeError("File '" + ifile + "' (size=" + get_octet_string_representation(isize) + ") exceeds size limits: " + csizel + ".")
                    except:
                        raise argparse.ArgumentTypeError("URL '" + file + "' is invalid!")
151
            # then test the type
Jerome Mariette's avatar
Jerome Mariette committed
152
            return returned_value
153
154
155
        inner_function.__name__ = ctype+AbstractInputFile.SIZE_LIMIT_SPLITER+csizel
        return inner_function
    except:
156
157
158
159
        if type(itype) == str:
            return eval(itype)
        else:
            return itype
160

Jerome Mariette's avatar
Jerome Mariette committed
161
class MultipleParameters(object):
162
    def __init__(self, types, required, choices, excludes, default, actions):
Jerome Mariette's avatar
Jerome Mariette committed
163
        self.types = types
164
        self.choices = choices
Jerome Mariette's avatar
Jerome Mariette committed
165
        self.excludes = excludes
166
        self.default = default
167
        self.actions = actions
Jerome Mariette's avatar
Jerome Mariette committed
168
        self.index = None
169
        self.required = required
Jerome Mariette's avatar
Jerome Mariette committed
170
        self.__name__ = "MultipleParameters"
171

Jerome Mariette's avatar
help ok    
Jerome Mariette committed
172
173
174
175
176
    def get_help(self):
        help = " ("
        for flag in self.types.keys():
            help += flag + "=<" + self.types[flag].__name__.upper() + ">, "
        return help[:-2] + ")"
177

178
    def __call__(self, arg):
Jerome Mariette's avatar
Jerome Mariette committed
179
180
181
        parts = arg.split("=")
        if not self.types.has_key(parts[0]):
            raise argparse.ArgumentTypeError(parts[0] + " is an invalid flag! Available ones are: "+", ".join(self.types.keys()))
182
183
184
        if self.choices[parts[0]] != None:
            if parts[1] not in self.choices[parts[0]]:
                raise argparse.ArgumentTypeError("argument " + parts[0] + ": invalid choice: '" + parts[1] + "' (choose from " + ", ".join(self.choices[parts[0]]) + "))")
185

186
187
188
189
190
191
192
        if self.types[parts[0]] == types.BooleanType:
            return (parts[0], not self.default[parts[0]], self.required, self.excludes)
        else:
            try:
                value = self.types[parts[0]](parts[1])
            except:
                raise argparse.ArgumentTypeError("invalid " + self.types[parts[0]].__name__ + " value: '" + parts[1] + "' for sub parameter '" + parts[0] + "'")
193

194
            self.index = parts[0]
195
            return (parts[0], value, self.required, self.excludes, self.actions)
Jerome Mariette's avatar
Jerome Mariette committed
196

197
198
class MiltipleAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
199
200
201
202
203
204
205
        # what is commun within required and excludes
        exclusif_required = {}
        for exclude_group in values[0][3]:
            exclusif_required[exclude_group] = False
            for param in values[0][3][exclude_group]:
                if param in values[0][2]:
                    exclusif_required[exclude_group] = True
Jerome Mariette's avatar
Jerome Mariette committed
206
207
        given_params = []
        # first check for required parameters
208
209
        try:
            required = _copy.copy(values[0][2])
210
211
212
213
214
215
            # delete required that are exclusive
            for group in exclusif_required:
                if exclusif_required[group]:
                    for val in values[0][3][group]:
                        if val in required:
                            del required[required.index(val)]
216
            for val in values:
Jerome Mariette's avatar
Jerome Mariette committed
217
                given_params.append(val[0])
218
219
220
221
222
                if val[0] in required:
                    del required[required.index(val[0])]
        except: pass
        if len(required) == 1: parser.error(", ".join(required) + " is a required parameter!")
        elif len(required) > 1: parser.error(", ".join(required) + " are required parameters!")
Jerome Mariette's avatar
Jerome Mariette committed
223
224
225
226
227
228
229
230
        # then for exclude ones    
        for exclude_group in values[0][3]:
            found = None
            for param in values[0][3][exclude_group]:
                if param in given_params and found != None:
                    parser.error("argument '" + found + "': not allowed with argument '" + param + "'")
                    break
                elif param in given_params: found = param
231

232
233
234
235
236
237
238
239
        # check for required exclusive if one of them is in
        if len(exclusif_required.keys()) > 0:
            for group in exclusif_required:
                if exclusif_required[group]:
                    rfound = False
                    for param in values[0][3][group]:
                        if param in given_params: rfound = True
            if not rfound: parser.error("one of the arguments: " + ", ".join(values[0][3][group]) + " is required")
240

Jerome Mariette's avatar
Jerome Mariette committed
241
        # if ok add the value
242
243
244
245
246
247
248
249
250
251
252
        final_hash, final_values = {}, []
        for value in values:
            if values[0][4][value[0]] == "append" and final_hash.has_key(value[0]):
                final_hash[value[0]].append(value[1])
            elif values[0][4][value[0]] == "append":
                final_hash[value[0]]= [value[1]]
            else:
                final_hash[value[0]]= value[1]
        for param in final_hash:
            final_values.append((param, final_hash[param]))
        setattr(namespace, self.dest, final_values)
253

254

255
256
class MiltipleAppendAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
257
258
259
260
261
262
263
        # what is commun within required and excludes
        exclusif_required = {}
        for exclude_group in values[0][3]:
            exclusif_required[exclude_group] = False
            for param in values[0][3][exclude_group]:
                if param in values[0][2]:
                    exclusif_required[exclude_group] = True
Jerome Mariette's avatar
Jerome Mariette committed
264
265
        given_params = []
        # first check for required parameters
266
267
        try:
            required = _copy.copy(values[0][2])
268
269
270
271
272
273
            # delete required that are exclusive
            for group in exclusif_required:
                if exclusif_required[group]:
                    for val in values[0][3][group]:
                        if val in required:
                            del required[required.index(val)]
274
            for val in values:
Jerome Mariette's avatar
Jerome Mariette committed
275
                given_params.append(val[0])
276
277
278
279
280
                if val[0] in required:
                    del required[required.index(val[0])]
        except: pass
        if len(required) == 1: parser.error(", ".join(required) + " is a required parameter!")
        elif len(required) > 1: parser.error(", ".join(required) + " are required parameters!")
Jerome Mariette's avatar
Jerome Mariette committed
281
282
283
284
285
286
287
288
        # then for exclude ones    
        for exclude_group in values[0][3]:
            found = None
            for param in values[0][3][exclude_group]:
                if param in given_params and found != None:
                    parser.error("argument '" + found + "': not allowed with argument '" + param + "'")
                    break
                elif param in given_params: found = param
289

290
291
292
293
294
295
296
297
        # check for required exclusive if one of them is in
        if len(exclusif_required.keys()) > 0:
            for group in exclusif_required:
                if exclusif_required[group]:
                    rfound = False
                    for param in values[0][3][group]:
                        if param in given_params: rfound = True
            if not rfound: parser.error("one of the arguments: " + ", ".join(values[0][3][group]) + " is required")
Jerome Mariette's avatar
Jerome Mariette committed
298
        # if ok add the value
299
        items = _copy.copy(_ensure_value(namespace, self.dest, []))
300
301
302
303
304
305
306
307
308
309
310
        final_hash, final_values = {}, []
        for value in values:
            if values[0][4][value[0]] == "append" and final_hash.has_key(value[0]):
                final_hash[value[0]].append(value[1])
            elif values[0][4][value[0]] == "append":
                final_hash[value[0]]= [value[1]]
            else:
                final_hash[value[0]]= value[1]
        for param in final_hash:
            final_values.append((param, final_hash[param]))
        items.append(final_values)
311
        setattr(namespace, self.dest, items)
312
313
314


class AbstractParameter(object):
315

316
317
    def __init__(self, name, help, default=None, type=types.StringType, choices=None, required=False,
                 flag=None, action="store", sub_parameters=None, group="default", display_name=None):
Jerome Mariette's avatar
Jerome Mariette committed
318

Jerome Mariette's avatar
Jerome Mariette committed
319
320
        self.name = name
        self.help = help
321
        self.action = action
Jerome Mariette's avatar
Jerome Mariette committed
322
        self.nargs = None
323
324
325
        if sub_parameters:
            self.sub_parameters = sub_parameters
        else: self.sub_parameters = []
Jerome Mariette's avatar
Jerome Mariette committed
326
        self.group = group
327
328
329
        if flag == None:
            self.flag = "--"+name.replace("_", "-")
        else: self.flag = flag
330
        if display_name == None:
331
            self.display_name = name.replace("_", " ").title()
Jerome Mariette's avatar
Jerome Mariette committed
332
        else: self.display_name = display_name
Jerome Mariette's avatar
help ok    
Jerome Mariette committed
333
        self.required = required
334
        self.choices = choices
335
336

        # Set parameter type
Jerome Mariette's avatar
Jerome Mariette committed
337
        if type == "date":
Frédéric Escudié's avatar
Frédéric Escudié committed
338
            self.type = date
Jerome Mariette's avatar
Jerome Mariette committed
339
        elif type == "multiple":
Jerome Mariette's avatar
help ok    
Jerome Mariette committed
340
            self.type = "multiple"
Jerome Mariette's avatar
Jerome Mariette committed
341
342
        elif isinstance(type, types.FunctionType):
            self.type = type
343
        elif type in [types.StringType, types.IntType, types.FloatType,  types.BooleanType]:
Jerome Mariette's avatar
Jerome Mariette committed
344
            self.type = type
Jerome Mariette's avatar
Jerome Mariette committed
345
346
347
        else:
            try: self.type = eval(type)
            except: self.type = types.StringType
348
349

        # Set parameter value
Jerome Mariette's avatar
Jerome Mariette committed
350
        self.default = default
351

352
    def export_to_argparse(self):
Jerome Mariette's avatar
Jerome Mariette committed
353
        if self.type == types.BooleanType and str(self.default).lower() in (False, "false",  "f", "0"):
354
355
356
            return {"help": self.help, "required": self.required, "dest": self.name, 
                    "default": False, "action": "store_true"}
        elif self.type == types.BooleanType:
357
            return {"help": self.help, "required": self.required, "dest": self.name, 
358
                    "default": True, "action": "store_false"}
Jerome Mariette's avatar
Jerome Mariette committed
359
        elif self.nargs > 1:
360
            return {"type": self.get_test_function(), "help": self.help, "required": self.required,
Jerome Mariette's avatar
Jerome Mariette committed
361
                    "dest": self.name, "default": self.default,
Jerome Mariette's avatar
Jerome Mariette committed
362
                    "action": self.action, "choices": self.choices, "nargs": "+"}
363
        else:
364
            return {"type": self.get_test_function(), "help": self.help, "required": self.required,
Jerome Mariette's avatar
Jerome Mariette committed
365
                    "dest": self.name, "default": self.default,
366
                    "action": self.action, "choices": self.choices}
367

Jerome Mariette's avatar
Jerome Mariette committed
368
369
    def get_type(self):
        return self.type.__name__
370

371
372
    def get_test_function(self):
        return create_test_function(self.type)
373

374

Frédéric Escudié's avatar
Frédéric Escudié committed
375
class LinkTraceback(object):
376

Frédéric Escudié's avatar
Frédéric Escudié committed
377
378
379
    def __init__(self, linkTrace_nameid=None, parent_linkTrace_nameid=None):
        self.linkTrace_nameid = linkTrace_nameid
        self.parent_linkTrace_nameid = [] if parent_linkTrace_nameid == None else parent_linkTrace_nameid
Frédéric Escudié's avatar
Frédéric Escudié committed
380
381
382

class AbstractIOFile(LinkTraceback):

Frédéric Escudié's avatar
Frédéric Escudié committed
383
384
    def __init__(self, file_format="any", linkTrace_nameid=None, parent_linkTrace_nameid=None):
        LinkTraceback.__init__(self, linkTrace_nameid, parent_linkTrace_nameid)
Jerome Mariette's avatar
Jerome Mariette committed
385
        self.file_format = file_format
386

387

Frédéric Escudié's avatar
Frédéric Escudié committed
388
class IOFile(str, AbstractIOFile):
389

Frédéric Escudié's avatar
Frédéric Escudié committed
390
    def __new__(self, val="", file_format="any", component_nameid=None, parent_component_nameid=None):
391
392
        return str.__new__(self, val)

Frédéric Escudié's avatar
Frédéric Escudié committed
393
394
    def __init__(self, val="", file_format="any", component_nameid=None, parent_component_nameid=None):
        AbstractIOFile.__init__(self, file_format, component_nameid, parent_component_nameid)
Jerome Mariette's avatar
Jerome Mariette committed
395
396
397


class MultiParameter(dict, AbstractParameter):
Frédéric Escudié's avatar
Frédéric Escudié committed
398

Jerome Mariette's avatar
Jerome Mariette committed
399
400
401
402
403
    def __init__(self, name, help, required=False, flag=None, group="default", display_name=None):
        AbstractParameter.__init__(self, name, help, required=required, type="multiple", flag=flag, group=group, 
                                   display_name=display_name)
        return dict.__init__(self, {})

Jerome Mariette's avatar
help ok    
Jerome Mariette committed
404
405
406
    def add_sub_parameter(self, param):
        param_flag = param.flag[2:]
        if self.type == "multiple":
Jerome Mariette's avatar
Jerome Mariette committed
407
408
409
            if param.required: req = [param_flag] 
            else: req = []
            self.type = MultipleParameters({param_flag: param.type}, req, 
Jerome Mariette's avatar
help ok    
Jerome Mariette committed
410
411
412
413
414
415
416
417
                                           {param_flag: param.choices}, {}, {param_flag: param.default},
                                           {param_flag: param.action})
            if self.action == "append":
                self.action = MiltipleAppendAction
            else:
                self.action = MiltipleAction
            self.global_help = self.help
            self.help = self.global_help + " (" + param_flag + "=<" + param.type.__name__.upper() + ">)"
Jerome Mariette's avatar
Jerome Mariette committed
418
            self.default = {}
Jerome Mariette's avatar
Jerome Mariette committed
419
            self.nargs = "+"
Jerome Mariette's avatar
help ok    
Jerome Mariette committed
420
421
422
        elif self.type.__class__ == MultipleParameters:
            self.type.types[param_flag] = param.type
            self.type.choices[param_flag] = param.choices
423
            self.type.default[param_flag] = param.default if param != None else None
Jerome Mariette's avatar
help ok    
Jerome Mariette committed
424
            self.type.actions[param_flag] = param.action
Jerome Mariette's avatar
Jerome Mariette committed
425
426
            if param.required:
                self.type.required.append(param_flag)
Jerome Mariette's avatar
help ok    
Jerome Mariette committed
427
            self.help = self.global_help + self.type.get_help()
Jerome Mariette's avatar
Jerome Mariette committed
428
        param.flag = param_flag
Jerome Mariette's avatar
help ok    
Jerome Mariette committed
429
        self.sub_parameters.append(param)
430

431
432

class MultiParameterList(list, AbstractParameter):
Frédéric Escudié's avatar
Frédéric Escudié committed
433

434
    def __init__(self, name, help, required=False, flag=None, group="default", display_name=None):
Jerome Mariette's avatar
help ok    
Jerome Mariette committed
435
436
        AbstractParameter.__init__(self, name, help, required=required, type="multiple", flag=flag, 
                                   action="append", group=group, display_name=display_name)
437
        return list.__init__(self, [])
Jerome Mariette's avatar
Jerome Mariette committed
438

Jerome Mariette's avatar
Jerome Mariette committed
439
440
441
    def add_sub_parameter(self, param):
        param_flag = param.flag[2:]
        if self.type == "multiple":
Frédéric Escudié's avatar
Frédéric Escudié committed
442
            if param.required: req = [param_flag]
Jerome Mariette's avatar
Jerome Mariette committed
443
            else: req = []
Frédéric Escudié's avatar
Frédéric Escudié committed
444
            self.type = MultipleParameters({param_flag: param.type}, req,
Jerome Mariette's avatar
Jerome Mariette committed
445
446
447
448
449
450
451
452
453
454
455
456
457
                                           {param_flag: param.choices}, {}, {param_flag: param.default},
                                           {param_flag: param.action})
            if self.action == "append":
                self.action = MiltipleAppendAction
            else:
                self.action = MiltipleAction
            self.global_help = self.help
            self.help = self.global_help + " (" + param_flag + "=<" + param.type.__name__.upper() + ">)"
            self.default = []
            self.nargs = "+"
        elif self.type.__class__ == MultipleParameters:
            self.type.types[param_flag] = param.type
            self.type.choices[param_flag] = param.choices
458
            self.type.default[param_flag] = param.default if param != None else None
Jerome Mariette's avatar
Jerome Mariette committed
459
460
461
462
463
464
465
            self.type.actions[param_flag] = param.action
            if param.required:
                self.type.required.append(param_flag)
            self.help = self.global_help + self.type.get_help()
        param.flag = param_flag
        self.sub_parameters.append(param)

466

Frédéric Escudié's avatar
Frédéric Escudié committed
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
class ParameterFactory(object):
    @staticmethod
    def factory(*args, **kwargs):
        if not kwargs.has_key( "type" ):
            return StrParameter( *args, **kwargs )

        if kwargs["type"] == "int" or kwargs["type"] is types.IntType:
            return IntParameter( *args, **kwargs )
        elif kwargs["type"] == "bool" or kwargs["type"] is types.BooleanType:
            return BoolParameter( *args, **kwargs )
        elif kwargs["type"] == "float" or kwargs["type"] is types.FloatType:
            return FloatParameter( *args, **kwargs )
        elif kwargs["type"] == "date" or kwargs["type"] == date:
            return DateParameter( *args, **kwargs )
        else:
            return StrParameter( *args, **kwargs )


485
486
487
488
489
490
491
def none_decorator(fn):
    def new_func(*args, **kwargs):
        if args[0].is_None:
            raise Exception("The parameter '" + args[0].name + "' is None.")
        else:
            return fn(*args, **kwargs)
    return new_func
492
493
494
495


class BoolParameter(int, AbstractParameter):

Frédéric Escudié's avatar
Frédéric Escudié committed
496
    def __new__(self, name, help, default=False, type=types.BooleanType, choices=None, required=False,
497
                flag=None, sub_parameters=None, group="default", display_name=None):
498
499
        bool_default = False if default == None else bool(default)
        val = int.__new__(self, bool_default)
500
501
502
503
504
505
        val.is_None = False if default != None else True
        for attr in bool.__dict__:
            func = getattr(bool, attr)
            if callable(func) and attr not in ["__new__", "__init__", "__bool__", "__getattribute__", "__setattribute__",
                                               "__eq__", "__ne__", "__nonzero__", "__str__", "__repr__"]:
                setattr(BoolParameter, attr, none_decorator(func))
506
507
508
509
        return val

    def __init__(self, name, help, default=None, type=types.BooleanType, choices=None, required=False,
                 flag=None, sub_parameters=None, group="default", display_name=None):
Frédéric Escudié's avatar
Frédéric Escudié committed
510
        AbstractParameter.__init__(self, name, help, flag=flag, default=bool(default), type=type, choices=choices, required=required, 
511
                                   action="store", sub_parameters=sub_parameters, group=group, display_name=display_name)
512

Frédéric Escudié's avatar
Frédéric Escudié committed
513
514
    def __str__(self):
        if self.is_None:
515
            return str(None)
Frédéric Escudié's avatar
Frédéric Escudié committed
516
517
        return str(bool(self))

518
519
520
    def __repr__(self):
        return str(self)

521
522
    def __eq__(self, other):
        if other.__class__.__name__ == "NoneType":
523
524
525
526
            return self.is_None
        elif self.is_None:
            return False
        else:
Frédéric Escudié's avatar
Frédéric Escudié committed
527
            return int(self) == int(bool(other))
528

529
    def __ne__(self, other):
Frédéric Escudié's avatar
Frédéric Escudié committed
530
        return not (self == other)
531

532
    def __nonzero__(self):
533
        if self.is_None:
534
            return False
535
536
537
        else:
            return self != 0

538

539
540
541
542
543
544
class IntParameter(int, AbstractParameter):

    def __new__(self, name, help, default=None, type=types.IntType, choices=None, required=False,
                flag=None, sub_parameters=None, group="default", display_name=None):
        int_default = 0 if default == None else int(default)
        val = int.__new__(self, int_default)
545
546
547
548
549
550
        val.is_None = False if default != None else True
        for attr in int.__dict__:
            func = getattr(int, attr)
            if callable(func) and attr not in ["__new__", "__init__", "__int__", "__getattribute__", "__setattribute__",
                                               "__eq__", "__ne__", "__nonzero__", "__str__", "__repr__"]:
                setattr(IntParameter, attr, none_decorator(func))
551
552
553
        return val

    def __init__(self, name, help, default=None, type=types.IntType, choices=None, required=False,
554
                 flag=None, sub_parameters=None, group="default", display_name=None):
555
556
        AbstractParameter.__init__( self, name, help, flag=flag, default=default, type=type, choices=choices, required=required,
                                    action="store", sub_parameters=sub_parameters, group=group, display_name=display_name )
557

558
559
560
561
562
    def __str__(self):
        if self.is_None:
            return str(None)
        return str(int(self))

563
564
565
    def __repr__(self):
        return str(self)

566
567
568
569
570
571
572
573
574
    def __eq__(self, other):
        if other.__class__.__name__ == "NoneType":
            return self.is_None
        elif self.is_None:
            return False
        else:
            return int(self) == int(other)

    def __ne__(self, other):
Frédéric Escudié's avatar
Frédéric Escudié committed
575
        return not (self == other)
576
577
578
579
580
581
582
583

    def __nonzero__(self):
        if self.is_None:
            return False
        else:
            return self != 0


Frédéric Escudié's avatar
Frédéric Escudié committed
584
class FloatParameter(float, AbstractParameter):
585
586
587
588

    def __new__(self, name, help, default=None, type=types.FloatType, choices=None, required=False,
                flag=None, sub_parameters=None, group="default", display_name=None):
        float_default = 0.0 if default == None else float(default)
Frédéric Escudié's avatar
Frédéric Escudié committed
589
        val = float.__new__(self, float_default)
590
591
592
593
594
595
        val.is_None = False if default != None else True
        for attr in float.__dict__:
            func = getattr(float, attr)
            if callable(func) and attr not in ["__new__", "__init__", "__float__", "__getattribute__", "__setattribute__", 
                                               "__eq__", "__ne__", "__nonzero__", "__str__", "__repr__"]:
                setattr(FloatParameter, attr, none_decorator(func))
596
597
598
599
600
601
602
        return val

    def __init__(self, name, help, default=None, type=types.FloatType, choices=None, required=False,
                 flag=None, sub_parameters=None, group="default", display_name=None):
        AbstractParameter.__init__(self, name, help, flag=flag, default=default, type=type, choices=choices, required=required, 
                                   action="store", sub_parameters=sub_parameters, group=group, display_name=display_name)

603
604
605
606
607
    def __str__(self):
        if self.is_None:
            return str(None)
        return str(float(self))

608
609
610
    def __repr__(self):
        return str(self)

611
612
613
614
615
616
617
618
619
    def __eq__(self, other):
        if other.__class__.__name__ == "NoneType":
            return self.is_None
        elif self.is_None:
            return False
        else:
            return float(self) == float(other)

    def __ne__(self, other):
Frédéric Escudié's avatar
Frédéric Escudié committed
620
        return not (self == other)
621
622
623
624
625
626
627
628
629
630
631
632
633
634

    def __nonzero__(self):
        if self.is_None:
            return False
        else:
            return self != 0.0


class StrParameter(str, AbstractParameter):

    def __new__(self, name, help, default=None, type=types.StringType, choices=None, required=False,
                flag=None, sub_parameters=None, group="default", display_name=None):
        str_default = "" if default == None else str(default)
        val = str.__new__(self, str_default)
635
636
637
638
639
640
        val.is_None = False if default != None else True
        for attr in str.__dict__:
            func = getattr(str, attr)
            if callable(func) and attr not in ["__new__", "__init__", "__str__", "__getattribute__", "__setattribute__",
                                               "__eq__", "__ne__", "__nonzero__", "__repr__"]:
                setattr(StrParameter, attr, none_decorator(func))
641
642
643
644
645
646
647
        return val

    def __init__(self, name, help, default=None, type=types.StringType, choices=None, required=False,
                 flag=None, sub_parameters=None, group="default", display_name=None):
        AbstractParameter.__init__(self, name, help, flag=flag, default=default, type=type, choices=choices, required=required, 
                                   action="store", sub_parameters=sub_parameters, group=group, display_name=display_name)

648
649
650
651
652
    def __str__(self):
        if self.is_None:
            return str(None)
        return str.__str__(self)

653
654
655
656
657
    def __repr__(self):
        if self.is_None:
            return str(None)
        return "'" + str(self) + "'"

658
659
660
661
662
663
664
665
666
    def __eq__(self, other):
        if other.__class__.__name__ == "NoneType":
            return self.is_None
        elif self.is_None:
            return False
        else:
            return str(self) == str(other)

    def __ne__(self, other):
Frédéric Escudié's avatar
Frédéric Escudié committed
667
        return not(self == other)
668
669
670
671
672
673
674
675

    def __nonzero__(self):
        if self.is_None:
            return False
        else:
            return (True if str(self) else False)


Frédéric Escudié's avatar
Frédéric Escudié committed
676
class DateParameter(datetime.datetime, AbstractParameter):
677

Frédéric Escudié's avatar
Frédéric Escudié committed
678
679
680
681
682
683
684
685
    def __new__(self, name, help, default=None, type=date, choices=None, required=False,
                flag=None, sub_parameters=None, group="default", display_name=None):
        date_default = datetime.datetime.today()
        if default != None and issubclass(default.__class__, datetime.datetime):
            date_default = default
        elif default != None:
            date_default = date(default)
        val = datetime.datetime.__new__(self, date_default.year, date_default.month, date_default.day)
686
687
688
689
690
691
        val.is_None = False if default != None else True
        for attr in datetime.datetime.__dict__:
            func = getattr(datetime.datetime, attr)
            if callable(func) and attr not in ["__new__", "__init__", "__getattribute__", "__setattribute__",
                                               "__eq__", "__ne__", "__nonzero__", "__str__", "__repr__"]:
                setattr(DateParameter, attr, none_decorator(func))
Frédéric Escudié's avatar
Frédéric Escudié committed
692
693
694
695
696
697
698
699
700
701
        return val

    def __init__(self, name, help, default=None, type=date, choices=None, required=False,
                 flag=None, sub_parameters=None, group="default", display_name=None):
        if default != None and not issubclass(default.__class__, datetime.datetime):
            date_default = date(default)
            default = datetime.datetime(date_default.year, date_default.month, date_default.day)
        AbstractParameter.__init__(self, name, help, flag=flag, default=default, type=type, choices=choices, required=required, 
                                   action="store", sub_parameters=sub_parameters, group=group, display_name=display_name)

702
703
704
705
706
    def __str__(self):
        if self.is_None:
            return str(None)
        return datetime.datetime.__str__(self)

707
708
709
    def __repr__(self):
        return str(self)

Frédéric Escudié's avatar
Frédéric Escudié committed
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
    def __eq__(self, other):
        if other.__class__.__name__ == "NoneType":
            return self.is_None
        elif self.is_None:
            return False
        else:
            return datetime.date(self.year, self.month, self.day) == other

    def __ne__(self, other):
        return not( self == other )

    def __nonzero__(self):
        if self.is_None:
            return False
        else:
            return (True if datetime.date(self.year, self.month, self.day) else False)

727
728
729
730
731
732
733
734
    def __reduce__(self):
        return (DateParameter, (self.name, self.help, self.default, date, self.choices, self.required,
                 self.flag, self.sub_parameters, self.group, self.display_name), None, None, None)

    def __reduce_ex__(self, protocol):
        return (DateParameter, (self.name, self.help, self.default, date, self.choices, self.required,
                 self.flag, self.sub_parameters, self.group, self.display_name), None, None, None)

Frédéric Escudié's avatar
Frédéric Escudié committed
735
736
737
738
739

class AbstractInputFile(AbstractIOFile):
    """
     @summary : Parent of all InputFile(s) parameters.
    """
740
741
742
743
744
745
746
    
    SIZE_LIMIT_SPLITER = "__sl"
    
    def __init__(self, file_format="any", size_limit="0"):
        AbstractIOFile.__init__(self, file_format)
        self.size_limit = size_limit
    
Jerome Mariette's avatar
Jerome Mariette committed
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
    def _download_urlfile(self, input):
        try:
            uri_object = urlparse(input)
            opener = urllib2.urlopen(input)
            block_size = 8000
            jflowconf = JFlowConfigReader()
            tmp_directory = os.path.join(jflowconf.get_tmp_directory(), os.path.basename(tempfile.NamedTemporaryFile().name))
            os.mkdir(tmp_directory) 
            file_path = os.path.join(tmp_directory, os.path.basename(uri_object.path))
            local_file = open(file_path, 'wb')
            if os.path.basename(uri_object.path) is not None and os.path.basename(uri_object.path) != "":
                metadata = opener.info()
                file_size = int(metadata.getheaders("Content-Length")[0])
                while True:
                    buffer = opener.read(block_size)
                    # End of download
                    if not buffer: break
                    # Parts of download
                    local_file.write(buffer)
                local_file.close()
                logging.getLogger("AbstractInputFile.download_urlfile").debug("URL file '{0}' successfully downloaded as: {1}".format(input, file_path))
            return [file_path, True]
        except:
            return [input, False]
771

Jerome Mariette's avatar
Jerome Mariette committed
772
    def check(self, ifile):
Jerome Mariette's avatar
Jerome Mariette committed
773
774
775
776
        try:
            eval(self.file_format)
            function_exists = True
        except: function_exists = False
777
778
779
780
        if function_exists:
            try: 
                eval(self.file_format)(ifile)
            except jflow.InvalidFormatError as e:
Jerome Mariette's avatar
Jerome Mariette committed
781
                display_error_message(str(e))
782
        else:
Jerome Mariette's avatar
Jerome Mariette committed
783
            display_error_message("Invalid file format '" + self.file_format + "'!")
Frédéric Escudié's avatar
Frédéric Escudié committed
784
785
786
787
788
789
790

class AbstractOutputFile(AbstractIOFile):
    """
     @summary : Parent of all OutputFile(s) parameters.
    """
    pass

791
792
793

class InputFile(StrParameter, AbstractInputFile):

Jerome Mariette's avatar
Jerome Mariette committed
794
    def __new__(self, name, help, file_format="any", default="", type="localfile", choices=None, 
795
                required=False, flag=None, group="default", display_name=None, size_limit="0"):
Jerome Mariette's avatar
Jerome Mariette committed
796
797
798
        if hasattr(type, '__call__'):
            type2test = type.__name__
        else: type2test = type
799

Jerome Mariette's avatar
Jerome Mariette committed
800
801
802
        if type2test not in INPUTFILE_TYPES:
            raise ValueError("InputFile.__new__: wrong type provided: '"+type2test+"', this should be choosen between '" 
                             + "', '".join(INPUTFILE_TYPES)+"'")
803
804
805
806

        return StrParameter.__new__(self, name, help, flag=flag, default=default, type=type, choices=choices, 
                           required=required, group=group, display_name=display_name)

Jerome Mariette's avatar
Jerome Mariette committed
807
    def __init__(self, name, help, file_format="any", default="", type="localfile", choices=None, 
808
809
                required=False, flag=None, group="default", display_name=None, size_limit="0"):
        AbstractInputFile.__init__(self, file_format, size_limit)
810
        StrParameter.__init__(self, name, help, flag=flag, default=default, type=type, choices=choices, 
811
                           required=required, group=group, display_name=display_name)
Jerome Mariette's avatar
Jerome Mariette committed
812

Jerome Mariette's avatar
Jerome Mariette committed
813
814
815
    def get_type(self):
        return self.type.__name__+AbstractInputFile.SIZE_LIMIT_SPLITER+self.size_limit

816
817
    def get_test_function(self):
        if (self.size_limit == "0"): ctype = self.type
Jerome Mariette's avatar
Jerome Mariette committed
818
        else: ctype = self.get_type()
819
820
        return create_test_function(ctype)

Jerome Mariette's avatar
Jerome Mariette committed
821
    def prepare_input_file(self, input):
822
823
        if input == None:
            return None
Jerome Mariette's avatar
Jerome Mariette committed
824
825
826
827
828
829
830
831
        # handle url inputs
        new_path, is_uri = self._download_urlfile(input)
        # handle upload inputs
        try: is_local = os.path.isfile(input)
        except: is_local = False
        if not is_uri and not is_local and self.type.__name__ == "inputfile" or self.type.__name__ == "browsefile":
            jflow_config_reader = JFlowConfigReader()
            new_path = os.path.join(jflow_config_reader.get_tmp_directory(), input)
Frédéric Escudié's avatar
Frédéric Escudié committed
832
        if is_local: new_path = os.path.abspath(input)
Jerome Mariette's avatar
Jerome Mariette committed
833
        self.check(new_path)
Jerome Mariette's avatar
Jerome Mariette committed
834
        return new_path
835

Jerome Mariette's avatar
Jerome Mariette committed
836

837
838
class OutputFile(StrParameter, AbstractOutputFile):

Frédéric Escudié's avatar
Frédéric Escudié committed
839
    def __new__(self, name, help, file_format="any", default="", choices=None,
840
                required=False, flag=None, group="default", display_name=None):
Frédéric Escudié's avatar
Frédéric Escudié committed
841
        return StrParameter.__new__(self, name, help, flag=flag, default=default, type="localfile", choices=choices,
842
843
                           required=required, group=group, display_name=display_name)

Frédéric Escudié's avatar
Frédéric Escudié committed
844
    def __init__(self, name, help, file_format="any", default="", choices=None,
845
                required=False, flag=None, group="default", display_name=None):
Jerome Mariette's avatar
Jerome Mariette committed
846
        AbstractIOFile.__init__(self, file_format)
847
        StrParameter.__init__(self, name, help, flag=flag, default=default, type="localfile", choices=choices, 
848
849
                           required=required, group=group, display_name=display_name)

850

851
class ParameterList(list, AbstractParameter):
852

Jerome Mariette's avatar
Jerome Mariette committed
853
    def __init__(self, name, help, default=None, type=types.StringType, choices=None, required=False,
854
                 flag=None, sub_parameters=None, group="default", display_name=None):
Jerome Mariette's avatar
Jerome Mariette committed
855
        if default == None: default = []
Frédéric Escudié's avatar
Frédéric Escudié committed
856
        AbstractParameter.__init__(self, name, help, flag=flag, default=default, type=type, choices=choices, required=required,
857
858
859
860
861
                                   action="append", sub_parameters=sub_parameters, group=group, display_name=display_name)
        if default.__class__.__name__ == "str":
            return list.__init__(self, [default])
        elif default.__class__.__name__ == "list":
            return list.__init__(self, default)
862

863
864
865
866
867
868
    def append(self, item):
        raise TypeError('A parameter is immutable.')

    def extend(self, items):
        raise TypeError('A parameter is immutable.')

869

Frédéric Escudié's avatar
Frédéric Escudié committed
870
class InputFileList(ParameterList, AbstractInputFile):
871

Jerome Mariette's avatar
Jerome Mariette committed
872
    def __init__(self, name, help, file_format="any", default=None, type="localfile", choices=None, 
873
                 required=False, flag=None, group="default", display_name=None, size_limit="0"):
874

875
        if default == None: default = []
Jerome Mariette's avatar
Jerome Mariette committed
876
        if hasattr(type, '__call__'):
877
878
            if type.__name__ == "inputfile":
                type = inputfiles
Jerome Mariette's avatar
Jerome Mariette committed
879
            type2test = type.__name__
880
881
882
883
884
        else:
            if type == "inputfile":
                type = "inputfiles"
            type2test = type
        if type2test not in INPUTFILES_TYPES:
Jerome Mariette's avatar
Jerome Mariette committed
885
886
            raise ValueError("InputFile.__new__: wrong type provided: '"+type2test+"', this should be choosen between '" 
                             + "', '".join(INPUTFILE_TYPES)+"'")
887

888
        AbstractInputFile.__init__(self, file_format, size_limit)
Jerome Mariette's avatar
Jerome Mariette committed
889
        ParameterList.__init__(self, name, help, flag=flag, default=default, type=type, choices=choices, 
890
                               required=required, group=group, display_name=display_name)
891

892
893
894
895
        if default.__class__.__name__ == "str":
            return list.__init__(self, [default])
        elif default.__class__.__name__ == "list":
            return list.__init__(self, default)
896
897
        elif issubclass( default.__class__, InputFile ):
            return list.__init__(self, [default])
Frédéric Escudié's avatar
Frédéric Escudié committed
898
        elif issubclass( default.__class__, AbstractInputFile ):
Jerome Mariette's avatar
Jerome Mariette committed
899
            return list.__init__(self, default)
900
901
        elif issubclass( default.__class__, OutputFile ):
            return list.__init__(self, [default])
Frédéric Escudié's avatar
Frédéric Escudié committed
902
        elif issubclass( default.__class__, AbstractOutputFile ):
Jerome Mariette's avatar
Jerome Mariette committed
903
            return list.__init__(self, default)
Jerome Mariette's avatar
Jerome Mariette committed
904
905
906
907
    
    def get_type(self):
        return self.type.__name__+AbstractInputFile.SIZE_LIMIT_SPLITER+self.size_limit
    
908
909
    def get_test_function(self):
        if (self.size_limit == "0"): ctype = self.type
Jerome Mariette's avatar
Jerome Mariette committed
910
        else: ctype = self.get_type()
911
912
        return create_test_function(ctype)

Jerome Mariette's avatar
Jerome Mariette committed
913
    def prepare_input_files(self, inputs):
Jerome Mariette's avatar
Jerome Mariette committed
914
        path2test = _copy.deepcopy(inputs)
Frédéric Escudié's avatar
Frédéric Escudié committed
915
        new_vals = list()
Jerome Mariette's avatar
Jerome Mariette committed
916
917
918
919
        if not path2test.__class__.__name__ == "list":
            path2test = [path2test]
        for path in path2test:
            new_url, is_uri = self._download_urlfile(path)
Frédéric Escudié's avatar
Frédéric Escudié committed
920
            if is_uri: # handle url inputs
Jerome Mariette's avatar
Jerome Mariette committed
921
                new_vals.append(new_url)
Frédéric Escudié's avatar
Frédéric Escudié committed
922
            elif os.path.isfile(path): # handle localfile
Frédéric Escudié's avatar
Frédéric Escudié committed
923
                new_vals.append(os.path.abspath(path))
Frédéric Escudié's avatar
Frédéric Escudié committed
924
925
926
927
928
929
930
931
932
            else:
                try: # handle regexp files
                    regexpfiles(path)
                    if ':' in path:
                        folder, pattern = path.rsplit(':')
                    else:
                        folder, pattern = os.path.split(path)
                    for item in sorted(os.listdir(folder)):
                        if os.path.isfile(os.path.join(folder, item)) and fnmatch.fnmatch(item, pattern):
Frédéric Escudié's avatar
Frédéric Escudié committed
933
                            new_vals.append( os.path.abspath(os.path.join(folder, item)) )
Frédéric Escudié's avatar
Frédéric Escudié committed
934
935
936
                except: # handle upload inputs
                    jflow_config_reader = JFlowConfigReader()
                    new_vals.append(os.path.join(jflow_config_reader.get_tmp_directory(), path))
Jerome Mariette's avatar
Jerome Mariette committed
937
938
939
        # now that all files are downloaded and ok, check the format
        for cfile in new_vals:
            self.check(cfile)
Jerome Mariette's avatar
Jerome Mariette committed
940
        return new_vals
941

Frédéric Escudié's avatar
Frédéric Escudié committed
942
943
class OutputFileList(ParameterList, AbstractOutputFile):

Jerome Mariette's avatar
Jerome Mariette committed
944
945
946
    def __init__(self, name, help, file_format="any", default=None, choices=None, 
                 required=False, flag=None, group="default", display_name=None):
        if default == None: default = []
Jerome Mariette's avatar
Jerome Mariette committed
947
        AbstractIOFile.__init__(self, file_format)
Jerome Mariette's avatar
Jerome Mariette committed
948
        ParameterList.__init__(self, name, help, flag=flag, default=default, type="localfile", choices=choices, 
949
950
951
952
953
                               required=required, group=group, display_name=display_name)
        if default.__class__.__name__ == "str":
            return list.__init__(self, [default])
        elif default.__class__.__name__ == "list":
            return list.__init__(self, default)
Frédéric Escudié's avatar
Frédéric Escudié committed
954

955

Frédéric Escudié's avatar
Frédéric Escudié committed
956