示例#1
0
文件: gen.py 项目: DakshMiglani/ccg
    def generate(_self) -> str:
        print(
            f"\n{colors.bs}Fields such as ID, created_at, updated_at are auto generated.{colors.be}\n")
        ques = [
            inquirer.Text('model_name',
                          message='Enter your model name', validate=validate_text),
            inquirer.Text('field_str',
                          message='Enter the model gen commands', validate=lambda _, x: x.strip() != '')
        ]
        ans = inquirer.prompt(ques)
        model_name = ans['model_name'].strip()
        gen_str = ans['field_str'].strip()

        field_data, field_content = parse_gen_str(model_name, gen_str)

        available_fields = list(
            filter(lambda x: x[1] in ('char', 'text'), field_data))

        if available_fields:
            obj = inquirer.prompt(
                [inquirer.List(
                    name="str_field",
                    message="Choose the field to be used in __str__ method",
                    choices=[x[0] for x in available_fields])]
            )
            obj['str_field'] = "self." + obj['str_field']
        else:
            obj = {'str_field': 'str(self.id)'}

        generated = model_template.format(
            model_name=model_name, fields=field_content, str_field=obj['str_field'])

        print("✨ Sucessfully Generated:")
        return generated
示例#2
0
def ask_function():
    questions = [
        inquirer.Text('function',
                      message="Enter source function, f(x) = ",
                      validate=lambda _, v: len(v) > 0),
        inquirer.Text('a',
                      message="Enter the left-border",
                      validate=lambda _, v: NUMBER_REGEXP.match(v)),
        inquirer.Text('b',
                      message="Enter the right-border",
                      validate=lambda _, v: NUMBER_REGEXP.match(v)),
    ]
    answers = None
    while True:
        answers = inquirer.prompt(questions)
        a = float(answers.get('a'))
        b = float(answers.get('b'))
        if a >= b:
            print('Caution! a==b, try again')
        else:
            answers['a'] = a
            answers['b'] = b
            break
    function = tools.sympify(answers.get('function').replace('^', '**'))
    print("You entered f(x) = %s" % function)
    return function, answers.get('a'), answers.get('b')
示例#3
0
    def run(self):
        print_line(":smile:  Let's configure your profile for the cli.")
        configs = get_configs()
        default_configs = get_default_configs()
        if configs:
            hosts = configs.get('hosts', {})
            services = configs.get('services', {})
        else:
            hosts = default_configs.get('hosts')
            services = default_configs.get('services')

        questions = [
            inquirer.Text('username', message="What's your username"),
            inquirer.Password(
                'pwd', message='Please enter your cap password, {username}'),
            inquirer.Text('xymon_base_url',
                          message="What's xymon's base url",
                          default="http://xymon.infra.local"),
        ]

        answers = inquirer.prompt(questions)
        username = answers.get('username')
        xymon_base_url = answers.get('xymon_base_url')
        pwd = answers.get('pwd')
        bp = encode_pwd(pwd)
        data = {
            'username': username,
            'bp': bp,
            'xymon_base_url': xymon_base_url
        }
        data['hosts'] = hosts
        data['services'] = services
        save_configs(data)
def createNewStack(authToken, orgUid, region):
    '''
    Creates a new stack
    '''
    body = {"stack": {}}
    stackList = [
        inquirer.Text('stackName',
                      message="{}Give your stack a name{}".format(
                          config.BOLD, config.END),
                      validate=noEmptyStr),
        inquirer.Text('stackDescription',
                      message="{}Give your stack some description{}".format(
                          config.BOLD, config.END),
                      default=""),
        inquirer.Text(
            'stackMasterLocale',
            message="{}What language should be the master locale?{}".format(
                config.BOLD, config.END),
            default="en-us")
    ]
    stackInfo = inquirer.prompt(stackList)
    stackName = stackInfo['stackName']
    stackDescription = stackInfo['stackDescription']
    stackMasterLocale = stackInfo['stackMasterLocale']
    body['stack']['name'] = stackName
    body['stack']['description'] = stackDescription
    body['stack']['master_locale'] = stackMasterLocale
    stack = cma.createStack(authToken, orgUid, region, body)
    if stack:
        return stackName, stack
    config.logging.error('{}Exiting. Stack {} not created.{}'.format(
        config.RED, stackName, config.END))
    return None
