Example #1
0
    def parse(self):
        self.INP_DATA = {}

        if self.CMD is None:
            out.printAbout()
            return False

        if self.CMD == "autocomplete":
            # substitute arguments for AutoComplete
            # 1 offset to make the argument as 1 is autocomplete
            self.__init__(self.sys_argv[1:])
            self.printAutocomplete()
            return False

        if self.CMD == "--help":
            self.printHelp()
            return False

        if self.CMD not in self.COMMANDS:
            self.printErrorCommand()
            return False

        if "--help" in self.INP:
            self.printHelp()
            return False

        # prepare data
        for arg, params in (self.CMD_ARGS.items() + self.CMD_FLAGS.items()):
            # set values by default
            if 'default' in params:
                self.INP_DATA[arg] = params['default']

            # replace `altName` entered arguments on full
            if 'altName' in params and params['altName'] in self.INP:
                self.INP[self.INP.index(params['altName'])] = arg

        activeArg = None
        ACTIVE_CMD = None
        # check and insert first argument by default
        if 'firstArg' in self.COMMANDS[self.CMD]:
            firstArg = self.COMMANDS[self.CMD]['firstArg']
            if len(self.INP) > 0:
                # Check that first argument is a default argument
                # and another argument.
                if self.INP[0] not in (self.CMD_ARGS.keys() +
                                       self.CMD_FLAGS.keys()):
                    self.INP = [firstArg, ] + self.INP
            else:
                self.INP = [firstArg, ]

        for item in self.INP:
            # check what are waiting the argument
            if activeArg is None:
                # actions for the argument
                if item in self.CMD_ARGS:
                    activeArg = item
                    ACTIVE_CMD = self.CMD_ARGS[activeArg]

                # actions for the flag
                elif item in self.CMD_FLAGS:
                    self.INP_DATA[item] = self.CMD_FLAGS[item]["value"]

                # error. parameter is not found
                else:
                    self.printErrorArgument(item)
                    return False

            else:
                activeArgTmp = None
                # values it is parameter
                if item in self.CMD_ARGS or item in self.CMD_FLAGS:
                    # active argument is "emptyValue"
                    if "emptyValue" in ACTIVE_CMD:
                        activeArgTmp = item # remember the new "active" argument
                        item = ACTIVE_CMD['emptyValue']  # set the active atgument to emptyValue
                    # Error, "active" argument has no values
                    else:
                        self.printErrorArgument(activeArg, item)
                        return False

                if 'type' in ACTIVE_CMD:
                    convType = ACTIVE_CMD['type']
                    if convType not in (int, str):
                        logging.error("Unsupported argument type: %s", convType)
                        return False

                    try:
                        item = convType(item)
                    except:
                        self.printErrorArgument(activeArg, item)
                        return False

                self.INP_DATA[activeArg] = item
                activeArg = activeArgTmp  # this is either a new "active" argument or emptyValue.

        # if there are still active arguments
        if activeArg is not None:
            # if the active argument is emptyValue
            if 'emptyValue' in ACTIVE_CMD:
                self.INP_DATA[activeArg] = ACTIVE_CMD['emptyValue']

            # An error argument
            else:
                self.printErrorArgument(activeArg, "")
                return False

        # check whether there is a necessary argument request
        for arg, params in (self.CMD_ARGS.items() + self.CMD_FLAGS.items()):
            if 'required' in params and arg not in self.INP:
                self.printErrorReqArgument(arg)
                return False

        # trim -- and ->_
        self.INP_DATA = dict([key.lstrip("-").replace("-", "_"), val] for key, val in self.INP_DATA.items())
        return self.INP_DATA
