generator.py 58.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
#!/usr/bin/python -u
#
# generate python wrappers from the XML API description
#

functions = {}
enums = {} # { enumType: { enumConstant: enumValue } }

import os
import sys
import string
12
import re
13 14 15 16

if __name__ == "__main__":
    # launched as a script
    srcPref = os.path.dirname(sys.argv[0])
17 18 19 20 21
    if len(sys.argv) > 1:
        python = sys.argv[1]
    else:
        print "Python binary not specified"
        sys.exit(1)
22 23 24 25 26 27 28
else:
    # imported
    srcPref = os.path.dirname(__file__)

#######################################################################
#
#  That part if purely the API acquisition phase from the
29
#  libvirt API description
30 31 32
#
#######################################################################
import os
33
import xml.sax
34 35 36

debug = 0

37 38 39
def getparser():
    # Attach parser to an unmarshalling object. return both objects.
    target = docParser()
40 41 42
    parser = xml.sax.make_parser()
    parser.setContentHandler(target)
    return parser, target
43

44
class docParser(xml.sax.handler.ContentHandler):
45 46 47 48 49
    def __init__(self):
        self._methodname = None
        self._data = []
        self.in_function = 0

50 51 52 53
        self.startElement = self.start
        self.endElement = self.end
        self.characters = self.data

54 55 56 57 58 59 60 61 62 63 64 65
    def close(self):
        if debug:
            print "close"

    def getmethodname(self):
        return self._methodname

    def data(self, text):
        if debug:
            print "data %s" % text
        self._data.append(text)

66 67 68 69 70
    def cdata(self, text):
        if debug:
            print "data %s" % text
        self._data.append(text)

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
    def start(self, tag, attrs):
        if debug:
            print "start %s, %s" % (tag, attrs)
        if tag == 'function':
            self._data = []
            self.in_function = 1
            self.function = None
            self.function_cond = None
            self.function_args = []
            self.function_descr = None
            self.function_return = None
            self.function_file = None
            if attrs.has_key('name'):
                self.function = attrs['name']
            if attrs.has_key('file'):
                self.function_file = attrs['file']
        elif tag == 'cond':
            self._data = []
        elif tag == 'info':
            self._data = []
        elif tag == 'arg':
            if self.in_function == 1:
                self.function_arg_name = None
                self.function_arg_type = None
                self.function_arg_info = None
                if attrs.has_key('name'):
                    self.function_arg_name = attrs['name']
98 99
                    if self.function_arg_name == 'from':
                        self.function_arg_name = 'frm'
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
                if attrs.has_key('type'):
                    self.function_arg_type = attrs['type']
                if attrs.has_key('info'):
                    self.function_arg_info = attrs['info']
        elif tag == 'return':
            if self.in_function == 1:
                self.function_return_type = None
                self.function_return_info = None
                self.function_return_field = None
                if attrs.has_key('type'):
                    self.function_return_type = attrs['type']
                if attrs.has_key('info'):
                    self.function_return_info = attrs['info']
                if attrs.has_key('field'):
                    self.function_return_field = attrs['field']
        elif tag == 'enum':
            enum(attrs['type'],attrs['name'],attrs['value'])

    def end(self, tag):
        if debug:
            print "end %s" % tag
        if tag == 'function':
            if self.function != None:
                function(self.function, self.function_descr,
                         self.function_return, self.function_args,
                         self.function_file, self.function_cond)
                self.in_function = 0
        elif tag == 'arg':
            if self.in_function == 1:
                self.function_args.append([self.function_arg_name,
                                           self.function_arg_type,
                                           self.function_arg_info])
        elif tag == 'return':
            if self.in_function == 1:
                self.function_return = [self.function_return_type,
                                        self.function_return_info,
                                        self.function_return_field]
        elif tag == 'info':
            str = ''
            for c in self._data:
                str = str + c
            if self.in_function == 1:
                self.function_descr = str
        elif tag == 'cond':
            str = ''
            for c in self._data:
                str = str + c
            if self.in_function == 1:
                self.function_cond = str
149 150


151 152 153 154 155 156
def function(name, desc, ret, args, file, cond):
    functions[name] = (desc, ret, args, file, cond)

def enum(type, name, value):
    if not enums.has_key(type):
        enums[type] = {}
157 158 159 160 161 162 163 164 165 166 167 168
    if value == 'VIR_TYPED_PARAM_INT':
        value = 1
    elif value == 'VIR_TYPED_PARAM_UINT':
        value = 2
    elif value == 'VIR_TYPED_PARAM_LLONG':
        value = 3
    elif value == 'VIR_TYPED_PARAM_ULLONG':
        value = 4
    elif value == 'VIR_TYPED_PARAM_DOUBLE':
        value = 5
    elif value == 'VIR_TYPED_PARAM_BOOLEAN':
        value = 6
169 170 171 172 173 174
    elif value == 'VIR_DOMAIN_AFFECT_CURRENT':
        value = 0
    elif value == 'VIR_DOMAIN_AFFECT_LIVE':
        value = 1
    elif value == 'VIR_DOMAIN_AFFECT_CONFIG':
        value = 2
175 176 177 178 179 180 181 182 183
    enums[type][name] = value

#######################################################################
#
#  Some filtering rukes to drop functions/types which should not
#  be exposed as-is on the Python interface
#
#######################################################################

184
functions_failed = []
185
functions_skipped = [
186
    "virConnectListDomains",
187
]
188

189 190 191 192
skipped_modules = {
}

skipped_types = {
193
#    'int *': "usually a return type",
194
     'virConnectDomainEventCallback': "No function types in python",
195
     'virConnectDomainEventGenericCallback': "No function types in python",
196
     'virConnectDomainEventRTCChangeCallback': "No function types in python",
197
     'virConnectDomainEventWatchdogCallback': "No function types in python",
198
     'virConnectDomainEventIOErrorCallback': "No function types in python",
199
     'virConnectDomainEventGraphicsCallback': "No function types in python",
200
     'virEventAddHandleFunc': "No function types in python",
201 202 203 204 205 206 207 208 209 210 211 212
}

#######################################################################
#
#  Table of remapping to/from the python type or class to the C
#  counterpart.
#
#######################################################################

