parameter.py 40.5 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
25
import os
import tempfile
26
from argparse import _ensure_value
Jerome Mariette's avatar
Jerome Mariette committed
27
import urllib2
28
import copy as _copy
Jerome Mariette's avatar
Jerome Mariette committed
29
from urlparse import urlparse
30

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

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

Jerome Mariette's avatar
Jerome Mariette committed
38
39
40
41
42
43
44
45
46
47
48
49
50

# define all input type available
INPUTFILE_TYPES = ["inputfile", "localfile", "urlfile", "browsefile"]

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):
        return os.path.abspath(file)
    else:
Jerome Mariette's avatar
Jerome Mariette committed
51
        raise argparse.ArgumentTypeError("File '" + file + "' does not exists! Please provide a valid file path!")
52

Jerome Mariette's avatar
Jerome Mariette committed
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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!")
68

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

80
81
def create_test_function(itype):
    try: itype = itype.encode('ascii','ignore')
Jerome Mariette's avatar
Jerome Mariette committed
82
    except: pass
83
    try:
84
        ctype, csizel = itype.split(AbstractInputFile.SIZE_LIMIT_SPLITER)
85
        def inner_function(ifile):
Jerome Mariette's avatar
Jerome Mariette committed
86
87
            # first eval the asked type
            returned_value = eval(ctype)(ifile)
88
89
90
91
92
93
            # if 0 unlimited size
            if csizel != "0":
                # first test the size of the file
                uri_object = urlparse(ifile)
                if uri_object.scheme == '':
                    isize = os.path.getsize(ifile)
94
95
                    if isize > int(get_nb_octet(csizel)):
                        raise argparse.ArgumentTypeError("File '" + ifile + "' (size=" + get_octet_string_representation(isize) + ") exceeds size limits: " + csizel + ".")
96
97
98
99
100
101
102
103
104
                else:
                    try:
                        opener = urllib2.urlopen(file)
                        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!")
105
            # then test the type
Jerome Mariette's avatar
Jerome Mariette committed
106
            return returned_value
107
108
109
        inner_function.__name__ = ctype+AbstractInputFile.SIZE_LIMIT_SPLITER+csizel
        return inner_function
    except:
110
111
112
113
        if type(itype) == str:
            return eval(itype)
        else:
            return itype
114

Jerome Mariette's avatar
Jerome Mariette committed
115
class MultipleParameters(object):
116
    def __init__(self, types, required, choices, excludes, default, actions):
Jerome Mariette's avatar
Jerome Mariette committed
117
        self.types = types
118
        self.choices = choices
Jerome Mariette's avatar
Jerome Mariette committed
119
        self.excludes = excludes
120
        self.default = default
121
        self.actions = actions
Jerome Mariette's avatar
Jerome Mariette committed
122
        self.index = None
123
        self.required = required
Jerome Mariette's avatar
Jerome Mariette committed
124
        self.__name__ = "MultipleParameters"
125

Jerome Mariette's avatar
help ok    
Jerome Mariette committed
126
127
128
129
130
    def get_help(self):
        help = " ("
        for flag in self.types.keys():
            help += flag + "=<" + self.types[flag].__name__.upper() + ">, "
        return help[:-2] + ")"
131

132
    def __call__(self, arg):
Jerome Mariette's avatar
Jerome Mariette committed
133
134
135
        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()))
136
137
138
        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]]) + "))")
139

140
141
142
143
144
145
146
        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] + "'")
147

148
            self.index = parts[0]
149
            return (parts[0], value, self.required, self.excludes, self.actions)
Jerome Mariette's avatar
Jerome Mariette committed
150

151
152
class MiltipleAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
153
154
155
156
157
158
159
        # 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
160
161
        given_params = []
        # first check for required parameters
162
163
        try:
            required = _copy.copy(values[0][2])
164
165
166
167
168
169
            # 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)]
170
            for val in values:
Jerome Mariette's avatar
Jerome Mariette committed
171
                given_params.append(val[0])
172
173
174
175
176
                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
177
178
179
180
181
182
183
184
        # 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
185

186
187
188
189
190
191
192
193
        # 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")
194

Jerome Mariette's avatar
Jerome Mariette committed
195
        # if ok add the value
196
197
198
199
200
201
202
203
204
205
206
        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)
207

208

209
210
class MiltipleAppendAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
211
212
213
214
215
216
217
        # 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
218
219
        given_params = []
        # first check for required parameters
