Exemple #1
0
    def __init__(self, **kwargs):
        """Creates a new instance of MarkupError."""

        self._thrown     = Logger.getFormattedStackTrace(2, 3)
        self._definition = ArgsUtils.get('errorDef', None, kwargs)
        self._tag        = ArgsUtils.get('tag', None, kwargs)
        self._block      = ArgsUtils.get('block', self._tag.block if self._tag else None, kwargs)
        self._processor  = ArgsUtils.get('processor', self._tag.processor if self._tag else None, kwargs)
        self._code       = ArgsUtils.get('code', self._definition.code, kwargs, allowNone=False)
        self.label       = ArgsUtils.get('label', self._definition.label, kwargs, allowNone=False)
        self.message     = ArgsUtils.get('message', self._definition.message, kwargs, allowNone=False)
        self._critical   = ArgsUtils.get('critical', False, kwargs)

        replacements = ArgsUtils.getAsList('replacements', kwargs)
        replacements.append([u'#TAG#', unicode(self._tag.tagName if self._tag else u'???')])

        for r in replacements:
            if self.message:
                self.message = self.message.replace(unicode(r[0]), unicode(r[1]))

            if self.label:
                self.label = self.label.replace(unicode(r[0]), unicode(r[1]))

        self._verbose   = ArgsUtils.get('verbose', False, kwargs)
        self._line      = None
        self._character = None
        self._source    = None
        self._logSource = None
        self._populateData()
    def add(self, *args, **kwargs):
        """Adds item(s) to the existing list of items, ignoring duplicates.

        @@@param items:mixed,list
            The items argument can be a single item or a list of items.

        @@@param group:string
            The name of the group in which to add the items. Default of None adds the items to the
            root group.
        """

        items = ArgsUtils.get('items', None, kwargs, args, 0)
        if items is None or not items:
            return

        group = ArgsUtils.get('group', None, kwargs, args, 1)
        once  = ArgsUtils.get('once', False, kwargs)

        if group:
            target = self._tempSubs if once else self._subs
            if not group in target:
                target[group] = []
            for n in items:
                if not n in target[group]:
                    target[group].append(n)
        else:
            target = self._tempRoot if once else self._root
            for n in items:
                if not n in target:
                    target.append(n)
Exemple #3
0
    def __init__(self, parent =None, **kwargs):
        """Creates a new instance of PySideGui."""
        flags = ArgsUtils.extract('flags', None, kwargs)
        if flags is None:
            # By default the close button is hidden (only title shows)
            flags = QtCore.Qt.CustomizeWindowHint | QtCore.Qt.WindowTitleHint

        title          = ArgsUtils.extract('title', 'Dialog', kwargs)
        modal          = ArgsUtils.extract('modal', True, kwargs)
        widgetClass    = ArgsUtils.extract('widget', None, kwargs)
        self._callback = ArgsUtils.extract('callback', None, kwargs)
        self._canceled = True

        QtGui.QDialog.__init__(self, parent, flags)

        self.setStyleSheet(self.owner.styleSheetPath)
        if widgetClass is None:
            self._widget = None
        else:
            layout       = self._getLayout(self)
            self._widget = widgetClass(parent=self, **kwargs)
            layout.addWidget(self._widget)

        self.setModal(modal)
        self.setWindowTitle(title)
Exemple #4
0
    def __init__(self, **kwargs):
        """Creates a new instance of ClassTemplate."""
        self._content  = ArgsUtils.get('content', '', kwargs)

        SVADO          = SingleValuedAttributeDataOrganizer
        self._id       = self._createOrganizer('id', kwargs, SVADO, name='id')
        self._renderID = self._createOrganizer(['renderID', 'rid'], kwargs, SVADO, name='data-v-rid')
        self._dataID   = self._createOrganizer(['dataID', 'did'], kwargs, SVADO, name='data-v-did')
        self._styleID  = self._createOrganizer(['themeID', 'sid'], kwargs, SVADO, name='data-v-sid')

        ADO            = AttributeDataOrganizer
        self._vdata    = self._createOrganizer('vdata', kwargs, ADO, prefix='data-v-')
        self._data     = self._createOrganizer('data', kwargs, ADO, prefix='data-')
        self._attrs    = self._createOrganizer('attrs', kwargs, ADO, prefix='')

        SADO            = SingleAttributeDataOrganizer
        self._dataState = self._createOrganizer('dataState', kwargs, SADO, name='data-v-data')
        self._inits     = self._createOrganizer('inits', kwargs, SADO, name='data-v-ini')
        self._events    = self._createOrganizer('events', kwargs, SADO, name='data-v-evt')
        self._settings  = self._createOrganizer('settings', kwargs, SADO, name='data-v-sets')
        self._icon      = self._createOrganizer('icons', kwargs, SADO, name='data-v-icon')

        self._styles   = self._createOrganizer('styles', kwargs, Stylesheet)
        self._classes  = self._createOrganizer('classes', kwargs, Classes)

        self._render   = ArgsUtils.get('render', {}, kwargs)
        self._doms     = ArgsUtils.get('doms', {}, kwargs)
        self._writes   = ArgsUtils.get('writes', [], kwargs)
