示例#1
0
def execute_string(
        code: str,
        debug: bool = False) -> Tuple[BlockStatus, AhVisitor, float]:
    Drivers.add("scriptax", ScriptaxDriver(path="~/"))
    LoadedDrivers.load("scriptax")

    drivers_path = Path(
        Path(__file__).resolve().parents[1]).joinpath('drivers.json')
    packages = list(drivers_path)
    for key, value in packages.items():
        drivers = value['drivers']

        # Imports default driver
        try:
            module = importlib.import_module(key + '.drivers.driver')
            Drivers.add(key, module.driver)
            LoadedDrivers.load(key)
        except:
            print("Unable to load default driver inside of package: " + key)

        # Imports other drivers
        for driver in drivers:
            try:
                module = importlib.import_module(key + '.drivers.' + driver)
                Drivers.add(key + "_" + driver, module.driver)
                LoadedDrivers.load(key + "_" + driver)
            except:
                print("Unable to load driver `" + driver +
                      "` inside of package: " + key)

    start_time = time.process_time()
    block_status, ahvisitor = customizable_parser(read_string(code),
                                                  options=Options(debug=debug))
    total_time = time.process_time() - start_time
    return block_status, ahvisitor, total_time
示例#2
0
    def __init__(self,
                 parameters: List[Parameter] = None,
                 options: Options = None,
                 file=None,
                 symbol_table: SymbolTable = None):
        """
        Parameters
        ----------
        parameters : dict
            Parameters sent to the parser. Typically method or constructor arguments
        options : Options
            Application options such as debug mode
        file : str
            The file path + name
        symbol_table : SymbolTable
            If we would like to parse off of an existing symbol table
        """

        # Aliases
        self.logger = State.log
        self.config = State.config

        # Parameters
        self.appOptions: Options = options if options is not None else Options(
        )
        # self.appOptions.debug = True
        self.parameters: List[
            Parameter] = parameters if parameters is not None else []

        # TODO: Evaluate necessity of these
        self.state = {'file': file, 'line': 0, 'char': 0}
        self.parser = None
        self.options: AhOptions = AhOptions()

        # Parsing status
        # Values: ok, error, exit, return
        self.status = 'ok'
        self.message = ''

        # Symbol Table
        if not symbol_table:
            self.symbol_table: SymbolTable = SymbolTable(name="main",
                                                         type=SCOPE_MODULE)
        else:
            self.symbol_table: SymbolTable = symbol_table

        # Used for mustache syntax dynamic replacement
        # self.regexVar = '{{[ ]{0,}[A-z0-9_$.\-]{1,}[ ]{0,}}}'
        self.regexVar = r"<\|[ ]{0,}[A-z0-9_$.\-]{1,}[ ]{0,}>"
示例#3
0
    def __init__(self, options=None, credentials=None, command='', parameters={}, request=None):
        self.options: Options = options if options is not None else Options()
        self.parameters = parameters
        self.credentials: Credentials = credentials if credentials is not None else Credentials()
        self.request: ApitaxRequest = request if request is not None else ApitaxRequest()

        self.command: str = command
        self.command = self.command.replace('\\"', '"')
        self.command = self.command.replace('\\\'', '\'')
        self.command: list = shlex.split(self.command.strip())

        self.executionTime = None
        self.commandtax = None
        self.logBuffer = []

        self.options.driver: Driver = LoadedDrivers.getDriver('commandtax')

        self.request.headerBuilder = self.options.driver.addApiHeaders(self.request.headerBuilder)
        self.request.bodyBuilder = self.options.driver.addApiBody(self.request.bodyBuilder)
示例#4
0
    def execute_command(self, command: Command) -> ApitaxResponse:
        """
        Executes commandtax
        """
        from commandtax.flow.Connector import Connector
        self.log('Executing Commandtax: \'' + command.command + '\' ' +
                 'with parameters: ' + str(command.parameters))

        if not command.options:
            command.options = self.appOptions

        if not command.options:
            command.options = Options()

        connector = Connector(options=command.options,
                              credentials=command.credentials,
                              command=command.command,
                              parameters=command.parameters,
                              request=command.request)
        return connector.execute()
