Edgewall Software

Ticket #7241: 7241-trac-admin-wiki-export-r7376.2.diff

File 7241-trac-admin-wiki-export-r7376.2.diff, 18.2 KB (added by cboos, 4 months ago)

Updated patch, also use printerr now

  • trac/admin/console.py

     
    3737from trac.util.html import html 
    3838from trac.util.text import to_unicode, wrap, unicode_quote, unicode_unquote, \ 
    3939                           print_table, console_print 
    40 from trac.util.translation import _ 
     40from trac.util.translation import _, ngettext 
    4141from trac.wiki import WikiPage 
    4242from trac.wiki.api import WikiSystem 
    4343from trac.wiki.macros import WikiMacroBase 
    4444 
    4545TRAC_VERSION = pkg_resources.get_distribution('Trac').version 
    4646 
     47def printout(*args): 
     48    console_print(sys.stdout, *args) 
     49 
     50def printerr(*args): 
     51    console_print(sys.stderr, *args) 
     52 
    4753def copytree(src, dst, symlinks=False, skip=[]): 
    4854    """Recursively copy a directory tree using copy2() (from shutil.copytree.) 
    4955 
     
    117123        except SystemExit: 
    118124            raise 
    119125        except TracError, e: 
    120             console_print(sys.stderr, 'Command failed:', e) 
     126            printerr(_("Command failed:", e)) 
    121127            rv = 2 
    122128        if not self.interactive: 
    123129            return rv 
    124130 
    125131    def run(self): 
    126132        self.interactive = True 
    127         print """Welcome to trac-admin %(version)s 
     133        printout(_("""Welcome to trac-admin %(version)s 
    128134Interactive Trac administration console. 
    129135Copyright (c) 2003-2008 Edgewall Software 
    130136 
    131137Type:  '?' or 'help' for help on commands. 
    132         """ % {'version': TRAC_VERSION} 
     138        """, version=TRAC_VERSION)) 
    133139        self.cmdloop() 
    134140 
    135141    ## 
     
    155161                self.__env = Environment(self.envname) 
    156162            return self.__env 
    157163        except Exception, e: 
    158             console_print(sys.stderr, 'Failed to open environment.', e) 
     164            printerr(_("Failed to open environment.", e)) 
    159165            traceback.print_exc() 
    160166            sys.exit(1) 
    161167 
     
    282288                doc = getattr(self, "_help_" + arg[0]) 
    283289                self.print_doc(doc) 
    284290            except AttributeError: 
    285                 console_print(sys.stderr, "No documentation found for '%s'" %  
    286                               arg[0]) 
     291                printerr(_("No documentation found for '%(cmd)s'", cmd=arg[0])) 
    287292        else: 
    288             print 'trac-admin - The Trac Administration Console %s' \ 
    289                   % TRAC_VERSION 
     293            printout(_("trac-admin - The Trac Administration Console " 
     294                       "%(version)s", version=TRAC_VERSION)) 
    290295            if not self.interactive: 
    291296                print 
    292                 print "Usage: trac-admin </path/to/projenv> [command [subcommand] [option ...]]\n" 
    293                 print "Invoking trac-admin without command starts "\ 
    294                       "interactive mode." 
     297                printout(_("Usage: trac-admin </path/to/projenv> " 
     298                           "[command [subcommand] [option ...]]\n") 
     299                    ) 
     300                printout(_("Invoking trac-admin without command starts " 
     301                           "interactive mode.")) 
    295302            self.print_doc(self.all_docs()) 
    296303 
    297304 
     
    427434        rows.sort() 
    428435        print_table(rows, ['User', 'Action']) 
    429436        print 
    430         print 'Available actions:' 
     437        printout(_("Available actions:")) 
    431438        actions = self._permsys.get_actions() 
    432439        actions.sort() 
    433440        text = ', '.join(actions) 
    434         print wrap(text, initial_indent=' ', subsequent_indent=' ', 
    435                    linesep='\n') 
     441        printout(wrap(text, initial_indent=' ', subsequent_indent=' ',  
     442                      linesep='\n')) 
    436443        print 
    437444 
    438445    def _do_permission_add(self, user, action): 
    439446        if not self._permsys: 
    440447            self._permsys = PermissionSystem(self.env_open()) 
    441448        if not action.islower() and not action.isupper(): 
    442             print 'Group names must be in lower case and actions in upper case' 
     449            printout(_("Group names must be in lower case and actions in " 
     450                       "upper case")) 
    443451            return 
    444452        self._permsys.grant_permission(user, action) 
    445453 
     
    471479 
    472480    def get_initenv_args(self): 
    473481        returnvals = [] 
    474         print 'Creating a new Trac environment at %s' % self.envname 
    475         print 
    476         print 'Trac will first ask a few questions about your environment ' 
    477         print 'in order to initalize and prepare the project database.' 
    478         print 
    479         print " Please enter the name of your project." 
    480         print " This name will be used in page titles and descriptions." 
    481         print 
     482        printout(_("Creating a new Trac environment at %(envname)s", 
     483                   envname=self.envname)) 
     484        printout(_(""" 
     485Trac will first ask a few questions about your environment  
     486in order to initialize and prepare the project database. 
     487 
     488 Please enter the name of your project. 
     489 This name will be used in page titles and descriptions. 
     490""")) 
    482491        dp = 'My Project' 
    483         returnvals.append(raw_input('Project Name [%s]> ' % dp).strip() or dp) 
    484         print 
    485         print ' Please specify the connection string for the database to use.' 
    486         print ' By default, a local SQLite database is created in the environment ' 
    487         print ' directory. It is also possible to use an already existing ' 
    488         print ' PostgreSQL database (check the Trac documentation for the exact ' 
    489         print ' connection string syntax).' 
    490         print 
     492        returnvals.append(raw_input(_("Project Name [%(default)s]> ", 
     493                                      default=dp)).strip() or dp) 
     494        printout(_("""  
     495 Please specify the connection string for the database to use. 
     496 By default, a local SQLite database is created in the environment 
     497 directory. It is also possible to use an already existing 
     498 PostgreSQL database (check the Trac documentation for the exact 
     499 connection string syntax). 
     500 
     501""")) 
    491502        ddb = 'sqlite:db/trac.db' 
    492         prompt = 'Database connection string [%s]> ' % ddb 
     503        prompt = _("Database connection string [%(default)s]> ", default=ddb) 
    493504        returnvals.append(raw_input(prompt).strip() or ddb) 
    494         print 
    495         print ' Please specify the type of version control system,' 
    496         print ' By default, it will be svn.' 
    497         print 
    498         print ' If you don\'t want to use Trac with version control integration, ' 
    499         print ' choose the default here and don\'t specify a repository directory. ' 
    500         print ' in the next question.' 
    501         print  
     505        printout(_("""  
     506 Please specify the type of version control system, 
     507 By default, it will be svn. 
     508 
     509 If you don't want to use Trac with version control integration, 
     510 choose the default here and don\'t specify a repository directory. 
     511 in the next question. 
     512 
     513""")) 
    502514        drpt = 'svn' 
    503         prompt = 'Repository type [%s]> ' % drpt 
     515        prompt = _("Repository type [%(default)s]> ", default=drpt) 
    504516        returnvals.append(raw_input(prompt).strip() or drpt) 
    505         print 
    506         print ' Please specify the absolute path to the version control ' 
    507         print ' repository, or leave it blank to use Trac without a repository.' 
    508         print ' You can also set the repository location later.' 
    509         print  
    510         prompt = 'Path to repository [/path/to/repos]> ' 
     517        printout(_(""" 
     518 Please specify the absolute path to the version control 
     519 repository, or leave it blank to use Trac without a repository. 
     520 You can also set the repository location later. 
     521 
     522""")) 
     523        prompt = _("Path to repository [/path/to/repos]> ") 
    511524        returnvals.append(raw_input(prompt).strip()) 
    512525        print 
    513526        return returnvals 
    514527 
    515528    def do_initenv(self, line): 
    516529        def initenv_error(msg): 
    517             console_print(sys.stderr, "Initenv for '%s' failed.\n%s" %  
    518                           (self.envname, msg)) 
     530            printerr(_("Initenv for '%(env)s' failed.", env=self.envname), 
     531                     "\n", msg) 
    519532        if self.env_check(): 
    520533            initenv_error("Does an environment already exist?") 
    521534            return 2 
     
    543556            project_name, db_str, repository_type, repository_dir = arg[:4] 
    544557 
    545558        try: 
    546             print 'Creating and Initializing Project' 
     559            printout(_("Creating and Initializing Project")) 
    547560            options = [ 
    548561                ('trac', 'database', db_str), 
    549562                ('trac', 'repository_type', repository_type), 
     
    557570                                         options=options) 
    558571            except Exception, e: 
    559572                initenv_error('Failed to create environment.') 
    560                 console_print(sys.stderr, e) 
     573                printerr(e) 
    561574                traceback.print_exc() 
    562575                sys.exit(1) 
    563576 
    564577            # Add a few default wiki pages 
    565             print ' Installing default wiki pages' 
     578            printout(_(" Installing default wiki pages")) 
    566579            cnx = self.__env.get_db_cnx() 
    567580            cursor = cnx.cursor() 
    568581            pages_dir = pkg_resources.resource_filename('trac.wiki',  
     
    574587                try: 
    575588                    repos = self.__env.get_repository() 
    576589                    if repos: 
    577                         print ' Indexing repository' 
     590                        printout(_(" Indexing repository")) 
    578591                        repos.sync(self._resync_feedback) 
    579592                except TracError, e: 
    580                     console_print(sys.stderr, "\nWarning:\n") 
     593                    printerr("\n", _("Warning:"), "\n") 
    581594                    if repository_type == "svn": 
    582                         console_print(sys.stderr,  
    583                                       "You should install the SVN bindings") 
     595                        printerr(_("You should install the SVN bindings")) 
    584596                    else: 
    585                         console_print(sys.stderr,  
    586                                       "Repository type %s not supported" % 
    587                                       repository_type) 
     597                        printerr(_("Repository type %(type)s not supported",  
     598                                   type=repository_type)) 
    588599        except Exception, e: 
    589600            initenv_error(to_unicode(e)) 
    590601            traceback.print_exc() 
    591602            return 2 
    592603 
    593         print """ 
     604        printout(_(""" 
    594605--------------------------------------------------------------------- 
    595606Project environment for '%(project_name)s' created. 
    596607 
     
    614625  http://trac.edgewall.org/ 
    615626 
    616627Congratulations! 
    617 """ % dict(project_name=project_name, project_path=self.envname, 
     628""", project_name=project_name, project_path=self.envname, 
    618629           project_dir=os.path.basename(self.envname), 
    619            config_path=os.path.join(self.envname, 'conf', 'trac.ini')) 
     630           config_path=os.path.join(self.envname, 'conf', 'trac.ini'))) 
    620631 
    621632    _help_resync = [('resync', 'Re-synchronize trac with the repository'), 
    622633                    ('resync <rev>', 'Re-synchronize only the given <rev>')] 
     
    633644            rev = argv[0] 
    634645            if rev: 
    635646                env.get_repository().sync_changeset(rev) 
    636                 print '%s resynced.' % rev 
     647                printout(_("%(rev)s resynced.", rev=rev)) 
    637648                return 
    638649        from trac.versioncontrol.cache import CACHE_METADATA_KEYS 
    639         print 'Resyncing repository history... ' 
     650        printout(_("Resyncing repository history... ")) 
    640651        cnx = self.db_open() 
    641652        cursor = cnx.cursor() 
    642653        cursor.execute("DELETE FROM revision") 
     
    649660        repos = env.get_repository().sync(self._resync_feedback) 
    650661        cursor.execute("SELECT count(rev) FROM revision") 
    651662        for cnt, in cursor: 
    652             print cnt, 'revisions cached.', 
    653         print 'Done.' 
     663            printout(ngettext("%(num)s revision cached.", 
     664                              "%(num)s revisions cached.", cnt, num=cnt)) 
     665        printout(_("Done.")) 
    654666 
    655667    ## Wiki 
    656668    _help_wiki = [('wiki list', 'List wiki pages'), 
     
    749761                             params=(title,)) 
    750762        old = list(rows) 
    751763        if old and title in create_only: 
    752             console_print(sys.stdout, '  %s already exists.' % title) 
     764            printout('  %s already exists.' % title) 
    753765            return False 
    754766        if old and data == old[0][0]: 
    755             console_print(sys.stdout, '  %s already up to date.' % title) 
     767            printout('  %s already up to date.' % title) 
    756768            return False 
    757769        f.close() 
    758770 
     
    768780                             "ORDER BY version DESC LIMIT 1", params=[page]) 
    769781        text = data.next()[0] 
    770782        if not filename: 
    771             print text 
     783            printout(text) 
    772784        else: 
    773785            if os.path.isfile(filename): 
    774786                raise Exception("File '%s' exists" % filename) 
     
    785797                raise TracError("%s is not a directory" % dir) 
    786798        for p in pages: 
    787799            dst = os.path.join(dir, unicode_quote(p, '')) 
    788             console_print(sys.stdout, " %s => %s" % (p, dst)) 
     800            printout(_(" %(src)s => %(dst)s", src=p, dst=dst)) 
    789801            self._do_wiki_export(p, dst) 
    790802 
    791803    def _do_wiki_load(self, dir, cursor=None, ignore=[], create_only=[]): 
     
    797809            page = unicode_unquote(page.encode('utf-8')) 
    798810            if os.path.isfile(filename): 
    799811                if self._do_wiki_import(filename, page, cursor, create_only): 
    800                     print (" %s imported from %s" % 
    801                            (filename, page)).encode(cons_charset) 
     812                    printout(_(" %(page)s imported from %(filename)s", 
     813                               filename=filename, page=page)) 
    802814 
    803815    ## Ticket 
    804816    _help_ticket = [('ticket remove <number>', 'Remove ticket')] 
     
    819831            try: 
    820832                number = int(arg[1]) 
    821833            except ValueError: 
    822                 console_print(sys.stderr, "<number> must be a number") 
     834                printerr(_("<number> must be a number")) 
    823835                return 
    824836            self._do_ticket_remove(number) 
    825837        else:     
    826838            self.do_help ('ticket') 
    827839 
    828     def _do_ticket_remove(self, number): 
    829         ticket = Ticket(self.env_open(), number) 
     840    def _do_ticket_remove(self, num): 
     841        ticket = Ticket(self.env_open(), num) 
    830842        ticket.delete() 
    831         print "Ticket %d and all associated data removed." % number 
     843        printout(_("Ticket %(num)s and all associated data removed.", num=num)) 
    832844 
    833845 
    834846    ## (Ticket) Type 
     
    11211133        self.db_open() 
    11221134 
    11231135        if not self.__env.needs_upgrade(): 
    1124             print "Database is up to date, no upgrade necessary." 
     1136            printout(_("Database is up to date, no upgrade necessary.")) 
    11251137            return 
    11261138 
    11271139        try: 
     
    11331145                                "upgrade without doing a backup." % msg) 
    11341146            else: 
    11351147                raise 
    1136         print 'Upgrade done.' 
     1148        printout(_("Upgrade done.")) 
    11371149 
    11381150    _help_hotcopy = [('hotcopy <backupdir>', 
    11391151                      'Make a hot backup copy of an environment')] 
     
    11551167        cursor.execute("UPDATE system SET name=NULL WHERE name IS NULL") 
    11561168 
    11571169        try: 
    1158             print 'Hotcopying %s to %s ...' % (self.__env.path, dest), 
     1170            printout(_('Hotcopying %(src)s to %(dst)s ...',  
     1171                       src=self.__env.path, dst=dest)) 
    11591172            db_str = self.__env.config.get('trac', 'database') 
    11601173            prefix, db_path = db_str.split(':', 1) 
    11611174            if prefix == 'sqlite': 
     
    11691182            # Unlock database 
    11701183            cnx.rollback() 
    11711184 
    1172         print 'Hotcopy done.' 
     1185        printout(_("Hotcopy done.")) 
    11731186 
    11741187    _help_deploy = [('deploy <directory>', 
    11751188                     'Extract static resources from Trac and all plugins.')] 
     
    11901203        os.makedirs(target) 
    11911204        os.makedirs(chrome_target) 
    11921205        from trac.web.chrome import Chrome 
    1193         print 'Copying resources from:' 
     1206        printout(_("Copying resources from:")) 
    11941207        for provider in Chrome(self.env_open()).template_providers: 
    11951208            paths = list(provider.get_htdocs_dirs()) 
    11961209            if not len(paths): 
    11971210                continue 
    1198             print '  %s.%s' % (provider.__module__, provider.__class__.__name__) 
     1211            printout('  %s.%s' % (provider.__module__,  
     1212                                  provider.__class__.__name__)) 
    11991213            for key, root in paths: 
    12001214                source = os.path.normpath(root) 
    1201                 print '   ', source 
     1215                printout('   ', source) 
    12021216                if os.path.exists(source): 
    12031217                    dest = os.path.join(chrome_target, key) 
    12041218                    copytree(source, dest) 
    12051219         
    12061220        # Create and copy scripts 
    12071221        os.makedirs(script_target) 
    1208         print 'Creating scripts.' 
     1222        printout(_("Creating scripts.")) 
    12091223        data = {'env': self.env_open(), 'executable': sys.executable} 
    12101224        for script in ('cgi', 'fcgi', 'wsgi'): 
    12111225            dest = os.path.join(script_target, 'trac.'+script) 
     
    12601274        if args[0] in ('-h', '--help', 'help'): 
    12611275            return admin.onecmd('help') 
    12621276        elif args[0] in ('-v','--version'): 
    1263             print '%s %s' % (os.path.basename(sys.argv[0]), TRAC_VERSION) 
     1277            printout(os.path.basename(sys.argv[0]), TRAC_VERSION) 
    12641278        else: 
    12651279            env_path = os.path.abspath(args[0]) 
    12661280            try: 
    12671281                unicode(env_path, 'ascii') 
    12681282            except UnicodeDecodeError: 
    1269                 console_print(sys.stderr, _("non-ascii environment path " 
    1270                                             "'%(path)s' not supported.", 
    1271                                             path=env_path)) 
     1283                printerr(_("non-ascii environment path '%(path)s' not " 
     1284                           "supported.", path=env_path)) 
    12721285                sys.exit(2) 
    12731286            admin.env_set(env_path) 
    12741287            if len(args) > 1: 
  • trac/util/text.py

     
    112112 
    113113def console_print(out, *args): 
    114114    cons_charset = getattr(out, 'encoding', None) or 'utf-8' 
    115     out.write(' '.join([to_unicode(a).encode(cons_charset) for a in args])+ 
    116               '\n') 
     115    out.write(' '.join([to_unicode(a).encode(cons_charset, 'replace')  
     116                        for a in args])+ '\n') 
    117117 
    118118# -- Plain text formatting 
    119119