Exemple #5
0
    def createPath(cls, *args, **kwargs):
        """Doc..."""
        if not args or args[0] is None:
            return None

        src = []
        for item in args:
            if isinstance(item, list):
                src.extend(item)
            else:
                src.append(item)
        out = os.path.join(*src)

        if out.endswith(os.sep) or ArgsUtils.get('isFile', False, kwargs):
            return cls._getAbsolutePath(out)

        noTail = ArgsUtils.get('noTail', False, kwargs)
        if ArgsUtils.get('isDir', False, kwargs):
            return cls._getAbsolutePath(out) if noTail else (cls._getAbsolutePath(out) + os.sep)

        if os.path.exists(out):
            if os.path.isfile(out):
                return cls._getAbsolutePath(out)

            if os.path.isdir(out) and not noTail and not out.endswith(os.sep):
                out += os.sep
        elif out.endswith('..'):
            out += os.sep
        elif src[-1].find('.') == -1:
            out += os.sep

        return cls._getAbsolutePath(out)
    def add(self, *args, **kwargs):
        """Adds value to the existing item, replacing existing entries.

        @@@param value:string
            The value argument can be a single value.

        @@@param group:string
            The name of the group in which to add the value. Default of None adds the value to the
            root group.
        """

        value = ArgsUtils.get('value', None, kwargs, args, 0)
        if value is None:
            value = u''
        elif isinstance(value, dict) or isinstance(value, list):
            value = JSON.asString(value)
        else:
            value = unicode(value)

        group = ArgsUtils.get('group', None, kwargs, args, 1)
        once  = ArgsUtils.get('once', False, kwargs)

        if group:
            target        = self._tempSubs if once else self._subs
            target[group] = value
        else:
            if once:
                self._tempRoot = value
            else:
                self._root = value
Exemple #7
0
    def __init__(self, containerPath, isRemoteDeploy =False, sourceRootFolder ='src', **kwargs):
        """Creates a new instance of Site."""
        super(Site, self).__init__()

        self.errorCount     = 0
        self.warningCount   = 0
        self._staticPaths   = []

        self._logger = ArgsUtils.getLogger(self, kwargs)
        self._sourceRootFolderName = sourceRootFolder

        # NGinx root path in which all files reside
        self._containerPath = FileUtils.cleanupPath(containerPath, isDir=True)

        # Location of the source files used to create the website
        self._sourceWebRootPath = FileUtils.createPath(containerPath, sourceRootFolder, isDir=True)

        # Locations where files should be deployed. If the target root path is None, which is the
        # default value, the local web root path is used in its place.

        if isRemoteDeploy:
            self._targetWebRootPath = FileUtils.cleanupPath(
                tempfile.mkdtemp(prefix='staticFlow_'), isDir=True)
        else:
            self._targetWebRootPath = None

        self._localWebRootPath  = FileUtils.createPath(
            containerPath, ArgsUtils.get('localRootFolder', 'root', kwargs), isDir=True)

        path = FileUtils.createPath(self.sourceWebRootPath, '__site__.def', isFile=True)
        try:
            self._data.data = JSON.fromFile(path, throwError=True)
        except Exception, err:
            self.writeLogError(u'Unable to load site definition file: "%s"' % path, error=err)
            pass
Exemple #8
0
    def write(self, *args, **kwargs):
        group  = ArgsUtils.get('group', None, kwargs, args, 0)
        skipID = ArgsUtils.get('skipID', False, kwargs)
        items  = None if len(args) < 2 else args[1:]

        s   = []
        out = None
        if items and len(items):
            for a in items:
                out = a.write(group=group, **kwargs)
                if out and len(out) > 0:
                    s.append(out)
        else:
            writes = self._writes + DomRenderData._WRITES
            for w in writes:
                if skipID and w == 'id':
                    continue

                try:
                    out = getattr(self, w).write(group=group, **kwargs)
                    if out and len(out) > 0:
                        s.append(out)
                except Exception, err:
                    DomRenderData._LOGGER.writeError(['Organizer write failure',
                                                      'organizer: ' + str(out),
                                                      'renderData: ' + str(self)], err)
                    pass
