svartalf is sharing code with you

Bitbucket is a code hosting site. Unlimited public and private repositories. Free for small teams.

Don't show this again

svartalf / misc

Разные куски кода

Clone this repository (size: 4.5 KB): HTTPS / SSH
hg clone https://bitbucket.org/svartalf/misc
hg clone ssh://hg@bitbucket.org/svartalf/misc

misc / mercurial_hooks.py

Branch
default
# -*- coding: utf-8 -*-

"""
Примеры хуков для mercurial
"""

import os
import re

from mercurial import patch

def print_check(ui, repo, **kwargs):
    """Отмена коммита, если в коде есть print

    Подключение в .hgrc:
        precommit = python:.hg/hooks.py:print_check"""

    linenum, header = 0, False

    files = {}

    diff = patch.diff(repo)

    for num, filediff in enumerate(diff):
        for line in filediff.split('\n'):
            if header:
                m = re.match(r'(?:---|\+\+\+) ([^\t]+)', line)
                if m and m.group(1) != '/dev/null':
                    filename = m.group(1).split('/', 1)[-1]
                if line.startswith('+++ '):
                    header = False
                continue
            if line.startswith('diff '):
                header = True
                continue
            m = re.match(r'@@ -\d+,\d+ \+(\d+),', line)
            if m:
                linenum = int(m.group(1))
                continue
            m = re.match(r'^(?:-|\+)\s*print', line)
            if m:
                if not files.has_key(filename):
                    files[filename] = []
                files[filename].append((linenum, line))
            if line and line[0] in ' +':
                linenum += 1

    if files:
        ui.warn('Error! Print statements founded\n')
        for file in files:
            ui.warn('\nFile: %s\n' % file)
            for error in files[file]:
                ui.warn('\tLine %s: %s\n' % (error[0], error[1].strip(' -+')[:70]))

    return bool(files)

def console_check(ui, repo, **kwargs):
    """Отмена коммита, если в .js файлах есть вызов console.*

    Подключение в .hgrc:
        precommit = python:.hg/hooks.py:console_check"""

    linenum, header = 0, False

    files = {}

    diff = patch.diff(repo)

    for num, filediff in enumerate(diff):
        for line in filediff.split('\n'):
            if header:
                m = re.match(r'(?:---|\+\+\+) ([^\t]+)', line)
                if m and m.group(1) != '/dev/null':
                    filename = m.group(1).split('/', 1)[-1]
                if line.startswith('+++ '):
                    header = False
                continue
            if line.startswith('diff '):
                header = True
                continue
            if not os.path.splitext(filename)[1] in ('.js', '.html'):
                continue
            m = re.match(r'@@ -\d+,\d+ \+(\d+),', line)
            if m:
                linenum = int(m.group(1))
                continue
            m = re.match(r'^(?:-|\+)\s*console.', line)
            if m:
                if not files.has_key(filename):
                    files[filename] = []
                files[filename].append((linenum, line))
            if line and line[0] in ' +':
                linenum += 1

    if files:
        ui.warn('Error! JS console statements founded\n')
        for file in files:
            ui.warn('\nFile: %s\n' % file)
            for error in files[file]:
                ui.warn('\tLine %s: %s\n' % (error[0], error[1].strip(' -+')[:70]))

def clean_cache(ui, repo, **kwargs):
    """После обновления репозитория удаляем .pyc файлы

    Подключение в .hgrc:
        preupdate = python:.hg/hooks.py:clean_cache"""

    for root, dirs, files in os.walk(repo.root):
        for file in files:
            if os.path.splitext(file)[1] == '.pyc':
                os.remove(os.path.join(root, file))