def test_raise_if_options_is_not_a_non_empty_list(): """Test function called by cookiecutter raise expected errors. Test for choice type invocation. """ with pytest.raises(TypeError): read_user_choice('foo', 'NOT A LIST') with pytest.raises(ValueError): read_user_choice('foo', [])
def prompt_user(): # Prompt user for input for key, value in defaults.items(): if not key.startswith("_"): if isinstance(value, list): defaults[key] = prompt.read_user_choice(key, value) elif isinstance(value, str): defaults[key] = prompt.read_user_variable(key, value) # adjust defaults based on special conditions if key.endswith("import_type"): defaults["import"] = defaults["installed"][defaults[key]] elif key.endswith("import"): defaults["project_name"] = defaults[key] defaults["repository_name"] = ( defaults[key].replace(" ", "_") + "_Rainmeter_Skin" ) # promt user to pick skin to load if importing an installed skin if ( defaults["import_type"] == "Skin" and defaults["import"] != "Create a new skin" ): # now ask the user which skin to load on-install skin_configs = [] for dirpath, _, filenames in os.walk( defaults["_skins_path"] + os.sep + defaults[key] ): for f in filenames: if f.endswith(".ini"): skin_configs.append( dirpath.replace( defaults["_skins_path"] + os.sep, "", ) + os.sep + f ) defaults["_load_skin"] = prompt.read_user_choice( "skin to load", skin_configs ) elif key.endswith("project_name"): defaults["repository_name"] = ( defaults[key].replace(" ", "_") + "_Rainmeter_Skin" ) elif key.endswith("req_windows_version"): defaults["req_windows_version"] = defaults["_windows_version_alias"][defaults[key]] elif key.endswith("req_rainmeter_version"): # restrict windows version based on rainmeter version if float(defaults[key][:3]) >= 4.0: defaults["req_windows_version"].remove("Windows XP") defaults["req_windows_version"].remove("Windows Vista") if vcs.is_vcs_installed("git"): print("git is installed") init_commit = prompt.read_user_yes_no("Create initial commit? (y/n)", "y") if isinstance(init_commit, str): init_commit = True if init_commit == "y" else False defaults["_init_commit"] = init_commit
def _prompt_choice_and_subitems(cookiecutter_dict, env, key, options, no_input): result = {} # first, get the selection rendered_options = [ render_variable(env, list(raw.keys())[0], cookiecutter_dict) for raw in options ] if no_input: selected = rendered_options[0] selected = read_user_choice(key, rendered_options) selected_item = [list(c.values())[0] for c in options if list(c.keys())[0] == selected][0] result[selected] = {} # then, fill in the sub values for that item for subkey, raw in selected_item.items(): # We are dealing with a regular variable val = render_variable(env, raw, cookiecutter_dict) if not no_input: val = read_user_variable(subkey, val) result[selected][subkey] = val return result
def test_click_invocation(mocker, user_choice, expected_value): choice = mocker.patch('click.Choice') choice.return_value = click.Choice(OPTIONS) prompt = mocker.patch('click.prompt') prompt.return_value = '{}'.format(user_choice) assert read_user_choice('varname', OPTIONS) == expected_value prompt.assert_called_once_with(EXPECTED_PROMPT, type=click.Choice(OPTIONS), default='1')
def test_click_invocation(mocker, user_choice, expected_value): choice = mocker.patch("click.Choice") choice.return_value = click.Choice(OPTIONS) prompt = mocker.patch("click.prompt") prompt.return_value = "{}".format(user_choice) assert read_user_choice("varname", OPTIONS) == expected_value prompt.assert_called_once_with( EXPECTED_PROMPT, type=click.Choice(OPTIONS), default="1", show_choices=False, )
def test_click_invocation(mocker, user_choice, expected_value): choice = mocker.patch('click.Choice') choice.return_value = click.Choice(OPTIONS) prompt = mocker.patch('click.prompt') prompt.return_value = '{}'.format(user_choice) assert read_user_choice('varname', OPTIONS) == expected_value prompt.assert_called_once_with( EXPECTED_PROMPT, type=click.Choice(OPTIONS), default='1' )
def test_click_invocation(mocker, user_choice, expected_value): """Test click function called correctly by cookiecutter. Test for choice type invocation. """ choice = mocker.patch('click.Choice') choice.return_value = click.Choice(OPTIONS) prompt = mocker.patch('click.prompt') prompt.return_value = '{}'.format(user_choice) assert read_user_choice('varname', OPTIONS) == expected_value prompt.assert_called_once_with( EXPECTED_PROMPT, type=click.Choice(OPTIONS), default='1', show_choices=False )
def test_raise_if_options_is_not_a_non_empty_list(): with pytest.raises(TypeError): read_user_choice('foo', 'NOT A LIST') with pytest.raises(ValueError): read_user_choice('foo', [])
def test_raise_if_options_is_not_a_non_empty_list(): with pytest.raises(TypeError): read_user_choice("foo", "NOT A LIST") with pytest.raises(ValueError): read_user_choice("foo", [])
if __name__ == '__main__': from cookiecutter.prompt import read_user_variable, read_user_choice, read_repo_password from cookiecutter.main import cookiecutter context = {} context['project_name'] = read_user_variable('project_name', 'my_project_name') context['django_template'] = read_user_choice('django_template', ['django']) context['db_backend'] = read_user_choice('db_backend', ['mysql', 'postgresql']) context['db_password'] = read_repo_password('db_password') context['docker_compose_file_version'] = read_user_variable('docker_compose_file_version', '3.8') if context['db_backend'] == 'mysql': context['db_user'] = '******' elif context['db_backend'] == 'postgresql': context['db_user'] = '******' repo = 'https://github.com/otto-torino/webapp-boilerplate/' template = 'templates/base' output_dir = '.' cookiecutter(repo, no_input=True, extra_context=context, directory=template, output_dir=output_dir) template = f'templates/{context['django_template']}' output_dir = f'{output_dir}/{context['project_name']}' cookiecutter(repo, no_input=True, extra_context=context, directory=template, output_dir=output_dir)
def prompt_dict(message, d, sort=True): options = list(d.keys()) if sort: options = sorted(options) return d[prompt.read_user_choice(message, options)]
def bump(ctx, self, version=None, fast_forward=False, force_version=False): """ Change the Unikraft library's source origin version. Usually this involves updating the LIBNAME_VERSION variable in the Makefile.uk file. Args: version: The version to set. If None, the latest version will be set. fast_forward: If True, choose the latest version. force_version: Whatever the specified version is, use it. Raises: NonCompatibleUnikraftLibrary: Provided path is not a Unikraft library. UnknownLibraryOriginVersion: The provided version does not match known versions from the origin. BumpLibraryDowngrade: Attempting to downgrade a library. NoRemoteVersionsAvailable: No remote versions to select from. CannotDetermineRemoteVersion: Unable to determine which version to upgrade to. UnknownLibraryProvider: Undetermined origin provider. KraftError: Miscellaneous error. """ if self.origin_provider is None: raise UnknownLibraryProvider(self.name) # Retrieve known versions versions = self.origin_provider.probe_remote_versions() semversions = [] if len(versions) == 0: raise NoRemoteVersionsAvailable(self.origin_provider.source) # filter out non-semver versions for known_version in list(versions.keys()): found = SEMVER_PATTERN.search(known_version) if found is not None: semversions.append(known_version) current_version = self.origin_version if version is None: # Pick the highest listed verson if ctx.obj.assume_yes: # There are no semversions if len(semversions) == 0: raise CannotDetermineRemoteVersion(self.localdir) current_not_semver = False try: semver.VersionInfo.parse(current_version) except ValueError as e: logger.warn(e) current_not_semver = True # Remove non-semvers latest_version = None _semversions = semversions semversions = list() for checkv in _semversions: try: semver.VersionInfo.parse(checkv) semversions.append(checkv) except ValueError: continue latest_version = sorted(semversions, reverse=True)[0] # Pick the latest version if fast_forward or current_not_semver: version = latest_version # Check if we're already at the latest version elif semver.compare(current_version, latest_version) == 0: version = latest_version # Find the next version else: semversions = sorted(semversions) for i in range(len(semversions)): try: comparison = semver.compare( semversions[i], current_version) except ValueError as e: logger.warn(e) continue if comparison == 0: # We should have never made it this far, but because we # did, we're at the latest version. if i + 1 == len(semversions): version = latest_version break # Select the next version else: version = semversions[i + 1] break # Prompt user for a version else: version = read_user_choice( 'version', sorted(list(versions.keys()), reverse=True)) if version not in versions.keys(): if ctx.obj.assume_yes: logger.warn("Provided version '%s' not known in: {%s}" % (version, ', '.join(versions.keys()))) else: raise UnknownLibraryOriginVersion(version, versions.keys()) if VSEMVER_PATTERN.search(version): version = version[1:] # Are we dealing with a semver pattern? try: if semver.compare(current_version, version) == 0: logger.info("Library already latest version: %s" % version) return version if semver.compare(current_version, version) > 0: if force_version: logger.warn("Downgrading library from %s to %s..." % (current_version, version)) else: raise BumpLibraryDowngrade(current_version, version) except ValueError: if current_version == version: logger.info("Library already at version: %s" % version) return version # Actually perform the bump makefile_uk = os.path.join(self.localdir, MAKEFILE_UK) logger.debug("Reading %s..." % makefile_uk) makefile_vars = make_list_vars(makefile_uk)['makefile'] version_var = None for var in makefile_vars: if var.endswith(UNIKRAFT_LIB_MAKEFILE_VERSION_EXT): version_var = var break logger.info('Upgrading library from %s to %s...' % (current_version, version)) for line in fileinput.input(makefile_uk, inplace=1): if line.startswith(version_var) and current_version in line: print('%s = %s' % (version_var, version)) else: print(line, end='') return version