py_types = {
    'void': (None, None, None, None),
    'int':  ('i', None, "int", "int"),
213
    'long':  ('l', None, "long", "long"),
214 215
    'double':  ('d', None, "double", "double"),
    'unsigned int':  ('i', None, "int", "int"),
216
    'unsigned long':  ('l', None, "long", "long"),
217
    'unsigned long long':  ('l', None, "longlong", "long long"),
218 219 220
    'unsigned char *':  ('z', None, "charPtr", "char *"),
    'char *':  ('z', None, "charPtr", "char *"),
    'const char *':  ('z', None, "charPtrConst", "const char *"),
221

222 223 224 225
    'virDomainPtr':  ('O', "virDomain", "virDomainPtr", "virDomainPtr"),
    'const virDomainPtr':  ('O', "virDomain", "virDomainPtr", "virDomainPtr"),
    'virDomain *':  ('O', "virDomain", "virDomainPtr", "virDomainPtr"),
    'const virDomain *':  ('O', "virDomain", "virDomainPtr", "virDomainPtr"),
226

227 228 229 230
    'virNetworkPtr':  ('O', "virNetwork", "virNetworkPtr", "virNetworkPtr"),
    'const virNetworkPtr':  ('O', "virNetwork", "virNetworkPtr", "virNetworkPtr"),
    'virNetwork *':  ('O', "virNetwork", "virNetworkPtr", "virNetworkPtr"),
    'const virNetwork *':  ('O', "virNetwork", "virNetworkPtr", "virNetworkPtr"),
231

232 233 234 235 236
    'virInterfacePtr':  ('O', "virInterface", "virInterfacePtr", "virInterfacePtr"),
    'const virInterfacePtr':  ('O', "virInterface", "virInterfacePtr", "virInterfacePtr"),
    'virInterface *':  ('O', "virInterface", "virInterfacePtr", "virInterfacePtr"),
    'const virInterface *':  ('O', "virInterface", "virInterfacePtr", "virInterfacePtr"),

237 238 239 240 241 242 243 244 245 246
    'virStoragePoolPtr':  ('O', "virStoragePool", "virStoragePoolPtr", "virStoragePoolPtr"),
    'const virStoragePoolPtr':  ('O', "virStoragePool", "virStoragePoolPtr", "virStoragePoolPtr"),
    'virStoragePool *':  ('O', "virStoragePool", "virStoragePoolPtr", "virStoragePoolPtr"),
    'const virStoragePool *':  ('O', "virStoragePool", "virStoragePoolPtr", "virStoragePoolPtr"),

    'virStorageVolPtr':  ('O', "virStorageVol", "virStorageVolPtr", "virStorageVolPtr"),
    'const virStorageVolPtr':  ('O', "virStorageVol", "virStorageVolPtr", "virStorageVolPtr"),
    'virStorageVol *':  ('O', "virStorageVol", "virStorageVolPtr", "virStorageVolPtr"),
    'const virStorageVol *':  ('O', "virStorageVol", "virStorageVolPtr", "virStorageVolPtr"),

247 248 249 250
    'virConnectPtr':  ('O', "virConnect", "virConnectPtr", "virConnectPtr"),
    'const virConnectPtr':  ('O', "virConnect", "virConnectPtr", "virConnectPtr"),
    'virConnect *':  ('O', "virConnect", "virConnectPtr", "virConnectPtr"),
    'const virConnect *':  ('O', "virConnect", "virConnectPtr", "virConnectPtr"),
251 252 253 254 255

    'virNodeDevicePtr':  ('O', "virNodeDevice", "virNodeDevicePtr", "virNodeDevicePtr"),
    'const virNodeDevicePtr':  ('O', "virNodeDevice", "virNodeDevicePtr", "virNodeDevicePtr"),
    'virNodeDevice *':  ('O', "virNodeDevice", "virNodeDevicePtr", "virNodeDevicePtr"),
    'const virNodeDevice *':  ('O', "virNodeDevice", "virNodeDevicePtr", "virNodeDevicePtr"),
256 257 258 259 260

    'virSecretPtr':  ('O', "virSecret", "virSecretPtr", "virSecretPtr"),
    'const virSecretPtr':  ('O', "virSecret", "virSecretPtr", "virSecretPtr"),
    'virSecret *':  ('O', "virSecret", "virSecretPtr", "virSecretPtr"),
    'const virSecret *':  ('O', "virSecret", "virSecretPtr", "virSecretPtr"),
261

262 263 264 265 266
    'virNWFilterPtr':  ('O', "virNWFilter", "virNWFilterPtr", "virNWFilterPtr"),
    'const virNWFilterPtr':  ('O', "virNWFilter", "virNWFilterPtr", "virNWFilterPtr"),
    'virNWFilter *':  ('O', "virNWFilter", "virNWFilterPtr", "virNWFilterPtr"),
    'const virNWFilter *':  ('O', "virNWFilter", "virNWFilterPtr", "virNWFilterPtr"),

267 268 269 270
    'virStreamPtr':  ('O', "virStream", "virStreamPtr", "virStreamPtr"),
    'const virStreamPtr':  ('O', "virStream", "virStreamPtr", "virStreamPtr"),
    'virStream *':  ('O', "virStream", "virStreamPtr", "virStreamPtr"),
    'const virStream *':  ('O', "virStream", "virStreamPtr", "virStreamPtr"),
C
Chris Lalancette 已提交
271 272

    'virDomainSnapshotPtr':  ('O', "virDomainSnapshot", "virDomainSnapshotPtr", "virDomainSnapshotPtr"),
273 274 275
    'const virDomainSnapshotPtr':  ('O', "virDomainSnapshot", "virDomainSnapshotPtr", "virDomainSnapshotPtr"),
    'virDomainSnapshot *':  ('O', "virDomainSnapshot", "virDomainSnapshotPtr", "virDomainSnapshotPtr"),
    'const virDomainSnapshot *':  ('O', "virDomainSnapshot", "virDomainSnapshotPtr", "virDomainSnapshotPtr"),
276 277 278 279 280 281 282 283 284 285 286 287
}

py_return_types = {
}

unknown_types = {}

foreign_encoding_args = (
)

#######################################################################
#
288 289
#  This part writes the C <-> Python stubs libvirt.[ch] and
#  the table libvirt-export.c to add when registrering the Python module
290 291 292 293 294 295
#
#######################################################################

# Class methods which are written by hand in libvir.c but the Python-level
# code is still automatically generated (so they are not in skip_function()).
skip_impl = (
T
Taizo ITO 已提交
296
    'virConnectGetVersion',
297
    'virConnectGetLibVersion',
298
    'virConnectListDomainsID',
299
    'virConnectListDefinedDomains',
300 301
    'virConnectListNetworks',
    'virConnectListDefinedNetworks',
302
    'virConnectListSecrets',
303
    'virConnectListInterfaces',
304 305 306 307
    'virConnectListStoragePools',
    'virConnectListDefinedStoragePools',
    'virConnectListStorageVols',
    'virConnectListDefinedStorageVols',
308
    'virConnectListDefinedInterfaces',
309
    'virConnectListNWFilters',
310
    'virDomainSnapshotListNames',
311 312
    'virConnGetLastError',
    'virGetLastError',
313
    'virDomainGetInfo',
J
Jiri Denemark 已提交
314
    'virDomainGetState',
315
    'virDomainGetBlockInfo',
316
    'virDomainGetJobInfo',
317
    'virNodeGetInfo',
318
    'virDomainGetUUID',
319
    'virDomainGetUUIDString',
320
    'virDomainLookupByUUID',
321
    'virNetworkGetUUID',
322
    'virNetworkGetUUIDString',
323
    'virNetworkLookupByUUID',
324 325
    'virDomainGetAutostart',
    'virNetworkGetAutostart',
326 327
    'virDomainBlockStats',
    'virDomainInterfaceStats',
328
    'virDomainMemoryStats',
329
    'virNodeGetCellsFreeMemory',
330 331
    'virDomainGetSchedulerType',
    'virDomainGetSchedulerParameters',
332
    'virDomainGetSchedulerParametersFlags',
333
    'virDomainSetSchedulerParameters',
334
    'virDomainSetSchedulerParametersFlags',
335 336
    'virDomainSetBlkioParameters',
    'virDomainGetBlkioParameters',
337 338
    'virDomainSetMemoryParameters',
    'virDomainGetMemoryParameters',
339 340
    'virDomainGetVcpus',
    'virDomainPinVcpu',
341 342
    'virSecretGetValue',
    'virSecretSetValue',
343 344 345
    'virSecretGetUUID',
    'virSecretGetUUIDString',
    'virSecretLookupByUUID',
346 347 348
    'virNWFilterGetUUID',
    'virNWFilterGetUUIDString',
    'virNWFilterLookupByUUID',
349 350
    'virStreamRecv',
    'virStreamSend',
351
    'virStoragePoolGetUUID',
352
    'virStoragePoolGetUUIDString',
353 354 355 356 357
    'virStoragePoolLookupByUUID',
    'virStoragePoolGetInfo',
    'virStorageVolGetInfo',
    'virStoragePoolGetAutostart',
    'virStoragePoolListVolumes',
358 359
    'virDomainBlockPeek',
    'virDomainMemoryPeek',
360
    'virEventRegisterImpl',
361 362
    'virNodeListDevices',
    'virNodeDeviceListCaps',
J
Jiri Denemark 已提交
363
    'virConnectBaselineCPU',
364
    'virDomainRevertToSnapshot',
365
    'virDomainSendKey',
M
Minoru Usui 已提交
366
    'virNodeGetCPUStats',
367
    'virNodeGetMemoryStats',
368 369
    'virDomainBlockPull',
    'virDomainGetBlockPullInfo',
370 371
)