Exemple #9
0
    def __init__(self, **kwargs):
        """Creates a new instance of MarkupTagError."""

        self._errorAtEnd = ArgsUtils.extract("errorAtEnd", False, kwargs)

        ArgsUtils.addIfMissing("errorDef", self.READ_FAILURE, kwargs, True)
        MarkupError.__init__(self, **kwargs)
Exemple #10
0
 def _activateWidgetDisplayImpl(self, **kwargs):
     super(LoadingWidget, self)._activateWidgetDisplayImpl(**kwargs)
     self.target     = ArgsUtils.get('target', None, kwargs)
     self.header     = ArgsUtils.get('header', None, kwargs)
     self.info       = ArgsUtils.get('info', None, kwargs)
     self.isShowing  = True
     self._animatedIcon.start()
Exemple #11
0
    def _renderImpl(self, **kwargs):
        a = self.attrs

        LayoutAttributeParser.parseScale(a, True, kwargs)
        LayoutAttributeParser.parseAlignment(a, True, kwargs)
        LayoutAttributeParser.parsePadding(a, True, kwargs, group=a.styleGroup, defaultValue=GeneralSizeEnum.xsmall[0])

        color = a.getAsColorValue(TagAttributesEnum.COLOR, ArgsUtils.get("colorDef", None, kwargs), kwargs)

        if not ArgsUtils.get("skipBorder", False, kwargs):
            LayoutAttributeParser.parseBorder(
                a,
                True,
                kwargs,
                group=a.styleGroup,
                defaultColor=ArgsUtils.get("borderColorDef", color.shiftColors[1] if color else None, kwargs),
            )

        # -------------------------------------------------------------------------------------------
        # BACKGROUND COLOR
        if not ArgsUtils.get("skipBackground", False, kwargs):
            if isinstance(color, ColorValue):
                a.styles.add("background-color", color.web, a.styleGroup)
            elif a.explicitAccent or a.themeChanged:
                self.useBackground()

        a.classes.add("sfml-push", a.styleGroup)
Exemple #12
0
    def __init__(self, **kwargs):
        """Creates a new instance of ConfigReader."""
        self._configs     = ArgsUtils.get('configs', dict(), kwargs)
        self._filenames   = ArgsUtils.get('filenames', None, kwargs)
        self._configPath  = ArgsUtils.get(
            'rootConfigPath',
            CadenceEnvironment.getConfigPath(),
            kwargs
        )

        if self._filenames:
            for n,v in self._filenames.iteritems():
                if not v:
                    continue

                path = os.path.join(self._configPath, v)
                if not path.endswith('.cfg'):
                    path += '.cfg'

                parser = ConfigParser.ConfigParser()
                if os.path.exists(path):
                    parser.read(path)
                else:
                    raise Exception, path + ' config file does not exist!'

                self._configs[n] = self._configParserToDict(parser)

        self._overrides = dict()
        self.setOverrides(ArgsUtils.get('overrides', None, kwargs))
Exemple #13
0
    def getPrefix(self, *args, **kwargs):
        if self._locationPrefix:
            item = self.getStackData()[-1]
            loc  = ' -> %s #%s]' % (item['file'], StringUtils.toUnicode(item['line']))
        else:
            loc = ']'

        if self._app and self._app.pyramidApp:
            wsgi     = self._app.environ
            initials = self._INITIALS_RX.sub('', ArgsUtils.get('REMOTE_USER', '', wsgi))
            if initials:
                initials += ' | '

            domainName  = ArgsUtils.get('SERVER_NAME', '', wsgi)
            uriPath = ArgsUtils.get(
                'REQUEST_URI',
                ArgsUtils.get('HTTP_REQUEST_URI', '', wsgi), wsgi)

            info = ' <' + initials + domainName + uriPath + '>'
        else:
            info = ''

        threadID = ThreadUtils.getCurrentID()
        return StringUtils.toUnicode(
            TimeUtils.toFormat('[%a %H:%M <%S.%f>') + '<' + threadID + '>' + info + loc)