示例#5
0
    def ask_basics(self):

        questions = [
            inquirer.Text(
                'name',
                message = 'Name of job'
            ),
            inquirer.Text(
                'description',
                message = 'Description of job',
            ),
            inquirer.Text(
                'cronexp',
                message = 'Cron expression',
                validate = check_cron,
            ),
            inquirer.Confirm(
                'enabled',
                message = 'Enable the job?',
                default = True,
            )
        ]

        job = inquirer.prompt(questions)

        return job
 def menuCreateContainer(self):
     container_menu = [
         inquirer.Text('name',
                       message="Write the name of the container",
                       ),
         inquirer.Text('duration',
                       message="Define the duration of the trimmed video as mm:ss knowing that the maximun is 10:35",
                       ),
         inquirer.Text('size',
                       message="Define the width and height as (360x240) or the resolution as (720p)",
                       ),
         inquirer.List('video_codec',
                       message="Choose a video code among the following options",
                       choices=['mpeg2video', 'h264'],
                       ),
         inquirer.List('audio_codec',
                       message="Choose an audio code among the following options",
                       choices=['aac', 'mp3', 'ac3'],
                       ),
         inquirer.Text('bitrate',
                       message="Define the bitrate of the audio",
                       ),
     ]
     result = inquirer.prompt(container_menu)
     if (checkDuration(result['duration']) and checkSize(result['size'])):
         return result
     return None
示例#7
0
文件: project.py 项目: zxyle/builder
class PythonProject(Base):
    temp_name = "python"
    questions = [
        inquirer.Text('projectName',
                      message="Please enter a projectName",
                      default="awesome"),
        inquirer.Text('author',
                      message="What's your name",
                      default=get_sys_user()),
        inquirer.List(
            'license',
            message="license?",
            choices=['none', 'mit', 'apache'],
        ),
    ]

    def run(self, dst):
        self.input_prompt()
        project_name = self.metadata.get("projectName")
        target_dir = self.copy_template(self.temp_name, dst, project_name)
        self.render(target_dir, self.metadata)
        self.docker_support()
        self.empty_files.extend([
            "requirements.txt",
            "setup.cfg",
            "tests/__init__.py",
            f"{project_name}/__init__.py",
            "scripts/__init__.py",
            "docs/guide.md",
            "docs/TODO.md",
        ])
        self.after()
示例#8
0
文件: project.py 项目: zxyle/builder
class GolangProject(Base):
    temp_name = "golang"
    questions = [
        inquirer.Text('projectName',
                      message="Please enter a projectName",
                      default="awesome"),
        inquirer.Text('goVersion',
                      message="Please enter a goVersion",
                      default=find_go_version()),
        inquirer.Text('author',
                      message="What's your name",
                      default=get_sys_user()),
        inquirer.List(
            'license',
            message="license?",
            choices=['none', 'mit', 'apache'],
        ),
    ]

    def run(self, dst):
        self.input_prompt()
        project_name = self.metadata.get("projectName")
        target_dir = self.copy_template(self.temp_name, dst, project_name)
        self.render(target_dir, self.metadata)
        self.docker_support()
        self.empty_files.extend([
            "docs/guide.md",
            "docs/TODO.md",
            "go.sum",
        ])
        self.after()