372 373 374 375 376 377 378 379 380 381 382 383 384 385

# These are functions which the generator skips completly - no python
# or C code is generated. Generally should not be used for any more
# functions than those already listed
skip_function = (
    'virConnectListDomains', # Python API is called virConectListDomainsID for unknown reasons
    'virConnSetErrorFunc', # Not used in Python API  XXX is this a bug ?
    'virResetError', # Not used in Python API  XXX is this a bug ?
    'virGetVersion', # Python C code is manually written
    'virSetErrorFunc', # Python API is called virRegisterErrorHandler for unknown reasons
    'virConnCopyLastError', # Python API is called virConnGetLastError instead
    'virCopyLastError', # Python API is called virGetLastError instead
    'virConnectOpenAuth', # Python C code is manually written
    'virDefaultErrorFunc', # Python virErrorFuncHandler impl calls this from C
386 387
    'virDomainGetSecurityLabel', # Needs investigation...
    'virNodeGetSecurityModel', # Needs investigation...
388 389
    'virConnectDomainEventRegister',   # overridden in virConnect.py
    'virConnectDomainEventDeregister', # overridden in virConnect.py
390 391
    'virConnectDomainEventRegisterAny',   # overridden in virConnect.py
    'virConnectDomainEventDeregisterAny', # overridden in virConnect.py
392 393
    'virSaveLastError', # We have our own python error wrapper
    'virFreeError', # Only needed if we use virSaveLastError
394 395 396 397 398
    'virStreamEventAddCallback',
    'virStreamRecvAll',
    'virStreamSendAll',
    'virStreamRef',
    'virStreamFree',
399 400 401 402 403 404 405 406

    # These have no use for bindings users.
    "virConnectRef",
    "virDomainRef",
    "virInterfaceRef",
    "virNetworkRef",
    "virNodeDeviceRef",
    "virSecretRef",
407
    "virNWFilterRef",
408 409
    "virStoragePoolRef",
    "virStorageVolRef",
410 411 412 413 414 415 416 417

    # This functions shouldn't be called via the bindings (and even the docs
    # contain an explicit warning to that effect). The equivalent should be
    # implemented in pure python for each class
    "virDomainGetConnect",
    "virInterfaceGetConnect",
    "virNetworkGetConnect",
    "virSecretGetConnect",
418
    "virNWFilterGetConnect",
419 420
    "virStoragePoolGetConnect",
    "virStorageVolGetConnect",
421 422
)

423 424 425 426
function_skip_index_one = (
    "virDomainRevertToSnapshot",
)

427 428 429 430 431 432 433 434 435 436 437 438 439 440 441

def print_function_wrapper(name, output, export, include):
    global py_types
    global unknown_types
    global functions
    global skipped_modules

    try:
        (desc, ret, args, file, cond) = functions[name]
    except:
        print "failed to get function %s infos"
        return

    if skipped_modules.has_key(file):
        return 0
442
    if name in skip_function:
443 444
        return 0
    if name in skip_impl:
445 446
        # Don't delete the function entry in the caller.
        return 1
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461

    c_call = "";
    format=""
    format_args=""
    c_args=""
    c_return=""
    c_convert=""
    num_bufs=0
    for arg in args:
        # This should be correct
        if arg[1][0:6] == "const ":
            arg[1] = arg[1][6:]
        c_args = c_args + "    %s %s;\n" % (arg[1], arg[0])
        if py_types.has_key(arg[1]):
            (f, t, n, c) = py_types[arg[1]]
462 463
            if (f == 'z') and (name in foreign_encoding_args) and (num_bufs == 0):
                f = 't#'
464 465 466 467 468 469 470 471 472 473
            if f != None:
                format = format + f
            if t != None:
                format_args = format_args + ", &pyobj_%s" % (arg[0])
                c_args = c_args + "    PyObject *pyobj_%s;\n" % (arg[0])
                c_convert = c_convert + \
                   "    %s = (%s) Py%s_Get(pyobj_%s);\n" % (arg[0],
                   arg[1], t, arg[0]);
            else:
                format_args = format_args + ", &%s" % (arg[0])
474 475 476 477
            if f == 't#':
                format_args = format_args + ", &py_buffsize%d" % num_bufs
                c_args = c_args + "    int py_buffsize%d;\n" % num_bufs
                num_bufs = num_bufs + 1
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
            if c_call != "":
                c_call = c_call + ", ";
            c_call = c_call + "%s" % (arg[0])
        else:
            if skipped_types.has_key(arg[1]):
                return 0
            if unknown_types.has_key(arg[1]):
                lst = unknown_types[arg[1]]
                lst.append(name)
            else:
                unknown_types[arg[1]] = [name]
            return -1
    if format != "":
        format = format + ":%s" % (name)

    if ret[0] == 'void':
        if file == "python_accessor":
495 496 497 498 499 500 501 502
            if args[1][1] == "char *":
                c_call = "\n    free(%s->%s);\n" % (
                                 args[0][0], args[1][0], args[0][0], args[1][0])
                c_call = c_call + "    %s->%s = (%s)strdup((const xmlChar *)%s);\n" % (args[0][0],
                                 args[1][0], args[1][1], args[1][0])
            else:
                c_call = "\n    %s->%s = %s;\n" % (args[0][0], args[1][0],
                                                   args[1][0])
503 504 505 506 507 508 509 510 511 512
        else:
            c_call = "\n    %s(%s);\n" % (name, c_call);
        ret_convert = "    Py_INCREF(Py_None);\n    return(Py_None);\n"
    elif py_types.has_key(ret[0]):
        (f, t, n, c) = py_types[ret[0]]
        c_return = "    %s c_retval;\n" % (ret[0])
        if file == "python_accessor" and ret[2] != None:
            c_call = "\n    c_retval = %s->%s;\n" % (args[0][0], ret[2])
        else:
            c_call = "\n    c_retval = %s(%s);\n" % (name, c_call);