220
221
        try:
            required = _copy.copy(values[0][2])
222
223
224
225
226
227
            # 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)]
228
            for val in values:
Jerome Mariette's avatar
Jerome Mariette committed
229
                given_params.append(val[0])
230
231
232
233
234
                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
235
236
237
238
239
240
241
242
        # 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
243

244
245
246
247
248
249
250
251
        # 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
252
        # if ok add the value
253
        items = _copy.copy(_ensure_value(namespace, self.dest, []))
254
255
256
257
258
259
260
261
262
263
264
        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)
265
        setattr(namespace, self.dest, items)
266
267
268


class AbstractParameter(object):
269

270
271
    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
272

Jerome Mariette's avatar
Jerome Mariette committed
273
274
        self.name = name
        self.help = help
275
        self.action = action
Jerome Mariette's avatar
Jerome Mariette committed
276
        self.nargs = None
277
278
279
        if sub_parameters:
            self.sub_parameters = sub_parameters
        else: self.sub_parameters = []
Jerome Mariette's avatar
Jerome Mariette committed
280
        self.group = group
281
282
283
        if flag == None:
            self.flag = "--"+name.replace("_", "-")
        else: self.flag = flag
284
        if display_name == None:
285
            self.display_name = name.replace("_", " ").title()
Jerome Mariette's avatar
Jerome Mariette committed
286
        else: self.display_name = display_name
Jerome Mariette's avatar
help ok    
Jerome Mariette committed
287
        self.required = required
288
        self.choices = choices
289
290

        # Set parameter type
Jerome Mariette's avatar
Jerome Mariette committed
291
        if type == "date":
Frédéric Escudié's avatar
Frédéric Escudié committed
292
            self.type = date
Jerome Mariette's avatar
Jerome Mariette committed
293
        elif type == "multiple":
Jerome Mariette's avatar
help ok    
Jerome Mariette committed
294
            self.type = "multiple"
Jerome Mariette's avatar
Jerome Mariette committed
295
296
        elif isinstance(type, types.FunctionType):
            self.type = type
297
        elif type in [types.StringType, types.IntType, types.FloatType,  types.BooleanType]:
Jerome Mariette's avatar
Jerome Mariette committed
298
            self.type = type
Jerome Mariette's avatar
Jerome Mariette committed
299
300
301
        else:
            try: self.type = eval(type)
            except: self.type = types.StringType
302
303

        # Set parameter value
Jerome Mariette's avatar
Jerome Mariette committed
304
        self.default = default
305

306
    def export_to_argparse(self):
Jerome Mariette's avatar
Jerome Mariette committed
307
        if self.type == types.BooleanType and str(self.default).lower() in (False, "false",  "f", "0"):
308
309
310
            return {"help": self.help, "required": self.required, "dest": self.name, 
                    "default": False, "action": "store_true"}
        elif self.type == types.BooleanType:
311
            return {"help": self.help, "required": self.required, "dest": self.name, 
312
                    "default": True, "action": "store_false"}
Jerome Mariette's avatar
Jerome Mariette committed
313
        elif self.nargs > 1:
314
            return {"type": self.get_test_function(), "help": self.help, "required": self.required,
Jerome Mariette's avatar
Jerome Mariette committed
315
                    "dest": self.name, "default": self.default,
Jerome Mariette's avatar
Jerome Mariette committed
316
                    "action": self.action, "choices": self.choices, "nargs": "+"}
317
        else:
318
            return {"type": self.get_test_function(), "help": self.help, "required": self.required,
Jerome Mariette's avatar
Jerome Mariette committed
319
                    "dest": self.name, "default": self.default,
320
                    "action": self.action, "choices": self.choices}
321

Jerome Mariette's avatar
Jerome Mariette committed
322
323
    def get_type(self):
        return self.type.__name__
324

325
326
    def get_test_function(self):
        return create_test_function(self.type)
327

Jerome Mariette's avatar
Jerome Mariette committed
328
class AbstractIOFile(object):
329

Jerome Mariette's avatar
Jerome Mariette committed
330
331
    def __init__(self, file_format="any"):
        self.file_format = file_format
Jerome Mariette's avatar
Jerome Mariette committed
332
        self.component_nameid = None
333
        self.parent_component_nameid = []
Jerome Mariette's avatar
Jerome Mariette committed
334
335
336


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

Jerome Mariette's avatar
Jerome Mariette committed
338
339
340
341
342
    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