示例#5
0
文件: Setup.py 项目: Apitax/Apitax
    def __init__(self, passedArgs: list = []):

        if len(passedArgs) == 0:
            self.args = sys.argv[1:]
        else:
            self.args = passedArgs

        self.usage = 'cli'

        self.debug = False
        self.sensitive = False

        self.reloader = False
        self.watcher = False

        self.username = ''
        self.password = ''

        self.command = ''
        self.script = ''

        self.build = True

        self.doLog = True
        if State.paths['log'] != "":
            self.logPath = State.paths['log']
        else:
            self.logPath = '/logs/apitax.log'
        self.logColorize = True
        self.logPrefixes = True
        self.logHumanReadable = False

        # print(getRootPath('/config.txt'))
        if State.paths['config'] != "":
            configFile = State.paths['config']
        else:
            configFile = getRoot('/config.txt')
        self.config = ConfigConsumer.read()
        self.config.path = str(Path(os.path.dirname(os.path.abspath(inspect.stack()[0][1]))).resolve())
        # print(getRootPath())

        if self.config.has('default-mode'):
            self.usage = self.config.get('default-mode')

        if self.config.has('log'):
            self.doLog = self.config.get('log')

        if self.config.has('log-file'):
            self.logPath = self.config.get('log-file')

        if self.config.has('log-colorize'):
            self.logColorize = self.config.get('log-colorize')

        if self.config.has('log-human-readable'):
            self.logHumanReadable = self.config.get('log-human-readable')

        if self.config.has('log-prefixes'):
            self.logPrefixes = self.config.get('log-prefixes')

        if self.logPath[:1] != '/':
            self.logPath = '/' + self.logPath

        # self.logPath = getRootPath(self.logPath)

        if self.config.has('log-buffered') and self.config.get('log-buffered'):
            logDriver = BufferedLog()
        else:
            logDriver = StandardLog()

        self.log = Log(logDriver, logFile=self.logPath, doLog=self.doLog, logColorize=self.logColorize,
                       logPrefixes=self.logPrefixes,
                       logHumanReadable=self.logHumanReadable)

        self.log.log('')
        self.log.log('')
        self.log.log(">>>  Apitax - Combining the power of Commandtax and Scriptax")
        self.log.log('')
        self.log.log('')

        if '--cli' in self.args:
            self.usage = 'cli'
        elif '--api' in self.args:
            self.usage = 'api'
        elif '--grammar-test' in self.args:
            self.usage = 'grammar-test'
        elif '--feature-test' in self.args:
            self.usage = 'feature-test'

        if '--debug' in self.args:
            self.debug = True

        if '--sensitive' in self.args:
            self.sensitive = True

        if '--reloader' in self.args:
            self.reloader = True

        if '-u' in self.args:
            self.username = self.args[self.args.index('-u') + 1]

        if '-p' in self.args:
            self.password = click.prompt('Enter Your Password', hide_input=True)

        if '-s' in self.args:
            self.script = self.args[self.args.index('-s') + 1]

        if '-r' in self.args:
            self.command = self.args[self.args.index('-r') + 1]
        elif self.script == '' and self.usage == 1:
            self.command = click.prompt('R')

        # This is to turn the '-s' flag into a command behind the scenes
        if self.script != '':
            self.command = 'script ' + self.script

        self.options = Options(debug=self.debug, sensitive=self.sensitive)

        self.loggingSettings = self.log.getLoggerSettings()

        self.log.log('>> Runtime Settings:')

        self.log.log('    * Paths')

        self.log.log('      * Root:   ' + State.paths['root'])

        self.log.log('      * Config: ' + configFile)

        self.log.log('      * Log:    ' + str(self.loggingSettings.get('path')))

        self.log.log('      * Apitax: ' + State.paths['apitax'])

        self.log.log('    * Debug: ' + str(self.debug))

        self.log.log('    * Sensitive: ' + str(self.sensitive))

        self.log.log('    * Operating out of: ' + str(self.config.path))

        self.log.log('    * Logging: ' + str(self.loggingSettings.get('doLog')))

        if self.loggingSettings.get('doLog'):
            self.log.log('      * Colorize CLI: ' + str(self.loggingSettings.get('colorize')))

        self.log.log('')
        self.log.log('')

        if self.options.debug:
            self.log.log('>> Setting up AppState')
            self.log.log('')
            self.log.log('')

        # Setup App State
        State.config = self.config
        State.options = self.options
        State.log = self.log
        if State.paths['log'] == "":
            State.paths['log'] = self.logPath
        if State.paths['root'] == "":
            State.paths['root'] = getRoot()
        if State.paths['apitax'] == "":
            State.paths['apitax'] = str(Path(os.path.dirname(os.path.abspath(inspect.stack()[0][1]))).resolve())
        if State.paths['config'] == "":
            State.paths['config'] = configFile

        if (self.options.debug):
            self.log.log('>> Loading Drivers')
            self.log.log('')

        self.log.getLoggerDriver().outputLog()
示例#6
0
State.log.log("> test")
State.log.log("")

Drivers.add("commandtax", Commandtax())
Drivers.add("scriptax", Scriptax())
Drivers.add("std", StandardLibrary())
Drivers.add("api", Api())
Drivers.add("apixml", ApiXml())
LoadedDrivers.load("commandtax")
LoadedDrivers.load("scriptax")
LoadedDrivers.load("std")
LoadedDrivers.load("api")
LoadedDrivers.load("apixml")