513
        ret_convert = "    py_retval = libvirt_%sWrap((%s) c_retval);\n" % (n,c)
514 515 516 517 518
        ret_convert = ret_convert + "    return(py_retval);\n"
    elif py_return_types.has_key(ret[0]):
        (f, t, n, c) = py_return_types[ret[0]]
        c_return = "    %s c_retval;\n" % (ret[0])
        c_call = "\n    c_retval = %s(%s);\n" % (name, c_call);
519
        ret_convert = "    py_retval = libvirt_%sWrap((%s) c_retval);\n" % (n,c)
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
        ret_convert = ret_convert + "    return(py_retval);\n"
    else:
        if skipped_types.has_key(ret[0]):
            return 0
        if unknown_types.has_key(ret[0]):
            lst = unknown_types[ret[0]]
            lst.append(name)
        else:
            unknown_types[ret[0]] = [name]
        return -1

    if cond != None and cond != "":
        include.write("#if %s\n" % cond)
        export.write("#if %s\n" % cond)
        output.write("#if %s\n" % cond)

    include.write("PyObject * ")
537
    include.write("libvirt_%s(PyObject *self, PyObject *args);\n" % (name));
538

539
    export.write("    { (char *)\"%s\", libvirt_%s, METH_VARARGS, NULL },\n" %
540 541 542 543
                 (name, name))

    if file == "python":
        # Those have been manually generated
544 545 546 547
        if cond != None and cond != "":
            include.write("#endif\n");
            export.write("#endif\n");
            output.write("#endif\n");
548 549 550
        return 1
    if file == "python_accessor" and ret[0] != "void" and ret[2] is None:
        # Those have been manually generated
551 552 553 554
        if cond != None and cond != "":
            include.write("#endif\n");
            export.write("#endif\n");
            output.write("#endif\n");
555 556 557
        return 1

    output.write("PyObject *\n")
558
    output.write("libvirt_%s(PyObject *self ATTRIBUTE_UNUSED," % (name))
559 560
    output.write(" PyObject *args")
    if format == "":
561
        output.write(" ATTRIBUTE_UNUSED")
562 563 564 565 566 567 568 569 570 571 572 573 574
    output.write(") {\n")
    if ret[0] != 'void':
        output.write("    PyObject *py_retval;\n")
    if c_return != "":
        output.write(c_return)
    if c_args != "":
        output.write(c_args)
    if format != "":
        output.write("\n    if (!PyArg_ParseTuple(args, (char *)\"%s\"%s))\n" %
                     (format, format_args))
        output.write("        return(NULL);\n")
    if c_convert != "":
        output.write(c_convert)
575 576 577 578

    output.write("LIBVIRT_BEGIN_ALLOW_THREADS;\n");
    output.write(c_call);
    output.write("LIBVIRT_END_ALLOW_THREADS;\n");
579 580 581 582 583 584 585 586 587 588 589 590 591 592
    output.write(ret_convert)
    output.write("}\n\n")
    if cond != None and cond != "":
        include.write("#endif /* %s */\n" % cond)
        export.write("#endif /* %s */\n" % cond)
        output.write("#endif /* %s */\n" % cond)
    return 1

def buildStubs():
    global py_types
    global py_return_types
    global unknown_types

    try:
593 594 595 596 597
        f = open(os.path.join(srcPref,"libvirt-api.xml"))
        data = f.read()
        (parser, target)  = getparser()
        parser.feed(data)
        parser.close()
598
    except IOError, msg:
599 600 601 602 603 604 605 606 607
        try:
            f = open(os.path.join(srcPref,"..","docs","libvirt-api.xml"))
            data = f.read()
            (parser, target)  = getparser()
            parser.feed(data)
            parser.close()
        except IOError, msg:
            print file, ":", msg
            sys.exit(1)
608 609

    n = len(functions.keys())
610
    print "Found %d functions in libvirt-api.xml" % (n)
611 612 613

    py_types['pythonObject'] = ('O', "pythonObject", "pythonObject", "pythonObject")
    try:
614 615 616 617 618
        f = open(os.path.join(srcPref,"libvirt-override-api.xml"))
        data = f.read()
        (parser, target)  = getparser()
        parser.feed(data)
        parser.close()
619
    except IOError, msg:
620
        print file, ":", msg
621 622


623
    print "Found %d functions in libvirt-override-api.xml" % (
624
          len(functions.keys()) - n)
625 626 627 628
    nb_wrap = 0
    failed = 0
    skipped = 0

629
    include = open("libvirt.h", "w")
630
    include.write("/* Generated */\n\n")
631
    export = open("libvirt-export.c", "w")
632
    export.write("/* Generated */\n\n")
633
    wrapper = open("libvirt.c", "w")
634 635
    wrapper.write("/* Generated */\n\n")
    wrapper.write("#include <Python.h>\n")
636
    wrapper.write("#include <libvirt/libvirt.h>\n")
637 638
    wrapper.write("#include \"typewrappers.h\"\n")
    wrapper.write("#include \"libvirt.h\"\n\n")
639
    for function in functions.keys():
640 641 642 643 644 645 646 647 648 649 650
        ret = print_function_wrapper(function, wrapper, export, include)
        if ret < 0:
            failed = failed + 1
            functions_failed.append(function)
            del functions[function]
        if ret == 0:
            skipped = skipped + 1
            functions_skipped.append(function)
            del functions[function]
        if ret == 1:
            nb_wrap = nb_wrap + 1
651 652 653 654
    include.close()
    export.close()
    wrapper.close()

655 656
    print "Generated %d wrapper functions" % nb_wrap

657 658
    print "Missing type converters: "
    for type in unknown_types.keys():
659
        print "%s:%d " % (type, len(unknown_types[type])),
660 661
    print

662 663 664 665 666 667 668
    for f in functions_failed:
        print "ERROR: failed %s" % f

    if failed > 0:
        return -1
    return 0

669 670 671 672 673 674 675 676 677 678 679 680
#######################################################################
#
#  This part writes part of the Python front-end classes based on
#  mapping rules between types and classes and also based on function
#  renaming to get consistent function names at the Python level
#
#######################################################################

