/usr/share/pyshared/asrun/dev/messages.py is in code-aster-run 1.13.1-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 | # -*- coding: utf-8 -*-
# ==============================================================================
# COPYRIGHT (C) 1991 - 2003 EDF R&D WWW.CODE-ASTER.ORG
# 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 2 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, WRITE TO EDF R&D CODE_ASTER,
# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE.
# ==============================================================================
"""
Tools for developpers :
- search messages
"""
import os
import os.path as osp
import re
import cPickle
import time
from glob import glob
from asrun.common.i18n import _
from asrun.mystring import print3, ufmt
from asrun.config import AsterConfig, build_config_of_version
from asrun.build import AsterBuild, unigest2dict
from asrun.progress import Progress
class CataMessageError(Exception):
"""Error with a catalog of messages."""
def __init__(self, fcata, reason):
self.reason = reason
self.fcata = fcata
def __str__(self):
return ufmt(_(u"%s: %s, error: %s"),
self.__class__.__name__, self.fcata, self.reason)
class MessageError(Exception):
"""Error on a message."""
def __init__(self, msgid, reason):
self.reason = reason
self.msgid = msgid
def __str__(self):
return "%s: %s, error: %s" \
% (self.__class__.__name__, self.msgid, self.reason)
class MESSAGE_MANAGER(object):
"""Classe pour récupérer des informations sur le catalogue de messages.
"""
def __init__(self, repref,
fort=('bibfor', 'bibf90'),
pyt='bibpyt',
capy='catapy',
cache_dict=None, verbose=True, force=False,
ignore_comments=True, debug=False,
surch_fort=[], surch_pyt=[], unig=None):
"""Initialisations."""
if type(fort) not in (list, tuple):
fort = [fort,]
if type(surch_fort) not in (list, tuple):
surch_fort = [surch_fort,]
if type(surch_pyt) not in (list, tuple):
surch_pyt = [surch_pyt,]
self.repref = repref
self.fort = [osp.join(repref, rep) for rep in fort]
self.pyt = osp.join(repref, pyt)
self.capy = osp.join(repref, capy)
self.surch_fort = [osp.abspath(d) for d in surch_fort]
self.surch_pyt = [osp.abspath(d) for d in surch_pyt]
self.verbose = verbose
self.debug = debug
self.force = force
self.message_dir = 'Messages'
self.cache_dict = cache_dict or osp.join('/tmp', 'messages_dicts.pick')
self.ignore_comments = ignore_comments
self.wrk_fort = osp.join(os.getcwdu(), 'F')
self.wrk_pyt = osp.join(os.getcwdu(), 'PY')
self.unig = unig
# init AsterConfig, AsterBuild objects
fconf = osp.join(self.repref, 'config.txt')
self.conf_obj = AsterConfig(fconf, run=None)
self.build_obj = AsterBuild(run=None, conf=self.conf_obj)
if unig:
# use with_fordepla=False not to mark moved files as removed
self.unig = unigest2dict(unig, self.conf_obj, with_fordepla=True)
if self.verbose:
print3('Repertoires :\n REF=%s\n FORTRAN=%s\n PYTHON=%s\n CAPY=%s' \
% (self.repref, self.fort, self.pyt, self.capy))
self.l_cata = self._get_list_cata()
self.l_src, self.l_pyt = self._get_list_src()
# self._build_regexp()
def read_cata(self):
"""Read all catalogues"""
self._build_dict()
self.print_stats()
def _filename_cata(self, cata):
"""Retourne le nom du fichier associé à un catalogue."""
name = osp.join(self.pyt, self.message_dir, cata + '.py')
return name
def _id2filename(self, msgid):
"""Retourne modelisa5 à partir de MODELISA5_46"""
mat = re.search('([A-Z]+[0-9]*)_([0-9]+)', msgid)
if mat == None:
raise MessageError(msgid, _(u'invalid message id'))
cata, num = mat.groups()
return self._filename_cata(cata.lower()), int(num)
def _filename2id(self, fcata, num):
"""Retourne MODELISA5_46 à partir de modelisa5"""
return '%s_%d' % (osp.splitext(osp.basename(fcata))[0].upper(), num)
def makedirs(self):
"""Crée les répertoires pour les fichiers modifiés
"""
for d in (self.wrk_fort, self.wrk_pyt):
if not osp.isdir(d):
os.makedirs(d)
def _get_list_cata(self):
"""Retourne la liste des catalogues de messages.
"""
re_mess = re.compile('#@.*Messages')
s_cata = set(glob(osp.join(self.pyt, self.message_dir, '*.py')))
s_suppr = set()
l_surch = []
# ajouter la surcharge et retirer le catalogue d'origine
for dsrc in self.surch_pyt:
for f in glob(osp.join(dsrc, '*.py')) + glob(osp.join(dsrc, '*', '*.py')):
txt = open(f, 'r').read()
if re_mess.search(txt):
l_surch.append(osp.abspath(f))
fsup = osp.join(self.pyt, self.message_dir, osp.basename(f))
if osp.exists(fsup):
s_suppr.add(fsup)
s_cata.update(l_surch)
if len(l_surch) > 0:
print3('%5d catalogues en surcharge : ' % len(l_surch))
print3(os.linesep.join(l_surch))
s_cata = set([osp.abspath(f) for f in s_cata \
if not osp.basename(f) in ['__init__.py', 'context_info.py', 'fermetur.py']])
l_suppr = []
if self.unig and len(self.unig['py']) > 0:
l_suppr = [osp.abspath(osp.join(self.repref, f)) \
for f in self.unig['py'] if f.find(self.message_dir) > -1]
s_suppr.update(l_suppr)
l_suppr = list(s_suppr)
l_suppr.sort()
if len(l_suppr) > 0:
print3('%5d catalogue(s) supprime(s) :' % len(l_suppr))
if self.verbose: print3(os.linesep.join(l_suppr))
l_cata = list(s_cata.difference(s_suppr))
l_cata.sort()
return l_cata
def check_cata(self):
"""Vérifie les catalogues.
"""
if self.verbose:
print3('%5d catalogues dans %s + %s' \
% (len(self.l_cata), self.pyt, self.surch_pyt))
all_msg = []
error_occurs = False
for f in self.l_cata:
try:
cata = CATA(f)
cata.check()
all_msg.extend([self._filename2id(f, i) for i in cata])
if self.verbose:
print3(cata)
except CataMessageError, msg:
error_occurs = True
print3(msg)
self.l_cata.remove(f)
if error_occurs:
raise CataMessageError(_(u"global"), _(u"errors occurred!"))
all_msg = set(all_msg)
# messages jamais appelés
used = set(self.d_msg_call.keys())
unused = list(all_msg.difference(used))
unused.sort()
union = used.union(all_msg)
not_found = list(used.difference(all_msg))
not_found.sort()
if self.verbose:
print3('%6d messages dans les catalogues' % len(all_msg))
print3('dont %6d messages appeles presents dans les catalogues' % (len(used) - len(not_found)))
print3(' et %6d messages inutilises' % len(unused))
print3(' + %6d messages appeles absents des catalogues' % len(not_found))
#print '%6d messages total (union pour verif)' % len(union)
return unused, not_found
def _build_regexp(self):
"""Construit la liste des expressions régulières pour la recherche des messages.
"""
l_regexp = []
for cata in self.l_cata:
cata = osp.splitext(osp.basename(cata))[0]
l_regexp.append('%s_[0-9]+' % cata.upper())
self.regexp = re.compile('|'.join(l_regexp))
def _get_list_src(self):
"""Retourne la liste des routines fortran et python.
"""
l_f = self._get_list_fort()
l_pyt = self._get_list_python()
if self.verbose:
print3('%5d routines fortran dans %s + %s' % (len(l_f), self.fort, self.surch_fort))
print3('%5d modules python dans %s + %s' % (len(l_pyt), self.pyt, self.surch_pyt))
return l_f, l_pyt
def _get_list_fort(self):
"""Retourne la liste des fichiers sources fortran/fortran90."""
s_f = set()
for dsrc in self.fort:
s_f.update(glob(osp.join(dsrc, '*.f')))
s_f.update(glob(osp.join(dsrc, '*', '*.f')))
s_f.update(glob(osp.join(dsrc, '*.F')))
s_f.update(glob(osp.join(dsrc, '*', '*.F')))
s_f.update(glob(osp.join(dsrc, '*.F90')))
s_f.update(glob(osp.join(dsrc, '*', '*.F90')))
if self.conf_obj.use_hg:
l_f = [osp.abspath(f) for f in s_f]
l_f.sort()
return l_f
d_f = {}
for f in s_f:
assert d_f.get(osp.basename(f)) is None, 'ERROR : %s (old : %s)' % (f, d_f[osp.basename(f)])
d_f[osp.basename(f)] = f
# surcharge
s_surch = set()
for dsrc in self.surch_fort:
s_surch.update(glob(osp.join(dsrc, '*.f')))
s_surch.update(glob(osp.join(dsrc, '*', '*.f')))
s_surch.update(glob(osp.join(dsrc, '*.F')))
s_surch.update(glob(osp.join(dsrc, '*', '*.F')))
if len(s_surch) > 0:
l_surch = list(s_surch)
l_surch.sort()
print3('%5d sources en surcharge : ' % len(l_surch))
print3(os.linesep.join(l_surch))
# retirer des sources originaux ceux de la surcharge...
s_suppr = set()
for f in s_surch:
fexist = d_f.get(osp.basename(f))
if fexist:
s_suppr.add(fexist)
if self.verbose: print3('suppression :', fexist)
# ... et ceux de l'unigest
if self.unig:
iunig = 0
for f in self.unig['f'] + self.unig['f90']:
iunig += 1
s_suppr.add(d_f.get(osp.basename(f), ''))
if self.verbose: print3('suppression :', f)
if iunig > 0:
print3('%5d source(s) supprime(s).' % iunig)
s_f.difference_update(s_suppr)
s_f.update(s_surch)
l_f = [osp.abspath(f) for f in s_f]
l_f.sort()
return l_f
def _get_list_python(self):
"""Retourne la liste des fichiers python
"""
s_pyt = set()
s_pyt.update(glob(osp.join(self.pyt, '*.py')))
s_pyt.update(glob(osp.join(self.pyt, '*', '*.py')))
s_pyt.update(glob(osp.join(self.capy, '*.capy')))
s_pyt.update(glob(osp.join(self.capy, '*', '*.capy')))
if self.conf_obj.use_hg:
l_pyt = [osp.abspath(f) for f in s_pyt]
l_pyt.sort()
return l_pyt
d_py = {}
for f in s_pyt:
typ = osp.splitext(f)[-1][1:]
key = self.build_obj.GetCModif(typ, f)
assert d_py.get(key) is None, 'ERROR : %s (old : %s)' % (key, d_py[key])
d_py[key] = f
# surcharge
s_surch = set()
for dsrc in self.surch_pyt:
s_surch.update(glob(osp.join(dsrc, '*.py')))
s_surch.update(glob(osp.join(dsrc, '*', '*.py')))
s_surch.update(glob(osp.join(dsrc, '*.capy')))
s_surch.update(glob(osp.join(dsrc, '*', '*.capy')))
if len(s_surch) > 0:
l_surch = list(s_surch)
l_surch.sort()
print3('%5d module(s) python en surcharge : ' % len(l_surch))
print3(os.linesep.join(l_surch))
# retirer des sources originaux ceux de la surcharge...
s_suppr = set()
for f in s_surch:
typ = osp.splitext(f)[-1][1:]
key = self.build_obj.GetCModif(typ, f)
fexist = d_py.get(key)
if fexist:
s_suppr.add(fexist)
if self.verbose: print3('suppression :', fexist)
# ... et ceux de l'unigest
if self.unig:
iunig = 0
for typ in ('py', 'capy'):
for f in self.unig[typ]:
iunig += 1
fabs = osp.abspath(osp.join(self.repref, f))
key = self.build_obj.GetCModif(typ, fabs)
s_suppr.add(d_py.get(key, ''))
if self.verbose: print3('suppression :', fabs)
if iunig > 0:
print3('%5d module(s) python supprime(s).' % iunig)
s_pyt.difference_update(s_suppr)
s_pyt.update(s_surch)
l_pyt = [osp.abspath(f) for f in s_pyt]
l_pyt.sort()
return l_pyt
def search_message(self, fich):
"""Retourne les messages utilisés dans 'fich'.
"""
try:
txt = open(fich, 'r').read()
except IOError, msg:
print3(_(u'Error with file %s : %s') % (fich, msg))
return []
ext = osp.splitext(fich)[-1]
txt = clean_source(txt, ext, ignore_comments=self.ignore_comments, wrap=True)
if osp.splitext(fich)[-1] not in ('.py', '.capy'):
expr = 'CALL\s+(U2MES.|UTEXC[MP]+|UTPRIN)\s*\(([^,]*?), *[\'\"]+(.*?)[\'\"]+ *[,\)]+'
else:
expr = '[\s\.:]+(UTMESS|GetText)\s*\(([^,]*?), *[\'\"]+(.*?)[\'\"]+ *[,\)]+'
all_msg = re.findall(expr, txt, flags=re.I)
l_msg = []
for found in all_msg:
sub, typ, msg = found
if msg.startswith('FERMETUR_'):
pass
elif re.search('^[A-Z0-9]+_[0-9]+$', msg) is None:
print3("Invalid message id ('%s') in file %s (%s)" % (msg, fich, sub))
else:
mattyp = re.search('[\'\" ]+(.*?)[\+\'\" ]+', typ)
# variables and numbers (for exception) are allowed
if mattyp is not None and \
mattyp.group(1) not in ('', 'A', 'I', 'E', 'S', 'F', 'M', 'D'):
# may be '' for example STY//'+'
print3("Invalid message type (%s) for message '%s' in file %s" \
% (mattyp.group(1), msg, fich))
print3("type = %s" % typ)
else:
l_msg.append(msg)
# l_msg = self.regexp.findall(txt)
# verif
l_res = []
for msg in l_msg:
spl = msg.split('_')
assert len(spl) == 2, 'ERROR invalid : %s' % msg
msg = '%s_%d' % (spl[0], int(spl[1]))
l_res.append(msg)
return l_res
def _build_dict(self):
"""Construit les dictionnaires :
fichier source : liste des messsages appelés
message : liste des fichiers appelant ce message
"""
# est-ce dans le cache ?
if not self.force and osp.isfile(self.cache_dict) \
and os.stat(self.cache_dict).st_size > 0:
if self.verbose:
print3('Load dicts from cache (%s)...' % self.cache_dict)
pick = open(self.cache_dict, 'r')
self.d_msg_used = cPickle.load(pick)
self.d_msg_call = cPickle.load(pick)
pick.close()
else:
self.d_msg_used = {}
self.d_msg_call = {}
l_all = self.l_src + self.l_pyt
if self.verbose:
p = Progress(maxi=len(l_all), format='%5.1f %%',
msg='Analyse des sources... ')
for i, f in enumerate(l_all):
if self.verbose:
p.Update(i)
# key = f.replace(self.repref, '')
key = re.sub('^%s/*', '', f)
lm = self.search_message(f)
if len(lm) > 0:
self.d_msg_used[key] = lm
for msg in lm:
self.d_msg_call[msg] = self.d_msg_call.get(msg, []) + [key,]
if self.verbose:
p.End()
#pprint.pprint(self.d_msg_used)
pick = open(self.cache_dict, 'w')
cPickle.dump(self.d_msg_used, pick)
cPickle.dump(self.d_msg_call, pick)
pick.close()
def print_stats(self):
"""Affiche les stats sur les données lues/construites
"""
if self.verbose:
print3('%6d messages appelés dans les sources' % len(self.d_msg_call.keys()))
print3('%6d fichiers sources appellent le catalogue de messages' % len(self.d_msg_used.keys()))
def move(self, oldid, dest, reuse_hole=True):
"""Déplace le message 'oldid' dans le catalogue 'dest'.
"""
if self.verbose:
print3('--- moving "%s" into "%s"' % (oldid, dest))
# catalogue objects
old_f, old_num = self._id2filename(oldid)
new_f = self._filename_cata(dest.lower())
# have these catalogues been already changed ?
fmod = osp.join(self.wrk_pyt, osp.basename(old_f))
if osp.isfile(fmod):
print3('from %s' % fmod)
old_f = fmod
fmod = osp.join(self.wrk_pyt, osp.basename(new_f))
if osp.isfile(fmod):
print3('from %s' % fmod)
new_f = fmod
old_cata = CATA(old_f)
new_cata = CATA(new_f)
if self.verbose:
print3(old_cata)
print3(new_cata)
new_num = new_cata.get_new_id(reuse_hole)
if new_num < 0:
raise CataMessageError(new_f, _(u'no message id available in this catalog'))
newid = self._filename2id(new_f, new_num)
# check message existence
if old_cata[old_num] == None:
raise MessageError(oldid, _(u'unknown message'))
new_cata[new_num] = old_cata[old_num]
del old_cata[old_num]
# write modified catalogues
self.makedirs()
fout = osp.join(self.wrk_pyt, osp.basename(old_f))
content = old_cata.get_content()
open(fout, 'w').write(content)
fout = osp.join(self.wrk_pyt, osp.basename(new_f))
content = new_cata.get_content()
open(fout, 'w').write(content)
print3('Nouveau fichier : %s' % fout)
# modify source using 'oldid' message
l_src = self.d_msg_call.get(oldid, [])
for f in l_src:
ext = osp.splitext(f)[-1]
rdest = self.wrk_fort
if ext == '.py':
rdest = self.wrk_pyt
# already changed ?
fmod = osp.join(rdest, osp.basename(f))
if osp.isfile(fmod):
print3('from %s' % fmod)
f = fmod
txt = open(osp.join(self.repref, f), 'r').read()
new = re.sub('%s([\'\"]+)' % oldid, newid + r'\1', txt)
fout = osp.join(rdest, osp.basename(f))
open(fout, 'w').write(new)
print3('Nouveau fichier : %s' % fout)
def who_use(self, msg):
"""Qui utilise le message 'msg' ?
"""
return tuple(self.d_msg_call.get(msg.upper(), []))
def get_key(self, sub):
"""Retourne la clé dans d_msg_used correspondant à 'sub'.
Seule la première est retournée si jamais il y en avait plusieurs.
"""
l_allsub = self.d_msg_used.keys()
l_sub = [f for f in l_allsub if f.split(os.sep)[-1] == sub]
if len(l_sub) > 1:
print3('Plusieurs routines correspondent : %s' % ', '.join(l_sub))
print3('On utilise la première valeur.')
if len(l_sub) == 0:
result = None
else:
result = l_sub[0]
return result
def which_msg(self, sub):
"""Quels sont les messages utilisés par la routine 'sub' ?
"""
key = self.get_key(sub)
return tuple(self.d_msg_used.get(key, []))
template_cata_header = """# -*- coding: utf-8 -*-
# CONFIGURATION MANAGEMENT OF EDF VERSION
# ======================================================================
# COPYRIGHT (C) 1991 - %s EDF R&D WWW.CODE-ASTER.ORG
# 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 2 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, WRITE TO EDF R&D CODE_ASTER,
# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE.
# ======================================================================
def _(x) : return x
cata_msg = {""" % time.strftime('%Y')
template_cata_footer = """
}
"""
template_cata_msg = '''
%(msgid)s : _(u"""%(text)s"""),'''
class CATA:
"""Classe représentant un catalogue de messages.
Méthodes attendues :
- nombre de messages,
- indice du dernier messages,
- indice libre,
- ajouter/supprimer un message,
- ...
"""
def __init__(self, fcata):
"""Initialisation
"""
self.fcata = fcata
self.cata_msg = {}
try:
d = { '_' : lambda x: x, }
execfile(fcata, d)
self.cata_msg = d['cata_msg']
except Exception, msg:
print3('-'*80+'\n', msg, '\n'+'-'*80)
raise CataMessageError(self.fcata, _(u'unable to import the file'))
def get_nb_msg(self):
"""Nombre de messages.
"""
return len(self.cata_msg)
def get_last_id(self):
"""Indice du dernier message.
"""
return max(self.cata_msg.keys() or [0,])
def get_new_id(self, reuse_hole=True):
"""Indice libre. Si 'end', on prend systématiquement à la fin,
sinon on cherche aussi dans les trous.
"""
if not reuse_hole:
start = self.get_last_id()
else:
start = 1
all = set(range(start, 100))
free = all.difference(self.cata_msg.keys())
if len(free) == 0:
new = -1
else:
new = min(free)
return new
def __getitem__(self, key):
"""Retourne le contenu du message ou None.
"""
return self.cata_msg.get(key, None)
def __setitem__(self, key, msg):
"""Ajoute le message 'msg' à l'indice 'key'.
"""
if self[key] != None:
raise MessageError(key, _(u'message already exists !'))
self.cata_msg[key] = msg
def __delitem__(self, key):
"""Supprime le message d'indice 'key'.
"""
if self[key] == None:
raise MessageError(key, _(u'this message does not exist !'))
del self.cata_msg[key]
def __repr__(self):
"""Résumé du catalogue.
"""
return ufmt(_(u'%3d messages (last=%3d, next=%3d) in %s'),
self.get_nb_msg(), self.get_last_id(), self.get_new_id(), self.fcata)
def __iter__(self):
"""Itération sur les id des messages.
"""
return iter(self.cata_msg)
def check(self):
"""Vérifie le texte des messages."""
def_args = {}
for i in range(1,100):
def_args['i%d' % i] = 99999999
def_args['r%d' % i] = 1.234e16 # not too big to avoid python issue1742669
def_args['k%d' % i] = 'xxxxxx'
def_args['ktout'] = "all strings !"
error = []
for num, msg in self.cata_msg.items():
if type(msg) is dict:
msg = msg['message']
try:
txt = msg % def_args
except:
error.append(ufmt(_(u'message #%s invalid : %s'), num, msg))
if len(error) > 0:
raise CataMessageError(self.fcata, os.linesep.join(error))
def get_cmodif(self):
"""Retourne la carte MODIF.
"""
cmodif = None
fobj = open(self.fcata, 'r')
for line in fobj:
if re.search('#@ +MODIF|#@ +AJOUT', line):
cmodif = line.replace(os.linesep, '')
break
fobj.close()
if cmodif == None:
raise CataMessageError(self.fcata, _(u'invalid header "#@ MODIF/AJOUT..."'))
return cmodif
def get_content(self):
"""Contenu du catalogue "reconstruit".
"""
txt = [self.get_cmodif(),]
txt.append(template_cata_header)
l_ind = self.cata_msg.keys()
l_ind.sort()
for msgid in l_ind:
txt.append(template_cata_msg % {'msgid' : msgid, 'text' : self.cata_msg[msgid]})
txt.append(template_cata_footer)
return os.linesep.join(txt)
def clean_source(content, ext, ignore_comments, wrap):
"""Nettoie un fichier source.
"""
if ignore_comments:
assert ext in ('.f', '.F', '.F90', '.py', '.capy'), 'unknown type : %s' % str(ext)
if ext in ('.f', '.F'):
reg_ign = re.compile('(^[A-Z!#].*$)', re.MULTILINE)
elif ext in ('.F90'):
reg_ign = re.compile('(^[!#].*$)', re.MULTILINE)
elif ext in ('.py', '.capy'):
reg_ign = re.compile('(#.*$)', re.MULTILINE)
content = reg_ign.sub('', content).expandtabs()
if wrap and ext in ('.f', '.F'):
content = ''.join([lin[6:] for lin in content.splitlines()])
return content
def GetMessageInfo(run, *args):
"""Return info about Code_Aster messages.
"""
if not run.get('aster_vers'):
run.parser.error(_(u"You must define 'default_vers' in 'aster' configuration file or use '--vers' option."))
REPREF = run.get_version_path(run['aster_vers'])
fconf = run.get('config')
if fconf:
fconf = osp.abspath(fconf)
conf = build_config_of_version(run, run['aster_vers'], fconf)
if run['nolocal']:
run.Mess(_(u'This operation only works on local source files. "--nolocal" option ignored'))
bibfor = [conf['SRCFOR'][0],]
if conf['SRCF90'][0] != '':
bibfor.append(conf['SRCF90'][0])
args = list(args)
named_actions = ('check', 'move',)
action = None
if len(args) > 0 and args[0] in named_actions:
action = args.pop(0)
elif len(args) == 0:
run.Mess(_(u'You must choose an operation from %s or give a subroutine name or a message ID') \
% repr(named_actions), '<F>_INVALID_ARGUMENT')
# surcharge
surch_fort = run.get('surch_fort', [])
if surch_fort:
surch_fort = surch_fort.split(',')
surch_pyt = run.get('surch_pyt', [])
if surch_pyt:
surch_pyt = surch_pyt.split(',')
pick_cache = 'messages_dicts.%s.pick' % (run['aster_vers'].replace(os.sep, '_'))
msgman = MESSAGE_MANAGER(repref=REPREF,
fort=bibfor,
pyt=conf['SRCPY'][0],
capy=conf['SRCCAPY'][0],
cache_dict=osp.join(run['cache_dir'], pick_cache),
force=run['force'], verbose=run['verbose'],
debug=run['debug'],
surch_fort=surch_fort,
surch_pyt =surch_pyt,
unig =run.get('unigest', None),
)
msgman.read_cata()
if action == 'check':
try:
unused, not_found = msgman.check_cata()
except CataMessageError, msg:
run.Sortie(4)
if not run['silent']:
print3('Messages inutilises :')
print3(' '.join(unused))
print3('Messages inexistants :')
print3(' '.join(not_found))
if len(unused) + len(not_found) > 0:
run.Sortie(4)
elif action == 'move':
if len(args) != 2:
run.parser.error(
_(u"'--%s %s' requires 2 arguments") % (run.current_action, action))
msgman.move(*args)
else:
print3()
fmt = '%12s : %s'
for obj in args:
l_msg = list(set(msgman.which_msg(obj)))
if len(l_msg) > 0:
l_msg.sort()
print3(fmt % (obj, l_msg))
l_sub = list(set(msgman.who_use(obj)))
if len(l_sub) > 0:
l_sub.sort()
print3(fmt % (obj, l_sub))
|