def install(ctx, version, url, y): """Download and initialise a MineCraft server with the specified VERSION or download URL into the working directory. """ # Input validation if version is not None and url is not None: raise UsageError('Use option VERSION or URL. Not both.') if version is None and url is None: ctx.invoke(versions) value = click.prompt( 'Please enter the MineCraft Server VERSION number' ' or URL to a JAR file', default='1.16.1').strip() if value.startswith('http:') or value.startswith('https:'): url = value else: version = value # URL passed if url is not None: server_info = {'url': url} # VERSION passed if version is not None: versions_info = util.get_server_versions_info() if version not in versions_info: raise UsageError('VERSION not found in list of versions. Try URL ' 'or mcserver versions command to list known ' 'versions.') server_info = versions_info[version] # Prompt message print( f'\nDownload and initialise this MineCraft Server under {Path.cwd()}:', f'version: {version or "-"}', f'release date: {server_info.get("date", "-")}', f'download url: {server_info["url"]}', sep='\n\t') if not y: click.confirm('Do you want to continue?', default=True, abort=True) # Eula print('\nPlease read the MINECRAFT END USER LICENSE AGREEMENT:', 'https://account.mojang.com/documents/minecraft_eula', sep='\n\t') if not y: click.confirm('Do you accept?', default=True, abort=True) # Download print('\nDownloading server.jar...') util.download_from_url(server_info['url']) # Run print('Initialising server...') subprocess.call(['java', '-jar', 'server.jar', '--initSettings']) with open('eula.txt', 'r') as f: eula = f.read() with open('eula.txt', 'w') as f: f.write(eula.replace('false', 'true')) # Ending message print('Server initialised!')
def test_usage_hint(mocker, mocked_utils): mocked_utils.is_brewblox_cwd.return_value = True main.usage_hint(UsageError('')) assert mocked_utils.is_brewblox_cwd.call_count == 0 main.usage_hint(UsageError('No such command')) assert mocked_utils.is_brewblox_cwd.call_count == 1 mocked_utils.is_brewblox_cwd.return_value = False mocked_utils.path_exists.return_value = False main.usage_hint(UsageError('No such command')) mocked_utils.path_exists.return_value = True main.usage_hint(UsageError('No such command')) mock_cli = mocker.patch(TESTED + '.click_helpers.OrderedCommandCollection') mock_cli.return_value.side_effect = main.UsageError('No such command') mocked_utils.is_root.return_value = False mocked_utils.is_v6.return_value = False # call to getenv(BREWBLOX_DEBUG) mocked_utils.getenv.side_effect = [ 'true', None, ] with pytest.raises(UsageError): main.main(['nope']) with pytest.raises(SystemExit): main.main(['nope'])
def call(cls, method, *args, **kwargs): """ Call a remote api method and return the result.""" try: api = cls.get_api_connector() apikey = cls.get('api.key') except MissingConfiguration: if not kwargs.get('safe'): cls.echo("No configuration found, please use 'gandi setup' " "command") sys.exit(1) else: return [] # make the call cls.debug('calling method: %s' % method) for arg in args: cls.debug('with params: %r' % arg) try: return api.request(apikey, method, *args) except APICallFailed as err: if kwargs.get('safe'): return [] error = UsageError(err.errors) setattr(error, 'code', err.code) if err.code == 510150: cls.echo("Invalid API key, please use 'gandi setup' command.") sys.exit(1) raise error
def convert(self, value, param, ctx): parts = value.split('=', 1) if len(parts) < 2: raise UsageError( f"Invalid argument: {value}: must be in Key=Value form.", ctx=ctx) return parts[0], parts[1]
def start(world, universe): """Start server.jar in the working directory using the command: java -jar server.jar --world WORLD --universe UNIVERSE For more flexibility, you can use the java command instead. java <JAVA-SETTINGS> -jar server.jar <MINECRAFT-SETTINGS> java -Xms512M -Xmx5G -jar server.jar --universe worlds/ --world myworld See `java --help` and `java -X` for flags/options Java runtime. See `java -jar server.jar --help` for flags/options for MineCraft. Important: use options `--universe worlds/ --world <WORLD-NAME>` so that EZ-mcserver can detect worlds (only sees worlds in worlds/ directory). """ if Path('server.jar').exists(): try: ip = requests.get('https://api.ipify.org').text print('Starting server with public IP', ip) except Exception as e: print('Starting server. Public IP cannot be determined. (Ensure ' 'that your device has access to the internet. If using an ' 'instance on the cloud, ensure that firewalls/security-' 'groups/ACLs allow port 25565 traffic to the internet') command = f'java -jar server.jar --world {world} --universe {universe}' subprocess.call(command.split()) else: raise UsageError('server.jar file does not exist. Aborted!')
def inbox_put(state, file): """Upload a recording file to the MH inbox""" if file.startswith('s3'): with cd(state.inbox_path): sudo("aws s3 cp %s ." % file) result = state.inbox_path + '/' + basename(file) elif exists(file): size_in_bytes = getsize(file) if size_in_bytes / (1024 * 1024) > 1024: raise UsageError( "File > 1G. Upload to s3 and use the url instead.") result = put(local_path=file, remote_path=state.inbox_path, use_sudo=True) else: raise UsageError("Local file %s not found" % file) print(cyan("Files created: {}".format(str(result))))
def load_all(filename): """Generate objects contained in ``filename``.""" if filename.endswith('.yaml') or filename.endswith('.yml'): with io.open(filename, encoding='utf-8') as handle: for obj in yaml.load_all(handle): yield obj else: raise UsageError( "Unsupported file type (extension) in '{}'!".format(filename))
def check_endpoint(value): """Check if the given endpoint is in the allowed ones.""" endpoints = ENDPOINTS.keys() if value not in endpoints: raise UsageError('This endpoint does not exist ({})'.format(', '.join( sorted(endpoints)))) return value
def worlds_delete(name, y): """Delete a world in the worlds/ directory (universe)""" world_path = Path('worlds').joinpath(name) if world_path not in [w for w in Path('worlds').glob('*')]: raise UsageError(f'No world found under {world_path}') if not y: click.confirm(f'Are you sure you want to delete {world_path}?', abort=True) shutil.rmtree(world_path)
def save(self, name): input_file = tempfile.NamedTemporaryFile(dir='.', delete=False) input_file.close() with io.open(input_file.name, 'w', encoding='utf-8') as input_file: input_file.write(self.render(name).decode('utf-8')) output_file = self.get_report_config_value(name, 'filename') if not output_file and name: output_file = '%s.pdf' % name if not output_file: output_file = 'default.pdf' output_file = self.render_string(output_file, name) cmd = 'pandoc "%s" -t html5 -o "%s"' % (input_file.name, output_file) styling = self.get_report_config_value(name, 'styling') template_name = self.get_report_config_value(name, 'template') if styling: styling = os.path.join(self.cfg_templates, styling) styling = '--css "%s"' % styling elif template_name: styling_default = template_name.split('.')[0] + '.css' styling_default_path = os.path.join(self.cfg_templates, styling_default) if os.path.exists(styling_default_path): cmd = cmd + ' --css %s' % styling_default_path input_file.close() cmd_list = split_arg_string(cmd) try: subprocess.check_output(cmd_list) except OSError: raise UsageError('Pandoc was not found on your system') except subprocess.CalledProcessError: raise UsageError('Pandoc %s returned non-zero exit status' % cmd) os.unlink(input_file.name) return output_file
def login(ctx): """Set or change Vault login credentials in your keyring.""" if not keyring: raise UsageError("'keyring' support is not available, please read" " 'https://config-sesame.readthedocs.io/en/latest/deploy.html'!", ctx=ctx) url, user, token, _ = vault.default_credentials() if not url: raise UsageError("You MUST provide a VAULT_ADDR!", ctx=ctx) if token: click.secho("WARN: You have a VAULT_TOKEN variable in your environment," " which will override any keyring credentials!", fg='yellow', bg='black', bold=True, reverse=True) click.echo("Please enter credentials for storing in {}.{}..." .format(keyring.get_keyring().__class__.__module__, keyring.get_keyring().__class__.__name__)) access = security.Credentials(url) user, token = access.auth_pair(force_console=True) # Prompt for new password keyring.set_password(url, user, token) click.echo("Updated {}'s password (token) for {}".format(user, url))
def backup(self, **kwargs): """Get backup operation.""" try: conn = sqlite3.connect(kwargs['db_path']) cursor = conn.cursor() query = cursor.execute('SELECT KEY, PATH FROM keys') except sqlite3.OperationalError: raise UsageError(message='Invalid database [PATH].') return query
def convert(self, value, param, ctx): values = value.split(',') pairs = [] for v in values: parts = v.split('=', 1) if len(parts) < 2: raise UsageError( f"Invalid argument: {v}: must be in Key=Value form.", ctx=ctx) pairs.append((parts[0], parts[1])) return pairs
def handle_parse_result(self, ctx, opts, args): current_opt: bool = self.name in opts for mutex_opt in self.exclusive_with: if mutex_opt in opts: if current_opt: raise UsageError("'" + str(self.name) + "' is mutually exclusive with " + str(mutex_opt) + ".", ctx=ctx) else: self.prompt = None return super(ClickMutex, self).handle_parse_result(ctx, opts, args)
def wrapped(state, *args, **kwargs): # set up the fabric env env.host_string = state.host if state.ssh_user: env.user = state.ssh_user if not remote_exists(state.inbox_path): raise UsageError( "Invalid remote inbox path: %s" % state.inbox_path) return click_cmd(state, *args, **kwargs)
def handle_parse_result(self, option: GroupedOption, ctx: Context, opts) -> None: options = self.get_options(ctx) this_group_opts = set(options).intersection(opts) other_group_opts = self._conflicts.intersection(opts) if this_group_opts and other_group_opts: # noinspection PyUnboundLocalVariable raise UsageError( f'Arguments {this_group_opts} are not allowed to be combined with {other_group_opts}', ctx) elif this_group_opts or (not this_group_opts and not other_group_opts): missing = { name for name, opt in options.items() if name not in this_group_opts and isinstance(opt, MaybeRequiredOption) and opt._required } if missing: raise UsageError( 'The following arguments are required: {}'.format( ', '.join(sorted(missing))))
def handle_parse_result(self, ctx, opts, args): current_opt: bool = self.name in opts for req_opt in self.required_if: if req_opt in opts: if not current_opt: raise UsageError("'" + str(self.name) + "' is required if '" + str(req_opt) + "' is specified.", ctx=ctx) else: self.prompt = None return super(ClickRequiredIfPresent, self).handle_parse_result(ctx, opts, args)
def export(ctx, repo, outfile, serializer): """Export labels of the given repo(s) to a file.""" api = github.api(config=None) # TODO: config object tabdata = tablib.Dataset() if repo and repo[-1].lower() == 'to': repo = repo[:-1] if not repo: raise UsageError("You provided no repository names!", ctx=ctx) outname = getattr(outfile, 'name', None) if serializer is None: _, ext = os.path.splitext(outname or '<stream>') ext = ext.lstrip('.') if ext in SERIALIZERS: serializer = ext else: raise UsageError( 'No --format given, and extension of "{}" is not one of {}.'. format(outname, ', '.join(SERIALIZERS)), ctx=ctx) for idx, reponame in enumerate(repo): user, repo, data = get_labels(api, reponame) if not idx: tabdata.headers = HEADERS tabdata.append_separator('⎇ {}/{}'.format(user, repo)) tabdata.extend(data) text = getattr(tabdata, serializer) if not isinstance(text, string_types): text = repr(text) if serializer in SERIALIZERS_NEED_NL: text += '\n' if isinstance(text, text_type): text = text.encode('utf-8') try: outfile.write(text) except EnvironmentError as cause: raise dclick.LoggedFailure('Error while writing "{}" ({})'.format( outname, cause))