_objects.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /*
  2. * Copyright (C) 2009 Jelmer Vernooij <jelmer@samba.org>
  3. *
  4. * This program is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU General Public License
  6. * as published by the Free Software Foundation; version 2
  7. * of the License or (at your option) a later version of the License.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program; if not, write to the Free Software
  16. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  17. * MA 02110-1301, USA.
  18. */
  19. #include <Python.h>
  20. #define bytehex(x) (((x)<0xa)?('0'+(x)):('a'-0xa+(x)))
  21. static PyObject *sha_to_pyhex(const unsigned char *sha)
  22. {
  23. char hexsha[41];
  24. int i;
  25. for (i = 0; i < 20; i++) {
  26. hexsha[i*2] = bytehex((sha[i] & 0xF0) >> 4);
  27. hexsha[i*2+1] = bytehex(sha[i] & 0x0F);
  28. }
  29. return PyString_FromStringAndSize(hexsha, 40);
  30. }
  31. static PyObject *py_parse_tree(PyObject *self, PyObject *args)
  32. {
  33. char *text, *end;
  34. int len, namelen;
  35. PyObject *ret, *item, *name;
  36. if (!PyArg_ParseTuple(args, "s#", &text, &len))
  37. return NULL;
  38. ret = PyDict_New();
  39. if (ret == NULL) {
  40. return NULL;
  41. }
  42. end = text + len;
  43. while (text < end) {
  44. long mode;
  45. mode = strtol(text, &text, 8);
  46. if (*text != ' ') {
  47. PyErr_SetString(PyExc_RuntimeError, "Expected space");
  48. Py_DECREF(ret);
  49. return NULL;
  50. }
  51. text++;
  52. namelen = strlen(text);
  53. name = PyString_FromStringAndSize(text, namelen);
  54. if (name == NULL) {
  55. Py_DECREF(ret);
  56. return NULL;
  57. }
  58. item = Py_BuildValue("(lN)", mode, sha_to_pyhex((unsigned char *)text+namelen+1));
  59. if (item == NULL) {
  60. Py_DECREF(ret);
  61. Py_DECREF(name);
  62. return NULL;
  63. }
  64. if (PyDict_SetItem(ret, name, item) == -1) {
  65. Py_DECREF(ret);
  66. Py_DECREF(item);
  67. return NULL;
  68. }
  69. Py_DECREF(name);
  70. Py_DECREF(item);
  71. text += namelen+21;
  72. }
  73. return ret;
  74. }
  75. static PyMethodDef py_objects_methods[] = {
  76. { "parse_tree", (PyCFunction)py_parse_tree, METH_VARARGS, NULL },
  77. { NULL, NULL, 0, NULL }
  78. };
  79. void init_objects(void)
  80. {
  81. PyObject *m;
  82. m = Py_InitModule3("_objects", py_objects_methods, NULL);
  83. if (m == NULL)
  84. return;
  85. }