#
# The type automatically remapped to generated classes
#
classes_type = {
681 682 683 684
    "virDomainPtr": ("._o", "virDomain(self,_obj=%s)", "virDomain"),
    "virDomain *": ("._o", "virDomain(self, _obj=%s)", "virDomain"),
    "virNetworkPtr": ("._o", "virNetwork(self, _obj=%s)", "virNetwork"),
    "virNetwork *": ("._o", "virNetwork(self, _obj=%s)", "virNetwork"),
685 686
    "virInterfacePtr": ("._o", "virInterface(self, _obj=%s)", "virInterface"),
    "virInterface *": ("._o", "virInterface(self, _obj=%s)", "virInterface"),
687 688 689 690
    "virStoragePoolPtr": ("._o", "virStoragePool(self, _obj=%s)", "virStoragePool"),
    "virStoragePool *": ("._o", "virStoragePool(self, _obj=%s)", "virStoragePool"),
    "virStorageVolPtr": ("._o", "virStorageVol(self, _obj=%s)", "virStorageVol"),
    "virStorageVol *": ("._o", "virStorageVol(self, _obj=%s)", "virStorageVol"),
691 692
    "virNodeDevicePtr": ("._o", "virNodeDevice(self, _obj=%s)", "virNodeDevice"),
    "virNodeDevice *": ("._o", "virNodeDevice(self, _obj=%s)", "virNodeDevice"),
693 694
    "virSecretPtr": ("._o", "virSecret(self, _obj=%s)", "virSecret"),
    "virSecret *": ("._o", "virSecret(self, _obj=%s)", "virSecret"),
695 696
    "virNWFilterPtr": ("._o", "virNWFilter(self, _obj=%s)", "virNWFilter"),
    "virNWFilter *": ("._o", "virNWFilter(self, _obj=%s)", "virNWFilter"),
697 698
    "virStreamPtr": ("._o", "virStream(self, _obj=%s)", "virStream"),
    "virStream *": ("._o", "virStream(self, _obj=%s)", "virStream"),
699 700
    "virConnectPtr": ("._o", "virConnect(_obj=%s)", "virConnect"),
    "virConnect *": ("._o", "virConnect(_obj=%s)", "virConnect"),
701 702
    "virDomainSnapshotPtr": ("._o", "virDomainSnapshot(self,_obj=%s)", "virDomainSnapshot"),
    "virDomainSnapshot *": ("._o", "virDomainSnapshot(self, _obj=%s)", "virDomainSnapshot"),
703 704 705 706 707
}

converter_type = {
}

708 709
primary_classes = ["virDomain", "virNetwork", "virInterface",
                   "virStoragePool", "virStorageVol",
710
                   "virConnect", "virNodeDevice", "virSecret",
711
                   "virNWFilter", "virStream", "virDomainSnapshot"]
712 713 714 715 716

classes_ancestor = {
}
classes_destructors = {
    "virDomain": "virDomainFree",
717
    "virNetwork": "virNetworkFree",
718
    "virInterface": "virInterfaceFree",
719 720
    "virStoragePool": "virStoragePoolFree",
    "virStorageVol": "virStorageVolFree",
721
    "virNodeDevice" : "virNodeDeviceFree",
722
    "virSecret": "virSecretFree",
723
    "virNWFilter": "virNWFilterFree",
724
    "virDomainSnapshot": "virDomainSnapshotFree",
725 726
    # We hand-craft __del__ for this one
    #"virStream": "virStreamFree",
727 728
}

729
class_skip_connect_impl = {
730 731
    "virConnect" : True,
    "virDomainSnapshot": True,
732 733
}

734 735 736
class_domain_impl = {
    "virDomainSnapshot": True,
}
737

738
functions_noexcept = {
739 740
    'virDomainGetID': True,
    'virDomainGetName': True,
741
    'virNetworkGetName': True,
742
    'virInterfaceGetName': True,
743 744 745
    'virStoragePoolGetName': True,
    'virStorageVolGetName': True,
    'virStorageVolGetkey': True,
746 747
    'virNodeDeviceGetName': True,
    'virNodeDeviceGetParent': True,
748 749
    'virSecretGetUsageType': True,
    'virSecretGetUsageID': True,
750
    'virNWFilterGetName': True,
751 752 753 754 755 756 757 758 759
}

reference_keepers = {
}

function_classes = {}

function_classes["None"] = []

760
function_post = {}
761

762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
# Functions returning an integral type which need special rules to
# check for errors and raise exceptions.
functions_int_exception_test = {
    'virDomainGetMaxMemory': "%s == 0",
}
functions_int_default_test = "%s == -1"

def is_integral_type (name):
    return not re.search ("^(unsigned)? ?(int|long)$", name) is None

# Functions returning lists which need special rules to check for errors
# and raise exceptions.
functions_list_exception_test = {
}
functions_list_default_test = "%s is None"

def is_list_type (name):
779 780 781 782
    whitelist = [ "virDomainBlockStats",
                  "virDomainInterfaceStats" ]

    return name[-1:] == "*" or name in whitelist
783

784
def nameFixup(name, classe, type, file):
785
    # avoid a desastrous clash
786 787 788 789 790 791
    listname = classe + "List"
    ll = len(listname)
    l = len(classe)
    if name[0:l] == listname:
        func = name[l:]
        func = string.lower(func[0:1]) + func[1:]
792 793 794
    elif name[0:16] == "virNetworkDefine":
        func = name[3:]
        func = string.lower(func[0:1]) + func[1:]
795 796 797
    elif name[0:19] == "virNetworkCreateXML":
        func = name[3:]
        func = string.lower(func[0:1]) + func[1:]
798
    elif name[0:16] == "virNetworkLookup":
799 800
        func = name[3:]
        func = string.lower(func[0:1]) + func[1:]
801 802 803 804 805 806 807 808 809
    elif name[0:18] == "virInterfaceDefine":
        func = name[3:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:21] == "virInterfaceCreateXML":
        func = name[3:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:18] == "virInterfaceLookup":
        func = name[3:]
        func = string.lower(func[0:1]) + func[1:]
810 811 812 813 814 815
    elif name[0:15] == "virSecretDefine":
        func = name[3:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:15] == "virSecretLookup":
        func = name[3:]
        func = string.lower(func[0:1]) + func[1:]
816 817 818 819 820 821
    elif name[0:17] == "virNWFilterDefine":
        func = name[3:]
        func = string.lower(func[0:3]) + func[3:]
    elif name[0:17] == "virNWFilterLookup":
        func = name[3:]
        func = string.lower(func[0:3]) + func[3:]
822 823 824
    elif name[0:20] == "virStoragePoolDefine":
        func = name[3:]
        func = string.lower(func[0:1]) + func[1:]
825 826 827
    elif name[0:23] == "virStoragePoolCreateXML":
        func = name[3:]
        func = string.lower(func[0:1]) + func[1:]
828 829 830 831 832 833 834 835 836
    elif name[0:20] == "virStoragePoolLookup":
        func = name[3:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:19] == "virStorageVolDefine":
        func = name[3:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:19] == "virStorageVolLookup":
        func = name[3:]
        func = string.lower(func[0:1]) + func[1:]
837 838 839
    elif name[0:12] == "virDomainGet":
        func = name[12:]
        func = string.lower(func[0:1]) + func[1:]
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
    elif name[0:29] == "virDomainSnapshotLookupByName":
        func = name[9:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:26] == "virDomainSnapshotListNames":
        func = name[9:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:20] == "virDomainSnapshotNum":
        func = name[9:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:26] == "virDomainSnapshotCreateXML":
        func = name[9:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:24] == "virDomainSnapshotCurrent":
        func = name[9:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:17] == "virDomainSnapshot":
        func = name[17:]
        func = string.lower(func[0:1]) + func[1:]
858 859 860
    elif name[0:9] == "virDomain":
        func = name[9:]
        func = string.lower(func[0:1]) + func[1:]
861 862 863 864 865 866
    elif name[0:13] == "virNetworkGet":
        func = name[13:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:10] == "virNetwork":
        func = name[10:]
        func = string.lower(func[0:1]) + func[1:]
867
    elif name[0:15] == "virInterfaceGet":
868
        func = name[15:]
869 870
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:12] == "virInterface":
871
        func = name[12:]
872
        func = string.lower(func[0:1]) + func[1:]
873 874 875 876 877 878
    elif name[0:12] == 'virSecretGet':
        func = name[12:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:9] == 'virSecret':
        func = name[9:]
        func = string.lower(func[0:1]) + func[1:]