示例#9
0
文件: cli.py 项目: P-Y-X/pyx
def configure(args, pyx_project, **kwargs):
    """
    Configure project
    """

    questions = [
        inquirer.Text('name',
                      message="Please, specify model name",
                      default=pyx_project['name']),
        inquirer.Text('paper_url',
                      message="Please, specify paper url if you have one",
                      default=pyx_project['paper_url']),
        inquirer.Text('dataset',
                      message="Please, specify dataset you used",
                      default=pyx_project['dataset']),
        inquirer.Text('license',
                      message="Please, specify license",
                      default=pyx_project['license']),
        inquirer.Text('price',
                      message="Please, specify price (0.0 for free models)",
                      default=pyx_project['price']),
        inquirer.Editor(
            'description_short',
            message="Please, specify short description of your model",
            default=pyx_project['description_short']),
    ]

    answers = inquirer.prompt(questions)
    for k in answers:
        pyx_project[k] = answers[k]

    print("pyx.json:")
    print(json.dumps(pyx_project, indent=4))
示例#10
0
文件: main.py 项目: ksbains/Nursery
def employeeSignIn():
        questions = [
                inquirer.Text('username', message="What's your username"),
                inquirer.Text('password', message="What's your password")
        ]

        answers = inquirer.prompt(questions)
        empUsername = answers['username']
        empPassword = answers['password']

        # check if the employee is in the DB
        result = nursery.inEmployee(empUsername)
        if not result:
                print("You are an IMPOSTER!!")
                employeeStart()


        if nursery.verify_password(result[3],empPassword):
                if not result[8]:
                        employeeManagerMainMenu(result[0], result[4])
                else:
                        employeeCommonMainMenu(result[0], result[4])

        else:
                print("Incorrect Password!!! Try again")
                employeeSignIn()
示例#11
0
def updateOrderMenu(orderId):	
	question = [
		inquirer.List(
			'status',
			message='Choose the new status of order',
			choices=['Current', 'Completed', 'Dispatched', 'Back']
			)
	]
	answer = inquirer.prompt(question)
	status = answer.get('status')
	if status == 'Completed':
		question2 = [
			inquirer.Text('date', 'Enter the delivered date')    		
		]
		ans = inquirer.prompt(question2)
		date = ans.get('date')
		updateDeliveredOrder(orderId, status, date)	
		prGreen("Order has been successfully updated!\n")	
	elif status == 'Current' or status == 'Dispatched':
		question2 = [
			inquirer.Text('date', 'Enter the expected date of delivery')    		
		]
		ans = inquirer.prompt(question2)
		date = ans.get('date')
		updateCurrentOrder(orderId, status, date)
		prGreen("Order has been successfully updated!\n")
	showEmployeeOrders()
示例#12
0
    def get_user_inputs(self):
        # inquirer questions for hydrologic_variable, binning, and functional_bin_number
        print('')
        questions = [
            inquirer.List(
                'hydrologic_variable',
                message="Which hydrologic variable?",
                choices=['d: depth', 'v: velocity', 't: shear stress'],
            ),
            inquirer.Text('binning',
                          message="Define the binning. Example: 1.2, 2.1 ",
                          validate=lambda _, d: d is not ''),
            inquirer.Text(
                'functional_bin_number',
                message="Input functional bin number. Example: 0 or 1",
                validate=lambda _, d: will_it_float(d)),
        ]

        answers = inquirer.prompt(questions)
        # parse answers to desired values
        self.hydrologic_variable = answers['hydrologic_variable'][0]
        self.binning = [
            float(x.strip()) for x in answers['binning'].split(',')
        ]
        self.functional_bin_number = int(answers['functional_bin_number'])
示例#13
0
def main():
    questions = [
        inquirer.List('user_option',
                      message="in order to proceed please choose an option",
                      choices=["scraper", "immediate data"]
                      )
    ]

    question_scraper = [
        inquirer.Text('symbol',
                      message='if you like to scrape a specific symbol enter the the symbol\nplease please enter "ALL" for all the symbol ',
                      ),
        inquirer.Text('saving flag',
                      message='if you like to save the data locally please add True (default - False) '
                      ),

    ]

    answers = inquirer.prompt(questions)

    if answers.get("user_option") == "scraper" : # TODO fix scraper - cannot scraped data while choosing "scraper"
        answer_scraper = inquirer.prompt(question_scraper)
        symbol = answer_scraper.get("symbol")
        saving_flag = answer_scraper.get("saving flag")
        scraper = Scraper(save=saving_flag)
        scraper.scrape_all(symbol_choice=symbol)

    elif answers.get("user_option") == "immediate data" :
        get_data_from_api()
