text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
⌀
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def call(method: Method, *args: Any, **kwargs: Any) -> Any: """ Validates arguments and then calls the method. Args: method: The method to call. *args, **kwargs: ...
return validate_args(method, *args, **kwargs)(*args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def safe_call(request: Request, methods: Methods, *, debug: bool) -> Response: """ Call a Request, catching exceptions to ensure we always return a Response. Args...
with handle_exceptions(request, debug) as handler: result = call(methods.items[request.method], *request.args, **request.kwargs) handler.response = SuccessResponse(result=result, id=request.id) return handler.response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def call_requests( requests: Union[Request, Iterable[Request]], methods: Methods, debug: bool ) -> Response: """ Takes a request or list of Requests and calls the...
if isinstance(requests, collections.Iterable): return BatchResponse(safe_call(r, methods, debug=debug) for r in requests) return safe_call(requests, methods, debug=debug)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dispatch_pure( request: str, methods: Methods, *, context: Any, convert_camel_case: bool, debug: bool, ) -> Response: """ Pure version of dispatch - no loggin...
try: deserialized = validate(deserialize(request), schema) except JSONDecodeError as exc: return InvalidJSONResponse(data=str(exc), debug=debug) except ValidationError as exc: return InvalidJSONRPCResponse(data=None, debug=debug) return call_requests( create_requests( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serve(name: str = "", port: int = 5000) -> None: """ A basic way to serve the methods. Args: name: Server address. port: Server port. """
logging.info(" * Listening on port %s", port) httpd = HTTPServer((name, port), RequestHandler) httpd.serve_forever()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_camel_case_string(name: str) -> str: """Convert camel case string to snake case"""
string = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name) return re.sub("([a-z0-9])([A-Z])", r"\1_\2", string).lower()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_camel_case_keys(original_dict: Dict[str, Any]) -> Dict[str, Any]: """Converts all keys of a dict from camel case to snake case, recursively"""
new_dict = dict() for key, val in original_dict.items(): if isinstance(val, dict): # Recurse new_dict[convert_camel_case_string(key)] = convert_camel_case_keys(val) else: new_dict[convert_camel_case_string(key)] = val return new_dict
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_arguments( params: Union[List, Dict, object] = NOPARAMS, context: Any = NOCONTEXT ) -> Tuple[List, Dict]: """ Get the positional and keyword arguments fro...
positionals, nameds = [], {} # type: list, dict if params is not NOPARAMS: assert isinstance(params, (list, dict)) if isinstance(params, list): positionals, nameds = (params, {}) elif isinstance(params, dict): positionals, nameds = ([], params) # If context...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_args(func: Method, *args: Any, **kwargs: Any) -> Method: """ Check if the request's arguments match a function's signature. Raises TypeError exceptio...
signature(func).bind(*args, **kwargs) return func
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add(self, *args: Any, **kwargs: Any) -> Optional[Callable]: """ Register a function to the list. Args: *args: Set/Sequence of positional arguments. **kwargs: ...
self.items = { **self.items, # Methods passed as positional args need a __name__ attribute, raises # AttributeError otherwise. **{m.__name__: validate(m) for m in args}, **{k: validate(v) for k, v in kwargs.items()}, } if len(args): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fix_hyphen_commands(raw_cli_arguments): """Update options to match their module names with underscores."""
for i in ['gen-sample']: raw_cli_arguments[i.replace('-', '_')] = raw_cli_arguments[i] raw_cli_arguments.pop(i) return raw_cli_arguments
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(): """Provide main CLI entrypoint."""
if os.environ.get('DEBUG'): logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) # botocore info is spammy logging.getLogger('botocore').setLevel(logging.ERROR) cli_arguments = fix_hyphen_commands(docopt(__doc__, version=version)) # at...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calculate_hash_of_files(files, root): """Return a hash of all of the given files at the given root. Adapted from stacker.hooks.aws_lambda; used according to ...
file_hash = hashlib.md5() for fname in sorted(files): fileobj = os.path.join(root, fname) file_hash.update((fname + "\0").encode()) with open(fileobj, "rb") as filedes: for chunk in iter(lambda: filedes.read(4096), ""): # noqa pylint: disable=cell-var-from-loop ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_hash_of_files(root_path, directories=None): """Generate md5 hash of files."""
if not directories: directories = [{'path': './'}] files_to_hash = [] for i in directories: ignorer = get_ignorer(os.path.join(root_path, i['path']), i.get('exclusions')) with change_dir(root_path): for root, dirs, files in os.walk(i['path...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_ignorer(path, additional_exclusions=None): """Create ignorer with directory gitignore file."""
ignorefile = zgitignore.ZgitIgnore() gitignore_file = os.path.join(path, '.gitignore') if os.path.isfile(gitignore_file): with open(gitignore_file, 'r') as fileobj: ignorefile.add_patterns(fileobj.read().splitlines()) if additional_exclusions is not None: ignorefile.add_pat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_tf_release(version, versions_dir, command_suffix, tf_platform=None, arch=None): """Download Terraform archive and return path to it."""
version_dir = os.path.join(versions_dir, version) if arch is None: arch = ( os.environ.get('TFENV_ARCH') if os.environ.get('TFENV_ARCH') else 'amd64') if tf_platform: tfver_os = tf_platform + '_' + arch else: if platform.system().startswith('Darwin'): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_available_tf_versions(include_prerelease=False): """Return available Terraform versions."""
tf_releases = json.loads( requests.get('https://releases.hashicorp.com/index.json').text )['terraform'] tf_versions = sorted([k # descending for k, _v in tf_releases['versions'].items()], key=LooseVersion, reverse=True) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_min_required(path): """Inspect terraform files and find minimum version."""
found_min_required = '' for filename in glob.glob(os.path.join(path, '*.tf')): with open(filename, 'r') as stream: tf_config = hcl.load(stream) if tf_config.get('terraform', {}).get('required_version'): found_min_required = tf_config.get('terraform', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_version_requested(path): """Return string listing requested Terraform version."""
tf_version_path = os.path.join(path, TF_VERSION_FILENAME) if not os.path.isfile(tf_version_path): LOGGER.error("Terraform install attempted and no %s file present to " "dictate the version. Please create it (e.g. write " "\"0...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ensure_versions_dir_exists(tfenv_path): """Ensure versions directory is available."""
versions_dir = os.path.join(tfenv_path, 'versions') if not os.path.isdir(tfenv_path): os.mkdir(tfenv_path) if not os.path.isdir(versions_dir): os.mkdir(versions_dir) return versions_dir
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install(self, version_requested=None): """Ensure terraform is available."""
command_suffix = '.exe' if platform.system() == 'Windows' else '' versions_dir = ensure_versions_dir_exists(self.tfenv_dir) if not version_requested: version_requested = get_version_requested(self.path) if re.match(r'^min-required$', version_requested): LOGGER....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_param(context, provider, **kwargs): # noqa pylint: disable=unused-argument """Delete SSM parameter."""
parameter_name = kwargs.get('parameter_name') if not parameter_name: raise ValueError('Must specify `parameter_name` for delete_param ' 'hook.') session = get_session(provider.region) ssm_client = session.client('ssm') try: ssm_client.delete_parameter(Name...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_existing_iam_env_vars(self): """Backup IAM environment variables for later restoration."""
for i in ['AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY', 'AWS_SESSION_TOKEN']: if i in self.env_vars: self.env_vars['OLD_' + i] = self.env_vars[i]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restore_existing_iam_env_vars(self): """Restore backed up IAM environment variables."""
for i in ['AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY', 'AWS_SESSION_TOKEN']: if 'OLD_' + i in self.env_vars: self.env_vars[i] = self.env_vars['OLD_' + i] elif i in self.env_vars: self.env_vars.pop(i)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hello(event, context): # pylint: disable=unused-argument """Return Serverless Hello World."""
body = { "message": "Go Serverless v1.0! Your function executed successfully!", "input": event } response = { "statusCode": 200, "body": json.dumps(body) } return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_env(path, ignore_git_branch=False): """Determine environment name."""
if 'DEPLOY_ENVIRONMENT' in os.environ: return os.environ['DEPLOY_ENVIRONMENT'] if ignore_git_branch: LOGGER.info('Skipping environment lookup from current git branch ' '("ignore_git_branch" is set to true in the runway ' 'config)') else: # Th...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_env_dirs(self): """Return list of directories in env_root."""
repo_dirs = next(os.walk(self.env_root))[1] if '.git' in repo_dirs: repo_dirs.remove('.git') # not relevant for any repo operations return repo_dirs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_yaml_files_at_env_root(self): """Return list of yaml files in env_root."""
yaml_files = glob.glob( os.path.join(self.env_root, '*.yaml') ) yml_files = glob.glob( os.path.join(self.env_root, '*.yml') ) return yaml_files + yml_files
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_cookbook_dirs(self, base_dir=None): """Find cookbook directories."""
if base_dir is None: base_dir = self.env_root cookbook_dirs = [] dirs_to_skip = set(['.git']) for root, dirs, files in os.walk(base_dir): # pylint: disable=W0612 dirs[:] = [d for d in dirs if d not in dirs_to_skip] for name in files: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def path_only_contains_dirs(self, path): """Return boolean on whether a path only contains directories."""
pathlistdir = os.listdir(path) if pathlistdir == []: return True if any(os.path.isfile(os.path.join(path, i)) for i in pathlistdir): return False return all(self.path_only_contains_dirs(os.path.join(path, i)) for i in pathlistdir)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_empty_dirs(self, path): """Return a list of empty directories in path."""
empty_dirs = [] for i in os.listdir(path): child_path = os.path.join(path, i) if i == '.git' or os.path.isfile(child_path) or os.path.islink(child_path): # noqa continue if self.path_only_contains_dirs(child_path): empty_dirs.append(i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_runway_config(self): """Read and parse runway.yml."""
if not os.path.isfile(self.runway_config_path): LOGGER.error("Runway config file was not found (looking for " "%s)", self.runway_config_path) sys.exit(1) with open(self.runway_config_path) as data_file: return yaml.sa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def runway_config(self): """Return parsed runway.yml."""
if not self._runway_config: self._runway_config = self.parse_runway_config() return self._runway_config
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def purge_bucket(context, provider, **kwargs): """Delete objects in bucket."""
session = get_session(provider.region) if kwargs.get('bucket_name'): bucket_name = kwargs['bucket_name'] else: if kwargs.get('bucket_output_lookup'): value = kwargs['bucket_output_lookup'] handler = OutputLookup.handle elif kwargs.get('bucket_rxref_lookup'):...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute(self): """Output environment name."""
# Disable other runway logging so the only response is the env name logging.getLogger('runway').setLevel(logging.ERROR) # This may be invoked from a module directory in an environment; # account for that here if necessary if not os.path.isfile('runway.yml'): self.en...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_api_endpoint(): """Update app environment file with backend endpoint."""
environment = subprocess.check_output(['pipenv', 'run', 'runway', 'whichenv']).decode().strip() environment_file = os.path.join( os.path.dirname(os.path.realpath(__file__)), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def change_dir(newdir): """Change directory. Adapted from http://stackoverflow.com/a/24176022 """
prevdir = os.getcwd() os.chdir(os.path.expanduser(newdir)) try: yield finally: os.chdir(prevdir)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ensure_file_is_executable(path): """Exit if file is not executable."""
if platform.system() != 'Windows' and ( not stat.S_IXUSR & os.stat(path)[stat.ST_MODE]): print("Error: File %s is not executable" % path) sys.exit(1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge_dicts(dict1, dict2, deep_merge=True): """Merge dict2 into dict1."""
if deep_merge: if isinstance(dict1, list) and isinstance(dict2, list): return dict1 + dict2 if not isinstance(dict1, dict) or not isinstance(dict2, dict): return dict2 for key in dict2: dict1[key] = merge_dicts(dict1[key], dict2[key]) if key in dict1 el...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_boto_args_from_env(env_vars): """Return boto3 client args dict with environment creds."""
boto_args = {} for i in ['aws_access_key_id', 'aws_secret_access_key', 'aws_session_token']: if env_vars.get(i.upper()): boto_args[i] = env_vars[i.upper()] return boto_args
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flatten_path_lists(env_dict, env_root=None): """Join paths in environment dict down to strings."""
for (key, val) in env_dict.items(): # Lists are presumed to be path components and will be turned back # to strings if isinstance(val, list): env_dict[key] = os.path.join(env_root, os.path.join(*val)) if (env_root and not os.path.isabs(os.path.join(*val))) else os.path.join(*val...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge_nested_environment_dicts(env_dicts, env_name=None, env_root=None): """Return single-level dictionary from dictionary of dictionaries."""
# If the provided dictionary is just a single "level" (no nested # environments), it applies to all environments if all(isinstance(val, (six.string_types, list)) for (_key, val) in env_dicts.items()): return flatten_path_lists(env_dicts, env_root) if env_name is None: if env...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_embedded_lib_path(): """Return path of embedded libraries."""
return os.path.join( os.path.dirname(os.path.abspath(__file__)), 'embedded' )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_hash_for_filename(filename, hashfile_path): """Return hash for filename in the hashfile."""
filehash = '' with open(hashfile_path, 'r') as stream: for _cnt, line in enumerate(stream): if line.rstrip().endswith(filename): filehash = re.match(r'^[A-Za-z0-9]*', line).group(0) break if filehash: return filehash raise AttributeError("File...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fix_windows_command_list(commands): # type: (List[str]) -> List[str] """Return command list with working Windows commands. npm on windows is npm.cmd, which w...
fully_qualified_cmd_path = which(commands[0]) if fully_qualified_cmd_path and ( not which(commands[0], add_win_suffixes=False)): commands[0] = os.path.basename(fully_qualified_cmd_path) return commands
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_commands(commands, # type: List[Union[str, List[str], Dict[str, Union[str, List[str]]]]] directory, # type: str env=None # type: Optional[Dict[str, Union[...
if env is None: env = os.environ.copy() for step in commands: if isinstance(step, (list, six.string_types)): execution_dir = directory raw_command = step elif step.get('command'): # dictionary execution_dir = os.path.join(directory, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sha256sum(filename): """Return SHA256 hash of file."""
sha256 = hashlib.sha256() mem_view = memoryview(bytearray(128*1024)) with open(filename, 'rb', buffering=0) as stream: for i in iter(lambda: stream.readinto(mem_view), 0): sha256.update(mem_view[:i]) return sha256.hexdigest()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def use_embedded_pkgs(embedded_lib_path=None): """Temporarily prepend embedded packages to sys.path."""
if embedded_lib_path is None: embedded_lib_path = get_embedded_lib_path() old_sys_path = list(sys.path) sys.path.insert( 1, # https://stackoverflow.com/a/10097543 embedded_lib_path ) try: yield finally: sys.path = old_sys_path
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def which(program, add_win_suffixes=True): """Mimic 'which' command behavior. Adapted from https://stackoverflow.com/a/377028 """
def is_exe(fpath): """Determine if program exists and is executable.""" return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if add_win_suffixes and platform.system().lower() == 'windows' and not ( fname.endswith('.exe') or fname.ends...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_config_backend_options(module_opts, env_name, env_vars): """Return backend options defined in module options."""
backend_opts = {} if module_opts.get('terraform_backend_config'): backend_opts['config'] = merge_nested_environment_dicts( module_opts.get('terraform_backend_config'), env_name ) if module_opts.get('terraform_backend_cfn_outputs'): if not backend_opts.get('c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_backend_init_list(backend_vals): """Turn backend config dict into command line items."""
cmd_list = [] for (key, val) in backend_vals.items(): cmd_list.append('-backend-config') cmd_list.append(key + '=' + val) return cmd_list
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_backend_tfvars_file(path, environment, region): """Determine Terraform backend file."""
backend_filenames = gen_backend_tfvars_files(environment, region) for name in backend_filenames: if os.path.isfile(os.path.join(path, name)): return name return backend_filenames[-1]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_module_defined_tf_var(terraform_version_opts, env_name): """Return version of Terraform requested in module options."""
if isinstance(terraform_version_opts, six.string_types): return terraform_version_opts if terraform_version_opts.get(env_name): return terraform_version_opts.get(env_name) if terraform_version_opts.get('*'): return terraform_version_opts.get('*') return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_workspace_tfvars_file(path, environment, region): """Determine Terraform workspace-specific tfvars file name."""
for name in gen_workspace_tfvars_files(environment, region): if os.path.isfile(os.path.join(path, name)): return name return "%s.tfvars" % environment
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reinit_on_backend_changes(tf_bin, # pylint: disable=too-many-arguments module_path, backend_options, env_name, env_region, env_vars): """Clean terraform dire...
terraform_dir = os.path.join(module_path, '.terraform') local_tfstate_path = os.path.join(terraform_dir, 'terraform.tfstate') current_backend_config = {} desired_backend_config = {} LOGGER.debug('Comparing previous & desired Terraform backend configs') if os.path.isfile(local_tfstate_path): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_terraform_init(tf_bin, # pylint: disable=too-many-arguments module_path, backend_options, env_name, env_region, env_vars): """Run Terraform init."""
init_cmd = [tf_bin, 'init'] cmd_opts = {'env_vars': env_vars, 'exit_on_error': False} if backend_options.get('config'): LOGGER.info('Using provided backend values "%s"', str(backend_options.get('config'))) cmd_opts['cmd_list'] = init_cmd + get_backend_init_list(backend_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_command_class(possible_command_names): """Try to find a class for one of the given command names."""
for command_name in possible_command_names: if hasattr(ALL_COMMANDS_MODULE, command_name): command_module = getattr(ALL_COMMANDS_MODULE, command_name) command_class_hierarchy = getmembers(command_module, isclass) command_class_tuple = list(filter(_not_base_class, command...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_sample_module(module_dir): """Generate skeleton sample module."""
if os.path.isdir(module_dir): LOGGER.error("Error generating sample module -- directory %s " "already exists!", module_dir) sys.exit(1) os.mkdir(module_dir)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_sample_sls_module(env_root, module_dir=None): """Generate skeleton Serverless sample module."""
if module_dir is None: module_dir = os.path.join(env_root, 'sampleapp.sls') generate_sample_module(module_dir) for i in ['config-dev-us-east-1.json', 'handler.py', 'package.json', 'serverless.yml']: shutil.copyfile( os.path.join(ROOT, 'temp...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_sample_sls_tsc_module(env_root, module_dir=None): """Generate skeleton Serverless TypeScript sample module."""
if module_dir is None: module_dir = os.path.join(env_root, 'sampleapp.sls') generate_sample_module(module_dir) for i in ['package.json', 'serverless.yml', 'tsconfig.json', 'webpack.config.js']: shutil.copyfile( os.path.join(ROOT, 'templates...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_sample_cdk_tsc_module(env_root, module_dir=None): """Generate skeleton CDK TS sample module."""
if module_dir is None: module_dir = os.path.join(env_root, 'sampleapp.cdk') generate_sample_module(module_dir) for i in ['.npmignore', 'cdk.json', 'package.json', 'runway.module.yml', 'tsconfig.json', 'README.md']: shutil.copyfile( os.path.join(ROOT, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_sample_cdk_py_module(env_root, module_dir=None): """Generate skeleton CDK python sample module."""
if module_dir is None: module_dir = os.path.join(env_root, 'sampleapp.cdk') generate_sample_module(module_dir) for i in ['app.py', 'cdk.json', 'lambda-index.py', 'package.json', 'runway.module.yml', 'Pipfile']: shutil.copyfile( os.path.join(ROOT, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_sample_cfn_module(env_root, module_dir=None): """Generate skeleton CloudFormation sample module."""
if module_dir is None: module_dir = os.path.join(env_root, 'sampleapp.cfn') generate_sample_module(module_dir) for i in ['stacks.yaml', 'dev-us-east-1.env']: shutil.copyfile( os.path.join(ROOT, 'templates', 'cfn', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_sample_stacker_module(env_root, module_dir=None): """Generate skeleton Stacker sample module."""
if module_dir is None: module_dir = os.path.join(env_root, 'runway-sample-tfstate.cfn') generate_sample_module(module_dir) for i in ['stacks.yaml', 'dev-us-east-1.env']: shutil.copyfile( os.path.join(ROOT, 'templates', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_sample_tf_module(env_root, module_dir=None): """Generate skeleton Terraform sample module."""
if module_dir is None: module_dir = os.path.join(env_root, 'sampleapp.tf') generate_sample_module(module_dir) for i in ['backend-us-east-1.tfvars', 'dev-us-east-1.tfvars', 'main.tf']: shutil.copyfile( os.path.join(ROOT, 'templates', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute(self): """Run selected module generator."""
if self._cli_arguments['cfn']: generate_sample_cfn_module(self.env_root) elif self._cli_arguments['sls']: generate_sample_sls_module(self.env_root) elif self._cli_arguments['sls-tsc']: generate_sample_sls_tsc_module(self.env_root) elif self._cli_argum...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute(self): # pylint: disable=no-self-use """Generate runway.yml."""
if os.path.isfile('runway.yml'): print('Runway config already present') sys.exit(1) with open('runway.yml', 'w') as stream: stream.write("""--- deployments: - modules: - nameofmyfirstmodulefolder - nameofmysecondmodulefolder # - etc... regions...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def does_s3_object_exist(bucket_name, key, session=None): """Determine if object exists on s3."""
if session: s3_resource = session.resource('s3') else: s3_resource = boto3.resource('s3') try: s3_resource.Object(bucket_name, key).load() except ClientError as exc: if exc.response['Error']['Code'] == '404': return False raise return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_and_extract_to_mkdtemp(bucket, key, session=None): """Download zip archive and extract it to temporary directory."""
if session: s3_client = session.client('s3') else: s3_client = boto3.client('s3') transfer = S3Transfer(s3_client) filedes, temp_file = tempfile.mkstemp() os.close(filedes) transfer.download_file(bucket, key, temp_file) output_dir = tempfile.mkdtemp() zip_ref = zipfile...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def zip_and_upload(app_dir, bucket, key, session=None): """Zip built static site and upload to S3."""
if session: s3_client = session.client('s3') else: s3_client = boto3.client('s3') transfer = S3Transfer(s3_client) filedes, temp_file = tempfile.mkstemp() os.close(filedes) LOGGER.info("staticsite: archiving app at %s to s3://%s/%s", app_dir, bucket, key) wi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build(context, provider, **kwargs): # pylint: disable=unused-argument """Build static site."""
session = get_session(provider.region) options = kwargs.get('options', {}) context_dict = {} context_dict['artifact_key_prefix'] = "%s-%s-" % (options['namespace'], options['name']) # noqa default_param_name = "%shash" % context_dict['artifact_key_prefix'] if options.get('build_output'): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ensure_valid_environment_config(module_name, config): """Exit if config is invalid."""
if not config.get('namespace'): LOGGER.fatal("staticsite: module %s's environment configuration is " "missing a namespace definition!", module_name) sys.exit(1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plan(self): """Create website CFN module and run stacker diff."""
if self.options.get('environments', {}).get(self.context.env_name): self.setup_website_module(command='plan') else: LOGGER.info("Skipping staticsite plan of %s; no environment " "config found for this environment/region", self.opti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_npm_command_for_logging(command): """Convert npm command list to string for display to user."""
if platform.system().lower() == 'windows': if command[0] == 'npx.cmd' and command[1] == '-c': return "npx.cmd -c \"%s\"" % " ".join(command[2:]) return " ".join(command) # Strip out redundant npx quotes not needed when executing the command # directly return " ".join(command...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_node_command(command, command_opts, path): """Return node bin command list for subprocess execution."""
if which(NPX_BIN): # Use npx if available (npm v5.2+) LOGGER.debug("Using npx to invoke %s.", command) if platform.system().lower() == 'windows': cmd_list = [NPX_BIN, '-c', "%s %s" % (command, ' '.join(command_opts))] else:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_module_command(cmd_list, env_vars, exit_on_error=True): """Shell out to provisioner command."""
if exit_on_error: try: subprocess.check_call(cmd_list, env=env_vars) except subprocess.CalledProcessError as shelloutexc: sys.exit(shelloutexc.returncode) else: subprocess.check_call(cmd_list, env=env_vars)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def use_npm_ci(path): """Return true if npm ci should be used in lieu of npm install."""
# https://docs.npmjs.com/cli/ci#description with open(os.devnull, 'w') as fnull: if ((os.path.isfile(os.path.join(path, 'package-lock.json')) or os.path.isfile(os.path.join(path, 'npm-shrinkwrap.json'))) and ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cdk_module_matches_env(env_name, env_config, env_vars): """Return bool on whether cdk command should continue in current env."""
if env_config.get(env_name): current_env_config = env_config[env_name] if isinstance(current_env_config, type(True)) and current_env_config: return True if isinstance(current_env_config, six.string_types): (account_id, region) = current_env_config.split('/') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_cdk_stacks(module_path, env_vars, context_opts): """Return list of CDK stacks."""
LOGGER.debug('Listing stacks in the CDK app prior to ' 'diff') return subprocess.check_output( generate_node_command( command='cdk', command_opts=['list'] + context_opts, path=module_path), env=env_vars ).strip().split('\n')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assume_role(role_arn, session_name=None, duration_seconds=None, region='us-east-1', env_vars=None): """Assume IAM role."""
if session_name is None: session_name = 'runway' assume_role_opts = {'RoleArn': role_arn, 'RoleSessionName': session_name} if duration_seconds: assume_role_opts['DurationSeconds'] = int(duration_seconds) boto_args = {} if env_vars: for i in ['aws_acce...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def determine_module_class(path, class_path): """Determine type of module and return deployment module class."""
if not class_path: # First check directory name for type-indicating suffix basename = os.path.basename(path) if basename.endswith('.sls'): class_path = 'runway.module.serverless.Serverless' elif basename.endswith('.tf'): class_path = 'runway.module.terraform....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_module_opts_from_file(path, module_options): """Update module_options with any options defined in module path."""
module_options_file = os.path.join(path, 'runway.module.yml') if os.path.isfile(module_options_file): with open(module_options_file, 'r') as stream: module_options = merge_dicts(module_options, yaml.safe_load(st...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def post_deploy_assume_role(assume_role_config, context): """Revert to previous credentials, if necessary."""
if isinstance(assume_role_config, dict): if assume_role_config.get('post_deploy_env_revert'): context.restore_existing_iam_env_vars()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_account_alias(iam_client, account_alias): """Exit if list_account_aliases doesn't include account_alias."""
# Super overkill here using pagination when an account can only # have a single alias, but at least this implementation should be # future-proof current_account_aliases = [] paginator = iam_client.get_paginator('list_account_aliases') response_iterator = paginator.paginate() for page in res...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_account_id(sts_client, account_id): """Exit if get_caller_identity doesn't match account_id."""
resp = sts_client.get_caller_identity() if 'Account' in resp: if resp['Account'] == account_id: LOGGER.info('Verified current AWS account matches required ' 'account id %s.', account_id) else: LOGGER.error('Current AWS acco...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_account_credentials(deployment, context): """Exit if requested deployment account doesn't match credentials."""
boto_args = {'region_name': context.env_vars['AWS_DEFAULT_REGION']} for i in ['aws_access_key_id', 'aws_secret_access_key', 'aws_session_token']: if context.env_vars.get(i.upper()): boto_args[i] = context.env_vars[i.upper()] if isinstance(deployment.get('account-id'), (int...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def echo_detected_environment(env_name, env_vars): """Print a helper note about how the environment was determined."""
env_override_name = 'DEPLOY_ENVIRONMENT' LOGGER.info("") if env_override_name in env_vars: LOGGER.info("Environment \"%s\" was determined from the %s environment variable.", env_name, env_override_name) LOGGER.info("If this is not correct, update " ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _module_menu_entry(module, environment_name): """Build a string to display in the 'select module' menu."""
name = _module_name_for_display(module) if isinstance(module, dict): environment_config = module.get('environments', {}).get(environment_name) if environment_config: return "%s (%s)" % (name, environment_config) return "%s" % (name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _deployment_menu_entry(deployment): """Build a string to display in the 'select deployment' menu."""
paths = ", ".join([_module_name_for_display(module) for module in deployment['modules']]) regions = ", ".join(deployment.get('regions', [])) return "%s - %s (%s)" % (deployment.get('name'), paths, regions)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select_deployment_to_run(env_name, deployments=None, command='build'): # noqa pylint: disable=too-many-branches,too-many-statements,too-many-locals """Query ...
if deployments is None or not deployments: return [] deployments_to_run = [] num_deployments = len(deployments) if num_deployments == 1: selected_deployment_index = 1 else: print('') print('Configured deployments:') f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gen_sls_config_files(stage, region): """Generate possible SLS config files names."""
names = [] for ext in ['yml', 'json']: # Give preference to explicit stage-region files names.append( os.path.join('env', "%s-%s.%s" % (stage, region, ext)) ) names.append("config-%s-%s.%s" % (stage, region, ext)) # Fallback to stage ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_sls_config_file(path, stage, region): """Determine Serverless config file name."""
for name in gen_sls_config_files(stage, region): if os.path.isfile(os.path.join(path, name)): return name return "config-%s.json" % stage
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_sls_remove(sls_cmd, env_vars): """Run sls remove command."""
sls_process = subprocess.Popen(sls_cmd, stdout=subprocess.PIPE, env=env_vars) stdoutdata, _stderrdata = sls_process.communicate() sls_return = sls_process.wait() print(stdoutdata) if sls_return != 0 and (sls_return == 1 and not (...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_serverless(self, command='deploy'): """Run Serverless."""
response = {'skipped_configs': False} sls_opts = [command] if not which('npm'): LOGGER.error('"npm" not found in path or is not executable; ' 'please ensure it is installed correctly.') sys.exit(1) if 'CI' in self.context.env_vars and c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def aws_cli(*cmd): """Invoke aws command."""
old_env = dict(os.environ) try: # Environment env = os.environ.copy() env['LC_CTYPE'] = u'en_US.UTF' os.environ.update(env) # Run awscli in the same process exit_code = create_clidriver().main(*cmd) # Deal with problems if exit_code > 0: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_archives_to_prune(archives, hook_data): """Return list of keys to delete."""
files_to_skip = [] for i in ['current_archive_filename', 'old_archive_filename']: if hook_data.get(i): files_to_skip.append(hook_data[i]) archives.sort(key=itemgetter('LastModified'), reverse=False) # sort from oldest to newest # Drop all but last 15 files ret...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sync(context, provider, **kwargs): # pylint: disable=too-many-locals """Sync static website to S3 bucket."""
session = get_session(provider.region) bucket_name = OutputLookup.handle(kwargs.get('bucket_output_lookup'), provider=provider, context=context) if context.hook_data['staticsite']['deploy_is_current']: LOGGER.info('statics...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ensure_stacker_compat_config(config_filename): """Ensure config file can be loaded by Stacker."""
try: with open(config_filename, 'r') as stream: yaml.safe_load(stream) except yaml.constructor.ConstructorError as yaml_error: if yaml_error.problem.startswith( 'could not determine a constructor for the tag \'!'): LOGGER.error('"%s" appears to be a Cloud...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_stacker_env_file(path, environment, region): """Determine Stacker environment file name."""
for name in gen_stacker_env_files(environment, region): if os.path.isfile(os.path.join(path, name)): return name return "%s-%s.env" % (environment, region)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_stacker_cmd_string(args, lib_path): """Generate stacker invocation script from command line arg list. This is the standard stacker invocation script, wi...
if platform.system().lower() == 'windows': # Because this will be run via subprocess, the backslashes on Windows # will cause command errors lib_path = lib_path.replace('\\', '/') return ("import sys;" "sys.argv = ['stacker'] + {args};" "sys.path.insert(1, '{lib_...