Skip to content

Commit

Permalink
No object should ever be False
Browse files Browse the repository at this point in the history
The representation of Tree as a sequence causes boolean coercion to
consider the empty tree to be False, which is nonsensical.

Override __nonzero__ for all object types to return True.

This fixes libgit2#432.
  • Loading branch information
carlosmn committed Oct 6, 2014
1 parent a53d8b2 commit 156a82e
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
26 changes: 25 additions & 1 deletion src/object.c
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,15 @@ Object_peel(Object *self, PyObject *py_type)
return wrap_object(peeled, self->repo);
}

PyDoc_STRVAR(Object___nonzero____doc__,
"Boolean coercion, an object is always True");

PyObject *
Object___nonzero__(Object *self)
{
Py_RETURN_TRUE;
}

PyGetSetDef Object_getseters[] = {
GETTER(Object, oid),
GETTER(Object, id),
Expand All @@ -200,6 +209,21 @@ PyMethodDef Object_methods[] = {
};


static PyNumberMethods NumberMethods = {
0, /* nb_add */
0, /* nb_subtract */
0, /* nb_multiply */
0, /*nb_divide */
0, /* nb_remainder */
0, /* nb_divmod */
0, /* nb_power */
0, /* nb_negative */
0, /* nb_positive */
0, /* nb_absolute */
Object___nonzero__, /* nb_nonzero */
/* There are a lot more, we we don't need any of them */
};

PyDoc_STRVAR(Object__doc__, "Base class for Git objects.");

PyTypeObject ObjectType = {
Expand All @@ -213,7 +237,7 @@ PyTypeObject ObjectType = {
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
&NumberMethods, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
Expand Down
9 changes: 8 additions & 1 deletion test/test_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
import unittest

import pygit2
from pygit2 import GIT_OBJ_TREE, GIT_OBJ_TAG, Tree, Tag
from pygit2 import GIT_OBJ_TREE, GIT_OBJ_TAG, GIT_OBJ_BLOB, Tree, Tag
from . import utils


Expand Down Expand Up @@ -78,5 +78,12 @@ def test_invalid_type(self):

self.assertRaises(ValueError, commit.peel, Tag)

def test_nonzero(self):
empty_tree_id = self.repo.TreeBuilder().write()
self.assertTrue(self.repo[empty_tree_id])

empty_blob_id = self.repo.write(GIT_OBJ_BLOB, '')
self.assertTrue(self.repo[empty_tree_id])

if __name__ == '__main__':
unittest.main()

0 comments on commit 156a82e

Please sign in to comment.