879 880 881 882 883 884
    elif name[0:14] == 'virNWFilterGet':
        func = name[14:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:11] == 'virNWFilter':
        func = name[11:]
        func = string.lower(func[0:1]) + func[1:]
885 886 887 888 889
    elif name[0:12] == 'virStreamNew':
        func = "newStream"
    elif name[0:9] == 'virStream':
        func = name[9:]
        func = string.lower(func[0:1]) + func[1:]
890 891 892 893 894 895 896 897 898 899 900 901
    elif name[0:17] == "virStoragePoolGet":
        func = name[17:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:14] == "virStoragePool":
        func = name[14:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:16] == "virStorageVolGet":
        func = name[16:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:13] == "virStorageVol":
        func = name[13:]
        func = string.lower(func[0:1]) + func[1:]
902 903 904
    elif name[0:13] == "virNodeDevice":
        if name[13:16] == "Get":
            func = string.lower(name[16]) + name[17:]
905
        elif name[13:19] == "Lookup" or name[13:19] == "Create":
906 907 908
            func = string.lower(name[3]) + name[4:]
        else:
            func = string.lower(name[13]) + name[14:]
909 910 911
    elif name[0:7] == "virNode":
        func = name[7:]
        func = string.lower(func[0:1]) + func[1:]
912 913 914 915 916 917 918 919
    elif name[0:10] == "virConnect":
        func = name[10:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:3] == "xml":
        func = name[3:]
        func = string.lower(func[0:1]) + func[1:]
    else:
        func = name
920 921
    if func == "iD":
        func = "ID"
922 923
    if func == "uUID":
        func = "UUID"
924 925
    if func == "uUIDString":
        func = "UUIDString"
926 927 928 929
    if func == "oSType":
        func = "OSType"
    if func == "xMLDesc":
        func = "XMLDesc"
930 931 932
    if func == "mACString":
        func = "MACString"

933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
    return func


def functionCompare(info1, info2):
    (index1, func1, name1, ret1, args1, file1) = info1
    (index2, func2, name2, ret2, args2, file2) = info2
    if file1 == file2:
        if func1 < func2:
            return -1
        if func1 > func2:
            return 1
    if file1 == "python_accessor":
        return -1
    if file2 == "python_accessor":
        return 1
    if file1 < file2:
        return -1
    if file1 > file2:
        return 1
    return 0

def writeDoc(name, args, indent, output):
     if functions[name][0] is None or functions[name][0] == "":
         return
     val = functions[name][0]
     val = string.replace(val, "NULL", "None");
     output.write(indent)
     output.write('"""')
961 962 963 964
     i = string.find(val, "\n")
     while i >= 0:
         str = val[0:i+1]
         val = val[i+1:]
965
         output.write(str)
966
         i = string.find(val, "\n")
967
         output.write(indent)
968
     output.write(val)
969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
     output.write(' """\n')

def buildWrappers():
    global ctypes
    global py_types
    global py_return_types
    global unknown_types
    global functions
    global function_classes
    global classes_type
    global classes_list
    global converter_type
    global primary_classes
    global converter_type
    global classes_ancestor
    global converter_type
    global primary_classes
    global classes_ancestor
    global classes_destructors
    global functions_noexcept

    for type in classes_type.keys():
991
        function_classes[classes_type[type][2]] = []
992 993 994 995 996 997 998 999 1000 1001

    #
    # Build the list of C types to look for ordered to start
    # with primary classes
    #
    ctypes = []
    classes_list = []
    ctypes_processed = {}
    classes_processed = {}
    for classe in primary_classes:
1002 1003 1004 1005 1006 1007 1008
        classes_list.append(classe)
        classes_processed[classe] = ()
        for type in classes_type.keys():
            tinfo = classes_type[type]
            if tinfo[2] == classe:
                ctypes.append(type)
                ctypes_processed[type] = ()
1009
    for type in classes_type.keys():
1010 1011 1012 1013 1014 1015
        if ctypes_processed.has_key(type):
            continue
        tinfo = classes_type[type]
        if not classes_processed.has_key(tinfo[2]):
            classes_list.append(tinfo[2])
            classes_processed[tinfo[2]] = ()
1016

1017 1018
        ctypes.append(type)
        ctypes_processed[type] = ()
1019 1020

    for name in functions.keys():
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
        found = 0;
        (desc, ret, args, file, cond) = functions[name]
        for type in ctypes:
            classe = classes_type[type][2]

            if name[0:3] == "vir" and len(args) >= 1 and args[0][1] == type:
                found = 1
                func = nameFixup(name, classe, type, file)
                info = (0, func, name, ret, args, file)
                function_classes[classe].append(info)
            elif name[0:3] == "vir" and len(args) >= 2 and args[1][1] == type \
                and file != "python_accessor" and not name in function_skip_index_one:
                found = 1
                func = nameFixup(name, classe, type, file)
                info = (1, func, name, ret, args, file)
                function_classes[classe].append(info)
        if found == 1:
            continue
        func = nameFixup(name, "None", file, file)
        info = (0, func, name, ret, args, file)
        function_classes['None'].append(info)
1042

1043 1044 1045
    classes = open("libvirt.py", "w")

    extra = open(os.path.join(srcPref,"libvirt-override.py"), "r")
1046
    classes.write("#! " + python + " -i\n")
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
    classes.write("#\n")
    classes.write("# WARNING WARNING WARNING WARNING\n")
    classes.write("#\n")
    classes.write("# This file is automatically written by generator.py. Any changes\n")
    classes.write("# made here will be lost.\n")
    classes.write("#\n")
    classes.write("# To change the manually written methods edit libvirt-override.py\n")
    classes.write("# To change the automatically written methods edit generator.py\n")
    classes.write("#\n")
    classes.write("# WARNING WARNING WARNING WARNING\n")
    classes.write("#\n")
    classes.writelines(extra.readlines())
    classes.write("#\n")
    classes.write("# WARNING WARNING WARNING WARNING\n")
    classes.write("#\n")
    classes.write("# Automatically written part of python bindings for libvirt\n")
    classes.write("#\n")
    classes.write("# WARNING WARNING WARNING WARNING\n")
    extra.close()
1066 1067

    if function_classes.has_key("None"):
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
        flist = function_classes["None"]
        flist.sort(functionCompare)
        oldfile = ""
        for info in flist:
            (index, func, name, ret, args, file) = info
            if file != oldfile:
                classes.write("#\n# Functions from module %s\n#\n\n" % file)
                oldfile = file
            classes.write("def %s(" % func)
            n = 0
            for arg in args:
                if n != 0:
                    classes.write(", ")
                classes.write("%s" % arg[0])
                n = n + 1
            classes.write("):\n")
            writeDoc(name, args, '    ', classes);

            for arg in args:
                if classes_type.has_key(arg[1]):
                    classes.write("    if %s is None: %s__o = None\n" %
                                  (arg[0], arg[0]))
                    classes.write("    else: %s__o = %s%s\n" %
                                  (arg[0], arg[0], classes_type[arg[1]][0]))
            if ret[0] != "void":
                classes.write("    ret = ");
            else:
                classes.write("    ");
            classes.write("libvirtmod.%s(" % name)
            n = 0
            for arg in args:
                if n != 0:
                    classes.write(", ");
                classes.write("%s" % arg[0])
                if classes_type.has_key(arg[1]):
                    classes.write("__o");
                n = n + 1
            classes.write(")\n");
