"""Test for repository helper functions in hglib"""

import os
import pytest

from mercurial import (
    hg,
    node as nodemod,
)
from tortoisehg.util import hglib

import helpers

def setup_module():
    global _tmpdir
    _tmpdir = helpers.mktmpdir(__name__)

    hg = helpers.HgClient(os.path.join(_tmpdir, b'empty'))
    hg.init()
    setup_repoid()

def openrepo(name):
    return hg.repository(hglib.loadui(), os.path.join(_tmpdir, name))


_repoidnodes = [
    b'093f0fe4b6a9db9ad3537827ddb92c4dcf1406f9',
    b'121d24cace2c5ed7211158e5eb4ad8ac4691f505',
    b'0000000000000000000000000000000000000000',  # -1
    ]

def setup_repoid():
    for name in [b'repoid-trivial', b'repoid-allhidden', b'repoid-rev0hidden']:
        hg = helpers.HgClient(os.path.join(_tmpdir, name))
        hg.init()
        # to use "hg debugobsolete" and suppress "obsolete feature not enabled"
        hg.fappend(b'.hg/hgrc', b'[experimental]\nevolution.createmarkers = 1\n')
        hg.ftouch(b'foo')
        hg.commit(b'-Am0')
        hg.update(b'null')
        hg.ftouch(b'bar')
        hg.commit(b'-Am1')
        hg.update(b'null')
    hg = helpers.HgClient(os.path.join(_tmpdir, b'repoid-allhidden'))
    for n in _repoidnodes:
        hg.debugobsolete(n)
    hg = helpers.HgClient(os.path.join(_tmpdir, b'repoid-rev0hidden'))
    hg.debugobsolete(_repoidnodes[0])

@pytest.mark.parametrize('reponame, rootrev', [
    (b'empty', -1),
    (b'repoid-trivial', 0),
    (b'repoid-allhidden', -1),
    (b'repoid-rev0hidden', 1)
])
def test_repoid(reponame, rootrev):
    repo = openrepo(reponame)
    nodehex = _repoidnodes[rootrev]
    assert hglib.shortrepoid(repo) == nodehex[:12].decode('ascii')
    assert hglib.repoidnode(repo) == nodemod.bin(nodehex)
