forked from NaN-tic/tryton-tasks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
351 lines (296 loc) · 11.4 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
from blessings import Terminal
from invoke import task, Collection
from path import Path
import configparser
import os
import psycopg2
import shutil
import subprocess
import sys
try:
from proteus import config, Wizard, Model
except ImportError:
proteus_path = os.path.abspath(os.path.normpath(os.path.join(os.getcwd(),
'proteus')))
if os.path.isdir(proteus_path):
sys.path.insert(0, proteus_path)
try:
from proteus import config, Wizard, Model
except ImportError as e:
print("proteus importation error: ", e, file=sys.stderr)
trytond_path = os.path.abspath(os.path.normpath(os.path.join(os.getcwd(),
'trytond')))
if os.path.isdir(trytond_path):
sys.path.insert(0, trytond_path)
NO_MODULE_REPOS = ['trytond', 'tryton', 'proteus', 'nereid_app', 'sao',
'tasks', 'utils', 'config', 'patches']
BASE_MODULES = ['ir', 'res', 'tests', 'webdav']
CORE_FILES = ['core.cfg']
t = Terminal()
def _exit(initial_path, message=None):
if Path.getcwd() != initial_path:
os.chdir(initial_path)
if not message:
return sys.exit(0)
sys.exit(message)
def _ask_ok(prompt, default_answer=None):
ok = input(prompt) or default_answer
if ok.lower() in ('y', 'ye', 'yes'):
return True
if ok.lower() in ('n', 'no', 'nop', 'nope'):
return False
_exit("Yes or no, please")
def _check_required_file(filename, directory_name, directory_path):
if not directory_path.joinpath(filename).exists():
_exit('%s file not found in %s directory: %s' % (filename,
directory_name, directory_path))
def get_config_files():
""" Return all config files paths """
config_files = []
for r, d, f in os.walk("./config"):
for files in f:
if not files.endswith(".cfg"):
continue
config_files.append(os.path.join(r, files))
return config_files
def read_config_file(config_file=None, type='repos', unstable=True,
avoid_core=False):
assert type in ('repos', 'patches', 'all'), "Invalid 'type' param"
Config = configparser.ConfigParser()
if config_file is not None:
Config.readfp(open(config_file))
else:
for r, d, f in os.walk("./config", followlinks=True):
for files in f:
if avoid_core and files in CORE_FILES:
continue
if not files.endswith(".cfg"):
continue
if not unstable and files.endswith("-unstable.cfg"):
continue
if 'templates' in r:
continue
path = os.path.join(r, files)
if os.path.isfile(path):
# Check if file exists because it may be a symlink to
# ../local.cfg and it might not exist.
Config.readfp(open(path))
if type == 'all':
return Config
for section in Config.sections():
is_patch = (Config.has_option(section, 'patch')
and Config.getboolean(section, 'patch'))
if type == 'repos' and is_patch:
Config.remove_section(section)
elif type == 'patches' and not is_patch:
Config.remove_section(section)
return Config
@task()
def update_parent_left_right(ctx, database, table, field=None, host='localhost',
port='5432', user=None, password=None):
''' Compute left/right fields for a parent field in a tryton table '''
if field is None:
field = 'parent'
def _parent_store_compute(cr, table, field):
def browse_rec(root, pos=0):
where = field + '=' + str(root)
if not root:
where = field + 'IS NULL'
cr.execute('SELECT id FROM %s WHERE %s \
ORDER BY %s' % (table, where, field))
pos2 = pos + 1
childs = cr.fetchall()
for id in childs:
pos2 = browse_rec(id[0], pos2)
cr.execute('update %s set "left"=%s, "right"=%s\
where id=%s' % (table, pos, pos2, root))
return pos2 + 1
query = 'SELECT id FROM %s WHERE %s IS NULL order by %s' % (
table, field, field)
pos = 0
cr.execute(query)
for (root,) in cr.fetchall():
pos = browse_rec(root, pos)
return True
db = _check_database(database, host, port, user, password)
if not db:
return
print("calculating parent_left of table", table, "and field:", field)
_parent_store_compute(db.cursor(), table, field)
db.commit()
db.close()
@task()
def prepare_translations(ctx, database, langs=None, host=None, port=None,
dbuser=None, dbpassword=None,
config_file=os.environ.get('TRYTOND_CONFIG')):
"""
Runs the set, clean and update translations wizards in the given database.
"""
print(t.bold('prepare_translations: database=%s, langs=%s') % (database,
langs))
if not _check_database(database, host, port, dbuser, dbpassword):
return
config.set_trytond(database=database, config_file=config_file)
Lang = Model.get('ir.lang')
if langs is None:
languages = Lang.find([
('translatable', '=', True),
])
else:
langs = langs.split(',')
languages = Lang.find([
('code', 'in', langs),
])
if set(langs) != set(l.code for l in languages):
print(t.bold('Invalid languages: %s') % languages)
return
translation_set = Wizard('ir.translation.set')
translation_set.execute('set_')
translation_set.execute('end')
translation_clean = Wizard('ir.translation.clean')
translation_clean.execute('clean')
translation_clean.execute('end')
for language in languages:
translation_update = Wizard('ir.translation.update')
translation_update.form.language = language
translation_update.execute('update')
print("%s translation updated" % language.name)
@task()
def export_translations(ctx,database, modules, langs=None,
host=None, port=None, dbuser=None, dbpassword=None,
config_file=os.environ.get('TRYTOND_CONFIG')):
"""
Creates translation files for the given modules and the specified languages.
If no languages are specified, the ones marked as translatable in the
database are used.
"""
print(t.bold('export_translations: %s, %s, %s') % (database, modules,
langs))
if not _check_database(database, host, port, dbuser, dbpassword):
return
config.set_trytond(database=database, config_file=config_file)
try:
Module = Model.get('ir.module')
except KeyError:
# Compatibility with versions older than 3.8
Module = Model.get('ir.module.module')
if modules == 'all':
ir_modules = Module.find([
('state', 'in', ['installed', 'activated']),
])
else:
modules = modules.split(',')
ir_modules = Module.find([
('state', 'in', ['installed', 'activated']),
('name', 'in', modules),
])
missing_modules = set(modules) - set(m.name for m in ir_modules)
if missing_modules:
print(t.bold('Invalid modules: %s') % missing_modules)
return
Lang = Model.get('ir.lang')
if langs is None:
languages = Lang.find([
('translatable', '=', True),
])
else:
langs = langs.split(',')
languages = Lang.find([
('code', 'in', langs),
])
if set(langs) != set(l.code for l in languages):
print('Invalid languages: %s' % languages)
return
for module in ir_modules:
module_locale_path = os.path.abspath(os.path.normpath(
os.path.join(os.getcwd(), 'modules', module.name, 'locale')))
if not os.path.exists(module_locale_path):
os.makedirs(module_locale_path)
for language in languages:
if language.code == 'en_US':
continue
translation_export = Wizard('ir.translation.export')
translation_export.form.language = language
translation_export.form.module = module
translation_export.execute('export')
if not translation_export.form.file:
continue
file_path = os.path.join(module_locale_path,
'%s.po' % language.code)
with open(file_path, 'w') as f:
f.write(translation_export.form.file.decode('utf-8'))
translation_export.execute('end')
print(('Translation of "%s" in "%s" exported successfully.'
% (module.name, language.code)))
@task()
def account_reconcile(ctx, database, lines=2, months=6,
config_file=os.environ.get('TRYTOND_CONFIG')):
pref = config.set_trytond(database=database, config_file=config_file)
Module = Model.get('ir.module.module')
Company = Model.get('company.company')
modules = Module.find([
('name', '=', 'account_reconcile'),
])
if not modules:
print(t.bold('Module account_reconcile not found'))
return
reconcile, = modules
if reconcile.state != 'installed':
Module.install([reconcile.id], pref.context)
Wizard('ir.module.module.install_upgrade').execute('upgrade')
for company in Company.find([]):
print(t.bold('Start reconcile for company %s (Lines %s, Months %s)'
% (company.rec_name, lines, months)))
with pref.set_context({'company': company.id}):
reconcile = Wizard('account.move_reconcile')
reconcile.form.max_lines = str(lines)
reconcile.form.max_months = months
reconcile.form.start_date = None
reconcile.form.end_date = None
reconcile.execute('reconcile')
def _check_database(database, host=None, port=None, dbuser=None,
dbpassword=None):
connection_params = {'dbname': database}
if host:
connection_params['host'] = host
if port:
connection_params['port'] = port
if dbuser:
connection_params['user'] = dbuser
if dbpassword:
connection_params['password'] = dbpassword
try:
db = psycopg2.connect(**connection_params)
except Exception as e:
print(t.bold('Invalid database connection params:'))
print(str(e))
return False
return db
def execBashCommand(command, success_msg="", fail_msg="", quiet=True):
"""
Execute bash command.
@bashCommand: is list with the command and the options
return: list with the output and the posible error
"""
process = subprocess.Popen(command, stdout=subprocess.PIPE)
output, err = process.communicate()
if err and fail_msg:
print(fail_msg)
print(err)
return False
if not err and success_msg:
print(success_msg)
if not quiet:
print(output)
return True
def remove_dir(path, quiet=False):
if not quiet:
if not _ask_ok('Answer "yes" to remove path: "%s". [y/N] ' %
(path), 'n'):
return
shutil.rmtree(path)
UtilsCollection = Collection()
UtilsCollection.add_task(account_reconcile)
UtilsCollection.add_task(update_parent_left_right)
UtilsCollection.add_task(prepare_translations)
UtilsCollection.add_task(export_translations)