Beispiel #1
0
 def __init__(self):
     self.state = MainAppState.INIT
     self.display = Display()
     self.ee = BaseEventEmitter()
     self.cli = None
     if Config.ENABLE_CLI:
         self.cli = Cli()
Beispiel #2
0
    def __init__(self, should_perform_task_setup=True):
        from logger import log

        self.cli = Cli()

        # want some help
        self.cli.show_and_exit_on_help_request()

        # load/import task module
        self.task = self.cli.load_command()

        # get command specific args
        self.command_args = self.cli.get_command_args()

        # get global args
        self.global_args = self.cli.get_global_args()

        if should_perform_task_setup:
            # set log level
            if self.global_args['--debug']:
                log.setLogLevel(logging.DEBUG)
            else:
                log.setLogLevel(logging.INFO)

            # set log file
            if self.global_args['--logfile']:
                log.set_logfile(
                    self.global_args['--logfile']
                )
 def test_run_write(self):
     spy = mock.Mock(wraps=Feed())
     cli = Cli(spy)
     cli.run(self.josh_hello_cmd)
     spy.post_message.assert_called_once_with(username="******",
                                              message="Hello!")
     spy.get_messages_of.assert_not_called()
Beispiel #4
0
def start():
    core.file.SEARCH_PATH = os.getcwd()
    os.chdir(os.path.abspath(os.path.dirname(__file__)))
    control = Control()
    instance = Cli(control)
    #controller.register_view(instance, Attributes.CLI_ATTRIBUTES)
    instance.start()
def main():
    conn = sqlite3.connect(DB_NAME)
    conn.row_factory = sqlite3.Row

    cinema_db_manager = CinemaDatabaseManager(conn)
    client_interface = Cli(cinema_db_manager)

    client_interface.start()
Beispiel #6
0
 def test_get_all_arguments(self):
     cli = Cli()
     with patch.object(sys, 'argv', ["prog", "something", 4]):
         assert cli.get_all_arguments() == ["prog", "something", 4], "wrong user parameters getting"
     with patch.object(sys, 'argv', ["prog"]):
         assert cli.get_all_arguments() == ["prog"], "wrong user parameters getting"
     with patch.object(sys, 'argv', []):
         assert cli.get_all_arguments() == [], "wrong user parameters getting"
Beispiel #7
0
    def test_defaults(self):
        cli = Cli()
        opt, vls = cli.parse()

        self.assertEquals(opt.message, '')
        self.assertEquals(opt.soundfile, None)
        self.assertEquals(opt.exitat, 5)
        self.assertEquals(opt.timeline, False)
        self.assertEquals(opt.fullscreen, False)
        self.assertEquals(opt.alarm, False)
Beispiel #8
0
    def test_defaults(self):
        cli = Cli()
        opt, vls = cli.parse()

        self.assertEquals(opt.message, '')
        self.assertEquals(opt.soundfile, None)
        self.assertEquals(opt.exitat, 5)
        self.assertEquals(opt.timeline, False)
        self.assertEquals(opt.fullscreen, False)
        self.assertEquals(opt.alarm, False)