Example #2
0
    def parse(self):
        self.INP_DATA = {}

        if self.CMD is None:
            out.printAbout()
            return False

        if self.CMD == "autocomplete":
            # подставляем аргументы для автозаполнения
            # делаем смещение на 1 аргумент, т.к. 1 это autocomplete
            self.__init__(self.sys_argv[1:])
            self.printAutocomplete()
            return False

        if self.CMD == "--help":
            self.printHelp()
            return False

        if not self.COMMANDS.has_key(self.CMD):
            self.printErrorCommand()
            return False

        if "--help" in self.INP:
            self.printHelp()
            return False

        # Подготовка данных
        for arg, params in (self.CMD_ARGS.items() + self.CMD_FLAGS.items()):
            # установка значений по умолчаеию
            if params.has_key('default'):
                self.INP_DATA[arg] = params['default']

            # замена altName во входящих аргументах на полные
            if params.has_key('altName') and params['altName'] in self.INP:
                self.INP[self.INP.index(params['altName'])] = arg

        activeArg = None
        ACTIVE_CMD = None
        # проверяем и подставляем первый адгумент по умолчанию
        if self.COMMANDS[self.CMD].has_key('firstArg'):
            firstArg = self.COMMANDS[self.CMD]['firstArg']
            if len(self.INP) > 0:
                # смотрим что первое знаение не аргумент по умолчанию, а другой аргумент
                if self.INP[0] not in (self.CMD_ARGS.keys() + self.CMD_FLAGS.keys()):
                    self.INP = [firstArg, ] + self.INP
            else:
                self.INP = [firstArg, ]
        

        for item in self.INP:
            # Проверяем что ожидаем аргумент
            if activeArg is None:
                # Действия для аргумента
                if self.CMD_ARGS.has_key(item):
                    activeArg = item
                    ACTIVE_CMD = self.CMD_ARGS[activeArg]

                # Действия для флага
                elif self.CMD_FLAGS.has_key(item):
                    self.INP_DATA[item] = self.CMD_FLAGS[item]["value"]

                # Ошибка параметр не найден
                else:
                    self.printErrorArgument(item)
                    return False

            else:
                activeArgTmp = None
                # Значения является параметром
                if self.CMD_ARGS.has_key(item) or self.CMD_FLAGS.has_key(item):
                    # "Активный" аргумент имеет параметр emptyValue
                    if ACTIVE_CMD.has_key("emptyValue"):
                        activeArgTmp = item # запоминаем новый "активный" аргумент
                        item = ACTIVE_CMD['emptyValue'] # подменяем значение на emptyValue
                    # Ошибка, "активный" аргумент не имеет значений
                    else:
                        self.printErrorArgument(activeArg, item)
                        return False

                if ACTIVE_CMD.has_key("type"):
                    convType = ACTIVE_CMD['type']
                    if convType not in (int, str):
                        logging.error("Unsupported argument type: %s", convType)
                        return False

                    try:
                        item = convType(item)
                    except:
                        self.printErrorArgument(activeArg, item)
                        return False

                self.INP_DATA[activeArg] = item
                activeArg = activeArgTmp # тут или пусто, или новый "активный" аргумент

        # если остались "активные" аршументы
        if activeArg is not None:
            # если есть параметр emptyValue
            if ACTIVE_CMD.has_key("emptyValue"):
                self.INP_DATA[activeArg] = ACTIVE_CMD['emptyValue']

            # инече ошибка
            else:
                self.printErrorArgument(activeArg, "")
                return False

        # проверка, присутствует ли необходимый аргумент запросе
        for arg, params in (self.CMD_ARGS.items() + self.CMD_FLAGS.items()):
            if params.has_key('required') and arg not in self.INP:
                self.printErrorReqArgument(arg)
                return False

        # trim -- and ->_
        self.INP_DATA = dict([key.lstrip("-").replace("-", "_"), val] for key, val in self.INP_DATA.items() )
        return self.INP_DATA