343
344
345
    def add_sub_parameter(self, param):
        param_flag = param.flag[2:]
        if self.type == "multiple":
Jerome Mariette's avatar
Jerome Mariette committed
346
347
348
            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
349
350
351
352
353
354
355
356
                                           {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
357
            self.default = {}
Jerome Mariette's avatar
Jerome Mariette committed
358
            self.nargs = "+"
Jerome Mariette's avatar
help ok    
Jerome Mariette committed
359
360
361
        elif self.type.__class__ == MultipleParameters:
            self.type.types[param_flag] = param.type
            self.type.choices[param_flag] = param.choices
362
            self.type.default[param_flag] = param.default if param != None else None
Jerome Mariette's avatar
help ok    
Jerome Mariette committed
363
            self.type.actions[param_flag] = param.action
Jerome Mariette's avatar
Jerome Mariette committed
364
365
            if param.required:
                self.type.required.append(param_flag)
Jerome Mariette's avatar
help ok    
Jerome Mariette committed
366
            self.help = self.global_help + self.type.get_help()
Jerome Mariette's avatar
Jerome Mariette committed
367
        param.flag = param_flag
368
        self[param.name] = param
Jerome Mariette's avatar
help ok    
Jerome Mariette committed
369
        self.sub_parameters.append(param)
370

371
372

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

374
    def __init__(self, name, help, required=False, flag=None, group="default", display_name=None):
Jerome Mariette's avatar
help ok    
Jerome Mariette committed
375
376
        AbstractParameter.__init__(self, name, help, required=required, type="multiple", flag=flag, 
                                   action="append", group=group, display_name=display_name)
377
        return list.__init__(self, [])
Jerome Mariette's avatar
Jerome Mariette committed
378

Jerome Mariette's avatar
Jerome Mariette committed
379
380
381
    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
382
            if param.required: req = [param_flag]
Jerome Mariette's avatar
Jerome Mariette committed
383
            else: req = []
Frédéric Escudié's avatar
Frédéric Escudié committed
384
            self.type = MultipleParameters({param_flag: param.type}, req,
Jerome Mariette's avatar
Jerome Mariette committed
385
386
387
388
389
390
391
392
393
394
395
396
397
                                           {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
398
            self.type.default[param_flag] = param.default if param != None else None
Jerome Mariette's avatar
Jerome Mariette committed
399
400
401
402
403
            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
404
        self.append(param)
Jerome Mariette's avatar
Jerome Mariette committed
405
406
        self.sub_parameters.append(param)

407

Frédéric Escudié's avatar
Frédéric Escudié committed
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
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 )


426
427
428
429
430
431
432
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
433
434
435
436


class BoolParameter(int, AbstractParameter):

Frédéric Escudié's avatar
Frédéric Escudié committed
437
    def __new__(self, name, help, default=False, type=types.BooleanType, choices=None, required=False,
438
                flag=None, sub_parameters=None, group="default", display_name=None):
439
440
        bool_default = False if default == None else bool(default)
        val = int.__new__(self, bool_default)
441
442
443
444
445
446
        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))
447
448
449
450
        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
451
        AbstractParameter.__init__(self, name, help, flag=flag, default=bool(default), type=type, choices=choices, required=required, 
452
                                   action="store", sub_parameters=sub_parameters, group=group, display_name=display_name)
453

Frédéric Escudié's avatar
Frédéric Escudié committed
454
455
    def __str__(self):
        if self.is_None:
456
            return str(None)
Frédéric Escudié's avatar
Frédéric Escudié committed
457
458
        return str(bool(self))

459
460
461
    def __repr__(self):
        return str(self)

462
463
    def __eq__(self, other):
        if other.__class__.__name__ == "NoneType":
464
465
466
467
            return self.is_None
        elif self.is_None:
            return False
        else:
Frédéric Escudié's avatar
Frédéric Escudié committed
468
            return int(self) == int(bool(other))
469

470
    def __ne__(self, other):
Frédéric Escudié's avatar
Frédéric Escudié committed
471
        return not (self == other)
472

473
    def __nonzero__(self):
474
        if self.is_None:
475
            return False
476
477
478
        else:
            return self != 0

479

480
481
482
483
484
485
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)
486
487
488
489
490
491
        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))
492
493
494
        return val

    def __init__(self, name, help, default=None, type=types.IntType, choices=None, required=False,
495
                 flag=None, sub_parameters=None, group="default", display_name=None):
