Blender V4.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.h"
13
14#include "bpy_capi_utils.hh"
15
16#include "MEM_guardedalloc.h"
17
19
23
24#include "bpy_cli_command.hh" /* Own include. */
25
26static const char *bpy_cli_command_capsule_name = "bpy_cli_command";
27static const char *bpy_cli_command_capsule_name_invalid = "bpy_cli_command<invalid>";
28
29/* -------------------------------------------------------------------- */
36static PyObject *py_argv_from_bytes(const int argc, const char **argv)
37{
38 /* Copy functionality from Python's internal `sys.argv` initialization. */
39 PyConfig config;
40 PyConfig_InitPythonConfig(&config);
41 PyStatus status = PyConfig_SetBytesArgv(&config, argc, (char *const *)argv);
42 PyObject *py_argv = nullptr;
43 if (UNLIKELY(PyStatus_Exception(status))) {
44 PyErr_Format(PyExc_ValueError, "%s", status.err_msg);
45 }
46 else {
47 BLI_assert(argc == config.argv.length);
48 py_argv = PyList_New(config.argv.length);
49 for (Py_ssize_t i = 0; i < config.argv.length; i++) {
50 PyList_SET_ITEM(py_argv, i, PyUnicode_FromWideChar(config.argv.items[i], -1));
51 }
52 }
53 PyConfig_Clear(&config);
54 return py_argv;
55}
56
59/* -------------------------------------------------------------------- */
64 PyObject *py_exec_fn,
65 const int argc,
66 const char **argv)
67{
68 int exit_code = EXIT_FAILURE;
69 PyGILState_STATE gilstate;
70 bpy_context_set(C, &gilstate);
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 (((PySystemExitObject *)error_value)->code != nullptr))
100 {
101 /* When `SystemExit(..)` is raised. */
102 result = ((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 PyErr_Clear();
140 }
141
142 bpy_context_clear(C, &gilstate);
143
144 return exit_code;
145}
146
147static void bpy_cli_command_free(PyObject *py_exec_fn)
148{
149 /* An explicit unregister clears to avoid acquiring a lock. */
150 if (py_exec_fn) {
151 PyGILState_STATE gilstate = PyGILState_Ensure();
152 Py_DECREF(py_exec_fn);
153 PyGILState_Release(gilstate);
154 }
155}
156
159/* -------------------------------------------------------------------- */
164 public:
165 BPyCommandHandler(const std::string &id, PyObject *py_exec_fn)
167 {
168 }
170 {
172 }
173
174 int exec(bContext *C, int argc, const char **argv) override
175 {
176 return bpy_cli_command_exec(C, this->py_exec_fn, argc, argv);
177 }
178
179 PyObject *py_exec_fn = nullptr;
180};
181
184/* -------------------------------------------------------------------- */
189 /* Wrap. */
190 bpy_cli_command_register_doc,
191 ".. method:: register_cli_command(id, execute)\n"
192 "\n"
193 " Register a command, accessible via the (``-c`` / ``--command``) command-line argument.\n"
194 "\n"
195 " :arg id: The command identifier (must pass an ``str.isidentifier`` check).\n"
196 "\n"
197 " If the ``id`` is already registered, a warning is printed and "
198 "the command is inaccessible to prevent accidents invoking the wrong command.\n"
199 " :type id: str\n"
200 " :arg execute: Callback, taking a single list of strings and returns an int.\n"
201 " The arguments are built from all command-line arguments following the command id.\n"
202 " The return value should be 0 for success, 1 on failure "
203 "(specific error codes from the ``os`` module can also be used).\n"
204 " :type execute: callable\n"
205 " :return: The command handle which can be passed to :func:`unregister_cli_command`.\n"
206 " :rtype: capsule\n");
207static PyObject *bpy_cli_command_register(PyObject * /*self*/, PyObject *args, PyObject *kw)
208{
209 PyObject *py_id;
210 PyObject *py_exec_fn;
211
212 static const char *_keywords[] = {
213 "id",
214 "execute",
215 nullptr,
216 };
217 static _PyArg_Parser _parser = {
219 "O!" /* `id` */
220 "O" /* `execute` */
221 ":register_cli_command",
222 _keywords,
223 nullptr,
224 };
225 if (!_PyArg_ParseTupleAndKeywordsFast(args, kw, &_parser, &PyUnicode_Type, &py_id, &py_exec_fn))
226 {
227 return nullptr;
228 }
229 if (!PyUnicode_IsIdentifier(py_id)) {
230 PyErr_SetString(PyExc_ValueError, "The command id is not a valid identifier");
231 return nullptr;
232 }
233 if (!PyCallable_Check(py_exec_fn)) {
234 PyErr_SetString(PyExc_ValueError, "The execute argument must be callable");
235 return nullptr;
236 }
237
238 const char *id = PyUnicode_AsUTF8(py_id);
239
240 std::unique_ptr<CommandHandler> cmd_ptr = std::make_unique<BPyCommandHandler>(
241 std::string(id), Py_NewRef(py_exec_fn));
242 void *cmd_p = cmd_ptr.get();
243
244 BKE_blender_cli_command_register(std::move(cmd_ptr));
245
246 return PyCapsule_New(cmd_p, bpy_cli_command_capsule_name, nullptr);
247}
248
250 /* Wrap. */
251 bpy_cli_command_unregister_doc,
252 ".. method:: unregister_cli_command(handle)\n"
253 "\n"
254 " Unregister a CLI command.\n"
255 "\n"
256 " :arg handle: The return value of :func:`register_cli_command`.\n"
257 " :type handle: capsule\n");
258static PyObject *bpy_cli_command_unregister(PyObject * /*self*/, PyObject *value)
259{
260 if (!PyCapsule_CheckExact(value)) {
261 PyErr_Format(PyExc_TypeError,
262 "Expected a capsule returned from register_cli_command(...), found a: %.200s",
263 Py_TYPE(value)->tp_name);
264 return nullptr;
265 }
266
267 BPyCommandHandler *cmd = static_cast<BPyCommandHandler *>(
268 PyCapsule_GetPointer(value, bpy_cli_command_capsule_name));
269 if (cmd == nullptr) {
270 const char *capsule_name = PyCapsule_GetName(value);
271 if (capsule_name == bpy_cli_command_capsule_name_invalid) {
272 PyErr_SetString(PyExc_ValueError, "The command has already been removed");
273 }
274 else {
275 PyErr_Format(PyExc_ValueError,
276 "Unrecognized capsule ID \"%.200s\"",
277 capsule_name ? capsule_name : "<null>");
278 }
279 return nullptr;
280 }
281
282 /* Don't acquire the GIL when un-registering. */
283 Py_CLEAR(cmd->py_exec_fn);
284
285 /* Don't allow removing again. */
286 PyCapsule_SetName(value, bpy_cli_command_capsule_name_invalid);
287
289
290 Py_RETURN_NONE;
291}
292
293#if (defined(__GNUC__) && !defined(__clang__))
294# pragma GCC diagnostic push
295# pragma GCC diagnostic ignored "-Wcast-function-type"
296#endif
297
299 "register_cli_command",
300 (PyCFunction)bpy_cli_command_register,
301 METH_STATIC | METH_VARARGS | METH_KEYWORDS,
302 bpy_cli_command_register_doc,
303};
305 "unregister_cli_command",
306 (PyCFunction)bpy_cli_command_unregister,
307 METH_STATIC | METH_O,
308 bpy_cli_command_unregister_doc,
309};
310
311#if (defined(__GNUC__) && !defined(__clang__))
312# pragma GCC diagnostic pop
313#endif
314
Blender CLI Generic --command Support.
bool BKE_blender_cli_command_unregister(CommandHandler *cmd)
void BKE_blender_cli_command_register(std::unique_ptr< CommandHandler > cmd)
#define BLI_assert(a)
Definition BLI_assert.h:50
#define UNLIKELY(x)
Read Guarded memory(de)allocation.
void bpy_context_clear(struct bContext *C, const PyGILState_STATE *gilstate)
void bpy_context_set(struct bContext *C, PyGILState_STATE *gilstate)
PyMethodDef BPY_cli_command_register_def
static PyObject * py_argv_from_bytes(const int argc, const char **argv)
static void bpy_cli_command_free(PyObject *py_exec_fn)
static const char * bpy_cli_command_capsule_name
static int bpy_cli_command_exec(bContext *C, PyObject *py_exec_fn, const int argc, const char **argv)
PyDoc_STRVAR(bpy_cli_command_register_doc, ".. method:: register_cli_command(id, execute)\n" "\n" " Register a command, accessible via the (``-c`` / ``--command``) command-line argument.\n" "\n" " :arg id: The command identifier (must pass an ``str.isidentifier`` check).\n" "\n" " If the ``id`` is already registered, a warning is printed and " "the command is inaccessible to prevent accidents invoking the wrong command.\n" " :type id: str\n" " :arg execute: Callback, taking a single list of strings and returns an int.\n" " The arguments are built from all command-line arguments following the command id.\n" " The return value should be 0 for success, 1 on failure " "(specific error codes from the ``os`` module can also be used).\n" " :type execute: callable\n" " :return: The command handle which can be passed to :func:`unregister_cli_command`.\n" " :rtype: capsule\n")
static PyObject * bpy_cli_command_register(PyObject *, PyObject *args, PyObject *kw)
static PyObject * bpy_cli_command_unregister(PyObject *, PyObject *value)
static const char * bpy_cli_command_capsule_name_invalid
PyMethodDef BPY_cli_command_unregister_def
int exec(bContext *C, int argc, const char **argv) override
BPyCommandHandler(const std::string &id, PyObject *py_exec_fn)
~BPyCommandHandler() override
header-only compatibility defines.
#define PY_ARG_PARSER_HEAD_COMPAT()
header-only utilities