Example #3
0
    def parse(self):
        self.INP_DATA = {}

        if self.CMD is None:
            out.printAbout()
            return False

        if self.CMD == "autocomplete":
            # substitute arguments for AutoComplete
            # 1 offset to make the argument as 1 is autocomplete
            self.__init__(self.sys_argv[1:])
            self.printAutocomplete()
            return False

        if self.CMD == "--help":
            self.printHelp()
            return False

        if self.CMD not in self.COMMANDS:
            self.printErrorCommand()
            return False

        if "--help" in self.INP:
            self.printHelp()
            return False

        # prepare data
        for arg, params in (self.CMD_ARGS.items() + self.CMD_FLAGS.items()):
            # set values by default
            if 'default' in params:
                self.INP_DATA[arg] = params['default']

            # replace `altName` entered arguments on full
            if 'altName' in params and params['altName'] in self.INP:
                self.INP[self.INP.index(params['altName'])] = arg

        activeArg = None
        ACTIVE_CMD = None
        # check and insert first argument by default
        if 'firstArg' in self.COMMANDS[self.CMD]:
            firstArg = self.COMMANDS[self.CMD]['firstArg']
            if len(self.INP) > 0:
                # Check that first argument is a default argument
                # and another argument.
                if self.INP[0] not in (self.CMD_ARGS.keys() +
                                       self.CMD_FLAGS.keys()):
                    self.INP = [
                        firstArg,
                    ] + self.INP
            else:
                self.INP = [
                    firstArg,
                ]

        for item in self.INP:
            # check what are waiting the argument
            if activeArg is None:
                # actions for the argument
                if item in self.CMD_ARGS:
                    activeArg = item
                    ACTIVE_CMD = self.CMD_ARGS[activeArg]

                # actions for the flag
                elif item in self.CMD_FLAGS:
                    self.INP_DATA[item] = self.CMD_FLAGS[item]["value"]

                # error. parameter is not found
                else:
                    self.printErrorArgument(item)
                    return False

            else:
                activeArgTmp = None
                # values it is parameter
                if item in self.CMD_ARGS or item in self.CMD_FLAGS:
                    # active argument is "emptyValue"
                    if "emptyValue" in ACTIVE_CMD:
                        activeArgTmp = item  # remember the new "active" argument
                        item = ACTIVE_CMD[
                            'emptyValue']  # set the active atgument to emptyValue
                    # Error, "active" argument has no values
                    else:
                        self.printErrorArgument(activeArg, item)
                        return False

                if 'type' in ACTIVE_CMD:
                    convType = ACTIVE_CMD['type']
                    if convType not in (int, str):
                        logging.error("Unsupported argument type: %s",
                                      convType)
                        return False

                    try:
                        item = convType(item)
                    except:
                        self.printErrorArgument(activeArg, item)
                        return False

                self.INP_DATA[activeArg] = item
                activeArg = activeArgTmp  # this is either a new "active" argument or emptyValue.

        # if there are still active arguments
        if activeArg is not None:
            # if the active argument is emptyValue
            if 'emptyValue' in ACTIVE_CMD:
                self.INP_DATA[activeArg] = ACTIVE_CMD['emptyValue']

            # An error argument
            else:
                self.printErrorArgument(activeArg, "")
                return False

        # check whether there is a necessary argument request
        for arg, params in (self.CMD_ARGS.items() + self.CMD_FLAGS.items()):
            if 'required' in params and arg not in self.INP:
                self.printErrorReqArgument(arg)
                return False

        # trim -- and ->_
        self.INP_DATA = dict([key.lstrip("-").replace("-", "_"), val]
                             for key, val in self.INP_DATA.items())
        return self.INP_DATA
