summaryrefslogtreecommitdiff
path: root/pysnmp/smi/compiler.py
blob: c76463b7062e1fb13c26647b2b4ad27df3c842be (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#
# This file is part of pysnmp software.
#
# Copyright (c) 2005-2016, Ilya Etingof <ilya@glas.net>
# License: http://pysnmp.sf.net/license.html
#
import os
import sys

defaultSources = ['file:///usr/share/snmp/mibs', 'file:///usr/share/mibs']

if sys.platform[:3] == 'win':
    defaultDest = os.path.join(os.path.expanduser("~"),
                               'PySNMP Configuration', 'mibs')
else:
    defaultDest = os.path.join(os.path.expanduser("~"), '.pysnmp', 'mibs')

defaultBorrowers = []

try:
    from pysmi.reader.url import getReadersFromUrls
    from pysmi.searcher.pypackage import PyPackageSearcher
    from pysmi.searcher.stub import StubSearcher
    from pysmi.borrower.pyfile import PyFileBorrower
    from pysmi.writer.pyfile import PyFileWriter
    from pysmi.parser.smi import parserFactory
    from pysmi.parser.dialect import smiV1Relaxed
    from pysmi.codegen.pysnmp import PySnmpCodeGen, baseMibs
    from pysmi.compiler import MibCompiler

except ImportError:
    from pysnmp.smi import error


    def addMibCompilerDecorator(errorMsg):
        def addMibCompiler(mibBuilder, **kwargs):
            if not kwargs.get('ifAvailable'):
                raise error.SmiError('MIB compiler not available: %s' % errorMsg)

        return addMibCompiler


    addMibCompiler = addMibCompilerDecorator(sys.exc_info()[1])

else:

    def addMibCompiler(mibBuilder, **kwargs):
        if kwargs.get('ifNotAdded') and mibBuilder.getMibCompiler():
            return

        compiler = MibCompiler(parserFactory(**smiV1Relaxed)(),
                               PySnmpCodeGen(),
                               PyFileWriter(kwargs.get('destination') or defaultDest))

        compiler.addSources(*getReadersFromUrls(*kwargs.get('sources') or defaultSources))

        compiler.addSearchers(StubSearcher(*baseMibs))
        compiler.addSearchers(*[PyPackageSearcher(x.fullPath()) for x in mibBuilder.getMibSources()])
        compiler.addBorrowers(*[PyFileBorrower(x, genTexts=mibBuilder.loadTexts) for x in
                                getReadersFromUrls(*kwargs.get('borrowers') or defaultBorrowers,
                                                   **dict(lowcaseMatching=False))])

        mibBuilder.setMibCompiler(
            compiler, kwargs.get('destination') or defaultDest
        )