Exemple #14
0
    def __init__(self, src ='', debug =False, blockDefs =None, debugData =None, **kwargs):
        """Creates a new instance of ClassTemplate."""
        self._log = ArgsUtils.getLogger(self, kwargs)

        self._debugData = debugData
        self._debug     = debug

        src = StringUtils.toUnicode(src)

        self._raw = src.replace('\r','')
        if ArgsUtils.get('stripSource', True, kwargs):
            self._raw = self._raw.strip('\n')

        self._analyzed  = False
        self._errors    = []
        self._blocks    = []
        self._bookmarks = []
        self._initialBlock = ArgsUtils.get('initialBlock', None, kwargs)

        if isinstance(blockDefs, BlockDefinition):
            self._blockDefs = {'root':blockDefs}
        elif isinstance(blockDefs, dict):
            self._blockDefs = blockDefs
        elif isinstance(blockDefs, list):
            self._blockDefs = {'root':blockDefs}
        else:
            self._blockDefs = {
                'root':[
                    BlockDefinition.createQuoteDef(BlockDefinition.BLOCKED),
                    BlockDefinition.createLiteralDef(BlockDefinition.BLOCKED),
                    BlockDefinition.createParensDef(),
                    BlockDefinition.createBracketsDef(),
                    BlockDefinition.createBracesDef(),
                    ],
                }
Exemple #15
0
    def _listPath(cls, rootPath, recursive, **kwargs):
        listDirs        = ArgsUtils.get('listDirs', False, kwargs)
        skipSVN         = ArgsUtils.get('skipSVN', True, kwargs)
        skips           = ArgsUtils.get('skips', None, kwargs)
        allowExtensions = ArgsUtils.getAsList('allowExtensions', kwargs)
        skipExtensions  = ArgsUtils.getAsList('skipExtensions', kwargs)

        out = []
        for item in os.listdir(rootPath):
            if (skipSVN and item == '.svn') or (skips and item in skips):
                continue
            absItem = os.path.join(rootPath, item)
            if os.path.isdir(absItem):
                path = (absItem + os.sep)
                if listDirs:
                    out.append(path)
                absItem = None

                if recursive:
                    out += cls._listPath(path, recursive, **kwargs)

            elif os.path.isfile(absItem):
                if skipExtensions and StringUtils.ends(item, skipExtensions):
                    continue

                if allowExtensions and not StringUtils.ends(item, allowExtensions):
                    continue

            if absItem:
                out.append(absItem)

        return out
Exemple #16
0
    def addKeysFromLists(self, **kwargs):
        self._clearCache()

        x = ArgsUtils.get('times', None, kwargs)
        if not x:
            return

        y = ArgsUtils.get('values', None, kwargs)
        if not y:
            return

        tans    = ArgsUtils.get('tangents', None, kwargs)
        inTans  = ArgsUtils.get('inTangents', tans, kwargs)
        outTans = ArgsUtils.get('outTangents', tans, kwargs)

        if not inTans:
            inTans = 'lin'

        if not outTans:
            outTans = 'lin'

        for i in range(0,len(x)):
            self._keys.append(DataChannelKey(
                time=x[i],
                value=y[i],
                inTangent=inTans if StringUtils.isStringType(inTans) else inTans[i],
                outTangent=outTans if StringUtils.isStringType(outTans) else outTans[i] ))
Exemple #17
0
 def __init__(self, parent=None, **kwargs):
     """Creates a new instance of PySideGuiWidget."""
     QtGui.QWidget.__init__(self, parent)
     self._mainWindow = None
     self._id = ArgsUtils.get("id", self.__class__.__name__, kwargs)
     self._widgetID = ArgsUtils.get("widgetID", self._id, kwargs)
     self._userData = ArgsUtils.get("userData", None, kwargs)
     self._resourceFolderParts = PyGlassGuiUtils.getResourceFolderParts(self)
Exemple #18
0
 def __init__(self, **kwargs):
     """Creates a new instance of BarPlot."""
     ArgsUtils.addIfMissing('yLabel', 'Frequency', kwargs)
     super(BarPlot, self).__init__(**kwargs)
     self.color      = kwargs.get('color', 'b')
     self.strokeColor = kwargs.get('strokeColor', 'none')
     self.data       = kwargs.get('data', [])
     self.isLog      = kwargs.get('isLog', False)
    def _initializeData(cls, data, track):
        """_initializeData doc..."""

        if data is None:
            data = dict()
        ArgsUtils.addIfMissing('track', track, data)
        ArgsUtils.addIfMissing('debug', [], data)
        return data
Exemple #20
0
 def __init__(self, **kwargs):
     """Creates a new instance of Histogram."""
     ArgsUtils.addIfMissing('yLabel', 'Frequency', kwargs)
     super(Histogram, self).__init__(**kwargs)
     self.color      = kwargs.get('color', 'b')
     self.binCount   = kwargs.get('binCount', 100)
     self.data       = kwargs.get('data', [])
     self.isLog      = kwargs.get('isLog', False)
