Blender V5.3
bpy_cli_command.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2024 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
10#include <Python.h>
11
12#include "BLI_utildefines.hh"
13
14#include "bpy_capi_utils.hh"
15
17
19#include "../generic/python_compat.hh" /* IWYU pragma: keep. */
20
21#include "bpy_cli_command.hh" /* Own include. */
22
23namespace blender {
24
25static const char *bpy_cli_command_capsule_name = "bpy_cli_command";
26static const char *bpy_cli_command_capsule_name_invalid = "bpy_cli_command<invalid>";
27
28/* -------------------------------------------------------------------- */
31
35static PyObject *py_argv_from_bytes(const int argc, const char **argv)
36{
37 /* Copy functionality from Python's internal `sys.argv` initialization. */
38 PyConfig config;
39 PyConfig_InitPythonConfig(&config);
40 PyStatus status = PyConfig_SetBytesArgv(&config, argc, const_cast<char *const *>(argv));
41 PyObject *py_argv = nullptr;
42 if (PyStatus_Exception(status)) [[unlikely]] {
43 PyErr_Format(PyExc_ValueError, "%s", status.err_msg);
44 }
45 else {
46 BLI_assert(argc == config.argv.length);
47 py_argv = PyList_New(config.argv.length);
48 for (Py_ssize_t i = 0; i < config.argv.length; i++) {
49 PyList_SET_ITEM(py_argv, i, PyUnicode_FromWideChar(config.argv.items[i], -1));
50 }
51 }
52 PyConfig_Clear(&config);
53 return py_argv;
54}
55
57
58/* -------------------------------------------------------------------- */
61
63 PyObject *py_exec_fn,
64 const int argc,
65 const char **argv)
66{
67 PyGILState_STATE gilstate;
68 bpy_context_set(C, &gilstate);
69
70 int exit_code = EXIT_FAILURE;
71
72 /* For the most part `sys.argv[-argc:]` is sufficient & less trouble than re-creating this
73 * list. Don't do this because:
74 * - Python scripts *could* have manipulated `sys.argv` (although it's bad practice).
75 * - We may want to support invoking commands directly,
76 * where the arguments aren't necessarily from `sys.argv`.
77 */
78 bool has_error = false;
79 PyObject *py_argv = py_argv_from_bytes(argc, argv);
80
81 if (py_argv == nullptr) {
82 has_error = true;
83 }
84 else {
85 PyObject *exec_args = PyTuple_New(1);
86 PyTuple_SET_ITEM(exec_args, 0, py_argv);
87
88 PyObject *result = PyObject_Call(py_exec_fn, exec_args, nullptr);
89
90 Py_DECREF(exec_args); /* Frees `py_argv` too. */
91
92 /* Convert `sys.exit` into a return-value.
93 * NOTE: typically `sys.exit` *doesn't* need any special handling,
94 * however it's neater if we use the same code paths for exiting either way. */
95 if ((result == nullptr) && PyErr_ExceptionMatches(PyExc_SystemExit)) {
96 PyObject *error_type, *error_value, *error_traceback;
97 PyErr_Fetch(&error_type, &error_value, &error_traceback);
98 if (PyObject_TypeCheck(error_value, (PyTypeObject *)PyExc_SystemExit) &&
99 ((reinterpret_cast<PySystemExitObject *>(error_value))->code != nullptr))
100 {
101 /* When `SystemExit(..)` is raised. */
102 result = (reinterpret_cast<PySystemExitObject *>(error_value))->code;
103 }
104 else {
105 /* When `sys.exit()` is called. */
106 result = error_value;
107 }
108 Py_INCREF(result);
109 PyErr_Restore(error_type, error_value, error_traceback);
110 PyErr_Clear();
111 }
112
113 if (result == nullptr) {
114 has_error = true;
115 }
116 else {
117 if (!PyLong_Check(result)) {
118 PyErr_Format(PyExc_TypeError,
119 "Expected an int return value, not a %.200s",
120 Py_TYPE(result)->tp_name);
121 has_error = true;
122 }
123 else {
124 const int exit_code_test = PyC_Long_AsI32(result);
125 if ((exit_code_test == -1) && PyErr_Occurred()) {
126 exit_code = EXIT_SUCCESS;
127 has_error = true;
128 }
129 else {
130 exit_code = exit_code_test;
131 }
132 }
133 Py_DECREF(result);
134 }
135 }
136
137 if (has_error) {
138 PyErr_Print();
139 }
140
141 bpy_context_clear(C, &gilstate);
142
143 return exit_code;
144}
145
146static void bpy_cli_command_free(PyObject *py_exec_fn)
147{
148 /* An explicit unregister clears to avoid acquiring a lock. */
149 if (py_exec_fn) {
150 PyGILState_STATE gilstate = PyGILState_Ensure();
151 Py_DECREF(py_exec_fn);
152 PyGILState_Release(gilstate);
153 }
154}
155
157
158/* -------------------------------------------------------------------- */
161
163 public:
164 BPyCommandHandler(const std::string &id, PyObject *py_exec_fn)
166 {
167 }
169 {
171 }
172
173 int exec(bContext *C, int argc, const char **argv) override
174 {
175 return bpy_cli_command_exec(C, this->py_exec_fn, argc, argv);
176 }
177
178 PyObject *py_exec_fn = nullptr;
179};
180
182
183/* -------------------------------------------------------------------- */
186
188 /* Wrap. */
189 bpy_cli_command_register_doc,
190 ".. function:: register_cli_command(id, execute)\n"
191 "\n"
192 " Register a command, accessible via the (``-c`` / ``--command``) command-line argument.\n"
193 "\n"
194 " :param id: The command identifier (must pass an ``str.isidentifier`` check).\n"
195 "\n"
196 " If the ``id`` is already registered, a warning is printed and "
197 "the command is inaccessible to prevent accidents invoking the wrong command.\n"
198 " :type id: str\n"
199 " :param execute: Callback, taking a single list of strings and returns an int.\n"
200 " The arguments are built from all command-line arguments following the command id.\n"
201 " The return value should be 0 for success, 1 on failure "
202 "(specific error codes from the ``os`` module can also be used).\n"
203 " :type execute: Callable[[list[str]], int]\n"
204 " :return: The command handle which can be passed to :func:`unregister_cli_command`.\n"
205 "\n"
206 " This uses Python's capsule type "
207 "however the result should be considered an opaque handle only used for unregistering.\n"
208 /* No exposed type for "Capsule", use "Any". */
209 " :rtype: Any\n");
210static PyObject *bpy_cli_command_register(PyObject * /*self*/, PyObject *args, PyObject *kw)
211{
212 PyObject *py_id;
213 PyObject *py_exec_fn;
214
215 static const char *_keywords[] = {
216 "id",
217 "execute",
218 nullptr,
219 };
220 static _PyArg_Parser _parser = {
221 "O!" /* `id` */
222 "O" /* `execute` */
223 ":register_cli_command",
224 _keywords,
225 nullptr,
226 };
227 if (!_PyArg_ParseTupleAndKeywordsFast(args, kw, &_parser, &PyUnicode_Type, &py_id, &py_exec_fn))
228 {
229 return nullptr;
230 }
231 if (!PyUnicode_IsIdentifier(py_id)) {
232 PyErr_SetString(PyExc_ValueError, "The command id is not a valid identifier");
233 return nullptr;
234 }
235 if (!PyCallable_Check(py_exec_fn)) {
236 PyErr_SetString(PyExc_ValueError, "The execute argument must be callable");
237 return nullptr;
238 }
239
240 const char *id = PyUnicode_AsUTF8(py_id);
241
242 std::unique_ptr<CommandHandler> cmd_ptr = std::make_unique<BPyCommandHandler>(
243 std::string(id), Py_NewRef(py_exec_fn));
244 void *cmd_p = cmd_ptr.get();
245
246 BKE_blender_cli_command_register(std::move(cmd_ptr));
247
248 return PyCapsule_New(cmd_p, bpy_cli_command_capsule_name, nullptr);
249}
250
252 /* Wrap. */
253 bpy_cli_command_unregister_doc,
254 ".. function:: unregister_cli_command(handle)\n"
255 "\n"
256 " Unregister a CLI command.\n"
257 "\n"
258 " :param handle: The return value of :func:`register_cli_command`.\n"
259 /* No exposed type for "Capsule", use "Any". */
260 " :type handle: Any\n");
261static PyObject *bpy_cli_command_unregister(PyObject * /*self*/, PyObject *value)
262{
263 if (!PyCapsule_CheckExact(value)) {
264 PyErr_Format(PyExc_TypeError,
265 "Expected a capsule returned from register_cli_command(...), found a: %.200s",
266 Py_TYPE(value)->tp_name);
267 return nullptr;
268 }
269
270 BPyCommandHandler *cmd = static_cast<BPyCommandHandler *>(
271 PyCapsule_GetPointer(value, bpy_cli_command_capsule_name));
272 if (cmd == nullptr) {
273 const char *capsule_name = PyCapsule_GetName(value);
274 if (capsule_name == bpy_cli_command_capsule_name_invalid) {
275 PyErr_SetString(PyExc_ValueError, "The command has already been removed");
276 }
277 else {
278 PyErr_Format(PyExc_ValueError,
279 "Unrecognized capsule ID \"%.200s\"",
280 capsule_name ? capsule_name : "<null>");
281 }
282 return nullptr;
283 }
284
285 /* Don't acquire the GIL when un-registering. */
286 Py_CLEAR(cmd->py_exec_fn);
287
288 /* Don't allow removing again. */
289 PyCapsule_SetName(value, bpy_cli_command_capsule_name_invalid);
290
292
293 Py_RETURN_NONE;
294}
295
296#ifdef __GNUC__
297# ifdef __clang__
298# pragma clang diagnostic push
299# pragma clang diagnostic ignored "-Wcast-function-type"
300# else
301# pragma GCC diagnostic push
302# pragma GCC diagnostic ignored "-Wcast-function-type"
303# endif
304#endif
305
307 "register_cli_command",
308 reinterpret_cast<PyCFunction>(bpy_cli_command_register),
309 METH_STATIC | METH_VARARGS | METH_KEYWORDS,
310 bpy_cli_command_register_doc,
311};
313 "unregister_cli_command",
314 static_cast<PyCFunction>(bpy_cli_command_unregister),
315 METH_STATIC | METH_O,
316 bpy_cli_command_unregister_doc,
317};
318
319#ifdef __GNUC__
320# ifdef __clang__
321# pragma clang diagnostic pop
322# else
323# pragma GCC diagnostic pop
324# endif
325#endif
326
328
329} // namespace blender
Blender CLI Generic --command Support.
#define C
Definition RandGen.cpp:29
BPyCommandHandler(const std::string &id, PyObject *py_exec_fn)
int exec(bContext *C, int argc, const char **argv) override
CommandHandler(const std::string &id)
BMesh Iterators.
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
PyDoc_STRVAR(bpy_bm_new_doc, ".. function:: new(*, use_operators=True)\n" "\n" " :param use_operators: Support calling operators in :mod:`bmesh.ops` (uses some " "extra memory per vert/edge/face).\n" " :type use_operators: bool\n" " :return: Return a new, empty BMesh.\n" " :rtype: :class:`bmesh.types.BMesh`\n")
static PyObject * bpy_cli_command_unregister(PyObject *, PyObject *value)
static int bpy_cli_command_exec(bContext *C, PyObject *py_exec_fn, const int argc, const char **argv)
void BKE_blender_cli_command_register(std::unique_ptr< CommandHandler > cmd)
PyMethodDef BPY_cli_command_register_def
static const char * bpy_cli_command_capsule_name_invalid
static void bpy_cli_command_free(PyObject *py_exec_fn)
bool bpy_context_set(struct bContext *C, PyGILState_STATE *gilstate) ATTR_NONNULL(1)
static const char * bpy_cli_command_capsule_name
static PyObject * bpy_cli_command_register(PyObject *, PyObject *args, PyObject *kw)
void bpy_context_clear(struct bContext *C, const PyGILState_STATE *gilstate)
PyMethodDef BPY_cli_command_unregister_def
static PyObject * py_argv_from_bytes(const int argc, const char **argv)
bool BKE_blender_cli_command_unregister(CommandHandler *cmd)
header-only compatibility defines.