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: Arguments to the method. Returns: The "result" part of the JSON-RPC response (the return value from the method). Raises: TypeError: If arguments don't match function signature. """
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: request: The Request object. methods: The list of methods that can be called. debug: Include more information in error responses. Returns: A Response object. """
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 them. Args: requests: Request object, or a collection of them. methods: The list of methods that can be called. debug: Include more information in error responses. """
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 logging, no optional parameters. Does two things: 1. Deserializes and validates the string. 2. Calls each request. Args: request: The incoming request string. methods: Collection of methods that can be called. context: If specified, will be the first positional argument in all requests. convert_camel_case: Will convert the method name/any named params to snake case. debug: Include more information in error responses. Returns: A Response. """
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( deserialized, context=context, convert_camel_case=convert_camel_case ), 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 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 from a request. Takes the 'params' part of a JSON-RPC request and converts it to either positional or named arguments usable in a Python function call. Note that a JSON-RPC request can only have positional _or_ named arguments, but not both. See http://www.jsonrpc.org/specification#parameter_structures Args: params: The 'params' part of the JSON-RPC request (should be a list or dict). The 'params' value can be a JSON array (Python list), object (Python dict), or None. context: Optionally include some context data, which will be included as the first positional arguments passed to the method. Returns: A two-tuple containing the positional (in a list, or None) and named (in a dict, or None) arguments, extracted from the 'params' part of the request. """
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 data was passed, include it as the first positional argument. if context is not NOCONTEXT: positionals = [context] + positionals return (positionals, nameds)
<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 exception if arguments cannot be passed to a function. Args: func: The function to check. args: Positional arguments. kwargs: Keyword arguments. Raises: TypeError: If the arguments cannot be passed to the function. """
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: Mapping of named arguments. Raises: AttributeError: Raised if the method being added has no name. (i.e. it has no `__name__` property, and no `name` argument was given.) Examples: methods = Methods() @methods.add def subtract(minuend, subtrahend): return minuend - subtrahend """
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): return args[0] # for the decorator to work 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 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 least one of these must be enabled, i.e. the value is 'True'... but unfortunately # `docopts` doesn't give you the hierarchy... so given 'gen-sample cfn', there are # TWO enabled items in the list, 'gen-sample' and 'cfn' possible_commands = [command for command, enabled in cli_arguments.items() if enabled] command_class = find_command_class(possible_commands) if command_class: command_class(cli_arguments).execute() else: LOGGER.error("class not found for command '%s'", possible_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 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 its license: https://github.com/cloudtools/stacker/blob/1.4.0/LICENSE Args: files (list[str]): file names to include in the hash calculation, relative to ``root``. root (str): base directory to analyze files in. Returns: str: A hash of the hashes of the given files. """
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 if not chunk: break file_hash.update(chunk) file_hash.update("\0".encode()) return file_hash.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 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'], topdown=True): if (root != './') and ignorer.is_ignored(root, True): dirs[:] = [] files[:] = [] else: for filename in files: filepath = os.path.join(root, filename) if not ignorer.is_ignored(filepath): files_to_hash.append( filepath[2:] if filepath.startswith('./') else filepath # noqa ) return calculate_hash_of_files(files_to_hash, root_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_patterns(additional_exclusions) return ignorefile
<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'): tfver_os = "darwin_%s" % arch elif platform.system().startswith('MINGW64') or ( platform.system().startswith('MSYS_NT') or ( platform.system().startswith('CYGWIN_NT'))): tfver_os = "windows_%s" % arch else: tfver_os = "linux_%s" % arch download_dir = tempfile.mkdtemp() filename = "terraform_%s_%s.zip" % (version, tfver_os) shasums_name = "terraform_%s_SHA256SUMS" % version tf_url = "https://releases.hashicorp.com/terraform/" + version for i in [filename, shasums_name]: urlretrieve(tf_url + '/' + i, os.path.join(download_dir, i)) tf_hash = get_hash_for_filename(filename, os.path.join(download_dir, shasums_name)) if tf_hash != sha256sum(os.path.join(download_dir, filename)): LOGGER.error("Downloaded Terraform %s does not match sha256 %s", filename, tf_hash) sys.exit(1) tf_zipfile = zipfile.ZipFile(os.path.join(download_dir, filename)) os.mkdir(version_dir) tf_zipfile.extractall(version_dir) tf_zipfile.close() shutil.rmtree(download_dir) os.chmod( # ensure it is executable os.path.join(version_dir, 'terraform' + command_suffix), os.stat(os.path.join(version_dir, 'terraform' + command_suffix)).st_mode | 0o0111 )
<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) if include_prerelease: return tf_versions return [i for i in tf_versions if '-' not in 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 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', {}).get('required_version') break if found_min_required: if re.match(r'^!=.+', found_min_required): LOGGER.error('Min required Terraform version is a negation (%s) ' '- unable to determine required version', found_min_required) sys.exit(1) else: found_min_required = re.search(r'[0-9]*\.[0-9]*(?:\.[0-9]*)?', found_min_required).group(0) LOGGER.debug("Detected minimum terraform version is %s", found_min_required) return found_min_required LOGGER.error('Terraform version specified as min-required, but unable to ' 'find a specified version requirement in this module\'s tf ' 'files') 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 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.11.13\" (without quotes) to the file and try again", TF_VERSION_FILENAME) sys.exit(1) with open(tf_version_path, 'r') as stream: ver = stream.read().rstrip() return ver
<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.debug('tfenv: detecting minimal required version') version_requested = find_min_required(self.path) if re.match(r'^latest:.*$', version_requested): regex = re.search(r'latest:(.*)', version_requested).group(1) include_prerelease_versions = False elif re.match(r'^latest$', version_requested): regex = r'^[0-9]+\.[0-9]+\.[0-9]+$' include_prerelease_versions = False else: regex = "^%s$" % version_requested include_prerelease_versions = True # Return early (i.e before reaching out to the internet) if the # matching version is already installed if os.path.isdir(os.path.join(versions_dir, version_requested)): LOGGER.info("Terraform version %s already installed; using " "it...", version_requested) return os.path.join(versions_dir, version_requested, 'terraform') + command_suffix try: version = next(i for i in get_available_tf_versions( include_prerelease_versions) if re.match(regex, i)) except StopIteration: LOGGER.error("Unable to find a Terraform version matching regex: %s", regex) sys.exit(1) # Now that a version has been selected, skip downloading if it's # already been downloaded if os.path.isdir(os.path.join(versions_dir, version)): LOGGER.info("Terraform version %s already installed; using it...", version) return os.path.join(versions_dir, version, 'terraform') + command_suffix LOGGER.info("Downloading and using Terraform version %s ...", version) download_tf_release(version, versions_dir, command_suffix) LOGGER.info("Downloaded Terraform %s successfully", version) return os.path.join(versions_dir, version, 'terraform') + command_suffix
<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=parameter_name) except ssm_client.exceptions.ParameterNotFound: LOGGER.info("%s parameter appears to have already been deleted...", parameter_name) 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 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: # These are not located with the top imports because they throw an # error if git isn't installed from git import Repo as GitRepo from git.exc import InvalidGitRepositoryError try: b_name = GitRepo( path, search_parent_directories=True ).active_branch.name LOGGER.info('Deriving environment name from git branch %s...', b_name) return get_env_from_branch(b_name) except InvalidGitRepositoryError: pass LOGGER.info('Deriving environment name from directory %s...', path) return get_env_from_directory(os.path.basename(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_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: if name == 'metadata.rb': if 'cookbook' in os.path.basename(os.path.dirname(root)): cookbook_dirs.append(root) return cookbook_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 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) return empty_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 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.safe_load(data_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 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'): value = kwargs['bucket_rxref_lookup'] handler = RxrefLookup.handle elif kwargs.get('bucket_xref_lookup'): value = kwargs['bucket_xref_lookup'] handler = XrefLookup.handle else: LOGGER.fatal('No bucket name/source provided.') return False try: # Exit early if the bucket's stack is already deleted session.client('cloudformation').describe_stacks( StackName=context.get_fqn(value.split('::')[0]) ) except ClientError as exc: if 'does not exist' in exc.response['Error']['Message']: LOGGER.info('S3 bucket stack appears to have already been ' 'deleted...') return True raise bucket_name = handler( value, provider=provider, context=context ) s3_resource = session.resource('s3') try: s3_resource.meta.client.head_bucket(Bucket=bucket_name) except ClientError as exc: if exc.response['Error']['Code'] == '404': LOGGER.info("%s S3 bucket appears to have already been deleted...", bucket_name) return True raise bucket = s3_resource.Bucket(bucket_name) bucket.object_versions.delete() 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 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.env_root = os.path.dirname(os.getcwd()) self.runway_config_path = os.path.join(self.env_root, 'runway.yml') print(get_env( self.env_root, self.runway_config.get('ignore_git_branch', False) ))
<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__)), 'src', 'environments', 'environment.prod.ts' if environment == 'prod' else 'environment.ts' ) cloudformation = boto3.resource('cloudformation') stack = cloudformation.Stack(STACK_PREFIX + environment) endpoint = [i['OutputValue'] for i in stack.outputs if i['OutputKey'] == 'ServiceEndpoint'][0] with open(environment_file, 'r') as stream: content = stream.read() content = re.sub(r'api_url: \'.*\'$', "api_url: '%s/api'" % endpoint, content, flags=re.M) with open(environment_file, 'w') as stream: stream.write(content)
<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 else dict2[key] # noqa pylint: disable=line-too-long return dict1 dict3 = dict1.copy() dict3.update(dict2) return dict3
<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) # noqa pylint: disable=line-too-long return env_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 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_dicts.get('*'): return flatten_path_lists(env_dicts.get('*'), env_root) raise AttributeError("Provided config key:val pairs %s aren't usable with no environment provided" % env_dicts) # noqa pylint: disable=line-too-long if not env_dicts.get('*') and not env_dicts.get(env_name): raise AttributeError("Provided config key:val pairs %s aren't usable with environment %s" % (env_dicts, env_name)) # noqa pylint: disable=line-too-long combined_dicts = merge_dicts(env_dicts.get('*', {}), env_dicts.get(env_name, {})) return flatten_path_lists(combined_dicts, env_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 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("Filename %s not found in hash file" % filename)
<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 will blow up Similar issues arise when calling python apps like pipenv that will have a windows-only suffix applied to them """
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[str, int]]] ): # noqa """Run list of commands."""
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, step.get('cwd')) if step.get('cwd') else directory # noqa pylint: disable=line-too-long raw_command = step['command'] else: raise AttributeError("Invalid command step: %s" % step) command_list = raw_command.split(' ') if isinstance(raw_command, six.string_types) else raw_command # noqa pylint: disable=line-too-long if platform.system().lower() == 'windows': command_list = fix_windows_command_list(command_list) with change_dir(execution_dir): check_call(command_list, env=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 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.endswith('.cmd')): fnames = [fname + '.exe', fname + '.cmd'] else: fnames = [fname] for i in fnames: if fpath: exe_file = os.path.join(fpath, i) if is_exe(exe_file): return exe_file else: for path in os.environ['PATH'].split(os.pathsep): exe_file = os.path.join(path, i) if is_exe(exe_file): return exe_file 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 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('config'): backend_opts['config'] = {} if not backend_opts['config'].get('region'): backend_opts['config']['region'] = env_vars['AWS_DEFAULT_REGION'] boto_args = extract_boto_args_from_env(env_vars) cfn_client = boto3.client( 'cloudformation', region_name=backend_opts['config']['region'], **boto_args ) for (key, val) in merge_nested_environment_dicts(module_opts.get('terraform_backend_cfn_outputs'), # noqa pylint: disable=line-too-long env_name).items(): backend_opts['config'][key] = find_cfn_output( val.split('::')[1], cfn_client.describe_stacks( StackName=val.split('::')[0] )['Stacks'][0]['Outputs'] ) return backend_opts
<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 directory and run init if necessary. If deploying a TF module to multiple regions (or any scenario requiring multiple backend configs), switching the backend will cause TF to compare the old and new backends. This will frequently cause an access error as the creds/role for the new backend won't always have access to the old one. This method compares the defined & initialized backend configs and trashes the terraform directory & re-inits if they're out of sync. """
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): with open(local_tfstate_path, 'r') as stream: current_backend_config = hcl.load(stream).get('backend', {}).get('config', {}) if backend_options.get('config'): desired_backend_config = backend_options.get('config') elif os.path.isfile(os.path.join(module_path, backend_options.get('filename'))): with open(os.path.join(module_path, backend_options.get('filename')), 'r') as stream: desired_backend_config = hcl.load(stream) # Can't solely rely on the backend info defined in runway options or # backend files; merge in the values defined in main.tf # (or whatever tf file) for filename in ['main.tf'] + glob.glob(os.path.join(module_path, '*.tf')): if os.path.isfile(filename): with open(filename, 'r') as stream: tf_config = hcl.load(stream) if tf_config.get('terraform', {}).get('backend'): [(_s3key, tffile_backend_config)] = tf_config['terraform']['backend'].items() # noqa pylint: disable=line-too-long desired_backend_config = merge_dicts( desired_backend_config, tffile_backend_config ) break if current_backend_config != desired_backend_config: LOGGER.info("Desired and previously initialized TF backend config is " "out of sync; trashing local TF state directory %s", terraform_dir) send2trash(terraform_dir) run_terraform_init( tf_bin=tf_bin, module_path=module_path, backend_options=backend_options, env_name=env_name, env_region=env_region, env_vars=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 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_options.get('config')) # noqa pylint: disable=line-too-long elif os.path.isfile(os.path.join(module_path, backend_options.get('filename'))): LOGGER.info('Using backend config file %s', backend_options.get('filename')) cmd_opts['cmd_list'] = init_cmd + ['-backend-config=%s' % backend_options.get('filename')] # noqa pylint: disable=line-too-long else: LOGGER.info( "No backend tfvars file found -- looking for one " "of \"%s\" (proceeding with bare 'terraform " "init')", ', '.join(gen_backend_tfvars_files( env_name, env_region))) cmd_opts['cmd_list'] = init_cmd try: run_module_command(**cmd_opts) except subprocess.CalledProcessError as shelloutexc: # An error during initialization can leave things in an inconsistent # state (e.g. backend configured but no providers downloaded). Marking # this with a file so it will be deleted on the next run. if os.path.isdir(os.path.join(module_path, '.terraform')): with open(os.path.join(module_path, '.terraform', FAILED_INIT_FILENAME), 'w') as stream: stream.write('1') sys.exit(shelloutexc.returncode)
<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_class_hierarchy))[0] return command_class_tuple[1] 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 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, 'templates', 'serverless', i), os.path.join(module_dir, i), ) LOGGER.info("Sample Serverless module created at %s", 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_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', 'sls-tsc', i), os.path.join(module_dir, i), ) os.mkdir(os.path.join(module_dir, 'src')) for i in ['handler.spec.ts', 'handler.ts']: shutil.copyfile( os.path.join(ROOT, 'templates', 'sls-tsc', 'src', i), os.path.join(module_dir, 'src', i), ) LOGGER.info("Sample Serverless TypeScript module created at %s", 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_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, 'templates', 'cdk-tsc', i), os.path.join(module_dir, i), ) for i in [['bin', 'sample.ts'], ['lib', 'sample-stack.ts']]: os.mkdir(os.path.join(module_dir, i[0])) shutil.copyfile( os.path.join(ROOT, 'templates', 'cdk-tsc', i[0], i[1]), os.path.join(module_dir, i[0], i[1]), ) with open(os.path.join(module_dir, '.gitignore'), 'w') as stream: stream.write('*.js\n') stream.write('*.d.ts\n') stream.write('node_modules\n') LOGGER.info("Sample CDK module created at %s", module_dir) LOGGER.info('To finish its setup, change to the %s directory and execute ' '"npm install" to generate its lockfile.', 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_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, 'templates', 'cdk-py', i), os.path.join(module_dir, i), ) with open(os.path.join(module_dir, '.gitignore'), 'w') as stream: stream.write('node_modules') LOGGER.info("Sample CDK module created at %s", module_dir) LOGGER.info('To finish its setup, change to the %s directory and execute ' '"npm install" and "pipenv update -d --three" to generate its ' 'lockfiles.', 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_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', i), os.path.join(module_dir, i) ) os.mkdir(os.path.join(module_dir, 'templates')) with open(os.path.join(module_dir, 'templates', 'tf_state.yml'), 'w') as stream: stream.write( cfn_flip.flip( check_output( [sys.executable, os.path.join(ROOT, 'templates', 'stacker', 'tfstate_blueprints', 'tf_state.py')] ) ) ) LOGGER.info("Sample CloudFormation module created at %s", 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_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', 'stacker', i), os.path.join(module_dir, i) ) os.mkdir(os.path.join(module_dir, 'tfstate_blueprints')) for i in ['__init__.py', 'tf_state.py']: shutil.copyfile( os.path.join(ROOT, 'templates', 'stacker', 'tfstate_blueprints', i), os.path.join(module_dir, 'tfstate_blueprints', i) ) os.chmod( # make blueprint executable os.path.join(module_dir, 'tfstate_blueprints', 'tf_state.py'), os.stat(os.path.join(module_dir, 'tfstate_blueprints', 'tf_state.py')).st_mode | 0o0111 ) LOGGER.info("Sample Stacker module created at %s", 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_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', 'terraform', i), os.path.join(module_dir, i), ) tf_ver_template = os.path.join(ROOT, 'templates', 'terraform', '.terraform-version') if os.path.isfile(tf_ver_template): shutil.copyfile( tf_ver_template, os.path.join(module_dir, '.terraform-version'), ) else: # running directly from git latest_tf_ver = get_latest_tf_version() with open(os.path.join(module_dir, '.terraform-version'), 'w') as stream: stream.write(latest_tf_ver) LOGGER.info("Sample Terraform app created at %s", 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 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_arguments['stacker']: generate_sample_stacker_module(self.env_root) elif self._cli_arguments['tf']: generate_sample_tf_module(self.env_root) elif self._cli_arguments['cdk-tsc']: generate_sample_cdk_tsc_module(self.env_root) elif self._cli_arguments['cdk-py']: generate_sample_cdk_py_module(self.env_root) elif self._cli_arguments['cdk-csharp']: generate_sample_cdk_cs_module(self.env_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 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: - us-east-1 """) print('runway.yml generated') print('See additional getting started information at ' 'https://docs.onica.com/projects/runway/en/latest/how_to_use.html')
<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.ZipFile(temp_file, 'r') zip_ref.extractall(output_dir) zip_ref.close() os.remove(temp_file) return output_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 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) with zipfile.ZipFile(temp_file, 'w', zipfile.ZIP_DEFLATED) as filehandle: with change_dir(app_dir): for dirname, _subdirs, files in os.walk('./'): if dirname != './': filehandle.write(dirname) for filename in files: filehandle.write(os.path.join(dirname, filename)) transfer.upload_file(temp_file, bucket, key) os.remove(temp_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 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'): build_output = os.path.join( options['path'], options['build_output'] ) else: build_output = options['path'] context_dict['artifact_bucket_name'] = RxrefLookup.handle( kwargs.get('artifact_bucket_rxref_lookup'), provider=provider, context=context ) if options.get('pre_build_steps'): run_commands(options['pre_build_steps'], options['path']) context_dict['hash'] = get_hash_of_files( root_path=options['path'], directories=options.get('source_hashing', {}).get('directories') ) # Now determine if the current staticsite has already been deployed if options.get('source_hashing', {}).get('enabled', True): context_dict['hash_tracking_parameter'] = options.get( 'source_hashing', {}).get('parameter', default_param_name) ssm_client = session.client('ssm') try: old_parameter_value = ssm_client.get_parameter( Name=context_dict['hash_tracking_parameter'] )['Parameter']['Value'] except ssm_client.exceptions.ParameterNotFound: old_parameter_value = None else: context_dict['hash_tracking_disabled'] = True old_parameter_value = None context_dict['current_archive_filename'] = ( context_dict['artifact_key_prefix'] + context_dict['hash'] + '.zip' ) if old_parameter_value: context_dict['old_archive_filename'] = ( context_dict['artifact_key_prefix'] + old_parameter_value + '.zip' ) if old_parameter_value == context_dict['hash']: LOGGER.info("staticsite: skipping build; app hash %s already deployed " "in this environment", context_dict['hash']) context_dict['deploy_is_current'] = True return context_dict if does_s3_object_exist(context_dict['artifact_bucket_name'], context_dict['current_archive_filename'], session): context_dict['app_directory'] = download_and_extract_to_mkdtemp( context_dict['artifact_bucket_name'], context_dict['current_archive_filename'], session ) else: if options.get('build_steps'): LOGGER.info('staticsite: executing build commands') run_commands(options['build_steps'], options['path']) zip_and_upload(build_output, context_dict['artifact_bucket_name'], context_dict['current_archive_filename'], session) context_dict['app_directory'] = build_output context_dict['deploy_is_current'] = False return context_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 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.options['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 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).replace('\'\'', '\'')
<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: # The nested app-through-npx-via-subprocess command invocation # requires this redundant quoting cmd_list = [NPX_BIN, '-c', "''%s %s''" % (command, ' '.join(command_opts))] else: LOGGER.debug('npx not found; falling back invoking %s shell script ' 'directly.', command) cmd_list = [ os.path.join(path, 'node_modules', '.bin', command) ] + command_opts 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 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 subprocess.call( [NPM_BIN, 'ci', '-h'], stdout=fnull, stderr=subprocess.STDOUT ) == 0): return True return False
<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('/') if region == env_vars['AWS_DEFAULT_REGION']: boto_args = extract_boto_args_from_env(env_vars) sts_client = boto3.client( 'sts', region_name=env_vars['AWS_DEFAULT_REGION'], **boto_args ) if sts_client.get_caller_identity()['Account'] == account_id: return True if isinstance(current_env_config, dict): return True return False
<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_access_key_id', 'aws_secret_access_key', 'aws_session_token']: if env_vars.get(i.upper()): boto_args[i] = env_vars[i.upper()] sts_client = boto3.client('sts', region_name=region, **boto_args) LOGGER.info("Assuming role %s...", role_arn) response = sts_client.assume_role(**assume_role_opts) return {'AWS_ACCESS_KEY_ID': response['Credentials']['AccessKeyId'], 'AWS_SECRET_ACCESS_KEY': response['Credentials']['SecretAccessKey'], # noqa 'AWS_SESSION_TOKEN': response['Credentials']['SessionToken']}
<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.Terraform' elif basename.endswith('.cdk'): class_path = 'runway.module.cdk.CloudDevelopmentKit' elif basename.endswith('.cfn'): class_path = 'runway.module.cloudformation.CloudFormation' if not class_path: # Fallback to autodetection if os.path.isfile(os.path.join(path, 'serverless.yml')): class_path = 'runway.module.serverless.Serverless' elif glob.glob(os.path.join(path, '*.tf')): class_path = 'runway.module.terraform.Terraform' elif os.path.isfile(os.path.join(path, 'cdk.json')) \ and os.path.isfile(os.path.join(path, 'package.json')): class_path = 'runway.module.cdk.CloudDevelopmentKit' elif glob.glob(os.path.join(path, '*.env')) or ( glob.glob(os.path.join(path, '*.yaml'))) or ( glob.glob(os.path.join(path, '*.yml'))): class_path = 'runway.module.cloudformation.CloudFormation' if not class_path: LOGGER.error('No module class found for %s', os.path.basename(path)) sys.exit(1) return load_object_from_string(class_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 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(stream)) return module_options
<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 response_iterator: current_account_aliases.extend(page.get('AccountAliases', [])) if account_alias in current_account_aliases: LOGGER.info('Verified current AWS account alias matches required ' 'alias %s.', account_alias) else: LOGGER.error('Current AWS account aliases "%s" do not match ' 'required account alias %s in Runway config.', ','.join(current_account_aliases), account_alias) 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 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 account %s does not match ' 'required account %s in Runway config.', resp['Account'], account_id) sys.exit(1) else: LOGGER.error('Error checking current account ID') 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 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, six.string_types)): account_id = str(deployment['account-id']) elif deployment.get('account-id', {}).get(context.env_name): account_id = str(deployment['account-id'][context.env_name]) else: account_id = None if account_id: validate_account_id(boto3.client('sts', **boto_args), account_id) if isinstance(deployment.get('account-alias'), six.string_types): account_alias = deployment['account-alias'] elif deployment.get('account-alias', {}).get(context.env_name): account_alias = deployment['account-alias'][context.env_name] else: account_alias = None if account_alias: validate_account_alias(boto3.client('iam', **boto_args), account_alias)
<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 " "the value (or unset it to fall back to the name of " "the current git branch or parent directory).") else: LOGGER.info("Environment \"%s\" was determined from the current " "git branch or parent directory.", env_name) LOGGER.info("If this is not the environment name, update the branch/folder name or " "set an override value via the %s environment variable", env_override_name) LOGGER.info("")
<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 user for deployments to run."""
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:') for i, deployment in enumerate(deployments): print(" %d: %s" % (i+1, _deployment_menu_entry(deployment))) print('') print('') if command == 'destroy': print('(Operating in destroy mode -- "all" will destroy all ' 'deployments in reverse order)') selected_deployment_index = input('Enter number of deployment to run (or "all"): ') if selected_deployment_index == 'all': return deployments if selected_deployment_index == '': LOGGER.error('Please select a valid number (or "all")') sys.exit(1) selected_deployment = deployments[int(selected_deployment_index) - 1] if selected_deployment.get('current_dir', False): deployments_to_run.append(selected_deployment) elif not selected_deployment.get('modules', []): LOGGER.error('No modules configured in selected deployment') sys.exit(1) elif len(selected_deployment['modules']) == 1: # No need to select a module in the deployment - there's only one if command == 'destroy': LOGGER.info('(only one deployment detected; all modules ' 'automatically selected for termination)') if not strtobool(input('Proceed?: ')): sys.exit(0) deployments_to_run.append(selected_deployment) else: modules = selected_deployment['modules'] print('') print('Configured modules in deployment \'%s\':' % selected_deployment.get('name')) for i, module in enumerate(modules): print(" %s: %s" % (i+1, _module_menu_entry(module, env_name))) print('') print('') if command == 'destroy': print('(Operating in destroy mode -- "all" will destroy all ' 'deployments in reverse order)') selected_module_index = input('Enter number of module to run (or "all"): ') if selected_module_index == 'all': deployments_to_run.append(selected_deployment) elif selected_module_index == '' or ( not selected_module_index.isdigit() or ( not 0 < int(selected_module_index) <= len(modules))): LOGGER.error('Please select a valid number (or "all")') sys.exit(1) else: selected_deployment['modules'] = [modules[int(selected_module_index) - 1]] deployments_to_run.append(selected_deployment) LOGGER.debug('Selected deployment is %s...', deployments_to_run) return deployments_to_run
<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 name only names.append( os.path.join('env', "%s.%s" % (stage, ext)) ) names.append("config-%s.%s" % (stage, ext)) return names
<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 ( re.search(r"Stack '.*' does not exist", stdoutdata))): sys.exit(sls_return)
<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 command != 'remove': sls_opts.append('--conceal') # Hide secrets from serverless output if 'DEBUG' in self.context.env_vars: sls_opts.append('-v') # Increase logging if requested warn_on_boto_env_vars(self.context.env_vars) sls_opts.extend(['-r', self.context.env_region]) sls_opts.extend(['--stage', self.context.env_name]) sls_env_file = get_sls_config_file(self.path, self.context.env_name, self.context.env_region) sls_cmd = generate_node_command(command='sls', command_opts=sls_opts, path=self.path) if (not self.options.get('environments') and os.path.isfile(os.path.join(self.path, sls_env_file))) or ( # noqa pylint: disable=line-too-long self.options.get('environments', {}).get(self.context.env_name)): # noqa if os.path.isfile(os.path.join(self.path, 'package.json')): with change_dir(self.path): run_npm_install(self.path, self.options, self.context) LOGGER.info("Running sls %s on %s (\"%s\")", command, os.path.basename(self.path), format_npm_command_for_logging(sls_cmd)) if command == 'remove': # Need to account for exit code 1 on any removals after # the first run_sls_remove(sls_cmd, self.context.env_vars) else: run_module_command(cmd_list=sls_cmd, env_vars=self.context.env_vars) else: LOGGER.warning( "Skipping serverless %s of %s; no \"package.json\" " "file was found (need a package file specifying " "serverless in devDependencies)", command, os.path.basename(self.path)) else: response['skipped_configs'] = True LOGGER.info( "Skipping serverless %s of %s; no config file for " "this stage/region found (looking for one of \"%s\")", command, os.path.basename(self.path), ', '.join(gen_sls_config_files(self.context.env_name, self.context.env_region))) 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 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: raise RuntimeError('AWS CLI exited with code {}'.format(exit_code)) finally: os.environ.clear() os.environ.update(old_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_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 return [i['Key'] for i in archives[:-15] if i['Key'] not in files_to_skip]
<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('staticsite: skipping upload; latest version already ' 'deployed') else: distribution_id = OutputLookup.handle( kwargs.get('distributionid_output_lookup'), provider=provider, context=context ) distribution_domain = OutputLookup.handle( kwargs.get('distributiondomain_output_lookup'), provider=provider, context=context ) # Using the awscli for s3 syncing is incredibly suboptimal, but on # balance it's probably the most stable/efficient option for syncing # the files until https://github.com/boto/boto3/issues/358 is resolved aws_cli(['s3', 'sync', context.hook_data['staticsite']['app_directory'], "s3://%s/" % bucket_name, '--delete']) cf_client = session.client('cloudfront') cf_client.create_invalidation( DistributionId=distribution_id, InvalidationBatch={'Paths': {'Quantity': 1, 'Items': ['/*']}, 'CallerReference': str(time.time())} ) LOGGER.info("staticsite: sync & CF invalidation of %s (domain %s) " "complete", distribution_id, distribution_domain) if not context.hook_data['staticsite'].get('hash_tracking_disabled'): LOGGER.info("staticsite: updating environment SSM parameter %s " "with hash %s", context.hook_data['staticsite']['hash_tracking_parameter'], # noqa context.hook_data['staticsite']['hash']) ssm_client = session.client('ssm') ssm_client.put_parameter( Name=context.hook_data['staticsite']['hash_tracking_parameter'], # noqa Description='Hash of currently deployed static website source', Value=context.hook_data['staticsite']['hash'], Type='String', Overwrite=True ) LOGGER.info("staticsite: cleaning up old site archives...") archives = [] s3_client = session.client('s3') list_objects_v2_paginator = s3_client.get_paginator('list_objects_v2') response_iterator = list_objects_v2_paginator.paginate( Bucket=context.hook_data['staticsite']['artifact_bucket_name'], Prefix=context.hook_data['staticsite']['artifact_key_prefix'] ) for page in response_iterator: archives.extend(page.get('Contents', [])) archives_to_prune = get_archives_to_prune( archives, context.hook_data['staticsite'] ) # Iterate in chunks of 1000 to match delete_objects limit for objects in [archives_to_prune[i:i + 1000] for i in range(0, len(archives_to_prune), 1000)]: s3_client.delete_objects( Bucket=context.hook_data['staticsite']['artifact_bucket_name'], Delete={'Objects': [{'Key': i} for i in objects]} ) 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 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 CloudFormation template, ' 'but is located in the top level of a module ' 'alongside the CloudFormation config files (i.e. ' 'the file or files indicating the stack names & ' 'parameters). Please move the template to a ' 'subdirectory.', config_filename) 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 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, with the following changes: * Adding our explicit arguments to parse_args (instead of leaving it empty) * Overriding sys.argv * Adding embedded runway lib directory to sys.path """
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_path}');" "from stacker.logger import setup_logging;" "from stacker.commands import Stacker;" "stacker = Stacker(setup_logging=setup_logging);" "args = stacker.parse_args({args});" "stacker.configure(args);args.run(args)".format(args=str(args), lib_path=lib_path))