Exemple #1
0
    def _do_hotcopy(self, dest, no_db=None):
        if no_db not in (None, '--no-database'):
            raise AdminCommandError(_("Invalid argument '%(arg)s'", arg=no_db),
                                    show_usage=True)

        if os.path.exists(dest):
            raise TracError(
                _("hotcopy can't overwrite existing '%(dest)s'",
                  dest=path_to_unicode(dest)))

        printout(
            _("Hotcopying %(src)s to %(dst)s ...",
              src=path_to_unicode(self.env.path),
              dst=path_to_unicode(dest)))
        db_str = self.env.config.get('trac', 'database')
        prefix, db_path = db_str.split(':', 1)
        skip = []

        if prefix == 'sqlite':
            db_path = os.path.join(self.env.path, os.path.normpath(db_path))
            # don't copy the journal (also, this would fail on Windows)
            skip = [
                db_path + '-journal', db_path + '-stmtjrnl', db_path + '-shm',
                db_path + '-wal'
            ]
            if no_db:
                skip.append(db_path)

        # Bogus statement to lock the database while copying files
        with self.env.db_transaction as db:
            db("UPDATE " + db.quote('system') +
               " SET name=NULL WHERE name IS NULL")
            try:
                copytree(self.env.path, dest, symlinks=1, skip=skip)
            except shutil.Error as e:
                retval = 1
                printerr(
                    _("The following errors happened while copying "
                      "the environment:"))
                for src, dst, err in e.args[0]:
                    if src in err:
                        printerr('  %s' % err)
                    else:
                        printerr("  %s: '%s'" % (err, path_to_unicode(src)))
            else:
                retval = 0

            # db backup for non-sqlite
            if prefix != 'sqlite' and not no_db:
                printout(_("Backing up database ..."))
                sql_backup = os.path.join(dest, 'db',
                                          '%s-db-backup.sql' % prefix)
                self.env.backup(sql_backup)

        printout(_("Hotcopy done."))
        return retval
Exemple #2
0
 def _do_set(self, attr, sid, val):
     if attr not in ('name', 'email'):
         raise AdminCommandError(
             _("Invalid attribute '%(attr)s'", attr=attr))
     sid, authenticated = self._split_sid(sid)
     with self.env.db_transaction as db:
         if not db(
                 """SELECT sid FROM session
                      WHERE sid=%s AND authenticated=%s""",
             (sid, authenticated)):
             raise AdminCommandError(
                 _("Session '%(sid)s' not found", sid=sid))
         db(
             """
             DELETE FROM session_attribute
             WHERE sid=%s AND authenticated=%s AND name=%s
             """, (sid, authenticated, attr))
         db("INSERT INTO session_attribute VALUES (%s, %s, %s, %s)",
            (sid, authenticated, attr, val))
Exemple #3
0
    def _do_deploy(self, dest):
        target = os.path.normpath(dest)
        chrome_target = os.path.join(target, 'htdocs')
        script_target = os.path.join(target, 'cgi-bin')

        # Check source and destination to avoid recursively copying files
        for provider in Chrome(self.env).template_providers:
            paths = list(provider.get_htdocs_dirs() or [])
            if not paths:
                continue
            for key, root in paths:
                if not root:
                    continue
                source = os.path.normpath(root)
                dest = os.path.join(chrome_target, key)
                if os.path.exists(source) and is_path_below(dest, source):
                    raise AdminCommandError(
                        _(
                            "Resources cannot be deployed to a target "
                            "directory that is equal to or below the source "
                            "directory '%(source)s'.\n\nPlease choose a "
                            "different target directory and try again.",
                            source=source))

        # Copy static content
        makedirs(target, overwrite=True)
        makedirs(chrome_target, overwrite=True)
        printout(_("Copying resources from:"))
        for provider in Chrome(self.env).template_providers:
            paths = list(provider.get_htdocs_dirs() or [])
            if not paths:
                continue
            printout('  %s.%s' %
                     (provider.__module__, provider.__class__.__name__))
            for key, root in paths:
                if not root:
                    continue
                source = os.path.normpath(root)
                printout('   ', source)
                if os.path.exists(source):
                    dest = os.path.join(chrome_target, key)
                    copytree(source, dest, overwrite=True)

        # Create and copy scripts
        makedirs(script_target, overwrite=True)
        printout(_("Creating scripts."))
        data = {'env': self.env, 'executable': sys.executable, 'repr': repr}
        for script in ('cgi', 'fcgi', 'wsgi'):
            dest = os.path.join(script_target, 'trac.' + script)
            chrome = Chrome(self.env)
            template = chrome.load_template('deploy_trac.' + script, text=True)
            text = chrome.render_template_string(template, data, text=True)

            with open(dest, 'w') as out:
                out.write(text.encode('utf-8'))
