Skip to content

Return Python enums from _pygit2 #1263

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jan 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions pygit2/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@

# Low level API
from ._pygit2 import *
from ._pygit2 import _cache_enums

# High level API
from . import enums
Expand Down Expand Up @@ -59,6 +60,10 @@
# libgit version tuple
LIBGIT2_VER = (LIBGIT2_VER_MAJOR, LIBGIT2_VER_MINOR, LIBGIT2_VER_REVISION)

# Let _pygit2 cache references to Python enum types.
# This is separate from PyInit__pygit2() to avoid a circular import.
_cache_enums()


def init_repository(
path: typing.Union[str, bytes, PathLike, None],
Expand Down
39 changes: 22 additions & 17 deletions pygit2/_pygit2.pyi
Original file line number Diff line number Diff line change
@@ -1,18 +1,23 @@
from typing import Iterator, Literal, Optional, overload
from io import IOBase
from . import Index, Submodule
from .enums import ApplyLocation
from .enums import BranchType
from .enums import DiffFind
from .enums import DiffOption
from .enums import DiffStatsFormat
from .enums import MergeAnalysis
from .enums import MergePreference
from .enums import ObjectType
from .enums import Option
from .enums import ReferenceFilter
from .enums import ResetMode
from .enums import SortMode
from .enums import (
ApplyLocation,
BranchType,
DiffFind,
DiffFlag,
DiffOption,
DiffStatsFormat,
FileMode,
FileStatus,
MergeAnalysis,
MergePreference,
ObjectType,
Option,
ReferenceFilter,
ResetMode,
SortMode,
)

GIT_OBJ_BLOB: Literal[3]
GIT_OBJ_COMMIT: Literal[1]
Expand Down Expand Up @@ -139,19 +144,19 @@ class Diff:
def __len__(self) -> int: ...

class DiffDelta:
flags: int
flags: DiffFlag
is_binary: bool
new_file: DiffFile
nfiles: int
new_file: DiffFile
old_file: DiffFile
similarity: int
status: int
status: FileStatus
def status_char(self) -> str: ...

class DiffFile:
flags: int
flags: DiffFlag
id: Oid
mode: int
mode: FileMode
path: str
raw_path: bytes
size: int
Expand Down
58 changes: 53 additions & 5 deletions src/diff.c
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ extern PyTypeObject DiffLineType;
extern PyTypeObject DiffStatsType;
extern PyTypeObject RepositoryType;

extern PyObject *DeltaStatusEnum;
extern PyObject *DiffFlagEnum;
extern PyObject *FileModeEnum;

PyObject *
wrap_diff(git_diff *diff, Repository *repo)
{
Expand Down Expand Up @@ -204,13 +208,31 @@ DiffFile_from_c(DiffFile *dummy, PyObject *py_diff_file_ptr)
return wrap_diff_file(diff_file);
}

PyDoc_STRVAR(DiffFile_flags__doc__,
"A combination of enums.DiffFlag constants."
);

PyObject *
DiffFile_flags__get__(DiffFile *self)
{
return pygit2_enum(DiffFlagEnum, self->flags);
}

PyDoc_STRVAR(DiffFile_mode__doc__,
"Mode of the entry (an enums.FileMode constant)."
);

PyObject *
DiffFile_mode__get__(DiffFile *self)
{
return pygit2_enum(FileModeEnum, self->mode);
}

PyMemberDef DiffFile_members[] = {
MEMBER(DiffFile, id, T_OBJECT, "Oid of the item."),
MEMBER(DiffFile, path, T_STRING, "Path to the entry."),
MEMBER(DiffFile, raw_path, T_OBJECT, "Path to the entry (bytes)."),
MEMBER(DiffFile, size, T_LONG, "Size of the entry."),
MEMBER(DiffFile, flags, T_UINT, "Combination of GIT_DIFF_FLAG_* flags."),
MEMBER(DiffFile, mode, T_USHORT, "Mode of the entry."),
{NULL}
};

Expand All @@ -219,6 +241,12 @@ PyMethodDef DiffFile_methods[] = {
{NULL},
};

PyGetSetDef DiffFile_getsetters[] = {
GETTER(DiffFile, flags),
GETTER(DiffFile, mode),
{NULL},
};

PyDoc_STRVAR(DiffFile__doc__, "DiffFile object.");

PyTypeObject DiffFileType = {
Expand Down Expand Up @@ -251,7 +279,7 @@ PyTypeObject DiffFileType = {
0, /* tp_iternext */
DiffFile_methods, /* tp_methods */
DiffFile_members, /* tp_members */
0, /* tp_getset */
DiffFile_getsetters, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
Expand Down Expand Up @@ -294,6 +322,26 @@ DiffDelta_is_binary__get__(DiffDelta *self)
Py_RETURN_NONE;
}

PyDoc_STRVAR(DiffDelta_status__doc__,
"An enums.FileStatus constant."
);

PyObject *
DiffDelta_status__get__(DiffDelta *self)
{
return pygit2_enum(DeltaStatusEnum, self->status);
}

PyDoc_STRVAR(DiffDelta_flags__doc__,
"A combination of enums.DiffFlag constants."
);

PyObject *
DiffDelta_flags__get__(DiffDelta *self)
{
return pygit2_enum(DiffFlagEnum, self->flags);
}

static void
DiffDelta_dealloc(DiffDelta *self)
{
Expand All @@ -308,8 +356,6 @@ static PyMethodDef DiffDelta_methods[] = {
};

PyMemberDef DiffDelta_members[] = {
MEMBER(DiffDelta, status, T_UINT, "A GIT_DELTA_* constant."),
MEMBER(DiffDelta, flags, T_UINT, "Combination of GIT_DIFF_FLAG_* flags."),
MEMBER(DiffDelta, similarity, T_USHORT, "For renamed and copied."),
MEMBER(DiffDelta, nfiles, T_USHORT, "Number of files in the delta."),
MEMBER(DiffDelta, old_file, T_OBJECT, "\"from\" side of the diff."),
Expand All @@ -319,6 +365,8 @@ PyMemberDef DiffDelta_members[] = {

PyGetSetDef DiffDelta_getsetters[] = {
GETTER(DiffDelta, is_binary),
GETTER(DiffDelta, status),
GETTER(DiffDelta, flags),
{NULL}
};

Expand Down
72 changes: 70 additions & 2 deletions src/pygit2.c
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,13 @@ PyObject *GitError;
PyObject *AlreadyExistsError;
PyObject *InvalidSpecError;

PyObject *DeltaStatusEnum;
PyObject *DiffFlagEnum;
PyObject *FileModeEnum;
PyObject *FileStatusEnum;
PyObject *MergeAnalysisEnum;
PyObject *MergePreferenceEnum;

extern PyTypeObject RepositoryType;
extern PyTypeObject OdbType;
extern PyTypeObject OdbBackendType;
Expand Down Expand Up @@ -361,6 +368,67 @@ filter_unregister(PyObject *self, PyObject *args)
}


static void
forget_enums(void)
{
Py_CLEAR(DeltaStatusEnum);
Py_CLEAR(DiffFlagEnum);
Py_CLEAR(FileModeEnum);
Py_CLEAR(FileStatusEnum);
Py_CLEAR(MergeAnalysisEnum);
Py_CLEAR(MergePreferenceEnum);
}

PyDoc_STRVAR(_cache_enums__doc__,
"_cache_enums()\n"
"\n"
"For internal use only. Do not call this from user code.\n"
"\n"
"Let the _pygit2 C module cache references to Python enums\n"
"defined in pygit2.enums.\n");

PyObject *
_cache_enums(PyObject *self, PyObject *args)
{
(void) args;

/* In case this is somehow being called several times, let go of old references */
forget_enums();

PyObject *enums = PyImport_ImportModule("pygit2.enums");
if (enums == NULL) {
return NULL;
}

#define CACHE_PYGIT2_ENUM(name) do { \
name##Enum = PyObject_GetAttrString(enums, #name); \
if (name##Enum == NULL) { goto fail; } \
} while (0)

CACHE_PYGIT2_ENUM(DeltaStatus);
CACHE_PYGIT2_ENUM(DiffFlag);
CACHE_PYGIT2_ENUM(FileMode);
CACHE_PYGIT2_ENUM(FileStatus);
CACHE_PYGIT2_ENUM(MergeAnalysis);
CACHE_PYGIT2_ENUM(MergePreference);

#undef CACHE_PYGIT2_ENUM

Py_RETURN_NONE;

fail:
Py_DECREF(enums);
forget_enums();
return NULL;
}

void
free_module(void *self)
{
forget_enums();
}


PyMethodDef module_methods[] = {
{"discover_repository", discover_repository, METH_VARARGS, discover_repository__doc__},
{"hash", hash, METH_VARARGS, hash__doc__},
Expand All @@ -371,10 +439,10 @@ PyMethodDef module_methods[] = {
{"tree_entry_cmp", tree_entry_cmp, METH_VARARGS, tree_entry_cmp__doc__},
{"filter_register", (PyCFunction)filter_register, METH_VARARGS | METH_KEYWORDS, filter_register__doc__},
{"filter_unregister", filter_unregister, METH_VARARGS, filter_unregister__doc__},
{"_cache_enums", _cache_enums, METH_NOARGS, _cache_enums__doc__},
{NULL}
};


struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"_pygit2", /* m_name */
Expand All @@ -384,7 +452,7 @@ struct PyModuleDef moduledef = {
NULL, /* m_reload */
NULL, /* m_traverse */
NULL, /* m_clear */
NULL, /* m_free */
free_module, /* m_free */
};

PyMODINIT_FUNC
Expand Down
32 changes: 27 additions & 5 deletions src/repository.c
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,10 @@ extern PyTypeObject NoteIterType;
extern PyTypeObject StashType;
extern PyTypeObject RefsIteratorType;

extern PyObject *FileStatusEnum;
extern PyObject *MergeAnalysisEnum;
extern PyObject *MergePreferenceEnum;

/* forward-declaration for Repsository._from_c() */
PyTypeObject RepositoryType;

Expand Down Expand Up @@ -705,7 +709,22 @@ Repository_merge_analysis(Repository *self, PyObject *args)
goto out;
}

py_result = Py_BuildValue("(ii)", analysis, preference);
// Convert analysis to MergeAnalysis enum
PyObject *analysis_enum = pygit2_enum(MergeAnalysisEnum, analysis);
if (!analysis_enum) {
py_result = NULL;
goto out;
}

// Convert preference to MergePreference enum
PyObject *preference_enum = pygit2_enum(MergePreferenceEnum, preference);
if (!preference_enum) {
py_result = NULL;
Py_DECREF(analysis_enum);
goto out;
}

py_result = Py_BuildValue("(OO)", analysis_enum, preference_enum);

out:
git_reference_free(our_ref);
Expand Down Expand Up @@ -1754,14 +1773,17 @@ Repository_status(Repository *self, PyObject *args, PyObject *kw)
path = entry->head_to_index->old_file.path;
else
path = entry->index_to_workdir->old_file.path;
status = PyLong_FromLong((long) entry->status);

/* Get corresponding entry in enums.FileStatus for status int */
status = pygit2_enum(FileStatusEnum, entry->status);
if (status == NULL)
goto error;

err = PyDict_SetItemString(dict, path, status);
Py_CLEAR(status);

if (err < 0)
goto error;

}

git_status_list_free(list);
Expand All @@ -1775,7 +1797,7 @@ Repository_status(Repository *self, PyObject *args, PyObject *kw)


PyDoc_STRVAR(Repository_status_file__doc__,
"status_file(path: str) -> int\n"
"status_file(path: str) -> enums.FileStatus\n"
"\n"
"Returns the status of the given file path.");

Expand All @@ -1795,7 +1817,7 @@ Repository_status_file(Repository *self, PyObject *value)
}
free(path);

return PyLong_FromLong(status);
return pygit2_enum(FileStatusEnum, (int) status);
}


Expand Down
15 changes: 15 additions & 0 deletions src/utils.c
Original file line number Diff line number Diff line change
Expand Up @@ -276,3 +276,18 @@ py_object_to_otype(PyObject *py_type)
PyErr_SetString(PyExc_ValueError, "invalid target type");
return GIT_OBJECT_INVALID; /* -1 */
}


/**
* Convert an integer to a reference to an IntEnum or IntFlag in pygit2.enums.
*/
PyObject *
pygit2_enum(PyObject *enum_type, int value)
{
if (!enum_type) {
PyErr_SetString(PyExc_TypeError, "an enum has not been cached in _pygit2.cache_enums()");
return NULL;
}
PyObject *enum_instance = PyObject_CallFunction(enum_type, "(i)", value);
return enum_instance;
}
5 changes: 5 additions & 0 deletions src/utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,11 @@ char* pgit_encode_fsdefault(PyObject *value);

git_otype py_object_to_otype(PyObject *py_type);


/* Enum utilities (pygit2.enums) */
PyObject *pygit2_enum(PyObject *enum_type, int value);


/* Helpers to make shorter PyMethodDef and PyGetSetDef blocks */
#define METHOD(type, name, args)\
{#name, (PyCFunction) type ## _ ## name, args, type ## _ ## name ## __doc__}
Expand Down
Loading