Beispiel #1
0
def make_interface_choice() -> list:
    int_list = []
    for _, value in interfaces.items():
        int_string = "{:<10}".format(value.name[:8]) + " "
        int_string += "{:<10}".format(value.provider[:8]) + " "
        int_string += "{:<10}".format(value.itype[:8]) + " "
        int_string += "{:<19}".format(value.mac) + " "
        int_string += "{:<15}".format(value.status[:15]) + " "
        int_list.append(int_string)
    cli = Check(
        prompt="  Select from the interfaces below: (Using Spacebar)",
        choices=int_list,
        check_on_switch=colors.foreground["green"],
        word_on_switch=colors.foreground["green"],
        check_color=colors.foreground["green"],
        word_color=colors.foreground["white"],
        check="√",
        shift=1,
        margin=1,
    )
    temp_list = []
    for result in cli.launch():
        temp_list.append(result.split()[0])
    print("")
    return temp_list
Beispiel #2
0
    def start_instance(self):
        ec2 = boto3.resource('ec2', region_name=self.region)
        instance_iterator = ec2.instances.all()

        instance_list = []

        for i in instance_iterator:
            if not i.tags:
                name = ""
            else:
                name_tag = [x['Value'] for x in i.tags if x['Key'] == 'Name']
                name = name_tag[0] if len(name_tag) else ''
            tmp = i.id + self.splitter + i.state['Name'] + self.splitter + name
            instance_list.append(tmp)

        if not instance_list:
            print('No EC2 instance in ' + self.region + '.')
            exit(127)

        cli = Check(prompt="Hit <Space Bar> to check instances:",
                    choices=instance_list,
                    indent=0,
                    align=3,
                    margin=2,
                    shift=1,
                    pad_right=3,
                    check='✅')
        selected = cli.launch()

        for s in selected:
            instance_id = s.split(self.splitter)[0]
            print('Starting ' + instance_id + '\n')

            res = ec2.Instance(instance_id).start()
Beispiel #3
0
def file_types_prompt(prompt, valid_file_types=VigFile.ALL):
    if not prompt:
        prompt = "Select one or multiple file types from the list below:"
    choices = {f"{f}": f for f in VigFile if int(f) & valid_file_types == f}
    instructions = "(use SPACE BAR to select each file type, ENTER to confirm your selections)"
    file_types_prompt = Check(
        prompt=instructions,
        choices=list(choices.keys()),
        check=EMOJIS.get("CHECK", ""),
        shift=1,
        indent=0,
        margin=2,
        check_color=colors.foreground["default"],
        check_on_switch=colors.foreground["default"],
        word_color=colors.foreground["default"],
        word_on_switch=colors.bright(colors.foreground["cyan"]),
        background_color=colors.background["default"],
        background_on_switch=colors.background["default"],
    )
    file_types = []
    while not file_types:
        subprocess.run(["clear"])
        print_message(prompt, fg="bright_yellow", bold=True, underline=True)
        result = file_types_prompt.launch()
        if not result:
            print_error("\nYou must select at least one file type!")
            pause(message="Press any key to continue...")
            continue
        file_types = [choices[sel] for sel in result]
    return file_types
def ask_interfaces(_interfaces):
    """

    Parameters
    ----------
    _interfaces

    Returns
    -------

    """
    click.echo('\n')  # terminal new line
    choices = [f'dns[{itf["dns"]}], ip[{itf["ip"]}]' for itf in _interfaces]
    select_interfaces_cli = Check(
        prompt=f"Choose interfaces: input <space> to choose, then input <enter> to finish",
        choices=choices,
        align=4,
        margin=1,
    )
    selected_interfaces = select_interfaces_cli.launch()
    selected_interfaces = list(
        filter(
            lambda itf: f'dns[{itf["dns"]}], ip[{itf["ip"]}]' in selected_interfaces,
            _interfaces,
        ),
    )
    return selected_interfaces