1106 1107

            if ret[0] != "void":
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
                if classes_type.has_key(ret[0]):
                    #
                    # Raise an exception
                    #
                    if functions_noexcept.has_key(name):
                        classes.write("    if ret is None:return None\n");
                    else:
                        classes.write(
                     "    if ret is None:raise libvirtError('%s() failed')\n" %
                                      (name))

                    classes.write("    return ");
                    classes.write(classes_type[ret[0]][1] % ("ret"));
                    classes.write("\n");
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134

                # For functions returning an integral type there are
                # several things that we can do, depending on the
                # contents of functions_int_*:
                elif is_integral_type (ret[0]):
                    if not functions_noexcept.has_key (name):
                        if functions_int_exception_test.has_key (name):
                            test = functions_int_exception_test[name]
                        else:
                            test = functions_int_default_test
                        classes.write (("    if " + test +
                                        ": raise libvirtError ('%s() failed')\n") %
                                       ("ret", name))
1135
                    classes.write("    return ret\n")
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145

                elif is_list_type (ret[0]):
                    if not functions_noexcept.has_key (name):
                        if functions_list_exception_test.has_key (name):
                            test = functions_list_exception_test[name]
                        else:
                            test = functions_list_default_test
                        classes.write (("    if " + test +
                                        ": raise libvirtError ('%s() failed')\n") %
                                       ("ret", name))
1146
                    classes.write("    return ret\n")
1147

1148 1149
                else:
                    classes.write("    return ret\n")
1150

1151
            classes.write("\n");
1152 1153

    for classname in classes_list:
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
        if classname == "None":
            pass
        else:
            if classes_ancestor.has_key(classname):
                classes.write("class %s(%s):\n" % (classname,
                              classes_ancestor[classname]))
                classes.write("    def __init__(self, _obj=None):\n")
                if reference_keepers.has_key(classname):
                    rlist = reference_keepers[classname]
                    for ref in rlist:
                        classes.write("        self.%s = None\n" % ref[1])
                classes.write("        self._o = _obj\n")
                classes.write("        %s.__init__(self, _obj=_obj)\n\n" % (
                              classes_ancestor[classname]))
            else:
                classes.write("class %s:\n" % (classname))
1170
                if classname in [ "virDomain", "virNetwork", "virInterface", "virStoragePool",
1171 1172
                                  "virStorageVol", "virNodeDevice", "virSecret","virStream",
                                  "virNWFilter" ]:
1173
                    classes.write("    def __init__(self, conn, _obj=None):\n")
1174 1175
                elif classname in [ 'virDomainSnapshot' ]:
                    classes.write("    def __init__(self, dom, _obj=None):\n")
1176 1177
                else:
                    classes.write("    def __init__(self, _obj=None):\n")
1178 1179 1180 1181
                if reference_keepers.has_key(classname):
                    list = reference_keepers[classname]
                    for ref in list:
                        classes.write("        self.%s = None\n" % ref[1])
1182
                if classname in [ "virDomain", "virNetwork", "virInterface",
1183 1184
                                  "virNodeDevice", "virSecret", "virStream",
                                  "virNWFilter" ]:
1185
                    classes.write("        self._conn = conn\n")
1186 1187 1188 1189
                elif classname in [ "virStorageVol", "virStoragePool" ]:
                    classes.write("        self._conn = conn\n" + \
                                  "        if not isinstance(conn, virConnect):\n" + \
                                  "            self._conn = conn._conn\n")
1190 1191
                elif classname in [ "virDomainSnapshot" ]:
                    classes.write("        self._dom = dom\n")
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
                classes.write("        if _obj != None:self._o = _obj;return\n")
                classes.write("        self._o = None\n\n");
            destruct=None
            if classes_destructors.has_key(classname):
                classes.write("    def __del__(self):\n")
                classes.write("        if self._o != None:\n")
                classes.write("            libvirtmod.%s(self._o)\n" %
                              classes_destructors[classname]);
                classes.write("        self._o = None\n\n");
                destruct=classes_destructors[classname]
1202 1203 1204 1205 1206 1207

            if not class_skip_connect_impl.has_key(classname):
                # Build python safe 'connect' method
                classes.write("    def connect(self):\n")
                classes.write("        return self._conn\n\n")

1208 1209 1210 1211
            if class_domain_impl.has_key(classname):
                classes.write("    def domain(self):\n")
                classes.write("        return self._dom\n\n")

1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
            flist = function_classes[classname]
            flist.sort(functionCompare)
            oldfile = ""
            for info in flist:
                (index, func, name, ret, args, file) = info
                #
                # Do not provide as method the destructors for the class
                # to avoid double free
                #
                if name == destruct:
                    continue;
                if file != oldfile:
                    if file == "python_accessor":
                        classes.write("    # accessors for %s\n" % (classname))
                    else:
                        classes.write("    #\n")
                        classes.write("    # %s functions from module %s\n" % (
                                      classname, file))
                        classes.write("    #\n\n")
                oldfile = file
                classes.write("    def %s(self" % func)
                n = 0
                for arg in args:
                    if n != index:
                        classes.write(", %s" % arg[0])
                    n = n + 1
                classes.write("):\n")
                writeDoc(name, args, '        ', classes);
                n = 0
                for arg in args:
                    if classes_type.has_key(arg[1]):
                        if n != index:
                            classes.write("        if %s is None: %s__o = None\n" %
                                          (arg[0], arg[0]))
                            classes.write("        else: %s__o = %s%s\n" %
                                          (arg[0], arg[0], classes_type[arg[1]][0]))
                    n = n + 1
                if ret[0] != "void":
                    classes.write("        ret = ");
                else:
                    classes.write("        ");
                classes.write("libvirtmod.%s(" % name)
                n = 0
                for arg in args:
                    if n != 0:
                        classes.write(", ");
                    if n != index:
                        classes.write("%s" % arg[0])
                        if classes_type.has_key(arg[1]):
                            classes.write("__o");
                    else:
                        classes.write("self");
                        if classes_type.has_key(arg[1]):
                            classes.write(classes_type[arg[1]][0])
                    n = n + 1
                classes.write(")\n");
1268

1269 1270 1271
                if name == "virConnectClose":
                    classes.write("        self._o = None\n")

1272 1273
                # For functions returning object types:
                if ret[0] != "void":
1274 1275 1276 1277 1278 1279 1280 1281
                    if classes_type.has_key(ret[0]):
                        #
                        # Raise an exception
                        #
                        if functions_noexcept.has_key(name):
                            classes.write(
                                "        if ret is None:return None\n");
                        else:
1282 1283
                            if classname == "virConnect":
                                classes.write(
1284
                     "        if ret is None:raise libvirtError('%s() failed', conn=self)\n" %
1285
                                              (name))
1286 1287
                            elif classname == "virDomain":
                                classes.write(
1288
                     "        if ret is None:raise libvirtError('%s() failed', dom=self)\n" %
1289 1290 1291
                                              (name))
                            elif classname == "virNetwork":
                                classes.write(
1292
                     "        if ret is None:raise libvirtError('%s() failed', net=self)\n" %
1293 1294 1295
                                              (name))
                            elif classname == "virInterface":
                                classes.write(
1296
                     "        if ret is None:raise libvirtError('%s() failed', net=self)\n" %
1297
                                              (name))