示例#14
0
    def inner():
        arguments = func()
        questions = [
            inquirer.List('browser',
                          message='What browser do you want to use?',
                          choices=browsers),
            inquirer.Text('name', message='Full name: '),
            inquirer.Text('email', message='E-Mail: ')
        ]

        browser = arguments.get('browser') if arguments.get('browser') \
            else inquirer.prompt([questions[0], ]).get('browser')

        if arguments.get('rand'):
            return {'browser': browser, 'rand': arguments.get('rand')}

        else:
            name, email = arguments.get('name'), arguments.get('email')

            # TODO: Refactor
            if not arguments.get('name'):
                name = inquirer.prompt((questions[1], )).get('name')
            if not arguments.get('email'):
                email = inquirer.prompt((questions[2], )).get('email')
            check_data(name, email)

            return {
                'browser': browser,
                'name': name,
                'email': email,
                'rand': arguments.get('rand'),
            }
示例#15
0
    def generateEnumData(self):
        data = {"listItems": []}
        cond_stop = False
        self.clear()
        name_question = [
            inquirer.Text('name', message="What's the entity name")
        ]
        name_answer = inquirer.prompt(name_question)
        data["name"] = name_answer["name"]

        choose_step = [
            inquirer.List('choose',
                          message="What now",
                          choices=['Add item into the enum', 'Stop'])
        ]

        while not cond_stop:
            self.clear()
            step_answer = inquirer.prompt(choose_step)

            if step_answer['choose'] == 'Stop':
                cond_stop = True
            elif step_answer['choose'] == 'Add item into the enum':
                questions = [
                    inquirer.Text('name', message="What's the item name")
                ]
                self.clear()
                answers = inquirer.prompt(questions)
                data.listItems.append(answers["name"])
        return data
def main():
    # search for street
    questions = [inquirer.Text("street", message="Enter search string for street")]
    answers = inquirer.prompt(questions)

    # retrieve suggestions for street
    r = requests.get(
        "https://service.stuttgart.de/lhs-services/aws/strassennamen", params=answers
    )

    data = json.loads(r.text)
    street_choices = []
    for d in data["suggestions"]:
        street_choices.append((d["value"], d["data"]))

    # select street
    questions = [
        inquirer.List("street", choices=street_choices, message="Select street")
    ]
    results = inquirer.prompt(questions)

    # search for house number
    questions = [inquirer.Text("streetnr", message="Enter house number")]
    results.update(inquirer.prompt(questions))

    print("Copy the following statements into your configuration.yaml:\n")
    print("# waste_collection_schedule source configuration")
    print("waste_collection_schedule:")
    print("  sources:")
    print("    - name: stuttgart_de")
    print("      args:")
    for key, value in results.items():
        print(f"        {key}: {value}")
def main():
    questions = [
        inquirer.List("operating_sys",
                      message="Select the target OS",
                      choices=[("Linux", "linux"), ("Windows", "windows")]),
        inquirer.Text("email",
                      message="Enter email address to send reports to",
                      validate=lambda _, x: x != ''),
        inquirer.Text("password",
                      message="Enter password for given email address",
                      validate=lambda _, x: x != ''),
        inquirer.Text("url",
                      message="Enter absolute URL to laZagne .exe",
                      validate=lambda _, x: x != ''),
        inquirer.Text("file_name",
                      message="Enter output filename",
                      validate=lambda _, x: x != '')
    ]
    answers = inquirer.prompt(questions, raise_keyboard_interrupt=True)
    write_harvester(answers["file_name"], answers["email"],
                    answers["password"], answers["url"])
    if (answers["operating_sys"] == "windows"):
        compile_for_windows(answers["file_name"])
    if (answers["operating_sys"] == "linux"):
        compile_for_linux(answers["file_name"])
    print("\n[+] Compilation complete.")
    print(
        "[*] You must allow less secure applications in provided Gmail account."
    )
    print("[*] Do so here: https://myaccount.google.com/lesssecureapps")