Example #4
0
    def parse(self):
        self.INP_DATA = {}

        if self.CMD is None:
            out.printAbout()
            return False

        if self.CMD == "autocomplete":
            # подставляем аргументы для автозаполнения
            # делаем смещение на 1 аргумент, т.к. 1 это autocomplete
            self.__init__(self.sys_argv[1:])
            self.printAutocomplete()
            return False

        if self.CMD == "--help":
            self.printHelp()
            return False

        if self.CMD not in self.COMMANDS:
            self.printErrorCommand()
            return False

        if "--help" in self.INP:
            self.printHelp()
            return False

        # prepare data
        for arg, params in (self.CMD_ARGS.items() + self.CMD_FLAGS.items()):
            # set values by default
            if 'default' in params:
                self.INP_DATA[arg] = params['default']

            # replace `altName` entered arguments on full
            if 'altName' in params and params['altName'] in self.INP:
                self.INP[self.INP.index(params['altName'])] = arg

        activeArg = None
        ACTIVE_CMD = None
        # check and insert first argument by default
        if 'firstArg' in self.COMMANDS[self.CMD]:
            firstArg = self.COMMANDS[self.CMD]['firstArg']
            if len(self.INP) > 0:
                # смотрим что первое знаение не аргумент по умолчанию,
                # а другой аргумент
                if self.INP[0] not in (self.CMD_ARGS.keys() +
                                       self.CMD_FLAGS.keys()):
                    self.INP = [firstArg, ] + self.INP
            else:
                self.INP = [firstArg, ]

        for item in self.INP:
            # check what are waiting the argument
            if activeArg is None:
                # Действия для аргумента
                if item in self.CMD_ARGS:
                    activeArg = item
                    ACTIVE_CMD = self.CMD_ARGS[activeArg]

                # actions for the flag
                elif item in self.CMD_FLAGS:
                    self.INP_DATA[item] = self.CMD_FLAGS[item]["value"]

                # error. parameter is not found
                else:
                    self.printErrorArgument(item)
                    return False

            else:
                activeArgTmp = None
                # values it is parameter
                if item in self.CMD_ARGS or item in self.CMD_FLAGS:
                    # "Активный" аргумент имеет параметр emptyValue
                    if "emptyValue" in ACTIVE_CMD:
                        activeArgTmp = item  # запоминаем новый "активный" аргумент
                        item = ACTIVE_CMD['emptyValue']  # подменяем значение на emptyValue
                    # Ошибка, "активный" аргумент не имеет значений
                    else:
                        self.printErrorArgument(activeArg, item)
                        return False

                if 'type' in ACTIVE_CMD:
                    convType = ACTIVE_CMD['type']
                    if convType not in (int, str):
                        logging.error("Unsupported argument type: %s", convType)
                        return False

                    try:
                        item = convType(item)
                    except:
                        self.printErrorArgument(activeArg, item)
                        return False

                self.INP_DATA[activeArg] = item
                activeArg = activeArgTmp  # тут или пусто, или новый "активный" аргумент

        # если остались "активные" аршументы
        if activeArg is not None:
            # если есть параметр emptyValue
            if 'emptyValue' in ACTIVE_CMD:
                self.INP_DATA[activeArg] = ACTIVE_CMD['emptyValue']

            # инече ошибка
            else:
                self.printErrorArgument(activeArg, "")
                return False

        # проверка, присутствует ли необходимый аргумент запросе
        for arg, params in (self.CMD_ARGS.items() + self.CMD_FLAGS.items()):
            if 'required' in params and arg not in self.INP:
                self.printErrorReqArgument(arg)
                return False

        # trim -- and ->_
        self.INP_DATA = dict([key.lstrip("-").replace("-", "_"), val] for key, val in self.INP_DATA.items())
        return self.INP_DATA