496
497
        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 )
498

499
500
501
502
503
    def __str__(self):
        if self.is_None:
            return str(None)
        return str(int(self))

504
505
506
    def __repr__(self):
        return str(self)

507
508
509
510
511
512
513
514
515
    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
516
        return not (self == other)
517
518
519
520
521
522
523
524

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


Frédéric Escudié's avatar
Frédéric Escudié committed
525
class FloatParameter(float, AbstractParameter):
526
527
528
529

    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
530
        val = float.__new__(self, float_default)
531
532
533
534
535
536
        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))
537
538
539
540
541
542
543
        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)

544
545
546
547
548
    def __str__(self):
        if self.is_None:
            return str(None)
        return str(float(self))

549
550
551
    def __repr__(self):
        return str(self)

552
553
554
555
556
557
558
559
560
    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
561
        return not (self == other)
562
563
564
565
566
567
568
569
570
571
572
573
574
575

    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)
576
577
578
579
580
581
        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))
582
583
584
585
586
587
588
        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)

589
590
591
592
593
    def __str__(self):
        if self.is_None:
            return str(None)
        return str.__str__(self)

594
595
596
597
598
    def __repr__(self):
        if self.is_None:
            return str(None)
        return "'" + str(self) + "'"

599
600
601
602
603
604
605
606
607
    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
608
        return not(self == other)
609
610
611
612
613
614
615
616

    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
617
class DateParameter(datetime.datetime, AbstractParameter):
618

Frédéric Escudié's avatar
Frédéric Escudié committed
619
620
621
622
623
624
625
626
    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)
627
628
629
630
631
632
        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
633
634
635
636
637
638
639
640
641
642
        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)

643
644
645
646
647
    def __str__(self):
        if self.is_None:
            return str(None)
        return datetime.datetime.__str__(self)

648
649
650
    def __repr__(self):
        return str(self)

Frédéric Escudié's avatar
Frédéric Escudié committed
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
    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)

668
669
670
671
672
673
674
675
    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
676
677
678
679
680

class AbstractInputFile(AbstractIOFile):
    """
     @summary : Parent of all InputFile(s) parameters.
    """
681
682
683
684
685
686
687
    
    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
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
    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]
712

Jerome Mariette's avatar
Jerome Mariette committed
713
    def check(self, ifile):
Jerome Mariette's avatar
Jerome Mariette committed
714
715
716
717
        try:
            eval(self.file_format)
            function_exists = True
        except: function_exists = False
718
719
720
721
722
723
724
725
726
        if function_exists:
            try: 
                eval(self.file_format)(ifile)
            except jflow.InvalidFormatError as e:
                sys.stderr.write(str(e)+"\n")
                sys.exit(1)
        else:
            sys.stderr.write("Error: Invalid file format '" + self.file_format + "'!\n")
            sys.exit(1)
Frédéric Escudié's avatar
Frédéric Escudié committed
727
728
729
730
731
732
733

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

734
735
736

class InputFile(StrParameter, AbstractInputFile):

Jerome Mariette's avatar
Jerome Mariette committed
737
    def __new__(self, name, help, file_format="any", default="", type="localfile", choices=None, 
738
                required=False, flag=None, group="default", display_name=None, size_limit="0"):
Jerome Mariette's avatar
Jerome Mariette committed
739
740
741
        if hasattr(type, '__call__'):
            type2test = type.__name__
        else: type2test = type
742

Jerome Mariette's avatar
Jerome Mariette committed
743
744
745
        if type2test not in INPUTFILE_TYPES:
            raise ValueError("InputFile.__new__: wrong type provided: '"+type2test+"', this should be choosen between '" 
                             + "', '".join(INPUTFILE_TYPES)+"'")
746
747
748
749

        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
750
    def __init__(self, name, help, file_format="any", default="", type="localfile", choices=None, 
751
752
                required=False, flag=None, group="default", display_name=None, size_limit="0"):
        AbstractInputFile.__init__(self, file_format, size_limit)
753
        StrParameter.__init__(self, name, help, flag=flag, default=default, type=type, choices=choices, 
754
                           required=required, group=group, display_name=display_name)
Jerome Mariette's avatar
Jerome Mariette committed
755

Jerome Mariette's avatar
Jerome Mariette committed
756
757
758
    def get_type(self):
        return self.type.__name__+AbstractInputFile.SIZE_LIMIT_SPLITER+self.size_limit