示例#18
0
def main():
    questions = [
        # validate=validate_ip
        inquirer.Text("target_ip",
                      message="Enter the target/client IP address"),
        inquirer.Text("gateway_ip",
                      message="Enter the gateway/access point IP address"),
    ]
    answers = inquirer.prompt(questions, raise_keyboard_interrupt=True)
    target_ip = answers["target_ip"]
    gateway_ip = answers["gateway_ip"]
    spoofer = Spoofer(target_ip, gateway_ip)
    try:
        spoofer.run()
    except KeyboardInterrupt:
        try:
            print(
                "\n[x] ARP Spoofer terminated by user. Resetting ARP tables...\n"
            )
            spoofer.restore_defaults(target_ip, gateway_ip, spoofer.target_mac,
                                     spoofer.gateway_mac)
            spoofer.restore_defaults(gateway_ip, target_ip,
                                     spoofer.gateway_mac, spoofer.target_mac)
        except:
            print(
                "[-] Unable to reset ARP tables. You'll need to do this manually, it seems..."
            )
示例#19
0
    def create_issues(github_selected_repos: List[str]) -> i.Issue:
        """Prompt questions to create issues."""
        questions = [
            inquirer.Text(
                "title",
                message="Write an issue title",
                validate=val.not_empty_validation,
            ),
            inquirer.Text("body", message="Write an issue body [optional]"),
            inquirer.Text(
                "labels", message="Write issue labels [optional, separated by comma]"
            ),
            inquirer.Confirm(
                "correct",
                message=(
                    "Confirm creation of issue for the project(s) "
                    f"{github_selected_repos}. Continue?"
                ),
                default=False,
            ),
        ]
        correct = False
        while not correct:
            answers = inquirer.prompt(questions)
            correct = answers["correct"]

        labels = (
            set(label.strip() for label in answers["labels"].split(","))
            if answers["labels"]
            else set()
        )
        return i.Issue(answers["title"], answers["body"], labels)
示例#20
0
def describe_file(file):
    """
    describe_file [summary]

    [extended_summary]

    :param file: [description]
    :type file: [type]
    :return: [description]
    :rtype: [type]
    """
    questions = [
        inquirer.Text("name",
                      message=f"How would you like to name the file: {file}?"),
        inquirer.Text("description", message=f"What is {file} about?"),
        inquirer.Text(
            "updated_at",
            message=
            f"When was {file} last updated? In ISO date format such as 2020-02-17.",
        ),
    ]

    answers = inquirer.prompt(questions)
    meta = {
        "name": answers.get("name"),
        "description": answers.get("description"),
        "updated_at": answers.get("updated_at"),
    }

    return meta
示例#21
0
def main():
    try:
        questions = [
            # validate=validate_ip
            inquirer.Text("target_url", message="Enter the the target url"),
            inquirer.Text("redirect_ip",
                          message="Enter the IP to which target will resolve")
        ]
        answers = inquirer.prompt(questions, raise_keyboard_interrupt=True)
        target_url = answers["target_url"]
        redirect_ip = answers["redirect_ip"]
        Spoofer(target_url, redirect_ip)
    except TypeError:
        pass
    except KeyboardInterrupt:
        try:
            print(
                "\n[x] DNS Spoofer terminated by user. Resetting ARP tables...\n"
            )
            subprocess.call(["iptables --flush"],
                            shell=True)  # IMPT - clean up
        except:
            print(
                "[-] Unable to reset ARP tables. You'll need to do this manually, it seems..."
            )