Example #5
0
    def parse(self):
        self.INP_DATA = {}

        if self.CMD is None:
            out.printAbout()
            return False

        if self.CMD == "autocomplete":
           
            self.__init__(self.sys_argv[1:])
            self.printAutocomplete()
            return False

        if self.CMD == "--help":
            self.printHelp()
            return False

        if not self.COMMANDS.has_key(self.CMD):
            self.printErrorCommand()
            return False

        if "--help" in self.INP:
            self.printHelp()
            return False

      
        for arg, params in (self.CMD_ARGS.items() + self.CMD_FLAGS.items()):
   
            if params.has_key('default'):
                self.INP_DATA[arg] = params['default']

           
            if params.has_key('altName') and params['altName'] in self.INP:
                self.INP[self.INP.index(params['altName'])] = arg

        activeArg = None
        ACTIVE_CMD = None
        
        if self.COMMANDS[self.CMD].has_key('firstArg'):
            firstArg = self.COMMANDS[self.CMD]['firstArg']
            if len(self.INP) > 0:
                
                if self.INP[0] not in (self.CMD_ARGS.keys() + self.CMD_FLAGS.keys()):
                    self.INP = [firstArg, ] + self.INP
            else:
                self.INP = [firstArg, ]
        

        for item in self.INP:
            
            if activeArg is None:
                
                if self.CMD_ARGS.has_key(item):
                    activeArg = item
                    ACTIVE_CMD = self.CMD_ARGS[activeArg]

                
                elif self.CMD_FLAGS.has_key(item):
                    self.INP_DATA[item] = self.CMD_FLAGS[item]["value"]

           
                else:
                    self.printErrorArgument(item)
                    return False

            else:
                activeArgTmp = None
               
                if self.CMD_ARGS.has_key(item) or self.CMD_FLAGS.has_key(item):
                    
                    if ACTIVE_CMD.has_key("emptyValue"):
                        activeArgTmp = item 
                        item = ACTIVE_CMD['emptyValue'] 
                    else:
                        self.printErrorArgument(activeArg, item)
                        return False

                if ACTIVE_CMD.has_key("type"):
                    convType = ACTIVE_CMD['type']
                    if convType not in (int, str):
                        logging.error("Unsupported argument type: %s", convType)
                        return False

                    try:
                        item = convType(item)
                    except:
                        self.printErrorArgument(activeArg, item)
                        return False

                self.INP_DATA[activeArg] = item
                activeArg = activeArgTmp 

       
        if activeArg is not None:
          
            if ACTIVE_CMD.has_key("emptyValue"):
                self.INP_DATA[activeArg] = ACTIVE_CMD['emptyValue']

            
            else:
                self.printErrorArgument(activeArg, "")
                return False

        
        for arg, params in (self.CMD_ARGS.items() + self.CMD_FLAGS.items()):
            if params.has_key('required') and arg not in self.INP:
                self.printErrorReqArgument(arg)
                return False

       
        self.INP_DATA = dict([key.lstrip("-").replace("-", "_"), val] for key, val in self.INP_DATA.items() )
        return self.INP_DATA
Example #6
0
def main(args=None):
    try:
        exit_status_code = 0

        sys_argv = sys.argv[1:]
        if isinstance(args, list):
            sys_argv = args

        sys_argv = tools.decodeArgs(sys_argv)

        COMMAND = sys_argv[0] if len(sys_argv) >= 1 else None
        aparser = argparser(sys_argv)
        ARGS = aparser.parse()

        # Didn't read any command line arguments, and not attached
        # to an interactive tty?
        # If so, look for input on piped stream
        if COMMAND is None and not config.IS_IN_TERMINAL:
            COMMAND, ARGS = modifyArgsByStdinStream()

        if COMMAND is None:
            out.printAbout()

        # error or help
        if COMMAND is None or ARGS is False:
            return tools.exitErr()

        logging.debug("CLI options: %s", str(ARGS))

        # Users
        if COMMAND == 'user':
            User().user(**ARGS)

        if COMMAND == 'login':
            User().login(**ARGS)

        if COMMAND == 'logout':
            User().logout(**ARGS)

        if COMMAND == 'settings':
            User().settings(**ARGS)

        # Notes
        if COMMAND == 'create':
            Notes().create(**ARGS)

        if COMMAND == 'edit':
            Notes().edit(**ARGS)

        if COMMAND == 'remove':
            Notes().remove(**ARGS)

        if COMMAND == 'show':
            Notes().show(**ARGS)

        if COMMAND == 'find':
            Notes().find(**ARGS)

        # Notebooks
        if COMMAND == 'notebook-list':
            Notebooks().list(**ARGS)

        if COMMAND == 'notebook-create':
            Notebooks().create(**ARGS)

        if COMMAND == 'notebook-edit':
            Notebooks().edit(**ARGS)

        if COMMAND == 'notebook-remove':
            Notebooks().remove(**ARGS)

        # Tags
        if COMMAND == 'tag-list':
            Tags().list(**ARGS)

        if COMMAND == 'tag-create':
            Tags().create(**ARGS)

        if COMMAND == 'tag-edit':
            Tags().edit(**ARGS)

        if COMMAND == 'tag-remove':
            Tags().remove(**ARGS)

    except (KeyboardInterrupt, SystemExit, tools.ExitException), e:
        if e.message:
            exit_status_code = e.message