759
760
    def get_test_function(self):
        if (self.size_limit == "0"): ctype = self.type
Jerome Mariette's avatar
Jerome Mariette committed
761
        else: ctype = self.get_type()
762
763
        return create_test_function(ctype)

Jerome Mariette's avatar
Jerome Mariette committed
764
    def prepare_input_file(self, input):
765
766
        if input == None:
            return None
Jerome Mariette's avatar
Jerome Mariette committed
767
768
769
770
771
772
773
774
775
        # 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)
        if is_local: new_path = input
Jerome Mariette's avatar
Jerome Mariette committed
776
        self.check(new_path)
Jerome Mariette's avatar
Jerome Mariette committed
777
        return new_path
778

Jerome Mariette's avatar
Jerome Mariette committed
779

780
781
class OutputFile(StrParameter, AbstractOutputFile):

Frédéric Escudié's avatar
Frédéric Escudié committed
782
    def __new__(self, name, help, file_format="any", default="", choices=None,
783
                required=False, flag=None, group="default", display_name=None):
Frédéric Escudié's avatar
Frédéric Escudié committed
784
        return StrParameter.__new__(self, name, help, flag=flag, default=default, type="localfile", choices=choices,
785
786
                           required=required, group=group, display_name=display_name)

Frédéric Escudié's avatar
Frédéric Escudié committed
787
    def __init__(self, name, help, file_format="any", default="", choices=None,
788
                required=False, flag=None, group="default", display_name=None):
Jerome Mariette's avatar
Jerome Mariette committed
789
        AbstractIOFile.__init__(self, file_format)
790
        StrParameter.__init__(self, name, help, flag=flag, default=default, type="localfile", choices=choices, 
791
792
                           required=required, group=group, display_name=display_name)

793

794
class ParameterList(list, AbstractParameter):
795

Jerome Mariette's avatar
Jerome Mariette committed
796
    def __init__(self, name, help, default=None, type=types.StringType, choices=None, required=False,
797
                 flag=None, sub_parameters=None, group="default", display_name=None):
Jerome Mariette's avatar
Jerome Mariette committed
798
        if default == None: default = []
Frédéric Escudié's avatar
Frédéric Escudié committed
799
        AbstractParameter.__init__(self, name, help, flag=flag, default=default, type=type, choices=choices, required=required,
800
801
802
803
804
                                   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)
805

806

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

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

Jerome Mariette's avatar
Jerome Mariette committed
812
        if default == None: default = []   
Jerome Mariette's avatar
Jerome Mariette committed
813
814
815
        if hasattr(type, '__call__'):
            type2test = type.__name__
        else: type2test = type
816

Jerome Mariette's avatar
Jerome Mariette committed
817
818
819
        if type2test not in INPUTFILE_TYPES:
            raise ValueError("InputFile.__new__: wrong type provided: '"+type2test+"', this should be choosen between '" 
                             + "', '".join(INPUTFILE_TYPES)+"'")
820

821
        AbstractInputFile.__init__(self, file_format, size_limit)
Jerome Mariette's avatar
Jerome Mariette committed
822
        ParameterList.__init__(self, name, help, flag=flag, default=default, type=type, choices=choices, 
823
                               required=required, group=group, display_name=display_name)
824

825
826
827
828
        if default.__class__.__name__ == "str":
            return list.__init__(self, [default])
        elif default.__class__.__name__ == "list":
            return list.__init__(self, default)
829
830
        elif issubclass( default.__class__, InputFile ):
            return list.__init__(self, [default])
Frédéric Escudié's avatar
Frédéric Escudié committed
831
        elif issubclass( default.__class__, AbstractInputFile ):
Jerome Mariette's avatar
Jerome Mariette committed
832
            return list.__init__(self, default)
833
834
        elif issubclass( default.__class__, OutputFile ):
            return list.__init__(self, [default])
Frédéric Escudié's avatar
Frédéric Escudié committed
835
        elif issubclass( default.__class__, AbstractOutputFile ):
Jerome Mariette's avatar
Jerome Mariette committed
836
            return list.__init__(self, default)
Jerome Mariette's avatar
Jerome Mariette committed
837
838
839
840
    
    def get_type(self):
        return self.type.__name__+AbstractInputFile.SIZE_LIMIT_SPLITER+self.size_limit
    
841
842
    def get_test_function(self):
        if (self.size_limit == "0"): ctype = self.type