示例#22
0
def massiveDesc(edit):
    ''' Prepare the execution of setlabeldesc.py
        Add labels and description to an item given an specific source lang'''

    queriesAnswer = u.checkQueries()

    questions = [
        inquirer.Text("desc", message="Escribe la descripción que quieres añadir"),
        inquirer.Text("lang", message="¿En qué idioma está la descripción que quieres introducir?"),
        inquirer.Text("sourceLang", message="¿De que idioma quieres trabajar y copiar la etiqueta?")
    ]

    answers = inquirer.prompt(questions)
    desc = answers["desc"]
    lang = answers["lang"]
    sourceLang = answers["sourceLang"]

    try:
        print("\nSe ejecutará la consulta {}".format(queriesAnswer))

        with open("queries/" + queriesAnswer, "r") as queryFile:
            query = queryFile.read()

        sld.setLabel(query, desc, lang, sourceLang, edit)
    except FileNotFoundError:
        print("\nThe query {} does not exist".format(queriesAnswer))
        print(u"\nThis file does not exist Create it or enter another name.")
示例#23
0
def new_customer():
    print('Please Enter Customer Information')
    questions = [
        inquirer.Text('name', message="Full name"),
        inquirer.Text('address', message="Address"),
        inquirer.Text('number', message="Phone number")
    ]
    answers = inquirer.prompt(questions)
    print(answers)
示例#24
0
def custom(to_convert, to_save):
    questions = [
        inquirer.Text("r", message="What's the R value?"),
        inquirer.Text("g", message="Whats the G value?"),
        inquirer.Text("b", message="Whats the B value?")
    ]
    answers = inquirer.prompt(questions)
    cm.set_color(int(answers['r']), int(answers['g']), int(answers['b']))
    color.convert(color.ColorPresets.custom.value, to_convert, to_save)
示例#25
0
def askPlayerName():
    questions = [
        inquirer.Text('Name1',
                      message="Name of the first player ",
                      validate=name_validation),
        inquirer.Text('Name2',
                      message="Name of the second player ",
                      validate=name_validation),
    ]
    return inquirer.prompt(questions)
示例#26
0
def addPlantsMenu(empID, storeID):
    questions = [
        inquirer.Text('name', message="What's the plant name?"),
        inquirer.Text('price', message="What's the plant price?"),
        inquirer.Text('description', message="What's the plant description?"),
        inquirer.Text('age', message="What's the plant age?"),]
    answers = inquirer.prompt(questions)
    nursery.add_plant(answers["name"], answers["price"], answers["description"], answers["age"])
    print(answers["name"], "added!")
    invManMenu(empID, storeID)
示例#27
0
def get_book_from_input():
    questions = [
        inquirer.Text("title", message="What’s the title of the book?"),
        inquirer.Text("author", message="Who’s the author?"),
        inquirer.Text("publication_year", message="When was it published?"),
        inquirer.Text("cover_image_url", message="What’s the cover URL?"),
        inquirer.Text("cover_description", message="What’s the cover?"),
        inquirer.Text("isbn10", message="Do you know the ISBN-10?"),
        inquirer.Text("isbn13", message="Do you know the ISBN-13?"),
        inquirer.Number("pages", message="How many pages does the book have?"),
        inquirer.List(
            "series",
            message="Is this book part of a series?",
            choices=[("Yes", True), ("No", False)],
            default=False,
            carousel=True,
        ),
    ]

    answers = inquirer.prompt(questions)

    if answers["series"]:
        series_questions = [
            inquirer.Text("series",
                          message="Which series does this book belong to?"),
            inquirer.Text(
                "series_position",
                message="Which position does the book have in its series?",
            ),
        ]
        answers = {**answers, **inquirer.prompt(series_questions)}
    return answers