Example #7
0
    def parse(self):
        self.INP_DATA = {}

        if self.CMD is None:
            out.printAbout()
            return False

        if self.CMD == "autocomplete":
            # подставляем аргументы для автозаполнения
            # делаем смещение на 1 аргумент, т.к. 1 это autocomplete
            self.__init__(self.sys_argv[1:])
            self.printAutocomplete()
            return False

        if self.CMD == "--help":
            self.printHelp()
            return False

        if self.CMD not in self.COMMANDS:
            self.printErrorCommand()
            return False

        if "--help" in self.INP:
            self.printHelp()
            return False

        # prepare data
        for arg, params in (self.CMD_ARGS.items() + self.CMD_FLAGS.items()):
            # set values by default
            if 'default' in params:
                self.INP_DATA[arg] = params['default']

            # replace `altName` entered arguments on full
            if 'altName' in params and params['altName'] in self.INP:
                self.INP[self.INP.index(params['altName'])] = arg

        activeArg = None
        ACTIVE_CMD = None
        # check and insert first argument by default
        if 'firstArg' in self.COMMANDS[self.CMD]:
            firstArg = self.COMMANDS[self.CMD]['firstArg']
            if len(self.INP) > 0:
                # смотрим что первое знаение не аргумент по умолчанию,
                # а другой аргумент
                if self.INP[0] not in (self.CMD_ARGS.keys() +
                                       self.CMD_FLAGS.keys()):
                    self.INP = [
                        firstArg,
                    ] + self.INP
            else:
                self.INP = [
                    firstArg,
                ]

        for item in self.INP:
            # check what are waiting the argument
            if activeArg is None:
                # Действия для аргумента
                if item in self.CMD_ARGS:
                    activeArg = item
                    ACTIVE_CMD = self.CMD_ARGS[activeArg]

                # actions for the flag
                elif item in self.CMD_FLAGS:
                    self.INP_DATA[item] = self.CMD_FLAGS[item]["value"]

                # error. parameter is not found
                else:
                    self.printErrorArgument(item)
                    return False

            else:
                activeArgTmp = None
                # values it is parameter
                if item in self.CMD_ARGS or item in self.CMD_FLAGS:
                    # "Активный" аргумент имеет параметр emptyValue
                    if "emptyValue" in ACTIVE_CMD:
                        activeArgTmp = item  # запоминаем новый "активный" аргумент
                        item = ACTIVE_CMD[
                            'emptyValue']  # подменяем значение на emptyValue
                    # Ошибка, "активный" аргумент не имеет значений
                    else:
                        self.printErrorArgument(activeArg, item)
                        return False

                if 'type' in ACTIVE_CMD:
                    convType = ACTIVE_CMD['type']
                    if convType not in (int, str):
                        logging.error("Unsupported argument type: %s",
                                      convType)
                        return False

                    try:
                        item = convType(item)
                    except:
                        self.printErrorArgument(activeArg, item)
                        return False

                self.INP_DATA[activeArg] = item
                activeArg = activeArgTmp  # тут или пусто, или новый "активный" аргумент

        # если остались "активные" аршументы
        if activeArg is not None:
            # если есть параметр emptyValue
            if 'emptyValue' in ACTIVE_CMD:
                self.INP_DATA[activeArg] = ACTIVE_CMD['emptyValue']

            # инече ошибка
            else:
                self.printErrorArgument(activeArg, "")
                return False

        # проверка, присутствует ли необходимый аргумент запросе
        for arg, params in (self.CMD_ARGS.items() + self.CMD_FLAGS.items()):
            if 'required' in params and arg not in self.INP:
                self.printErrorReqArgument(arg)
                return False

        # trim -- and ->_
        self.INP_DATA = dict([key.lstrip("-").replace("-", "_"), val]
                             for key, val in self.INP_DATA.items())
        return self.INP_DATA