libgit-thin: pygit: Introduces GitRepoObject
[git/libgit-gsoc.git] / libgit-thin / pygit / pygit.c
blob6ca26715d560a5e932616a225f589f47bd684e0d
1 #include <Python.h>
2 #include "structmember.h"
4 #include <libgit-thin.h>
6 #define UNUSED(x) (x = x)
8 PyMODINIT_FUNC initpygit(void);
10 static int repository_open;
12 typedef struct {
13 PyObject_HEAD
14 } GitRepoObject;
16 static PyObject *
17 pygit_repo_read_commit(GitRepoObject *self, PyObject *args)
19 int err;
20 void *buf;
21 const char *hex;
22 unsigned char sha1[GIT_SHA1_SIZE];
24 UNUSED(self);
26 if (!repository_open)
27 return NULL;
29 if (!PyArg_ParseTuple(args, "s", &hex))
30 return NULL;
32 err = git_hex_to_sha1(hex, sha1);
33 if (err)
34 return NULL;
36 err = git_repo_commit_read(sha1, &buf, NULL);
37 if (err)
38 return NULL;
40 printf("%s", (char *) buf);
42 Py_RETURN_NONE;
45 static PyMethodDef git_repo_methods[] = {
46 {"read_commit", (PyCFunction) pygit_repo_read_commit,
47 METH_VARARGS, NULL},
48 {NULL}
51 static PyObject *
52 git_repo_getattr(GitRepoObject *self, char *name)
54 PyObject *res;
56 res = Py_FindMethod(git_repo_methods, (PyObject *) self, name);
57 if (res)
58 return res;
60 return NULL;
63 static void
64 git_repo_dealloc(GitRepoObject *self)
66 PyObject_DEL(self);
69 static PyTypeObject Git_Repo_Type = {
70 PyObject_HEAD_INIT(NULL)
71 0, /* ob_size */
72 "pygit.repo", /* tp_name */
73 sizeof(GitRepoObject), /* tp_basicsize */
74 0, /* tp_itemsize */
75 (destructor)git_repo_dealloc, /* tp_dealloc */
76 0, /* tp_print */
77 (getattrfunc)git_repo_getattr, /* tp_getattr */
78 0, /* tp_setattr */
79 0, /* tp_compare */
80 0, /* tp_repr */
81 0, /* tp_as_number */
82 0, /* tp_as_sequence */
83 0, /* tp_as_mapping */
84 0, /* tp_hash */
85 0, /* tp_call */
86 0, /* tp_str */
87 0, /* tp_getattro */
88 0, /* tp_setattro */
89 0, /* tp_as_buffer */
90 Py_TPFLAGS_DEFAULT, /* tp_flags */
91 0, /* tp_doc */
92 0, /* tp_traverse */
93 0, /* tp_clear */
94 0, /* tp_richcompare */
97 static PyObject *
98 pygit_open(PyObject *self, PyObject *args)
100 const char *dir;
101 GitRepoObject *m;
103 UNUSED(self);
105 if (!PyArg_ParseTuple(args, "s", &dir))
106 return NULL;
108 if (git_repo_open(dir)) {
109 PyErr_SetFromErrno(PyExc_IOError);
110 return NULL;
113 m = PyObject_New(GitRepoObject, &Git_Repo_Type);
114 if (!m)
115 return NULL;
117 repository_open = 1;
118 return (PyObject *) m;
121 static PyMethodDef pygit_methods[] = {
122 { "open", pygit_open, METH_VARARGS, "Open a GIT repository" },
123 { NULL, NULL, 0, NULL}
126 PyMODINIT_FUNC
127 initpygit(void)
129 /* Patch object types */
130 Git_Repo_Type.ob_type = &PyType_Type;
132 (void) Py_InitModule("pygit", pygit_methods);