Exemple #4
0
 def default(self, line):
     try:
         if not self.__env:
             self._init_env()
         if self.needs_upgrade is None:
             self.needs_upgrade = self.__env.needs_upgrade()
     except TracError as e:
         raise AdminCommandError(to_unicode(e))
     except Exception as e:
         raise AdminCommandError(exception_to_unicode(e))
     args = self.arg_tokenize(line)
     if args[0] == 'upgrade':
         self.needs_upgrade = None
     elif self.needs_upgrade:
         raise TracError(
             _(
                 'The Trac Environment needs to be upgraded. '
                 'Run:\n\n  trac-admin "%(path)s" upgrade',
                 path=self.envname))
     return self.cmd_mgr.execute_command(*args)
Exemple #5
0
 def _do_remove_comment(self, ticket_number, comment_number):
     ticket_number = as_int(ticket_number, None)
     if ticket_number is None:
         raise AdminCommandError(_('<ticket#> must be a number'))
     comment_number = as_int(comment_number, None)
     if comment_number is None:
         raise AdminCommandError(_('<comment#> must be a number'))
     with self.env.db_transaction:
         ticket = model.Ticket(self.env, ticket_number)
         change = ticket.get_change(comment_number)
         if not change:
             raise AdminCommandError(
                 _("Comment %(num)s not found", num=comment_number))
         ticket.delete_change(comment_number)
     printout(
         _(
             "The ticket comment %(num)s on ticket #%(id)s has been "
             "deleted.",
             num=comment_number,
             id=ticket_number))
Exemple #6
0
 def _do_set(self, attr, sid, val):
     if attr not in ('name', 'email', 'default_handler'):
         raise AdminCommandError(_("Invalid attribute '%(attr)s'",
                                   attr=attr))
     if attr == 'default_handler':
         if val and val not in self._valid_default_handlers:
             raise AdminCommandError(_("Invalid default_handler '%(val)s'",
                                       val=val))
     sid, authenticated = self._split_sid(sid)
     with self.env.db_transaction as db:
         if not db("""SELECT sid FROM session
                      WHERE sid=%s AND authenticated=%s""",
                      (sid, authenticated)):
             raise AdminCommandError(_("Session '%(sid)s' not found",
                                       sid=sid))
         db("""
             DELETE FROM session_attribute
             WHERE sid=%s AND authenticated=%s AND name=%s
             """, (sid, authenticated, attr))
         db("INSERT INTO session_attribute VALUES (%s, %s, %s, %s)",
            (sid, authenticated, attr, val))
     self.env.invalidate_known_users_cache()
Exemple #7
0
 def _do_add(self, sid, name=None, email=None):
     sid, authenticated = self._split_sid(sid)
     with self.env.db_transaction as db:
         try:
             db("INSERT INTO session VALUES (%s, %s, %s)",
                (sid, authenticated, int(time.time())))
         except Exception:
             raise AdminCommandError(_("Session '%(sid)s' already exists",
                                       sid=sid))
         if name is not None:
             db("INSERT INTO session_attribute VALUES (%s,%s,'name',%s)",
                 (sid, authenticated, name))
         if email is not None:
             db("INSERT INTO session_attribute VALUES (%s,%s,'email',%s)",
                 (sid, authenticated, email))
Exemple #8
0
 def set_attr(db):
     cursor = db.cursor()
     cursor.execute("""
         SELECT sid FROM session WHERE sid=%s AND authenticated=%s
         """, (sid, authenticated))
     if not cursor.fetchone():
         raise AdminCommandError(_("Session '%(sid)s' not found",
                                   sid=sid))
     cursor.execute("""
         DELETE FROM session_attribute
         WHERE sid=%s AND authenticated=%s AND name=%s
         """, (sid, authenticated, attr))
     cursor.execute("""
         INSERT INTO session_attribute VALUES (%s, %s, %s, %s)
         """, (sid, authenticated, attr, val))
Exemple #9
0
 def _do_order(self, name, up_down):
     if up_down not in ('up', 'down'):
         raise AdminCommandError(_("Invalid up/down value: %(value)s",
                                   value=up_down))
     direction = -1 if up_down == 'up' else 1
     enum1 = self._enum_cls(self.env, name)
     enum1.value = int(float(enum1.value) + direction)
     for enum2 in self._enum_cls.select(self.env):
         if int(float(enum2.value)) == enum1.value:
             enum2.value = int(float(enum2.value) - direction)
             break
     else:
         return
     with self.env.db_transaction:
         enum1.update()
         enum2.update()