Exemple #21
0
    def __init__(self, target, **kwargs):
        """Creates a new instance of TargetData."""
        self._target        = target
        self._channels      = ArgsUtils.get('channels', dict(), kwargs)
        self._dutyFactor    = ArgsUtils.get('dutyFactor', 0.5, kwargs)
        self._phaseOffset   = float(ArgsUtils.get('phaseOffset', 0.0, kwargs))

        print(self.target, self._phaseOffset)
Exemple #22
0
 def __init__(self, ident, label =None, message =None, **kwargs):
     """Creates a new instance of ViewResponse."""
     self._id      = ident
     self._label   = label
     self._message = message
     self._kind    = ArgsUtils.get('kind', self.DEFAULT_KIND, kwargs)
     self._allowCaching = ArgsUtils.get('allowCaching', False, kwargs)
     self._data = ArgsUtils.getAsDict('data', kwargs)
Exemple #23
0
    def addApplicationLevelWidget(self, widgetID, widgetClass =None, **kwargs):
        if widgetClass is None:
            widgetClass = ApplicationLevelWidget
            ArgsUtils.addIfMissing('widgetFile', False, kwargs)

        widget = widgetClass(parent=self._appWrappingWidget, **kwargs)
        self._appWrappingWidget.layout().addWidget(widget)
        self._appLevelWidgets[widgetID] = widget
        return widget
Exemple #24
0
    def updateValues(self, *args, **kwargs):
        x = ArgsUtils.get('x', None, kwargs, args, 0)
        if x is not None:
            self.x = x

        y = ArgsUtils.get('y', None, kwargs, args, 1)
        if y is not None:
            self.y = y

        return True
Exemple #25
0
 def __init__(self, *args, **kwargs):
     """Creates a new instance of Vector2D."""
     if args and isinstance(args[0], (list, tuple)):
         self._values = list(args[0]) + []
     elif args and isinstance(args[0], Vector2D):
         self._values = [args[0].x, args[0].y]
     else:
         x = ArgsUtils.get('x', 0.0, kwargs, args, 0)
         y = ArgsUtils.get('y', 0.0, kwargs, args, 1)
         self._values = [x, y]
Exemple #26
0
    def __init__(self, **kwargs):
        """ Creates a new instance of CadenceData.

            @@@param name:string
                The name identifying the data.
        """

        self._name = ArgsUtils.get("name", None, kwargs)
        self._configs = ArgsUtils.get("configs", None, kwargs)
        self._channels = ArgsUtils.get("channels", [], kwargs)
    def __init__(self, parent, path, importType, session =None, analysisSession =None, **kwargs):
        """Creates a new instance of TrackImporterRemoteThread."""
        self._compressed = ArgsUtils.extract('compressed', False, kwargs)

        RemoteExecutionThread.__init__(self, parent, **kwargs)
        self._path       = path
        self._session    = session
        self._analysisSession = analysisSession
        self._importType = importType
        self._verbose    = ArgsUtils.get('verbose', True, kwargs)
Exemple #28
0
    def __init__(self, start, end =None, name =None, data =None, **kwargs):
        """Creates a new instance of TextBookmark."""

        self._name  = name
        self._start = start
        self._end   = start if end is None else end
        self._data  = data

        self._originalStart = ArgsUtils.get('originalStart', self._start, kwargs)
        self._originalEnd   = ArgsUtils.get('originalEnd', self._end, kwargs)
    def __init__(self, parent, path, session=None, **kwargs):
        """Creates a new instance of TrackImporterRemoteThread."""
        self._pretty = ArgsUtils.extract("pretty", False, kwargs)
        self._gzipped = ArgsUtils.extract("compressed", True, kwargs)
        self._difference = ArgsUtils.extract("difference", True, kwargs)

        RemoteExecutionThread.__init__(self, parent, **kwargs)

        self._path = path
        self._session = session
