#include <Python.h>
-#define hexbyte(x) (isdigit(x)?(x)-'0':(x)-'a'+0xa)
#define bytehex(x) (((x)<0xa)?('0'+(x)):('a'-0xa+(x)))
-static PyObject *py_hex_to_sha(PyObject *self, PyObject *py_hexsha)
-{
- char *hexsha;
- char sha[20];
- int i;
-
- if (!PyString_CheckExact(py_hexsha)) {
- PyErr_SetString(PyExc_TypeError, "hex sha is not a string");
- return NULL;
- }
-
- if (PyString_Size(py_hexsha) != 40) {
- PyErr_SetString(PyExc_ValueError, "hex sha is not 40 bytes long");
- return NULL;
- }
-
- hexsha = PyString_AsString(py_hexsha);
-
- for (i = 0; i < 20; i++) {
- sha[i] = (hexbyte(hexsha[i*2]) << 4) + hexbyte(hexsha[i*2+1]);
- }
-
- return PyString_FromStringAndSize(sha, 20);
-}
-
static PyObject *sha_to_pyhex(const unsigned char *sha)
{
char hexsha[41];
return PyString_FromStringAndSize(hexsha, 40);
}
-static PyObject *py_sha_to_hex(PyObject *self, PyObject *py_sha)
-{
- if (!PyString_CheckExact(py_sha)) {
- PyErr_SetString(PyExc_TypeError, "sha is not a string");
- return NULL;
- }
-
- if (PyString_Size(py_sha) != 20) {
- PyErr_SetString(PyExc_ValueError, "sha is not 20 bytes long");
- return NULL;
- }
-
- return sha_to_pyhex((unsigned char *)PyString_AsString(py_sha));
-}
-
static PyObject *py_parse_tree(PyObject *self, PyObject *args)
{
char *text, *end;
}
static PyMethodDef py_objects_methods[] = {
- { "hex_to_sha", (PyCFunction)py_hex_to_sha, METH_O, NULL },
- { "sha_to_hex", (PyCFunction)py_sha_to_hex, METH_O, NULL },
{ "parse_tree", (PyCFunction)py_parse_tree, METH_VARARGS, NULL },
{ NULL, NULL, 0, NULL }
};
"""Access to base git objects."""
+import binascii
from cStringIO import (
StringIO,
)
def sha_to_hex(sha):
"""Takes a string and returns the hex of the sha within"""
- hexsha = "".join(["%02x" % ord(c) for c in sha])
+ hexsha = binascii.hexlify(sha)
assert len(hexsha) == 40, "Incorrect length of sha1 string: %d" % hexsha
return hexsha
def hex_to_sha(hex):
"""Takes a hex sha and returns a binary sha"""
assert len(hex) == 40, "Incorrent length of hexsha: %s" % hex
- return ''.join([chr(int(hex[i:i+2], 16)) for i in xrange(0, len(hex), 2)])
+ return binascii.unhexlify(hex)
def serializable_property(name, docstring=None):
try:
# Try to import C versions
- from dulwich._objects import hex_to_sha, sha_to_hex, parse_tree
+ from dulwich._objects import parse_tree
except ImportError:
pass