Exemple #10
0
 def add_session(db):
     cursor = db.cursor()
     try:
         cursor.execute("INSERT INTO session VALUES (%s, %s, %s)",
                        (sid, authenticated, int(time.time())))
     except Exception:
         raise AdminCommandError(_("Session '%(sid)s' already exists",
                                   sid=sid))
     if name is not None:
         cursor.execute("""
             INSERT INTO session_attribute VALUES (%s, %s, 'name', %s)
             """, (sid, authenticated, name))
     if email is not None:
         cursor.execute("""
             INSERT INTO session_attribute VALUES (%s, %s, 'email', %s)
             """, (sid, authenticated, email))
Exemple #11
0
 def _do_set(self, attr, sid, val):
     if attr not in ('name', 'email'):
         raise AdminCommandError(_("Invalid attribute '%(attr)s'",
                                   attr=attr))
     sid, authenticated = self._split_sid(sid)
     @self.env.with_transaction()
     def set_attr(db):
         cursor = db.cursor()
         cursor.execute("""
             SELECT sid FROM session WHERE sid=%s AND authenticated=%s
             """, (sid, authenticated))
         if not cursor.fetchone():
             raise AdminCommandError(_("Session '%(sid)s' not found",
                                       sid=sid))
         cursor.execute("""
             DELETE FROM session_attribute
             WHERE sid=%s AND authenticated=%s AND name=%s
             """, (sid, authenticated, attr))
         cursor.execute("""
             INSERT INTO session_attribute VALUES (%s, %s, %s, %s)
             """, (sid, authenticated, attr, val))
Exemple #12
0
    def _do_upgrade(self, no_backup=None):
        if no_backup not in (None, '-b', '--no-backup'):
            raise AdminCommandError(_("Invalid arguments"), show_usage=True)

        if not self.env.needs_upgrade():
            printout(_("Database is up to date, no upgrade necessary."))
            return

        try:
            self.env.upgrade(backup=no_backup is None)
        except BackupError as e:
            printerr(_("The pre-upgrade backup failed.\nUse '--no-backup' to "
                       "upgrade without doing a backup.\n"))
            raise e.args[0]
        except Exception:
            printerr(_("The upgrade failed. Please fix the issue and try "
                       "again.\n"))
            raise

        printout(_('Upgrade done.\n\n'
                   'You may want to upgrade the Trac documentation now by '
                   'running:\n\n  trac-admin "%(path)s" wiki upgrade',
                   path=path_to_unicode(self.env.path)))
Exemple #13
0
 def _do_product_admin(self, prefix, *args):
     mgr = self.product_admincmd_mgr(prefix)
     if args and args[0] in self.GLOBAL_COMMANDS:
         raise AdminCommandError('%s command not supported for products' %
                                 (args[0],))
     if args and args[0] == 'help':
         help_args = args[1:]
         if help_args:
             doc = mgr.get_command_help(list(help_args))
             if doc:
                 TracAdmin.print_doc(doc)
             else:
                 printerr(_("No documentation found for '%(cmd)s'."
                            " Use 'help' to see the list of commands.",
                            cmd=' '.join(help_args)))
                 cmds = mgr.get_similar_commands(help_args[0])
                 if cmds:
                     printout('')
                     printout(ngettext("Did you mean this?",
                                       "Did you mean one of these?",
                                       len(cmds)))
                     for cmd in cmds:
                         printout('    ' + cmd)
         else:
             printout(_("trac-admin - The Trac Administration Console "
                        "%(version)s", version=TRAC_VERSION))
             env = mgr.env
             TracAdmin.print_doc(TracAdmin.all_docs(env), short=True)
     else:
         try:
             mgr.execute_command(*args)
         except AdminCommandError, e:
             printerr(_("Error: %(msg)s", msg=to_unicode(e)))
             if e.show_usage:
                 print
                 self._do_product_admin(prefix, 'help', *args[:2])
         except:
Exemple #14
0
 def _do_product_remove(self, prefix):
     raise AdminCommandError(
         _("Command 'product remove' not supported yet"))
Exemple #15
0
 def load_product(self, prefix):
     products = Product.select(self.env, where={'prefix': prefix})
     if not products:
         raise AdminCommandError('Unknown product %s' % (prefix, ))
     return products[0]