Exemple #30
0
    def __init__(self, targetClass, isSocket =False, **kwargs):

        self._logger = targetClass.getLogger()

        try:
            self._verbose = targetClass.VERBOSE
        except Exception as err:
            self._logger.write('Failed to acquire VERBOSE from ' + str(targetClass.__name__), err)
            sys.exit(126)

        try:
            self._uid = targetClass.SERVICE_UID
        except Exception as err:
            self._logger.write('Failed to acquire SERVICE_UID from ' + str(targetClass.__name__), err)
            sys.exit(126)

        if isSocket:
            self._wait = 0
        else:
            try:
                self._wait = targetClass.WAIT_INTERVAL
            except Exception as err:
                self._logger.write(
                    'Failed to acquire WAIT_INTERVAL from ' + str(targetClass.__name__), err )
                sys.exit(126)

        if isSocket:
            from pyaid.system.service.systemd.SystemSocketDaemon import SystemSocketDaemon
            self._targetClass = SystemSocketDaemon
            self._socketClass = targetClass
        else:
            self._targetClass = targetClass
            self._socketClass = None

        self._terminated  = False
        self._failCount   = 0
        self._target      = None

        self._workPath = os.path.join(targetClass.WORK_PATH, self._uid)
        self._pidPath  = os.path.join(targetClass.RUN_PATH, self._uid + '.pid')
        self._context  = daemon.DaemonContext(
            working_directory=ArgsUtils.get('workPath', self._workPath, kwargs),
            umask=ArgsUtils.get('umask', 0o000, kwargs),
            uid=ArgsUtils.get('uid', os.getuid(), kwargs),
            gid=ArgsUtils.get('gid', os.getgid(), kwargs),
            detach_process=True,
            pidfile=lockfile.FileLock(self._pidPath) )

        self._context.signal_map = {
            signal.SIGQUIT: self._handleQuit,
            signal.SIGTERM: self._handleCleanup,
            signal.SIGHUP: self._handleQuit,
            signal.SIGUSR1: self._handleUser }

        self._logger.write(self._uid + ' daemon initialized')
Exemple #31
0
    def fetch(self, name, defaultValue=None):
        """ Retrieves the value of the script argument specified by the name. If no such argument
            exists (or the argument is None) the default value will be returned.

            name: Script argument name to fetch.
            [defaultValue =None]: Value returned if the script argument is None or missing. """
        return ArgsUtils.get(name, defaultValue, self.kwargs)
Exemple #32
0
    def __call__(self, s='', *args, **kwargs):

        # If the call is an error, write the error
        err = ArgsUtils.get('err', args=args, index=1)
        if err and isinstance(err, Exception):
            if self._buffer:
                self.addError(s, err)
            else:
                self.writeError(s, err)

            return

        # Handle the non-error case
        traceStack = ArgsUtils.get('traceStack', False, kwargs, args, 1)
        shaveStackTrace = ArgsUtils.get('shaveStackTrace', 0, kwargs, args, 2)
        if self._buffer:
            self.add(s, traceStack, shaveStackTrace)
        else:
            self.write(s, traceStack, shaveStackTrace)
Exemple #33
0
    def __init__(self,
                 src='',
                 debug=False,
                 blockDefs=None,
                 debugData=None,
                 **kwargs):
        """Creates a new instance of ClassTemplate."""
        self._log = ArgsUtils.getLogger(self, kwargs)

        self._debugData = debugData
        self._debug = debug

        src = StringUtils.toUnicode(src)

        self._raw = src.replace('\r', '')
        if ArgsUtils.get('stripSource', True, kwargs):
            self._raw = self._raw.strip('\n')

        self._analyzed = False
        self._errors = []
        self._blocks = []
        self._bookmarks = []
        self._initialBlock = ArgsUtils.get('initialBlock', None, kwargs)

        if isinstance(blockDefs, BlockDefinition):
            self._blockDefs = {'root': blockDefs}
        elif isinstance(blockDefs, dict):
            self._blockDefs = blockDefs
        elif isinstance(blockDefs, list):
            self._blockDefs = {'root': blockDefs}
        else:
            self._blockDefs = {
                'root': [
                    BlockDefinition.createQuoteDef(BlockDefinition.BLOCKED),
                    BlockDefinition.createLiteralDef(BlockDefinition.BLOCKED),
                    BlockDefinition.createParensDef(),
                    BlockDefinition.createBracketsDef(),
                    BlockDefinition.createBracesDef(),
                ],
            }
Exemple #34
0
    def createReply(cls, kind, result, errorMessage=None):
        payload = result if isinstance(result, dict) else {'result': result}
        warnings = ArgsUtils.extract(
            NimbleEnvironment.REMOTE_RESULT_WARNING_KEY, None, payload)

        if errorMessage:
            return NimbleResponseData(
                kind=kind,
                response=NimbleResponseData.FAILED_RESPONSE,
                warnings=warnings,
                error=errorMessage,
                payload=payload)

        return NimbleResponseData(kind=kind,
                                  warnings=warnings,
                                  response=NimbleResponseData.SUCCESS_RESPONSE,
                                  payload=payload)