Beispiel #5
0
def multi_season_prompt(db_session, prompt=None, heading=None):
    if not prompt:
        prompt = "Select one or multiple seasons from the list below:"
    all_seasons = db.Season.get_all_regular_seasons(db_session)
    choices = {f"{season.year}": season.year for season in all_seasons}
    instructions = "(use SPACE BAR to select each file type, ENTER to confirm your selections)"
    seasons_prompt = Check(
        prompt=instructions,
        choices=list(choices.keys()),
        check=EMOJIS.get("CHECK", ""),
        shift=1,
        indent=0,
        margin=2,
        check_color=colors.foreground["default"],
        check_on_switch=colors.foreground["default"],
        word_color=colors.foreground["default"],
        word_on_switch=colors.bright(colors.foreground["cyan"]),
        background_color=colors.background["default"],
        background_on_switch=colors.background["default"],
    )
    selected_years = []
    while not selected_years:
        subprocess.run(["clear"])
        if heading:
            print_heading(heading, fg="bright_yellow")
        print_message(prompt, wrap=True)
        result = seasons_prompt.launch()
        if not result:
            print_error("\nYou must select at least one season!")
            pause(message="Press any key to continue...")
            continue
        selected_years = [choices[sel] for sel in result]
    return selected_years
Beispiel #6
0
def ask_graphs(graphs):
    """
    1つのホストに対して行う
    return graphs: [dicts]
    """
    click.echo('\n')  # terminal new line
    choices = ['all']
    choices.extend([f'{graph["host"]}: {graph["name"]}' for graph in graphs])

    # 入力のバリデーションするのでwhile回す
    while True:
        select_graphs_cli = Check(
            prompt=
            f"Choose graph: input <space> to choose, then input <enter> to finish",
            choices=choices,
            align=4,
            margin=1,
        )
        selected_graphs = select_graphs_cli.launch()
        if 'all' in selected_graphs:
            if len(selected_graphs) != 1:
                # When select all, be able to select only all.
                click.echo('Select only all.')
                continue
            else:
                return graphs

        selected_graphs = list(
            filter(
                lambda graph: f'{graph["host"]}: {graph["name"]}' in
                selected_graphs,
                graphs,
            ))
        return selected_graphs
Beispiel #7
0
def mark_deletion(dir):
    if os.path.exists(dir):
        filenames = sorted(os.listdir(dir), reverse=True)
        if filenames:
            not_dotfiles = [f for f in filenames if not f.startswith(".")]
            cprint(f"Mark listened with [Space]. [Enter] to continue.", "red")
            cli = Check(choices=not_dotfiles,
                        check="X ",
                        check_color=colors.foreground["red"])
            return cli.launch()
Beispiel #8
0
def ask_hosts(hosts):
    """
    host を選択する
    return selected_hosts: [dict]
    """
    click.echo('\n')  # ターミナルをリフレッシュ

    select_hostnames_cli = Check(
        prompt=
        "Choose instance: input <space> to choose, then input <enter> to finish",
        choices=[host['name'] for host in hosts],
        align=4,
        margin=1,
    )
    hostnames = select_hostnames_cli.launch()
    selected_hosts = list(filter(lambda host: host['name'] in hostnames,
                                 hosts))

    return selected_hosts
def list_room(client: AsyncClient):
    selection=[]
    user_id=ARGS.user
    with open(
            f"{OUTPUT_DIR}/.env/rooms_list.{user_id}.txt","w"
            ) as rlist:
        for room_id, room in client.rooms.items():
            selection.append( f"{room_id} -> {room.display_name}")
         #   print(selection)

        cli = Check(choices=selection)
        result=cli.launch()
        #rlist.write(f"{room_id}, {room.display_name}\n")
        final=""
        for val in result:
            val=re.sub(":smart4.*","",re.sub("!","",val))
            final=final + val+"\n"
        rlist.write(final)
    return client
Beispiel #10
0
from bullet import Bullet
from bullet import Check
from bullet import styles