Beispiel #9
0
def main():
    """ The main function executes the program """
    logging.config.fileConfig(LOG_CONF)
    cli = Cli()
    cli.parse_arguments_advanced()
    try:
        ret = cli.args_handel()
        if ret[0] == Cmd.invalid_input:
            sys.exit("invalid input")
        logging.debug(f'Arguments received: {ret}')
    except Exception as ex:
        logging.error(f'Failed to handel args, error: {ex}')
        sys.exit("invalid input")

    sc = Scrapping()
    cat = ret[1]
    sub_cats = ret[2]

    exist_cat = sc.get_category_list(URL)
    logging.debug(f'List of categories: {exist_cat}')

    if ret[0] == Cmd.cat_list:
        print(exist_cat)
    elif ret[0] == Cmd.sub_cat_list:
        if cat not in exist_cat:
            logging.error(f'Invalid input: category {cat} not exists')
            sys.exit("invalid input")
        cat_link = sc.get_category_links(URL, cat)
        sub_category_list = sc.get_category_list(cat_link[cat])
        print(sub_category_list)
    elif ret[0] == Cmd.write_to_db:
        if cat not in exist_cat:
            logging.error(f'Invalid input: category {cat} not exists')
            sys.exit("invalid input")

        cat_link = sc.get_category_links(URL, cat)
        exist_subcat = sc.get_category_list(cat_link[cat])
        if set(sub_cats) - set(exist_subcat) != set():
            logging.error(f'Invalid input: at least on of subcategories {sub_cats} not exists')
            sys.exit("invalid input")

        cat_link = sc.get_category_links(URL, cat)
        sub_cat_links = sc.get_category_links(cat_link[cat], sub_cats)
        recipes = {}
        for sub_cat, link in sub_cat_links.items():
            recipes[sub_cat] = sc.get_recipe_links(link)

        logging.debug(f'Scrap for categories: {cat}, and sub-categories: {sub_cat}')
        data_sc = sc.scrap_data(cat, recipes)
        api = API()
        data_api = api.get_info_ingred()
        sc.write_data_to_csv(data_sc, REC_FILENAME, RECIPE_DETAILS)
        sc.write_data_to_csv(data_api, ING_FILENAME, ING_DETAILS)
        db = DataBase(DB_HOST, DB_USER, DB_PASSWD, DB_NAME)
        db.write_data_to_db(data_sc, data_api)
Beispiel #10
0
    def test_if_have_just_those_options(self):
        cli = Cli()
        opt, vls = cli.parse()

        #FIXME: need to find another way to test if 'Cli' just have that options
        self.assertEquals(opt, {'fullscreen': False,
                                'message': '',
                                'exitat': 5,
                                'soundfile': None,
                                'timeline': False,
                                'debug': False,
                                'alarm': False,
                                'color': ''})