#scriptax = "from std import String as stdstr; log(stdstr.substr(text='this_is_some_fantastic_text', start=3, length=10));"
#scriptax = "from std import Map as map; mymap = new map(); mymap.map.test = 'wtf'; mymap.map.bob = 'yes'; mymap.map.shawn = {'noway': 'yesway'}; log(mymap.has(key='noway', sMap=mymap.map.shawn)); return 'test complete';"
#scriptax = "from std import Restapi as stdapi; mydata = {}; mydata.title = 'awesome'; mydata.body='shawn is'; mydata.id=5; log(stdapi.jget(endp='https://jsonplaceholder.typicode.com/posts')); log(stdapi.jpost(endp='https://jsonplaceholder.typicode.com/posts', dataPost=mydata)); return 'test complete';"
#scriptax = "from std import Restapi as stdapi; mydata = {}; mydata.title = 'awesome'; mydata.body='shawn is'; mydata.id=555; log(stdapi.jpost(endp='https://jsonplaceholder.typicode.com/posts', dataPost=mydata)); return 'test complete';"
#scriptax = "from std import Restapi(debug=true) as stdapi; mydata = {}; mydata.title = 'awesome'; mydata.body='shawn is'; mydata.id=555; log(stdapi.dpost(driver='api',endp='https://jsonplaceholder.typicode.com/posts', dataPost=mydata)); return 'test complete';"
#scriptax = "from std import Json as stdjson; mydata = {}; mydata.title = 'awesome'; mydata.body='shawn is'; mydata.id=555; log(mydata); log(stdjson.toJson(obj=mydata)); log(ct('api --url https://jsonplaceholder.typicode.com/posts --post --data-post \\\'' + stdjson.toJson(obj=mydata) + '\\\''));"

#scriptax = "from std import Restapi(debug=true) as stdapi; mydata = {}; mydata.title = 'awesome'; mydata.body='shawn is'; mydata.id=555; mydata.something = {}; mydata.somnething={\"address\":\"address\",\"city\":\"Regina\",\"email\":\"[email protected]\",\"extra\":{},\"fax\":\"123456789\",\"name\":\"Tristans Legit Clinic\",\"phone_number\":\"987654321\",\"province\":\"Saskatchewan\"}; log(mydata); log(stdapi.dpost(driver='api',endp='https://jsonplaceholder.typicode.com/posts', dataPost=mydata)); return 'test complete';"

scriptax = "from std import Json as stdjson; from std import Restapi(debug=true) as stdapi; mydata={\"address\":\"address\",\"city\":\"Regina\",\"email\":\"[email protected]\",\"extra\":{},\"fax\":\"123456789\",\"name\":\"Tristans Legit Clinic\",\"phone_number\":\"987654321\",\"province\":\"Saskatchewan\"}; log(mydata); log(ct('api --url https://jsonplaceholder.typicode.com/posts --post --data-post \\\'' + stdjson.toJson(obj=mydata) + '\\\''));"

visitor = customizableParser(scriptax, file='inline_program', options=Options(debug=True))

print('Return: ' + str(visitor[0][1]))
print()
print("===")
示例#7
0
def command(driver, execute=None):  # noqa: E501
    """Execute a Command

    Execute a command # noqa: E501

    :param driver: The driver to use for the request. ie. github
    :type driver: str
    :param execute: The data needed to execute this command
    :type execute: dict | bytes

    :rtype: Response
    """
    if connexion.request.is_json:
        execute = Execute.from_dict(connexion.request.get_json())  # noqa: E501

    # TODO: Utilize the driver passed rather than the first string component

    response = errorIfUnauthorized(role='user')
    if response:
        return response

    try:
        parameters = {}

        if execute.command.parameters:
            parameters = execute.command.parameters

        credentials = Credentials()

        options = Options()

        if execute.command.options:
            if 'debug' in execute.command.options:
                options.debug = execute.command.options['debug']

            if 'sensitive' in execute.command.options:
                options.sensitive = execute.command.options['sensitive']

        if execute.auth:
            credentials = mapUserAuthToCredentials(execute.auth, credentials)
            if not execute.auth.api_token:
                options.sensitive = True

        connector = Connector(options=options, credentials=credentials, command=driver + " " + execute.command.command,
                              parameters=parameters)

        response: ApitaxResponse = connector.execute()

        response = Response(status=response.getResponseStatusCode(), body=response.getResponseBody())

        if options.debug:
            response.log = connector.logBuffer

        return response
    except:
        State.log.error(traceback.format_exc())
        State.log.getLoggerDriver().outputLog()
        if 'debug' in execute.command.options and execute.command.options['debug']:
            return ErrorResponse(status=500,
                                 message="Uncaught exception occured during processing. To get a larger stack trace, visit the logs.",
                                 state=traceback.format_exc())
        else:
            return ErrorResponse(status=500, message="")
示例#8
0
def execute(scriptax: str) -> Tuple[BlockStatus, AhVisitor]:
    return customizable_parser(read_string(scriptax),
                               file='inline_program',
                               options=Options(debug=True))