示例#28
0
 def cli_generate():
     do_create = inquirer.confirm("Do you want to create the project file right now?")
     if do_create:
         # questions to prompt the user
         project_queries = [
             inquirer.Text("name", "Enter the name of the project"),
             inquirer.List("type", "Enter the type of project", [e.value for e in ProjectType]),
         ]
         # ask questions and get answers
         answer = inquirer.prompt(project_queries)
         # create an author from CLI prompt
         author: Author = Author.create_author()
         # subprojects list, which is empty presently
         subprojects = []
         spcreateprompt = inquirer.Text("name", "Enter the name of the new subproject")
         # add any generated projects here, for each generated project, create
         # an empty directory also
         while True:
             if subprojects == []:
                 if inquirer.confirm("No subprojects created. Create one?"):
                     spname = inquirer.prompt([spcreateprompt])["name"]
                     if inquirer.confirm(f"Do you want to continue creating '{spname}'?"):
                         sp_pathname = os.path.join(os.getcwd(), spname)
                         if not os.path.exists(sp_pathname):
                             os.makedirs(spname)
                         subprojects.append(spname)
                         Subproject.generate_subproject(spname, answer["name"], author.name)
                 else:
                     break
             else:
                 if inquirer.confirm("Do you want to create more subprojects?"):
                     spname = inquirer.prompt([spcreateprompt])["name"]
                     if inquirer.confirm(f"Do you want to continue creating {spname}?"):
                         os.makedirs(os.path.join(os.getcwd(), spname))
                         subprojects.append(spname)
                         Subproject.generate_subproject(spname, answer["name"], author.name)
                 else:
                     break
         # return the generated project
         try:
             project_config = Project(
                 {
                     Project.AUTHOR: author.to_dict(),
                     Project.NAME: spname,
                     Project.TYPE_OF_PROJECT: answer["type"],
                     Project.SUBPROJECTS: subprojects,
                 }
             )
             print(project_config.to_yaml())
             with open(os.path.join(os.getcwd(), Project.PROJECT_FILE), "w") as project_out:
                 project_out.write(project_config.to_yaml())
                 print("Project configuration written")
         except TypeError as te:
             print(te)
             return None
示例#29
0
def sign_in():
    system('clear')
    display_border_title('Employee Log In')

    questions = [
        inquirer.Text('username', message="Username".rjust(19)),
        inquirer.Text('password', message="Password".rjust(19))
    ]
    answers = inquirer.prompt(questions)
    username = answers['username']
    password = answers['password']
示例#30
0
文件: cli.py 项目: strannik19/aws-sso
def configure(args):
    profile = args.profile
    cfg = Configuration()
    params = config_override(cfg.config, profile, args)

    try:
        inquirer.prompt([
            inquirer.Text('url',
                          message='URL',
                          default=params.get('url', ''),
                          validate=validate_url),
            inquirer.Text('aws_profile',
                          message='AWS CLI profile',
                          default=params.get('aws_profile', profile),
                          validate=validate_empty),
            inquirer.Text('username',
                          message='Username',
                          default=params.get('username', ''),
                          validate=validate_empty)
        ],
                        answers=params,
                        raise_keyboard_interrupt=True)
        secrets = SecretsManager(params.get('username'), params.get('url'))
        password = inquirer.password(message='Password',
                                     default=secrets.get('credentials', ''),
                                     validate=validate_empty)

        token = __get_or_refresh_token(params['url'], params['username'],
                                       password, secrets, cfg.configdir,
                                       args.force_refresh, args.headless,
                                       args.spinner)
        sso = SSOClient(token, params['region'])

        instances = sso.get_instances()
        inquirer.prompt([
            inquirer.List('instance_id',
                          message='AWS Account',
                          choices=[(_['name'], _['id']) for _ in instances])
        ],
                        answers=params,
                        raise_keyboard_interrupt=True)

        profiles = sso.get_profiles(params['instance_id'])
        inquirer.prompt([
            inquirer.List('profile_id',
                          message='AWS Profile',
                          choices=[(_['name'], _['id']) for _ in profiles])
        ],
                        answers=params,
                        raise_keyboard_interrupt=True)

        cfg.save()
    except KeyboardInterrupt:
        sys.exit(1)