Exemple #35
0
 def __init__(self, name, pattern, blockType, terminator=None, **kwargs):
     """Creates a new instance of ClassTemplate."""
     self.name = name
     self.pattern = pattern
     self.blockType = blockType
     self._terminator = terminator
     self.findState = ArgsUtils.get('findState', None, kwargs)
     self.matchReqs = ArgsUtils.get('matchReqs', None, kwargs)
     self.terminatorReqs = ArgsUtils.get('terminatorReqs', None, kwargs)
     self.chainBlocks = ArgsUtils.get('chainBlocks', False, kwargs)
     self.chainBreakers = ArgsUtils.getAsList('chainBreakers', kwargs)
     self.closeAtEnd = ArgsUtils.get('closeAtEnd', False, kwargs)
Exemple #36
0
 def __init__(self, *args, **kwargs):
     """Creates a new instance of TextSource."""
     self._raw = ArgsUtils.get('source', '', kwargs, args, 0)
     self._analyzer = ArgsUtils.get('analyzer', None, kwargs, args, 1)
     self._blocks = ArgsUtils.get('blocks', [], kwargs, args, 2)
Exemple #37
0
def runPythonExec(script, kwargs=None):
    from nimble.NimbleEnvironment import NimbleEnvironment
    from nimble.data.NimbleResponseData import NimbleResponseData
    from nimble.data.enum.DataKindEnum import DataKindEnum

    try:
        nimble.cmds.undoInfo(openChunk=True)
    except Exception as err:
        return False

    try:
        # Create a new, temporary module in which to run the script
        module = imp.new_module('runExecTempModule')

        # Initialize the script with script inputs
        setattr(module, NimbleEnvironment.REMOTE_KWARGS_KEY,
                kwargs if kwargs is not None else dict())
        setattr(module, NimbleEnvironment.REMOTE_RESULT_KEY, dict())

        # Executes the script in the new module
        exec_(script, module.__dict__)

        # Find a NimbleScriptBase derived class definition and if it exists, run it to populate the
        # results
        for name, value in Reflection.getReflectionDict(module).iteritems():
            if not inspect.isclass(value):
                continue

            if NimbleScriptBase in value.__bases__:
                getattr(module, name)().run()
                break

        # Retrieve the results object that contains all results set by the execution of the script
        result = getattr(module, NimbleEnvironment.REMOTE_RESULT_KEY)
    except Exception as err:
        logger = Logger('runPythonExec', printOut=True)
        logger.writeError('ERROR: Failed Remote Script Execution', err)
        result = NimbleResponseData(
            kind=DataKindEnum.PYTHON_SCRIPT,
            response=NimbleResponseData.FAILED_RESPONSE,
            error=str(err))

    # If a result dictionary contains an error key format the response as a failure
    try:
        errorMessage = ArgsUtils.extract(
            NimbleEnvironment.REMOTE_RESULT_ERROR_KEY, None, result)
        if errorMessage:
            return NimbleResponseData(
                kind=DataKindEnum.PYTHON_SCRIPT,
                response=NimbleResponseData.FAILED_RESPONSE,
                error=errorMessage,
                payload=result)
    except Exception as err:
        pass

    try:
        nimble.cmds.undoInfo(closeChunk=True)
    except Exception as err:
        return False

    return result
Exemple #38
0
    def _listPath(cls, rootPath, recursive, **kwargs):
        allowDots = kwargs.get('allowDots', True)
        rootPath = cls.cleanupPath(rootPath, isDir=True)
        listFiles = kwargs.get('listFiles', True)
        listDirs = kwargs.get('listDirs', False)
        skipSVN = kwargs.get('skipSVN', True)
        skips = kwargs.get('skips', None)

        absolute = kwargs.get('absolute', True)
        pieces = kwargs.get('pieces', False)

        topPath = ArgsUtils.extract('topPath', rootPath, kwargs)
        allowExtensions = ArgsUtils.getAsList('allowExtensions', kwargs)
        skipExtensions = ArgsUtils.getAsList('skipExtensions', kwargs)

        out = []
        for item in os.listdir(rootPath):
            if not allowDots and item.startswith('.'):
                continue

            if (skipSVN and item == '.svn') or (skips and item in skips):
                continue

            absItem = os.path.join(rootPath, item)
            if os.path.isdir(absItem):
                path = absItem + os.sep
                if listDirs:
                    out.append(path if absolute else item)
                absItem = None

                if recursive:
                    out += cls._listPath(rootPath=path,
                                         recursive=recursive,
                                         topPath=topPath,
                                         **kwargs)

            elif os.path.isfile(absItem):
                skip = skipExtensions and StringUtils.ends(
                    item, skipExtensions)
                if not listFiles or skip:
                    continue

                if allowExtensions and not StringUtils.ends(
                        item, allowExtensions):
                    continue

            if not absItem:
                continue

            if not pieces and not absolute:
                out.append(item)
                continue

            relativeItem = absItem[len(topPath):].strip(os.sep).split(os.sep)
            if absolute:
                relativeItem.insert(0, topPath)

            if pieces:
                out.append(relativeItem)
            else:
                out.append(os.path.join(*relativeItem))

        return out
