Changeset - c1516b35f91d
[Not reviewed]
rhodecode/controllers/admin/ldap_settings.py
Show inline comments
 
@@ -120,13 +120,12 @@ class LdapSettingsController(BaseControl
 
            h.flash(_('Unable to activate ldap. The "python-ldap" library '
 
                      'is missing.'), category='warning')
 

	
 
        except formencode.Invalid, errors:
 
            e = errors.error_dict or {}
 

	
 

	
 
            return htmlfill.render(
 
                render('admin/ldap/ldap.html'),
 
                defaults=errors.value,
 
                errors=e,
 
                prefix_error=False,
 
                encoding="UTF-8")
rhodecode/controllers/files.py
Show inline comments
 
@@ -245,12 +245,14 @@ class FilesController(BaseRepoController
 
                h.flash(_('No changes'),
 
                    category='warning')
 
                return redirect(url('changeset_home', repo_name=c.repo_name,
 
                                    revision='tip'))
 

	
 
            try:
 
                # decoding here will force that we have proper encoded values
 
                # in any other case this will throw exceptions and deny commit
 
                content = content.encode('utf8')
 
                message = message.encode('utf8')
 
                path = f_path.encode('utf8')
 
                author = self.rhodecode_user.full_contact.encode('utf8')
 
                m = IMC(c.rhodecode_repo)
 
                m.change(FileNode(path, content))
 
@@ -260,13 +262,12 @@ class FilesController(BaseRepoController
 
                h.flash(_('Successfully committed to %s' % f_path),
 
                        category='success')
 

	
 
            except Exception, e:
 
                log.error(traceback.format_exc())
 
                h.flash(_('Error occurred during commit'), category='error')
 
                raise
 
            return redirect(url('changeset_home',
 
                                repo_name=c.repo_name, revision='tip'))
 

	
 
        return render('files/files_edit.html')
 

	
 
    @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
rhodecode/lib/__init__.py
Show inline comments
 
@@ -21,13 +21,12 @@
 
# 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, see <http://www.gnu.org/licenses/>.
 

	
 

	
 

	
 
def __get_lem():
 
    from pygments import lexers
 
    from string import lower
 
    from collections import defaultdict
 

	
 
    d = defaultdict(lambda: [])
 
@@ -57,18 +56,19 @@ def __get_lem():
 
    return dict(d)
 

	
 
# language map is also used by whoosh indexer, which for those specified
 
# extensions will index it's content
 
LANGUAGES_EXTENSIONS_MAP = __get_lem()
 

	
 
#Additional mappings that are not present in the pygments lexers
 
# Additional mappings that are not present in the pygments lexers
 
# NOTE: that this will overide any mappings in LANGUAGES_EXTENSIONS_MAP
 
ADDITIONAL_MAPPINGS = {'xaml': 'XAML'}
 

	
 
LANGUAGES_EXTENSIONS_MAP.update(ADDITIONAL_MAPPINGS)
 

	
 

	
 
def str2bool(_str):
 
    """
 
    returs True/False value from given string, it tries to translate the
 
    string into boolean
 

	
 
    :param _str: string value to translate into boolean
 
@@ -79,12 +79,13 @@ def str2bool(_str):
 
        return False
 
    if _str in (True, False):
 
        return _str
 
    _str = str(_str).strip().lower()
 
    return _str in ('t', 'true', 'y', 'yes', 'on', '1')
 

	
 

	
 
def convert_line_endings(temp, mode):
 
    from string import replace
 
    #modes:  0 - Unix, 1 - Mac, 2 - DOS
 
    if mode == 0:
 
            temp = replace(temp, '\r\n', '\n')
 
            temp = replace(temp, '\r', '\n')
 
@@ -95,21 +96,31 @@ def convert_line_endings(temp, mode):
 
            import re
 
            temp = re.sub("\r(?!\n)|(?<!\r)\n", "\r\n", temp)
 
    return temp
 

	
 

	
 
def detect_mode(line, default):
 
    """
 
    Detects line break for given line, if line break couldn't be found
 
    given default value is returned
 

	
 
    :param line: str line
 
    :param default: default
 
    :rtype: int
 
    :return: value of line end on of 0 - Unix, 1 - Mac, 2 - DOS
 
    """
 
    if line.endswith('\r\n'):
 
        return 2
 
    elif line.endswith('\n'):
 
        return 0
 
    elif line.endswith('\r'):
 
        return 1
 
    else:
 
        return default
 

	
 

	
 
def generate_api_key(username, salt=None):
 
    """
 
    Generates unique API key for given username,if salt is not given
 
    it'll be generated from some random string
 

	
 
    :param username: username as string
 
@@ -148,19 +159,17 @@ def safe_unicode(_str, from_encoding='ut
 

	
 

	
 
def engine_from_config(configuration, prefix='sqlalchemy.', **kwargs):
 
    """
 
    Custom engine_from_config functions that makes sure we use NullPool for
 
    file based sqlite databases. This prevents errors on sqlite.
 
    
 

	
 
    """
 
    from sqlalchemy import engine_from_config as efc
 
    from sqlalchemy.pool import NullPool
 

	
 
    url = configuration[prefix + 'url']
 

	
 
    if url.startswith('sqlite'):
 
        kwargs.update({'poolclass':NullPool})
 
        kwargs.update({'poolclass': NullPool})
 

	
 
    return efc(configuration, prefix, **kwargs)
 

	
 

	
rhodecode/lib/app_globals.py
Show inline comments
 
"""The application's Globals object"""
 

	
 
from beaker.cache import CacheManager
 
from beaker.util import parse_cache_config_options
 

	
 

	
 
class Globals(object):
 
    """Globals acts as a container for objects available throughout the
 
    life of the application
 

	
 
    """
 

	
rhodecode/lib/auth.py
Show inline comments
 
@@ -200,13 +200,13 @@ def authenticate(username, password):
 
            try:
 
                aldap = AuthLdap(**kwargs)
 
                (user_dn, ldap_attrs) = aldap.authenticate_ldap(username,
 
                                                                password)
 
                log.debug('Got ldap DN response %s', user_dn)
 

	
 
                get_ldap_attr = lambda k:ldap_attrs.get(ldap_settings\
 
                get_ldap_attr = lambda k: ldap_attrs.get(ldap_settings\
 
                                                           .get(k), [''])[0]
 

	
 
                user_attrs = {
 
                    'name': get_ldap_attr('ldap_attr_firstname'),
 
                    'lastname': get_ldap_attr('ldap_attr_lastname'),
 
                    'email': get_ldap_attr('ldap_attr_email'),
rhodecode/lib/backup_manager.py
Show inline comments
 
#!/usr/bin/env python
 
# encoding: utf-8
 
# mercurial repository backup manager
 
# Copyright (C) 2009-2011 Marcin Kuzminski <marcin@python-works.com>
 
# -*- coding: utf-8 -*-
 
"""
 
    rhodecode.lib.backup_manager
 
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 

	
 
    Mercurial repositories backup manager, it allows to backups all 
 
    repositories and send it to backup server using RSA key via ssh.
 

	
 
    :created_on: Feb 28, 2010
 
    :copyright: (c) 2010 by marcink.
 
    :license: LICENSE_NAME, see LICENSE_FILE for more details.
 
"""
 
# 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 3 of the License, or
 
# (at your option) any later version.
 
#
 
# This program is distributed in the hope that it will be useful,
 
@@ -13,28 +20,24 @@
 
# 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, see <http://www.gnu.org/licenses/>.
 

	
 
"""
 
Created on Feb 28, 2010
 
Mercurial repositories backup manager
 
@author: marcink
 
"""
 

	
 
import os
 
import sys
 

	
 
import logging
 
import tarfile
 
import os
 
import datetime
 
import sys
 
import subprocess
 

	
 
logging.basicConfig(level=logging.DEBUG,
 
                    format="%(asctime)s %(levelname)-5.5s %(message)s")
 

	
 

	
 
class BackupManager(object):
 
    def __init__(self, repos_location, rsa_key, backup_server):
 
        today = datetime.datetime.now().weekday() + 1
 
        self.backup_file_name = "mercurial_repos.%s.tar.gz" % today
 

	
 
        self.id_rsa_path = self.get_id_rsa(rsa_key)
 
@@ -43,13 +46,12 @@ class BackupManager(object):
 

	
 
        self.backup_file_path = '/tmp'
 

	
 
        logging.info('starting backup for %s', self.repos_path)
 
        logging.info('backup target %s', self.backup_file_path)
 

	
 

	
 
    def get_id_rsa(self, rsa_key):
 
        if not os.path.isfile(rsa_key):
 
            logging.error('Could not load id_rsa key file in %s', rsa_key)
 
            sys.exit()
 
        return rsa_key
 

	
 
@@ -66,35 +68,30 @@ class BackupManager(object):
 
        for dir_name in os.listdir(self.repos_path):
 
            logging.info('backing up %s', dir_name)
 
            tar.add(os.path.join(self.repos_path, dir_name), dir_name)
 
        tar.close()
 
        logging.info('finished backup of mercurial repositories')
 

	
 

	
 

	
 
    def transfer_files(self):
 
        params = {
 
                  'id_rsa_key': self.id_rsa_path,
 
                  'backup_file':os.path.join(self.backup_file_path,
 
                  'backup_file': os.path.join(self.backup_file_path,
 
                                             self.backup_file_name),
 
                  'backup_server':self.backup_server
 
                  'backup_server': self.backup_server
 
                  }
 
        cmd = ['scp', '-l', '40000', '-i', '%(id_rsa_key)s' % params,
 
               '%(backup_file)s' % params,
 
               '%(backup_server)s' % params]
 

	
 
        subprocess.call(cmd)
 
        logging.info('Transfered file %s to %s', self.backup_file_name, cmd[4])
 

	
 

	
 
    def rm_file(self):
 
        logging.info('Removing file %s', self.backup_file_name)
 
        os.remove(os.path.join(self.backup_file_path, self.backup_file_name))
 

	
 

	
 

	
 
if __name__ == "__main__":
 

	
 
    repo_location = '/home/repo_path'
 
    backup_server = 'root@192.168.1.100:/backups/mercurial'
 
    rsa_key = '/home/id_rsa'
 

	
rhodecode/lib/base.py
Show inline comments
 
@@ -12,12 +12,13 @@ from rhodecode import __version__
 
from rhodecode.lib.auth import AuthUser
 
from rhodecode.lib.utils import get_repo_slug
 
from rhodecode.model import meta
 
from rhodecode.model.scm import ScmModel
 
from rhodecode import BACKENDS
 

	
 

	
 
class BaseController(WSGIController):
 

	
 
    def __before__(self):
 
        c.rhodecode_version = __version__
 
        c.rhodecode_name = config.get('rhodecode_title')
 
        c.ga_code = config.get('rhodecode_ga_code')
 
@@ -33,13 +34,13 @@ class BaseController(WSGIController):
 
    def __call__(self, environ, start_response):
 
        """Invoke the Controller"""
 
        # WSGIController.__call__ dispatches to the Controller method
 
        # the request is routed to. This routing information is
 
        # available in environ['pylons.routes_dict']
 
        try:
 
            #putting this here makes sure that we update permissions every time
 
            # putting this here makes sure that we update permissions each time
 
            api_key = request.GET.get('api_key')
 
            user_id = getattr(session.get('rhodecode_user'), 'user_id', None)
 
            self.rhodecode_user = c.rhodecode_user = AuthUser(user_id, api_key)
 
            self.rhodecode_user.set_authenticated(
 
                                        getattr(session.get('rhodecode_user'),
 
                                       'is_authenticated', False))
 
@@ -63,17 +64,18 @@ class BaseRepoController(BaseController)
 
        super(BaseRepoController, self).__before__()
 
        if c.repo_name:
 

	
 
            r, dbrepo = self.scm_model.get(c.repo_name, retval='repo')
 

	
 
            if r is not None:
 
                c.repository_followers = self.scm_model.get_followers(c.repo_name)
 
                c.repository_followers = \
 
                    self.scm_model.get_followers(c.repo_name)
 
                c.repository_forks = self.scm_model.get_forks(c.repo_name)
 
            else:
 
                c.repository_followers = 0
 
                c.repository_forks = 0
 

	
 
            # Since RhodeCode uses heavy memory caching we make a deepcopy
 
            # of object taken from cache. This way we lose reference to cached
 
            # instance in memory and keep it relatively small even for 
 
            # instance in memory and keep it relatively small even for
 
            # very large number of changesets
 
            c.rhodecode_repo = copy.copy(r)
rhodecode/lib/colored_formatter.py
Show inline comments
 
@@ -6,27 +6,29 @@ BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA
 
# Sequences
 
RESET_SEQ = "\033[0m"
 
COLOR_SEQ = "\033[1;%dm"
 
BOLD_SEQ = "\033[1m"
 

	
 
COLORS = {
 
    'CRITICAL': MAGENTA, # level 50
 
    'ERROR': RED, # level 40
 
    'WARNING': CYAN, # level 30
 
    'INFO': GREEN, # level 20
 
    'DEBUG': BLUE, # level 10
 
    'SQL' : YELLOW
 
    'CRITICAL': MAGENTA,
 
    'ERROR': RED,
 
    'WARNING': CYAN,
 
    'INFO': GREEN,
 
    'DEBUG': BLUE,
 
    'SQL': YELLOW
 
}
 

	
 

	
 
def one_space_trim(s):
 
    if s.find("  ") == -1:
 
        return s
 
    else:
 
        s = s.replace('  ', ' ')
 
        return one_space_trim(s)
 

	
 

	
 
def format_sql(sql):
 
    sql = sql.replace('\n', '')
 
    sql = one_space_trim(sql)
 
    sql = sql\
 
        .replace(',', ',\n\t')\
 
        .replace('SELECT', '\n\tSELECT \n\t')\
 
@@ -40,12 +42,13 @@ def format_sql(sql):
 
        .replace('LEFT', '\n\tLEFT')\
 
        .replace('INNER', '\n\tINNER')\
 
        .replace('INSERT', '\n\tINSERT')\
 
        .replace('DELETE', '\n\tDELETE')
 
    return sql
 

	
 

	
 
class ColorFormatter(logging.Formatter):
 

	
 
    def __init__(self, *args, **kwargs):
 
        # can't do super(...) here because Formatter is an old school class
 
        logging.Formatter.__init__(self, *args, **kwargs)
 

	
rhodecode/lib/exceptions.py
Show inline comments
 
#!/usr/bin/env python
 
# encoding: utf-8
 
# Custom Exceptions modules
 
# Copyright (C) 2009-2011 Marcin Kuzminski <marcin@python-works.com>
 
#
 
# -*- coding: utf-8 -*-
 
"""
 
    rhodecode.lib.exceptions
 
    ~~~~~~~~~~~~~~~~~~~~~~~~
 

	
 
    Set of custom exceptions used in RhodeCode
 

	
 
    :created_on: Nov 17, 2010
 
    :copyright: (c) 2010 by marcink.
 
    :license: LICENSE_NAME, see LICENSE_FILE for more details.
 
"""
 
# 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 3 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, see <http://www.gnu.org/licenses/>.
 
"""
 
Created on Nov 17, 2010
 
Custom Exceptions modules
 
@author: marcink
 
"""
 

	
 

	
 
class LdapUsernameError(Exception):
 
    pass
 

	
 

	
 
class LdapPasswordError(Exception):
 
    pass
 

	
 

	
 
class LdapUsernameError(Exception):pass
 
class LdapPasswordError(Exception):pass
 
class LdapConnectionError(Exception):pass
 
class LdapImportError(Exception):pass
 
class LdapConnectionError(Exception):
 
    pass
 

	
 

	
 
class LdapImportError(Exception):
 
    pass
 

	
 
class DefaultUserException(Exception):pass
 
class UserOwnsReposException(Exception):pass
 

	
 
class DefaultUserException(Exception):
 
    pass
 

	
 

	
 
class UserOwnsReposException(Exception):
 
    pass
rhodecode/lib/hooks.py
Show inline comments
 
@@ -29,12 +29,13 @@ import getpass
 
from mercurial.cmdutil import revrange
 
from mercurial.node import nullrev
 

	
 
from rhodecode.lib import helpers as h
 
from rhodecode.lib.utils import action_logger
 

	
 

	
 
def repo_size(ui, repo, hooktype=None, **kwargs):
 
    """Presents size of repository after push
 

	
 
    :param ui:
 
    :param repo:
 
    :param hooktype:
 
@@ -60,12 +61,13 @@ def repo_size(ui, repo, hooktype=None, *
 
    size_hg_f = h.format_byte_size(size_hg)
 
    size_root_f = h.format_byte_size(size_root)
 
    size_total_f = h.format_byte_size(size_root + size_hg)
 
    sys.stdout.write('Repository size .hg:%s repo:%s total:%s\n' \
 
                     % (size_hg_f, size_root_f, size_total_f))
 

	
 

	
 
def log_pull_action(ui, repo, **kwargs):
 
    """Logs user last pull action
 

	
 
    :param ui:
 
    :param repo:
 
    """
 
@@ -76,12 +78,13 @@ def log_pull_action(ui, repo, **kwargs):
 
    action = 'pull'
 

	
 
    action_logger(username, action, repository, extra_params['ip'])
 

	
 
    return 0
 

	
 

	
 
def log_push_action(ui, repo, **kwargs):
 
    """Maps user last push action to new changeset id, from mercurial
 

	
 
    :param ui:
 
    :param repo:
 
    """
rhodecode/lib/pidlock.py
Show inline comments
 
import os, time
 
import os
 
import sys
 
import time
 
import errno
 

	
 
from warnings import warn
 
from multiprocessing.util import Finalize
 
import errno
 

	
 
from rhodecode import __platform__, PLATFORM_WIN
 

	
 
if __platform__ in PLATFORM_WIN:
 
    import ctypes
 

	
 
    def kill(pid):
 
        """kill function for Win32"""
 
        kernel32 = ctypes.windll.kernel32
 
        handle = kernel32.OpenProcess(1, 0, pid)
 
        return (0 != kernel32.TerminateProcess(handle, 0))
 

	
 
else:
 
    kill = os.kill
 

	
 
class LockHeld(Exception):pass
 

	
 
class LockHeld(Exception):
 
    pass
 

	
 

	
 
class DaemonLock(object):
 
    """daemon locking
 
    USAGE:
 
    try:
 
@@ -31,14 +36,15 @@ class DaemonLock(object):
 
        sys.exit(1)
 
    """
 

	
 
    def __init__(self, file=None, callbackfn=None,
 
                 desc='daemon lock', debug=False):
 

	
 
        self.pidfile = file if file else os.path.join(os.path.dirname(__file__),
 
                                                      'running.lock')
 
        self.pidfile = file if file else os.path.join(
 
                                                    os.path.dirname(__file__),
 
                                                    'running.lock')
 
        self.callbackfn = callbackfn
 
        self.desc = desc
 
        self.debug = debug
 
        self.held = False
 
        #run the lock automatically !
 
        self.lock()
 
@@ -49,15 +55,16 @@ class DaemonLock(object):
 
    def _on_finalize(lock, debug):
 
        if lock.held:
 
            if debug:
 
                print 'leck held finilazing and running lock.release()'
 
            lock.release()
 

	
 

	
 
    def lock(self):
 
        """locking function, if lock is present it will raise LockHeld exception
 
        """
 
        locking function, if lock is present it
 
        will raise LockHeld exception
 
        """
 
        lockname = '%s' % (os.getpid())
 
        if self.debug:
 
            print 'running lock'
 
        self.trylock()
 
        self.makelock(lockname, self.pidfile)
 
@@ -72,22 +79,23 @@ class DaemonLock(object):
 
            pidfile.seek(0)
 
            running_pid = int(pidfile.readline())
 

	
 
            pidfile.close()
 

	
 
            if self.debug:
 
                print 'lock file present running_pid: %s, checking for execution'\
 
                % running_pid
 
                print ('lock file present running_pid: %s, '
 
                       'checking for execution') % running_pid
 
            # Now we check the PID from lock file matches to the current
 
            # process PID
 
            if running_pid:
 
                try:
 
                    kill(running_pid, 0)
 
                except OSError, exc:
 
                    if exc.errno in (errno.ESRCH, errno.EPERM):
 
                        print "Lock File is there but the program is not running"
 
                        print ("Lock File is there but"
 
                               " the program is not running")
 
                        print "Removing lock file for the: %s" % running_pid
 
                        self.release()
 
                    else:
 
                        raise
 
                else:
 
                    print "You already have an instance of the program running"
 
@@ -119,12 +127,13 @@ class DaemonLock(object):
 
                print 'removing pidfile failed %s' % e
 
            pass
 

	
 
    def makelock(self, lockname, pidfile):
 
        """
 
        this function will make an actual lock
 

	
 
        :param lockname: acctual pid of file
 
        :param pidfile: the file to write the pid in
 
        """
 
        if self.debug:
 
            print 'creating a file %s and pid: %s' % (pidfile, lockname)
 
        pidfile = open(self.pidfile, "wb")
rhodecode/lib/profiler.py
Show inline comments
 
@@ -5,21 +5,22 @@ import pstats
 
import cgi
 
import pprint
 
import threading
 

	
 
from StringIO import StringIO
 

	
 

	
 
class ProfilingMiddleware(object):
 
    def __init__(self, app):
 
        self.lock = threading.Lock()
 
        self.app = app
 

	
 

	
 
    def __call__(self, environ, start_response):
 
        with self.lock:
 
            profiler = cProfile.Profile()
 

	
 
            def run_app(*a, **kw):
 
                self.response = self.app(environ, start_response)
 

	
 
            profiler.runcall(run_app, environ, start_response)
 

	
 
            profiler.snapshot_stats()
 
@@ -36,13 +37,14 @@ class ProfilingMiddleware(object):
 
            resp = ''.join(self.response)
 

	
 
            # Lets at least only put this on html-like responses.
 
            if resp.strip().startswith('<'):
 
                ## The profiling info is just appended to the response.
 
                ##  Browsers don't mind this.
 
                resp += '<pre style="text-align:left; border-top: 4px dashed red; padding: 1em;">'
 
                resp += ('<pre style="text-align:left; '
 
                         'border-top: 4px dashed red; padding: 1em;">')
 
                resp += cgi.escape(out.getvalue(), True)
 

	
 
                output = StringIO()
 
                pprint.pprint(environ, output, depth=3)
 

	
 
                resp += cgi.escape(output.getvalue(), True)
rhodecode/lib/smtp_mailer.py
Show inline comments
 
@@ -20,16 +20,18 @@ from email.mime.image import MIMEImage
 
from email.mime.audio import MIMEAudio
 
from email.mime.base import MIMEBase
 
from email.mime.text import MIMEText
 
from email.utils import formatdate
 
from email import encoders
 

	
 

	
 
class SmtpMailer(object):
 
    """SMTP mailer class
 

	
 
    mailer = SmtpMailer(mail_from, user, passwd, mail_server, mail_port, ssl, tls)
 
    mailer = SmtpMailer(mail_from, user, passwd, mail_server,
 
                        mail_port, ssl, tls)
 
    mailer.send(recipients, subject, body, attachment_files)
 

	
 
    :param recipients might be a list of string or single string
 
    :param attachment_files is a dict of {filename:location}
 
        it tries to guess the mimetype and attach the file
 

	
 
@@ -67,13 +69,12 @@ class SmtpMailer(object):
 

	
 
        #if server requires authorization you must provide login and password
 
        #but only if we have them
 
        if self.user and self.passwd:
 
            smtp_serv.login(self.user, self.passwd)
 

	
 

	
 
        date_ = formatdate(localtime=True)
 
        msg = MIMEMultipart()
 
        msg['From'] = self.mail_from
 
        msg['To'] = ','.join(recipients)
 
        msg['Date'] = date_
 
        msg['Subject'] = subject
 
@@ -90,22 +91,21 @@ class SmtpMailer(object):
 
        try:
 
            smtp_serv.quit()
 
        except sslerror:
 
            # sslerror is raised in tls connections on closing sometimes
 
            pass
 

	
 

	
 

	
 
    def __atach_files(self, msg, attachment_files):
 
        if isinstance(attachment_files, dict):
 
            for f_name, msg_file in attachment_files.items():
 
                ctype, encoding = mimetypes.guess_type(f_name)
 
                logging.info("guessing file %s type based on %s" , ctype, f_name)
 
                logging.info("guessing file %s type based on %s", ctype,
 
                             f_name)
 
                if ctype is None or encoding is not None:
 
                    # No guess could be made, or the file is encoded (compressed), so
 
                    # use a generic bag-of-bits type.
 
                    # No guess could be made, or the file is encoded
 
                    # (compressed), so use a generic bag-of-bits type.
 
                    ctype = 'application/octet-stream'
 
                maintype, subtype = ctype.split('/', 1)
 
                if maintype == 'text':
 
                    # Note: we should handle calculating the charset
 
                    file_part = MIMEText(self.get_content(msg_file),
 
                                         _subtype=subtype)
rhodecode/lib/timerproxy.py
Show inline comments
 
@@ -2,18 +2,20 @@ from sqlalchemy.interfaces import Connec
 
import time
 
import logging
 
log = logging.getLogger('timerproxy')
 

	
 
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = xrange(30, 38)
 

	
 

	
 
def color_sql(sql):
 
    COLOR_SEQ = "\033[1;%dm"
 
    COLOR_SQL = YELLOW
 
    normal = '\x1b[0m'
 
    return COLOR_SEQ % COLOR_SQL + sql + normal
 

	
 

	
 
class TimerProxy(ConnectionProxy):
 

	
 
    def __init__(self):
 
        super(TimerProxy, self).__init__()
 

	
 
    def cursor_execute(self, execute, cursor, statement, parameters,
0 comments (0 inline, 0 general)