Pergunta

Quero ter um gancho mercurial que será executado antes de cometer uma transação que abortará a transação se um arquivo binário que está sendo cometido for maior que 1 megabyte. Encontrei o seguinte código que funciona bem, exceto por um problema. Se o meu troca envolver a remoção de um arquivo, esse gancho lançará uma exceção.

O gancho (estou usando pretxncommit = python:checksize.newbinsize):

from mercurial import context, util
from mercurial.i18n import _
import mercurial.node as dpynode

'''hooks to forbid adding binary file over a given size

Ensure the PYTHONPATH is pointing where hg_checksize.py is and setup your
repo .hg/hgrc like this:

[hooks]
pretxncommit = python:checksize.newbinsize
pretxnchangegroup = python:checksize.newbinsize
preoutgoing = python:checksize.nopull

[limits]
maxnewbinsize = 10240
'''

def newbinsize(ui, repo, node=None, **kwargs):
    '''forbid to add binary files over a given size'''
    forbid = False
    # default limit is 10 MB
    limit = int(ui.config('limits', 'maxnewbinsize', 10000000))
    tip = context.changectx(repo, 'tip').rev()
    ctx = context.changectx(repo, node)
    for rev in range(ctx.rev(), tip+1):
        ctx = context.changectx(repo, rev)
        print ctx.files()
        for f in ctx.files():
            fctx = ctx.filectx(f)
            filecontent = fctx.data()
            # check only for new files
            if not fctx.parents():
                if len(filecontent) > limit and util.binary(filecontent):
                    msg = 'new binary file %s of %s is too large: %ld > %ld\n'
                    hname = dpynode.short(ctx.node())
                    ui.write(_(msg) % (f, hname, len(filecontent), limit))
                    forbid = True
    return forbid

A exceção:

$  hg commit -m 'commit message'
error: pretxncommit hook raised an exception: apps/helpers/templatetags/include_extends.py@bced6272d8f4: not found in manifest
transaction abort!
rollback completed
abort: apps/helpers/templatetags/include_extends.py@bced6272d8f4: not found in manifest!

Não estou familiarizado em escrever ganchos mercuriais, por isso estou muito confuso sobre o que está acontecendo. Por que o gancho se importa com o fato de um arquivo ter sido removido se HG já sabe disso? Existe uma maneira de consertar esse gancho para que funcione o tempo todo?

Atualização (resolvido):Modifiquei o gancho para filtrar os arquivos que foram removidos no alterações.

def newbinsize(ui, repo, node=None, **kwargs):
    '''forbid to add binary files over a given size'''
    forbid = False
    # default limit is 10 MB
    limit = int(ui.config('limits', 'maxnewbinsize', 10000000))
    ctx = repo[node]
    for rev in xrange(ctx.rev(), len(repo)):
        ctx = context.changectx(repo, rev)

        # do not check the size of files that have been removed
        # files that have been removed do not have filecontexts
        # to test for whether a file was removed, test for the existence of a filecontext
        filecontexts = list(ctx)
        def file_was_removed(f):
            """Returns True if the file was removed"""
            if f not in filecontexts:
                return True
            else:
                return False

        for f in itertools.ifilterfalse(file_was_removed, ctx.files()):
            fctx = ctx.filectx(f)
            filecontent = fctx.data()
            # check only for new files
            if not fctx.parents():
                if len(filecontent) > limit and util.binary(filecontent):
                    msg = 'new binary file %s of %s is too large: %ld > %ld\n'
                    hname = dpynode.short(ctx.node())
                    ui.write(_(msg) % (f, hname, len(filecontent), limit))
                    forbid = True
    return forbid
Foi útil?

Solução

for f in ctx.files() Incluirá arquivos removidos, você precisa filtrá -los.

(e você pode substituir for rev in range(ctx.rev(), tip+1): por for rev in xrange(ctx.rev(), len(repo)):, e remova tip = ...)

Se você está usando um HG moderno, você não faz ctx = context.changectx(repo, node) mas ctx = repo[node] em vez de.

Outras dicas

Isso é realmente fácil de fazer em um gancho de concha no Mercurial recente:

if hg locate -r tip "set:(added() or modified()) and binary() and size('>100k')"; then
  echo "bad files!"
  exit 1
else
  exit 0
fi

O que está acontecendo aqui? Primeiro, temos um conjunto de arquivos para encontrar todos os arquivos alterados que são problemáticos (consulte 'HG Ajuda Arquivos de Ajuda' no HG 1.9). O comando 'Locate' é como o status, exceto que apenas lista arquivos e retorna 0 se encontrar alguma coisa. E especificamos '-r dica' para olhar para a confirmação pendente.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top