Exemple #39
0
    def runPythonImport(cls, payload):
        try:
            kwargs = payload.get('kwargs', {})
            targetModule = StringUtils.toStr2(payload.get('module'))
            targetMethod = StringUtils.toStr2(payload.get('method'))
            targetClass = StringUtils.toStr2(payload.get('class'))
            target = targetClass if targetClass is not None else targetMethod
            if target is None:
                parts = targetModule.rsplit('.', 1)
                targetModule = parts[0]
                target = parts[1]
        except Exception as err:
            NimbleEnvironment.logError([
                'ERROR: Failed to parse python import payload',
                'PAYLOAD: ' + DictUtils.prettyPrint(payload)
            ], err)
            return NimbleResponseData(
                kind=DataKindEnum.PYTHON_IMPORT,
                error=cls._getDetailedError(
                    '\n'.join([
                        'ERROR: Failed to parse python import payload',
                        'PAYLOAD: ' + DictUtils.prettyPrint(payload)
                    ]), err),
                response=NimbleResponseData.FAILED_RESPONSE)

        # Dynamically import the specified module and reload it to make sure any changes have
        # been updated
        try:
            module = __import__(StringUtils.toStr2(targetModule), globals(),
                                locals(),
                                [StringUtils.toStr2(target)] if target else [])
            reload(module)
            target = getattr(module, target)
        except Exception as err:
            NimbleEnvironment.logError([
                'ERROR: Failed to import python target',
                'MODULE: %s' % targetModule,
                'TARGET: %s' % target,
                'PAYLOAD: ' + DictUtils.prettyPrint(payload)
            ], err)
            return NimbleResponseData(
                kind=DataKindEnum.PYTHON_IMPORT,
                error=cls._getDetailedError('Failed to import python module',
                                            err),
                response=NimbleResponseData.FAILED_RESPONSE)

        try:
            result = dict()
            if targetClass is not None:
                tc = target()
                result = getattr(tc, targetMethod)(**kwargs) \
                    if targetMethod else \
                    tc(**kwargs)
            elif targetMethod is not None:
                result = target(**kwargs)
            else:
                # Find a NimbleScriptBase derived class definition and if it exists, run it to
                # populate the results
                for name, value in DictUtils.iter(
                        Reflection.getReflectionDict(target)):
                    if not inspect.isclass(value):
                        continue

                    if NimbleScriptBase in value.__bases__:
                        result = getattr(target, name)()(**kwargs)
                        found = True

            # If a result dictionary contains an error key format the response as a failure
            errorMessage = None
            try:
                errorMessage = ArgsUtils.extract(
                    NimbleEnvironment.REMOTE_RESULT_ERROR_KEY, None, result)
            except Exception as err:
                pass

            return cls.createReply(DataKindEnum.PYTHON_IMPORT,
                                   result,
                                   errorMessage=errorMessage)
        except Exception as err:
            msg = 'ERROR: Failed to execute remote script'
            NimbleEnvironment.logError([
                msg, 'PAYLOAD: ' + DictUtils.prettyPrint(payload),
                'TARGET: ' + str(target)
            ], err)
            return NimbleResponseData(
                kind=DataKindEnum.PYTHON_IMPORT,
                error=cls._getDetailedError(msg, err),
                response=NimbleResponseData.FAILED_RESPONSE)
Exemple #40
0
 def addError(self, s, err, htmlEscape=False, **kwargs):
     self._hasError = True
     ArgsUtils.addIfMissing('traceStack', True, kwargs)
     return self.add(self.createErrorMessage(s, err),
                     htmlEscape=htmlEscape,
                     **kwargs)
Exemple #41
0
 def echoError(self, s, err, htmlEscape=False, **kwargs):
     ArgsUtils.addIfMissing('traceStack', True, kwargs)
     return self.echo(self.createErrorMessage(s, err),
                      htmlEscape=htmlEscape,
                      **kwargs)
 def __init__(self, parent, **kwargs):
     super(NGinxRemoteThread, self).__init__(parent, **kwargs)
     self._path = ArgsUtils.get('rootPath', None, kwargs)
     if not self._path:
         self._path = NGinxSetupOps.getExePath()