Jerome Mariette's avatar
Jerome Mariette committed
843
        else: ctype = self.get_type()
844
845
        return create_test_function(ctype)

Jerome Mariette's avatar
Jerome Mariette committed
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
    def prepare_input_files(self, inputs):
        path2test = inputs
        if not path2test.__class__.__name__ == "list":
            path2test = [path2test]
        new_vals, done = [], []
        # handle url inputs
        for path in path2test:
            new_url, is_uri = self._download_urlfile(path)
            if is_uri:
                new_vals.append(new_url)
                done.append(path)
        for d in done: path2test.remove(d)
        done = []
        # handle localfile
        for path in path2test:
            if os.path.isfile(path):
                new_vals.append(path)
                done.append(path)
        for d in done: path2test.remove(d)        
        # handle upload inputs
        if self.type.__name__ == "inputfile" or self.type.__name__ == "browsefile":
            for path in path2test:
                jflow_config_reader = JFlowConfigReader()
                new_vals.append(os.path.join(jflow_config_reader.get_tmp_directory(), path))
Jerome Mariette's avatar
Jerome Mariette committed
870
871
872
        # 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
873
        return new_vals
874

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

Jerome Mariette's avatar
Jerome Mariette committed
877
878
879
    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
880
        AbstractIOFile.__init__(self, file_format)
Jerome Mariette's avatar
Jerome Mariette committed
881
        ParameterList.__init__(self, name, help, flag=flag, default=default, type="localfile", choices=choices, 
882
883
884
885
886
                               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
887

888

Frédéric Escudié's avatar
Frédéric Escudié committed
889
890
891
892
893
894
895
896
897
898
class DynamicOutput(ParameterList, AbstractOutputFile):
    """
     @warning : with this class of output, the component become dynamic.
    """
    def update(self):
        """
         This method is used at the end of component execution to update output list.
        """
        raise NotImplementedError

899

Frédéric Escudié's avatar
Frédéric Escudié committed
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
class OutputFilesEndsWith(DynamicOutput):

    def __init__(self, name, help, output_directory, end_str, include=True, file_format="any", choices=None, 
                 required=False, flag=None, group="default", display_name=None):
        """
         @warning : with this class of output, the component become dynamic.
         @param output_directory : path to the directory where outputs will be created.
         @param end_str : the end of the files names.
         @param include : if true, the files with name terminated by end_str are added into output files.
                          If false, the files with name not terminated by end_str are added into output files.
        """
        AbstractIOFile.__init__(self, file_format)
        default = []
        ParameterList.__init__(self, name, help, flag=flag, default=default, type="localfile", choices=choices, 
                               required=required, group=group, display_name=display_name)
        self.output_directory = output_directory
        self.end_str = end_str
        self.include = include
        return list.__init__(self, default)

    def update(self):
        output_files = list()
        for file in os.listdir( self.output_directory ):
            if file.endswith( self.end_str ) and self.include :
                output_files.append( os.path.join(self.output_directory, file) )
            elif not file.endswith( self.end_str ) and not self.include:
                output_files.append( os.path.join(self.output_directory, file) )
        list.__init__(self, output_files)

929

Frédéric Escudié's avatar
Frédéric Escudié committed
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
class OutputFilesPattern(DynamicOutput):

    def __init__(self, name, help, output_directory, pattern, include=True, file_format="any", choices=None, 
                  required=False, flag=None, group="default", display_name=None):
        """
         @warning : with this class of output, the component become dynamic.
         @param output_directory : path to the directory where outputs will be created.
         @param pattern : the pattern of (a part) the file names.
         @param include : if true, the files with the pattern in file name are added into output files.
                          If false, the files with the pattern in file name are added into output files.
        """
        AbstractIOFile.__init__(self, file_format)
        default = []
        ParameterList.__init__(self, name, help, flag=flag, default=default, type="localfile", choices=choices, 
                               required=required, group=group, display_name=display_name)
        self.output_directory = output_directory
        self.pattern = pattern
        self.include = include
        return list.__init__(self, default)

    def update(self):
        output_files = list()
        for file in os.listdir( self.output_directory ):
            if self.include and re.search( self.pattern, file ) is not None:
                output_files.append( os.path.join(self.output_directory, file) )
            elif not self.include and re.search( self.pattern, file ) is None:
                output_files.append( os.path.join(self.output_directory, file) )
        return list.__init__(self, output_files)