1298 1299
                            elif classname == "virStoragePool":
                                classes.write(
1300
                     "        if ret is None:raise libvirtError('%s() failed', pool=self)\n" %
1301 1302 1303
                                              (name))
                            elif classname == "virStorageVol":
                                classes.write(
1304
                     "        if ret is None:raise libvirtError('%s() failed', vol=self)\n" %
1305
                                              (name))
1306 1307 1308 1309
                            elif classname == "virDomainSnapshot":
                                classes.write(
                     "        if ret is None:raise libvirtError('%s() failed', dom=self._dom)\n" %
                                              (name))
1310 1311
                            else:
                                classes.write(
1312
                     "        if ret is None:raise libvirtError('%s() failed')\n" %
1313
                                              (name))
1314

1315 1316 1317 1318 1319 1320
                        #
                        # generate the returned class wrapper for the object
                        #
                        classes.write("        __tmp = ");
                        classes.write(classes_type[ret[0]][1] % ("ret"));
                        classes.write("\n");
1321 1322

                        #
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
                        # Sometime one need to keep references of the source
                        # class in the returned class object.
                        # See reference_keepers for the list
                        #
                        tclass = classes_type[ret[0]][2]
                        if reference_keepers.has_key(tclass):
                            list = reference_keepers[tclass]
                            for pref in list:
                                if pref[0] == classname:
                                    classes.write("        __tmp.%s = self\n" %
                                                  pref[1])
1334 1335 1336 1337 1338 1339

                        # Post-processing - just before we return.
                        if function_post.has_key(name):
                            classes.write("        %s\n" %
                                          (function_post[name]));

1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350
                        #
                        # return the class
                        #
                        classes.write("        return __tmp\n");
                    elif converter_type.has_key(ret[0]):
                        #
                        # Raise an exception
                        #
                        if functions_noexcept.has_key(name):
                            classes.write(
                                "        if ret is None:return None");
1351 1352 1353 1354 1355 1356

                        # Post-processing - just before we return.
                        if function_post.has_key(name):
                            classes.write("        %s\n" %
                                          (function_post[name]));

1357 1358 1359
                        classes.write("        return ");
                        classes.write(converter_type[ret[0]] % ("ret"));
                        classes.write("\n");
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373

                    # For functions returning an integral type there
                    # are several things that we can do, depending on
                    # the contents of functions_int_*:
                    elif is_integral_type (ret[0]):
                        if not functions_noexcept.has_key (name):
                            if functions_int_exception_test.has_key (name):
                                test = functions_int_exception_test[name]
                            else:
                                test = functions_int_default_test
                            if classname == "virConnect":
                                classes.write (("        if " + test +
                                                ": raise libvirtError ('%s() failed', conn=self)\n") %
                                               ("ret", name))
1374 1375 1376 1377 1378 1379 1380 1381
                            elif classname == "virDomain":
                                classes.write (("        if " + test +
                                                ": raise libvirtError ('%s() failed', dom=self)\n") %
                                               ("ret", name))
                            elif classname == "virNetwork":
                                classes.write (("        if " + test +
                                                ": raise libvirtError ('%s() failed', net=self)\n") %
                                               ("ret", name))
1382 1383 1384 1385
                            elif classname == "virInterface":
                                classes.write (("        if " + test +
                                                ": raise libvirtError ('%s() failed', net=self)\n") %
                                               ("ret", name))
1386 1387 1388 1389 1390 1391 1392 1393
                            elif classname == "virStoragePool":
                                classes.write (("        if " + test +
                                                ": raise libvirtError ('%s() failed', pool=self)\n") %
                                               ("ret", name))
                            elif classname == "virStorageVol":
                                classes.write (("        if " + test +
                                                ": raise libvirtError ('%s() failed', vol=self)\n") %
                                               ("ret", name))
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
                            else:
                                classes.write (("        if " + test +
                                                ": raise libvirtError ('%s() failed')\n") %
                                               ("ret", name))

                        # Post-processing - just before we return.
                        if function_post.has_key(name):
                            classes.write("        %s\n" %
                                          (function_post[name]));

                        classes.write ("        return ret\n")

                    elif is_list_type (ret[0]):
                        if not functions_noexcept.has_key (name):
                            if functions_list_exception_test.has_key (name):
                                test = functions_list_exception_test[name]
                            else:
                                test = functions_list_default_test
                            if classname == "virConnect":
                                classes.write (("        if " + test +
                                                ": raise libvirtError ('%s() failed', conn=self)\n") %
                                               ("ret", name))
1416 1417 1418 1419 1420 1421 1422 1423
                            elif classname == "virDomain":
                                classes.write (("        if " + test +
                                                ": raise libvirtError ('%s() failed', dom=self)\n") %
                                               ("ret", name))
                            elif classname == "virNetwork":
                                classes.write (("        if " + test +
                                                ": raise libvirtError ('%s() failed', net=self)\n") %
                                               ("ret", name))
1424 1425 1426 1427
                            elif classname == "virInterface":
                                classes.write (("        if " + test +
                                                ": raise libvirtError ('%s() failed', net=self)\n") %
                                               ("ret", name))
1428 1429 1430 1431 1432 1433 1434 1435
                            elif classname == "virStoragePool":
                                classes.write (("        if " + test +
                                                ": raise libvirtError ('%s() failed', pool=self)\n") %
                                               ("ret", name))
                            elif classname == "virStorageVol":
                                classes.write (("        if " + test +
                                                ": raise libvirtError ('%s() failed', vol=self)\n") %
                                               ("ret", name))
1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447
                            else:
                                classes.write (("        if " + test +
                                                ": raise libvirtError ('%s() failed')\n") %
                                               ("ret", name))

                        # Post-processing - just before we return.
                        if function_post.has_key(name):
                            classes.write("        %s\n" %
                                          (function_post[name]));

                        classes.write ("        return ret\n")

1448
                    else:
1449 1450 1451 1452 1453
                        # Post-processing - just before we return.
                        if function_post.has_key(name):
                            classes.write("        %s\n" %
                                          (function_post[name]));

1454
                        classes.write("        return ret\n");
1455

1456
                classes.write("\n");
1457 1458
            # Append "<classname>.py" to class def, iff it exists
            try:
1459
                extra = open(os.path.join(srcPref,"libvirt-override-" + classname + ".py"), "r")
1460 1461 1462 1463
                classes.write ("    #\n")
                classes.write ("    # %s methods from %s.py (hand coded)\n" % (classname,classname))
                classes.write ("    #\n")
                classes.writelines(extra.readlines())
1464
                classes.write("\n")
1465 1466 1467
                extra.close()
            except:
                pass
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481

    #
    # Generate enum constants
    #
    for type,enum in enums.items():
        classes.write("# %s\n" % type)
        items = enum.items()
        items.sort(lambda i1,i2: cmp(long(i1[1]),long(i2[1])))
        for name,value in items:
            classes.write("%s = %s\n" % (name,value))
        classes.write("\n");

    classes.close()

1482 1483
if buildStubs() < 0:
    sys.exit(1)
1484
buildWrappers()
1485
sys.exit(0)