Beispiel #11
0
def main(argv):
    opts = None
    try:
        opts, args = getopt.getopt(argv[1:],
                                   'hcsa:u:p:',
                                   ["help", "client", "server", "app=", "user="******"password="******"unhandled option"

    if server:
        conf = {
            '/': {
                'tools.sessions.on': True
            }
        }

        cherrypy.quickstart(SafeBox(os.environ['DB_KEY'], os.environ['MASTER_PASSWORD']), '/', conf)
    elif client:
        check_arg(app, "app is required")
        cli = Cli('http://localhost:8080')

        if user is None and password is None:
            cli.get(app)
        else:
            check_arg(user, "username of app required")
            check_arg(password, "password of app required")
            cli.save(app, user, password)
Beispiel #12
0
    def test_if_have_just_those_options(self):
        cli = Cli()
        opt, vls = cli.parse()

        #FIXME: need to find another way to test if 'Cli' just have that options
        self.assertEquals(
            opt, {
                'fullscreen': False,
                'message': '',
                'exitat': 5,
                'soundfile': None,
                'timeline': False,
                'debug': False,
                'alarm': False,
                'color': ''
            })
Beispiel #13
0
    def __init__(self, config, message_cb):
        # print MAC, set MAC is given and restart

        self.config = config
        self.mesh = MeshInterface(self.config, message_cb)

        self.kill_all = False
        self.deepsleep_timeout = 0
        self.new_lora_mac = None

        # self.mesh.statistics.sleep_function = self.deepsleep_init
        self.mesh.sleep_function = self.deepsleep_init

        self.cli = Cli(self.mesh, self)
        self.cli.sleep = self.deepsleep_init
        self.is_paused = False
        self._threads_start()
        _thread.start_new_thread(self.cli.process, (1, 2))


        self.ble_rpc = None
        if config.get("ble_api", False):
            try:
                from ble_rpc import BleRpc
            except:
                from _ble_rpc import BleRpc

            self.ble_rpc = BleRpc(self.config, self.mesh)
Beispiel #14
0
class Scheduler(object):
  """Manager object for outlet cron jobs"""
  def __init__(self, root_path=None):
    self._root_path = root_path
    self.refresh()

  def refresh(self):
    self._crontab = CronTab('root')
    self._cli = Cli()
    self._load()

  def _load(self):
    self._jobs = {}
    for cron in self._crontab:
      comment = cron.comment
      i = comment.find(CRON_APP_ID)
      if i >= 0:
        name = comment[i + len(CRON_APP_ID):].strip()  # get string after CRON_APP_ID
        self._jobs[name] = {
          'name': name,
          'outlets': self._cli.get_outlets(command=str(cron.command)),
          'enabled': cron.is_enabled(),
          'next': str(cron.schedule().get_next()),
          'cron': str(cron.render_time())
        }
    return self._jobs
  
  def __getitem__(self, key):
    return self._jobs[key]

  def __setitem__(self, key, item):
    self._jobs[key] = item

  def __delitem__(self, key):
    del self._jobs[key]

  def serialize(self):
    return [v for k, v in self._jobs.iteritems()]

  def save(self):
    # Remove old lightcontrol cron jobs
    crontab = self._crontab
    old_crons = [cron for cron in crontab if CRON_APP_ID in cron.comment]
    while len(old_crons):
      crontab.remove(old_crons.pop())

    # Add new ones
    client_exe = '%s/client.py' % self._root_path
    for job in self._jobs.itervalues():
      exe = client_exe
      for outlet in job['outlets']:
        if outlet['value'] is not None:
          exe += ' -%s %s' % (outlet['id'], 't' if int(outlet['value']) == 0 else 'f')
      
      cron = crontab.new(command=exe, comment='%s %s' %(CRON_APP_ID, job['name']))
      cron.setall(job['cron'])
      #TODO: enabled flag
    crontab.write()
Beispiel #15
0
class Atm(object):
    def run(self):
        self.__database.open()
        name = self.__interface.promptUser("what is your name? ")
        name = name.lower()
        pin = self.__interface.promptUser("what is your pin? ")
        user = User(name, pin)
        userIndex = self.__database.authenticate(user)
        if userIndex == -1:
            print("Access is denied!")

        else:
            user = self.__database.getUserData(userIndex)
            print("Welcome " + user.name + "!")
            Input = ""
            while Input != "exit":
                Input = self.__interface.promptUser(
                    "Withdrawal, Deposit, or Balance? ")
                Input = Input.lower()
                if Input == "withdrawal":
                    self._withdrawal(user)

                elif Input == "deposit":
                    self._deposit(user)

                elif Input == "balance":
                    self._balance(user)

                elif Input != "exit":
                    print("Invalid command!")
        self.__database.close()
        self._exit()

    def _withdrawal(self, user):
        m = self.__interface.promptUser(
            "How much would you like to withdrawal? ")
        m = int(m)
        user.money = user.money - m
        self.__database.save(user)
        self._balance(user)

    def __init__(self):
        super().__init__()
        self.__interface = Cli()
        self.__database = Database("database.txt")

    def _deposit(self, user):
        m = self.__interface.promptUser("How much would you like to deposit? ")
        m = int(m)
        user.money = user.money + m
        self.__database.save(user)
        self._balance(user)

    def _balance(self, user):
        print("Your balance is " + str(user.money) + "!")

    def _exit(self):
        print("Goodbye!")
Beispiel #16
0
def cli(*args):
    cli = Cli(os.environ.get('ATOMIX_HOST', 'localhost'),
              int(os.environ.get('ATOMIX_PORT', 5678)))
    try:
        if len(args) > 0:
            cli._process_command(*args)
        else:
            cli.run()
    except (EOFError, KeyboardInterrupt):
        cli.set_return_value(None)
Beispiel #17
0
def run(args):
    cli = Cli("example")
    num1 = int(args["NUM1"])
    num2 = int(args["NUM2"])

    total = num1 + num2
    total_minus_one = total - 1

    logger.info(f"{num1} plus {num2} is {total}")
    logger.info(f"minus 1 that's {total_minus_one}")
    logger.warn("QUICK MATHS")
Beispiel #18
0
    def test_parameters(self):
        cli = Cli()
        parser = cli.get_parser()

        self.assertTrue(parser.has_option("-m"))
        self.assertTrue(parser.has_option("--message"))

        self.assertTrue(parser.has_option("-s"))
        self.assertTrue(parser.has_option("--soundfile"))

        self.assertTrue(parser.has_option("-e"))
        self.assertTrue(parser.has_option("--exitat"))

        self.assertTrue(parser.has_option("-t"))
        self.assertTrue(parser.has_option("--timeline"))

        self.assertTrue(parser.has_option("-f"))
        self.assertTrue(parser.has_option("--fullscreen"))

        self.assertTrue(parser.has_option("-a"))
        self.assertTrue(parser.has_option("--alarm"))
Beispiel #19
0
def main():
    global SONM_CLI
    SONM_CLI = Cli(set_sonmcli())
    global INTERVIEWED_WORKERS
    INTERVIEWED_WORKERS = []
    global DEAD_WORKERS
    DEAD_WORKERS = []
    global CURL
    CURL = "curl -s https://dwh.livenet.sonm.com:15022/DWHServer/GetOrders/ -d"
    global ORDERS_FOR_REMOVAL
    ORDERS_FOR_REMOVAL = []
    global DEALS
    DEALS = []

    workers_count, workers_addrs = get_orders()

    print("========= Checking worker status ==========")
    for address in workers_addrs:
        threading.Thread(target=check_worker, kwargs={
            'address': address
        }).start()
        time.sleep(1)

    # waiting for all workers to be interviewed
    while len(INTERVIEWED_WORKERS) < workers_count:
        time.sleep(1)

    print("=========== Bad guys (" + str(len(DEAD_WORKERS)) +
          ") are: ===========")
    for i in DEAD_WORKERS:
        print(i)

    print("====== Gathering orders for removal ======")
    for address in DEAD_WORKERS:
        threading.Thread(target=get_orders_for_bad_suppliers,
                         kwargs={
                             'supplier': address
                         }).start()
    time.sleep(3)

    print("TOTAL Orders for removal: " + str(len(ORDERS_FOR_REMOVAL)))

    print("======== Removing orders... ========")
    for order in ORDERS_FOR_REMOVAL:
        threading.Thread(target=open_deal, kwargs={'order': order}).start()
        time.sleep(1)

    while True:
        if len(DEALS) == len(ORDERS_FOR_REMOVAL):
            break
    total_spendings = calc_expanses()
    print("=====================" + "\n" + "Total spendings: " +
          str(total_spendings) + " SNM")
Beispiel #20
0
    def test_parameters(self):
        cli = Cli()
        parser = cli.get_parser()

        self.assertTrue(parser.has_option("-m"))
        self.assertTrue(parser.has_option("--message"))

        self.assertTrue(parser.has_option("-s"))
        self.assertTrue(parser.has_option("--soundfile"))

        self.assertTrue(parser.has_option("-e"))
        self.assertTrue(parser.has_option("--exitat"))

        self.assertTrue(parser.has_option("-t"))
        self.assertTrue(parser.has_option("--timeline"))

        self.assertTrue(parser.has_option("-f"))
        self.assertTrue(parser.has_option("--fullscreen"))

        self.assertTrue(parser.has_option("-a"))
        self.assertTrue(parser.has_option("--alarm"))
Beispiel #21
0
def auto_complete():
    cli = Cli()
    complete = get_best_completions.Complete()
    input_ = cli.input()
    while input_ != QUIT_REQUEST:
        cli.output(complete.get_best_completions(input_))
        input_ = cli.input()
Beispiel #22
0
    def test_e2e(self):
        cli = Cli(Feed())
        cmds = [
            "Josh -> As Josh used to say",
            "Josh",
            "Josh follows Bob",
            "Bob -> @Josh whats'up?",
            "John -> pancakes",
            "Bob -> @John you cooking pancakes?",
            "Josh -> mamma mia",
            "Josh wall",
        ]
        parsed = [cli.parse(cmd) for cmd in cmds]
        run = [cli.run(cmd) for cmd in parsed]
        expected = [
            "mamma mia",
            "@John you cooking pancakes?",
            "@Josh whats'up?",
            "As Josh used to say",
        ]

        self.assertEqual(expected, run[-1])
Beispiel #23
0
def main(argv):

    _, mode, starter, emule = ["main.py", "pc", "1", "1"]

    emule = bool(int(emule))    # '0' -> 0 -> False
                                # '1' -> 1 -> True
    starter = int(starter)
    g = Game(bool(emule), mode)
    c = Cli(g)

    game = Thread(target=g.run, args=(starter,))
    cli = Thread(target=c.run)

    game.start()
    cli.start()
Beispiel #24
0
 def __init__(self):
     """Member variables will be cli
     """
     self.deploy = run_deploy
     self.monitor = run_monitor
     self.cluster = Cluster()
     self.thriftserver = ThriftServer()
     self.ll = log.set_level
     self.cli = Cli()
     self.passwd = run_passwd
     self.adduser = run_adduser
     self.import_conf = run_import_conf
     self.sql = run_fbsql
     self.c = run_cluster_use
     self.edit = run_edit
     self.delete = run_delete
Beispiel #25
0
def main(argv):
    opts = None
    try:
        opts, args = getopt.getopt(
            argv[1:], 'hcsa:u:p:',
            ["help", "client", "server", "app=", "user="******"password="******"unhandled option"

    if server:
        conf = {'/': {'tools.sessions.on': True}}

        cherrypy.quickstart(
            SafeBox(os.environ['DB_KEY'], os.environ['MASTER_PASSWORD']), '/',
            conf)
    elif client:
        check_arg(app, "app is required")
        cli = Cli('http://localhost:8080')

        if user is None and password is None:
            cli.get(app)
        else:
            check_arg(user, "username of app required")
            check_arg(password, "password of app required")
            cli.save(app, user, password)
Beispiel #26
0
    def __init__(self, config, message_cb):
        # print MAC, set MAC is given and restart

        self.config = config
        self.mesh = MeshInterface(config, message_cb)

        self.kill_all = False
        self.deepsleep_timeout = 0
        self.new_lora_mac = None
        # watchdog = Watchdog(meshaging, mesh)

        self.mesh.statistics.sleep_function = self.deepsleep_init
        self.mesh.sleep_function = self.deepsleep_init

        self.cli = Cli(self.mesh)
        self.cli.sleep = self.deepsleep_init
        _thread.start_new_thread(self.process, (1, 2))
        _thread.start_new_thread(self.cli.process, (1, 2))

        self.ble_rpc = None
        if config.get("ble_api", False):
            self.ble_rpc = BleRpc(self.config, self.mesh)
Beispiel #27
0
def main(ctx, hosts, debug):
    """A Powerful Zookeeper Client Tool."""
    cli = None
    try:
        # 解析参数
        config = parse_config(hosts=hosts, debug=debug)
        # 创建客户端
        cli = Cli(config=config)
        cli.connect()
        log.banner()
        # 进入交互界面
        loop_prompt(cli, config)
    except Exception as e:
        log.error(e)
        ctx.exit(code=1)
    finally:
        if cli:
            cli.quit()
        log.info('BYE!')
Beispiel #28
0

def deepsleep_init(timeout, new_MAC=None):
    """ initializes an deep-sleep sequence, that will be performed later """
    global deepsleep_timeout, kill_all, new_lora_mac
    deepsleep_timeout = timeout
    kill_all = True
    if new_MAC:
        new_lora_mac = new_MAC
    return


mesh.statistics.sleep_function = deepsleep_init
mesh.sleep_function = deepsleep_init

cli = Cli(mesh, rpc_handler, ble_comm)
cli.sleep = deepsleep_init

_thread.start_new_thread(cli.process, (1, 2))

try:
    while True:
        if kill_all:
            deepsleep_now()

        time.sleep(.1)
        pass

except KeyboardInterrupt:
    print('Got Ctrl-C')
except Exception as e:
Beispiel #29
0
import os, sys

from cli import Cli


if __name__ == "__main__":
    try:
        # cli = Cli()
        # cli.main()
        Cli.main()
    except KeyboardInterrupt:
        print('\nProcess interrupted by user')
        try:
            sys.exit(0)
        except SystemExit:
            os._exit(0) 
Beispiel #30
0
def main():
    args = get_args()
    cmd = Cli()
    result = getattr(cmd, args.command)(*args.args)
    pprint(result)
Beispiel #31
0
    elif args.file is not None:
        args.dirname, args.filename = os.path.split(args.file)

    if error is not None:
        print "Error: {}".format(error)
        parser.exit(1)

    return isGui, (args)


if __name__ == '__main__':
    print APP_NAME + "\n"
    if 'rtlsdr_update_timestamp'in os.environ:
        set_version_timestamp()

    isGui, args = __arguments()
    if isGui:
        app = RtlSdrScanner()
        app.SetClassName(APP_NAME)
        wx.Locale().Init2()
        frame = FrameMain(APP_NAME)
        if args.file is not None:
            frame.open(os.path.abspath(args.dirname), args.filename)
        app.MainLoop()
    else:
        try:
            Cli(args)
        except KeyboardInterrupt:
            print '\nAborted'
            exit(1)
Beispiel #32
0
    if error is not None:
        print "Error: {}".format(error)
        parser.exit(1)

    return isGui, (args)


if __name__ == '__main__':
    multiprocessing.freeze_support()
    pool = multiprocessing.Pool(initializer=__init_worker)
    print APP_NAME + "\n"
    if 'rtlsdr_update_timestamp'in os.environ:
        set_version_timestamp()

    isGui, args = __arguments()
    if isGui:
        app = RtlSdrScanner(pool)
        app.SetClassName(APP_NAME)
        wx.Locale().Init2()
        frame = FrameMain(APP_NAME, pool)
        if args.file is not None:
            frame.open(os.path.abspath(args.dirname), args.filename)
        app.MainLoop()
    else:
        try:
            Cli(pool, args)
        except KeyboardInterrupt:
            print '\nAborted'
            exit(1)
Beispiel #33
0
 def __init__(self):
     super().__init__()
     self.__interface = Cli()
     self.__database = Database("database.txt")
Beispiel #34
0
class PiSy(object):
    """
    PiSy main class
    """
    def __init__(self):
        self.cli = Cli()
        self.logger = Logger(self.cli.get_arg('verbosity_level'))

    def run(self):
        self._remove_deprecated_target_files()

        sources = self._read_source_files()
        self._write_target_files(sources)

    def _remove_deprecated_target_files(self):
        """
        remove sls files on target side
        :return: void
        """
        args = self.cli.get_args()
        dir_path = args.get('target')

        files = self._get_sls_files(dir_path)

        for file_path in files:
            self.logger.info('remove "%s"' % file_path)
            os.remove(file_path)

    def _write_target_files(self, sources):
        """
        write sls files on target side with replaced values
        :param sources:
        :return:  void
        """
        args = self.cli.get_args()
        dir_path = args.get('target')

        for key, content in sources.items():
            content = self._replace_secret_values(content)
            target_file = "%s/%s" % (dir_path, key)
            target_file_dir = os.path.dirname(target_file)

            # create directory
            if not os.path.isdir(target_file_dir):
                os.makedirs(target_file_dir)

            # write pillar file
            self.logger.info('adding "%s"' % target_file)
            if content:
                with open(target_file, 'w') as stream:
                    yaml.dump(content,
                              stream,
                              default_flow_style=False,
                              indent=2)
            else:
                with open(target_file, 'w') as stream:
                    stream.write('# no values')
                    stream.close()

    def _replace_secret_values(self,
                               dictionary,
                               replace='PiSy_DUMMY_SECRET_MOCK'):
        """
        loop through dict and replace final string values recursively
        :param dictionary:dict
        :param replace:string
        :return: dict
        """
        if dictionary is None:
            return dictionary

        result = dict()
        for key, value in dictionary.iteritems():
            if isinstance(value, dict):
                result[key] = self._replace_secret_values(value)
            elif isinstance(value, list):
                result[key] = []
                for _ in value:
                    result[key].append(replace)
            elif isinstance(value, tuple):
                result[key] = tuple(replace for n in value)
            elif isinstance(value, six.string_types):
                result[key] = replace
            else:
                result[key] = value

        return result

    def _read_source_files(self):
        """
        read sls files on source side
        :return: dict
        """
        args = self.cli.get_args()
        dir_path = args.get('source')

        files = self._get_sls_files(dir_path)
        result_dict = {}

        for file_path in files:
            file_key = file_path.replace(dir_path, '')

            with open(file_path, 'r') as stream:
                content = stream.read()
                replaced = self._replace_jinja(content)

            try:
                result_dict[file_key] = yaml.load(replaced)
            except yaml.YAMLError as exc:
                self.logger.error(exc)

        return result_dict

    def _get_sls_files(self, path):
        """
        get all sls files recursively by glob
        :param path:
        :return: list
        """
        sls_files = glob.glob("%s/*.sls" % path)

        for f in os.listdir(path):
            sub_path = join(path, f)
            if isdir(sub_path):
                sls_files.extend(self._get_sls_files(sub_path))

        return sls_files

    @staticmethod
    def _replace_jinja(string):
        """
        remove jinja settings to keep yaml valid
        :param string:
        :return: string
        """
        regex = '{%.*?%}'
        replaced = re.sub(regex, '', string, flags=re.DOTALL)

        return replaced
Beispiel #35
0
 def __init__(self):
     self.cli = Cli()
     self.logger = Logger(self.cli.get_arg('verbosity_level'))
Beispiel #36
0
                Util.error(
                    "Can't work without account_from || account_to || account_src_file!! Please, inform all parameters!!"
                ))
            logging.error(Util.error("message: {m}".format(m=error)))
            logging.error(
                Util.error("type: {t} with args {args}".format(
                    t=type(error), args=error.args)))
            sys.exit("Failed execution. Please, see the log above.")

    logging.debug(Util.debug(vars(account)))

    if account is None:
        logging.error(Util.error("Failed with account: need be defined!!!"))
        sys.exit("Failed execution. Please, see the log above.")

    print("--------------------------")
    print(args.classifier)
    logging.debug(
        Util.debug("args.classifier --> {c}".format(c=args.classifier)))
    print("--------------------------")

    classifier = None
    if args.classifier is not None:
        classifier = Classifier(args.classifier)
    logging.debug(Util.debug("classifier --> {c}".format(c=classifier)))

    # FIXME args.gnucash_file must be mandatory!!!
    Cli.import_data(account, args.currency, args.dry_run, args.gnucash_file,
                    classifier)
    sys.exit(0)
Beispiel #37
0
class CliTask(object):
    """
        Base class for all task classes, loads the task and provides
        the interface to the command options and the XML description
    """
    def __init__(self, should_perform_task_setup=True):
        from logger import log

        self.cli = Cli()

        # want some help
        self.cli.show_and_exit_on_help_request()

        # load/import task module
        self.task = self.cli.load_command()

        # get command specific args
        self.command_args = self.cli.get_command_args()

        # get global args
        self.global_args = self.cli.get_global_args()

        if should_perform_task_setup:
            # set log level
            if self.global_args['--debug']:
                log.setLogLevel(logging.DEBUG)
            else:
                log.setLogLevel(logging.INFO)

            # set log file
            if self.global_args['--logfile']:
                log.set_logfile(
                    self.global_args['--logfile']
                )

    def load_xml_description(self, description_directory):
        from logger import log

        log.info('Loading XML description')
        config_file = description_directory + '/config.xml'
        if not os.path.exists(config_file):
            # alternative config file lookup location
            config_file = description_directory + '/image/config.xml'
        if not os.path.exists(config_file):
            # glob config file search, first match wins
            glob_match = description_directory + '/*.kiwi'
            for kiwi_file in glob.iglob(glob_match):
                config_file = kiwi_file
                break

        if not os.path.exists(config_file):
            raise KiwiConfigFileNotFound(
                'no XML description found in %s' % description_directory
            )

        description = XMLDescription(
            config_file
        )
        self.xml_data = description.load()
        self.config_file = config_file.replace('//', '/')
        self.xml_state = XMLState(
            self.xml_data,
            self.global_args['--profile'],
            self.global_args['--type']
        )

        log.info('--> loaded %s', self.config_file)
        if self.xml_state.build_type:
            log.info(
                '--> Selected build type: %s',
                self.xml_state.get_build_type_name()
            )
        if self.xml_state.profiles:
            log.info(
                '--> Selected profiles: %s',
                ','.join(self.xml_state.profiles)
            )

    def quadruple_token(self, option):
        tokens = option.split(',', 3)
        return [tokens.pop(0) if len(tokens) else None for _ in range(0, 4)]