client = Check(prompt="Choose from a list: ", **styles.Example, **styles.Exam)
print('\n', end='')
result = client.launch()
print(result)
Beispiel #11
0
 def rlaunch(self, key, depth):
   results = {}
   section_config = self.configuration[key]
   if section_config["prompt_type"] == "Check":
     ui = Check(section_config["prompt"],
                choices=section_config["choices"],
                check=" √",
                margin=2,
                check_color=colors.bright(colors.foreground["red"]),
                check_on_switch=colors.bright(colors.foreground["red"]),
                background_color=colors.background["black"],
                background_on_switch=colors.background["white"],
                word_color=colors.foreground["white"],
                word_on_switch=colors.foreground["black"],
                indent=depth * 2)
     choices = ui.launch()
     branching = section_config.get("branching")
     if branching is not None:
       for sub_key in choices:
         branching_key = branching.get(sub_key)
         if branching_key is not None:
           if branching_key.startswith("."):
             results[sub_key] = self.rlaunch("{}{}".format(key, branching_key), depth)
           else:
             results[sub_key] = self.rlaunch(branching_key, depth)
         else:
           raise ValueError("the key {} is not in branching {}".format(sub_key, branching.keys()))
       return results
     else:
       return results
   if section_config["prompt_type"] == "ListInput":
     ui = ListInput(section_config["prompt"],
       word_color=colors.foreground["yellow"],
       indent=depth * 2)
     results = ui.launch()
     return results
   if section_config["prompt_type"] == "Input":
     ui = Input(section_config["prompt"],
       word_color=colors.foreground["yellow"],
       indent=depth * 2)
     results = ui.launch()
     return results
   if section_config["prompt_type"] == "YesNo":
     ui = YesNo(section_config["prompt"],
       word_color=colors.foreground["yellow"],
       default=section_config["default"] if "default" in section_config else 'y',
       indent=depth * 2)
     results = ui.launch()
     return results
   if section_config["prompt_type"] == "Bullet":
     ui = Bullet(section_config["prompt"],
           choices=section_config["choices"],
           bullet=" >",
           margin=2,
           bullet_color=colors.bright(colors.foreground["cyan"]),
           background_color=colors.background["black"],
           background_on_switch=colors.background["black"],
           word_color=colors.foreground["white"],
           word_on_switch=colors.foreground["white"],
           indent=depth * 2)
     results = ui.launch()
     return results
   if section_config["prompt_type"] == "GoTo":
     for sub_key in section_config["goto"]:
       if sub_key.startswith("."):
         sub_value = self.rlaunch("{}{}".format(key, sub_key), depth)
         sub_key = sub_key[1:]
       else:
         sub_value = self.rlaunch(sub_key, depth)
       if isinstance(sub_value, bool) or sub_value:
         # If True/False or other non-empty data (! "", [], {})
         results[sub_key] = sub_value
     return results
A module for adding shebang and encoding to python files
"""
from os import listdir

from bullet import Check

SHEBANG = "#!/usr/bin/env python3\n"
ENCODING = "# -*- coding: utf-8 -*-\n"

ALL_FILES = listdir(path=".")

PYTHON_FILES = [file for file in ALL_FILES if file.endswith(".py")]

CLI = Check(prompt="Choose an option:", choices=PYTHON_FILES)

RESULT = CLI.launch()

NEEDED = None
for file in RESULT:
    with open(file=file, mode="r") as f:
        FIRST_LINE = f.readline()
        SECOND_LINE = f.readline()
        if FIRST_LINE == SHEBANG and SECOND_LINE == ENCODING:
            print(f"Shebang and encoding present in {file}.")
        elif FIRST_LINE == SHEBANG and SECOND_LINE != ENCODING:
            print(f"Shebang present in {file}, but not encoding.")
            NEEDED = "encoding"
        else:
            print(f"Shebang and encoding not present in {file}.")
            NEEDED = "shebang and encoding"
    if NEEDED: