[FIX] tools.convert: use tools.ustr() instead of str() on exceptions.
[odoo/odoo.git] / openerpcommand / common.py
1 """
2 Define a few common arguments for server-side command-line tools.
3 """
4 import argparse
5 import os
6 try:
7     from setproctitle import setproctitle
8 except ImportError:
9     setproctitle = lambda x: None
10 import sys
11
12 def add_addons_argument(parser):
13     """
14     Add a common --addons argument to a parser.
15     """
16     parser.add_argument('--addons', metavar='ADDONS',
17         **required_or_default('ADDONS',
18                               'colon-separated list of paths to addons'))
19 def set_addons(args):
20     """
21     Turn args.addons into a list instead of a column-separated strings.
22     Set openerp.toools.config accordingly.
23     """
24     import openerp.tools.config
25     config = openerp.tools.config
26
27     assert hasattr(args, 'addons')
28     if args.addons:
29         args.addons = args.addons.split(':')
30     else:
31         args.addons = []
32
33     config['addons_path'] = ','.join(args.addons)
34
35 def get_addons_from_paths(paths, exclude):
36     """
37     Build a list of available modules from a list of addons paths.
38     """
39     exclude = exclude or []
40     module_names = []
41     for p in paths:
42         if os.path.exists(p):
43             names = list(set(os.listdir(p)))
44             names = filter(lambda a: not (a.startswith('.') or a in exclude), names)
45             module_names.extend(names)
46         else:
47             print "The addons path `%s` doesn't exist." % p
48             sys.exit(1)
49     return module_names
50
51 def required_or_default(name, h):
52     """
53     Helper to define `argparse` arguments. If the name is the environment,
54     the argument is optional and draw its value from the environment if not
55     supplied on the command-line. If it is not in the environment, make it
56     a mandatory argument.
57     """
58     if os.environ.get('OPENERP_' + name.upper()):
59         d = {'default': os.environ['OPENERP_' + name.upper()]}
60     else:
61         d = {'required': True}
62     d['help'] = h + '. The environment variable OPENERP_' + \
63         name.upper() + ' can be used instead.'
64     return d
65
66 class Command(object):
67     """
68     Base class to create command-line tools. It must be inherited and the
69     run() method overriden.
70     """
71
72     command_name = 'stand-alone'
73
74     def __init__(self, subparsers=None):
75         if subparsers:
76             self.parser = parser = subparsers.add_parser(self.command_name,
77                 description=self.__class__.__doc__)
78         else:
79             self.parser = parser = argparse.ArgumentParser(
80                 description=self.__class__.__doc__)
81
82         parser.add_argument('-d', '--database', metavar='DATABASE',
83             **required_or_default('DATABASE', 'the database to connect to'))
84         parser.add_argument('-u', '--user', metavar='USER',
85             **required_or_default('USER', 'the user login or ID. When using '
86             'RPC, providing an ID avoid the login() step'))
87         parser.add_argument('-p', '--password', metavar='PASSWORD',
88             **required_or_default('PASSWORD', 'the user password')) # TODO read it from the command line or from file.
89
90         parser.set_defaults(run=self.run_with_args)
91
92     def run_with_args(self, args):
93         self.args = args
94         self.run()
95
96     def run(self):
97         print 'Stub Command.run().'
98
99     @classmethod
100     def stand_alone(cls):
101         """
102         A single Command object is a complete command-line program. See
103         `openerp-command/stand-alone` for an example.
104         """
105         command = cls()
106         args = command.parser.parse_args()
107         args.run(args)