Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the following code snippet before the placeholder: <|code_start|> SKIP_UPDATE_REFERENCES = True
def run(self, stack_context):
# stack contexts
session = stack_context.session
parameters = stack_context.parameters
metadata = stack_context.metadata
self.ppt.pprint_stack_name(stack_context.stack_key,
parameters['StackName'])
# shortcut since dry run is already handled in cli package
if self.options.dry_run:
return
# metadata and parameters only get printed when verbosity>0
self.ppt.pprint_metadata(metadata)
self.ppt.pprint_parameters(parameters)
cfn = session.resource('cloudformation')
stack = cfn.Stack(parameters['StackName'])
try:
stack.stack_status
except botocore.exceptions.ClientError as ex:
if is_stack_does_not_exist_exception(ex):
# make a "dummy" stack object so prettyprint is happy
stack = dummy_stack(parameters['StackName'], 'STACK_NOT_FOUND')
self.ppt.pprint_stack(stack, status=True)
return
else:
<|code_end|>
, predict the next line using imports from the current file:
from collections import namedtuple
from .command import Command
from .utils import is_stack_does_not_exist_exception
import botocore.exceptions
and context including class names, function names, and sometimes code from other files:
# Path: awscfncli2/runner/commands/command.py
# class Command(object):
# SKIP_UPDATE_REFERENCES = False
#
# def __init__(self, pretty_printer, options):
# assert isinstance(pretty_printer, StackPrettyPrinter)
# self.ppt = pretty_printer
# self.options = options
#
# def run(self, stack_context):
# raise NotImplementedError
#
# Path: awscfncli2/runner/commands/utils.py
# def is_stack_does_not_exist_exception(ex):
# """Check whether given exception is "stack does not exist",
# botocore doesn't throw a distinct exception class in this case.
# """
# if isinstance(ex, botocore.exceptions.ClientError):
# error = ex.response.get('Error', {})
# error_message = error.get('Message', 'Unknown')
# return error_message.endswith('does not exist')
# else:
# return False
. Output only the next line. | raise |
Next line prediction: <|code_start|>
@click.command('status')
@click.option('--dry-run', '-d', is_flag=True, default=False,
help='Don\'t retrieve stack deployment status (faster).')
@click.option('--stack-resources', '-r', is_flag=True, default=False,
help='Display stack resources.')
@click.option('--stack-exports', '-e', is_flag=True, default=False,
help='Display stack exports.')
@click.pass_context
@command_exception_handler
def cli(ctx, dry_run, stack_resources, stack_exports):
"""Print stack status and resources.
Also includes parameters, resources, outputs & exports."""
# shortcut if we only print stack key (and names)
if dry_run:
for context in ctx.obj.runner.contexts:
ctx.obj.ppt.secho(context.stack_key, bold=True)
return
options = StackStatusOptions(
<|code_end|>
. Use current file imports:
(import click
from awscfncli2.cli.utils.deco import command_exception_handler
from awscfncli2.runner.commands.stack_status_command import StackStatusOptions, StackStatusCommand)
and context including class names, function names, or small code snippets from other files:
# Path: awscfncli2/cli/utils/deco.py
# def command_exception_handler(f):
# """Capture and pretty print exceptions."""
#
# @wraps(f)
# def wrapper(ctx, *args, **kwargs):
# try:
# return f(ctx, *args, **kwargs)
# except (botocore.exceptions.ClientError,
# botocore.exceptions.BotoCoreError,
# ) as e:
# if ctx.obj.verbosity > 0:
# click.secho(traceback.format_exc(), fg='red')
# else:
# click.secho(str(e), fg='red')
# raise click.Abort
# except ConfigError as e:
# click.secho(str(e), fg='red')
# if ctx.obj.verbosity > 0:
# traceback.print_exc()
# raise click.Abort
#
# return wrapper
#
# Path: awscfncli2/runner/commands/stack_status_command.py
# class StackStatusOptions(namedtuple('StackStatusOptions',
# ['dry_run', 'stack_resources',
# 'stack_exports'])):
# pass
#
# class StackStatusCommand(Command):
# SKIP_UPDATE_REFERENCES = True
#
# def run(self, stack_context):
# # stack contexts
# session = stack_context.session
# parameters = stack_context.parameters
# metadata = stack_context.metadata
#
# self.ppt.pprint_stack_name(stack_context.stack_key,
# parameters['StackName'])
# # shortcut since dry run is already handled in cli package
# if self.options.dry_run:
# return
#
# # metadata and parameters only get printed when verbosity>0
# self.ppt.pprint_metadata(metadata)
# self.ppt.pprint_parameters(parameters)
#
# cfn = session.resource('cloudformation')
# stack = cfn.Stack(parameters['StackName'])
#
# try:
# stack.stack_status
# except botocore.exceptions.ClientError as ex:
# if is_stack_does_not_exist_exception(ex):
# # make a "dummy" stack object so prettyprint is happy
# stack = dummy_stack(parameters['StackName'], 'STACK_NOT_FOUND')
# self.ppt.pprint_stack(stack, status=True)
# return
# else:
# raise
#
# self.ppt.pprint_stack(stack, status=True)
#
# if self.options.stack_resources:
# self.ppt.pprint_stack_resources(stack)
#
# if self.options.stack_exports:
# self.ppt.pprint_stack_parameters(stack)
# self.ppt.pprint_stack_exports(stack, session)
# client = session.client('cloudformation')
. Output only the next line. | dry_run=dry_run, |
Given the following code snippet before the placeholder: <|code_start|>
@click.command('status')
@click.option('--dry-run', '-d', is_flag=True, default=False,
help='Don\'t retrieve stack deployment status (faster).')
@click.option('--stack-resources', '-r', is_flag=True, default=False,
help='Display stack resources.')
@click.option('--stack-exports', '-e', is_flag=True, default=False,
help='Display stack exports.')
@click.pass_context
@command_exception_handler
def cli(ctx, dry_run, stack_resources, stack_exports):
"""Print stack status and resources.
Also includes parameters, resources, outputs & exports."""
# shortcut if we only print stack key (and names)
if dry_run:
for context in ctx.obj.runner.contexts:
ctx.obj.ppt.secho(context.stack_key, bold=True)
return
options = StackStatusOptions(
dry_run=dry_run,
stack_resources=stack_resources,
stack_exports=stack_exports,
)
command = StackStatusCommand(
<|code_end|>
, predict the next line using imports from the current file:
import click
from awscfncli2.cli.utils.deco import command_exception_handler
from awscfncli2.runner.commands.stack_status_command import StackStatusOptions, StackStatusCommand
and context including class names, function names, and sometimes code from other files:
# Path: awscfncli2/cli/utils/deco.py
# def command_exception_handler(f):
# """Capture and pretty print exceptions."""
#
# @wraps(f)
# def wrapper(ctx, *args, **kwargs):
# try:
# return f(ctx, *args, **kwargs)
# except (botocore.exceptions.ClientError,
# botocore.exceptions.BotoCoreError,
# ) as e:
# if ctx.obj.verbosity > 0:
# click.secho(traceback.format_exc(), fg='red')
# else:
# click.secho(str(e), fg='red')
# raise click.Abort
# except ConfigError as e:
# click.secho(str(e), fg='red')
# if ctx.obj.verbosity > 0:
# traceback.print_exc()
# raise click.Abort
#
# return wrapper
#
# Path: awscfncli2/runner/commands/stack_status_command.py
# class StackStatusOptions(namedtuple('StackStatusOptions',
# ['dry_run', 'stack_resources',
# 'stack_exports'])):
# pass
#
# class StackStatusCommand(Command):
# SKIP_UPDATE_REFERENCES = True
#
# def run(self, stack_context):
# # stack contexts
# session = stack_context.session
# parameters = stack_context.parameters
# metadata = stack_context.metadata
#
# self.ppt.pprint_stack_name(stack_context.stack_key,
# parameters['StackName'])
# # shortcut since dry run is already handled in cli package
# if self.options.dry_run:
# return
#
# # metadata and parameters only get printed when verbosity>0
# self.ppt.pprint_metadata(metadata)
# self.ppt.pprint_parameters(parameters)
#
# cfn = session.resource('cloudformation')
# stack = cfn.Stack(parameters['StackName'])
#
# try:
# stack.stack_status
# except botocore.exceptions.ClientError as ex:
# if is_stack_does_not_exist_exception(ex):
# # make a "dummy" stack object so prettyprint is happy
# stack = dummy_stack(parameters['StackName'], 'STACK_NOT_FOUND')
# self.ppt.pprint_stack(stack, status=True)
# return
# else:
# raise
#
# self.ppt.pprint_stack(stack, status=True)
#
# if self.options.stack_resources:
# self.ppt.pprint_stack_resources(stack)
#
# if self.options.stack_exports:
# self.ppt.pprint_stack_parameters(stack)
# self.ppt.pprint_stack_exports(stack, session)
# client = session.client('cloudformation')
. Output only the next line. | pretty_printer=ctx.obj.ppt, |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
class Boto3RunBook(RunBook):
def __init__(self, profile, artifact_store, manager, selector, pretty_printer):
RunBook.__init__(self)
self._profile = profile
self._artifact_store = artifact_store
self._manager = manager
self._selector = selector
self._ppt = pretty_printer
selected_deployments = self._manager.query_stacks(
self._selector.stage_pattern,
self._selector.stack_pattern)
selected_stack_keys = list(
d.stack_key.qualified_name for d in selected_deployments)
if len(selected_deployments) == 0:
self._ppt.secho('No stack matches specified pattern.', fg='red')
<|code_end|>
, predict the immediate next line with the help of imports:
import sys
from .boto3_context import Boto3DeploymentContext
from .boto3_outputs import Boto3OutputStore
from .base import RunBook
and context (classes, functions, sometimes code) from other files:
# Path: awscfncli2/runner/runbook/boto3_context.py
# class Boto3DeploymentContext(StackDeploymentContext):
# def __init__(self, profile, artifact_store, deployment, pretty_printer):
# self._boto3_profile = Boto3Profile(
# profile_name=deployment.profile.Profile,
# region_name=deployment.profile.Region
# )
# self._boto3_profile.update(profile)
# self._session = None
# self._session_lock = threading.Lock()
#
# self._deployment = deployment
#
# self._stack_key = deployment.stack_key.qualified_name
# self._metadata = deployment.metadata._asdict()
# self._parameters = deployment.parameters._asdict()
#
# self._artifact_store = artifact_store
# self._ppt = pretty_printer
#
# @property
# def stack_key(self):
# return self._stack_key
#
# @property
# def session(self):
# with self._session_lock:
# if self._session is None:
# self._session = self._boto3_profile.get_boto3_session()
# return self._session
#
# @property
# def metadata(self):
# return self._metadata
#
# @property
# def parameters(self):
# return self._parameters
#
# def get_parameters_reference(self):
# return self._deployment.parameters.find_references()
#
# def update_parameters_reference(self, **outputs):
# self._parameters = self._deployment.parameters.substitute_references(**outputs)
#
# def make_boto3_parameters(self):
# self._parameters = make_boto3_parameters(
# self._parameters, self.metadata['Package'])
#
# def run_packaging(self):
# """Package templates and resources and upload to artifact bucket"""
# package = self.metadata["Package"]
#
# if not package:
# return
#
# template_path = self.parameters.get('TemplateURL', None)
#
# if not os.path.exists(template_path):
# raise ConfigError(
# "Can'not find %s. Package is supported for local template only" %
# (template_path))
#
# artifact_store = self._artifact_store if self._artifact_store else \
# self.metadata["ArtifactStore"]
#
# template_body, template_url = package_template(
# self._ppt,
# self.session,
# template_path,
# bucket_region=self.session.region_name,
# bucket_name=artifact_store,
# prefix=self.parameters['StackName']
# )
#
# if template_url is not None:
# # packaged template is too large, use S3 pre-signed url
# self.parameters['TemplateURL'] = template_url
# else:
# # packaged template is passed with request body
# self.parameters['TemplateBody'] = template_body
# self.parameters.pop('TemplateURL')
#
# Path: awscfncli2/runner/runbook/boto3_outputs.py
# class Boto3OutputStore(object):
# def __init__(self, contexts, pretty_printer):
# self._contexts = contexts
# self._outputs = dict()
# self._ppt = pretty_printer
#
# def collect_stack_outputs(self, *attributes):
# for attribute in attributes:
# try:
# qualified_name, attribute_name = attribute.rsplit('.', 1)
# except Exception as e:
# self._ppt.secho(
# 'Invalid Config Reference %s' % attribute,
# color='yellow')
# raise e
#
# for context in self._contexts:
# if context.stack_key != qualified_name:
# continue
#
# try:
# cfn = context.session.resource('cloudformation')
#
# stack_name = context.parameters['StackName']
# stack = cfn.Stack(stack_name)
#
# stack.load()
# status = stack.stack_status
# if status not in (
# 'CREATE_COMPLETE',
# 'ROLLBACK_COMPLETE',
# 'UPDATE_COMPLETE',
# 'UPDATE_ROLLBACK_COMPLETE'):
# continue
# except Exception as e:
# self._ppt.secho(
# 'Collect Outputs: Unable to access outputs from %s' % qualified_name,
# color='yellow')
# raise e
#
# if stack.outputs:
# outputs = dict(
# map(lambda o: (
# '.'.join((context.stack_key, o['OutputKey'])),
# o['OutputValue']),
# stack.outputs))
# if attribute not in outputs:
# raise RuntimeError('Collect Outputs: Attribute %s not found' % attribute)
#
# self._ppt.secho(
# 'Collected outputs from %s' % qualified_name, color='yellow')
# self._outputs.update(outputs)
#
# def get_outputs(self):
# return self._outputs
#
# Path: awscfncli2/runner/runbook/base.py
# class RunBook:
# def __init__(self):
# self._contexts = list()
#
# @property
# def contexts(self):
# return self._contexts
#
# def pre_run(self, command, context):
# pass
#
# def post_run(self, command, context):
# pass
#
# def run(self, command, rev=False):
# if rev:
# stack_contexts = reversed(self.contexts)
# else:
# stack_contexts = self.contexts
#
# for context in stack_contexts:
# self.pre_run(command, context)
# command.run(context)
# self.post_run(command, context)
. Output only the next line. | self._ppt.secho('Available stacks are:') |
Given snippet: <|code_start|>
def test_main():
cli_runner = click.testing.CliRunner()
with cli_runner.isolated_filesystem():
# by default, print help when invoked with no options
result = cli_runner.invoke(cli)
assert result.exit_code == 0
assert "AWS CloudFormation CLI" in result.output
# Generate a sample config
cli_runner.invoke(cli, "generate")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import click.testing
from unittest.mock import patch
from awscfncli2.cli.main import cli
from awscfncli2.cli.context import Context
and context:
# Path: awscfncli2/cli/main.py
# @click.command(cls=MultiCommand)
# @click.version_option(version=__version__)
# @click.option('--install-completion', is_flag=True, callback=install_callback,
# expose_value=False,
# help='Automatically install completion for the current shell. Make sure '
# 'to have psutil installed.')
# @click.option('-f', '--file',
# type=click.Path(exists=False, dir_okay=True),
# default=None,
# help='Specify an alternate stack configuration file, default is '
# 'cfn-cli.yml.')
# @click.option('-s', '--stack', autocompletion=stack_auto_complete,
# type=click.STRING, default='*',
# help='Select stacks to operate on, defined by STAGE_NAME.STACK_NAME, '
# 'nix glob is supported to select multiple stacks. Default value is '
# '"*", which means all stacks in all stages.')
# @click.option('-p', '--profile', autocompletion=profile_auto_complete,
# type=click.STRING, default=None,
# help='Override AWS profile specified in the config file. Warning: '
# 'Don\'t use this option on stacks in different accounts.')
# @click.option('-r', '--region',
# type=click.STRING, default=None,
# help='Override AWS region specified in the config. Warning: Don\'t use '
# 'this option on stacks in different regions.')
# @click.option('-a', '--artifact-store',
# type=click.STRING, default='',
# help='Override artifact store specified in the config. Artifact store is'
# 'the s3 bucket used to store packaged template resource. Warning: '
# 'Don\'t use this option on stacks in different accounts & regions.')
# @click.option('-v', '--verbose', count=True,
# help='Be more verbose, can be specified multiple times.')
# @click.pass_context
# def cli(ctx, file, stack, profile, region, artifact_store, verbose):
# """AWS CloudFormation CLI - The missing CLI for CloudFormation.
#
# Quickstart: use `cfn-cli generate` to generate a new project.
#
# cfn-cli operates on a single YAML based config file and can manages stacks
# across regions & accounts. By default, cfn-cli will try to locate config file
# cfn-cli.yml in current directory, override this using -f option:
#
# \b
# cfn-cli -f some-other-config-file.yaml <command>
#
# If the config contains multiple stacks, they can be can be selected using
# full qualified stack name:
#
# \b
# cfn-cli -s StageName.StackName <command>
#
# Unix style globs is also supported when selecting stacks to operate on:
# \b
# cfn-cli -s Backend.* <command>
#
# By default, command operates on all stacks in every stages, with order specified
# in the config file.
#
# Options can also be specified using environment variables:
#
# \b
# CFN_STACK=StageName.StackName cfn-cli <command>
# """
#
# # Setup global logging level
# if verbose >= 2: verbose = 2 # cap at 2
#
# logger = logging.getLogger()
# logger.setLevel(VERBOSITY_LOGLEVEL_MAPPING[verbose])
#
# # Build context from command options
# options = Options(
# config_filename=file,
# stack_selector=stack,
# profile_name=profile,
# region_name=region,
# artifact_store=artifact_store,
# verbosity=verbose,
# )
# context: Context = CONTEXT_BUILDER(options).build()
#
# # Assign context object
# ctx.obj = context
#
# Path: awscfncli2/cli/context.py
# class Context:
# """Click context object
#
#
# # Manage config parsing, transforming deployment process.
# """
#
# def __init__(self,
# config_filename: str,
# artifact_store: str,
# pretty_printer: StackPrettyPrinter,
# stack_selector: StackSelector,
# boto3_profile: Boto3Profile,
# builder,
# ):
# # simple
# self._config_filename: str = config_filename
# self._artifact_store: str = artifact_store
# # complex
# self._pretty_printer: StackPrettyPrinter = pretty_printer
# self._stack_selector = stack_selector
# self._boto3_profile = boto3_profile
# # lazy-loaded
# self._deployments = None
# self._command_runner = None
#
# # internals
# self.__builder = builder
# self.__lock = threading.RLock()
#
# @property
# def config_filename(self):
# """Config file name"""
# return self._config_filename
#
# @property
# def stack_selector(self):
# """Stack selector"""
# return self._stack_selector
#
# @property
# def boto3_profile(self):
# """Boto3 session profiles"""
# return self._boto3_profile
#
# @property
# def verbosity(self):
# """Verbosity level"""
# return self._pretty_printer.verbosity
#
# @property
# def ppt(self):
# """CLI pretty printer"""
# return self._pretty_printer
#
# @property
# def deployments(self):
# """Stack deployment spec."""
# # XXX: Lazy-loading so we don't get error if user is just looking at help
# with self.__lock:
# if self._deployments is None:
# self._deployments = self.__builder.parse_config(self.config_filename)
# return self._deployments
#
# @property
# def runner(self):
# """Command runner."""
# with self.__lock:
# if self._command_runner is None:
# self._command_runner = self.__builder.build_runner(
# self.boto3_profile,
# self._artifact_store,
# self.deployments,
# self.stack_selector,
# self.ppt
# )
# return self._command_runner
which might include code, classes, or functions. Output only the next line. | assert os.path.exists("cfn-cli.yaml") |
Using the snippet: <|code_start|>
class StackDeleteOptions(namedtuple('StackDeleteOptions',
['no_wait',
'ignore_missing'])):
pass
class StackDeleteCommand(Command):
SKIP_UPDATE_REFERENCES = True
def run(self, stack_context):
# stack contexts
session = stack_context.session
parameters = stack_context.parameters
metadata = stack_context.metadata
self.ppt.pprint_stack_name(stack_context.stack_key,
<|code_end|>
, determine the next line of code. You have imports:
from collections import namedtuple
from .command import Command
from .utils import update_termination_protection, \
is_stack_does_not_exist_exception
and context (class names, function names, or code) available:
# Path: awscfncli2/runner/commands/command.py
# class Command(object):
# SKIP_UPDATE_REFERENCES = False
#
# def __init__(self, pretty_printer, options):
# assert isinstance(pretty_printer, StackPrettyPrinter)
# self.ppt = pretty_printer
# self.options = options
#
# def run(self, stack_context):
# raise NotImplementedError
#
# Path: awscfncli2/runner/commands/utils.py
# def update_termination_protection(session,
# termination_protection,
# stack_name,
# ppt):
# """Update termination protection on a stack"""
#
# if termination_protection is None:
# # don't care, don't change
# return
#
# client = session.client('cloudformation')
#
# if termination_protection:
# ppt.secho('Enabling TerminationProtection')
# else:
# ppt.secho('Disabling TerminationProtection', fg='red')
#
# client.update_termination_protection(
# StackName=stack_name,
# EnableTerminationProtection=termination_protection)
#
# def is_stack_does_not_exist_exception(ex):
# """Check whether given exception is "stack does not exist",
# botocore doesn't throw a distinct exception class in this case.
# """
# if isinstance(ex, botocore.exceptions.ClientError):
# error = ex.response.get('Error', {})
# error_message = error.get('Message', 'Unknown')
# return error_message.endswith('does not exist')
# else:
# return False
. Output only the next line. | parameters['StackName'], |
Next line prediction: <|code_start|>
class StackDeleteOptions(namedtuple('StackDeleteOptions',
['no_wait',
'ignore_missing'])):
pass
class StackDeleteCommand(Command):
SKIP_UPDATE_REFERENCES = True
def run(self, stack_context):
# stack contexts
session = stack_context.session
parameters = stack_context.parameters
metadata = stack_context.metadata
self.ppt.pprint_stack_name(stack_context.stack_key,
<|code_end|>
. Use current file imports:
(from collections import namedtuple
from .command import Command
from .utils import update_termination_protection, \
is_stack_does_not_exist_exception)
and context including class names, function names, or small code snippets from other files:
# Path: awscfncli2/runner/commands/command.py
# class Command(object):
# SKIP_UPDATE_REFERENCES = False
#
# def __init__(self, pretty_printer, options):
# assert isinstance(pretty_printer, StackPrettyPrinter)
# self.ppt = pretty_printer
# self.options = options
#
# def run(self, stack_context):
# raise NotImplementedError
#
# Path: awscfncli2/runner/commands/utils.py
# def update_termination_protection(session,
# termination_protection,
# stack_name,
# ppt):
# """Update termination protection on a stack"""
#
# if termination_protection is None:
# # don't care, don't change
# return
#
# client = session.client('cloudformation')
#
# if termination_protection:
# ppt.secho('Enabling TerminationProtection')
# else:
# ppt.secho('Disabling TerminationProtection', fg='red')
#
# client.update_termination_protection(
# StackName=stack_name,
# EnableTerminationProtection=termination_protection)
#
# def is_stack_does_not_exist_exception(ex):
# """Check whether given exception is "stack does not exist",
# botocore doesn't throw a distinct exception class in this case.
# """
# if isinstance(ex, botocore.exceptions.ClientError):
# error = ex.response.get('Error', {})
# error_message = error.get('Message', 'Unknown')
# return error_message.endswith('does not exist')
# else:
# return False
. Output only the next line. | parameters['StackName'], |
Given the following code snippet before the placeholder: <|code_start|> # stack contexts
session = stack_context.session
parameters = stack_context.parameters
metadata = stack_context.metadata
self.ppt.pprint_stack_name(stack_context.stack_key,
parameters['StackName'],
'Deleting stack ')
# create boto3 cfn resource
cfn = session.resource('cloudformation')
self.ppt.pprint_session(session)
self.ppt.pprint_parameters(parameters)
# call boto3
stack = cfn.Stack(parameters['StackName'])
try:
update_termination_protection(
session,
parameters.pop('EnableTerminationProtection', None),
parameters['StackName'],
self.ppt)
self.ppt.pprint_stack(stack)
stack.delete()
except Exception as ex:
if self.options.ignore_missing and \
is_stack_does_not_exist_exception(ex):
self.ppt.secho(str(ex), fg='red')
return
else:
<|code_end|>
, predict the next line using imports from the current file:
from collections import namedtuple
from .command import Command
from .utils import update_termination_protection, \
is_stack_does_not_exist_exception
and context including class names, function names, and sometimes code from other files:
# Path: awscfncli2/runner/commands/command.py
# class Command(object):
# SKIP_UPDATE_REFERENCES = False
#
# def __init__(self, pretty_printer, options):
# assert isinstance(pretty_printer, StackPrettyPrinter)
# self.ppt = pretty_printer
# self.options = options
#
# def run(self, stack_context):
# raise NotImplementedError
#
# Path: awscfncli2/runner/commands/utils.py
# def update_termination_protection(session,
# termination_protection,
# stack_name,
# ppt):
# """Update termination protection on a stack"""
#
# if termination_protection is None:
# # don't care, don't change
# return
#
# client = session.client('cloudformation')
#
# if termination_protection:
# ppt.secho('Enabling TerminationProtection')
# else:
# ppt.secho('Disabling TerminationProtection', fg='red')
#
# client.update_termination_protection(
# StackName=stack_name,
# EnableTerminationProtection=termination_protection)
#
# def is_stack_does_not_exist_exception(ex):
# """Check whether given exception is "stack does not exist",
# botocore doesn't throw a distinct exception class in this case.
# """
# if isinstance(ex, botocore.exceptions.ClientError):
# error = ex.response.get('Error', {})
# error_message = error.get('Message', 'Unknown')
# return error_message.endswith('does not exist')
# else:
# return False
. Output only the next line. | raise |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
def _extends(base, **kwargs):
for k, v in base.items():
base[k] = kwargs.get(k, v)
class StackDefaults(object):
STACK_KEY = dict(
<|code_end|>
, determine the next line of code. You have imports:
import fnmatch
import copy
from collections import namedtuple
from .template import find_references, substitute_references
and context (class names, function names, or code) available:
# Path: awscfncli2/config/template.py
# def find_references(params):
# dumps = json.dumps(params)
# references = []
# for match in _Template.pattern.findall(dumps):
# if match and match[2]:
# references.append(match[2])
# return references
#
# def substitute_references(params, **kwargs):
# dumps = json.dumps(params)
# return json.loads(_Template(dumps).safe_substitute(**kwargs))
. Output only the next line. | StageKey=None, |
Next line prediction: <|code_start|>
def run(self, stack_context):
# stack contexts
session = stack_context.session
parameters = stack_context.parameters
metadata = stack_context.metadata
# print qualified name
self.ppt.pprint_stack_name(stack_context.stack_key,
parameters['StackName'],
'Deploying stack ')
# create boto3 cfn resource
cfn = session.resource('cloudformation')
self.ppt.pprint_session(session)
# packaging if necessary
stack_context.run_packaging()
# overwrite using cli parameters
if self.options.on_failure is not None:
parameters['OnFailure'] = self.options.on_failure
if self.options.disable_rollback:
parameters['DisableRollback'] = self.options.disable_rollback
if self.options.timeout_in_minutes:
parameters['TimeoutInMinutes'] = self.options.timeout_in_minutes
self.ppt.pprint_parameters(parameters)
# calling boto3...
<|code_end|>
. Use current file imports:
(import uuid
from collections import namedtuple
from .command import Command
from .utils import is_stack_already_exists_exception)
and context including class names, function names, or small code snippets from other files:
# Path: awscfncli2/runner/commands/command.py
# class Command(object):
# SKIP_UPDATE_REFERENCES = False
#
# def __init__(self, pretty_printer, options):
# assert isinstance(pretty_printer, StackPrettyPrinter)
# self.ppt = pretty_printer
# self.options = options
#
# def run(self, stack_context):
# raise NotImplementedError
#
# Path: awscfncli2/runner/commands/utils.py
# def is_stack_already_exists_exception(ex):
# """Check whether given exception is "stack already exist"
# Exception class is dynamiclly generated in botocore.
# """
# return ex.__class__.__name__ == 'AlreadyExistsException'
. Output only the next line. | try: |
Continue the code snippet: <|code_start|>
class StackDeployOptions(
namedtuple('StackDeployOptions',
[
'no_wait',
'on_failure',
'disable_rollback',
'timeout_in_minutes',
'ignore_existing'
])):
pass
class StackDeployCommand(Command):
def run(self, stack_context):
# stack contexts
<|code_end|>
. Use current file imports:
import uuid
from collections import namedtuple
from .command import Command
from .utils import is_stack_already_exists_exception
and context (classes, functions, or code) from other files:
# Path: awscfncli2/runner/commands/command.py
# class Command(object):
# SKIP_UPDATE_REFERENCES = False
#
# def __init__(self, pretty_printer, options):
# assert isinstance(pretty_printer, StackPrettyPrinter)
# self.ppt = pretty_printer
# self.options = options
#
# def run(self, stack_context):
# raise NotImplementedError
#
# Path: awscfncli2/runner/commands/utils.py
# def is_stack_already_exists_exception(ex):
# """Check whether given exception is "stack already exist"
# Exception class is dynamiclly generated in botocore.
# """
# return ex.__class__.__name__ == 'AlreadyExistsException'
. Output only the next line. | session = stack_context.session |
Given the following code snippet before the placeholder: <|code_start|>
@click.command('validate')
@click.pass_context
@command_exception_handler
<|code_end|>
, predict the next line using imports from the current file:
import click
from awscfncli2.cli.context import Context
from awscfncli2.cli.utils.deco import command_exception_handler
from awscfncli2.cli.utils.pprint import echo_pair_if_exists
and context including class names, function names, and sometimes code from other files:
# Path: awscfncli2/cli/context.py
# class Context:
# """Click context object
#
#
# # Manage config parsing, transforming deployment process.
# """
#
# def __init__(self,
# config_filename: str,
# artifact_store: str,
# pretty_printer: StackPrettyPrinter,
# stack_selector: StackSelector,
# boto3_profile: Boto3Profile,
# builder,
# ):
# # simple
# self._config_filename: str = config_filename
# self._artifact_store: str = artifact_store
# # complex
# self._pretty_printer: StackPrettyPrinter = pretty_printer
# self._stack_selector = stack_selector
# self._boto3_profile = boto3_profile
# # lazy-loaded
# self._deployments = None
# self._command_runner = None
#
# # internals
# self.__builder = builder
# self.__lock = threading.RLock()
#
# @property
# def config_filename(self):
# """Config file name"""
# return self._config_filename
#
# @property
# def stack_selector(self):
# """Stack selector"""
# return self._stack_selector
#
# @property
# def boto3_profile(self):
# """Boto3 session profiles"""
# return self._boto3_profile
#
# @property
# def verbosity(self):
# """Verbosity level"""
# return self._pretty_printer.verbosity
#
# @property
# def ppt(self):
# """CLI pretty printer"""
# return self._pretty_printer
#
# @property
# def deployments(self):
# """Stack deployment spec."""
# # XXX: Lazy-loading so we don't get error if user is just looking at help
# with self.__lock:
# if self._deployments is None:
# self._deployments = self.__builder.parse_config(self.config_filename)
# return self._deployments
#
# @property
# def runner(self):
# """Command runner."""
# with self.__lock:
# if self._command_runner is None:
# self._command_runner = self.__builder.build_runner(
# self.boto3_profile,
# self._artifact_store,
# self.deployments,
# self.stack_selector,
# self.ppt
# )
# return self._command_runner
#
# Path: awscfncli2/cli/utils/deco.py
# def command_exception_handler(f):
# """Capture and pretty print exceptions."""
#
# @wraps(f)
# def wrapper(ctx, *args, **kwargs):
# try:
# return f(ctx, *args, **kwargs)
# except (botocore.exceptions.ClientError,
# botocore.exceptions.BotoCoreError,
# ) as e:
# if ctx.obj.verbosity > 0:
# click.secho(traceback.format_exc(), fg='red')
# else:
# click.secho(str(e), fg='red')
# raise click.Abort
# except ConfigError as e:
# click.secho(str(e), fg='red')
# if ctx.obj.verbosity > 0:
# traceback.print_exc()
# raise click.Abort
#
# return wrapper
#
# Path: awscfncli2/cli/utils/pprint.py
# def echo_pair_if_exists(data, key, value, indent=2, key_style=None,
# value_style=None):
# if value in data:
# echo_pair(key, data[value], indent=indent,
# key_style=key_style, value_style=value_style, )
. Output only the next line. | def cli(ctx): |
Given the following code snippet before the placeholder: <|code_start|>
@click.command('validate')
@click.pass_context
@command_exception_handler
<|code_end|>
, predict the next line using imports from the current file:
import click
from awscfncli2.cli.context import Context
from awscfncli2.cli.utils.deco import command_exception_handler
from awscfncli2.cli.utils.pprint import echo_pair_if_exists
and context including class names, function names, and sometimes code from other files:
# Path: awscfncli2/cli/context.py
# class Context:
# """Click context object
#
#
# # Manage config parsing, transforming deployment process.
# """
#
# def __init__(self,
# config_filename: str,
# artifact_store: str,
# pretty_printer: StackPrettyPrinter,
# stack_selector: StackSelector,
# boto3_profile: Boto3Profile,
# builder,
# ):
# # simple
# self._config_filename: str = config_filename
# self._artifact_store: str = artifact_store
# # complex
# self._pretty_printer: StackPrettyPrinter = pretty_printer
# self._stack_selector = stack_selector
# self._boto3_profile = boto3_profile
# # lazy-loaded
# self._deployments = None
# self._command_runner = None
#
# # internals
# self.__builder = builder
# self.__lock = threading.RLock()
#
# @property
# def config_filename(self):
# """Config file name"""
# return self._config_filename
#
# @property
# def stack_selector(self):
# """Stack selector"""
# return self._stack_selector
#
# @property
# def boto3_profile(self):
# """Boto3 session profiles"""
# return self._boto3_profile
#
# @property
# def verbosity(self):
# """Verbosity level"""
# return self._pretty_printer.verbosity
#
# @property
# def ppt(self):
# """CLI pretty printer"""
# return self._pretty_printer
#
# @property
# def deployments(self):
# """Stack deployment spec."""
# # XXX: Lazy-loading so we don't get error if user is just looking at help
# with self.__lock:
# if self._deployments is None:
# self._deployments = self.__builder.parse_config(self.config_filename)
# return self._deployments
#
# @property
# def runner(self):
# """Command runner."""
# with self.__lock:
# if self._command_runner is None:
# self._command_runner = self.__builder.build_runner(
# self.boto3_profile,
# self._artifact_store,
# self.deployments,
# self.stack_selector,
# self.ppt
# )
# return self._command_runner
#
# Path: awscfncli2/cli/utils/deco.py
# def command_exception_handler(f):
# """Capture and pretty print exceptions."""
#
# @wraps(f)
# def wrapper(ctx, *args, **kwargs):
# try:
# return f(ctx, *args, **kwargs)
# except (botocore.exceptions.ClientError,
# botocore.exceptions.BotoCoreError,
# ) as e:
# if ctx.obj.verbosity > 0:
# click.secho(traceback.format_exc(), fg='red')
# else:
# click.secho(str(e), fg='red')
# raise click.Abort
# except ConfigError as e:
# click.secho(str(e), fg='red')
# if ctx.obj.verbosity > 0:
# traceback.print_exc()
# raise click.Abort
#
# return wrapper
#
# Path: awscfncli2/cli/utils/pprint.py
# def echo_pair_if_exists(data, key, value, indent=2, key_style=None,
# value_style=None):
# if value in data:
# echo_pair(key, data[value], indent=indent,
# key_style=key_style, value_style=value_style, )
. Output only the next line. | def cli(ctx): |
Given the following code snippet before the placeholder: <|code_start|> ['no_wait',
'use_previous_template',
'ignore_no_update',
'override_policy'])):
pass
class StackUpdateCommand(Command):
def run(self, stack_context):
# stack contexts
session = stack_context.session
parameters = stack_context.parameters
metadata = stack_context.metadata
# print stack qualified name
self.ppt.pprint_stack_name(
stack_context.stack_key,
parameters['StackName'],
'Updating stack '
)
# create boto3 cfn resource
cfn = session.resource('cloudformation')
self.ppt.pprint_session(session)
# manipulate stack parameters for update call
if self.options.use_previous_template:
parameters.pop('TemplateBody', None)
parameters.pop('TemplateURL', None)
<|code_end|>
, predict the next line using imports from the current file:
from collections import namedtuple
from ...config import CANNED_STACK_POLICIES
from .command import Command
from .utils import update_termination_protection, \
is_no_updates_being_performed_exception
and context including class names, function names, and sometimes code from other files:
# Path: awscfncli2/config/formats.py
# CANNED_STACK_POLICIES = {
# 'ALLOW_ALL': '{"Statement":[{"Effect":"Allow","Action":"Update:*","Principal":"*","Resource":"*"}]}',
# 'ALLOW_MODIFY': '{"Statement":[{"Effect":"Allow","Action":["Update:Modify"],"Principal":"*","Resource":"*"}]}',
# 'DENY_DELETE': '{"Statement":[{"Effect":"Allow","NotAction":"Update:Delete","Principal":"*","Resource":"*"}]}',
# 'DENY_ALL': '{"Statement":[{"Effect":"Deny","Action":"Update:*","Principal":"*","Resource":"*"}]}',
# }
#
# Path: awscfncli2/runner/commands/command.py
# class Command(object):
# SKIP_UPDATE_REFERENCES = False
#
# def __init__(self, pretty_printer, options):
# assert isinstance(pretty_printer, StackPrettyPrinter)
# self.ppt = pretty_printer
# self.options = options
#
# def run(self, stack_context):
# raise NotImplementedError
#
# Path: awscfncli2/runner/commands/utils.py
# def update_termination_protection(session,
# termination_protection,
# stack_name,
# ppt):
# """Update termination protection on a stack"""
#
# if termination_protection is None:
# # don't care, don't change
# return
#
# client = session.client('cloudformation')
#
# if termination_protection:
# ppt.secho('Enabling TerminationProtection')
# else:
# ppt.secho('Disabling TerminationProtection', fg='red')
#
# client.update_termination_protection(
# StackName=stack_name,
# EnableTerminationProtection=termination_protection)
#
# def is_no_updates_being_performed_exception(ex):
# """Check whether given exception is "no update to be performed"
# botocore doesn't throw a distinct exception class in this case.
# """
# if isinstance(ex, botocore.exceptions.ClientError):
# error = ex.response.get('Error', {})
# error_message = error.get('Message', 'Unknown')
# return error_message.endswith('No updates are to be performed.')
# else:
# return False
. Output only the next line. | parameters['UsePreviousTemplate'] = True |
Given the following code snippet before the placeholder: <|code_start|> CANNED_STACK_POLICIES[self.options.override_policy]
self.ppt.pprint_parameters(parameters)
# termination protection state should be updated no matter
# stack's update succeeded or not
update_termination_protection(session,
termination_protection,
parameters['StackName'],
self.ppt)
# calling boto3...
stack = cfn.Stack(parameters['StackName'])
try:
stack.update(**parameters)
except Exception as ex:
if self.options.ignore_no_update and \
is_no_updates_being_performed_exception(ex):
self.ppt.secho(str(ex), fg='red')
return
else:
raise
self.ppt.pprint_stack(stack)
# wait until update is complete
if self.options.no_wait:
self.ppt.secho('Stack update started.')
else:
self.ppt.wait_until_update_complete(session, stack)
<|code_end|>
, predict the next line using imports from the current file:
from collections import namedtuple
from ...config import CANNED_STACK_POLICIES
from .command import Command
from .utils import update_termination_protection, \
is_no_updates_being_performed_exception
and context including class names, function names, and sometimes code from other files:
# Path: awscfncli2/config/formats.py
# CANNED_STACK_POLICIES = {
# 'ALLOW_ALL': '{"Statement":[{"Effect":"Allow","Action":"Update:*","Principal":"*","Resource":"*"}]}',
# 'ALLOW_MODIFY': '{"Statement":[{"Effect":"Allow","Action":["Update:Modify"],"Principal":"*","Resource":"*"}]}',
# 'DENY_DELETE': '{"Statement":[{"Effect":"Allow","NotAction":"Update:Delete","Principal":"*","Resource":"*"}]}',
# 'DENY_ALL': '{"Statement":[{"Effect":"Deny","Action":"Update:*","Principal":"*","Resource":"*"}]}',
# }
#
# Path: awscfncli2/runner/commands/command.py
# class Command(object):
# SKIP_UPDATE_REFERENCES = False
#
# def __init__(self, pretty_printer, options):
# assert isinstance(pretty_printer, StackPrettyPrinter)
# self.ppt = pretty_printer
# self.options = options
#
# def run(self, stack_context):
# raise NotImplementedError
#
# Path: awscfncli2/runner/commands/utils.py
# def update_termination_protection(session,
# termination_protection,
# stack_name,
# ppt):
# """Update termination protection on a stack"""
#
# if termination_protection is None:
# # don't care, don't change
# return
#
# client = session.client('cloudformation')
#
# if termination_protection:
# ppt.secho('Enabling TerminationProtection')
# else:
# ppt.secho('Disabling TerminationProtection', fg='red')
#
# client.update_termination_protection(
# StackName=stack_name,
# EnableTerminationProtection=termination_protection)
#
# def is_no_updates_being_performed_exception(ex):
# """Check whether given exception is "no update to be performed"
# botocore doesn't throw a distinct exception class in this case.
# """
# if isinstance(ex, botocore.exceptions.ClientError):
# error = ex.response.get('Error', {})
# error_message = error.get('Message', 'Unknown')
# return error_message.endswith('No updates are to be performed.')
# else:
# return False
. Output only the next line. | self.ppt.secho('Stack update complete.', fg='green') |
Here is a snippet: <|code_start|> self.ppt.pprint_session(session)
# manipulate stack parameters for update call
if self.options.use_previous_template:
parameters.pop('TemplateBody', None)
parameters.pop('TemplateURL', None)
parameters['UsePreviousTemplate'] = True
else:
# packaging if necessary
stack_context.run_packaging()
parameters.pop('DisableRollback', None)
parameters.pop('OnFailure', None)
termination_protection = parameters.pop('EnableTerminationProtection',
None)
if self.options.override_policy is not None:
self.ppt.secho(
'Overriding stack policy with {} during update'.format(
self.options.override_policy), fg='red')
parameters['StackPolicyDuringUpdateBody'] = \
CANNED_STACK_POLICIES[self.options.override_policy]
self.ppt.pprint_parameters(parameters)
# termination protection state should be updated no matter
# stack's update succeeded or not
update_termination_protection(session,
termination_protection,
parameters['StackName'],
<|code_end|>
. Write the next line using the current file imports:
from collections import namedtuple
from ...config import CANNED_STACK_POLICIES
from .command import Command
from .utils import update_termination_protection, \
is_no_updates_being_performed_exception
and context from other files:
# Path: awscfncli2/config/formats.py
# CANNED_STACK_POLICIES = {
# 'ALLOW_ALL': '{"Statement":[{"Effect":"Allow","Action":"Update:*","Principal":"*","Resource":"*"}]}',
# 'ALLOW_MODIFY': '{"Statement":[{"Effect":"Allow","Action":["Update:Modify"],"Principal":"*","Resource":"*"}]}',
# 'DENY_DELETE': '{"Statement":[{"Effect":"Allow","NotAction":"Update:Delete","Principal":"*","Resource":"*"}]}',
# 'DENY_ALL': '{"Statement":[{"Effect":"Deny","Action":"Update:*","Principal":"*","Resource":"*"}]}',
# }
#
# Path: awscfncli2/runner/commands/command.py
# class Command(object):
# SKIP_UPDATE_REFERENCES = False
#
# def __init__(self, pretty_printer, options):
# assert isinstance(pretty_printer, StackPrettyPrinter)
# self.ppt = pretty_printer
# self.options = options
#
# def run(self, stack_context):
# raise NotImplementedError
#
# Path: awscfncli2/runner/commands/utils.py
# def update_termination_protection(session,
# termination_protection,
# stack_name,
# ppt):
# """Update termination protection on a stack"""
#
# if termination_protection is None:
# # don't care, don't change
# return
#
# client = session.client('cloudformation')
#
# if termination_protection:
# ppt.secho('Enabling TerminationProtection')
# else:
# ppt.secho('Disabling TerminationProtection', fg='red')
#
# client.update_termination_protection(
# StackName=stack_name,
# EnableTerminationProtection=termination_protection)
#
# def is_no_updates_being_performed_exception(ex):
# """Check whether given exception is "no update to be performed"
# botocore doesn't throw a distinct exception class in this case.
# """
# if isinstance(ex, botocore.exceptions.ClientError):
# error = ex.response.get('Error', {})
# error_message = error.get('Message', 'Unknown')
# return error_message.endswith('No updates are to be performed.')
# else:
# return False
, which may include functions, classes, or code. Output only the next line. | self.ppt) |
Next line prediction: <|code_start|> # create boto3 cfn resource
cfn = session.resource('cloudformation')
self.ppt.pprint_session(session)
# manipulate stack parameters for update call
if self.options.use_previous_template:
parameters.pop('TemplateBody', None)
parameters.pop('TemplateURL', None)
parameters['UsePreviousTemplate'] = True
else:
# packaging if necessary
stack_context.run_packaging()
parameters.pop('DisableRollback', None)
parameters.pop('OnFailure', None)
termination_protection = parameters.pop('EnableTerminationProtection',
None)
if self.options.override_policy is not None:
self.ppt.secho(
'Overriding stack policy with {} during update'.format(
self.options.override_policy), fg='red')
parameters['StackPolicyDuringUpdateBody'] = \
CANNED_STACK_POLICIES[self.options.override_policy]
self.ppt.pprint_parameters(parameters)
# termination protection state should be updated no matter
# stack's update succeeded or not
update_termination_protection(session,
<|code_end|>
. Use current file imports:
(from collections import namedtuple
from ...config import CANNED_STACK_POLICIES
from .command import Command
from .utils import update_termination_protection, \
is_no_updates_being_performed_exception)
and context including class names, function names, or small code snippets from other files:
# Path: awscfncli2/config/formats.py
# CANNED_STACK_POLICIES = {
# 'ALLOW_ALL': '{"Statement":[{"Effect":"Allow","Action":"Update:*","Principal":"*","Resource":"*"}]}',
# 'ALLOW_MODIFY': '{"Statement":[{"Effect":"Allow","Action":["Update:Modify"],"Principal":"*","Resource":"*"}]}',
# 'DENY_DELETE': '{"Statement":[{"Effect":"Allow","NotAction":"Update:Delete","Principal":"*","Resource":"*"}]}',
# 'DENY_ALL': '{"Statement":[{"Effect":"Deny","Action":"Update:*","Principal":"*","Resource":"*"}]}',
# }
#
# Path: awscfncli2/runner/commands/command.py
# class Command(object):
# SKIP_UPDATE_REFERENCES = False
#
# def __init__(self, pretty_printer, options):
# assert isinstance(pretty_printer, StackPrettyPrinter)
# self.ppt = pretty_printer
# self.options = options
#
# def run(self, stack_context):
# raise NotImplementedError
#
# Path: awscfncli2/runner/commands/utils.py
# def update_termination_protection(session,
# termination_protection,
# stack_name,
# ppt):
# """Update termination protection on a stack"""
#
# if termination_protection is None:
# # don't care, don't change
# return
#
# client = session.client('cloudformation')
#
# if termination_protection:
# ppt.secho('Enabling TerminationProtection')
# else:
# ppt.secho('Disabling TerminationProtection', fg='red')
#
# client.update_termination_protection(
# StackName=stack_name,
# EnableTerminationProtection=termination_protection)
#
# def is_no_updates_being_performed_exception(ex):
# """Check whether given exception is "no update to be performed"
# botocore doesn't throw a distinct exception class in this case.
# """
# if isinstance(ex, botocore.exceptions.ClientError):
# error = ex.response.get('Error', {})
# error_message = error.get('Message', 'Unknown')
# return error_message.endswith('No updates are to be performed.')
# else:
# return False
. Output only the next line. | termination_protection, |
Predict the next line for this snippet: <|code_start|># -*- encoding: utf-8 -*-
@click.command()
@click.pass_context
@command_exception_handler
<|code_end|>
with the help of current file imports:
import click
from awscfncli2.cli.context import Context
from awscfncli2.cli.utils.deco import command_exception_handler
from awscfncli2.runner.commands.drift_diff_command import DriftDiffOptions, \
DriftDiffCommand
and context from other files:
# Path: awscfncli2/cli/context.py
# class Context:
# """Click context object
#
#
# # Manage config parsing, transforming deployment process.
# """
#
# def __init__(self,
# config_filename: str,
# artifact_store: str,
# pretty_printer: StackPrettyPrinter,
# stack_selector: StackSelector,
# boto3_profile: Boto3Profile,
# builder,
# ):
# # simple
# self._config_filename: str = config_filename
# self._artifact_store: str = artifact_store
# # complex
# self._pretty_printer: StackPrettyPrinter = pretty_printer
# self._stack_selector = stack_selector
# self._boto3_profile = boto3_profile
# # lazy-loaded
# self._deployments = None
# self._command_runner = None
#
# # internals
# self.__builder = builder
# self.__lock = threading.RLock()
#
# @property
# def config_filename(self):
# """Config file name"""
# return self._config_filename
#
# @property
# def stack_selector(self):
# """Stack selector"""
# return self._stack_selector
#
# @property
# def boto3_profile(self):
# """Boto3 session profiles"""
# return self._boto3_profile
#
# @property
# def verbosity(self):
# """Verbosity level"""
# return self._pretty_printer.verbosity
#
# @property
# def ppt(self):
# """CLI pretty printer"""
# return self._pretty_printer
#
# @property
# def deployments(self):
# """Stack deployment spec."""
# # XXX: Lazy-loading so we don't get error if user is just looking at help
# with self.__lock:
# if self._deployments is None:
# self._deployments = self.__builder.parse_config(self.config_filename)
# return self._deployments
#
# @property
# def runner(self):
# """Command runner."""
# with self.__lock:
# if self._command_runner is None:
# self._command_runner = self.__builder.build_runner(
# self.boto3_profile,
# self._artifact_store,
# self.deployments,
# self.stack_selector,
# self.ppt
# )
# return self._command_runner
#
# Path: awscfncli2/cli/utils/deco.py
# def command_exception_handler(f):
# """Capture and pretty print exceptions."""
#
# @wraps(f)
# def wrapper(ctx, *args, **kwargs):
# try:
# return f(ctx, *args, **kwargs)
# except (botocore.exceptions.ClientError,
# botocore.exceptions.BotoCoreError,
# ) as e:
# if ctx.obj.verbosity > 0:
# click.secho(traceback.format_exc(), fg='red')
# else:
# click.secho(str(e), fg='red')
# raise click.Abort
# except ConfigError as e:
# click.secho(str(e), fg='red')
# if ctx.obj.verbosity > 0:
# traceback.print_exc()
# raise click.Abort
#
# return wrapper
#
# Path: awscfncli2/runner/commands/drift_diff_command.py
# class DriftDiffOptions(namedtuple('DriftDiffOptions',
# [])):
# pass
#
# class DriftDiffCommand(Command):
# SKIP_UPDATE_REFERENCES = True
#
# def run(self, stack_context):
# # stack contexts
# session = stack_context.session
# parameters = stack_context.parameters
# metadata = stack_context.metadata
#
# self.ppt.pprint_stack_name(stack_context.stack_key,
# parameters['StackName'],
# 'Describing drift of ')
#
# # create boto3 client
# self.ppt.pprint_session(session)
# self.ppt.pprint_parameters(parameters)
#
# client = session.client('cloudformation')
#
# # call boto3
# self.ppt.secho('Drifted resources:')
# response = client.describe_stack_resource_drifts(
# StackName=parameters['StackName'],
# StackResourceDriftStatusFilters=['MODIFIED','DELETED']
# )
#
# for drift in response['StackResourceDrifts']:
# self.ppt.pprint_resource_drift(drift)
, which may contain function names, class names, or code. Output only the next line. | def diff(ctx): |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
CANNED_STACK_POLICIES = {
'ALLOW_ALL': '{"Statement":[{"Effect":"Allow","Action":"Update:*","Principal":"*","Resource":"*"}]}',
'ALLOW_MODIFY': '{"Statement":[{"Effect":"Allow","Action":["Update:Modify"],"Principal":"*","Resource":"*"}]}',
<|code_end|>
with the help of current file imports:
import copy
import os
import jsonschema
import six
from .deployment import StackKey, StackDeployment, StackMetadata, StackProfile, \
StackParameters, Deployment
from .schema import load_schema
from .template import find_references
and context from other files:
# Path: awscfncli2/config/deployment.py
# class StackKey(namedtuple('StackKey', sorted(StackDefaults.STACK_KEY))):
#
# @property
# def qualified_name(self):
# return '.'.join([self.StageKey, self.StackKey])
#
# @staticmethod
# def from_dict(**params):
# result = copy.deepcopy(StackDefaults.STACK_KEY)
# _extends(result, **params)
# return StackKey(**result)
#
# class StackDeployment(
# namedtuple('StackDeployment', 'stack_key, metadata, profile, parameters')):
# pass
#
# class StackMetadata(
# namedtuple('StackMetadata', sorted(StackDefaults.STACK_METADATA))):
# @staticmethod
# def from_dict(**params):
# result = copy.deepcopy(StackDefaults.STACK_METADATA)
# _extends(result, **params)
# return StackMetadata(**result)
#
# class StackProfile(
# namedtuple('StackMetadata', sorted(StackDefaults.STACK_PROFILE))):
# @staticmethod
# def from_dict(**params):
# result = copy.deepcopy(StackDefaults.STACK_PROFILE)
# _extends(result, **params)
# return StackProfile(**result)
#
# class StackParameters(
# namedtuple('StackParameters', sorted(StackDefaults.STACK_PARAMETERS))):
# @staticmethod
# def from_dict(**params):
# result = copy.deepcopy(StackDefaults.STACK_PARAMETERS)
# _extends(result, **params)
# return StackParameters(**result)
#
# def find_references(self):
# # TODO Need refactor to reduce duplicated ParameterTemplate construction
# return find_references(self._asdict())
#
# def substitute_references(self, **args):
# return substitute_references(self._asdict(), **args)
#
# class Deployment(object):
#
# def __init__(self):
# self._index = dict()
#
# def add_stack(self, stage_key, stack_key, stack):
# key = (stage_key, stack_key)
# self._index[key] = stack
#
# def get_stack(self, stage_key, stack_key):
# key = (stage_key, stack_key)
# return self._index.get(key)
#
# def get_stacks(self, stage_key):
# return list(k1 for (k1, k2) in self._index if k1 == stage_key)
#
# def query_stacks(self, stage_pattern='*', stack_pattern='*'):
# """Find all stack config matching stage/stack patterns
# """
# result = list()
# for (k1, k2) in self._index:
# if fnmatch.fnmatchcase(k1, stage_pattern) \
# and fnmatch.fnmatchcase(k2, stack_pattern):
# result.append(self._index[(k1, k2)])
#
# result.sort(key=lambda stack: stack.metadata.Order)
#
# return result
#
# Path: awscfncli2/config/schema.py
# def load_schema(version):
# filename = os.path.join(
# get_schema_path(), 'schema_v{0}.json'.format(version))
# with open(filename, 'r') as fp:
# return json.load(fp)
#
# Path: awscfncli2/config/template.py
# def find_references(params):
# dumps = json.dumps(params)
# references = []
# for match in _Template.pattern.findall(dumps):
# if match and match[2]:
# references.append(match[2])
# return references
, which may contain function names, class names, or code. Output only the next line. | 'DENY_DELETE': '{"Statement":[{"Effect":"Allow","NotAction":"Update:Delete","Principal":"*","Resource":"*"}]}', |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
CANNED_STACK_POLICIES = {
'ALLOW_ALL': '{"Statement":[{"Effect":"Allow","Action":"Update:*","Principal":"*","Resource":"*"}]}',
'ALLOW_MODIFY': '{"Statement":[{"Effect":"Allow","Action":["Update:Modify"],"Principal":"*","Resource":"*"}]}',
'DENY_DELETE': '{"Statement":[{"Effect":"Allow","NotAction":"Update:Delete","Principal":"*","Resource":"*"}]}',
'DENY_ALL': '{"Statement":[{"Effect":"Deny","Action":"Update:*","Principal":"*","Resource":"*"}]}',
}
class FormatError(Exception):
pass
def load_format(version):
if version == 3:
return FormatV3
elif version == 2:
return FormatV2
elif version == 1 or version is None:
return FormatV1
else:
raise FormatError('Unspported config version {}'.format(version))
<|code_end|>
. Use current file imports:
import copy
import os
import jsonschema
import six
from .deployment import StackKey, StackDeployment, StackMetadata, StackProfile, \
StackParameters, Deployment
from .schema import load_schema
from .template import find_references
and context (classes, functions, or code) from other files:
# Path: awscfncli2/config/deployment.py
# class StackKey(namedtuple('StackKey', sorted(StackDefaults.STACK_KEY))):
#
# @property
# def qualified_name(self):
# return '.'.join([self.StageKey, self.StackKey])
#
# @staticmethod
# def from_dict(**params):
# result = copy.deepcopy(StackDefaults.STACK_KEY)
# _extends(result, **params)
# return StackKey(**result)
#
# class StackDeployment(
# namedtuple('StackDeployment', 'stack_key, metadata, profile, parameters')):
# pass
#
# class StackMetadata(
# namedtuple('StackMetadata', sorted(StackDefaults.STACK_METADATA))):
# @staticmethod
# def from_dict(**params):
# result = copy.deepcopy(StackDefaults.STACK_METADATA)
# _extends(result, **params)
# return StackMetadata(**result)
#
# class StackProfile(
# namedtuple('StackMetadata', sorted(StackDefaults.STACK_PROFILE))):
# @staticmethod
# def from_dict(**params):
# result = copy.deepcopy(StackDefaults.STACK_PROFILE)
# _extends(result, **params)
# return StackProfile(**result)
#
# class StackParameters(
# namedtuple('StackParameters', sorted(StackDefaults.STACK_PARAMETERS))):
# @staticmethod
# def from_dict(**params):
# result = copy.deepcopy(StackDefaults.STACK_PARAMETERS)
# _extends(result, **params)
# return StackParameters(**result)
#
# def find_references(self):
# # TODO Need refactor to reduce duplicated ParameterTemplate construction
# return find_references(self._asdict())
#
# def substitute_references(self, **args):
# return substitute_references(self._asdict(), **args)
#
# class Deployment(object):
#
# def __init__(self):
# self._index = dict()
#
# def add_stack(self, stage_key, stack_key, stack):
# key = (stage_key, stack_key)
# self._index[key] = stack
#
# def get_stack(self, stage_key, stack_key):
# key = (stage_key, stack_key)
# return self._index.get(key)
#
# def get_stacks(self, stage_key):
# return list(k1 for (k1, k2) in self._index if k1 == stage_key)
#
# def query_stacks(self, stage_pattern='*', stack_pattern='*'):
# """Find all stack config matching stage/stack patterns
# """
# result = list()
# for (k1, k2) in self._index:
# if fnmatch.fnmatchcase(k1, stage_pattern) \
# and fnmatch.fnmatchcase(k2, stack_pattern):
# result.append(self._index[(k1, k2)])
#
# result.sort(key=lambda stack: stack.metadata.Order)
#
# return result
#
# Path: awscfncli2/config/schema.py
# def load_schema(version):
# filename = os.path.join(
# get_schema_path(), 'schema_v{0}.json'.format(version))
# with open(filename, 'r') as fp:
# return json.load(fp)
#
# Path: awscfncli2/config/template.py
# def find_references(params):
# dumps = json.dumps(params)
# references = []
# for match in _Template.pattern.findall(dumps):
# if match and match[2]:
# references.append(match[2])
# return references
. Output only the next line. | class ConfigFormat(object): |
Given snippet: <|code_start|> for key, (typ, default) in self.STACK_CONFIG.items():
# skip unknown parameters
if key not in extends:
continue
# overwrite Capabilities parameter
if key == 'Capabilities':
config[key] = copy.deepcopy(extends[key])
# append list
elif typ is list:
if key not in config:
config[key] = list(extends[key])
else:
config[key].extend(extends[key])
# update dict
elif typ is dict:
if key not in config:
config[key] = dict(extends[key])
else:
config[key].update(extends[key])
# copy everything else
else:
config[key] = copy.deepcopy(extends[key])
return config
def _build_stack(self, stage_key, stack_key, stage_config, stack_config):
# add default order
stage_order = stage_config.get('Order', 0)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import copy
import os
import jsonschema
import six
from .deployment import StackKey, StackDeployment, StackMetadata, StackProfile, \
StackParameters, Deployment
from .schema import load_schema
from .template import find_references
and context:
# Path: awscfncli2/config/deployment.py
# class StackKey(namedtuple('StackKey', sorted(StackDefaults.STACK_KEY))):
#
# @property
# def qualified_name(self):
# return '.'.join([self.StageKey, self.StackKey])
#
# @staticmethod
# def from_dict(**params):
# result = copy.deepcopy(StackDefaults.STACK_KEY)
# _extends(result, **params)
# return StackKey(**result)
#
# class StackDeployment(
# namedtuple('StackDeployment', 'stack_key, metadata, profile, parameters')):
# pass
#
# class StackMetadata(
# namedtuple('StackMetadata', sorted(StackDefaults.STACK_METADATA))):
# @staticmethod
# def from_dict(**params):
# result = copy.deepcopy(StackDefaults.STACK_METADATA)
# _extends(result, **params)
# return StackMetadata(**result)
#
# class StackProfile(
# namedtuple('StackMetadata', sorted(StackDefaults.STACK_PROFILE))):
# @staticmethod
# def from_dict(**params):
# result = copy.deepcopy(StackDefaults.STACK_PROFILE)
# _extends(result, **params)
# return StackProfile(**result)
#
# class StackParameters(
# namedtuple('StackParameters', sorted(StackDefaults.STACK_PARAMETERS))):
# @staticmethod
# def from_dict(**params):
# result = copy.deepcopy(StackDefaults.STACK_PARAMETERS)
# _extends(result, **params)
# return StackParameters(**result)
#
# def find_references(self):
# # TODO Need refactor to reduce duplicated ParameterTemplate construction
# return find_references(self._asdict())
#
# def substitute_references(self, **args):
# return substitute_references(self._asdict(), **args)
#
# class Deployment(object):
#
# def __init__(self):
# self._index = dict()
#
# def add_stack(self, stage_key, stack_key, stack):
# key = (stage_key, stack_key)
# self._index[key] = stack
#
# def get_stack(self, stage_key, stack_key):
# key = (stage_key, stack_key)
# return self._index.get(key)
#
# def get_stacks(self, stage_key):
# return list(k1 for (k1, k2) in self._index if k1 == stage_key)
#
# def query_stacks(self, stage_pattern='*', stack_pattern='*'):
# """Find all stack config matching stage/stack patterns
# """
# result = list()
# for (k1, k2) in self._index:
# if fnmatch.fnmatchcase(k1, stage_pattern) \
# and fnmatch.fnmatchcase(k2, stack_pattern):
# result.append(self._index[(k1, k2)])
#
# result.sort(key=lambda stack: stack.metadata.Order)
#
# return result
#
# Path: awscfncli2/config/schema.py
# def load_schema(version):
# filename = os.path.join(
# get_schema_path(), 'schema_v{0}.json'.format(version))
# with open(filename, 'r') as fp:
# return json.load(fp)
#
# Path: awscfncli2/config/template.py
# def find_references(params):
# dumps = json.dumps(params)
# references = []
# for match in _Template.pattern.findall(dumps):
# if match and match[2]:
# references.append(match[2])
# return references
which might include code, classes, or functions. Output only the next line. | stack_order = stack_config.get('Order', 0) |
Next line prediction: <|code_start|>
def __init__(self, **context):
self._context = context
def validate(self, config):
schema = load_schema(str(self.VERSION))
jsonschema.validate(config, schema)
def parse(self, config):
raise NotImplementedError
class FormatV2(ConfigFormat):
VERSION = '2.0.0'
STAGE_CONFIG = dict(
Order=(six.integer_types, None),
)
STACK_CONFIG = dict(
Order=(six.integer_types, None),
Profile=(six.string_types, None),
Region=(six.string_types, None),
Package=(bool, None),
ArtifactStore=(six.string_types, None),
StackName=(six.string_types, None),
Template=(six.string_types, None),
Parameters=(dict, None),
DisableRollback=(bool, None),
RollbackConfiguration=(dict, None),
<|code_end|>
. Use current file imports:
(import copy
import os
import jsonschema
import six
from .deployment import StackKey, StackDeployment, StackMetadata, StackProfile, \
StackParameters, Deployment
from .schema import load_schema
from .template import find_references)
and context including class names, function names, or small code snippets from other files:
# Path: awscfncli2/config/deployment.py
# class StackKey(namedtuple('StackKey', sorted(StackDefaults.STACK_KEY))):
#
# @property
# def qualified_name(self):
# return '.'.join([self.StageKey, self.StackKey])
#
# @staticmethod
# def from_dict(**params):
# result = copy.deepcopy(StackDefaults.STACK_KEY)
# _extends(result, **params)
# return StackKey(**result)
#
# class StackDeployment(
# namedtuple('StackDeployment', 'stack_key, metadata, profile, parameters')):
# pass
#
# class StackMetadata(
# namedtuple('StackMetadata', sorted(StackDefaults.STACK_METADATA))):
# @staticmethod
# def from_dict(**params):
# result = copy.deepcopy(StackDefaults.STACK_METADATA)
# _extends(result, **params)
# return StackMetadata(**result)
#
# class StackProfile(
# namedtuple('StackMetadata', sorted(StackDefaults.STACK_PROFILE))):
# @staticmethod
# def from_dict(**params):
# result = copy.deepcopy(StackDefaults.STACK_PROFILE)
# _extends(result, **params)
# return StackProfile(**result)
#
# class StackParameters(
# namedtuple('StackParameters', sorted(StackDefaults.STACK_PARAMETERS))):
# @staticmethod
# def from_dict(**params):
# result = copy.deepcopy(StackDefaults.STACK_PARAMETERS)
# _extends(result, **params)
# return StackParameters(**result)
#
# def find_references(self):
# # TODO Need refactor to reduce duplicated ParameterTemplate construction
# return find_references(self._asdict())
#
# def substitute_references(self, **args):
# return substitute_references(self._asdict(), **args)
#
# class Deployment(object):
#
# def __init__(self):
# self._index = dict()
#
# def add_stack(self, stage_key, stack_key, stack):
# key = (stage_key, stack_key)
# self._index[key] = stack
#
# def get_stack(self, stage_key, stack_key):
# key = (stage_key, stack_key)
# return self._index.get(key)
#
# def get_stacks(self, stage_key):
# return list(k1 for (k1, k2) in self._index if k1 == stage_key)
#
# def query_stacks(self, stage_pattern='*', stack_pattern='*'):
# """Find all stack config matching stage/stack patterns
# """
# result = list()
# for (k1, k2) in self._index:
# if fnmatch.fnmatchcase(k1, stage_pattern) \
# and fnmatch.fnmatchcase(k2, stack_pattern):
# result.append(self._index[(k1, k2)])
#
# result.sort(key=lambda stack: stack.metadata.Order)
#
# return result
#
# Path: awscfncli2/config/schema.py
# def load_schema(version):
# filename = os.path.join(
# get_schema_path(), 'schema_v{0}.json'.format(version))
# with open(filename, 'r') as fp:
# return json.load(fp)
#
# Path: awscfncli2/config/template.py
# def find_references(params):
# dumps = json.dumps(params)
# references = []
# for match in _Template.pattern.findall(dumps):
# if match and match[2]:
# references.append(match[2])
# return references
. Output only the next line. | TimeoutInMinutes=(six.integer_types, None), |
Continue the code snippet: <|code_start|>CANNED_STACK_POLICIES = {
'ALLOW_ALL': '{"Statement":[{"Effect":"Allow","Action":"Update:*","Principal":"*","Resource":"*"}]}',
'ALLOW_MODIFY': '{"Statement":[{"Effect":"Allow","Action":["Update:Modify"],"Principal":"*","Resource":"*"}]}',
'DENY_DELETE': '{"Statement":[{"Effect":"Allow","NotAction":"Update:Delete","Principal":"*","Resource":"*"}]}',
'DENY_ALL': '{"Statement":[{"Effect":"Deny","Action":"Update:*","Principal":"*","Resource":"*"}]}',
}
class FormatError(Exception):
pass
def load_format(version):
if version == 3:
return FormatV3
elif version == 2:
return FormatV2
elif version == 1 or version is None:
return FormatV1
else:
raise FormatError('Unspported config version {}'.format(version))
class ConfigFormat(object):
VERSION = None
def validate(self, config):
raise NotImplementedError
def parse(self, config):
<|code_end|>
. Use current file imports:
import copy
import os
import jsonschema
import six
from .deployment import StackKey, StackDeployment, StackMetadata, StackProfile, \
StackParameters, Deployment
from .schema import load_schema
from .template import find_references
and context (classes, functions, or code) from other files:
# Path: awscfncli2/config/deployment.py
# class StackKey(namedtuple('StackKey', sorted(StackDefaults.STACK_KEY))):
#
# @property
# def qualified_name(self):
# return '.'.join([self.StageKey, self.StackKey])
#
# @staticmethod
# def from_dict(**params):
# result = copy.deepcopy(StackDefaults.STACK_KEY)
# _extends(result, **params)
# return StackKey(**result)
#
# class StackDeployment(
# namedtuple('StackDeployment', 'stack_key, metadata, profile, parameters')):
# pass
#
# class StackMetadata(
# namedtuple('StackMetadata', sorted(StackDefaults.STACK_METADATA))):
# @staticmethod
# def from_dict(**params):
# result = copy.deepcopy(StackDefaults.STACK_METADATA)
# _extends(result, **params)
# return StackMetadata(**result)
#
# class StackProfile(
# namedtuple('StackMetadata', sorted(StackDefaults.STACK_PROFILE))):
# @staticmethod
# def from_dict(**params):
# result = copy.deepcopy(StackDefaults.STACK_PROFILE)
# _extends(result, **params)
# return StackProfile(**result)
#
# class StackParameters(
# namedtuple('StackParameters', sorted(StackDefaults.STACK_PARAMETERS))):
# @staticmethod
# def from_dict(**params):
# result = copy.deepcopy(StackDefaults.STACK_PARAMETERS)
# _extends(result, **params)
# return StackParameters(**result)
#
# def find_references(self):
# # TODO Need refactor to reduce duplicated ParameterTemplate construction
# return find_references(self._asdict())
#
# def substitute_references(self, **args):
# return substitute_references(self._asdict(), **args)
#
# class Deployment(object):
#
# def __init__(self):
# self._index = dict()
#
# def add_stack(self, stage_key, stack_key, stack):
# key = (stage_key, stack_key)
# self._index[key] = stack
#
# def get_stack(self, stage_key, stack_key):
# key = (stage_key, stack_key)
# return self._index.get(key)
#
# def get_stacks(self, stage_key):
# return list(k1 for (k1, k2) in self._index if k1 == stage_key)
#
# def query_stacks(self, stage_pattern='*', stack_pattern='*'):
# """Find all stack config matching stage/stack patterns
# """
# result = list()
# for (k1, k2) in self._index:
# if fnmatch.fnmatchcase(k1, stage_pattern) \
# and fnmatch.fnmatchcase(k2, stack_pattern):
# result.append(self._index[(k1, k2)])
#
# result.sort(key=lambda stack: stack.metadata.Order)
#
# return result
#
# Path: awscfncli2/config/schema.py
# def load_schema(version):
# filename = os.path.join(
# get_schema_path(), 'schema_v{0}.json'.format(version))
# with open(filename, 'r') as fp:
# return json.load(fp)
#
# Path: awscfncli2/config/template.py
# def find_references(params):
# dumps = json.dumps(params)
# references = []
# for match in _Template.pattern.findall(dumps):
# if match and match[2]:
# references.append(match[2])
# return references
. Output only the next line. | raise NotImplementedError |
Based on the snippet: <|code_start|> Order=(six.integer_types, None),
Profile=(six.string_types, None),
Region=(six.string_types, None),
Package=(bool, None),
ArtifactStore=(six.string_types, None),
StackName=(six.string_types, None),
Template=(six.string_types, None),
Parameters=(dict, None),
DisableRollback=(bool, None),
RollbackConfiguration=(dict, None),
TimeoutInMinutes=(six.integer_types, None),
NotificationARNs=(six.string_types, None),
Capabilities=(list, None),
ResourceTypes=(list, None),
RoleARN=(six.string_types, None),
OnFailure=(six.string_types, None),
StackPolicy=(six.string_types, None),
Tags=(dict, None),
ClientRequestToken=(six.string_types, None),
EnableTerminationProtection=(bool, None)
)
def __init__(self, basedir='.'):
self._basedir = basedir
def validate(self, config):
schema = load_schema(str(self.VERSION))
jsonschema.validate(config, schema)
if have_parameter_reference_pattern(config):
<|code_end|>
, predict the immediate next line with the help of imports:
import copy
import os
import jsonschema
import six
from .deployment import StackKey, StackDeployment, StackMetadata, StackProfile, \
StackParameters, Deployment
from .schema import load_schema
from .template import find_references
and context (classes, functions, sometimes code) from other files:
# Path: awscfncli2/config/deployment.py
# class StackKey(namedtuple('StackKey', sorted(StackDefaults.STACK_KEY))):
#
# @property
# def qualified_name(self):
# return '.'.join([self.StageKey, self.StackKey])
#
# @staticmethod
# def from_dict(**params):
# result = copy.deepcopy(StackDefaults.STACK_KEY)
# _extends(result, **params)
# return StackKey(**result)
#
# class StackDeployment(
# namedtuple('StackDeployment', 'stack_key, metadata, profile, parameters')):
# pass
#
# class StackMetadata(
# namedtuple('StackMetadata', sorted(StackDefaults.STACK_METADATA))):
# @staticmethod
# def from_dict(**params):
# result = copy.deepcopy(StackDefaults.STACK_METADATA)
# _extends(result, **params)
# return StackMetadata(**result)
#
# class StackProfile(
# namedtuple('StackMetadata', sorted(StackDefaults.STACK_PROFILE))):
# @staticmethod
# def from_dict(**params):
# result = copy.deepcopy(StackDefaults.STACK_PROFILE)
# _extends(result, **params)
# return StackProfile(**result)
#
# class StackParameters(
# namedtuple('StackParameters', sorted(StackDefaults.STACK_PARAMETERS))):
# @staticmethod
# def from_dict(**params):
# result = copy.deepcopy(StackDefaults.STACK_PARAMETERS)
# _extends(result, **params)
# return StackParameters(**result)
#
# def find_references(self):
# # TODO Need refactor to reduce duplicated ParameterTemplate construction
# return find_references(self._asdict())
#
# def substitute_references(self, **args):
# return substitute_references(self._asdict(), **args)
#
# class Deployment(object):
#
# def __init__(self):
# self._index = dict()
#
# def add_stack(self, stage_key, stack_key, stack):
# key = (stage_key, stack_key)
# self._index[key] = stack
#
# def get_stack(self, stage_key, stack_key):
# key = (stage_key, stack_key)
# return self._index.get(key)
#
# def get_stacks(self, stage_key):
# return list(k1 for (k1, k2) in self._index if k1 == stage_key)
#
# def query_stacks(self, stage_pattern='*', stack_pattern='*'):
# """Find all stack config matching stage/stack patterns
# """
# result = list()
# for (k1, k2) in self._index:
# if fnmatch.fnmatchcase(k1, stage_pattern) \
# and fnmatch.fnmatchcase(k2, stack_pattern):
# result.append(self._index[(k1, k2)])
#
# result.sort(key=lambda stack: stack.metadata.Order)
#
# return result
#
# Path: awscfncli2/config/schema.py
# def load_schema(version):
# filename = os.path.join(
# get_schema_path(), 'schema_v{0}.json'.format(version))
# with open(filename, 'r') as fp:
# return json.load(fp)
#
# Path: awscfncli2/config/template.py
# def find_references(params):
# dumps = json.dumps(params)
# references = []
# for match in _Template.pattern.findall(dumps):
# if match and match[2]:
# references.append(match[2])
# return references
. Output only the next line. | raise jsonschema.SchemaError( |
Predict the next line after this snippet: <|code_start|> else:
config[key].update(extends[key])
# copy everything else
else:
config[key] = copy.deepcopy(extends[key])
return config
def _build_stack(self, stage_key, stack_key, stage_config, stack_config):
# add default order
stage_order = stage_config.get('Order', 0)
stack_order = stack_config.get('Order', 0)
stack_config['Order'] = (stage_order, stack_order)
# add default name
if 'StackName' not in stack_config:
stack_config['StackName'] = stack_key
# Make relate template path
template = stack_config.get('Template')
if template and \
not (template.startswith('https') and template.startswith(
'http')):
template_path = os.path.realpath(
os.path.join(self._basedir, template))
if not os.path.exists(template_path):
raise FormatError('File Not Found %s' % template_path)
stack_config['Template'] = template_path
stack_policy = stack_config.get('StackPolicy')
<|code_end|>
using the current file's imports:
import copy
import os
import jsonschema
import six
from .deployment import StackKey, StackDeployment, StackMetadata, StackProfile, \
StackParameters, Deployment
from .schema import load_schema
from .template import find_references
and any relevant context from other files:
# Path: awscfncli2/config/deployment.py
# class StackKey(namedtuple('StackKey', sorted(StackDefaults.STACK_KEY))):
#
# @property
# def qualified_name(self):
# return '.'.join([self.StageKey, self.StackKey])
#
# @staticmethod
# def from_dict(**params):
# result = copy.deepcopy(StackDefaults.STACK_KEY)
# _extends(result, **params)
# return StackKey(**result)
#
# class StackDeployment(
# namedtuple('StackDeployment', 'stack_key, metadata, profile, parameters')):
# pass
#
# class StackMetadata(
# namedtuple('StackMetadata', sorted(StackDefaults.STACK_METADATA))):
# @staticmethod
# def from_dict(**params):
# result = copy.deepcopy(StackDefaults.STACK_METADATA)
# _extends(result, **params)
# return StackMetadata(**result)
#
# class StackProfile(
# namedtuple('StackMetadata', sorted(StackDefaults.STACK_PROFILE))):
# @staticmethod
# def from_dict(**params):
# result = copy.deepcopy(StackDefaults.STACK_PROFILE)
# _extends(result, **params)
# return StackProfile(**result)
#
# class StackParameters(
# namedtuple('StackParameters', sorted(StackDefaults.STACK_PARAMETERS))):
# @staticmethod
# def from_dict(**params):
# result = copy.deepcopy(StackDefaults.STACK_PARAMETERS)
# _extends(result, **params)
# return StackParameters(**result)
#
# def find_references(self):
# # TODO Need refactor to reduce duplicated ParameterTemplate construction
# return find_references(self._asdict())
#
# def substitute_references(self, **args):
# return substitute_references(self._asdict(), **args)
#
# class Deployment(object):
#
# def __init__(self):
# self._index = dict()
#
# def add_stack(self, stage_key, stack_key, stack):
# key = (stage_key, stack_key)
# self._index[key] = stack
#
# def get_stack(self, stage_key, stack_key):
# key = (stage_key, stack_key)
# return self._index.get(key)
#
# def get_stacks(self, stage_key):
# return list(k1 for (k1, k2) in self._index if k1 == stage_key)
#
# def query_stacks(self, stage_pattern='*', stack_pattern='*'):
# """Find all stack config matching stage/stack patterns
# """
# result = list()
# for (k1, k2) in self._index:
# if fnmatch.fnmatchcase(k1, stage_pattern) \
# and fnmatch.fnmatchcase(k2, stack_pattern):
# result.append(self._index[(k1, k2)])
#
# result.sort(key=lambda stack: stack.metadata.Order)
#
# return result
#
# Path: awscfncli2/config/schema.py
# def load_schema(version):
# filename = os.path.join(
# get_schema_path(), 'schema_v{0}.json'.format(version))
# with open(filename, 'r') as fp:
# return json.load(fp)
#
# Path: awscfncli2/config/template.py
# def find_references(params):
# dumps = json.dumps(params)
# references = []
# for match in _Template.pattern.findall(dumps):
# if match and match[2]:
# references.append(match[2])
# return references
. Output only the next line. | if stack_policy and stack_policy not in CANNED_STACK_POLICIES: |
Next line prediction: <|code_start|> STACK_CONFIG = dict(
Order=(six.integer_types, None),
Profile=(six.string_types, None),
Region=(six.string_types, None),
Package=(bool, None),
ArtifactStore=(six.string_types, None),
StackName=(six.string_types, None),
Template=(six.string_types, None),
Parameters=(dict, None),
DisableRollback=(bool, None),
RollbackConfiguration=(dict, None),
TimeoutInMinutes=(six.integer_types, None),
NotificationARNs=(six.string_types, None),
Capabilities=(list, None),
ResourceTypes=(list, None),
RoleARN=(six.string_types, None),
OnFailure=(six.string_types, None),
StackPolicy=(six.string_types, None),
Tags=(dict, None),
ClientRequestToken=(six.string_types, None),
EnableTerminationProtection=(bool, None)
)
def __init__(self, basedir='.'):
self._basedir = basedir
def validate(self, config):
schema = load_schema(str(self.VERSION))
jsonschema.validate(config, schema)
<|code_end|>
. Use current file imports:
(import copy
import os
import jsonschema
import six
from .deployment import StackKey, StackDeployment, StackMetadata, StackProfile, \
StackParameters, Deployment
from .schema import load_schema
from .template import find_references)
and context including class names, function names, or small code snippets from other files:
# Path: awscfncli2/config/deployment.py
# class StackKey(namedtuple('StackKey', sorted(StackDefaults.STACK_KEY))):
#
# @property
# def qualified_name(self):
# return '.'.join([self.StageKey, self.StackKey])
#
# @staticmethod
# def from_dict(**params):
# result = copy.deepcopy(StackDefaults.STACK_KEY)
# _extends(result, **params)
# return StackKey(**result)
#
# class StackDeployment(
# namedtuple('StackDeployment', 'stack_key, metadata, profile, parameters')):
# pass
#
# class StackMetadata(
# namedtuple('StackMetadata', sorted(StackDefaults.STACK_METADATA))):
# @staticmethod
# def from_dict(**params):
# result = copy.deepcopy(StackDefaults.STACK_METADATA)
# _extends(result, **params)
# return StackMetadata(**result)
#
# class StackProfile(
# namedtuple('StackMetadata', sorted(StackDefaults.STACK_PROFILE))):
# @staticmethod
# def from_dict(**params):
# result = copy.deepcopy(StackDefaults.STACK_PROFILE)
# _extends(result, **params)
# return StackProfile(**result)
#
# class StackParameters(
# namedtuple('StackParameters', sorted(StackDefaults.STACK_PARAMETERS))):
# @staticmethod
# def from_dict(**params):
# result = copy.deepcopy(StackDefaults.STACK_PARAMETERS)
# _extends(result, **params)
# return StackParameters(**result)
#
# def find_references(self):
# # TODO Need refactor to reduce duplicated ParameterTemplate construction
# return find_references(self._asdict())
#
# def substitute_references(self, **args):
# return substitute_references(self._asdict(), **args)
#
# class Deployment(object):
#
# def __init__(self):
# self._index = dict()
#
# def add_stack(self, stage_key, stack_key, stack):
# key = (stage_key, stack_key)
# self._index[key] = stack
#
# def get_stack(self, stage_key, stack_key):
# key = (stage_key, stack_key)
# return self._index.get(key)
#
# def get_stacks(self, stage_key):
# return list(k1 for (k1, k2) in self._index if k1 == stage_key)
#
# def query_stacks(self, stage_pattern='*', stack_pattern='*'):
# """Find all stack config matching stage/stack patterns
# """
# result = list()
# for (k1, k2) in self._index:
# if fnmatch.fnmatchcase(k1, stage_pattern) \
# and fnmatch.fnmatchcase(k2, stack_pattern):
# result.append(self._index[(k1, k2)])
#
# result.sort(key=lambda stack: stack.metadata.Order)
#
# return result
#
# Path: awscfncli2/config/schema.py
# def load_schema(version):
# filename = os.path.join(
# get_schema_path(), 'schema_v{0}.json'.format(version))
# with open(filename, 'r') as fp:
# return json.load(fp)
#
# Path: awscfncli2/config/template.py
# def find_references(params):
# dumps = json.dumps(params)
# references = []
# for match in _Template.pattern.findall(dumps):
# if match and match[2]:
# references.append(match[2])
# return references
. Output only the next line. | if have_parameter_reference_pattern(config): |
Predict the next line after this snippet: <|code_start|>
class DriftDiffOptions(namedtuple('DriftDiffOptions',
[])):
pass
class DriftDiffCommand(Command):
SKIP_UPDATE_REFERENCES = True
def run(self, stack_context):
# stack contexts
session = stack_context.session
parameters = stack_context.parameters
<|code_end|>
using the current file's imports:
from collections import namedtuple
from .command import Command
and any relevant context from other files:
# Path: awscfncli2/runner/commands/command.py
# class Command(object):
# SKIP_UPDATE_REFERENCES = False
#
# def __init__(self, pretty_printer, options):
# assert isinstance(pretty_printer, StackPrettyPrinter)
# self.ppt = pretty_printer
# self.options = options
#
# def run(self, stack_context):
# raise NotImplementedError
. Output only the next line. | metadata = stack_context.metadata |
Given the following code snippet before the placeholder: <|code_start|> client_request_token = 'awscfncli-sync-{}'.format(uuid.uuid1())
self.ppt.secho('Executing ChangeSet...')
client.execute_change_set(
ChangeSetName=changeset_name,
StackName=parameters['StackName'],
ClientRequestToken=client_request_token
)
cfn = session.resource('cloudformation')
stack = cfn.Stack(parameters['StackName'])
if self.options.no_wait:
self.ppt.secho('ChangeSet execution started.')
else:
if is_new_stack:
self.ppt.wait_until_deploy_complete(session, stack, self.options.disable_tail_events)
else:
self.ppt.wait_until_update_complete(session, stack, self.options.disable_tail_events)
self.ppt.secho('ChangeSet execution complete.', fg='green')
@backoff.on_exception(backoff.expo, botocore.exceptions.ClientError, max_tries=10,
giveup=is_not_rate_limited_exception)
def create_change_set(self, client, parameters):
return client.create_change_set(**parameters)
@backoff.on_exception(backoff.expo, botocore.exceptions.ClientError, max_tries=10,
giveup=is_not_rate_limited_exception)
def describe_change_set(self, client, changeset_name, parameters):
return client.describe_change_set(
ChangeSetName=changeset_name,
StackName=parameters['StackName'],
<|code_end|>
, predict the next line using imports from the current file:
import uuid
import backoff
import botocore.exceptions
from collections import namedtuple
from awscfncli2.cli.utils.common import is_not_rate_limited_exception, is_rate_limited_exception
from awscfncli2.cli.utils.pprint import echo_pair
from .command import Command
from .utils import update_termination_protection
and context including class names, function names, and sometimes code from other files:
# Path: awscfncli2/cli/utils/common.py
# def is_not_rate_limited_exception(e):
# return not is_rate_limited_exception(e)
#
# def is_rate_limited_exception(e):
# if isinstance(e, (botocore.exceptions.ClientError, botocore.exceptions.WaiterError)):
# return 'Rate exceeded' in str(e)
# else:
# return False
#
# Path: awscfncli2/cli/utils/pprint.py
# def echo_pair(key, value=None, indent=0,
# value_style=None, key_style=None,
# sep=': '):
# """Pretty print a key value pair
# :param key: The key
# :param value: The value
# :param indent: Number of leading spaces
# :param value_style: click.style parameters of value as a dict, default is none
# :param key_style: click.style parameters of value as a dict, default is bold text
# :param sep: separator between key and value
# """
# assert key
# key = ' ' * indent + key + sep
# if key_style is None:
# click.secho(key, bold=False, nl=False)
# else:
# click.secho(key, nl=False, **key_style)
#
# if value is None:
# click.echo('')
# else:
#
# if value_style is None:
# click.echo(value)
# else:
# click.secho(value, **value_style)
#
# Path: awscfncli2/runner/commands/command.py
# class Command(object):
# SKIP_UPDATE_REFERENCES = False
#
# def __init__(self, pretty_printer, options):
# assert isinstance(pretty_printer, StackPrettyPrinter)
# self.ppt = pretty_printer
# self.options = options
#
# def run(self, stack_context):
# raise NotImplementedError
#
# Path: awscfncli2/runner/commands/utils.py
# def update_termination_protection(session,
# termination_protection,
# stack_name,
# ppt):
# """Update termination protection on a stack"""
#
# if termination_protection is None:
# # don't care, don't change
# return
#
# client = session.client('cloudformation')
#
# if termination_protection:
# ppt.secho('Enabling TerminationProtection')
# else:
# ppt.secho('Disabling TerminationProtection', fg='red')
#
# client.update_termination_protection(
# StackName=stack_name,
# EnableTerminationProtection=termination_protection)
. Output only the next line. | ) |
Here is a snippet: <|code_start|> termination_protection = parameters.pop(
'EnableTerminationProtection', None)
self.ppt.pprint_parameters(parameters)
# create changeset
echo_pair('ChangeSet Name', changeset_name)
echo_pair('ChangeSet Type', changeset_type)
result = self.create_change_set(client, parameters)
changeset_id = result['Id']
echo_pair('ChangeSet ARN', changeset_id)
self.ppt.wait_until_changset_complete(client, changeset_id)
result = self.describe_change_set(client, changeset_name, parameters)
self.ppt.pprint_changeset(result)
# termination protection should be set after the creation of stack
# or changeset
update_termination_protection(session,
termination_protection,
parameters['StackName'],
self.ppt)
# check whether changeset is executable
if result['Status'] not in ('AVAILABLE', 'CREATE_COMPLETE'):
self.ppt.secho('ChangeSet not executable.', fg='red')
return
<|code_end|>
. Write the next line using the current file imports:
import uuid
import backoff
import botocore.exceptions
from collections import namedtuple
from awscfncli2.cli.utils.common import is_not_rate_limited_exception, is_rate_limited_exception
from awscfncli2.cli.utils.pprint import echo_pair
from .command import Command
from .utils import update_termination_protection
and context from other files:
# Path: awscfncli2/cli/utils/common.py
# def is_not_rate_limited_exception(e):
# return not is_rate_limited_exception(e)
#
# def is_rate_limited_exception(e):
# if isinstance(e, (botocore.exceptions.ClientError, botocore.exceptions.WaiterError)):
# return 'Rate exceeded' in str(e)
# else:
# return False
#
# Path: awscfncli2/cli/utils/pprint.py
# def echo_pair(key, value=None, indent=0,
# value_style=None, key_style=None,
# sep=': '):
# """Pretty print a key value pair
# :param key: The key
# :param value: The value
# :param indent: Number of leading spaces
# :param value_style: click.style parameters of value as a dict, default is none
# :param key_style: click.style parameters of value as a dict, default is bold text
# :param sep: separator between key and value
# """
# assert key
# key = ' ' * indent + key + sep
# if key_style is None:
# click.secho(key, bold=False, nl=False)
# else:
# click.secho(key, nl=False, **key_style)
#
# if value is None:
# click.echo('')
# else:
#
# if value_style is None:
# click.echo(value)
# else:
# click.secho(value, **value_style)
#
# Path: awscfncli2/runner/commands/command.py
# class Command(object):
# SKIP_UPDATE_REFERENCES = False
#
# def __init__(self, pretty_printer, options):
# assert isinstance(pretty_printer, StackPrettyPrinter)
# self.ppt = pretty_printer
# self.options = options
#
# def run(self, stack_context):
# raise NotImplementedError
#
# Path: awscfncli2/runner/commands/utils.py
# def update_termination_protection(session,
# termination_protection,
# stack_name,
# ppt):
# """Update termination protection on a stack"""
#
# if termination_protection is None:
# # don't care, don't change
# return
#
# client = session.client('cloudformation')
#
# if termination_protection:
# ppt.secho('Enabling TerminationProtection')
# else:
# ppt.secho('Disabling TerminationProtection', fg='red')
#
# client.update_termination_protection(
# StackName=stack_name,
# EnableTerminationProtection=termination_protection)
, which may include functions, classes, or code. Output only the next line. | if self.options.confirm: |
Here is a snippet: <|code_start|> def describe_change_set(self, client, changeset_name, parameters):
return client.describe_change_set(
ChangeSetName=changeset_name,
StackName=parameters['StackName'],
)
@backoff.on_exception(backoff.expo, botocore.exceptions.ClientError, max_tries=10,
giveup=is_not_rate_limited_exception)
def check_changeset_type(self, client, parameters):
try:
# check whether stack is already created.
status = client.describe_stacks(StackName=parameters['StackName'])
stack_status = status['Stacks'][0]['StackStatus']
except botocore.exceptions.ClientError as e:
if is_rate_limited_exception(e):
# stack might exist but we got Throttling error, retry is needed so rerasing exception
raise
# stack not yet created
is_new_stack = True
changeset_type = 'CREATE'
else:
if stack_status == 'REVIEW_IN_PROGRESS':
# first ChangeSet execution failed, create "new stack" changeset again
is_new_stack = True
changeset_type = 'CREATE'
else:
# updating an existing stack
is_new_stack = False
changeset_type = 'UPDATE'
<|code_end|>
. Write the next line using the current file imports:
import uuid
import backoff
import botocore.exceptions
from collections import namedtuple
from awscfncli2.cli.utils.common import is_not_rate_limited_exception, is_rate_limited_exception
from awscfncli2.cli.utils.pprint import echo_pair
from .command import Command
from .utils import update_termination_protection
and context from other files:
# Path: awscfncli2/cli/utils/common.py
# def is_not_rate_limited_exception(e):
# return not is_rate_limited_exception(e)
#
# def is_rate_limited_exception(e):
# if isinstance(e, (botocore.exceptions.ClientError, botocore.exceptions.WaiterError)):
# return 'Rate exceeded' in str(e)
# else:
# return False
#
# Path: awscfncli2/cli/utils/pprint.py
# def echo_pair(key, value=None, indent=0,
# value_style=None, key_style=None,
# sep=': '):
# """Pretty print a key value pair
# :param key: The key
# :param value: The value
# :param indent: Number of leading spaces
# :param value_style: click.style parameters of value as a dict, default is none
# :param key_style: click.style parameters of value as a dict, default is bold text
# :param sep: separator between key and value
# """
# assert key
# key = ' ' * indent + key + sep
# if key_style is None:
# click.secho(key, bold=False, nl=False)
# else:
# click.secho(key, nl=False, **key_style)
#
# if value is None:
# click.echo('')
# else:
#
# if value_style is None:
# click.echo(value)
# else:
# click.secho(value, **value_style)
#
# Path: awscfncli2/runner/commands/command.py
# class Command(object):
# SKIP_UPDATE_REFERENCES = False
#
# def __init__(self, pretty_printer, options):
# assert isinstance(pretty_printer, StackPrettyPrinter)
# self.ppt = pretty_printer
# self.options = options
#
# def run(self, stack_context):
# raise NotImplementedError
#
# Path: awscfncli2/runner/commands/utils.py
# def update_termination_protection(session,
# termination_protection,
# stack_name,
# ppt):
# """Update termination protection on a stack"""
#
# if termination_protection is None:
# # don't care, don't change
# return
#
# client = session.client('cloudformation')
#
# if termination_protection:
# ppt.secho('Enabling TerminationProtection')
# else:
# ppt.secho('Disabling TerminationProtection', fg='red')
#
# client.update_termination_protection(
# StackName=stack_name,
# EnableTerminationProtection=termination_protection)
, which may include functions, classes, or code. Output only the next line. | return changeset_type, is_new_stack |
Predict the next line after this snippet: <|code_start|>
self.ppt.pprint_parameters(parameters)
# create changeset
echo_pair('ChangeSet Name', changeset_name)
echo_pair('ChangeSet Type', changeset_type)
result = self.create_change_set(client, parameters)
changeset_id = result['Id']
echo_pair('ChangeSet ARN', changeset_id)
self.ppt.wait_until_changset_complete(client, changeset_id)
result = self.describe_change_set(client, changeset_name, parameters)
self.ppt.pprint_changeset(result)
# termination protection should be set after the creation of stack
# or changeset
update_termination_protection(session,
termination_protection,
parameters['StackName'],
self.ppt)
# check whether changeset is executable
if result['Status'] not in ('AVAILABLE', 'CREATE_COMPLETE'):
self.ppt.secho('ChangeSet not executable.', fg='red')
return
if self.options.confirm:
if self.options.no_wait:
<|code_end|>
using the current file's imports:
import uuid
import backoff
import botocore.exceptions
from collections import namedtuple
from awscfncli2.cli.utils.common import is_not_rate_limited_exception, is_rate_limited_exception
from awscfncli2.cli.utils.pprint import echo_pair
from .command import Command
from .utils import update_termination_protection
and any relevant context from other files:
# Path: awscfncli2/cli/utils/common.py
# def is_not_rate_limited_exception(e):
# return not is_rate_limited_exception(e)
#
# def is_rate_limited_exception(e):
# if isinstance(e, (botocore.exceptions.ClientError, botocore.exceptions.WaiterError)):
# return 'Rate exceeded' in str(e)
# else:
# return False
#
# Path: awscfncli2/cli/utils/pprint.py
# def echo_pair(key, value=None, indent=0,
# value_style=None, key_style=None,
# sep=': '):
# """Pretty print a key value pair
# :param key: The key
# :param value: The value
# :param indent: Number of leading spaces
# :param value_style: click.style parameters of value as a dict, default is none
# :param key_style: click.style parameters of value as a dict, default is bold text
# :param sep: separator between key and value
# """
# assert key
# key = ' ' * indent + key + sep
# if key_style is None:
# click.secho(key, bold=False, nl=False)
# else:
# click.secho(key, nl=False, **key_style)
#
# if value is None:
# click.echo('')
# else:
#
# if value_style is None:
# click.echo(value)
# else:
# click.secho(value, **value_style)
#
# Path: awscfncli2/runner/commands/command.py
# class Command(object):
# SKIP_UPDATE_REFERENCES = False
#
# def __init__(self, pretty_printer, options):
# assert isinstance(pretty_printer, StackPrettyPrinter)
# self.ppt = pretty_printer
# self.options = options
#
# def run(self, stack_context):
# raise NotImplementedError
#
# Path: awscfncli2/runner/commands/utils.py
# def update_termination_protection(session,
# termination_protection,
# stack_name,
# ppt):
# """Update termination protection on a stack"""
#
# if termination_protection is None:
# # don't care, don't change
# return
#
# client = session.client('cloudformation')
#
# if termination_protection:
# ppt.secho('Enabling TerminationProtection')
# else:
# ppt.secho('Disabling TerminationProtection', fg='red')
#
# client.update_termination_protection(
# StackName=stack_name,
# EnableTerminationProtection=termination_protection)
. Output only the next line. | return |
Predict the next line for this snippet: <|code_start|> parameters.pop('TemplateURL', None)
parameters['UsePreviousTemplate'] = True
else:
stack_context.run_packaging()
# create cfn client
client = session.client('cloudformation')
# generate a unique changeset name
changeset_name = '%s-%s' % \
(parameters['StackName'], str(uuid.uuid1()))
# get changeset type: CREATE or UPDATE
changeset_type, is_new_stack = self.check_changeset_type(client,
parameters)
# prepare stack parameters
parameters['ChangeSetName'] = changeset_name
parameters['ChangeSetType'] = changeset_type
parameters.pop('StackPolicyBody', None)
parameters.pop('StackPolicyURL', None)
termination_protection = parameters.pop(
'EnableTerminationProtection', None)
self.ppt.pprint_parameters(parameters)
# create changeset
echo_pair('ChangeSet Name', changeset_name)
echo_pair('ChangeSet Type', changeset_type)
<|code_end|>
with the help of current file imports:
import uuid
import backoff
import botocore.exceptions
from collections import namedtuple
from awscfncli2.cli.utils.common import is_not_rate_limited_exception, is_rate_limited_exception
from awscfncli2.cli.utils.pprint import echo_pair
from .command import Command
from .utils import update_termination_protection
and context from other files:
# Path: awscfncli2/cli/utils/common.py
# def is_not_rate_limited_exception(e):
# return not is_rate_limited_exception(e)
#
# def is_rate_limited_exception(e):
# if isinstance(e, (botocore.exceptions.ClientError, botocore.exceptions.WaiterError)):
# return 'Rate exceeded' in str(e)
# else:
# return False
#
# Path: awscfncli2/cli/utils/pprint.py
# def echo_pair(key, value=None, indent=0,
# value_style=None, key_style=None,
# sep=': '):
# """Pretty print a key value pair
# :param key: The key
# :param value: The value
# :param indent: Number of leading spaces
# :param value_style: click.style parameters of value as a dict, default is none
# :param key_style: click.style parameters of value as a dict, default is bold text
# :param sep: separator between key and value
# """
# assert key
# key = ' ' * indent + key + sep
# if key_style is None:
# click.secho(key, bold=False, nl=False)
# else:
# click.secho(key, nl=False, **key_style)
#
# if value is None:
# click.echo('')
# else:
#
# if value_style is None:
# click.echo(value)
# else:
# click.secho(value, **value_style)
#
# Path: awscfncli2/runner/commands/command.py
# class Command(object):
# SKIP_UPDATE_REFERENCES = False
#
# def __init__(self, pretty_printer, options):
# assert isinstance(pretty_printer, StackPrettyPrinter)
# self.ppt = pretty_printer
# self.options = options
#
# def run(self, stack_context):
# raise NotImplementedError
#
# Path: awscfncli2/runner/commands/utils.py
# def update_termination_protection(session,
# termination_protection,
# stack_name,
# ppt):
# """Update termination protection on a stack"""
#
# if termination_protection is None:
# # don't care, don't change
# return
#
# client = session.client('cloudformation')
#
# if termination_protection:
# ppt.secho('Enabling TerminationProtection')
# else:
# ppt.secho('Disabling TerminationProtection', fg='red')
#
# client.update_termination_protection(
# StackName=stack_name,
# EnableTerminationProtection=termination_protection)
, which may contain function names, class names, or code. Output only the next line. | result = self.create_change_set(client, parameters) |
Given snippet: <|code_start|># -*- encoding: utf-8 -*-
@click.command()
@click.option('--no-wait', '-w', is_flag=True, default=False,
help='Exit immediately after operation is started.')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import click
from awscfncli2.cli.context import Context
from awscfncli2.cli.utils.deco import command_exception_handler
from awscfncli2.runner.commands.drift_detect_command import DriftDetectOptions, \
DriftDetectCommand
and context:
# Path: awscfncli2/cli/context.py
# class Context:
# """Click context object
#
#
# # Manage config parsing, transforming deployment process.
# """
#
# def __init__(self,
# config_filename: str,
# artifact_store: str,
# pretty_printer: StackPrettyPrinter,
# stack_selector: StackSelector,
# boto3_profile: Boto3Profile,
# builder,
# ):
# # simple
# self._config_filename: str = config_filename
# self._artifact_store: str = artifact_store
# # complex
# self._pretty_printer: StackPrettyPrinter = pretty_printer
# self._stack_selector = stack_selector
# self._boto3_profile = boto3_profile
# # lazy-loaded
# self._deployments = None
# self._command_runner = None
#
# # internals
# self.__builder = builder
# self.__lock = threading.RLock()
#
# @property
# def config_filename(self):
# """Config file name"""
# return self._config_filename
#
# @property
# def stack_selector(self):
# """Stack selector"""
# return self._stack_selector
#
# @property
# def boto3_profile(self):
# """Boto3 session profiles"""
# return self._boto3_profile
#
# @property
# def verbosity(self):
# """Verbosity level"""
# return self._pretty_printer.verbosity
#
# @property
# def ppt(self):
# """CLI pretty printer"""
# return self._pretty_printer
#
# @property
# def deployments(self):
# """Stack deployment spec."""
# # XXX: Lazy-loading so we don't get error if user is just looking at help
# with self.__lock:
# if self._deployments is None:
# self._deployments = self.__builder.parse_config(self.config_filename)
# return self._deployments
#
# @property
# def runner(self):
# """Command runner."""
# with self.__lock:
# if self._command_runner is None:
# self._command_runner = self.__builder.build_runner(
# self.boto3_profile,
# self._artifact_store,
# self.deployments,
# self.stack_selector,
# self.ppt
# )
# return self._command_runner
#
# Path: awscfncli2/cli/utils/deco.py
# def command_exception_handler(f):
# """Capture and pretty print exceptions."""
#
# @wraps(f)
# def wrapper(ctx, *args, **kwargs):
# try:
# return f(ctx, *args, **kwargs)
# except (botocore.exceptions.ClientError,
# botocore.exceptions.BotoCoreError,
# ) as e:
# if ctx.obj.verbosity > 0:
# click.secho(traceback.format_exc(), fg='red')
# else:
# click.secho(str(e), fg='red')
# raise click.Abort
# except ConfigError as e:
# click.secho(str(e), fg='red')
# if ctx.obj.verbosity > 0:
# traceback.print_exc()
# raise click.Abort
#
# return wrapper
#
# Path: awscfncli2/runner/commands/drift_detect_command.py
# class DriftDetectOptions(namedtuple('DriftDetectOptions',
# ['no_wait', ])):
# pass
#
# class DriftDetectCommand(Command):
# SKIP_UPDATE_REFERENCES = True
#
# def run(self, stack_context):
# # stack contexts
# session = stack_context.session
# parameters = stack_context.parameters
# metadata = stack_context.metadata
#
# self.ppt.pprint_stack_name(stack_context.stack_key,
# parameters['StackName'],
# 'Detecting drift of ')
#
# # create boto3 client
# self.ppt.pprint_session(session)
# self.ppt.pprint_parameters(parameters)
#
# client = session.client('cloudformation')
#
# # call boto3
#
# response = client.detect_stack_drift(StackName=parameters['StackName'])
# drift_detection_id = response['StackDriftDetectionId']
#
# # wait until delete complete
# if self.options.no_wait:
# self.ppt.secho('Drift detect started.')
# else:
# # create custom waiter
# waiter = botocore.waiter.create_waiter_with_client(
# 'DriftDetectionComplete', waiter_model, client)
# waiter.wait(StackDriftDetectionId=drift_detection_id)
#
# # self.ppt.secho('Drift detection complete.', fg='green')
#
# result = client.describe_stack_drift_detection_status(
# StackDriftDetectionId=drift_detection_id)
#
# self.ppt.pprint_stack_drift(result)
#
# if result['DriftedStackResourceCount'] > 0:
# self.ppt.secho('Use `drift diff` command to show drifted resources.')
which might include code, classes, or functions. Output only the next line. | @click.pass_context |
Next line prediction: <|code_start|># -*- encoding: utf-8 -*-
@click.command()
@click.option('--no-wait', '-w', is_flag=True, default=False,
help='Exit immediately after operation is started.')
<|code_end|>
. Use current file imports:
(import click
from awscfncli2.cli.context import Context
from awscfncli2.cli.utils.deco import command_exception_handler
from awscfncli2.runner.commands.drift_detect_command import DriftDetectOptions, \
DriftDetectCommand)
and context including class names, function names, or small code snippets from other files:
# Path: awscfncli2/cli/context.py
# class Context:
# """Click context object
#
#
# # Manage config parsing, transforming deployment process.
# """
#
# def __init__(self,
# config_filename: str,
# artifact_store: str,
# pretty_printer: StackPrettyPrinter,
# stack_selector: StackSelector,
# boto3_profile: Boto3Profile,
# builder,
# ):
# # simple
# self._config_filename: str = config_filename
# self._artifact_store: str = artifact_store
# # complex
# self._pretty_printer: StackPrettyPrinter = pretty_printer
# self._stack_selector = stack_selector
# self._boto3_profile = boto3_profile
# # lazy-loaded
# self._deployments = None
# self._command_runner = None
#
# # internals
# self.__builder = builder
# self.__lock = threading.RLock()
#
# @property
# def config_filename(self):
# """Config file name"""
# return self._config_filename
#
# @property
# def stack_selector(self):
# """Stack selector"""
# return self._stack_selector
#
# @property
# def boto3_profile(self):
# """Boto3 session profiles"""
# return self._boto3_profile
#
# @property
# def verbosity(self):
# """Verbosity level"""
# return self._pretty_printer.verbosity
#
# @property
# def ppt(self):
# """CLI pretty printer"""
# return self._pretty_printer
#
# @property
# def deployments(self):
# """Stack deployment spec."""
# # XXX: Lazy-loading so we don't get error if user is just looking at help
# with self.__lock:
# if self._deployments is None:
# self._deployments = self.__builder.parse_config(self.config_filename)
# return self._deployments
#
# @property
# def runner(self):
# """Command runner."""
# with self.__lock:
# if self._command_runner is None:
# self._command_runner = self.__builder.build_runner(
# self.boto3_profile,
# self._artifact_store,
# self.deployments,
# self.stack_selector,
# self.ppt
# )
# return self._command_runner
#
# Path: awscfncli2/cli/utils/deco.py
# def command_exception_handler(f):
# """Capture and pretty print exceptions."""
#
# @wraps(f)
# def wrapper(ctx, *args, **kwargs):
# try:
# return f(ctx, *args, **kwargs)
# except (botocore.exceptions.ClientError,
# botocore.exceptions.BotoCoreError,
# ) as e:
# if ctx.obj.verbosity > 0:
# click.secho(traceback.format_exc(), fg='red')
# else:
# click.secho(str(e), fg='red')
# raise click.Abort
# except ConfigError as e:
# click.secho(str(e), fg='red')
# if ctx.obj.verbosity > 0:
# traceback.print_exc()
# raise click.Abort
#
# return wrapper
#
# Path: awscfncli2/runner/commands/drift_detect_command.py
# class DriftDetectOptions(namedtuple('DriftDetectOptions',
# ['no_wait', ])):
# pass
#
# class DriftDetectCommand(Command):
# SKIP_UPDATE_REFERENCES = True
#
# def run(self, stack_context):
# # stack contexts
# session = stack_context.session
# parameters = stack_context.parameters
# metadata = stack_context.metadata
#
# self.ppt.pprint_stack_name(stack_context.stack_key,
# parameters['StackName'],
# 'Detecting drift of ')
#
# # create boto3 client
# self.ppt.pprint_session(session)
# self.ppt.pprint_parameters(parameters)
#
# client = session.client('cloudformation')
#
# # call boto3
#
# response = client.detect_stack_drift(StackName=parameters['StackName'])
# drift_detection_id = response['StackDriftDetectionId']
#
# # wait until delete complete
# if self.options.no_wait:
# self.ppt.secho('Drift detect started.')
# else:
# # create custom waiter
# waiter = botocore.waiter.create_waiter_with_client(
# 'DriftDetectionComplete', waiter_model, client)
# waiter.wait(StackDriftDetectionId=drift_detection_id)
#
# # self.ppt.secho('Drift detection complete.', fg='green')
#
# result = client.describe_stack_drift_detection_status(
# StackDriftDetectionId=drift_detection_id)
#
# self.ppt.pprint_stack_drift(result)
#
# if result['DriftedStackResourceCount'] > 0:
# self.ppt.secho('Use `drift diff` command to show drifted resources.')
. Output only the next line. | @click.pass_context |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
class ConfigError(Exception):
pass
class ConfigParser(object):
def get_format(self, config, **context):
# inspect version
version = config.get('Version')
config_format = load_format(version)
return config_format(**context)
def parse(self, filename):
basedir = os.path.dirname(filename)
with open(filename) as fp:
config = yaml.safe_load(fp)
if config is None:
config = dict()
fmt = self.get_format(config, basedir=basedir)
<|code_end|>
. Use current file imports:
import os
import yaml
import logging
from .formats import load_format
and context (classes, functions, or code) from other files:
# Path: awscfncli2/config/formats.py
# def load_format(version):
# if version == 3:
# return FormatV3
# elif version == 2:
# return FormatV2
# elif version == 1 or version is None:
# return FormatV1
# else:
# raise FormatError('Unspported config version {}'.format(version))
. Output only the next line. | fmt.validate(config) |
Next line prediction: <|code_start|>
@click.command()
@click.option('--no-wait', '-w', is_flag=True, default=False,
help='Exit immediately after operation is started.')
@click.pass_context
@command_exception_handler
def cancel(ctx, no_wait):
"""Cancel current stack update.
Only works if stack being canceled is in "UPDATING" status."""
assert isinstance(ctx.obj, Context)
for stack_context in ctx.obj.runner.contexts:
stack_context.make_boto3_parameters()
ctx.obj.ppt.pprint_stack_name(
stack_context.stack_key,
stack_context.parameters['StackName'],
'Canceling update '
)
session = stack_context.session
client = session.client('cloudformation')
try:
client.cancel_update_stack(StackName=stack_context.parameters['StackName'])
except botocore.exceptions.ClientError as ex:
error = ex.response.get('Error', {})
error_message = error.get('Message', 'Unknown')
if error_message.endswith(
<|code_end|>
. Use current file imports:
(import botocore.exceptions
import click
from awscfncli2.cli.context import Context
from awscfncli2.cli.utils.deco import command_exception_handler)
and context including class names, function names, or small code snippets from other files:
# Path: awscfncli2/cli/context.py
# class Context:
# """Click context object
#
#
# # Manage config parsing, transforming deployment process.
# """
#
# def __init__(self,
# config_filename: str,
# artifact_store: str,
# pretty_printer: StackPrettyPrinter,
# stack_selector: StackSelector,
# boto3_profile: Boto3Profile,
# builder,
# ):
# # simple
# self._config_filename: str = config_filename
# self._artifact_store: str = artifact_store
# # complex
# self._pretty_printer: StackPrettyPrinter = pretty_printer
# self._stack_selector = stack_selector
# self._boto3_profile = boto3_profile
# # lazy-loaded
# self._deployments = None
# self._command_runner = None
#
# # internals
# self.__builder = builder
# self.__lock = threading.RLock()
#
# @property
# def config_filename(self):
# """Config file name"""
# return self._config_filename
#
# @property
# def stack_selector(self):
# """Stack selector"""
# return self._stack_selector
#
# @property
# def boto3_profile(self):
# """Boto3 session profiles"""
# return self._boto3_profile
#
# @property
# def verbosity(self):
# """Verbosity level"""
# return self._pretty_printer.verbosity
#
# @property
# def ppt(self):
# """CLI pretty printer"""
# return self._pretty_printer
#
# @property
# def deployments(self):
# """Stack deployment spec."""
# # XXX: Lazy-loading so we don't get error if user is just looking at help
# with self.__lock:
# if self._deployments is None:
# self._deployments = self.__builder.parse_config(self.config_filename)
# return self._deployments
#
# @property
# def runner(self):
# """Command runner."""
# with self.__lock:
# if self._command_runner is None:
# self._command_runner = self.__builder.build_runner(
# self.boto3_profile,
# self._artifact_store,
# self.deployments,
# self.stack_selector,
# self.ppt
# )
# return self._command_runner
#
# Path: awscfncli2/cli/utils/deco.py
# def command_exception_handler(f):
# """Capture and pretty print exceptions."""
#
# @wraps(f)
# def wrapper(ctx, *args, **kwargs):
# try:
# return f(ctx, *args, **kwargs)
# except (botocore.exceptions.ClientError,
# botocore.exceptions.BotoCoreError,
# ) as e:
# if ctx.obj.verbosity > 0:
# click.secho(traceback.format_exc(), fg='red')
# else:
# click.secho(str(e), fg='red')
# raise click.Abort
# except ConfigError as e:
# click.secho(str(e), fg='red')
# if ctx.obj.verbosity > 0:
# traceback.print_exc()
# raise click.Abort
#
# return wrapper
. Output only the next line. | 'CancelUpdateStack cannot be called from current stack status'): |
Continue the code snippet: <|code_start|># -*- encoding: utf-8 -*-
@click.command()
@click.option('--no-wait', '-w', is_flag=True, default=False,
help='Exit immediately after operation is started.')
@click.pass_context
@command_exception_handler
<|code_end|>
. Use current file imports:
import botocore.exceptions
import click
from awscfncli2.cli.context import Context
from awscfncli2.cli.utils.deco import command_exception_handler
and context (classes, functions, or code) from other files:
# Path: awscfncli2/cli/context.py
# class Context:
# """Click context object
#
#
# # Manage config parsing, transforming deployment process.
# """
#
# def __init__(self,
# config_filename: str,
# artifact_store: str,
# pretty_printer: StackPrettyPrinter,
# stack_selector: StackSelector,
# boto3_profile: Boto3Profile,
# builder,
# ):
# # simple
# self._config_filename: str = config_filename
# self._artifact_store: str = artifact_store
# # complex
# self._pretty_printer: StackPrettyPrinter = pretty_printer
# self._stack_selector = stack_selector
# self._boto3_profile = boto3_profile
# # lazy-loaded
# self._deployments = None
# self._command_runner = None
#
# # internals
# self.__builder = builder
# self.__lock = threading.RLock()
#
# @property
# def config_filename(self):
# """Config file name"""
# return self._config_filename
#
# @property
# def stack_selector(self):
# """Stack selector"""
# return self._stack_selector
#
# @property
# def boto3_profile(self):
# """Boto3 session profiles"""
# return self._boto3_profile
#
# @property
# def verbosity(self):
# """Verbosity level"""
# return self._pretty_printer.verbosity
#
# @property
# def ppt(self):
# """CLI pretty printer"""
# return self._pretty_printer
#
# @property
# def deployments(self):
# """Stack deployment spec."""
# # XXX: Lazy-loading so we don't get error if user is just looking at help
# with self.__lock:
# if self._deployments is None:
# self._deployments = self.__builder.parse_config(self.config_filename)
# return self._deployments
#
# @property
# def runner(self):
# """Command runner."""
# with self.__lock:
# if self._command_runner is None:
# self._command_runner = self.__builder.build_runner(
# self.boto3_profile,
# self._artifact_store,
# self.deployments,
# self.stack_selector,
# self.ppt
# )
# return self._command_runner
#
# Path: awscfncli2/cli/utils/deco.py
# def command_exception_handler(f):
# """Capture and pretty print exceptions."""
#
# @wraps(f)
# def wrapper(ctx, *args, **kwargs):
# try:
# return f(ctx, *args, **kwargs)
# except (botocore.exceptions.ClientError,
# botocore.exceptions.BotoCoreError,
# ) as e:
# if ctx.obj.verbosity > 0:
# click.secho(traceback.format_exc(), fg='red')
# else:
# click.secho(str(e), fg='red')
# raise click.Abort
# except ConfigError as e:
# click.secho(str(e), fg='red')
# if ctx.obj.verbosity > 0:
# traceback.print_exc()
# raise click.Abort
#
# return wrapper
. Output only the next line. | def cancel(ctx, no_wait): |
Predict the next line for this snippet: <|code_start|> def example_tester_mean(self, solver="cbc", solver_io=None):
model = self.model_runner(solver=solver, solver_io=solver_io, how="mean")
# Full 1-hourly model run: 22312488.670967
assert float(model.results.cost.sum()) == approx(22172253.328)
# Full 1-hourly model run: 0.296973
assert float(
model.results.systemwide_levelised_cost.loc[
{"carriers": "power", "techs": "battery"}
].item()
) == approx(0.127783, abs=0.000001)
# Full 1-hourly model run: 0.064362
assert float(
model.results.systemwide_capacity_factor.loc[dict(carriers="power")]
.to_series()
.T["battery"]
) == approx(0.044458, abs=0.000001)
def example_tester_storage_inter_cluster(self):
model = self.model_runner(storage_inter_cluster=True)
# Full 1-hourly model run: 22312488.670967
assert float(model.results.cost.sum()) == approx(21825515.304)
# Full 1-hourly model run: 0.296973
assert float(
model.results.systemwide_levelised_cost.loc[
{"carriers": "power", "techs": "battery"}
].item()
<|code_end|>
with the help of current file imports:
from calliope import exceptions
from pytest import approx
from calliope.test.common.util import check_error_or_warning
import shutil
import pytest
import pandas as pd
import numpy as np
import calliope
and context from other files:
# Path: calliope/exceptions.py
# def _formatwarning(message, category, filename, lineno, line=None):
# def warn(message, _class=ModelWarning):
# def print_warnings_and_raise_errors(warnings=None, errors=None):
# class ModelError(Exception):
# class BackendError(Exception):
# class ModelWarning(Warning):
# class BackendWarning(Warning):
#
# Path: calliope/test/common/util.py
# def check_error_or_warning(error_warning, test_string_or_strings):
# if hasattr(error_warning, "list"):
# output = ",".join(
# str(error_warning.list[i]) for i in range(len(error_warning.list))
# )
# else:
# output = str(error_warning.value)
#
# if isinstance(test_string_or_strings, list):
# result = all(test_string in output for test_string in test_string_or_strings)
# else:
# result = test_string_or_strings in output
#
# return result
, which may contain function names, class names, or code. Output only the next line. | ) == approx(0.100760, abs=0.000001) |
Given the following code snippet before the placeholder: <|code_start|>
# Full 1-hourly model run: 0.296973
assert float(
model.results.systemwide_levelised_cost.loc[
{"carriers": "power", "techs": "battery"}
].item()
) == approx(0.122564, abs=0.000001)
# Full 1-hourly model run: 0.064362
assert float(
model.results.systemwide_capacity_factor.loc[
{"carriers": "power", "techs": "battery"}
].item()
) == approx(0.075145, abs=0.000001)
@pytest.mark.xfail(
reason="Inter-cluster things are probably badly broken in myriad ways"
)
def test_storage_inter_cluster_no_storage(self):
with pytest.warns(calliope.exceptions.ModelWarning) as excinfo:
self.model_runner(storage_inter_cluster=True, storage=False)
expected_warnings = [
"Tech battery was removed by setting ``exists: False``",
"Tech csp was removed by setting ``exists: False``",
]
assert check_error_or_warning(excinfo, expected_warnings)
class TestUrbanScaleExampleModelSenseChecks:
<|code_end|>
, predict the next line using imports from the current file:
from calliope import exceptions
from pytest import approx
from calliope.test.common.util import check_error_or_warning
import shutil
import pytest
import pandas as pd
import numpy as np
import calliope
and context including class names, function names, and sometimes code from other files:
# Path: calliope/exceptions.py
# def _formatwarning(message, category, filename, lineno, line=None):
# def warn(message, _class=ModelWarning):
# def print_warnings_and_raise_errors(warnings=None, errors=None):
# class ModelError(Exception):
# class BackendError(Exception):
# class ModelWarning(Warning):
# class BackendWarning(Warning):
#
# Path: calliope/test/common/util.py
# def check_error_or_warning(error_warning, test_string_or_strings):
# if hasattr(error_warning, "list"):
# output = ",".join(
# str(error_warning.list[i]) for i in range(len(error_warning.list))
# )
# else:
# output = str(error_warning.value)
#
# if isinstance(test_string_or_strings, list):
# result = all(test_string in output for test_string in test_string_or_strings)
# else:
# result = test_string_or_strings in output
#
# return result
. Output only the next line. | def example_tester(self, resource_unit, solver="cbc", solver_io=None): |
Here is a snippet: <|code_start|>
calliope.set_log_verbosity("CRITICAL", include_solver_output=False)
assert logging.getLogger("calliope").getEffectiveLevel() == 50
assert logging.getLogger("py.warnings").getEffectiveLevel() == 50
assert (
logging.getLogger("calliope.backend.pyomo.model").getEffectiveLevel() == 50
)
calliope.set_log_verbosity()
assert logging.getLogger("calliope").getEffectiveLevel() == 20
assert logging.getLogger("py.warnings").getEffectiveLevel() == 20
assert (
logging.getLogger("calliope.backend.pyomo.model").getEffectiveLevel() == 10
)
def test_timing_log(self):
timings = {"model_creation": datetime.datetime.now()}
logger = logging.getLogger("calliope.testlogger")
# TODO: capture logging output and check that comment is in string
log_time(logger, timings, "test", comment="test_comment", level="info")
assert isinstance(timings["test"], datetime.datetime)
log_time(logger, timings, "test2", comment=None, level="info")
assert isinstance(timings["test2"], datetime.datetime)
# TODO: capture logging output and check that time_since_run_start is in the string
log_time(
<|code_end|>
. Write the next line using the current file imports:
import pytest # noqa: F401
import calliope
import logging
import datetime
import os
import tempfile
import xarray as xr
from calliope.core.util import dataset, observed_dict
from calliope.core.util.tools import memoize, memoize_instancemethod
from calliope.core.util.logging import log_time
from calliope.core.util.generate_runs import generate_runs
from calliope.test.common.util import (
python36_or_higher,
check_error_or_warning,
)
and context from other files:
# Path: calliope/core/util/dataset.py
# def reorganise_xarray_dimensions(data):
#
# Path: calliope/core/util/observed_dict.py
# class ObservedDict(dict):
# class UpdateObserverDict(ObservedDict):
# def __init__(self, initial_dict, initial_yaml_string, on_changed=None, flat=False):
# def __setitem__(self, key, value):
# def update(self, other=None, **kwargs):
# def notify(self, updated=None):
# def __init__(
# self,
# name,
# observer,
# initial_dict=None,
# initial_yaml_string=None,
# *args,
# **kwargs,
# ):
# def notify(self, updated=None):
#
# Path: calliope/core/util/tools.py
# def get_from_dict(data_dict, map_list):
# def apply_to_dict(data_dict, map_list, func, args):
# def __init__(self, func):
# def __get__(self, obj, objtype=None):
# def __call__(self, *args, **kw):
# def relative_path(base_path_file, path):
# def load_function(source):
# def plugin_load(name, builtin_module):
# class memoize_instancemethod(object):
#
# Path: calliope/core/util/logging.py
# def log_time(
# logger, timings, identifier, comment=None, level="info", time_since_run_start=False
# ):
# if comment is None:
# comment = identifier
#
# timings[identifier] = now = datetime.datetime.now()
#
# if time_since_run_start and "run_start" in timings:
# time_diff = now - timings["run_start"]
# comment += ". Time since start of model run: {}".format(time_diff)
#
# getattr(logger, level)(comment)
#
# Path: calliope/core/util/generate_runs.py
# def generate_runs(model_file, scenarios=None, additional_args=None, override_dict=None):
# """
# Returns a list of "calliope run" invocations.
#
# ``scenarios`` must be specified as either a semicolon-separated
# list of scenarios or a semicolon-separated list of comma-separated
# individual override combinations, such as:
#
# ``override1,override2;override1,override3;...``
#
# If ``scenarios`` is not given, use all scenarios in the model
# configuration, and if no scenarios given in the model configuration,
# uses all individual overrides, one by one.
#
# """
# if scenarios is None:
# config = AttrDict.from_yaml(model_file)
# if override_dict:
# override = AttrDict.from_yaml_string(override_dict)
# config.union(override, allow_override=True, allow_replacement=True)
#
# if "scenarios" in config:
# runs = config.scenarios.keys()
# else:
# runs = config.overrides.keys()
# else:
# runs = scenarios.split(";")
#
# commands = []
#
# # len(str(x)) gives us the number of digits in x, for padding
# i_string = "{:0>" + str(len(str(len(runs)))) + "d}"
#
# for i, run in enumerate(runs):
# cmd = (
# f"calliope run {model_file} --scenario {run} "
# f"--save_netcdf out_{i_string.format(i + 1)}_{run}.nc "
# ).strip()
#
# if override_dict:
# cmd = cmd + ' --override_dict="{}"'.format(override_dict)
#
# if additional_args:
# cmd = cmd + " " + additional_args
#
# commands.append(cmd)
#
# return commands
#
# Path: calliope/test/common/util.py
# def build_test_model(
# override_dict=None,
# scenario=None,
# model_file="model.yaml",
# timeseries_dataframes=None,
# ):
# def check_error_or_warning(error_warning, test_string_or_strings):
# def check_variable_exists(backend_model, constraint, variable, idx=None):
, which may include functions, classes, or code. Output only the next line. | logger, |
Given the following code snippet before the placeholder: <|code_start|> ("foo", None, None, {"foobar": {"baz": 2}}),
),
)
def test_set_item_observer(
self, observed_from_dict, observer, key1, key2, value, result
):
if key2 is None:
observed_from_dict[key1] = value
else:
observed_from_dict[key1][key2] = value
assert observer.attrs["test"] == self.as_yaml(result)
def test_update_observer(self, observed_from_dict, observer):
observed_from_dict.update({"baz": 4})
assert observer.attrs["test"] == self.as_yaml({"foobar": {"baz": 2}, "baz": 4})
def test_reinstate_observer(self, observed_from_dict, observer):
observer.attrs["test"] = "{}"
assert observer.attrs["test"] == "{}"
observed_from_dict["foo"] = 5
assert observer.attrs["test"] == self.as_yaml(
{"foo": 5, "foobar": {"baz": 2}, "baz": 4}
)
def test_model_config(self, model):
assert hasattr(model, "model_config")
assert "model_config" in model._model_data.attrs.keys()
assert model._model_data.attrs["model_config"] == self.as_yaml(
model.model_config, strip=True
<|code_end|>
, predict the next line using imports from the current file:
import pytest # noqa: F401
import calliope
import logging
import datetime
import os
import tempfile
import xarray as xr
from calliope.core.util import dataset, observed_dict
from calliope.core.util.tools import memoize, memoize_instancemethod
from calliope.core.util.logging import log_time
from calliope.core.util.generate_runs import generate_runs
from calliope.test.common.util import (
python36_or_higher,
check_error_or_warning,
)
and context including class names, function names, and sometimes code from other files:
# Path: calliope/core/util/dataset.py
# def reorganise_xarray_dimensions(data):
#
# Path: calliope/core/util/observed_dict.py
# class ObservedDict(dict):
# class UpdateObserverDict(ObservedDict):
# def __init__(self, initial_dict, initial_yaml_string, on_changed=None, flat=False):
# def __setitem__(self, key, value):
# def update(self, other=None, **kwargs):
# def notify(self, updated=None):
# def __init__(
# self,
# name,
# observer,
# initial_dict=None,
# initial_yaml_string=None,
# *args,
# **kwargs,
# ):
# def notify(self, updated=None):
#
# Path: calliope/core/util/tools.py
# def get_from_dict(data_dict, map_list):
# def apply_to_dict(data_dict, map_list, func, args):
# def __init__(self, func):
# def __get__(self, obj, objtype=None):
# def __call__(self, *args, **kw):
# def relative_path(base_path_file, path):
# def load_function(source):
# def plugin_load(name, builtin_module):
# class memoize_instancemethod(object):
#
# Path: calliope/core/util/logging.py
# def log_time(
# logger, timings, identifier, comment=None, level="info", time_since_run_start=False
# ):
# if comment is None:
# comment = identifier
#
# timings[identifier] = now = datetime.datetime.now()
#
# if time_since_run_start and "run_start" in timings:
# time_diff = now - timings["run_start"]
# comment += ". Time since start of model run: {}".format(time_diff)
#
# getattr(logger, level)(comment)
#
# Path: calliope/core/util/generate_runs.py
# def generate_runs(model_file, scenarios=None, additional_args=None, override_dict=None):
# """
# Returns a list of "calliope run" invocations.
#
# ``scenarios`` must be specified as either a semicolon-separated
# list of scenarios or a semicolon-separated list of comma-separated
# individual override combinations, such as:
#
# ``override1,override2;override1,override3;...``
#
# If ``scenarios`` is not given, use all scenarios in the model
# configuration, and if no scenarios given in the model configuration,
# uses all individual overrides, one by one.
#
# """
# if scenarios is None:
# config = AttrDict.from_yaml(model_file)
# if override_dict:
# override = AttrDict.from_yaml_string(override_dict)
# config.union(override, allow_override=True, allow_replacement=True)
#
# if "scenarios" in config:
# runs = config.scenarios.keys()
# else:
# runs = config.overrides.keys()
# else:
# runs = scenarios.split(";")
#
# commands = []
#
# # len(str(x)) gives us the number of digits in x, for padding
# i_string = "{:0>" + str(len(str(len(runs)))) + "d}"
#
# for i, run in enumerate(runs):
# cmd = (
# f"calliope run {model_file} --scenario {run} "
# f"--save_netcdf out_{i_string.format(i + 1)}_{run}.nc "
# ).strip()
#
# if override_dict:
# cmd = cmd + ' --override_dict="{}"'.format(override_dict)
#
# if additional_args:
# cmd = cmd + " " + additional_args
#
# commands.append(cmd)
#
# return commands
#
# Path: calliope/test/common/util.py
# def build_test_model(
# override_dict=None,
# scenario=None,
# model_file="model.yaml",
# timeseries_dataframes=None,
# ):
# def check_error_or_warning(error_warning, test_string_or_strings):
# def check_variable_exists(backend_model, constraint, variable, idx=None):
. Output only the next line. | ) |
Based on the snippet: <|code_start|> or (isinstance(v, dict) and len(v.keys()) > 0)
}
return calliope.AttrDict.to_yaml(calliope.AttrDict(_dict))
@pytest.fixture(scope="module")
def model(self):
return calliope.examples.national_scale()
@pytest.fixture(scope="module")
def observer(self):
return xr.Dataset()
@pytest.fixture(scope="module")
def observed_from_dict(self, observer):
initial_dict = {"foo": "bar", "foobar": {"baz": "fob"}}
return observed_dict.UpdateObserverDict(
initial_dict=initial_dict, name="test", observer=observer
)
@pytest.fixture(scope="module")
def observed_from_string(self, observer):
initial_dict = {"foo": "bar", "foobar": {"baz": "fob"}}
return observed_dict.UpdateObserverDict(
initial_yaml_string=self.as_yaml(initial_dict),
name="test_2",
observer=observer,
)
def test_initialise_observer(
self, observer, observed_from_dict, observed_from_string
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest # noqa: F401
import calliope
import logging
import datetime
import os
import tempfile
import xarray as xr
from calliope.core.util import dataset, observed_dict
from calliope.core.util.tools import memoize, memoize_instancemethod
from calliope.core.util.logging import log_time
from calliope.core.util.generate_runs import generate_runs
from calliope.test.common.util import (
python36_or_higher,
check_error_or_warning,
)
and context (classes, functions, sometimes code) from other files:
# Path: calliope/core/util/dataset.py
# def reorganise_xarray_dimensions(data):
#
# Path: calliope/core/util/observed_dict.py
# class ObservedDict(dict):
# class UpdateObserverDict(ObservedDict):
# def __init__(self, initial_dict, initial_yaml_string, on_changed=None, flat=False):
# def __setitem__(self, key, value):
# def update(self, other=None, **kwargs):
# def notify(self, updated=None):
# def __init__(
# self,
# name,
# observer,
# initial_dict=None,
# initial_yaml_string=None,
# *args,
# **kwargs,
# ):
# def notify(self, updated=None):
#
# Path: calliope/core/util/tools.py
# def get_from_dict(data_dict, map_list):
# def apply_to_dict(data_dict, map_list, func, args):
# def __init__(self, func):
# def __get__(self, obj, objtype=None):
# def __call__(self, *args, **kw):
# def relative_path(base_path_file, path):
# def load_function(source):
# def plugin_load(name, builtin_module):
# class memoize_instancemethod(object):
#
# Path: calliope/core/util/logging.py
# def log_time(
# logger, timings, identifier, comment=None, level="info", time_since_run_start=False
# ):
# if comment is None:
# comment = identifier
#
# timings[identifier] = now = datetime.datetime.now()
#
# if time_since_run_start and "run_start" in timings:
# time_diff = now - timings["run_start"]
# comment += ". Time since start of model run: {}".format(time_diff)
#
# getattr(logger, level)(comment)
#
# Path: calliope/core/util/generate_runs.py
# def generate_runs(model_file, scenarios=None, additional_args=None, override_dict=None):
# """
# Returns a list of "calliope run" invocations.
#
# ``scenarios`` must be specified as either a semicolon-separated
# list of scenarios or a semicolon-separated list of comma-separated
# individual override combinations, such as:
#
# ``override1,override2;override1,override3;...``
#
# If ``scenarios`` is not given, use all scenarios in the model
# configuration, and if no scenarios given in the model configuration,
# uses all individual overrides, one by one.
#
# """
# if scenarios is None:
# config = AttrDict.from_yaml(model_file)
# if override_dict:
# override = AttrDict.from_yaml_string(override_dict)
# config.union(override, allow_override=True, allow_replacement=True)
#
# if "scenarios" in config:
# runs = config.scenarios.keys()
# else:
# runs = config.overrides.keys()
# else:
# runs = scenarios.split(";")
#
# commands = []
#
# # len(str(x)) gives us the number of digits in x, for padding
# i_string = "{:0>" + str(len(str(len(runs)))) + "d}"
#
# for i, run in enumerate(runs):
# cmd = (
# f"calliope run {model_file} --scenario {run} "
# f"--save_netcdf out_{i_string.format(i + 1)}_{run}.nc "
# ).strip()
#
# if override_dict:
# cmd = cmd + ' --override_dict="{}"'.format(override_dict)
#
# if additional_args:
# cmd = cmd + " " + additional_args
#
# commands.append(cmd)
#
# return commands
#
# Path: calliope/test/common/util.py
# def build_test_model(
# override_dict=None,
# scenario=None,
# model_file="model.yaml",
# timeseries_dataframes=None,
# ):
# def check_error_or_warning(error_warning, test_string_or_strings):
# def check_variable_exists(backend_model, constraint, variable, idx=None):
. Output only the next line. | ): |
Here is a snippet: <|code_start|>
_MODEL_NATIONAL = os.path.join(
os.path.dirname(__file__), "..", "example_models", "national_scale", "model.yaml"
)
_MODEL_URBAN = os.path.join(
os.path.dirname(__file__), "..", "example_models", "urban_scale", "model.yaml"
)
class TestDataset:
@pytest.fixture()
def example_dataarray(self):
return xr.DataArray(
[
[[[0], [1], [2]], [[3], [4], [5]], [[6], [7], [8]]],
[[[0], [1], [2]], [[3], [4], [5]], [[6], [7], [8]]],
],
dims=("timesteps", "nodes", "techs", "costs"),
coords={
"timesteps": ["foo", "bar"],
"nodes": ["a", "b", "c"],
"techs": ["foo", "bar", "baz"],
"costs": ["foo"],
<|code_end|>
. Write the next line using the current file imports:
import pytest # noqa: F401
import calliope
import logging
import datetime
import os
import tempfile
import xarray as xr
from calliope.core.util import dataset, observed_dict
from calliope.core.util.tools import memoize, memoize_instancemethod
from calliope.core.util.logging import log_time
from calliope.core.util.generate_runs import generate_runs
from calliope.test.common.util import (
python36_or_higher,
check_error_or_warning,
)
and context from other files:
# Path: calliope/core/util/dataset.py
# def reorganise_xarray_dimensions(data):
#
# Path: calliope/core/util/observed_dict.py
# class ObservedDict(dict):
# class UpdateObserverDict(ObservedDict):
# def __init__(self, initial_dict, initial_yaml_string, on_changed=None, flat=False):
# def __setitem__(self, key, value):
# def update(self, other=None, **kwargs):
# def notify(self, updated=None):
# def __init__(
# self,
# name,
# observer,
# initial_dict=None,
# initial_yaml_string=None,
# *args,
# **kwargs,
# ):
# def notify(self, updated=None):
#
# Path: calliope/core/util/tools.py
# def get_from_dict(data_dict, map_list):
# def apply_to_dict(data_dict, map_list, func, args):
# def __init__(self, func):
# def __get__(self, obj, objtype=None):
# def __call__(self, *args, **kw):
# def relative_path(base_path_file, path):
# def load_function(source):
# def plugin_load(name, builtin_module):
# class memoize_instancemethod(object):
#
# Path: calliope/core/util/logging.py
# def log_time(
# logger, timings, identifier, comment=None, level="info", time_since_run_start=False
# ):
# if comment is None:
# comment = identifier
#
# timings[identifier] = now = datetime.datetime.now()
#
# if time_since_run_start and "run_start" in timings:
# time_diff = now - timings["run_start"]
# comment += ". Time since start of model run: {}".format(time_diff)
#
# getattr(logger, level)(comment)
#
# Path: calliope/core/util/generate_runs.py
# def generate_runs(model_file, scenarios=None, additional_args=None, override_dict=None):
# """
# Returns a list of "calliope run" invocations.
#
# ``scenarios`` must be specified as either a semicolon-separated
# list of scenarios or a semicolon-separated list of comma-separated
# individual override combinations, such as:
#
# ``override1,override2;override1,override3;...``
#
# If ``scenarios`` is not given, use all scenarios in the model
# configuration, and if no scenarios given in the model configuration,
# uses all individual overrides, one by one.
#
# """
# if scenarios is None:
# config = AttrDict.from_yaml(model_file)
# if override_dict:
# override = AttrDict.from_yaml_string(override_dict)
# config.union(override, allow_override=True, allow_replacement=True)
#
# if "scenarios" in config:
# runs = config.scenarios.keys()
# else:
# runs = config.overrides.keys()
# else:
# runs = scenarios.split(";")
#
# commands = []
#
# # len(str(x)) gives us the number of digits in x, for padding
# i_string = "{:0>" + str(len(str(len(runs)))) + "d}"
#
# for i, run in enumerate(runs):
# cmd = (
# f"calliope run {model_file} --scenario {run} "
# f"--save_netcdf out_{i_string.format(i + 1)}_{run}.nc "
# ).strip()
#
# if override_dict:
# cmd = cmd + ' --override_dict="{}"'.format(override_dict)
#
# if additional_args:
# cmd = cmd + " " + additional_args
#
# commands.append(cmd)
#
# return commands
#
# Path: calliope/test/common/util.py
# def build_test_model(
# override_dict=None,
# scenario=None,
# model_file="model.yaml",
# timeseries_dataframes=None,
# ):
# def check_error_or_warning(error_warning, test_string_or_strings):
# def check_variable_exists(backend_model, constraint, variable, idx=None):
, which may include functions, classes, or code. Output only the next line. | }, |
Using the snippet: <|code_start|> assert observer.attrs["test"] == self.as_yaml(
{"foo": 5, "foobar": {"baz": 2}, "baz": 4}
)
def test_model_config(self, model):
assert hasattr(model, "model_config")
assert "model_config" in model._model_data.attrs.keys()
assert model._model_data.attrs["model_config"] == self.as_yaml(
model.model_config, strip=True
)
model.model_config["name"] = "new name"
assert model.model_config["name"] == "new name"
assert model._model_data.attrs["model_config"] == self.as_yaml(
model.model_config, strip=True
)
def test_run_config(self, model):
assert hasattr(model, "run_config")
assert "run_config" in model._model_data.attrs.keys()
assert model._model_data.attrs["run_config"] == self.as_yaml(
model.run_config, strip=True
)
model.run_config["solver"] = "cplex"
assert model.run_config["solver"] == "cplex"
assert model._model_data.attrs["run_config"] == self.as_yaml(
model.run_config, strip=True
)
<|code_end|>
, determine the next line of code. You have imports:
import pytest # noqa: F401
import calliope
import logging
import datetime
import os
import tempfile
import xarray as xr
from calliope.core.util import dataset, observed_dict
from calliope.core.util.tools import memoize, memoize_instancemethod
from calliope.core.util.logging import log_time
from calliope.core.util.generate_runs import generate_runs
from calliope.test.common.util import (
python36_or_higher,
check_error_or_warning,
)
and context (class names, function names, or code) available:
# Path: calliope/core/util/dataset.py
# def reorganise_xarray_dimensions(data):
#
# Path: calliope/core/util/observed_dict.py
# class ObservedDict(dict):
# class UpdateObserverDict(ObservedDict):
# def __init__(self, initial_dict, initial_yaml_string, on_changed=None, flat=False):
# def __setitem__(self, key, value):
# def update(self, other=None, **kwargs):
# def notify(self, updated=None):
# def __init__(
# self,
# name,
# observer,
# initial_dict=None,
# initial_yaml_string=None,
# *args,
# **kwargs,
# ):
# def notify(self, updated=None):
#
# Path: calliope/core/util/tools.py
# def get_from_dict(data_dict, map_list):
# def apply_to_dict(data_dict, map_list, func, args):
# def __init__(self, func):
# def __get__(self, obj, objtype=None):
# def __call__(self, *args, **kw):
# def relative_path(base_path_file, path):
# def load_function(source):
# def plugin_load(name, builtin_module):
# class memoize_instancemethod(object):
#
# Path: calliope/core/util/logging.py
# def log_time(
# logger, timings, identifier, comment=None, level="info", time_since_run_start=False
# ):
# if comment is None:
# comment = identifier
#
# timings[identifier] = now = datetime.datetime.now()
#
# if time_since_run_start and "run_start" in timings:
# time_diff = now - timings["run_start"]
# comment += ". Time since start of model run: {}".format(time_diff)
#
# getattr(logger, level)(comment)
#
# Path: calliope/core/util/generate_runs.py
# def generate_runs(model_file, scenarios=None, additional_args=None, override_dict=None):
# """
# Returns a list of "calliope run" invocations.
#
# ``scenarios`` must be specified as either a semicolon-separated
# list of scenarios or a semicolon-separated list of comma-separated
# individual override combinations, such as:
#
# ``override1,override2;override1,override3;...``
#
# If ``scenarios`` is not given, use all scenarios in the model
# configuration, and if no scenarios given in the model configuration,
# uses all individual overrides, one by one.
#
# """
# if scenarios is None:
# config = AttrDict.from_yaml(model_file)
# if override_dict:
# override = AttrDict.from_yaml_string(override_dict)
# config.union(override, allow_override=True, allow_replacement=True)
#
# if "scenarios" in config:
# runs = config.scenarios.keys()
# else:
# runs = config.overrides.keys()
# else:
# runs = scenarios.split(";")
#
# commands = []
#
# # len(str(x)) gives us the number of digits in x, for padding
# i_string = "{:0>" + str(len(str(len(runs)))) + "d}"
#
# for i, run in enumerate(runs):
# cmd = (
# f"calliope run {model_file} --scenario {run} "
# f"--save_netcdf out_{i_string.format(i + 1)}_{run}.nc "
# ).strip()
#
# if override_dict:
# cmd = cmd + ' --override_dict="{}"'.format(override_dict)
#
# if additional_args:
# cmd = cmd + " " + additional_args
#
# commands.append(cmd)
#
# return commands
#
# Path: calliope/test/common/util.py
# def build_test_model(
# override_dict=None,
# scenario=None,
# model_file="model.yaml",
# timeseries_dataframes=None,
# ):
# def check_error_or_warning(error_warning, test_string_or_strings):
# def check_variable_exists(backend_model, constraint, variable, idx=None):
. Output only the next line. | def test_load_from_netcdf(self, model): |
Predict the next line after this snippet: <|code_start|> def observed_from_string(self, observer):
initial_dict = {"foo": "bar", "foobar": {"baz": "fob"}}
return observed_dict.UpdateObserverDict(
initial_yaml_string=self.as_yaml(initial_dict),
name="test_2",
observer=observer,
)
def test_initialise_observer(
self, observer, observed_from_dict, observed_from_string
):
assert "test" in observer.attrs.keys()
assert "test_2" in observer.attrs.keys()
assert observer.attrs["test"] == self.as_yaml(
{"foo": "bar", "foobar": {"baz": "fob"}}
)
observer.attrs["test"] == observer.attrs["test_2"]
def test_value_error_on_initialising(self):
initial_dict = {"foo": "bar", "foobar": {"baz": "fob"}}
initial_string = self.as_yaml(initial_dict)
with pytest.raises(ValueError) as error:
observed_dict.UpdateObserverDict(name="test_2", observer=xr.Dataset())
assert check_error_or_warning(
error,
"must supply one, and only one, of initial_dict or initial_yaml_string",
)
with pytest.raises(ValueError) as error:
observed_dict.UpdateObserverDict(
initial_yaml_string=initial_string,
<|code_end|>
using the current file's imports:
import pytest # noqa: F401
import calliope
import logging
import datetime
import os
import tempfile
import xarray as xr
from calliope.core.util import dataset, observed_dict
from calliope.core.util.tools import memoize, memoize_instancemethod
from calliope.core.util.logging import log_time
from calliope.core.util.generate_runs import generate_runs
from calliope.test.common.util import (
python36_or_higher,
check_error_or_warning,
)
and any relevant context from other files:
# Path: calliope/core/util/dataset.py
# def reorganise_xarray_dimensions(data):
#
# Path: calliope/core/util/observed_dict.py
# class ObservedDict(dict):
# class UpdateObserverDict(ObservedDict):
# def __init__(self, initial_dict, initial_yaml_string, on_changed=None, flat=False):
# def __setitem__(self, key, value):
# def update(self, other=None, **kwargs):
# def notify(self, updated=None):
# def __init__(
# self,
# name,
# observer,
# initial_dict=None,
# initial_yaml_string=None,
# *args,
# **kwargs,
# ):
# def notify(self, updated=None):
#
# Path: calliope/core/util/tools.py
# def get_from_dict(data_dict, map_list):
# def apply_to_dict(data_dict, map_list, func, args):
# def __init__(self, func):
# def __get__(self, obj, objtype=None):
# def __call__(self, *args, **kw):
# def relative_path(base_path_file, path):
# def load_function(source):
# def plugin_load(name, builtin_module):
# class memoize_instancemethod(object):
#
# Path: calliope/core/util/logging.py
# def log_time(
# logger, timings, identifier, comment=None, level="info", time_since_run_start=False
# ):
# if comment is None:
# comment = identifier
#
# timings[identifier] = now = datetime.datetime.now()
#
# if time_since_run_start and "run_start" in timings:
# time_diff = now - timings["run_start"]
# comment += ". Time since start of model run: {}".format(time_diff)
#
# getattr(logger, level)(comment)
#
# Path: calliope/core/util/generate_runs.py
# def generate_runs(model_file, scenarios=None, additional_args=None, override_dict=None):
# """
# Returns a list of "calliope run" invocations.
#
# ``scenarios`` must be specified as either a semicolon-separated
# list of scenarios or a semicolon-separated list of comma-separated
# individual override combinations, such as:
#
# ``override1,override2;override1,override3;...``
#
# If ``scenarios`` is not given, use all scenarios in the model
# configuration, and if no scenarios given in the model configuration,
# uses all individual overrides, one by one.
#
# """
# if scenarios is None:
# config = AttrDict.from_yaml(model_file)
# if override_dict:
# override = AttrDict.from_yaml_string(override_dict)
# config.union(override, allow_override=True, allow_replacement=True)
#
# if "scenarios" in config:
# runs = config.scenarios.keys()
# else:
# runs = config.overrides.keys()
# else:
# runs = scenarios.split(";")
#
# commands = []
#
# # len(str(x)) gives us the number of digits in x, for padding
# i_string = "{:0>" + str(len(str(len(runs)))) + "d}"
#
# for i, run in enumerate(runs):
# cmd = (
# f"calliope run {model_file} --scenario {run} "
# f"--save_netcdf out_{i_string.format(i + 1)}_{run}.nc "
# ).strip()
#
# if override_dict:
# cmd = cmd + ' --override_dict="{}"'.format(override_dict)
#
# if additional_args:
# cmd = cmd + " " + additional_args
#
# commands.append(cmd)
#
# return commands
#
# Path: calliope/test/common/util.py
# def build_test_model(
# override_dict=None,
# scenario=None,
# model_file="model.yaml",
# timeseries_dataframes=None,
# ):
# def check_error_or_warning(error_warning, test_string_or_strings):
# def check_variable_exists(backend_model, constraint, variable, idx=None):
. Output only the next line. | initial_dict=initial_dict, |
Predict the next line for this snippet: <|code_start|> )
@pytest.mark.parametrize(
"key1,key2,value,result",
(
("foo", None, 1, {"foo": 1, "foobar": {"baz": "fob"}}),
("foobar", "baz", 2, {"foo": 1, "foobar": {"baz": 2}}),
(
"foo",
None,
{"baz": "fob"},
{"foo": {"baz": "fob"}, "foobar": {"baz": 2}},
),
("foo", "baz", 3, {"foo": {"baz": 3}, "foobar": {"baz": 2}}),
("foo", None, {}, {"foobar": {"baz": 2}}),
("foo", None, 5, {"foo": 5, "foobar": {"baz": 2}}),
("foo", None, None, {"foobar": {"baz": 2}}),
),
)
def test_set_item_observer(
self, observed_from_dict, observer, key1, key2, value, result
):
if key2 is None:
observed_from_dict[key1] = value
else:
observed_from_dict[key1][key2] = value
assert observer.attrs["test"] == self.as_yaml(result)
def test_update_observer(self, observed_from_dict, observer):
<|code_end|>
with the help of current file imports:
import pytest # noqa: F401
import calliope
import logging
import datetime
import os
import tempfile
import xarray as xr
from calliope.core.util import dataset, observed_dict
from calliope.core.util.tools import memoize, memoize_instancemethod
from calliope.core.util.logging import log_time
from calliope.core.util.generate_runs import generate_runs
from calliope.test.common.util import (
python36_or_higher,
check_error_or_warning,
)
and context from other files:
# Path: calliope/core/util/dataset.py
# def reorganise_xarray_dimensions(data):
#
# Path: calliope/core/util/observed_dict.py
# class ObservedDict(dict):
# class UpdateObserverDict(ObservedDict):
# def __init__(self, initial_dict, initial_yaml_string, on_changed=None, flat=False):
# def __setitem__(self, key, value):
# def update(self, other=None, **kwargs):
# def notify(self, updated=None):
# def __init__(
# self,
# name,
# observer,
# initial_dict=None,
# initial_yaml_string=None,
# *args,
# **kwargs,
# ):
# def notify(self, updated=None):
#
# Path: calliope/core/util/tools.py
# def get_from_dict(data_dict, map_list):
# def apply_to_dict(data_dict, map_list, func, args):
# def __init__(self, func):
# def __get__(self, obj, objtype=None):
# def __call__(self, *args, **kw):
# def relative_path(base_path_file, path):
# def load_function(source):
# def plugin_load(name, builtin_module):
# class memoize_instancemethod(object):
#
# Path: calliope/core/util/logging.py
# def log_time(
# logger, timings, identifier, comment=None, level="info", time_since_run_start=False
# ):
# if comment is None:
# comment = identifier
#
# timings[identifier] = now = datetime.datetime.now()
#
# if time_since_run_start and "run_start" in timings:
# time_diff = now - timings["run_start"]
# comment += ". Time since start of model run: {}".format(time_diff)
#
# getattr(logger, level)(comment)
#
# Path: calliope/core/util/generate_runs.py
# def generate_runs(model_file, scenarios=None, additional_args=None, override_dict=None):
# """
# Returns a list of "calliope run" invocations.
#
# ``scenarios`` must be specified as either a semicolon-separated
# list of scenarios or a semicolon-separated list of comma-separated
# individual override combinations, such as:
#
# ``override1,override2;override1,override3;...``
#
# If ``scenarios`` is not given, use all scenarios in the model
# configuration, and if no scenarios given in the model configuration,
# uses all individual overrides, one by one.
#
# """
# if scenarios is None:
# config = AttrDict.from_yaml(model_file)
# if override_dict:
# override = AttrDict.from_yaml_string(override_dict)
# config.union(override, allow_override=True, allow_replacement=True)
#
# if "scenarios" in config:
# runs = config.scenarios.keys()
# else:
# runs = config.overrides.keys()
# else:
# runs = scenarios.split(";")
#
# commands = []
#
# # len(str(x)) gives us the number of digits in x, for padding
# i_string = "{:0>" + str(len(str(len(runs)))) + "d}"
#
# for i, run in enumerate(runs):
# cmd = (
# f"calliope run {model_file} --scenario {run} "
# f"--save_netcdf out_{i_string.format(i + 1)}_{run}.nc "
# ).strip()
#
# if override_dict:
# cmd = cmd + ' --override_dict="{}"'.format(override_dict)
#
# if additional_args:
# cmd = cmd + " " + additional_args
#
# commands.append(cmd)
#
# return commands
#
# Path: calliope/test/common/util.py
# def build_test_model(
# override_dict=None,
# scenario=None,
# model_file="model.yaml",
# timeseries_dataframes=None,
# ):
# def check_error_or_warning(error_warning, test_string_or_strings):
# def check_variable_exists(backend_model, constraint, variable, idx=None):
, which may contain function names, class names, or code. Output only the next line. | observed_from_dict.update({"baz": 4}) |
Given snippet: <|code_start|> initial_dict = {"foo": "bar", "foobar": {"baz": "fob"}}
initial_string = self.as_yaml(initial_dict)
with pytest.raises(ValueError) as error:
observed_dict.UpdateObserverDict(name="test_2", observer=xr.Dataset())
assert check_error_or_warning(
error,
"must supply one, and only one, of initial_dict or initial_yaml_string",
)
with pytest.raises(ValueError) as error:
observed_dict.UpdateObserverDict(
initial_yaml_string=initial_string,
initial_dict=initial_dict,
name="test_2",
observer=xr.Dataset(),
)
assert check_error_or_warning(
error,
"must supply one, and only one, of initial_dict or initial_yaml_string",
)
@pytest.mark.parametrize(
"key1,key2,value,result",
(
("foo", None, 1, {"foo": 1, "foobar": {"baz": "fob"}}),
("foobar", "baz", 2, {"foo": 1, "foobar": {"baz": 2}}),
(
"foo",
None,
{"baz": "fob"},
{"foo": {"baz": "fob"}, "foobar": {"baz": 2}},
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest # noqa: F401
import calliope
import logging
import datetime
import os
import tempfile
import xarray as xr
from calliope.core.util import dataset, observed_dict
from calliope.core.util.tools import memoize, memoize_instancemethod
from calliope.core.util.logging import log_time
from calliope.core.util.generate_runs import generate_runs
from calliope.test.common.util import (
python36_or_higher,
check_error_or_warning,
)
and context:
# Path: calliope/core/util/dataset.py
# def reorganise_xarray_dimensions(data):
#
# Path: calliope/core/util/observed_dict.py
# class ObservedDict(dict):
# class UpdateObserverDict(ObservedDict):
# def __init__(self, initial_dict, initial_yaml_string, on_changed=None, flat=False):
# def __setitem__(self, key, value):
# def update(self, other=None, **kwargs):
# def notify(self, updated=None):
# def __init__(
# self,
# name,
# observer,
# initial_dict=None,
# initial_yaml_string=None,
# *args,
# **kwargs,
# ):
# def notify(self, updated=None):
#
# Path: calliope/core/util/tools.py
# def get_from_dict(data_dict, map_list):
# def apply_to_dict(data_dict, map_list, func, args):
# def __init__(self, func):
# def __get__(self, obj, objtype=None):
# def __call__(self, *args, **kw):
# def relative_path(base_path_file, path):
# def load_function(source):
# def plugin_load(name, builtin_module):
# class memoize_instancemethod(object):
#
# Path: calliope/core/util/logging.py
# def log_time(
# logger, timings, identifier, comment=None, level="info", time_since_run_start=False
# ):
# if comment is None:
# comment = identifier
#
# timings[identifier] = now = datetime.datetime.now()
#
# if time_since_run_start and "run_start" in timings:
# time_diff = now - timings["run_start"]
# comment += ". Time since start of model run: {}".format(time_diff)
#
# getattr(logger, level)(comment)
#
# Path: calliope/core/util/generate_runs.py
# def generate_runs(model_file, scenarios=None, additional_args=None, override_dict=None):
# """
# Returns a list of "calliope run" invocations.
#
# ``scenarios`` must be specified as either a semicolon-separated
# list of scenarios or a semicolon-separated list of comma-separated
# individual override combinations, such as:
#
# ``override1,override2;override1,override3;...``
#
# If ``scenarios`` is not given, use all scenarios in the model
# configuration, and if no scenarios given in the model configuration,
# uses all individual overrides, one by one.
#
# """
# if scenarios is None:
# config = AttrDict.from_yaml(model_file)
# if override_dict:
# override = AttrDict.from_yaml_string(override_dict)
# config.union(override, allow_override=True, allow_replacement=True)
#
# if "scenarios" in config:
# runs = config.scenarios.keys()
# else:
# runs = config.overrides.keys()
# else:
# runs = scenarios.split(";")
#
# commands = []
#
# # len(str(x)) gives us the number of digits in x, for padding
# i_string = "{:0>" + str(len(str(len(runs)))) + "d}"
#
# for i, run in enumerate(runs):
# cmd = (
# f"calliope run {model_file} --scenario {run} "
# f"--save_netcdf out_{i_string.format(i + 1)}_{run}.nc "
# ).strip()
#
# if override_dict:
# cmd = cmd + ' --override_dict="{}"'.format(override_dict)
#
# if additional_args:
# cmd = cmd + " " + additional_args
#
# commands.append(cmd)
#
# return commands
#
# Path: calliope/test/common/util.py
# def build_test_model(
# override_dict=None,
# scenario=None,
# model_file="model.yaml",
# timeseries_dataframes=None,
# ):
# def check_error_or_warning(error_warning, test_string_or_strings):
# def check_variable_exists(backend_model, constraint, variable, idx=None):
which might include code, classes, or functions. Output only the next line. | ), |
Here is a snippet: <|code_start|> "power", "region1", "ccgt"
] == approx(115569.4354)
assert float(model.results.cost.sum()) > 6.6e7
@pytest.mark.parametrize(
"scenario,cost_class,weight",
[
("monetary_objective", ["monetary"], [1]),
("emissions_objective", ["emissions"], [1]),
("weighted_objective", ["monetary", "emissions"], [0.9, 0.1]),
],
)
def test_weighted_objective_results(self, scenario, cost_class, weight):
model = build_model(model_file="weighted_obj_func.yaml", scenario=scenario)
model.run()
assert sum(
model.results.cost.loc[{"costs": cost_class[i]}].sum().item() * weight[i]
for i in range(len(cost_class))
) == approx(po.value(model._backend_model.obj))
def test_update_cost_classes_weights(self):
model = build_model(
model_file="weighted_obj_func.yaml", scenario="weighted_objective"
)
model.run()
obj_value = model._backend_model.obj()
total_cost = model.results.cost.sum()
model.backend.update_param("objective_cost_class", {"monetary": 1.8})
<|code_end|>
. Write the next line using the current file imports:
import pytest
import pyomo.core as po
import calliope
from pytest import approx
from calliope.test.common.util import build_test_model as build_model
and context from other files:
# Path: calliope/test/common/util.py
# def build_test_model(
# override_dict=None,
# scenario=None,
# model_file="model.yaml",
# timeseries_dataframes=None,
# ):
# return calliope.Model(
# os.path.join(os.path.dirname(__file__), "test_model", model_file),
# override_dict=override_dict,
# scenario=scenario,
# timeseries_dataframes=timeseries_dataframes,
# )
, which may include functions, classes, or code. Output only the next line. | model.backend.update_param("objective_cost_class", {"emissions": 0.2}) |
Given snippet: <|code_start|>
class TestIO:
@pytest.fixture(scope="module")
def model(self):
model = calliope.examples.national_scale()
model.run()
return model
def test_save_netcdf(self, model):
bool_attrs = [
k for k, v in model._model_data.attrs.items() if isinstance(v, bool)
]
with tempfile.TemporaryDirectory() as tempdir:
out_path = os.path.join(tempdir, "model.nc")
model.to_netcdf(out_path)
assert os.path.isfile(out_path)
# Ensure that boolean attrs have not changed
for k in bool_attrs:
assert isinstance(model._model_data.attrs[k], bool)
def test_save_csv_dir_mustnt_exist(self, model):
with tempfile.TemporaryDirectory() as tempdir:
out_path = os.path.join(tempdir)
with pytest.raises(FileExistsError):
model.to_csv(out_path)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import tempfile
import pytest # noqa: F401
import calliope
from calliope import exceptions
and context:
# Path: calliope/exceptions.py
# def _formatwarning(message, category, filename, lineno, line=None):
# def warn(message, _class=ModelWarning):
# def print_warnings_and_raise_errors(warnings=None, errors=None):
# class ModelError(Exception):
# class BackendError(Exception):
# class ModelWarning(Warning):
# class BackendWarning(Warning):
which might include code, classes, or functions. Output only the next line. | @pytest.mark.parametrize( |
Next line prediction: <|code_start|> "2005-01-02 23:00:00",
"2005-01-02 23:15:00",
"2005-01-02 23:30:00",
"2005-01-02 23:45:00",
]
)
assert dtindex.equals(mask)
def test_15min_to_2h_masking_1D(self):
# The data is identical for '2005-01-01' and '2005-01-03' timesteps,
# it is only different for '2005-01-02'
override = {
"techs.test_demand_elec.constraints.resource": "file=demand_elec_15T_to_2h.csv",
"model.subset_time": None,
}
model = build_test_model(override, scenario="simple_supply,one_day")
data = model._model_data
mask = masks.extreme(
data, "test_demand_elec", var="resource", how="max", length="1D"
)
dtindex = pd.DatetimeIndex(
[
"2005-01-02 00:00:00",
"2005-01-02 00:15:00",
"2005-01-02 00:30:00",
"2005-01-02 00:45:00",
<|code_end|>
. Use current file imports:
(import pandas as pd
import numpy as np
import pytest # noqa: F401
import calliope
from calliope import exceptions
from calliope.time import funcs, masks
from calliope.test.common.util import (
build_test_model,
check_error_or_warning,
python36_or_higher,
))
and context including class names, function names, or small code snippets from other files:
# Path: calliope/exceptions.py
# def _formatwarning(message, category, filename, lineno, line=None):
# def warn(message, _class=ModelWarning):
# def print_warnings_and_raise_errors(warnings=None, errors=None):
# class ModelError(Exception):
# class BackendError(Exception):
# class ModelWarning(Warning):
# class BackendWarning(Warning):
#
# Path: calliope/time/funcs.py
# def get_daily_timesteps(data, check_uniformity=False):
# def normalized_copy(data):
# def _copy_non_t_vars(data0, data1):
# def _combine_datasets(data0, data1):
# def _drop_timestep_vars(data, timesteps):
# def apply_clustering(
# data,
# timesteps,
# clustering_func,
# how,
# normalize=True,
# scale_clusters="mean",
# storage_inter_cluster=True,
# model_run=None,
# **kwargs,
# ):
# def resample(data, timesteps, resolution):
# def _resample(var, how):
# def drop(data, timesteps):
# def lookup_clusters(dataset):
#
# Path: calliope/time/masks.py
# def _get_array(data, var, tech, **kwargs):
# def zero(data, tech, var="resource", **kwargs):
# def _concat_indices(indices):
# def _get_minmax_timestamps(series, length, n, how="max", padding=None):
# def extreme(
# data,
# tech,
# var="resource",
# how="max",
# length="1D",
# n=1,
# groupby_length=None,
# padding=None,
# normalize=True,
# **kwargs,
# ):
# def extreme_diff(
# data,
# tech0,
# tech1,
# var="resource",
# how="max",
# length="1D",
# n=1,
# groupby_length=None,
# padding=None,
# normalize=True,
# **kwargs,
# ):
# def _extreme(arr, how="max", length="1D", n=1, groupby_length=None, padding=None):
# def _extreme_with_padding(arr, how, length, n, groupby_length, padding):
# def _calendar_week_padding(day, arr):
#
# Path: calliope/test/common/util.py
# def build_test_model(
# override_dict=None,
# scenario=None,
# model_file="model.yaml",
# timeseries_dataframes=None,
# ):
# def check_error_or_warning(error_warning, test_string_or_strings):
# def check_variable_exists(backend_model, constraint, variable, idx=None):
. Output only the next line. | "2005-01-02 01:00:00", |
Using the snippet: <|code_start|> "2005-01-02 14:45:00",
"2005-01-02 15:00:00",
"2005-01-02 15:15:00",
"2005-01-02 15:30:00",
"2005-01-02 15:45:00",
"2005-01-02 16:00:00",
"2005-01-02 16:15:00",
"2005-01-02 16:30:00",
"2005-01-02 16:45:00",
"2005-01-02 17:00:00",
"2005-01-02 17:15:00",
"2005-01-02 17:30:00",
"2005-01-02 17:45:00",
"2005-01-02 18:00:00",
"2005-01-02 18:15:00",
"2005-01-02 18:30:00",
"2005-01-02 18:45:00",
"2005-01-02 19:00:00",
"2005-01-02 19:15:00",
"2005-01-02 19:30:00",
"2005-01-02 19:45:00",
"2005-01-02 20:00:00",
"2005-01-02 20:15:00",
"2005-01-02 20:30:00",
"2005-01-02 20:45:00",
"2005-01-02 21:00:00",
"2005-01-02 21:15:00",
"2005-01-02 21:30:00",
"2005-01-02 21:45:00",
"2005-01-02 22:00:00",
<|code_end|>
, determine the next line of code. You have imports:
import pandas as pd
import numpy as np
import pytest # noqa: F401
import calliope
from calliope import exceptions
from calliope.time import funcs, masks
from calliope.test.common.util import (
build_test_model,
check_error_or_warning,
python36_or_higher,
)
and context (class names, function names, or code) available:
# Path: calliope/exceptions.py
# def _formatwarning(message, category, filename, lineno, line=None):
# def warn(message, _class=ModelWarning):
# def print_warnings_and_raise_errors(warnings=None, errors=None):
# class ModelError(Exception):
# class BackendError(Exception):
# class ModelWarning(Warning):
# class BackendWarning(Warning):
#
# Path: calliope/time/funcs.py
# def get_daily_timesteps(data, check_uniformity=False):
# def normalized_copy(data):
# def _copy_non_t_vars(data0, data1):
# def _combine_datasets(data0, data1):
# def _drop_timestep_vars(data, timesteps):
# def apply_clustering(
# data,
# timesteps,
# clustering_func,
# how,
# normalize=True,
# scale_clusters="mean",
# storage_inter_cluster=True,
# model_run=None,
# **kwargs,
# ):
# def resample(data, timesteps, resolution):
# def _resample(var, how):
# def drop(data, timesteps):
# def lookup_clusters(dataset):
#
# Path: calliope/time/masks.py
# def _get_array(data, var, tech, **kwargs):
# def zero(data, tech, var="resource", **kwargs):
# def _concat_indices(indices):
# def _get_minmax_timestamps(series, length, n, how="max", padding=None):
# def extreme(
# data,
# tech,
# var="resource",
# how="max",
# length="1D",
# n=1,
# groupby_length=None,
# padding=None,
# normalize=True,
# **kwargs,
# ):
# def extreme_diff(
# data,
# tech0,
# tech1,
# var="resource",
# how="max",
# length="1D",
# n=1,
# groupby_length=None,
# padding=None,
# normalize=True,
# **kwargs,
# ):
# def _extreme(arr, how="max", length="1D", n=1, groupby_length=None, padding=None):
# def _extreme_with_padding(arr, how, length, n, groupby_length, padding):
# def _calendar_week_padding(day, arr):
#
# Path: calliope/test/common/util.py
# def build_test_model(
# override_dict=None,
# scenario=None,
# model_file="model.yaml",
# timeseries_dataframes=None,
# ):
# def check_error_or_warning(error_warning, test_string_or_strings):
# def check_variable_exists(backend_model, constraint, variable, idx=None):
. Output only the next line. | "2005-01-02 22:15:00", |
Given the following code snippet before the placeholder: <|code_start|> "2005-01-02 05:00:00",
"2005-01-02 06:00:00",
"2005-01-02 16:00:00",
"2005-01-02 17:00:00",
"2005-01-02 18:00:00",
"2005-01-02 19:00:00",
"2005-01-02 20:00:00",
"2005-01-02 21:00:00",
"2005-01-02 22:00:00",
"2005-01-02 23:00:00",
"2005-01-03 00:00:00",
"2005-01-03 01:00:00",
"2005-01-03 02:00:00",
"2005-01-03 03:00:00",
"2005-01-03 04:00:00",
"2005-01-03 05:00:00",
"2005-01-03 06:00:00",
"2005-01-03 16:00:00",
"2005-01-03 17:00:00",
"2005-01-03 18:00:00",
"2005-01-03 19:00:00",
"2005-01-03 20:00:00",
"2005-01-03 21:00:00",
"2005-01-03 22:00:00",
"2005-01-03 23:00:00",
"2005-01-04 00:00:00",
"2005-01-04 01:00:00",
"2005-01-04 02:00:00",
"2005-01-04 03:00:00",
"2005-01-04 04:00:00",
<|code_end|>
, predict the next line using imports from the current file:
import pandas as pd
import numpy as np
import pytest # noqa: F401
import calliope
from calliope import exceptions
from calliope.time import funcs, masks
from calliope.test.common.util import (
build_test_model,
check_error_or_warning,
python36_or_higher,
)
and context including class names, function names, and sometimes code from other files:
# Path: calliope/exceptions.py
# def _formatwarning(message, category, filename, lineno, line=None):
# def warn(message, _class=ModelWarning):
# def print_warnings_and_raise_errors(warnings=None, errors=None):
# class ModelError(Exception):
# class BackendError(Exception):
# class ModelWarning(Warning):
# class BackendWarning(Warning):
#
# Path: calliope/time/funcs.py
# def get_daily_timesteps(data, check_uniformity=False):
# def normalized_copy(data):
# def _copy_non_t_vars(data0, data1):
# def _combine_datasets(data0, data1):
# def _drop_timestep_vars(data, timesteps):
# def apply_clustering(
# data,
# timesteps,
# clustering_func,
# how,
# normalize=True,
# scale_clusters="mean",
# storage_inter_cluster=True,
# model_run=None,
# **kwargs,
# ):
# def resample(data, timesteps, resolution):
# def _resample(var, how):
# def drop(data, timesteps):
# def lookup_clusters(dataset):
#
# Path: calliope/time/masks.py
# def _get_array(data, var, tech, **kwargs):
# def zero(data, tech, var="resource", **kwargs):
# def _concat_indices(indices):
# def _get_minmax_timestamps(series, length, n, how="max", padding=None):
# def extreme(
# data,
# tech,
# var="resource",
# how="max",
# length="1D",
# n=1,
# groupby_length=None,
# padding=None,
# normalize=True,
# **kwargs,
# ):
# def extreme_diff(
# data,
# tech0,
# tech1,
# var="resource",
# how="max",
# length="1D",
# n=1,
# groupby_length=None,
# padding=None,
# normalize=True,
# **kwargs,
# ):
# def _extreme(arr, how="max", length="1D", n=1, groupby_length=None, padding=None):
# def _extreme_with_padding(arr, how, length, n, groupby_length, padding):
# def _calendar_week_padding(day, arr):
#
# Path: calliope/test/common/util.py
# def build_test_model(
# override_dict=None,
# scenario=None,
# model_file="model.yaml",
# timeseries_dataframes=None,
# ):
# def check_error_or_warning(error_warning, test_string_or_strings):
# def check_variable_exists(backend_model, constraint, variable, idx=None):
. Output only the next line. | "2005-01-04 05:00:00", |
Using the snippet: <|code_start|> with pytest.raises(exceptions.ModelError) as error:
build_test_model(override4, scenario="simple_supply")
assert check_error_or_warning(
error,
"Missing data for the timeseries array(s) [('cluster_days.csv', 'a') ('cluster_days.csv', 'b')]",
)
class TestMasks:
@pytest.fixture
def model_national(self, scope="module"):
return calliope.examples.national_scale(
override_dict={"model.subset_time": ["2005-01-01", "2005-01-31"]}
)
@pytest.fixture
def model_urban(self, scope="module"):
return calliope.examples.urban_scale(
override_dict={"model.subset_time": ["2005-01-01", "2005-01-31"]}
)
def test_zero(self, model_national):
data = model_national._model_data_pre_clustering.copy()
mask = masks.zero(data, "csp", var="resource")
dtindex = pd.DatetimeIndex(
[
"2005-01-01 00:00:00",
"2005-01-01 01:00:00",
<|code_end|>
, determine the next line of code. You have imports:
import pandas as pd
import numpy as np
import pytest # noqa: F401
import calliope
from calliope import exceptions
from calliope.time import funcs, masks
from calliope.test.common.util import (
build_test_model,
check_error_or_warning,
python36_or_higher,
)
and context (class names, function names, or code) available:
# Path: calliope/exceptions.py
# def _formatwarning(message, category, filename, lineno, line=None):
# def warn(message, _class=ModelWarning):
# def print_warnings_and_raise_errors(warnings=None, errors=None):
# class ModelError(Exception):
# class BackendError(Exception):
# class ModelWarning(Warning):
# class BackendWarning(Warning):
#
# Path: calliope/time/funcs.py
# def get_daily_timesteps(data, check_uniformity=False):
# def normalized_copy(data):
# def _copy_non_t_vars(data0, data1):
# def _combine_datasets(data0, data1):
# def _drop_timestep_vars(data, timesteps):
# def apply_clustering(
# data,
# timesteps,
# clustering_func,
# how,
# normalize=True,
# scale_clusters="mean",
# storage_inter_cluster=True,
# model_run=None,
# **kwargs,
# ):
# def resample(data, timesteps, resolution):
# def _resample(var, how):
# def drop(data, timesteps):
# def lookup_clusters(dataset):
#
# Path: calliope/time/masks.py
# def _get_array(data, var, tech, **kwargs):
# def zero(data, tech, var="resource", **kwargs):
# def _concat_indices(indices):
# def _get_minmax_timestamps(series, length, n, how="max", padding=None):
# def extreme(
# data,
# tech,
# var="resource",
# how="max",
# length="1D",
# n=1,
# groupby_length=None,
# padding=None,
# normalize=True,
# **kwargs,
# ):
# def extreme_diff(
# data,
# tech0,
# tech1,
# var="resource",
# how="max",
# length="1D",
# n=1,
# groupby_length=None,
# padding=None,
# normalize=True,
# **kwargs,
# ):
# def _extreme(arr, how="max", length="1D", n=1, groupby_length=None, padding=None):
# def _extreme_with_padding(arr, how, length, n, groupby_length, padding):
# def _calendar_week_padding(day, arr):
#
# Path: calliope/test/common/util.py
# def build_test_model(
# override_dict=None,
# scenario=None,
# model_file="model.yaml",
# timeseries_dataframes=None,
# ):
# def check_error_or_warning(error_warning, test_string_or_strings):
# def check_variable_exists(backend_model, constraint, variable, idx=None):
. Output only the next line. | "2005-01-01 02:00:00", |
Using the snippet: <|code_start|> "2005-01-02 21:45:00",
"2005-01-02 22:00:00",
"2005-01-02 22:15:00",
"2005-01-02 22:30:00",
"2005-01-02 22:45:00",
"2005-01-02 23:00:00",
"2005-01-02 23:15:00",
"2005-01-02 23:30:00",
"2005-01-02 23:45:00",
"2005-01-03 00:00:00",
"2005-01-03 02:00:00",
"2005-01-03 04:00:00",
"2005-01-03 06:00:00",
"2005-01-03 08:00:00",
"2005-01-03 10:00:00",
"2005-01-03 12:00:00",
"2005-01-03 14:00:00",
"2005-01-03 16:00:00",
"2005-01-03 18:00:00",
"2005-01-03 20:00:00",
"2005-01-03 22:00:00",
]
)
assert dtindex.equals(data.timesteps.to_index())
def test_15min_resampling_to_6h(self):
# The data is identical for '2005-01-01' and '2005-01-03' timesteps,
# it is only different for '2005-01-02'
override = {
<|code_end|>
, determine the next line of code. You have imports:
import pandas as pd
import numpy as np
import pytest # noqa: F401
import calliope
from calliope import exceptions
from calliope.time import funcs, masks
from calliope.test.common.util import (
build_test_model,
check_error_or_warning,
python36_or_higher,
)
and context (class names, function names, or code) available:
# Path: calliope/exceptions.py
# def _formatwarning(message, category, filename, lineno, line=None):
# def warn(message, _class=ModelWarning):
# def print_warnings_and_raise_errors(warnings=None, errors=None):
# class ModelError(Exception):
# class BackendError(Exception):
# class ModelWarning(Warning):
# class BackendWarning(Warning):
#
# Path: calliope/time/funcs.py
# def get_daily_timesteps(data, check_uniformity=False):
# def normalized_copy(data):
# def _copy_non_t_vars(data0, data1):
# def _combine_datasets(data0, data1):
# def _drop_timestep_vars(data, timesteps):
# def apply_clustering(
# data,
# timesteps,
# clustering_func,
# how,
# normalize=True,
# scale_clusters="mean",
# storage_inter_cluster=True,
# model_run=None,
# **kwargs,
# ):
# def resample(data, timesteps, resolution):
# def _resample(var, how):
# def drop(data, timesteps):
# def lookup_clusters(dataset):
#
# Path: calliope/time/masks.py
# def _get_array(data, var, tech, **kwargs):
# def zero(data, tech, var="resource", **kwargs):
# def _concat_indices(indices):
# def _get_minmax_timestamps(series, length, n, how="max", padding=None):
# def extreme(
# data,
# tech,
# var="resource",
# how="max",
# length="1D",
# n=1,
# groupby_length=None,
# padding=None,
# normalize=True,
# **kwargs,
# ):
# def extreme_diff(
# data,
# tech0,
# tech1,
# var="resource",
# how="max",
# length="1D",
# n=1,
# groupby_length=None,
# padding=None,
# normalize=True,
# **kwargs,
# ):
# def _extreme(arr, how="max", length="1D", n=1, groupby_length=None, padding=None):
# def _extreme_with_padding(arr, how, length, n, groupby_length, padding):
# def _calendar_week_padding(day, arr):
#
# Path: calliope/test/common/util.py
# def build_test_model(
# override_dict=None,
# scenario=None,
# model_file="model.yaml",
# timeseries_dataframes=None,
# ):
# def check_error_or_warning(error_warning, test_string_or_strings):
# def check_variable_exists(backend_model, constraint, variable, idx=None):
. Output only the next line. | "techs.test_demand_elec.constraints.resource": "file=demand_elec_15mins.csv", |
Based on the snippet: <|code_start|> 1,
1,
2,
2,
2,
2,
2,
1,
1,
2,
2,
2,
],
)
@python36_or_higher
def test_predefined_clusters(self):
override = {
"model.subset_time": ["2005-01-01", "2005-01-04"],
"model.time": {
"function": "apply_clustering",
"function_options": {
"clustering_func": "file=clusters.csv:a",
"how": "mean",
},
},
}
model = build_test_model(override, scenario="simple_supply")
<|code_end|>
, predict the immediate next line with the help of imports:
import pandas as pd
import numpy as np
import pytest # noqa: F401
import calliope
from calliope import exceptions
from calliope.time import funcs, masks
from calliope.test.common.util import (
build_test_model,
check_error_or_warning,
python36_or_higher,
)
and context (classes, functions, sometimes code) from other files:
# Path: calliope/exceptions.py
# def _formatwarning(message, category, filename, lineno, line=None):
# def warn(message, _class=ModelWarning):
# def print_warnings_and_raise_errors(warnings=None, errors=None):
# class ModelError(Exception):
# class BackendError(Exception):
# class ModelWarning(Warning):
# class BackendWarning(Warning):
#
# Path: calliope/time/funcs.py
# def get_daily_timesteps(data, check_uniformity=False):
# def normalized_copy(data):
# def _copy_non_t_vars(data0, data1):
# def _combine_datasets(data0, data1):
# def _drop_timestep_vars(data, timesteps):
# def apply_clustering(
# data,
# timesteps,
# clustering_func,
# how,
# normalize=True,
# scale_clusters="mean",
# storage_inter_cluster=True,
# model_run=None,
# **kwargs,
# ):
# def resample(data, timesteps, resolution):
# def _resample(var, how):
# def drop(data, timesteps):
# def lookup_clusters(dataset):
#
# Path: calliope/time/masks.py
# def _get_array(data, var, tech, **kwargs):
# def zero(data, tech, var="resource", **kwargs):
# def _concat_indices(indices):
# def _get_minmax_timestamps(series, length, n, how="max", padding=None):
# def extreme(
# data,
# tech,
# var="resource",
# how="max",
# length="1D",
# n=1,
# groupby_length=None,
# padding=None,
# normalize=True,
# **kwargs,
# ):
# def extreme_diff(
# data,
# tech0,
# tech1,
# var="resource",
# how="max",
# length="1D",
# n=1,
# groupby_length=None,
# padding=None,
# normalize=True,
# **kwargs,
# ):
# def _extreme(arr, how="max", length="1D", n=1, groupby_length=None, padding=None):
# def _extreme_with_padding(arr, how, length, n, groupby_length, padding):
# def _calendar_week_padding(day, arr):
#
# Path: calliope/test/common/util.py
# def build_test_model(
# override_dict=None,
# scenario=None,
# model_file="model.yaml",
# timeseries_dataframes=None,
# ):
# def check_error_or_warning(error_warning, test_string_or_strings):
# def check_variable_exists(backend_model, constraint, variable, idx=None):
. Output only the next line. | assert np.array_equal( |
Using the snippet: <|code_start|>
@pytest.fixture(scope="class")
def model():
return build_model({}, "simple_supply,two_hours,investment_costs")
class TestGetParam:
<|code_end|>
, determine the next line of code. You have imports:
import pytest # noqa: F401
import pyomo.core as po
from calliope.test.common.util import build_test_model as build_model
from calliope.backend.pyomo.util import get_domain, get_param, invalid
and context (class names, function names, or code) available:
# Path: calliope/test/common/util.py
# def build_test_model(
# override_dict=None,
# scenario=None,
# model_file="model.yaml",
# timeseries_dataframes=None,
# ):
# return calliope.Model(
# os.path.join(os.path.dirname(__file__), "test_model", model_file),
# override_dict=override_dict,
# scenario=scenario,
# timeseries_dataframes=timeseries_dataframes,
# )
#
# Path: calliope/backend/pyomo/util.py
# def get_domain(var: xr.DataArray) -> str:
# def check_sign(var):
# if re.match("resource|node_coordinates|cost*", var.name):
# return ""
# else:
# return "NonNegative"
#
# if var.dtype.kind == "b":
# return "Boolean"
# elif is_numeric_dtype(var.dtype):
# return check_sign(var) + "Reals"
# else:
# return "Any"
#
# @memoize
# def get_param(backend_model, var, dims):
# """
# Get an input parameter held in a Pyomo object, or held in the defaults
# dictionary if that Pyomo object doesn't exist.
#
# Parameters
# ----------
# backend_model : Pyomo model instance
# var : str
# dims : single value or tuple
#
# """
# try:
# return getattr(backend_model, var)[dims]
# except AttributeError: # i.e. parameter doesn't exist at all
# logger.debug(
# "get_param: var {} and dims {} leading to default lookup".format(var, dims)
# )
# return backend_model.__calliope_defaults[var]
# except KeyError: # try removing timestep
# try:
# if len(dims) > 2:
# return getattr(backend_model, var)[dims[:-1]]
# else:
# return getattr(backend_model, var)[dims[0]]
# except KeyError: # Static default value
# logger.debug(
# "get_param: var {} and dims {} leading to default lookup".format(
# var, dims
# )
# )
# return backend_model.__calliope_defaults[var]
#
# def invalid(val) -> bool:
# if isinstance(val, po.base.param._ParamData):
# return val._value == po.Param.NoValue or po.value(val) is None
# elif val == po.Param.NoValue:
# return True
# else:
# return pd.isnull(val)
. Output only the next line. | def test_get_param_with_timestep_existing(self): |
Given the following code snippet before the placeholder: <|code_start|>
@pytest.fixture(scope="class")
def model():
return build_model({}, "simple_supply,two_hours,investment_costs")
<|code_end|>
, predict the next line using imports from the current file:
import pytest # noqa: F401
import pyomo.core as po
from calliope.test.common.util import build_test_model as build_model
from calliope.backend.pyomo.util import get_domain, get_param, invalid
and context including class names, function names, and sometimes code from other files:
# Path: calliope/test/common/util.py
# def build_test_model(
# override_dict=None,
# scenario=None,
# model_file="model.yaml",
# timeseries_dataframes=None,
# ):
# return calliope.Model(
# os.path.join(os.path.dirname(__file__), "test_model", model_file),
# override_dict=override_dict,
# scenario=scenario,
# timeseries_dataframes=timeseries_dataframes,
# )
#
# Path: calliope/backend/pyomo/util.py
# def get_domain(var: xr.DataArray) -> str:
# def check_sign(var):
# if re.match("resource|node_coordinates|cost*", var.name):
# return ""
# else:
# return "NonNegative"
#
# if var.dtype.kind == "b":
# return "Boolean"
# elif is_numeric_dtype(var.dtype):
# return check_sign(var) + "Reals"
# else:
# return "Any"
#
# @memoize
# def get_param(backend_model, var, dims):
# """
# Get an input parameter held in a Pyomo object, or held in the defaults
# dictionary if that Pyomo object doesn't exist.
#
# Parameters
# ----------
# backend_model : Pyomo model instance
# var : str
# dims : single value or tuple
#
# """
# try:
# return getattr(backend_model, var)[dims]
# except AttributeError: # i.e. parameter doesn't exist at all
# logger.debug(
# "get_param: var {} and dims {} leading to default lookup".format(var, dims)
# )
# return backend_model.__calliope_defaults[var]
# except KeyError: # try removing timestep
# try:
# if len(dims) > 2:
# return getattr(backend_model, var)[dims[:-1]]
# else:
# return getattr(backend_model, var)[dims[0]]
# except KeyError: # Static default value
# logger.debug(
# "get_param: var {} and dims {} leading to default lookup".format(
# var, dims
# )
# )
# return backend_model.__calliope_defaults[var]
#
# def invalid(val) -> bool:
# if isinstance(val, po.base.param._ParamData):
# return val._value == po.Param.NoValue or po.value(val) is None
# elif val == po.Param.NoValue:
# return True
# else:
# return pd.isnull(val)
. Output only the next line. | class TestGetParam: |
Given snippet: <|code_start|>
class TestDeprecationWarnings:
def test_get_formatted_array_deprecationwarning(self):
model = build_model(scenario="simple_supply,one_day,investment_costs")
model.run()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
import calliope
from calliope.test.common.util import build_test_model as build_model
from calliope.test.common.util import check_error_or_warning
and context:
# Path: calliope/test/common/util.py
# def build_test_model(
# override_dict=None,
# scenario=None,
# model_file="model.yaml",
# timeseries_dataframes=None,
# ):
# return calliope.Model(
# os.path.join(os.path.dirname(__file__), "test_model", model_file),
# override_dict=override_dict,
# scenario=scenario,
# timeseries_dataframes=timeseries_dataframes,
# )
#
# Path: calliope/test/common/util.py
# def check_error_or_warning(error_warning, test_string_or_strings):
# if hasattr(error_warning, "list"):
# output = ",".join(
# str(error_warning.list[i]) for i in range(len(error_warning.list))
# )
# else:
# output = str(error_warning.value)
#
# if isinstance(test_string_or_strings, list):
# result = all(test_string in output for test_string in test_string_or_strings)
# else:
# result = test_string_or_strings in output
#
# return result
which might include code, classes, or functions. Output only the next line. | with pytest.warns(DeprecationWarning) as warning: |
Next line prediction: <|code_start|>
class TestDeprecationWarnings:
def test_get_formatted_array_deprecationwarning(self):
model = build_model(scenario="simple_supply,one_day,investment_costs")
model.run()
with pytest.warns(DeprecationWarning) as warning:
model.get_formatted_array("carrier_prod")
assert check_error_or_warning(warning, "get_formatted_array() is deprecated")
def test_locations_instead_of_nodes(self):
with pytest.warns(DeprecationWarning) as warning:
model = build_model(
scenario="simple_supply_locations,one_day,investment_costs"
<|code_end|>
. Use current file imports:
(import pytest
import calliope
from calliope.test.common.util import build_test_model as build_model
from calliope.test.common.util import check_error_or_warning)
and context including class names, function names, or small code snippets from other files:
# Path: calliope/test/common/util.py
# def build_test_model(
# override_dict=None,
# scenario=None,
# model_file="model.yaml",
# timeseries_dataframes=None,
# ):
# return calliope.Model(
# os.path.join(os.path.dirname(__file__), "test_model", model_file),
# override_dict=override_dict,
# scenario=scenario,
# timeseries_dataframes=timeseries_dataframes,
# )
#
# Path: calliope/test/common/util.py
# def check_error_or_warning(error_warning, test_string_or_strings):
# if hasattr(error_warning, "list"):
# output = ",".join(
# str(error_warning.list[i]) for i in range(len(error_warning.list))
# )
# else:
# output = str(error_warning.value)
#
# if isinstance(test_string_or_strings, list):
# result = all(test_string in output for test_string in test_string_or_strings)
# else:
# result = test_string_or_strings in output
#
# return result
. Output only the next line. | ) |
Here is a snippet: <|code_start|> Parameters
----------
data : xarray Dataset
Dataset with all non-time dependent variables removed
Returns
-------
ds : xarray Dataset
Copy of `data`, with the absolute taken and normalized to 0-1
"""
ds = data.copy(deep=True) # Work off a copy
for var in ds.data_vars:
ds[var] = abs(ds[var] / abs(ds[var]).groupby("techs").max(..., skipna=True))
return ds
def _copy_non_t_vars(data0, data1):
"""Copies non-t-indexed variables from data0 into data1, then
returns data1"""
non_t_vars = [
varname
for varname, vardata in data0.data_vars.items()
if "timesteps" not in vardata.dims
]
# Manually copy over variables not in `timesteps`. If we don't do this,
# these vars get polluted with a superfluous `timesteps` dimension
for v in non_t_vars:
data1[v] = data0[v]
<|code_end|>
. Write the next line using the current file imports:
import logging
import datetime
import numpy as np
import pandas as pd
import xarray as xr
from calliope import exceptions
from calliope.time import clustering
and context from other files:
# Path: calliope/exceptions.py
# def _formatwarning(message, category, filename, lineno, line=None):
# def warn(message, _class=ModelWarning):
# def print_warnings_and_raise_errors(warnings=None, errors=None):
# class ModelError(Exception):
# class BackendError(Exception):
# class ModelWarning(Warning):
# class BackendWarning(Warning):
#
# Path: calliope/time/clustering.py
# def _stack_data(data, dates, times):
# def reshape_for_clustering(data, loc_techs=None, variables=None):
# def get_mean_from_clusters(data, clusters, timesteps_per_day):
# def find_nearest_vector_index(array, value, metric="rmse"):
# def get_closest_days_from_clusters(data, mean_data, clusters, daily_timesteps):
# def _timesteps_from_daily_index(idx, daily_timesteps):
# def map_clusters_to_data(
# data, clusters, how, daily_timesteps, storage_inter_cluster=True
# ):
# def get_clusters(
# data,
# func,
# timesteps_per_day,
# tech=None,
# timesteps=None,
# k=None,
# variables=None,
# **kwargs,
# ):
# def hartigan_n_clusters(X, threshold=10):
# def _H_rule(inertia, inertia_plus_one, n_clusters, len_input):
# X = np.nan_to_num(reshaped_data, nan=0.0, posinf=0.0, neginf=0.0)
# X = reshape_for_clustering(data, tech, variables)
# HK = threshold + 1
# HK = _H_rule(inertia, inertia_plus_one, n_clusters, len_input)
, which may include functions, classes, or code. Output only the next line. | return data1 |
Using the snippet: <|code_start|> Parameters
----------
data : xarray Dataset
Dataset with all non-time dependent variables removed
Returns
-------
ds : xarray Dataset
Copy of `data`, with the absolute taken and normalized to 0-1
"""
ds = data.copy(deep=True) # Work off a copy
for var in ds.data_vars:
ds[var] = abs(ds[var] / abs(ds[var]).groupby("techs").max(..., skipna=True))
return ds
def _copy_non_t_vars(data0, data1):
"""Copies non-t-indexed variables from data0 into data1, then
returns data1"""
non_t_vars = [
varname
for varname, vardata in data0.data_vars.items()
if "timesteps" not in vardata.dims
]
# Manually copy over variables not in `timesteps`. If we don't do this,
# these vars get polluted with a superfluous `timesteps` dimension
for v in non_t_vars:
data1[v] = data0[v]
<|code_end|>
, determine the next line of code. You have imports:
import logging
import datetime
import numpy as np
import pandas as pd
import xarray as xr
from calliope import exceptions
from calliope.time import clustering
and context (class names, function names, or code) available:
# Path: calliope/exceptions.py
# def _formatwarning(message, category, filename, lineno, line=None):
# def warn(message, _class=ModelWarning):
# def print_warnings_and_raise_errors(warnings=None, errors=None):
# class ModelError(Exception):
# class BackendError(Exception):
# class ModelWarning(Warning):
# class BackendWarning(Warning):
#
# Path: calliope/time/clustering.py
# def _stack_data(data, dates, times):
# def reshape_for_clustering(data, loc_techs=None, variables=None):
# def get_mean_from_clusters(data, clusters, timesteps_per_day):
# def find_nearest_vector_index(array, value, metric="rmse"):
# def get_closest_days_from_clusters(data, mean_data, clusters, daily_timesteps):
# def _timesteps_from_daily_index(idx, daily_timesteps):
# def map_clusters_to_data(
# data, clusters, how, daily_timesteps, storage_inter_cluster=True
# ):
# def get_clusters(
# data,
# func,
# timesteps_per_day,
# tech=None,
# timesteps=None,
# k=None,
# variables=None,
# **kwargs,
# ):
# def hartigan_n_clusters(X, threshold=10):
# def _H_rule(inertia, inertia_plus_one, n_clusters, len_input):
# X = np.nan_to_num(reshaped_data, nan=0.0, posinf=0.0, neginf=0.0)
# X = reshape_for_clustering(data, tech, variables)
# HK = threshold + 1
# HK = _H_rule(inertia, inertia_plus_one, n_clusters, len_input)
. Output only the next line. | return data1 |
Given the code snippet: <|code_start|>
def build_model(override_dict, scenario):
model_path = os.path.join(
os.path.dirname(__file__), "common", "test_model", "model.yaml"
)
return calliope.Model(model_path, override_dict=override_dict, scenario=scenario)
<|code_end|>
, generate the next line using the imports in this file:
import os
import pytest # noqa: F401
import calliope
from calliope import exceptions
from calliope.test.common.util import check_error_or_warning
and context (functions, classes, or occasionally code) from other files:
# Path: calliope/exceptions.py
# def _formatwarning(message, category, filename, lineno, line=None):
# def warn(message, _class=ModelWarning):
# def print_warnings_and_raise_errors(warnings=None, errors=None):
# class ModelError(Exception):
# class BackendError(Exception):
# class ModelWarning(Warning):
# class BackendWarning(Warning):
#
# Path: calliope/test/common/util.py
# def check_error_or_warning(error_warning, test_string_or_strings):
# if hasattr(error_warning, "list"):
# output = ",".join(
# str(error_warning.list[i]) for i in range(len(error_warning.list))
# )
# else:
# output = str(error_warning.value)
#
# if isinstance(test_string_or_strings, list):
# result = all(test_string in output for test_string in test_string_or_strings)
# else:
# result = test_string_or_strings in output
#
# return result
. Output only the next line. | class TestExistsFalse: |
Given snippet: <|code_start|>
def build_model(override_dict, scenario):
model_path = os.path.join(
os.path.dirname(__file__), "common", "test_model", "model.yaml"
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import pytest # noqa: F401
import calliope
from calliope import exceptions
from calliope.test.common.util import check_error_or_warning
and context:
# Path: calliope/exceptions.py
# def _formatwarning(message, category, filename, lineno, line=None):
# def warn(message, _class=ModelWarning):
# def print_warnings_and_raise_errors(warnings=None, errors=None):
# class ModelError(Exception):
# class BackendError(Exception):
# class ModelWarning(Warning):
# class BackendWarning(Warning):
#
# Path: calliope/test/common/util.py
# def check_error_or_warning(error_warning, test_string_or_strings):
# if hasattr(error_warning, "list"):
# output = ",".join(
# str(error_warning.list[i]) for i in range(len(error_warning.list))
# )
# else:
# output = str(error_warning.value)
#
# if isinstance(test_string_or_strings, list):
# result = all(test_string in output for test_string in test_string_or_strings)
# else:
# result = test_string_or_strings in output
#
# return result
which might include code, classes, or functions. Output only the next line. | ) |
Using the snippet: <|code_start|>
# Infeasible case, unmet_demand is required
assert hasattr(model_unmet_demand._backend_model, "unmet_demand")
assert hasattr(model_unmet_demand._backend_model, "unused_supply")
assert model_unmet_demand._model_data["unmet_demand"].sum() == 15
assert "unused_supply" not in model_unmet_demand._model_data.data_vars.keys()
def test_unmet_supply_nonzero(self, model_unused_supply):
# Infeasible case, unused_supply is required
assert hasattr(model_unused_supply._backend_model, "unmet_demand")
assert hasattr(model_unused_supply._backend_model, "unused_supply")
assert model_unused_supply._model_data["unmet_demand"].sum() == -15
assert "unused_supply" not in model_unused_supply._model_data.data_vars.keys()
def test_expected_impact_on_objective_function_value(
self, model_no_unmet, model_unmet_demand, model_unused_supply
):
assert (
model_unused_supply._backend_model.obj.expr()
- model_no_unmet._backend_model.obj.expr()
== approx(1e3 * 15)
)
assert (
model_unmet_demand._backend_model.obj.expr()
- model_no_unmet._backend_model.obj.expr()
== approx(1e3 * 15)
)
@pytest.mark.parametrize("override", (5, 15))
<|code_end|>
, determine the next line of code. You have imports:
import pytest
import calliope
from pytest import approx
from calliope.test.common.util import build_test_model as build_model
and context (class names, function names, or code) available:
# Path: calliope/test/common/util.py
# def build_test_model(
# override_dict=None,
# scenario=None,
# model_file="model.yaml",
# timeseries_dataframes=None,
# ):
# return calliope.Model(
# os.path.join(os.path.dirname(__file__), "test_model", model_file),
# override_dict=override_dict,
# scenario=scenario,
# timeseries_dataframes=timeseries_dataframes,
# )
. Output only the next line. | def test_expected_infeasible_result(self, override, run_model): |
Given the code snippet: <|code_start|>
def test_simple_case(tmpdir):
x = tmpdir.join('f')
x.write('#!/usr/bin/env echo')
make_executable(x.strpath)
assert parse_shebang.parse_filename(x.strpath) == ('echo',)
def test_find_executable_full_path():
assert parse_shebang.find_executable(sys.executable) == sys.executable
def test_find_executable_on_path():
assert parse_shebang.find_executable('echo') == _echo_exe()
def test_find_executable_not_found_none():
assert parse_shebang.find_executable('not-a-real-executable') is None
def write_executable(shebang, filename='run'):
os.mkdir('bin')
path = os.path.join('bin', filename)
with open(path, 'w') as f:
f.write(f'#!{shebang}')
make_executable(path)
return path
<|code_end|>
, generate the next line using the imports in this file:
import contextlib
import os.path
import shutil
import sys
import pytest
from pre_commit import parse_shebang
from pre_commit.envcontext import envcontext
from pre_commit.envcontext import Var
from pre_commit.util import make_executable
and context (functions, classes, or occasionally code) from other files:
# Path: pre_commit/parse_shebang.py
# class ExecutableNotFoundError(OSError):
# def to_output(self) -> tuple[int, bytes, None]:
# def parse_filename(filename: str) -> tuple[str, ...]:
# def find_executable(
# exe: str, _environ: Mapping[str, str] | None = None,
# ) -> str | None:
# def normexe(orig: str) -> str:
# def _error(msg: str) -> NoReturn:
# def normalize_cmd(cmd: tuple[str, ...]) -> tuple[str, ...]:
#
# Path: pre_commit/envcontext.py
# @contextlib.contextmanager
# def envcontext(
# patch: PatchesT,
# _env: MutableMapping[str, str] | None = None,
# ) -> Generator[None, None, None]:
# """In this context, `os.environ` is modified according to `patch`.
#
# `patch` is an iterable of 2-tuples (key, value):
# `key`: string
# `value`:
# - string: `environ[key] == value` inside the context.
# - UNSET: `key not in environ` inside the context.
# - template: A template is a tuple of strings and Var which will be
# replaced with the previous environment
# """
# env = os.environ if _env is None else _env
# before = dict(env)
#
# for k, v in patch:
# if v is UNSET:
# env.pop(k, None)
# elif isinstance(v, tuple):
# env[k] = format_env(v, before)
# else:
# env[k] = v
#
# try:
# yield
# finally:
# env.clear()
# env.update(before)
#
# Path: pre_commit/envcontext.py
# class Var(NamedTuple):
# name: str
# default: str = ''
#
# Path: pre_commit/util.py
# def make_executable(filename: str) -> None:
# original_mode = os.stat(filename).st_mode
# new_mode = original_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
# os.chmod(filename, new_mode)
. Output only the next line. | @contextlib.contextmanager |
Given the code snippet: <|code_start|>from __future__ import annotations
def _echo_exe() -> str:
exe = shutil.which('echo')
assert exe is not None
return exe
def test_file_doesnt_exist():
assert parse_shebang.parse_filename('herp derp derp') == ()
def test_simple_case(tmpdir):
<|code_end|>
, generate the next line using the imports in this file:
import contextlib
import os.path
import shutil
import sys
import pytest
from pre_commit import parse_shebang
from pre_commit.envcontext import envcontext
from pre_commit.envcontext import Var
from pre_commit.util import make_executable
and context (functions, classes, or occasionally code) from other files:
# Path: pre_commit/parse_shebang.py
# class ExecutableNotFoundError(OSError):
# def to_output(self) -> tuple[int, bytes, None]:
# def parse_filename(filename: str) -> tuple[str, ...]:
# def find_executable(
# exe: str, _environ: Mapping[str, str] | None = None,
# ) -> str | None:
# def normexe(orig: str) -> str:
# def _error(msg: str) -> NoReturn:
# def normalize_cmd(cmd: tuple[str, ...]) -> tuple[str, ...]:
#
# Path: pre_commit/envcontext.py
# @contextlib.contextmanager
# def envcontext(
# patch: PatchesT,
# _env: MutableMapping[str, str] | None = None,
# ) -> Generator[None, None, None]:
# """In this context, `os.environ` is modified according to `patch`.
#
# `patch` is an iterable of 2-tuples (key, value):
# `key`: string
# `value`:
# - string: `environ[key] == value` inside the context.
# - UNSET: `key not in environ` inside the context.
# - template: A template is a tuple of strings and Var which will be
# replaced with the previous environment
# """
# env = os.environ if _env is None else _env
# before = dict(env)
#
# for k, v in patch:
# if v is UNSET:
# env.pop(k, None)
# elif isinstance(v, tuple):
# env[k] = format_env(v, before)
# else:
# env[k] = v
#
# try:
# yield
# finally:
# env.clear()
# env.update(before)
#
# Path: pre_commit/envcontext.py
# class Var(NamedTuple):
# name: str
# default: str = ''
#
# Path: pre_commit/util.py
# def make_executable(filename: str) -> None:
# original_mode = os.stat(filename).st_mode
# new_mode = original_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
# os.chmod(filename, new_mode)
. Output only the next line. | x = tmpdir.join('f') |
Given snippet: <|code_start|>
def _echo_exe() -> str:
exe = shutil.which('echo')
assert exe is not None
return exe
def test_file_doesnt_exist():
assert parse_shebang.parse_filename('herp derp derp') == ()
def test_simple_case(tmpdir):
x = tmpdir.join('f')
x.write('#!/usr/bin/env echo')
make_executable(x.strpath)
assert parse_shebang.parse_filename(x.strpath) == ('echo',)
def test_find_executable_full_path():
assert parse_shebang.find_executable(sys.executable) == sys.executable
def test_find_executable_on_path():
assert parse_shebang.find_executable('echo') == _echo_exe()
def test_find_executable_not_found_none():
assert parse_shebang.find_executable('not-a-real-executable') is None
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import contextlib
import os.path
import shutil
import sys
import pytest
from pre_commit import parse_shebang
from pre_commit.envcontext import envcontext
from pre_commit.envcontext import Var
from pre_commit.util import make_executable
and context:
# Path: pre_commit/parse_shebang.py
# class ExecutableNotFoundError(OSError):
# def to_output(self) -> tuple[int, bytes, None]:
# def parse_filename(filename: str) -> tuple[str, ...]:
# def find_executable(
# exe: str, _environ: Mapping[str, str] | None = None,
# ) -> str | None:
# def normexe(orig: str) -> str:
# def _error(msg: str) -> NoReturn:
# def normalize_cmd(cmd: tuple[str, ...]) -> tuple[str, ...]:
#
# Path: pre_commit/envcontext.py
# @contextlib.contextmanager
# def envcontext(
# patch: PatchesT,
# _env: MutableMapping[str, str] | None = None,
# ) -> Generator[None, None, None]:
# """In this context, `os.environ` is modified according to `patch`.
#
# `patch` is an iterable of 2-tuples (key, value):
# `key`: string
# `value`:
# - string: `environ[key] == value` inside the context.
# - UNSET: `key not in environ` inside the context.
# - template: A template is a tuple of strings and Var which will be
# replaced with the previous environment
# """
# env = os.environ if _env is None else _env
# before = dict(env)
#
# for k, v in patch:
# if v is UNSET:
# env.pop(k, None)
# elif isinstance(v, tuple):
# env[k] = format_env(v, before)
# else:
# env[k] = v
#
# try:
# yield
# finally:
# env.clear()
# env.update(before)
#
# Path: pre_commit/envcontext.py
# class Var(NamedTuple):
# name: str
# default: str = ''
#
# Path: pre_commit/util.py
# def make_executable(filename: str) -> None:
# original_mode = os.stat(filename).st_mode
# new_mode = original_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
# os.chmod(filename, new_mode)
which might include code, classes, or functions. Output only the next line. | def write_executable(shebang, filename='run'): |
Given the following code snippet before the placeholder: <|code_start|>
def test_find_executable_full_path():
assert parse_shebang.find_executable(sys.executable) == sys.executable
def test_find_executable_on_path():
assert parse_shebang.find_executable('echo') == _echo_exe()
def test_find_executable_not_found_none():
assert parse_shebang.find_executable('not-a-real-executable') is None
def write_executable(shebang, filename='run'):
os.mkdir('bin')
path = os.path.join('bin', filename)
with open(path, 'w') as f:
f.write(f'#!{shebang}')
make_executable(path)
return path
@contextlib.contextmanager
def bin_on_path():
bindir = os.path.join(os.getcwd(), 'bin')
with envcontext((('PATH', (bindir, os.pathsep, Var('PATH'))),)):
yield
def test_find_executable_path_added(in_tmpdir):
<|code_end|>
, predict the next line using imports from the current file:
import contextlib
import os.path
import shutil
import sys
import pytest
from pre_commit import parse_shebang
from pre_commit.envcontext import envcontext
from pre_commit.envcontext import Var
from pre_commit.util import make_executable
and context including class names, function names, and sometimes code from other files:
# Path: pre_commit/parse_shebang.py
# class ExecutableNotFoundError(OSError):
# def to_output(self) -> tuple[int, bytes, None]:
# def parse_filename(filename: str) -> tuple[str, ...]:
# def find_executable(
# exe: str, _environ: Mapping[str, str] | None = None,
# ) -> str | None:
# def normexe(orig: str) -> str:
# def _error(msg: str) -> NoReturn:
# def normalize_cmd(cmd: tuple[str, ...]) -> tuple[str, ...]:
#
# Path: pre_commit/envcontext.py
# @contextlib.contextmanager
# def envcontext(
# patch: PatchesT,
# _env: MutableMapping[str, str] | None = None,
# ) -> Generator[None, None, None]:
# """In this context, `os.environ` is modified according to `patch`.
#
# `patch` is an iterable of 2-tuples (key, value):
# `key`: string
# `value`:
# - string: `environ[key] == value` inside the context.
# - UNSET: `key not in environ` inside the context.
# - template: A template is a tuple of strings and Var which will be
# replaced with the previous environment
# """
# env = os.environ if _env is None else _env
# before = dict(env)
#
# for k, v in patch:
# if v is UNSET:
# env.pop(k, None)
# elif isinstance(v, tuple):
# env[k] = format_env(v, before)
# else:
# env[k] = v
#
# try:
# yield
# finally:
# env.clear()
# env.update(before)
#
# Path: pre_commit/envcontext.py
# class Var(NamedTuple):
# name: str
# default: str = ''
#
# Path: pre_commit/util.py
# def make_executable(filename: str) -> None:
# original_mode = os.stat(filename).st_mode
# new_mode = original_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
# os.chmod(filename, new_mode)
. Output only the next line. | path = os.path.abspath(write_executable('/usr/bin/env sh')) |
Predict the next line for this snippet: <|code_start|> os.name == 'nt',
reason="lua isn't installed or can't be found",
)
skipif_cant_run_swift = pytest.mark.skipif(
parse_shebang.find_executable('swift') is None,
reason="swift isn't installed or can't be found",
)
xfailif_windows = pytest.mark.xfail(os.name == 'nt', reason='windows')
def run_opts(
all_files=False,
files=(),
color=False,
verbose=False,
hook=None,
remote_branch='',
local_branch='',
from_ref='',
to_ref='',
remote_name='',
remote_url='',
hook_stage='commit',
show_diff_on_failure=False,
commit_msg_filename='',
checkout_type='',
is_squash_merge='',
rewrite_command='',
):
# These are mutually exclusive
<|code_end|>
with the help of current file imports:
import contextlib
import os.path
import subprocess
import pytest
from pre_commit import parse_shebang
from pre_commit.util import CalledProcessError
from pre_commit.util import cmd_output
from pre_commit.util import cmd_output_b
from testing.auto_namedtuple import auto_namedtuple
and context from other files:
# Path: pre_commit/parse_shebang.py
# class ExecutableNotFoundError(OSError):
# def to_output(self) -> tuple[int, bytes, None]:
# def parse_filename(filename: str) -> tuple[str, ...]:
# def find_executable(
# exe: str, _environ: Mapping[str, str] | None = None,
# ) -> str | None:
# def normexe(orig: str) -> str:
# def _error(msg: str) -> NoReturn:
# def normalize_cmd(cmd: tuple[str, ...]) -> tuple[str, ...]:
#
# Path: pre_commit/util.py
# class CalledProcessError(RuntimeError):
# def __init__(
# self,
# returncode: int,
# cmd: tuple[str, ...],
# expected_returncode: int,
# stdout: bytes,
# stderr: bytes | None,
# ) -> None:
# super().__init__(returncode, cmd, expected_returncode, stdout, stderr)
# self.returncode = returncode
# self.cmd = cmd
# self.expected_returncode = expected_returncode
# self.stdout = stdout
# self.stderr = stderr
#
# def __bytes__(self) -> bytes:
# def _indent_or_none(part: bytes | None) -> bytes:
# if part:
# return b'\n ' + part.replace(b'\n', b'\n ')
# else:
# return b' (none)'
#
# return b''.join((
# f'command: {self.cmd!r}\n'.encode(),
# f'return code: {self.returncode}\n'.encode(),
# f'expected return code: {self.expected_returncode}\n'.encode(),
# b'stdout:', _indent_or_none(self.stdout), b'\n',
# b'stderr:', _indent_or_none(self.stderr),
# ))
#
# def __str__(self) -> str:
# return self.__bytes__().decode()
#
# Path: pre_commit/util.py
# def cmd_output(*cmd: str, **kwargs: Any) -> tuple[int, str, str | None]:
# returncode, stdout_b, stderr_b = cmd_output_b(*cmd, **kwargs)
# stdout = stdout_b.decode() if stdout_b is not None else None
# stderr = stderr_b.decode() if stderr_b is not None else None
# return returncode, stdout, stderr
#
# Path: pre_commit/util.py
# def cmd_output_b(
# *cmd: str,
# retcode: int | None = 0,
# **kwargs: Any,
# ) -> tuple[int, bytes, bytes | None]:
# _setdefault_kwargs(kwargs)
#
# try:
# cmd = parse_shebang.normalize_cmd(cmd)
# except parse_shebang.ExecutableNotFoundError as e:
# returncode, stdout_b, stderr_b = e.to_output()
# else:
# try:
# proc = subprocess.Popen(cmd, **kwargs)
# except OSError as e:
# returncode, stdout_b, stderr_b = _oserror_to_output(e)
# else:
# stdout_b, stderr_b = proc.communicate()
# returncode = proc.returncode
#
# if retcode is not None and retcode != returncode:
# raise CalledProcessError(returncode, cmd, retcode, stdout_b, stderr_b)
#
# return returncode, stdout_b, stderr_b
#
# Path: testing/auto_namedtuple.py
# def auto_namedtuple(classname='auto_namedtuple', **kwargs):
# """Returns an automatic namedtuple object.
#
# Args:
# classname - The class name for the returned object.
# **kwargs - Properties to give the returned object.
# """
# return (collections.namedtuple(classname, kwargs.keys())(**kwargs))
, which may contain function names, class names, or code. Output only the next line. | assert not (all_files and files) |
Based on the snippet: <|code_start|> verbose=verbose,
hook=hook,
remote_branch=remote_branch,
local_branch=local_branch,
from_ref=from_ref,
to_ref=to_ref,
remote_name=remote_name,
remote_url=remote_url,
hook_stage=hook_stage,
show_diff_on_failure=show_diff_on_failure,
commit_msg_filename=commit_msg_filename,
checkout_type=checkout_type,
is_squash_merge=is_squash_merge,
rewrite_command=rewrite_command,
)
@contextlib.contextmanager
def cwd(path):
original_cwd = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(original_cwd)
def git_commit(*args, fn=cmd_output, msg='commit!', all_files=True, **kwargs):
kwargs.setdefault('stderr', subprocess.STDOUT)
<|code_end|>
, predict the immediate next line with the help of imports:
import contextlib
import os.path
import subprocess
import pytest
from pre_commit import parse_shebang
from pre_commit.util import CalledProcessError
from pre_commit.util import cmd_output
from pre_commit.util import cmd_output_b
from testing.auto_namedtuple import auto_namedtuple
and context (classes, functions, sometimes code) from other files:
# Path: pre_commit/parse_shebang.py
# class ExecutableNotFoundError(OSError):
# def to_output(self) -> tuple[int, bytes, None]:
# def parse_filename(filename: str) -> tuple[str, ...]:
# def find_executable(
# exe: str, _environ: Mapping[str, str] | None = None,
# ) -> str | None:
# def normexe(orig: str) -> str:
# def _error(msg: str) -> NoReturn:
# def normalize_cmd(cmd: tuple[str, ...]) -> tuple[str, ...]:
#
# Path: pre_commit/util.py
# class CalledProcessError(RuntimeError):
# def __init__(
# self,
# returncode: int,
# cmd: tuple[str, ...],
# expected_returncode: int,
# stdout: bytes,
# stderr: bytes | None,
# ) -> None:
# super().__init__(returncode, cmd, expected_returncode, stdout, stderr)
# self.returncode = returncode
# self.cmd = cmd
# self.expected_returncode = expected_returncode
# self.stdout = stdout
# self.stderr = stderr
#
# def __bytes__(self) -> bytes:
# def _indent_or_none(part: bytes | None) -> bytes:
# if part:
# return b'\n ' + part.replace(b'\n', b'\n ')
# else:
# return b' (none)'
#
# return b''.join((
# f'command: {self.cmd!r}\n'.encode(),
# f'return code: {self.returncode}\n'.encode(),
# f'expected return code: {self.expected_returncode}\n'.encode(),
# b'stdout:', _indent_or_none(self.stdout), b'\n',
# b'stderr:', _indent_or_none(self.stderr),
# ))
#
# def __str__(self) -> str:
# return self.__bytes__().decode()
#
# Path: pre_commit/util.py
# def cmd_output(*cmd: str, **kwargs: Any) -> tuple[int, str, str | None]:
# returncode, stdout_b, stderr_b = cmd_output_b(*cmd, **kwargs)
# stdout = stdout_b.decode() if stdout_b is not None else None
# stderr = stderr_b.decode() if stderr_b is not None else None
# return returncode, stdout, stderr
#
# Path: pre_commit/util.py
# def cmd_output_b(
# *cmd: str,
# retcode: int | None = 0,
# **kwargs: Any,
# ) -> tuple[int, bytes, bytes | None]:
# _setdefault_kwargs(kwargs)
#
# try:
# cmd = parse_shebang.normalize_cmd(cmd)
# except parse_shebang.ExecutableNotFoundError as e:
# returncode, stdout_b, stderr_b = e.to_output()
# else:
# try:
# proc = subprocess.Popen(cmd, **kwargs)
# except OSError as e:
# returncode, stdout_b, stderr_b = _oserror_to_output(e)
# else:
# stdout_b, stderr_b = proc.communicate()
# returncode = proc.returncode
#
# if retcode is not None and retcode != returncode:
# raise CalledProcessError(returncode, cmd, retcode, stdout_b, stderr_b)
#
# return returncode, stdout_b, stderr_b
#
# Path: testing/auto_namedtuple.py
# def auto_namedtuple(classname='auto_namedtuple', **kwargs):
# """Returns an automatic namedtuple object.
#
# Args:
# classname - The class name for the returned object.
# **kwargs - Properties to give the returned object.
# """
# return (collections.namedtuple(classname, kwargs.keys())(**kwargs))
. Output only the next line. | cmd = ('git', 'commit', '--allow-empty', '--no-gpg-sign', *args) |
Continue the code snippet: <|code_start|>
def cmd_output_mocked_pre_commit_home(
*args, tempdir_factory, pre_commit_home=None, env=None, **kwargs,
):
if pre_commit_home is None:
pre_commit_home = tempdir_factory.get()
env = env if env is not None else os.environ
kwargs.setdefault('stderr', subprocess.STDOUT)
# Don't want to write to the home directory
env = dict(env, PRE_COMMIT_HOME=pre_commit_home)
ret, out, _ = cmd_output(*args, env=env, **kwargs)
return ret, out.replace('\r\n', '\n'), None
skipif_cant_run_coursier = pytest.mark.skipif(
os.name == 'nt' or parse_shebang.find_executable('cs') is None,
reason="coursier isn't installed or can't be found",
)
skipif_cant_run_docker = pytest.mark.skipif(
os.name == 'nt' or not docker_is_running(),
reason="Docker isn't running or can't be accessed",
)
skipif_cant_run_lua = pytest.mark.skipif(
os.name == 'nt',
reason="lua isn't installed or can't be found",
)
skipif_cant_run_swift = pytest.mark.skipif(
parse_shebang.find_executable('swift') is None,
reason="swift isn't installed or can't be found",
<|code_end|>
. Use current file imports:
import contextlib
import os.path
import subprocess
import pytest
from pre_commit import parse_shebang
from pre_commit.util import CalledProcessError
from pre_commit.util import cmd_output
from pre_commit.util import cmd_output_b
from testing.auto_namedtuple import auto_namedtuple
and context (classes, functions, or code) from other files:
# Path: pre_commit/parse_shebang.py
# class ExecutableNotFoundError(OSError):
# def to_output(self) -> tuple[int, bytes, None]:
# def parse_filename(filename: str) -> tuple[str, ...]:
# def find_executable(
# exe: str, _environ: Mapping[str, str] | None = None,
# ) -> str | None:
# def normexe(orig: str) -> str:
# def _error(msg: str) -> NoReturn:
# def normalize_cmd(cmd: tuple[str, ...]) -> tuple[str, ...]:
#
# Path: pre_commit/util.py
# class CalledProcessError(RuntimeError):
# def __init__(
# self,
# returncode: int,
# cmd: tuple[str, ...],
# expected_returncode: int,
# stdout: bytes,
# stderr: bytes | None,
# ) -> None:
# super().__init__(returncode, cmd, expected_returncode, stdout, stderr)
# self.returncode = returncode
# self.cmd = cmd
# self.expected_returncode = expected_returncode
# self.stdout = stdout
# self.stderr = stderr
#
# def __bytes__(self) -> bytes:
# def _indent_or_none(part: bytes | None) -> bytes:
# if part:
# return b'\n ' + part.replace(b'\n', b'\n ')
# else:
# return b' (none)'
#
# return b''.join((
# f'command: {self.cmd!r}\n'.encode(),
# f'return code: {self.returncode}\n'.encode(),
# f'expected return code: {self.expected_returncode}\n'.encode(),
# b'stdout:', _indent_or_none(self.stdout), b'\n',
# b'stderr:', _indent_or_none(self.stderr),
# ))
#
# def __str__(self) -> str:
# return self.__bytes__().decode()
#
# Path: pre_commit/util.py
# def cmd_output(*cmd: str, **kwargs: Any) -> tuple[int, str, str | None]:
# returncode, stdout_b, stderr_b = cmd_output_b(*cmd, **kwargs)
# stdout = stdout_b.decode() if stdout_b is not None else None
# stderr = stderr_b.decode() if stderr_b is not None else None
# return returncode, stdout, stderr
#
# Path: pre_commit/util.py
# def cmd_output_b(
# *cmd: str,
# retcode: int | None = 0,
# **kwargs: Any,
# ) -> tuple[int, bytes, bytes | None]:
# _setdefault_kwargs(kwargs)
#
# try:
# cmd = parse_shebang.normalize_cmd(cmd)
# except parse_shebang.ExecutableNotFoundError as e:
# returncode, stdout_b, stderr_b = e.to_output()
# else:
# try:
# proc = subprocess.Popen(cmd, **kwargs)
# except OSError as e:
# returncode, stdout_b, stderr_b = _oserror_to_output(e)
# else:
# stdout_b, stderr_b = proc.communicate()
# returncode = proc.returncode
#
# if retcode is not None and retcode != returncode:
# raise CalledProcessError(returncode, cmd, retcode, stdout_b, stderr_b)
#
# return returncode, stdout_b, stderr_b
#
# Path: testing/auto_namedtuple.py
# def auto_namedtuple(classname='auto_namedtuple', **kwargs):
# """Returns an automatic namedtuple object.
#
# Args:
# classname - The class name for the returned object.
# **kwargs - Properties to give the returned object.
# """
# return (collections.namedtuple(classname, kwargs.keys())(**kwargs))
. Output only the next line. | ) |
Given the following code snippet before the placeholder: <|code_start|>
def run_opts(
all_files=False,
files=(),
color=False,
verbose=False,
hook=None,
remote_branch='',
local_branch='',
from_ref='',
to_ref='',
remote_name='',
remote_url='',
hook_stage='commit',
show_diff_on_failure=False,
commit_msg_filename='',
checkout_type='',
is_squash_merge='',
rewrite_command='',
):
# These are mutually exclusive
assert not (all_files and files)
return auto_namedtuple(
all_files=all_files,
files=files,
color=color,
verbose=verbose,
hook=hook,
remote_branch=remote_branch,
local_branch=local_branch,
<|code_end|>
, predict the next line using imports from the current file:
import contextlib
import os.path
import subprocess
import pytest
from pre_commit import parse_shebang
from pre_commit.util import CalledProcessError
from pre_commit.util import cmd_output
from pre_commit.util import cmd_output_b
from testing.auto_namedtuple import auto_namedtuple
and context including class names, function names, and sometimes code from other files:
# Path: pre_commit/parse_shebang.py
# class ExecutableNotFoundError(OSError):
# def to_output(self) -> tuple[int, bytes, None]:
# def parse_filename(filename: str) -> tuple[str, ...]:
# def find_executable(
# exe: str, _environ: Mapping[str, str] | None = None,
# ) -> str | None:
# def normexe(orig: str) -> str:
# def _error(msg: str) -> NoReturn:
# def normalize_cmd(cmd: tuple[str, ...]) -> tuple[str, ...]:
#
# Path: pre_commit/util.py
# class CalledProcessError(RuntimeError):
# def __init__(
# self,
# returncode: int,
# cmd: tuple[str, ...],
# expected_returncode: int,
# stdout: bytes,
# stderr: bytes | None,
# ) -> None:
# super().__init__(returncode, cmd, expected_returncode, stdout, stderr)
# self.returncode = returncode
# self.cmd = cmd
# self.expected_returncode = expected_returncode
# self.stdout = stdout
# self.stderr = stderr
#
# def __bytes__(self) -> bytes:
# def _indent_or_none(part: bytes | None) -> bytes:
# if part:
# return b'\n ' + part.replace(b'\n', b'\n ')
# else:
# return b' (none)'
#
# return b''.join((
# f'command: {self.cmd!r}\n'.encode(),
# f'return code: {self.returncode}\n'.encode(),
# f'expected return code: {self.expected_returncode}\n'.encode(),
# b'stdout:', _indent_or_none(self.stdout), b'\n',
# b'stderr:', _indent_or_none(self.stderr),
# ))
#
# def __str__(self) -> str:
# return self.__bytes__().decode()
#
# Path: pre_commit/util.py
# def cmd_output(*cmd: str, **kwargs: Any) -> tuple[int, str, str | None]:
# returncode, stdout_b, stderr_b = cmd_output_b(*cmd, **kwargs)
# stdout = stdout_b.decode() if stdout_b is not None else None
# stderr = stderr_b.decode() if stderr_b is not None else None
# return returncode, stdout, stderr
#
# Path: pre_commit/util.py
# def cmd_output_b(
# *cmd: str,
# retcode: int | None = 0,
# **kwargs: Any,
# ) -> tuple[int, bytes, bytes | None]:
# _setdefault_kwargs(kwargs)
#
# try:
# cmd = parse_shebang.normalize_cmd(cmd)
# except parse_shebang.ExecutableNotFoundError as e:
# returncode, stdout_b, stderr_b = e.to_output()
# else:
# try:
# proc = subprocess.Popen(cmd, **kwargs)
# except OSError as e:
# returncode, stdout_b, stderr_b = _oserror_to_output(e)
# else:
# stdout_b, stderr_b = proc.communicate()
# returncode = proc.returncode
#
# if retcode is not None and retcode != returncode:
# raise CalledProcessError(returncode, cmd, retcode, stdout_b, stderr_b)
#
# return returncode, stdout_b, stderr_b
#
# Path: testing/auto_namedtuple.py
# def auto_namedtuple(classname='auto_namedtuple', **kwargs):
# """Returns an automatic namedtuple object.
#
# Args:
# classname - The class name for the returned object.
# **kwargs - Properties to give the returned object.
# """
# return (collections.namedtuple(classname, kwargs.keys())(**kwargs))
. Output only the next line. | from_ref=from_ref, |
Using the snippet: <|code_start|> verbose=False,
hook=None,
remote_branch='',
local_branch='',
from_ref='',
to_ref='',
remote_name='',
remote_url='',
hook_stage='commit',
show_diff_on_failure=False,
commit_msg_filename='',
checkout_type='',
is_squash_merge='',
rewrite_command='',
):
# These are mutually exclusive
assert not (all_files and files)
return auto_namedtuple(
all_files=all_files,
files=files,
color=color,
verbose=verbose,
hook=hook,
remote_branch=remote_branch,
local_branch=local_branch,
from_ref=from_ref,
to_ref=to_ref,
remote_name=remote_name,
remote_url=remote_url,
hook_stage=hook_stage,
<|code_end|>
, determine the next line of code. You have imports:
import contextlib
import os.path
import subprocess
import pytest
from pre_commit import parse_shebang
from pre_commit.util import CalledProcessError
from pre_commit.util import cmd_output
from pre_commit.util import cmd_output_b
from testing.auto_namedtuple import auto_namedtuple
and context (class names, function names, or code) available:
# Path: pre_commit/parse_shebang.py
# class ExecutableNotFoundError(OSError):
# def to_output(self) -> tuple[int, bytes, None]:
# def parse_filename(filename: str) -> tuple[str, ...]:
# def find_executable(
# exe: str, _environ: Mapping[str, str] | None = None,
# ) -> str | None:
# def normexe(orig: str) -> str:
# def _error(msg: str) -> NoReturn:
# def normalize_cmd(cmd: tuple[str, ...]) -> tuple[str, ...]:
#
# Path: pre_commit/util.py
# class CalledProcessError(RuntimeError):
# def __init__(
# self,
# returncode: int,
# cmd: tuple[str, ...],
# expected_returncode: int,
# stdout: bytes,
# stderr: bytes | None,
# ) -> None:
# super().__init__(returncode, cmd, expected_returncode, stdout, stderr)
# self.returncode = returncode
# self.cmd = cmd
# self.expected_returncode = expected_returncode
# self.stdout = stdout
# self.stderr = stderr
#
# def __bytes__(self) -> bytes:
# def _indent_or_none(part: bytes | None) -> bytes:
# if part:
# return b'\n ' + part.replace(b'\n', b'\n ')
# else:
# return b' (none)'
#
# return b''.join((
# f'command: {self.cmd!r}\n'.encode(),
# f'return code: {self.returncode}\n'.encode(),
# f'expected return code: {self.expected_returncode}\n'.encode(),
# b'stdout:', _indent_or_none(self.stdout), b'\n',
# b'stderr:', _indent_or_none(self.stderr),
# ))
#
# def __str__(self) -> str:
# return self.__bytes__().decode()
#
# Path: pre_commit/util.py
# def cmd_output(*cmd: str, **kwargs: Any) -> tuple[int, str, str | None]:
# returncode, stdout_b, stderr_b = cmd_output_b(*cmd, **kwargs)
# stdout = stdout_b.decode() if stdout_b is not None else None
# stderr = stderr_b.decode() if stderr_b is not None else None
# return returncode, stdout, stderr
#
# Path: pre_commit/util.py
# def cmd_output_b(
# *cmd: str,
# retcode: int | None = 0,
# **kwargs: Any,
# ) -> tuple[int, bytes, bytes | None]:
# _setdefault_kwargs(kwargs)
#
# try:
# cmd = parse_shebang.normalize_cmd(cmd)
# except parse_shebang.ExecutableNotFoundError as e:
# returncode, stdout_b, stderr_b = e.to_output()
# else:
# try:
# proc = subprocess.Popen(cmd, **kwargs)
# except OSError as e:
# returncode, stdout_b, stderr_b = _oserror_to_output(e)
# else:
# stdout_b, stderr_b = proc.communicate()
# returncode = proc.returncode
#
# if retcode is not None and retcode != returncode:
# raise CalledProcessError(returncode, cmd, retcode, stdout_b, stderr_b)
#
# return returncode, stdout_b, stderr_b
#
# Path: testing/auto_namedtuple.py
# def auto_namedtuple(classname='auto_namedtuple', **kwargs):
# """Returns an automatic namedtuple object.
#
# Args:
# classname - The class name for the returned object.
# **kwargs - Properties to give the returned object.
# """
# return (collections.namedtuple(classname, kwargs.keys())(**kwargs))
. Output only the next line. | show_diff_on_failure=show_diff_on_failure, |
Given the following code snippet before the placeholder: <|code_start|>from __future__ import annotations
ENVIRONMENT_DIR = 'coursier'
get_default_version = helpers.basic_get_default_version
healthy = helpers.basic_healthy
def install_environment(
prefix: Prefix,
<|code_end|>
, predict the next line using imports from the current file:
import contextlib
import os
from typing import Generator
from typing import Sequence
from pre_commit.envcontext import envcontext
from pre_commit.envcontext import PatchesT
from pre_commit.envcontext import Var
from pre_commit.hook import Hook
from pre_commit.languages import helpers
from pre_commit.prefix import Prefix
from pre_commit.util import clean_path_on_failure
and context including class names, function names, and sometimes code from other files:
# Path: pre_commit/envcontext.py
# @contextlib.contextmanager
# def envcontext(
# patch: PatchesT,
# _env: MutableMapping[str, str] | None = None,
# ) -> Generator[None, None, None]:
# """In this context, `os.environ` is modified according to `patch`.
#
# `patch` is an iterable of 2-tuples (key, value):
# `key`: string
# `value`:
# - string: `environ[key] == value` inside the context.
# - UNSET: `key not in environ` inside the context.
# - template: A template is a tuple of strings and Var which will be
# replaced with the previous environment
# """
# env = os.environ if _env is None else _env
# before = dict(env)
#
# for k, v in patch:
# if v is UNSET:
# env.pop(k, None)
# elif isinstance(v, tuple):
# env[k] = format_env(v, before)
# else:
# env[k] = v
#
# try:
# yield
# finally:
# env.clear()
# env.update(before)
#
# Path: pre_commit/envcontext.py
# UNSET = _Unset.UNSET
# class Var(NamedTuple):
# def format_env(parts: SubstitutionT, env: MutableMapping[str, str]) -> str:
# def envcontext(
# patch: PatchesT,
# _env: MutableMapping[str, str] | None = None,
# ) -> Generator[None, None, None]:
#
# Path: pre_commit/envcontext.py
# class Var(NamedTuple):
# name: str
# default: str = ''
#
# Path: pre_commit/hook.py
# class Hook(NamedTuple):
# src: str
# prefix: Prefix
# id: str
# name: str
# entry: str
# language: str
# alias: str
# files: str
# exclude: str
# types: Sequence[str]
# types_or: Sequence[str]
# exclude_types: Sequence[str]
# additional_dependencies: Sequence[str]
# args: Sequence[str]
# always_run: bool
# fail_fast: bool
# pass_filenames: bool
# description: str
# language_version: str
# log_file: str
# minimum_pre_commit_version: str
# require_serial: bool
# stages: Sequence[str]
# verbose: bool
#
# @property
# def cmd(self) -> tuple[str, ...]:
# return (*shlex.split(self.entry), *self.args)
#
# @property
# def install_key(self) -> tuple[Prefix, str, str, tuple[str, ...]]:
# return (
# self.prefix,
# self.language,
# self.language_version,
# tuple(self.additional_dependencies),
# )
#
# @classmethod
# def create(cls, src: str, prefix: Prefix, dct: dict[str, Any]) -> Hook:
# # TODO: have cfgv do this (?)
# extra_keys = set(dct) - _KEYS
# if extra_keys:
# logger.warning(
# f'Unexpected key(s) present on {src} => {dct["id"]}: '
# f'{", ".join(sorted(extra_keys))}',
# )
# return cls(src=src, prefix=prefix, **{k: dct[k] for k in _KEYS})
#
# Path: pre_commit/languages/helpers.py
# FIXED_RANDOM_SEED = 1542676187
# SHIMS_RE = re.compile(r'[/\\]shims[/\\]')
# def exe_exists(exe: str) -> bool:
# def run_setup_cmd(prefix: Prefix, cmd: tuple[str, ...], **kwargs: Any) -> None:
# def environment_dir(d: None, language_version: str) -> None: ...
# def environment_dir(d: str, language_version: str) -> str: ...
# def environment_dir(d: str | None, language_version: str) -> str | None:
# def assert_version_default(binary: str, version: str) -> None:
# def assert_no_additional_deps(
# lang: str,
# additional_deps: Sequence[str],
# ) -> None:
# def basic_get_default_version() -> str:
# def basic_healthy(prefix: Prefix, language_version: str) -> bool:
# def no_install(
# prefix: Prefix,
# version: str,
# additional_dependencies: Sequence[str],
# ) -> NoReturn:
# def target_concurrency(hook: Hook) -> int:
# def _shuffled(seq: Sequence[str]) -> list[str]:
# def run_xargs(
# hook: Hook,
# cmd: tuple[str, ...],
# file_args: Sequence[str],
# **kwargs: Any,
# ) -> tuple[int, bytes]:
#
# Path: pre_commit/prefix.py
# class Prefix(NamedTuple):
# prefix_dir: str
#
# def path(self, *parts: str) -> str:
# return os.path.normpath(os.path.join(self.prefix_dir, *parts))
#
# def exists(self, *parts: str) -> bool:
# return os.path.exists(self.path(*parts))
#
# def star(self, end: str) -> tuple[str, ...]:
# paths = os.listdir(self.prefix_dir)
# return tuple(path for path in paths if path.endswith(end))
#
# Path: pre_commit/util.py
# @contextlib.contextmanager
# def clean_path_on_failure(path: str) -> Generator[None, None, None]:
# """Cleans up the directory on an exceptional failure."""
# try:
# yield
# except BaseException:
# if os.path.exists(path):
# rmtree(path)
# raise
. Output only the next line. | version: str, |
Predict the next line for this snippet: <|code_start|>from __future__ import annotations
ENVIRONMENT_DIR = 'coursier'
get_default_version = helpers.basic_get_default_version
healthy = helpers.basic_healthy
def install_environment(
prefix: Prefix,
version: str,
<|code_end|>
with the help of current file imports:
import contextlib
import os
from typing import Generator
from typing import Sequence
from pre_commit.envcontext import envcontext
from pre_commit.envcontext import PatchesT
from pre_commit.envcontext import Var
from pre_commit.hook import Hook
from pre_commit.languages import helpers
from pre_commit.prefix import Prefix
from pre_commit.util import clean_path_on_failure
and context from other files:
# Path: pre_commit/envcontext.py
# @contextlib.contextmanager
# def envcontext(
# patch: PatchesT,
# _env: MutableMapping[str, str] | None = None,
# ) -> Generator[None, None, None]:
# """In this context, `os.environ` is modified according to `patch`.
#
# `patch` is an iterable of 2-tuples (key, value):
# `key`: string
# `value`:
# - string: `environ[key] == value` inside the context.
# - UNSET: `key not in environ` inside the context.
# - template: A template is a tuple of strings and Var which will be
# replaced with the previous environment
# """
# env = os.environ if _env is None else _env
# before = dict(env)
#
# for k, v in patch:
# if v is UNSET:
# env.pop(k, None)
# elif isinstance(v, tuple):
# env[k] = format_env(v, before)
# else:
# env[k] = v
#
# try:
# yield
# finally:
# env.clear()
# env.update(before)
#
# Path: pre_commit/envcontext.py
# UNSET = _Unset.UNSET
# class Var(NamedTuple):
# def format_env(parts: SubstitutionT, env: MutableMapping[str, str]) -> str:
# def envcontext(
# patch: PatchesT,
# _env: MutableMapping[str, str] | None = None,
# ) -> Generator[None, None, None]:
#
# Path: pre_commit/envcontext.py
# class Var(NamedTuple):
# name: str
# default: str = ''
#
# Path: pre_commit/hook.py
# class Hook(NamedTuple):
# src: str
# prefix: Prefix
# id: str
# name: str
# entry: str
# language: str
# alias: str
# files: str
# exclude: str
# types: Sequence[str]
# types_or: Sequence[str]
# exclude_types: Sequence[str]
# additional_dependencies: Sequence[str]
# args: Sequence[str]
# always_run: bool
# fail_fast: bool
# pass_filenames: bool
# description: str
# language_version: str
# log_file: str
# minimum_pre_commit_version: str
# require_serial: bool
# stages: Sequence[str]
# verbose: bool
#
# @property
# def cmd(self) -> tuple[str, ...]:
# return (*shlex.split(self.entry), *self.args)
#
# @property
# def install_key(self) -> tuple[Prefix, str, str, tuple[str, ...]]:
# return (
# self.prefix,
# self.language,
# self.language_version,
# tuple(self.additional_dependencies),
# )
#
# @classmethod
# def create(cls, src: str, prefix: Prefix, dct: dict[str, Any]) -> Hook:
# # TODO: have cfgv do this (?)
# extra_keys = set(dct) - _KEYS
# if extra_keys:
# logger.warning(
# f'Unexpected key(s) present on {src} => {dct["id"]}: '
# f'{", ".join(sorted(extra_keys))}',
# )
# return cls(src=src, prefix=prefix, **{k: dct[k] for k in _KEYS})
#
# Path: pre_commit/languages/helpers.py
# FIXED_RANDOM_SEED = 1542676187
# SHIMS_RE = re.compile(r'[/\\]shims[/\\]')
# def exe_exists(exe: str) -> bool:
# def run_setup_cmd(prefix: Prefix, cmd: tuple[str, ...], **kwargs: Any) -> None:
# def environment_dir(d: None, language_version: str) -> None: ...
# def environment_dir(d: str, language_version: str) -> str: ...
# def environment_dir(d: str | None, language_version: str) -> str | None:
# def assert_version_default(binary: str, version: str) -> None:
# def assert_no_additional_deps(
# lang: str,
# additional_deps: Sequence[str],
# ) -> None:
# def basic_get_default_version() -> str:
# def basic_healthy(prefix: Prefix, language_version: str) -> bool:
# def no_install(
# prefix: Prefix,
# version: str,
# additional_dependencies: Sequence[str],
# ) -> NoReturn:
# def target_concurrency(hook: Hook) -> int:
# def _shuffled(seq: Sequence[str]) -> list[str]:
# def run_xargs(
# hook: Hook,
# cmd: tuple[str, ...],
# file_args: Sequence[str],
# **kwargs: Any,
# ) -> tuple[int, bytes]:
#
# Path: pre_commit/prefix.py
# class Prefix(NamedTuple):
# prefix_dir: str
#
# def path(self, *parts: str) -> str:
# return os.path.normpath(os.path.join(self.prefix_dir, *parts))
#
# def exists(self, *parts: str) -> bool:
# return os.path.exists(self.path(*parts))
#
# def star(self, end: str) -> tuple[str, ...]:
# paths = os.listdir(self.prefix_dir)
# return tuple(path for path in paths if path.endswith(end))
#
# Path: pre_commit/util.py
# @contextlib.contextmanager
# def clean_path_on_failure(path: str) -> Generator[None, None, None]:
# """Cleans up the directory on an exceptional failure."""
# try:
# yield
# except BaseException:
# if os.path.exists(path):
# rmtree(path)
# raise
, which may contain function names, class names, or code. Output only the next line. | additional_dependencies: Sequence[str], |
Here is a snippet: <|code_start|>from __future__ import annotations
ENVIRONMENT_DIR = None
get_default_version = helpers.basic_get_default_version
healthy = helpers.basic_healthy
install_environment = helpers.no_install
<|code_end|>
. Write the next line using the current file imports:
from typing import Sequence
from pre_commit.hook import Hook
from pre_commit.languages import helpers
and context from other files:
# Path: pre_commit/hook.py
# class Hook(NamedTuple):
# src: str
# prefix: Prefix
# id: str
# name: str
# entry: str
# language: str
# alias: str
# files: str
# exclude: str
# types: Sequence[str]
# types_or: Sequence[str]
# exclude_types: Sequence[str]
# additional_dependencies: Sequence[str]
# args: Sequence[str]
# always_run: bool
# fail_fast: bool
# pass_filenames: bool
# description: str
# language_version: str
# log_file: str
# minimum_pre_commit_version: str
# require_serial: bool
# stages: Sequence[str]
# verbose: bool
#
# @property
# def cmd(self) -> tuple[str, ...]:
# return (*shlex.split(self.entry), *self.args)
#
# @property
# def install_key(self) -> tuple[Prefix, str, str, tuple[str, ...]]:
# return (
# self.prefix,
# self.language,
# self.language_version,
# tuple(self.additional_dependencies),
# )
#
# @classmethod
# def create(cls, src: str, prefix: Prefix, dct: dict[str, Any]) -> Hook:
# # TODO: have cfgv do this (?)
# extra_keys = set(dct) - _KEYS
# if extra_keys:
# logger.warning(
# f'Unexpected key(s) present on {src} => {dct["id"]}: '
# f'{", ".join(sorted(extra_keys))}',
# )
# return cls(src=src, prefix=prefix, **{k: dct[k] for k in _KEYS})
#
# Path: pre_commit/languages/helpers.py
# FIXED_RANDOM_SEED = 1542676187
# SHIMS_RE = re.compile(r'[/\\]shims[/\\]')
# def exe_exists(exe: str) -> bool:
# def run_setup_cmd(prefix: Prefix, cmd: tuple[str, ...], **kwargs: Any) -> None:
# def environment_dir(d: None, language_version: str) -> None: ...
# def environment_dir(d: str, language_version: str) -> str: ...
# def environment_dir(d: str | None, language_version: str) -> str | None:
# def assert_version_default(binary: str, version: str) -> None:
# def assert_no_additional_deps(
# lang: str,
# additional_deps: Sequence[str],
# ) -> None:
# def basic_get_default_version() -> str:
# def basic_healthy(prefix: Prefix, language_version: str) -> bool:
# def no_install(
# prefix: Prefix,
# version: str,
# additional_dependencies: Sequence[str],
# ) -> NoReturn:
# def target_concurrency(hook: Hook) -> int:
# def _shuffled(seq: Sequence[str]) -> list[str]:
# def run_xargs(
# hook: Hook,
# cmd: tuple[str, ...],
# file_args: Sequence[str],
# **kwargs: Any,
# ) -> tuple[int, bytes]:
, which may include functions, classes, or code. Output only the next line. | def run_hook( |
Using the snippet: <|code_start|> tree_hash = cmd_output('git', 'write-tree')[1].strip()
merge_diff_filenames = zsplit(
cmd_output(
'git', 'diff', '--name-only', '--no-ext-diff', '-z',
'-m', tree_hash, 'HEAD', 'MERGE_HEAD',
)[1],
)
return set(merge_conflict_filenames) | set(merge_diff_filenames)
def get_staged_files(cwd: str | None = None) -> list[str]:
return zsplit(
cmd_output(
'git', 'diff', '--staged', '--name-only', '--no-ext-diff', '-z',
# Everything except for D
'--diff-filter=ACMRTUXB',
cwd=cwd,
)[1],
)
def intent_to_add_files() -> list[str]:
_, stdout, _ = cmd_output(
'git', 'status', '--ignore-submodules', '--porcelain', '-z',
)
parts = list(reversed(zsplit(stdout)))
intent_to_add = []
while parts:
line = parts.pop()
status, filename = line[:3], line[3:]
<|code_end|>
, determine the next line of code. You have imports:
import logging
import os.path
import sys
from typing import MutableMapping
from pre_commit.errors import FatalError
from pre_commit.util import CalledProcessError
from pre_commit.util import cmd_output
from pre_commit.util import cmd_output_b
and context (class names, function names, or code) available:
# Path: pre_commit/errors.py
# class FatalError(RuntimeError):
# pass
#
# Path: pre_commit/util.py
# class CalledProcessError(RuntimeError):
# def __init__(
# self,
# returncode: int,
# cmd: tuple[str, ...],
# expected_returncode: int,
# stdout: bytes,
# stderr: bytes | None,
# ) -> None:
# super().__init__(returncode, cmd, expected_returncode, stdout, stderr)
# self.returncode = returncode
# self.cmd = cmd
# self.expected_returncode = expected_returncode
# self.stdout = stdout
# self.stderr = stderr
#
# def __bytes__(self) -> bytes:
# def _indent_or_none(part: bytes | None) -> bytes:
# if part:
# return b'\n ' + part.replace(b'\n', b'\n ')
# else:
# return b' (none)'
#
# return b''.join((
# f'command: {self.cmd!r}\n'.encode(),
# f'return code: {self.returncode}\n'.encode(),
# f'expected return code: {self.expected_returncode}\n'.encode(),
# b'stdout:', _indent_or_none(self.stdout), b'\n',
# b'stderr:', _indent_or_none(self.stderr),
# ))
#
# def __str__(self) -> str:
# return self.__bytes__().decode()
#
# Path: pre_commit/util.py
# def cmd_output(*cmd: str, **kwargs: Any) -> tuple[int, str, str | None]:
# returncode, stdout_b, stderr_b = cmd_output_b(*cmd, **kwargs)
# stdout = stdout_b.decode() if stdout_b is not None else None
# stderr = stderr_b.decode() if stderr_b is not None else None
# return returncode, stdout, stderr
#
# Path: pre_commit/util.py
# def cmd_output_b(
# *cmd: str,
# retcode: int | None = 0,
# **kwargs: Any,
# ) -> tuple[int, bytes, bytes | None]:
# _setdefault_kwargs(kwargs)
#
# try:
# cmd = parse_shebang.normalize_cmd(cmd)
# except parse_shebang.ExecutableNotFoundError as e:
# returncode, stdout_b, stderr_b = e.to_output()
# else:
# try:
# proc = subprocess.Popen(cmd, **kwargs)
# except OSError as e:
# returncode, stdout_b, stderr_b = _oserror_to_output(e)
# else:
# stdout_b, stderr_b = proc.communicate()
# returncode = proc.returncode
#
# if retcode is not None and retcode != returncode:
# raise CalledProcessError(returncode, cmd, retcode, stdout_b, stderr_b)
#
# return returncode, stdout_b, stderr_b
. Output only the next line. | if status[0] in {'C', 'R'}: # renames / moves have an additional arg |
Predict the next line after this snippet: <|code_start|>from __future__ import annotations
logger = logging.getLogger(__name__)
# see #2046
NO_FS_MONITOR = ('-c', 'core.useBuiltinFSMonitor=false')
<|code_end|>
using the current file's imports:
import logging
import os.path
import sys
from typing import MutableMapping
from pre_commit.errors import FatalError
from pre_commit.util import CalledProcessError
from pre_commit.util import cmd_output
from pre_commit.util import cmd_output_b
and any relevant context from other files:
# Path: pre_commit/errors.py
# class FatalError(RuntimeError):
# pass
#
# Path: pre_commit/util.py
# class CalledProcessError(RuntimeError):
# def __init__(
# self,
# returncode: int,
# cmd: tuple[str, ...],
# expected_returncode: int,
# stdout: bytes,
# stderr: bytes | None,
# ) -> None:
# super().__init__(returncode, cmd, expected_returncode, stdout, stderr)
# self.returncode = returncode
# self.cmd = cmd
# self.expected_returncode = expected_returncode
# self.stdout = stdout
# self.stderr = stderr
#
# def __bytes__(self) -> bytes:
# def _indent_or_none(part: bytes | None) -> bytes:
# if part:
# return b'\n ' + part.replace(b'\n', b'\n ')
# else:
# return b' (none)'
#
# return b''.join((
# f'command: {self.cmd!r}\n'.encode(),
# f'return code: {self.returncode}\n'.encode(),
# f'expected return code: {self.expected_returncode}\n'.encode(),
# b'stdout:', _indent_or_none(self.stdout), b'\n',
# b'stderr:', _indent_or_none(self.stderr),
# ))
#
# def __str__(self) -> str:
# return self.__bytes__().decode()
#
# Path: pre_commit/util.py
# def cmd_output(*cmd: str, **kwargs: Any) -> tuple[int, str, str | None]:
# returncode, stdout_b, stderr_b = cmd_output_b(*cmd, **kwargs)
# stdout = stdout_b.decode() if stdout_b is not None else None
# stderr = stderr_b.decode() if stderr_b is not None else None
# return returncode, stdout, stderr
#
# Path: pre_commit/util.py
# def cmd_output_b(
# *cmd: str,
# retcode: int | None = 0,
# **kwargs: Any,
# ) -> tuple[int, bytes, bytes | None]:
# _setdefault_kwargs(kwargs)
#
# try:
# cmd = parse_shebang.normalize_cmd(cmd)
# except parse_shebang.ExecutableNotFoundError as e:
# returncode, stdout_b, stderr_b = e.to_output()
# else:
# try:
# proc = subprocess.Popen(cmd, **kwargs)
# except OSError as e:
# returncode, stdout_b, stderr_b = _oserror_to_output(e)
# else:
# stdout_b, stderr_b = proc.communicate()
# returncode = proc.returncode
#
# if retcode is not None and retcode != returncode:
# raise CalledProcessError(returncode, cmd, retcode, stdout_b, stderr_b)
#
# return returncode, stdout_b, stderr_b
. Output only the next line. | def zsplit(s: str) -> list[str]: |
Based on the snippet: <|code_start|> return zsplit(
cmd_output(
'git', 'diff', '--staged', '--name-only', '--no-ext-diff', '-z',
# Everything except for D
'--diff-filter=ACMRTUXB',
cwd=cwd,
)[1],
)
def intent_to_add_files() -> list[str]:
_, stdout, _ = cmd_output(
'git', 'status', '--ignore-submodules', '--porcelain', '-z',
)
parts = list(reversed(zsplit(stdout)))
intent_to_add = []
while parts:
line = parts.pop()
status, filename = line[:3], line[3:]
if status[0] in {'C', 'R'}: # renames / moves have an additional arg
parts.pop()
if status[1] == 'A':
intent_to_add.append(filename)
return intent_to_add
def get_all_files() -> list[str]:
return zsplit(cmd_output('git', 'ls-files', '-z')[1])
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
import os.path
import sys
from typing import MutableMapping
from pre_commit.errors import FatalError
from pre_commit.util import CalledProcessError
from pre_commit.util import cmd_output
from pre_commit.util import cmd_output_b
and context (classes, functions, sometimes code) from other files:
# Path: pre_commit/errors.py
# class FatalError(RuntimeError):
# pass
#
# Path: pre_commit/util.py
# class CalledProcessError(RuntimeError):
# def __init__(
# self,
# returncode: int,
# cmd: tuple[str, ...],
# expected_returncode: int,
# stdout: bytes,
# stderr: bytes | None,
# ) -> None:
# super().__init__(returncode, cmd, expected_returncode, stdout, stderr)
# self.returncode = returncode
# self.cmd = cmd
# self.expected_returncode = expected_returncode
# self.stdout = stdout
# self.stderr = stderr
#
# def __bytes__(self) -> bytes:
# def _indent_or_none(part: bytes | None) -> bytes:
# if part:
# return b'\n ' + part.replace(b'\n', b'\n ')
# else:
# return b' (none)'
#
# return b''.join((
# f'command: {self.cmd!r}\n'.encode(),
# f'return code: {self.returncode}\n'.encode(),
# f'expected return code: {self.expected_returncode}\n'.encode(),
# b'stdout:', _indent_or_none(self.stdout), b'\n',
# b'stderr:', _indent_or_none(self.stderr),
# ))
#
# def __str__(self) -> str:
# return self.__bytes__().decode()
#
# Path: pre_commit/util.py
# def cmd_output(*cmd: str, **kwargs: Any) -> tuple[int, str, str | None]:
# returncode, stdout_b, stderr_b = cmd_output_b(*cmd, **kwargs)
# stdout = stdout_b.decode() if stdout_b is not None else None
# stderr = stderr_b.decode() if stderr_b is not None else None
# return returncode, stdout, stderr
#
# Path: pre_commit/util.py
# def cmd_output_b(
# *cmd: str,
# retcode: int | None = 0,
# **kwargs: Any,
# ) -> tuple[int, bytes, bytes | None]:
# _setdefault_kwargs(kwargs)
#
# try:
# cmd = parse_shebang.normalize_cmd(cmd)
# except parse_shebang.ExecutableNotFoundError as e:
# returncode, stdout_b, stderr_b = e.to_output()
# else:
# try:
# proc = subprocess.Popen(cmd, **kwargs)
# except OSError as e:
# returncode, stdout_b, stderr_b = _oserror_to_output(e)
# else:
# stdout_b, stderr_b = proc.communicate()
# returncode = proc.returncode
#
# if retcode is not None and retcode != returncode:
# raise CalledProcessError(returncode, cmd, retcode, stdout_b, stderr_b)
#
# return returncode, stdout_b, stderr_b
. Output only the next line. | def get_changed_files(old: str, new: str) -> list[str]: |
Given the following code snippet before the placeholder: <|code_start|>
return zsplit(out)
def head_rev(remote: str) -> str:
_, out, _ = cmd_output('git', 'ls-remote', '--exit-code', remote, 'HEAD')
return out.split()[0]
def has_diff(*args: str, repo: str = '.') -> bool:
cmd = ('git', 'diff', '--quiet', '--no-ext-diff', *args)
return cmd_output_b(*cmd, cwd=repo, retcode=None)[0] == 1
def has_core_hookpaths_set() -> bool:
_, out, _ = cmd_output_b('git', 'config', 'core.hooksPath', retcode=None)
return bool(out.strip())
def init_repo(path: str, remote: str) -> None:
if os.path.isdir(remote):
remote = os.path.abspath(remote)
git = ('git', *NO_FS_MONITOR)
env = no_git_env()
# avoid the user's template so that hooks do not recurse
cmd_output_b(*git, 'init', '--template=', path, env=env)
cmd_output_b(*git, 'remote', 'add', 'origin', remote, cwd=path, env=env)
<|code_end|>
, predict the next line using imports from the current file:
import logging
import os.path
import sys
from typing import MutableMapping
from pre_commit.errors import FatalError
from pre_commit.util import CalledProcessError
from pre_commit.util import cmd_output
from pre_commit.util import cmd_output_b
and context including class names, function names, and sometimes code from other files:
# Path: pre_commit/errors.py
# class FatalError(RuntimeError):
# pass
#
# Path: pre_commit/util.py
# class CalledProcessError(RuntimeError):
# def __init__(
# self,
# returncode: int,
# cmd: tuple[str, ...],
# expected_returncode: int,
# stdout: bytes,
# stderr: bytes | None,
# ) -> None:
# super().__init__(returncode, cmd, expected_returncode, stdout, stderr)
# self.returncode = returncode
# self.cmd = cmd
# self.expected_returncode = expected_returncode
# self.stdout = stdout
# self.stderr = stderr
#
# def __bytes__(self) -> bytes:
# def _indent_or_none(part: bytes | None) -> bytes:
# if part:
# return b'\n ' + part.replace(b'\n', b'\n ')
# else:
# return b' (none)'
#
# return b''.join((
# f'command: {self.cmd!r}\n'.encode(),
# f'return code: {self.returncode}\n'.encode(),
# f'expected return code: {self.expected_returncode}\n'.encode(),
# b'stdout:', _indent_or_none(self.stdout), b'\n',
# b'stderr:', _indent_or_none(self.stderr),
# ))
#
# def __str__(self) -> str:
# return self.__bytes__().decode()
#
# Path: pre_commit/util.py
# def cmd_output(*cmd: str, **kwargs: Any) -> tuple[int, str, str | None]:
# returncode, stdout_b, stderr_b = cmd_output_b(*cmd, **kwargs)
# stdout = stdout_b.decode() if stdout_b is not None else None
# stderr = stderr_b.decode() if stderr_b is not None else None
# return returncode, stdout, stderr
#
# Path: pre_commit/util.py
# def cmd_output_b(
# *cmd: str,
# retcode: int | None = 0,
# **kwargs: Any,
# ) -> tuple[int, bytes, bytes | None]:
# _setdefault_kwargs(kwargs)
#
# try:
# cmd = parse_shebang.normalize_cmd(cmd)
# except parse_shebang.ExecutableNotFoundError as e:
# returncode, stdout_b, stderr_b = e.to_output()
# else:
# try:
# proc = subprocess.Popen(cmd, **kwargs)
# except OSError as e:
# returncode, stdout_b, stderr_b = _oserror_to_output(e)
# else:
# stdout_b, stderr_b = proc.communicate()
# returncode = proc.returncode
#
# if retcode is not None and retcode != returncode:
# raise CalledProcessError(returncode, cmd, retcode, stdout_b, stderr_b)
#
# return returncode, stdout_b, stderr_b
. Output only the next line. | def commit(repo: str = '.') -> None: |
Predict the next line for this snippet: <|code_start|> description: str
language_version: str
log_file: str
minimum_pre_commit_version: str
require_serial: bool
stages: Sequence[str]
verbose: bool
@property
def cmd(self) -> tuple[str, ...]:
return (*shlex.split(self.entry), *self.args)
@property
def install_key(self) -> tuple[Prefix, str, str, tuple[str, ...]]:
return (
self.prefix,
self.language,
self.language_version,
tuple(self.additional_dependencies),
)
@classmethod
def create(cls, src: str, prefix: Prefix, dct: dict[str, Any]) -> Hook:
# TODO: have cfgv do this (?)
extra_keys = set(dct) - _KEYS
if extra_keys:
logger.warning(
f'Unexpected key(s) present on {src} => {dct["id"]}: '
f'{", ".join(sorted(extra_keys))}',
)
<|code_end|>
with the help of current file imports:
import logging
import shlex
from typing import Any
from typing import NamedTuple
from typing import Sequence
from pre_commit.prefix import Prefix
and context from other files:
# Path: pre_commit/prefix.py
# class Prefix(NamedTuple):
# prefix_dir: str
#
# def path(self, *parts: str) -> str:
# return os.path.normpath(os.path.join(self.prefix_dir, *parts))
#
# def exists(self, *parts: str) -> bool:
# return os.path.exists(self.path(*parts))
#
# def star(self, end: str) -> tuple[str, ...]:
# paths = os.listdir(self.prefix_dir)
# return tuple(path for path in paths if path.endswith(end))
, which may contain function names, class names, or code. Output only the next line. | return cls(src=src, prefix=prefix, **{k: dct[k] for k in _KEYS}) |
Given snippet: <|code_start|>from __future__ import annotations
ENVIRONMENT_DIR = None
get_default_version = helpers.basic_get_default_version
healthy = helpers.basic_healthy
install_environment = helpers.no_install
def run_hook(
hook: Hook,
file_args: Sequence[str],
color: bool,
) -> tuple[int, bytes]:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from typing import Sequence
from pre_commit.hook import Hook
from pre_commit.languages import helpers
and context:
# Path: pre_commit/hook.py
# class Hook(NamedTuple):
# src: str
# prefix: Prefix
# id: str
# name: str
# entry: str
# language: str
# alias: str
# files: str
# exclude: str
# types: Sequence[str]
# types_or: Sequence[str]
# exclude_types: Sequence[str]
# additional_dependencies: Sequence[str]
# args: Sequence[str]
# always_run: bool
# fail_fast: bool
# pass_filenames: bool
# description: str
# language_version: str
# log_file: str
# minimum_pre_commit_version: str
# require_serial: bool
# stages: Sequence[str]
# verbose: bool
#
# @property
# def cmd(self) -> tuple[str, ...]:
# return (*shlex.split(self.entry), *self.args)
#
# @property
# def install_key(self) -> tuple[Prefix, str, str, tuple[str, ...]]:
# return (
# self.prefix,
# self.language,
# self.language_version,
# tuple(self.additional_dependencies),
# )
#
# @classmethod
# def create(cls, src: str, prefix: Prefix, dct: dict[str, Any]) -> Hook:
# # TODO: have cfgv do this (?)
# extra_keys = set(dct) - _KEYS
# if extra_keys:
# logger.warning(
# f'Unexpected key(s) present on {src} => {dct["id"]}: '
# f'{", ".join(sorted(extra_keys))}',
# )
# return cls(src=src, prefix=prefix, **{k: dct[k] for k in _KEYS})
#
# Path: pre_commit/languages/helpers.py
# FIXED_RANDOM_SEED = 1542676187
# SHIMS_RE = re.compile(r'[/\\]shims[/\\]')
# def exe_exists(exe: str) -> bool:
# def run_setup_cmd(prefix: Prefix, cmd: tuple[str, ...], **kwargs: Any) -> None:
# def environment_dir(d: None, language_version: str) -> None: ...
# def environment_dir(d: str, language_version: str) -> str: ...
# def environment_dir(d: str | None, language_version: str) -> str | None:
# def assert_version_default(binary: str, version: str) -> None:
# def assert_no_additional_deps(
# lang: str,
# additional_deps: Sequence[str],
# ) -> None:
# def basic_get_default_version() -> str:
# def basic_healthy(prefix: Prefix, language_version: str) -> bool:
# def no_install(
# prefix: Prefix,
# version: str,
# additional_dependencies: Sequence[str],
# ) -> NoReturn:
# def target_concurrency(hook: Hook) -> int:
# def _shuffled(seq: Sequence[str]) -> list[str]:
# def run_xargs(
# hook: Hook,
# cmd: tuple[str, ...],
# file_args: Sequence[str],
# **kwargs: Any,
# ) -> tuple[int, bytes]:
which might include code, classes, or functions. Output only the next line. | cmd = (hook.prefix.path(hook.cmd[0]), *hook.cmd[1:]) |
Continue the code snippet: <|code_start|>from __future__ import annotations
ENVIRONMENT_DIR = None
get_default_version = helpers.basic_get_default_version
healthy = helpers.basic_healthy
install_environment = helpers.no_install
def run_hook(
hook: Hook,
<|code_end|>
. Use current file imports:
from typing import Sequence
from pre_commit.hook import Hook
from pre_commit.languages import helpers
and context (classes, functions, or code) from other files:
# Path: pre_commit/hook.py
# class Hook(NamedTuple):
# src: str
# prefix: Prefix
# id: str
# name: str
# entry: str
# language: str
# alias: str
# files: str
# exclude: str
# types: Sequence[str]
# types_or: Sequence[str]
# exclude_types: Sequence[str]
# additional_dependencies: Sequence[str]
# args: Sequence[str]
# always_run: bool
# fail_fast: bool
# pass_filenames: bool
# description: str
# language_version: str
# log_file: str
# minimum_pre_commit_version: str
# require_serial: bool
# stages: Sequence[str]
# verbose: bool
#
# @property
# def cmd(self) -> tuple[str, ...]:
# return (*shlex.split(self.entry), *self.args)
#
# @property
# def install_key(self) -> tuple[Prefix, str, str, tuple[str, ...]]:
# return (
# self.prefix,
# self.language,
# self.language_version,
# tuple(self.additional_dependencies),
# )
#
# @classmethod
# def create(cls, src: str, prefix: Prefix, dct: dict[str, Any]) -> Hook:
# # TODO: have cfgv do this (?)
# extra_keys = set(dct) - _KEYS
# if extra_keys:
# logger.warning(
# f'Unexpected key(s) present on {src} => {dct["id"]}: '
# f'{", ".join(sorted(extra_keys))}',
# )
# return cls(src=src, prefix=prefix, **{k: dct[k] for k in _KEYS})
#
# Path: pre_commit/languages/helpers.py
# FIXED_RANDOM_SEED = 1542676187
# SHIMS_RE = re.compile(r'[/\\]shims[/\\]')
# def exe_exists(exe: str) -> bool:
# def run_setup_cmd(prefix: Prefix, cmd: tuple[str, ...], **kwargs: Any) -> None:
# def environment_dir(d: None, language_version: str) -> None: ...
# def environment_dir(d: str, language_version: str) -> str: ...
# def environment_dir(d: str | None, language_version: str) -> str | None:
# def assert_version_default(binary: str, version: str) -> None:
# def assert_no_additional_deps(
# lang: str,
# additional_deps: Sequence[str],
# ) -> None:
# def basic_get_default_version() -> str:
# def basic_healthy(prefix: Prefix, language_version: str) -> bool:
# def no_install(
# prefix: Prefix,
# version: str,
# additional_dependencies: Sequence[str],
# ) -> NoReturn:
# def target_concurrency(hook: Hook) -> int:
# def _shuffled(seq: Sequence[str]) -> list[str]:
# def run_xargs(
# hook: Hook,
# cmd: tuple[str, ...],
# file_args: Sequence[str],
# **kwargs: Any,
# ) -> tuple[int, bytes]:
. Output only the next line. | file_args: Sequence[str], |
Given the code snippet: <|code_start|> cmd = ('ninechars',)
# counted as half because of utf-16 encode
varargs = ('😑' * 5,)
ret = xargs.partition(cmd, varargs, 1, _max_length=21)
assert ret == (cmd + varargs,)
def test_partition_limit_linux(linux_mock):
cmd = ('ninechars',)
varargs = ('😑' * 5,)
ret = xargs.partition(cmd, varargs, 1, _max_length=31)
assert ret == (cmd + varargs,)
def test_argument_too_long_with_large_unicode(linux_mock):
cmd = ('ninechars',)
varargs = ('😑' * 10,) # 4 bytes * 10
with pytest.raises(xargs.ArgumentTooLongError):
xargs.partition(cmd, varargs, 1, _max_length=20)
def test_partition_target_concurrency():
ret = xargs.partition(
('foo',), ('A',) * 22,
4,
_max_length=50,
)
assert ret == (
('foo',) + ('A',) * 6,
('foo',) + ('A',) * 6,
<|code_end|>
, generate the next line using the imports in this file:
import concurrent.futures
import os
import sys
import time
import pytest
from unittest import mock
from pre_commit import parse_shebang
from pre_commit import xargs
and context (functions, classes, or occasionally code) from other files:
# Path: pre_commit/parse_shebang.py
# class ExecutableNotFoundError(OSError):
# def to_output(self) -> tuple[int, bytes, None]:
# def parse_filename(filename: str) -> tuple[str, ...]:
# def find_executable(
# exe: str, _environ: Mapping[str, str] | None = None,
# ) -> str | None:
# def normexe(orig: str) -> str:
# def _error(msg: str) -> NoReturn:
# def normalize_cmd(cmd: tuple[str, ...]) -> tuple[str, ...]:
#
# Path: pre_commit/xargs.py
# def xargs(
# cmd: tuple[str, ...],
# varargs: Sequence[str],
# *,
# color: bool = False,
# target_concurrency: int = 1,
# _max_length: int = _get_platform_max_length(),
# **kwargs: Any,
# ) -> tuple[int, bytes]:
# """A simplified implementation of xargs.
#
# color: Make a pty if on a platform that supports it
# target_concurrency: Target number of partitions to run concurrently
# """
# cmd_fn = cmd_output_p if color else cmd_output_b
# retcode = 0
# stdout = b''
#
# try:
# cmd = parse_shebang.normalize_cmd(cmd)
# except parse_shebang.ExecutableNotFoundError as e:
# return e.to_output()[:2]
#
# # on windows, batch files have a separate length limit than windows itself
# if (
# sys.platform == 'win32' and
# cmd[0].lower().endswith(('.bat', '.cmd'))
# ): # pragma: win32 cover
# # this is implementation details but the command gets translated into
# # full/path/to/cmd.exe /c *cmd
# cmd_exe = parse_shebang.find_executable('cmd.exe')
# # 1024 is additionally subtracted to give headroom for further
# # expansion inside the batch file
# _max_length = 8192 - len(cmd_exe) - len(' /c ') - 1024
#
# partitions = partition(cmd, varargs, target_concurrency, _max_length)
#
# def run_cmd_partition(
# run_cmd: tuple[str, ...],
# ) -> tuple[int, bytes, bytes | None]:
# return cmd_fn(
# *run_cmd, retcode=None, stderr=subprocess.STDOUT, **kwargs,
# )
#
# threads = min(len(partitions), target_concurrency)
# with _thread_mapper(threads) as thread_map:
# results = thread_map(run_cmd_partition, partitions)
#
# for proc_retcode, proc_out, _ in results:
# retcode = max(retcode, proc_retcode)
# stdout += proc_out
#
# return retcode, stdout
. Output only the next line. | ('foo',) + ('A',) * 6, |
Based on the snippet: <|code_start|> # takes less, they must have run concurrently.
assert elapsed < 2.5
def test_thread_mapper_concurrency_uses_threadpoolexecutor_map():
with xargs._thread_mapper(10) as thread_map:
_self = thread_map.__self__ # type: ignore
assert isinstance(_self, concurrent.futures.ThreadPoolExecutor)
def test_thread_mapper_concurrency_uses_regular_map():
with xargs._thread_mapper(1) as thread_map:
assert thread_map is map
def test_xargs_propagate_kwargs_to_cmd():
env = {'PRE_COMMIT_TEST_VAR': 'Pre commit is awesome'}
cmd: tuple[str, ...] = ('bash', '-c', 'echo $PRE_COMMIT_TEST_VAR', '--')
cmd = parse_shebang.normalize_cmd(cmd)
ret, stdout = xargs.xargs(cmd, ('1',), env=env)
assert ret == 0
assert b'Pre commit is awesome' in stdout
@pytest.mark.xfail(os.name == 'nt', reason='posix only')
def test_xargs_color_true_makes_tty():
retcode, out = xargs.xargs(
(sys.executable, '-c', 'import sys; print(sys.stdout.isatty())'),
('1',),
<|code_end|>
, predict the immediate next line with the help of imports:
import concurrent.futures
import os
import sys
import time
import pytest
from unittest import mock
from pre_commit import parse_shebang
from pre_commit import xargs
and context (classes, functions, sometimes code) from other files:
# Path: pre_commit/parse_shebang.py
# class ExecutableNotFoundError(OSError):
# def to_output(self) -> tuple[int, bytes, None]:
# def parse_filename(filename: str) -> tuple[str, ...]:
# def find_executable(
# exe: str, _environ: Mapping[str, str] | None = None,
# ) -> str | None:
# def normexe(orig: str) -> str:
# def _error(msg: str) -> NoReturn:
# def normalize_cmd(cmd: tuple[str, ...]) -> tuple[str, ...]:
#
# Path: pre_commit/xargs.py
# def xargs(
# cmd: tuple[str, ...],
# varargs: Sequence[str],
# *,
# color: bool = False,
# target_concurrency: int = 1,
# _max_length: int = _get_platform_max_length(),
# **kwargs: Any,
# ) -> tuple[int, bytes]:
# """A simplified implementation of xargs.
#
# color: Make a pty if on a platform that supports it
# target_concurrency: Target number of partitions to run concurrently
# """
# cmd_fn = cmd_output_p if color else cmd_output_b
# retcode = 0
# stdout = b''
#
# try:
# cmd = parse_shebang.normalize_cmd(cmd)
# except parse_shebang.ExecutableNotFoundError as e:
# return e.to_output()[:2]
#
# # on windows, batch files have a separate length limit than windows itself
# if (
# sys.platform == 'win32' and
# cmd[0].lower().endswith(('.bat', '.cmd'))
# ): # pragma: win32 cover
# # this is implementation details but the command gets translated into
# # full/path/to/cmd.exe /c *cmd
# cmd_exe = parse_shebang.find_executable('cmd.exe')
# # 1024 is additionally subtracted to give headroom for further
# # expansion inside the batch file
# _max_length = 8192 - len(cmd_exe) - len(' /c ') - 1024
#
# partitions = partition(cmd, varargs, target_concurrency, _max_length)
#
# def run_cmd_partition(
# run_cmd: tuple[str, ...],
# ) -> tuple[int, bytes, bytes | None]:
# return cmd_fn(
# *run_cmd, retcode=None, stderr=subprocess.STDOUT, **kwargs,
# )
#
# threads = min(len(partitions), target_concurrency)
# with _thread_mapper(threads) as thread_map:
# results = thread_map(run_cmd_partition, partitions)
#
# for proc_retcode, proc_out, _ in results:
# retcode = max(retcode, proc_retcode)
# stdout += proc_out
#
# return retcode, stdout
. Output only the next line. | color=True, |
Predict the next line after this snippet: <|code_start|>from __future__ import annotations
def _is_header_line(line: str) -> bool:
return line.startswith(('#', '---')) or not line.strip()
def _migrate_map(contents: str) -> str:
if isinstance(yaml_load(contents), list):
# Find the first non-header line
lines = contents.splitlines(True)
i = 0
# Only loop on non empty configuration file
while i < len(lines) and _is_header_line(lines[i]):
<|code_end|>
using the current file's imports:
import re
import textwrap
import yaml
from pre_commit.util import yaml_load
and any relevant context from other files:
# Path: pre_commit/util.py
# def yaml_dump(o: Any, **kwargs: Any) -> str:
# def force_bytes(exc: Any) -> bytes:
# def clean_path_on_failure(path: str) -> Generator[None, None, None]:
# def tmpdir() -> Generator[str, None, None]:
# def resource_bytesio(filename: str) -> IO[bytes]:
# def resource_text(filename: str) -> str:
# def make_executable(filename: str) -> None:
# def __init__(
# self,
# returncode: int,
# cmd: tuple[str, ...],
# expected_returncode: int,
# stdout: bytes,
# stderr: bytes | None,
# ) -> None:
# def __bytes__(self) -> bytes:
# def _indent_or_none(part: bytes | None) -> bytes:
# def __str__(self) -> str:
# def _setdefault_kwargs(kwargs: dict[str, Any]) -> None:
# def _oserror_to_output(e: OSError) -> tuple[int, bytes, None]:
# def cmd_output_b(
# *cmd: str,
# retcode: int | None = 0,
# **kwargs: Any,
# ) -> tuple[int, bytes, bytes | None]:
# def cmd_output(*cmd: str, **kwargs: Any) -> tuple[int, str, str | None]:
# def __init__(self) -> None:
# def __enter__(self) -> Pty:
# def close_w(self) -> None:
# def close_r(self) -> None:
# def __exit__(
# self,
# exc_type: type[BaseException] | None,
# exc_value: BaseException | None,
# traceback: TracebackType | None,
# ) -> None:
# def cmd_output_p(
# *cmd: str,
# retcode: int | None = 0,
# **kwargs: Any,
# ) -> tuple[int, bytes, bytes | None]:
# def rmtree(path: str) -> None:
# def handle_remove_readonly(
# func: Callable[..., Any],
# path: str,
# exc: tuple[type[OSError], OSError, TracebackType],
# ) -> None:
# def parse_version(s: str) -> tuple[int, ...]:
# def win_exe(s: str) -> str:
# class CalledProcessError(RuntimeError):
# class Pty:
. Output only the next line. | i += 1 |
Based on the snippet: <|code_start|>from __future__ import annotations
ENVIRONMENT_DIR = None
get_default_version = helpers.basic_get_default_version
healthy = helpers.basic_healthy
install_environment = helpers.no_install
def _process_filename_by_line(pattern: Pattern[bytes], filename: str) -> int:
retv = 0
<|code_end|>
, predict the immediate next line with the help of imports:
import argparse
import re
import sys
from typing import NamedTuple
from typing import Pattern
from typing import Sequence
from pre_commit import output
from pre_commit.hook import Hook
from pre_commit.languages import helpers
from pre_commit.xargs import xargs
and context (classes, functions, sometimes code) from other files:
# Path: pre_commit/output.py
# def write(s: str, stream: IO[bytes] = sys.stdout.buffer) -> None:
# def write_line_b(
# s: bytes | None = None,
# stream: IO[bytes] = sys.stdout.buffer,
# logfile_name: str | None = None,
# ) -> None:
# def write_line(s: str | None = None, **kwargs: Any) -> None:
#
# Path: pre_commit/hook.py
# class Hook(NamedTuple):
# src: str
# prefix: Prefix
# id: str
# name: str
# entry: str
# language: str
# alias: str
# files: str
# exclude: str
# types: Sequence[str]
# types_or: Sequence[str]
# exclude_types: Sequence[str]
# additional_dependencies: Sequence[str]
# args: Sequence[str]
# always_run: bool
# fail_fast: bool
# pass_filenames: bool
# description: str
# language_version: str
# log_file: str
# minimum_pre_commit_version: str
# require_serial: bool
# stages: Sequence[str]
# verbose: bool
#
# @property
# def cmd(self) -> tuple[str, ...]:
# return (*shlex.split(self.entry), *self.args)
#
# @property
# def install_key(self) -> tuple[Prefix, str, str, tuple[str, ...]]:
# return (
# self.prefix,
# self.language,
# self.language_version,
# tuple(self.additional_dependencies),
# )
#
# @classmethod
# def create(cls, src: str, prefix: Prefix, dct: dict[str, Any]) -> Hook:
# # TODO: have cfgv do this (?)
# extra_keys = set(dct) - _KEYS
# if extra_keys:
# logger.warning(
# f'Unexpected key(s) present on {src} => {dct["id"]}: '
# f'{", ".join(sorted(extra_keys))}',
# )
# return cls(src=src, prefix=prefix, **{k: dct[k] for k in _KEYS})
#
# Path: pre_commit/languages/helpers.py
# FIXED_RANDOM_SEED = 1542676187
# SHIMS_RE = re.compile(r'[/\\]shims[/\\]')
# def exe_exists(exe: str) -> bool:
# def run_setup_cmd(prefix: Prefix, cmd: tuple[str, ...], **kwargs: Any) -> None:
# def environment_dir(d: None, language_version: str) -> None: ...
# def environment_dir(d: str, language_version: str) -> str: ...
# def environment_dir(d: str | None, language_version: str) -> str | None:
# def assert_version_default(binary: str, version: str) -> None:
# def assert_no_additional_deps(
# lang: str,
# additional_deps: Sequence[str],
# ) -> None:
# def basic_get_default_version() -> str:
# def basic_healthy(prefix: Prefix, language_version: str) -> bool:
# def no_install(
# prefix: Prefix,
# version: str,
# additional_dependencies: Sequence[str],
# ) -> NoReturn:
# def target_concurrency(hook: Hook) -> int:
# def _shuffled(seq: Sequence[str]) -> list[str]:
# def run_xargs(
# hook: Hook,
# cmd: tuple[str, ...],
# file_args: Sequence[str],
# **kwargs: Any,
# ) -> tuple[int, bytes]:
#
# Path: pre_commit/xargs.py
# def xargs(
# cmd: tuple[str, ...],
# varargs: Sequence[str],
# *,
# color: bool = False,
# target_concurrency: int = 1,
# _max_length: int = _get_platform_max_length(),
# **kwargs: Any,
# ) -> tuple[int, bytes]:
# """A simplified implementation of xargs.
#
# color: Make a pty if on a platform that supports it
# target_concurrency: Target number of partitions to run concurrently
# """
# cmd_fn = cmd_output_p if color else cmd_output_b
# retcode = 0
# stdout = b''
#
# try:
# cmd = parse_shebang.normalize_cmd(cmd)
# except parse_shebang.ExecutableNotFoundError as e:
# return e.to_output()[:2]
#
# # on windows, batch files have a separate length limit than windows itself
# if (
# sys.platform == 'win32' and
# cmd[0].lower().endswith(('.bat', '.cmd'))
# ): # pragma: win32 cover
# # this is implementation details but the command gets translated into
# # full/path/to/cmd.exe /c *cmd
# cmd_exe = parse_shebang.find_executable('cmd.exe')
# # 1024 is additionally subtracted to give headroom for further
# # expansion inside the batch file
# _max_length = 8192 - len(cmd_exe) - len(' /c ') - 1024
#
# partitions = partition(cmd, varargs, target_concurrency, _max_length)
#
# def run_cmd_partition(
# run_cmd: tuple[str, ...],
# ) -> tuple[int, bytes, bytes | None]:
# return cmd_fn(
# *run_cmd, retcode=None, stderr=subprocess.STDOUT, **kwargs,
# )
#
# threads = min(len(partitions), target_concurrency)
# with _thread_mapper(threads) as thread_map:
# results = thread_map(run_cmd_partition, partitions)
#
# for proc_retcode, proc_out, _ in results:
# retcode = max(retcode, proc_retcode)
# stdout += proc_out
#
# return retcode, stdout
. Output only the next line. | with open(filename, 'rb') as f: |
Given snippet: <|code_start|>from __future__ import annotations
DOCKER_CGROUP_EXAMPLE = b'''\
12:hugetlb:/docker/c33988ec7651ebc867cb24755eaf637a6734088bc7eef59d5799293a9e5450f7
11:blkio:/docker/c33988ec7651ebc867cb24755eaf637a6734088bc7eef59d5799293a9e5450f7
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import builtins
import json
import ntpath
import os.path
import posixpath
import pytest
from unittest import mock
from pre_commit.languages import docker
from pre_commit.util import CalledProcessError
and context:
# Path: pre_commit/languages/docker.py
# ENVIRONMENT_DIR = 'docker'
# PRE_COMMIT_LABEL = 'PRE_COMMIT'
# def _is_in_docker() -> bool:
# def _get_container_id() -> str:
# def _get_docker_path(path: str) -> str:
# def md5(s: str) -> str: # pragma: win32 no cover
# def docker_tag(prefix: Prefix) -> str: # pragma: win32 no cover
# def build_docker_image(
# prefix: Prefix,
# *,
# pull: bool,
# ) -> None: # pragma: win32 no cover
# def install_environment(
# prefix: Prefix, version: str, additional_dependencies: Sequence[str],
# ) -> None: # pragma: win32 no cover
# def get_docker_user() -> tuple[str, ...]: # pragma: win32 no cover
# def docker_cmd() -> tuple[str, ...]: # pragma: win32 no cover
# def run_hook(
# hook: Hook,
# file_args: Sequence[str],
# color: bool,
# ) -> tuple[int, bytes]: # pragma: win32 no cover
#
# Path: pre_commit/util.py
# class CalledProcessError(RuntimeError):
# def __init__(
# self,
# returncode: int,
# cmd: tuple[str, ...],
# expected_returncode: int,
# stdout: bytes,
# stderr: bytes | None,
# ) -> None:
# super().__init__(returncode, cmd, expected_returncode, stdout, stderr)
# self.returncode = returncode
# self.cmd = cmd
# self.expected_returncode = expected_returncode
# self.stdout = stdout
# self.stderr = stderr
#
# def __bytes__(self) -> bytes:
# def _indent_or_none(part: bytes | None) -> bytes:
# if part:
# return b'\n ' + part.replace(b'\n', b'\n ')
# else:
# return b' (none)'
#
# return b''.join((
# f'command: {self.cmd!r}\n'.encode(),
# f'return code: {self.returncode}\n'.encode(),
# f'expected return code: {self.expected_returncode}\n'.encode(),
# b'stdout:', _indent_or_none(self.stdout), b'\n',
# b'stderr:', _indent_or_none(self.stderr),
# ))
#
# def __str__(self) -> str:
# return self.__bytes__().decode()
which might include code, classes, or functions. Output only the next line. | 10:freezer:/docker/c33988ec7651ebc867cb24755eaf637a6734088bc7eef59d5799293a9e5450f7 |
Given the code snippet: <|code_start|>from __future__ import annotations
def test_identity(cap_out):
assert not identity.main(('a', 'b', 'c'))
<|code_end|>
, generate the next line using the imports in this file:
from pre_commit.meta_hooks import identity
and context (functions, classes, or occasionally code) from other files:
# Path: pre_commit/meta_hooks/identity.py
# def main(argv: Sequence[str] | None = None) -> int:
. Output only the next line. | assert cap_out.get() == 'a\nb\nc\n' |
Predict the next line for this snippet: <|code_start|> 'repos:\n'
'- repo: local\n'
' hooks:\n'
' - id: foo\n'
' name: foo\n'
' entry: ./bin/foo.sh\n'
' language: script\n'
)
def test_migrate_config_list_literal(tmpdir):
cfg = tmpdir.join(C.CONFIG_FILE)
cfg.write(
'[{\n'
' repo: local,\n'
' hooks: [{\n'
' id: foo, name: foo, entry: ./bin/foo.sh,\n'
' language: script,\n'
' }]\n'
'}]',
)
with tmpdir.as_cwd():
assert not migrate_config(C.CONFIG_FILE)
contents = cfg.read()
assert contents == (
'repos:\n'
' [{\n'
' repo: local,\n'
' hooks: [{\n'
' id: foo, name: foo, entry: ./bin/foo.sh,\n'
<|code_end|>
with the help of current file imports:
import pre_commit.constants as C
from pre_commit.commands.migrate_config import migrate_config
and context from other files:
# Path: pre_commit/commands/migrate_config.py
# def migrate_config(config_file: str, quiet: bool = False) -> int:
# with open(config_file) as f:
# orig_contents = contents = f.read()
#
# contents = _migrate_map(contents)
# contents = _migrate_sha_to_rev(contents)
#
# if contents != orig_contents:
# with open(config_file, 'w') as f:
# f.write(contents)
#
# print('Configuration has been migrated.')
# elif not quiet:
# print('Configuration is already migrated.')
# return 0
, which may contain function names, class names, or code. Output only the next line. | ' language: script,\n' |
Given the code snippet: <|code_start|>from __future__ import annotations
def test_init_templatedir(tmpdir, tempdir_factory, store, cap_out):
target = str(tmpdir.join('tmpl'))
init_templatedir(C.CONFIG_FILE, store, target, hook_types=['pre-commit'])
lines = cap_out.get().splitlines()
assert lines[0].startswith('pre-commit installed at ')
assert lines[1] == (
'[WARNING] `init.templateDir` not set to the target directory'
)
<|code_end|>
, generate the next line using the imports in this file:
import os.path
import pytest
import pre_commit.constants as C
from unittest import mock
from pre_commit.commands.init_templatedir import init_templatedir
from pre_commit.envcontext import envcontext
from pre_commit.util import cmd_output
from testing.fixtures import git_dir
from testing.fixtures import make_consuming_repo
from testing.util import cmd_output_mocked_pre_commit_home
from testing.util import cwd
from testing.util import git_commit
and context (functions, classes, or occasionally code) from other files:
# Path: pre_commit/commands/init_templatedir.py
# def init_templatedir(
# config_file: str,
# store: Store,
# directory: str,
# hook_types: Sequence[str],
# skip_on_missing_config: bool = True,
# ) -> int:
# install(
# config_file,
# store,
# hook_types=hook_types,
# overwrite=True,
# skip_on_missing_config=skip_on_missing_config,
# git_dir=directory,
# )
# try:
# _, out, _ = cmd_output('git', 'config', 'init.templateDir')
# except CalledProcessError:
# configured_path = None
# else:
# configured_path = os.path.realpath(os.path.expanduser(out.strip()))
# dest = os.path.realpath(directory)
# if configured_path != dest:
# logger.warning('`init.templateDir` not set to the target directory')
# logger.warning(f'maybe `git config --global init.templateDir {dest}`?')
# return 0
#
# Path: pre_commit/envcontext.py
# @contextlib.contextmanager
# def envcontext(
# patch: PatchesT,
# _env: MutableMapping[str, str] | None = None,
# ) -> Generator[None, None, None]:
# """In this context, `os.environ` is modified according to `patch`.
#
# `patch` is an iterable of 2-tuples (key, value):
# `key`: string
# `value`:
# - string: `environ[key] == value` inside the context.
# - UNSET: `key not in environ` inside the context.
# - template: A template is a tuple of strings and Var which will be
# replaced with the previous environment
# """
# env = os.environ if _env is None else _env
# before = dict(env)
#
# for k, v in patch:
# if v is UNSET:
# env.pop(k, None)
# elif isinstance(v, tuple):
# env[k] = format_env(v, before)
# else:
# env[k] = v
#
# try:
# yield
# finally:
# env.clear()
# env.update(before)
#
# Path: pre_commit/util.py
# def cmd_output(*cmd: str, **kwargs: Any) -> tuple[int, str, str | None]:
# returncode, stdout_b, stderr_b = cmd_output_b(*cmd, **kwargs)
# stdout = stdout_b.decode() if stdout_b is not None else None
# stderr = stderr_b.decode() if stderr_b is not None else None
# return returncode, stdout, stderr
#
# Path: testing/fixtures.py
# def git_dir(tempdir_factory):
# path = tempdir_factory.get()
# cmd_output('git', 'init', path)
# return path
#
# Path: testing/fixtures.py
# def make_consuming_repo(tempdir_factory, repo_source):
# path = make_repo(tempdir_factory, repo_source)
# config = make_config_from_repo(path)
# git_path = git_dir(tempdir_factory)
# return add_config_to_repo(git_path, config)
#
# Path: testing/util.py
# def cmd_output_mocked_pre_commit_home(
# *args, tempdir_factory, pre_commit_home=None, env=None, **kwargs,
# ):
# if pre_commit_home is None:
# pre_commit_home = tempdir_factory.get()
# env = env if env is not None else os.environ
# kwargs.setdefault('stderr', subprocess.STDOUT)
# # Don't want to write to the home directory
# env = dict(env, PRE_COMMIT_HOME=pre_commit_home)
# ret, out, _ = cmd_output(*args, env=env, **kwargs)
# return ret, out.replace('\r\n', '\n'), None
#
# Path: testing/util.py
# @contextlib.contextmanager
# def cwd(path):
# original_cwd = os.getcwd()
# os.chdir(path)
# try:
# yield
# finally:
# os.chdir(original_cwd)
#
# Path: testing/util.py
# def git_commit(*args, fn=cmd_output, msg='commit!', all_files=True, **kwargs):
# kwargs.setdefault('stderr', subprocess.STDOUT)
#
# cmd = ('git', 'commit', '--allow-empty', '--no-gpg-sign', *args)
# if all_files: # allow skipping `-a` with `all_files=False`
# cmd += ('-a',)
# if msg is not None: # allow skipping `-m` with `msg=None`
# cmd += ('-m', msg)
# ret, out, _ = fn(*cmd, **kwargs)
# return ret, out.replace('\r\n', '\n')
. Output only the next line. | assert lines[2].startswith( |
Given the code snippet: <|code_start|>from __future__ import annotations
def test_init_templatedir(tmpdir, tempdir_factory, store, cap_out):
target = str(tmpdir.join('tmpl'))
init_templatedir(C.CONFIG_FILE, store, target, hook_types=['pre-commit'])
lines = cap_out.get().splitlines()
assert lines[0].startswith('pre-commit installed at ')
<|code_end|>
, generate the next line using the imports in this file:
import os.path
import pytest
import pre_commit.constants as C
from unittest import mock
from pre_commit.commands.init_templatedir import init_templatedir
from pre_commit.envcontext import envcontext
from pre_commit.util import cmd_output
from testing.fixtures import git_dir
from testing.fixtures import make_consuming_repo
from testing.util import cmd_output_mocked_pre_commit_home
from testing.util import cwd
from testing.util import git_commit
and context (functions, classes, or occasionally code) from other files:
# Path: pre_commit/commands/init_templatedir.py
# def init_templatedir(
# config_file: str,
# store: Store,
# directory: str,
# hook_types: Sequence[str],
# skip_on_missing_config: bool = True,
# ) -> int:
# install(
# config_file,
# store,
# hook_types=hook_types,
# overwrite=True,
# skip_on_missing_config=skip_on_missing_config,
# git_dir=directory,
# )
# try:
# _, out, _ = cmd_output('git', 'config', 'init.templateDir')
# except CalledProcessError:
# configured_path = None
# else:
# configured_path = os.path.realpath(os.path.expanduser(out.strip()))
# dest = os.path.realpath(directory)
# if configured_path != dest:
# logger.warning('`init.templateDir` not set to the target directory')
# logger.warning(f'maybe `git config --global init.templateDir {dest}`?')
# return 0
#
# Path: pre_commit/envcontext.py
# @contextlib.contextmanager
# def envcontext(
# patch: PatchesT,
# _env: MutableMapping[str, str] | None = None,
# ) -> Generator[None, None, None]:
# """In this context, `os.environ` is modified according to `patch`.
#
# `patch` is an iterable of 2-tuples (key, value):
# `key`: string
# `value`:
# - string: `environ[key] == value` inside the context.
# - UNSET: `key not in environ` inside the context.
# - template: A template is a tuple of strings and Var which will be
# replaced with the previous environment
# """
# env = os.environ if _env is None else _env
# before = dict(env)
#
# for k, v in patch:
# if v is UNSET:
# env.pop(k, None)
# elif isinstance(v, tuple):
# env[k] = format_env(v, before)
# else:
# env[k] = v
#
# try:
# yield
# finally:
# env.clear()
# env.update(before)
#
# Path: pre_commit/util.py
# def cmd_output(*cmd: str, **kwargs: Any) -> tuple[int, str, str | None]:
# returncode, stdout_b, stderr_b = cmd_output_b(*cmd, **kwargs)
# stdout = stdout_b.decode() if stdout_b is not None else None
# stderr = stderr_b.decode() if stderr_b is not None else None
# return returncode, stdout, stderr
#
# Path: testing/fixtures.py
# def git_dir(tempdir_factory):
# path = tempdir_factory.get()
# cmd_output('git', 'init', path)
# return path
#
# Path: testing/fixtures.py
# def make_consuming_repo(tempdir_factory, repo_source):
# path = make_repo(tempdir_factory, repo_source)
# config = make_config_from_repo(path)
# git_path = git_dir(tempdir_factory)
# return add_config_to_repo(git_path, config)
#
# Path: testing/util.py
# def cmd_output_mocked_pre_commit_home(
# *args, tempdir_factory, pre_commit_home=None, env=None, **kwargs,
# ):
# if pre_commit_home is None:
# pre_commit_home = tempdir_factory.get()
# env = env if env is not None else os.environ
# kwargs.setdefault('stderr', subprocess.STDOUT)
# # Don't want to write to the home directory
# env = dict(env, PRE_COMMIT_HOME=pre_commit_home)
# ret, out, _ = cmd_output(*args, env=env, **kwargs)
# return ret, out.replace('\r\n', '\n'), None
#
# Path: testing/util.py
# @contextlib.contextmanager
# def cwd(path):
# original_cwd = os.getcwd()
# os.chdir(path)
# try:
# yield
# finally:
# os.chdir(original_cwd)
#
# Path: testing/util.py
# def git_commit(*args, fn=cmd_output, msg='commit!', all_files=True, **kwargs):
# kwargs.setdefault('stderr', subprocess.STDOUT)
#
# cmd = ('git', 'commit', '--allow-empty', '--no-gpg-sign', *args)
# if all_files: # allow skipping `-a` with `all_files=False`
# cmd += ('-a',)
# if msg is not None: # allow skipping `-m` with `msg=None`
# cmd += ('-m', msg)
# ret, out, _ = fn(*cmd, **kwargs)
# return ret, out.replace('\r\n', '\n')
. Output only the next line. | assert lines[1] == ( |
Predict the next line for this snippet: <|code_start|> # set HOME to ignore the current `.gitconfig`
with envcontext((('HOME', str(tmpdir)),)):
with tmpdir.join('tmpl').ensure_dir().as_cwd():
# we have not set init.templateDir so this should produce a warning
init_templatedir(
C.CONFIG_FILE, store, '.', hook_types=['pre-commit'],
)
lines = cap_out.get().splitlines()
assert len(lines) == 3
assert lines[1] == (
'[WARNING] `init.templateDir` not set to the target directory'
)
def test_init_templatedir_expanduser(tmpdir, tempdir_factory, store, cap_out):
target = str(tmpdir.join('tmpl'))
tmp_git_dir = git_dir(tempdir_factory)
with cwd(tmp_git_dir):
cmd_output('git', 'config', 'init.templateDir', '~/templatedir')
with mock.patch.object(os.path, 'expanduser', return_value=target):
init_templatedir(
C.CONFIG_FILE, store, target, hook_types=['pre-commit'],
)
lines = cap_out.get().splitlines()
assert len(lines) == 1
assert lines[0].startswith('pre-commit installed at')
<|code_end|>
with the help of current file imports:
import os.path
import pytest
import pre_commit.constants as C
from unittest import mock
from pre_commit.commands.init_templatedir import init_templatedir
from pre_commit.envcontext import envcontext
from pre_commit.util import cmd_output
from testing.fixtures import git_dir
from testing.fixtures import make_consuming_repo
from testing.util import cmd_output_mocked_pre_commit_home
from testing.util import cwd
from testing.util import git_commit
and context from other files:
# Path: pre_commit/commands/init_templatedir.py
# def init_templatedir(
# config_file: str,
# store: Store,
# directory: str,
# hook_types: Sequence[str],
# skip_on_missing_config: bool = True,
# ) -> int:
# install(
# config_file,
# store,
# hook_types=hook_types,
# overwrite=True,
# skip_on_missing_config=skip_on_missing_config,
# git_dir=directory,
# )
# try:
# _, out, _ = cmd_output('git', 'config', 'init.templateDir')
# except CalledProcessError:
# configured_path = None
# else:
# configured_path = os.path.realpath(os.path.expanduser(out.strip()))
# dest = os.path.realpath(directory)
# if configured_path != dest:
# logger.warning('`init.templateDir` not set to the target directory')
# logger.warning(f'maybe `git config --global init.templateDir {dest}`?')
# return 0
#
# Path: pre_commit/envcontext.py
# @contextlib.contextmanager
# def envcontext(
# patch: PatchesT,
# _env: MutableMapping[str, str] | None = None,
# ) -> Generator[None, None, None]:
# """In this context, `os.environ` is modified according to `patch`.
#
# `patch` is an iterable of 2-tuples (key, value):
# `key`: string
# `value`:
# - string: `environ[key] == value` inside the context.
# - UNSET: `key not in environ` inside the context.
# - template: A template is a tuple of strings and Var which will be
# replaced with the previous environment
# """
# env = os.environ if _env is None else _env
# before = dict(env)
#
# for k, v in patch:
# if v is UNSET:
# env.pop(k, None)
# elif isinstance(v, tuple):
# env[k] = format_env(v, before)
# else:
# env[k] = v
#
# try:
# yield
# finally:
# env.clear()
# env.update(before)
#
# Path: pre_commit/util.py
# def cmd_output(*cmd: str, **kwargs: Any) -> tuple[int, str, str | None]:
# returncode, stdout_b, stderr_b = cmd_output_b(*cmd, **kwargs)
# stdout = stdout_b.decode() if stdout_b is not None else None
# stderr = stderr_b.decode() if stderr_b is not None else None
# return returncode, stdout, stderr
#
# Path: testing/fixtures.py
# def git_dir(tempdir_factory):
# path = tempdir_factory.get()
# cmd_output('git', 'init', path)
# return path
#
# Path: testing/fixtures.py
# def make_consuming_repo(tempdir_factory, repo_source):
# path = make_repo(tempdir_factory, repo_source)
# config = make_config_from_repo(path)
# git_path = git_dir(tempdir_factory)
# return add_config_to_repo(git_path, config)
#
# Path: testing/util.py
# def cmd_output_mocked_pre_commit_home(
# *args, tempdir_factory, pre_commit_home=None, env=None, **kwargs,
# ):
# if pre_commit_home is None:
# pre_commit_home = tempdir_factory.get()
# env = env if env is not None else os.environ
# kwargs.setdefault('stderr', subprocess.STDOUT)
# # Don't want to write to the home directory
# env = dict(env, PRE_COMMIT_HOME=pre_commit_home)
# ret, out, _ = cmd_output(*args, env=env, **kwargs)
# return ret, out.replace('\r\n', '\n'), None
#
# Path: testing/util.py
# @contextlib.contextmanager
# def cwd(path):
# original_cwd = os.getcwd()
# os.chdir(path)
# try:
# yield
# finally:
# os.chdir(original_cwd)
#
# Path: testing/util.py
# def git_commit(*args, fn=cmd_output, msg='commit!', all_files=True, **kwargs):
# kwargs.setdefault('stderr', subprocess.STDOUT)
#
# cmd = ('git', 'commit', '--allow-empty', '--no-gpg-sign', *args)
# if all_files: # allow skipping `-a` with `all_files=False`
# cmd += ('-a',)
# if msg is not None: # allow skipping `-m` with `msg=None`
# cmd += ('-m', msg)
# ret, out, _ = fn(*cmd, **kwargs)
# return ret, out.replace('\r\n', '\n')
, which may contain function names, class names, or code. Output only the next line. | def test_init_templatedir_hookspath_set(tmpdir, tempdir_factory, store): |
Given the following code snippet before the placeholder: <|code_start|> )
assert target.join('hooks/pre-commit').exists()
@pytest.mark.parametrize(
('skip', 'commit_retcode', 'commit_output_snippet'),
(
(True, 0, 'Skipping `pre-commit`.'),
(False, 1, f'No {C.CONFIG_FILE} file was found'),
),
)
def test_init_templatedir_skip_on_missing_config(
tmpdir,
tempdir_factory,
store,
cap_out,
skip,
commit_retcode,
commit_output_snippet,
):
target = str(tmpdir.join('tmpl'))
init_git_dir = git_dir(tempdir_factory)
with cwd(init_git_dir):
cmd_output('git', 'config', 'init.templateDir', target)
init_templatedir(
C.CONFIG_FILE,
store,
target,
hook_types=['pre-commit'],
skip_on_missing_config=skip,
<|code_end|>
, predict the next line using imports from the current file:
import os.path
import pytest
import pre_commit.constants as C
from unittest import mock
from pre_commit.commands.init_templatedir import init_templatedir
from pre_commit.envcontext import envcontext
from pre_commit.util import cmd_output
from testing.fixtures import git_dir
from testing.fixtures import make_consuming_repo
from testing.util import cmd_output_mocked_pre_commit_home
from testing.util import cwd
from testing.util import git_commit
and context including class names, function names, and sometimes code from other files:
# Path: pre_commit/commands/init_templatedir.py
# def init_templatedir(
# config_file: str,
# store: Store,
# directory: str,
# hook_types: Sequence[str],
# skip_on_missing_config: bool = True,
# ) -> int:
# install(
# config_file,
# store,
# hook_types=hook_types,
# overwrite=True,
# skip_on_missing_config=skip_on_missing_config,
# git_dir=directory,
# )
# try:
# _, out, _ = cmd_output('git', 'config', 'init.templateDir')
# except CalledProcessError:
# configured_path = None
# else:
# configured_path = os.path.realpath(os.path.expanduser(out.strip()))
# dest = os.path.realpath(directory)
# if configured_path != dest:
# logger.warning('`init.templateDir` not set to the target directory')
# logger.warning(f'maybe `git config --global init.templateDir {dest}`?')
# return 0
#
# Path: pre_commit/envcontext.py
# @contextlib.contextmanager
# def envcontext(
# patch: PatchesT,
# _env: MutableMapping[str, str] | None = None,
# ) -> Generator[None, None, None]:
# """In this context, `os.environ` is modified according to `patch`.
#
# `patch` is an iterable of 2-tuples (key, value):
# `key`: string
# `value`:
# - string: `environ[key] == value` inside the context.
# - UNSET: `key not in environ` inside the context.
# - template: A template is a tuple of strings and Var which will be
# replaced with the previous environment
# """
# env = os.environ if _env is None else _env
# before = dict(env)
#
# for k, v in patch:
# if v is UNSET:
# env.pop(k, None)
# elif isinstance(v, tuple):
# env[k] = format_env(v, before)
# else:
# env[k] = v
#
# try:
# yield
# finally:
# env.clear()
# env.update(before)
#
# Path: pre_commit/util.py
# def cmd_output(*cmd: str, **kwargs: Any) -> tuple[int, str, str | None]:
# returncode, stdout_b, stderr_b = cmd_output_b(*cmd, **kwargs)
# stdout = stdout_b.decode() if stdout_b is not None else None
# stderr = stderr_b.decode() if stderr_b is not None else None
# return returncode, stdout, stderr
#
# Path: testing/fixtures.py
# def git_dir(tempdir_factory):
# path = tempdir_factory.get()
# cmd_output('git', 'init', path)
# return path
#
# Path: testing/fixtures.py
# def make_consuming_repo(tempdir_factory, repo_source):
# path = make_repo(tempdir_factory, repo_source)
# config = make_config_from_repo(path)
# git_path = git_dir(tempdir_factory)
# return add_config_to_repo(git_path, config)
#
# Path: testing/util.py
# def cmd_output_mocked_pre_commit_home(
# *args, tempdir_factory, pre_commit_home=None, env=None, **kwargs,
# ):
# if pre_commit_home is None:
# pre_commit_home = tempdir_factory.get()
# env = env if env is not None else os.environ
# kwargs.setdefault('stderr', subprocess.STDOUT)
# # Don't want to write to the home directory
# env = dict(env, PRE_COMMIT_HOME=pre_commit_home)
# ret, out, _ = cmd_output(*args, env=env, **kwargs)
# return ret, out.replace('\r\n', '\n'), None
#
# Path: testing/util.py
# @contextlib.contextmanager
# def cwd(path):
# original_cwd = os.getcwd()
# os.chdir(path)
# try:
# yield
# finally:
# os.chdir(original_cwd)
#
# Path: testing/util.py
# def git_commit(*args, fn=cmd_output, msg='commit!', all_files=True, **kwargs):
# kwargs.setdefault('stderr', subprocess.STDOUT)
#
# cmd = ('git', 'commit', '--allow-empty', '--no-gpg-sign', *args)
# if all_files: # allow skipping `-a` with `all_files=False`
# cmd += ('-a',)
# if msg is not None: # allow skipping `-m` with `msg=None`
# cmd += ('-m', msg)
# ret, out, _ = fn(*cmd, **kwargs)
# return ret, out.replace('\r\n', '\n')
. Output only the next line. | ) |
Given the following code snippet before the placeholder: <|code_start|> if '/*' in dct.get(self.key, ''):
logger.warning(
f'The top-level {self.key!r} field is a regex, not a glob -- '
f"matching '/*' probably isn't what you want here",
)
for fwd_slash_re in (r'[\\/]', r'[\/]', r'[/\\]'):
if fwd_slash_re in dct.get(self.key, ''):
logger.warning(
fr'pre-commit normalizes the slashes in the top-level '
fr'{self.key!r} field to forward slashes, so you '
fr'can use / instead of {fwd_slash_re}',
)
class MigrateShaToRev:
key = 'rev'
@staticmethod
def _cond(key: str) -> cfgv.Conditional:
return cfgv.Conditional(
key, cfgv.check_string,
condition_key='repo',
condition_value=cfgv.NotIn(LOCAL, META),
ensure_absent=True,
)
def check(self, dct: dict[str, Any]) -> None:
if dct.get('repo') in {LOCAL, META}:
self._cond('rev').check(dct)
self._cond('sha').check(dct)
<|code_end|>
, predict the next line using imports from the current file:
import argparse
import functools
import logging
import re
import shlex
import sys
import cfgv
import pre_commit.constants as C
from typing import Any
from typing import Sequence
from identify.identify import ALL_TAGS
from pre_commit.color import add_color_option
from pre_commit.errors import FatalError
from pre_commit.languages.all import all_languages
from pre_commit.logging_handler import logging_handler
from pre_commit.util import parse_version
from pre_commit.util import yaml_load
and context including class names, function names, and sometimes code from other files:
# Path: pre_commit/color.py
# def add_color_option(parser: argparse.ArgumentParser) -> None:
# parser.add_argument(
# '--color', default=os.environ.get('PRE_COMMIT_COLOR', 'auto'),
# type=use_color,
# metavar='{' + ','.join(COLOR_CHOICES) + '}',
# help='Whether to use color in output. Defaults to `%(default)s`.',
# )
#
# Path: pre_commit/errors.py
# class FatalError(RuntimeError):
# pass
#
# Path: pre_commit/languages/all.py
# class Language(NamedTuple):
# ENVIRONMENT_DIR: str | None
#
# Path: pre_commit/logging_handler.py
# @contextlib.contextmanager
# def logging_handler(use_color: bool) -> Generator[None, None, None]:
# handler = LoggingHandler(use_color)
# logger.addHandler(handler)
# logger.setLevel(logging.INFO)
# try:
# yield
# finally:
# logger.removeHandler(handler)
#
# Path: pre_commit/util.py
# def parse_version(s: str) -> tuple[int, ...]:
# """poor man's version comparison"""
# return tuple(int(p) for p in s.split('.'))
#
# Path: pre_commit/util.py
# def yaml_dump(o: Any, **kwargs: Any) -> str:
# def force_bytes(exc: Any) -> bytes:
# def clean_path_on_failure(path: str) -> Generator[None, None, None]:
# def tmpdir() -> Generator[str, None, None]:
# def resource_bytesio(filename: str) -> IO[bytes]:
# def resource_text(filename: str) -> str:
# def make_executable(filename: str) -> None:
# def __init__(
# self,
# returncode: int,
# cmd: tuple[str, ...],
# expected_returncode: int,
# stdout: bytes,
# stderr: bytes | None,
# ) -> None:
# def __bytes__(self) -> bytes:
# def _indent_or_none(part: bytes | None) -> bytes:
# def __str__(self) -> str:
# def _setdefault_kwargs(kwargs: dict[str, Any]) -> None:
# def _oserror_to_output(e: OSError) -> tuple[int, bytes, None]:
# def cmd_output_b(
# *cmd: str,
# retcode: int | None = 0,
# **kwargs: Any,
# ) -> tuple[int, bytes, bytes | None]:
# def cmd_output(*cmd: str, **kwargs: Any) -> tuple[int, str, str | None]:
# def __init__(self) -> None:
# def __enter__(self) -> Pty:
# def close_w(self) -> None:
# def close_r(self) -> None:
# def __exit__(
# self,
# exc_type: type[BaseException] | None,
# exc_value: BaseException | None,
# traceback: TracebackType | None,
# ) -> None:
# def cmd_output_p(
# *cmd: str,
# retcode: int | None = 0,
# **kwargs: Any,
# ) -> tuple[int, bytes, bytes | None]:
# def rmtree(path: str) -> None:
# def handle_remove_readonly(
# func: Callable[..., Any],
# path: str,
# exc: tuple[type[OSError], OSError, TracebackType],
# ) -> None:
# def parse_version(s: str) -> tuple[int, ...]:
# def win_exe(s: str) -> str:
# class CalledProcessError(RuntimeError):
# class Pty:
. Output only the next line. | elif 'sha' in dct and 'rev' in dct: |
Predict the next line after this snippet: <|code_start|> f'Hint: `pre-commit autoupdate` often fixes this.',
)
class OptionalSensibleRegexAtHook(cfgv.OptionalNoDefault):
def check(self, dct: dict[str, Any]) -> None:
super().check(dct)
if '/*' in dct.get(self.key, ''):
logger.warning(
f'The {self.key!r} field in hook {dct.get("id")!r} is a '
f"regex, not a glob -- matching '/*' probably isn't what you "
f'want here',
)
for fwd_slash_re in (r'[\\/]', r'[\/]', r'[/\\]'):
if fwd_slash_re in dct.get(self.key, ''):
logger.warning(
fr'pre-commit normalizes slashes in the {self.key!r} '
fr'field in hook {dct.get("id")!r} to forward slashes, '
fr'so you can use / instead of {fwd_slash_re}',
)
class OptionalSensibleRegexAtTop(cfgv.OptionalNoDefault):
def check(self, dct: dict[str, Any]) -> None:
super().check(dct)
if '/*' in dct.get(self.key, ''):
logger.warning(
f'The top-level {self.key!r} field is a regex, not a glob -- '
<|code_end|>
using the current file's imports:
import argparse
import functools
import logging
import re
import shlex
import sys
import cfgv
import pre_commit.constants as C
from typing import Any
from typing import Sequence
from identify.identify import ALL_TAGS
from pre_commit.color import add_color_option
from pre_commit.errors import FatalError
from pre_commit.languages.all import all_languages
from pre_commit.logging_handler import logging_handler
from pre_commit.util import parse_version
from pre_commit.util import yaml_load
and any relevant context from other files:
# Path: pre_commit/color.py
# def add_color_option(parser: argparse.ArgumentParser) -> None:
# parser.add_argument(
# '--color', default=os.environ.get('PRE_COMMIT_COLOR', 'auto'),
# type=use_color,
# metavar='{' + ','.join(COLOR_CHOICES) + '}',
# help='Whether to use color in output. Defaults to `%(default)s`.',
# )
#
# Path: pre_commit/errors.py
# class FatalError(RuntimeError):
# pass
#
# Path: pre_commit/languages/all.py
# class Language(NamedTuple):
# ENVIRONMENT_DIR: str | None
#
# Path: pre_commit/logging_handler.py
# @contextlib.contextmanager
# def logging_handler(use_color: bool) -> Generator[None, None, None]:
# handler = LoggingHandler(use_color)
# logger.addHandler(handler)
# logger.setLevel(logging.INFO)
# try:
# yield
# finally:
# logger.removeHandler(handler)
#
# Path: pre_commit/util.py
# def parse_version(s: str) -> tuple[int, ...]:
# """poor man's version comparison"""
# return tuple(int(p) for p in s.split('.'))
#
# Path: pre_commit/util.py
# def yaml_dump(o: Any, **kwargs: Any) -> str:
# def force_bytes(exc: Any) -> bytes:
# def clean_path_on_failure(path: str) -> Generator[None, None, None]:
# def tmpdir() -> Generator[str, None, None]:
# def resource_bytesio(filename: str) -> IO[bytes]:
# def resource_text(filename: str) -> str:
# def make_executable(filename: str) -> None:
# def __init__(
# self,
# returncode: int,
# cmd: tuple[str, ...],
# expected_returncode: int,
# stdout: bytes,
# stderr: bytes | None,
# ) -> None:
# def __bytes__(self) -> bytes:
# def _indent_or_none(part: bytes | None) -> bytes:
# def __str__(self) -> str:
# def _setdefault_kwargs(kwargs: dict[str, Any]) -> None:
# def _oserror_to_output(e: OSError) -> tuple[int, bytes, None]:
# def cmd_output_b(
# *cmd: str,
# retcode: int | None = 0,
# **kwargs: Any,
# ) -> tuple[int, bytes, bytes | None]:
# def cmd_output(*cmd: str, **kwargs: Any) -> tuple[int, str, str | None]:
# def __init__(self) -> None:
# def __enter__(self) -> Pty:
# def close_w(self) -> None:
# def close_r(self) -> None:
# def __exit__(
# self,
# exc_type: type[BaseException] | None,
# exc_value: BaseException | None,
# traceback: TracebackType | None,
# ) -> None:
# def cmd_output_p(
# *cmd: str,
# retcode: int | None = 0,
# **kwargs: Any,
# ) -> tuple[int, bytes, bytes | None]:
# def rmtree(path: str) -> None:
# def handle_remove_readonly(
# func: Callable[..., Any],
# path: str,
# exc: tuple[type[OSError], OSError, TracebackType],
# ) -> None:
# def parse_version(s: str) -> tuple[int, ...]:
# def win_exe(s: str) -> str:
# class CalledProcessError(RuntimeError):
# class Pty:
. Output only the next line. | f"matching '/*' probably isn't what you want here", |
Predict the next line for this snippet: <|code_start|> f'Try upgrading identify and pre-commit?',
)
def check_min_version(version: str) -> None:
if parse_version(version) > parse_version(C.VERSION):
raise cfgv.ValidationError(
f'pre-commit version {version} is required but version '
f'{C.VERSION} is installed. '
f'Perhaps run `pip install --upgrade pre-commit`.',
)
def _make_argparser(filenames_help: str) -> argparse.ArgumentParser:
parser = argparse.ArgumentParser()
parser.add_argument('filenames', nargs='*', help=filenames_help)
parser.add_argument('-V', '--version', action='version', version=C.VERSION)
add_color_option(parser)
return parser
MANIFEST_HOOK_DICT = cfgv.Map(
'Hook', 'id',
cfgv.Required('id', cfgv.check_string),
cfgv.Required('name', cfgv.check_string),
cfgv.Required('entry', cfgv.check_string),
cfgv.Required('language', cfgv.check_one_of(all_languages)),
cfgv.Optional('alias', cfgv.check_string, ''),
<|code_end|>
with the help of current file imports:
import argparse
import functools
import logging
import re
import shlex
import sys
import cfgv
import pre_commit.constants as C
from typing import Any
from typing import Sequence
from identify.identify import ALL_TAGS
from pre_commit.color import add_color_option
from pre_commit.errors import FatalError
from pre_commit.languages.all import all_languages
from pre_commit.logging_handler import logging_handler
from pre_commit.util import parse_version
from pre_commit.util import yaml_load
and context from other files:
# Path: pre_commit/color.py
# def add_color_option(parser: argparse.ArgumentParser) -> None:
# parser.add_argument(
# '--color', default=os.environ.get('PRE_COMMIT_COLOR', 'auto'),
# type=use_color,
# metavar='{' + ','.join(COLOR_CHOICES) + '}',
# help='Whether to use color in output. Defaults to `%(default)s`.',
# )
#
# Path: pre_commit/errors.py
# class FatalError(RuntimeError):
# pass
#
# Path: pre_commit/languages/all.py
# class Language(NamedTuple):
# ENVIRONMENT_DIR: str | None
#
# Path: pre_commit/logging_handler.py
# @contextlib.contextmanager
# def logging_handler(use_color: bool) -> Generator[None, None, None]:
# handler = LoggingHandler(use_color)
# logger.addHandler(handler)
# logger.setLevel(logging.INFO)
# try:
# yield
# finally:
# logger.removeHandler(handler)
#
# Path: pre_commit/util.py
# def parse_version(s: str) -> tuple[int, ...]:
# """poor man's version comparison"""
# return tuple(int(p) for p in s.split('.'))
#
# Path: pre_commit/util.py
# def yaml_dump(o: Any, **kwargs: Any) -> str:
# def force_bytes(exc: Any) -> bytes:
# def clean_path_on_failure(path: str) -> Generator[None, None, None]:
# def tmpdir() -> Generator[str, None, None]:
# def resource_bytesio(filename: str) -> IO[bytes]:
# def resource_text(filename: str) -> str:
# def make_executable(filename: str) -> None:
# def __init__(
# self,
# returncode: int,
# cmd: tuple[str, ...],
# expected_returncode: int,
# stdout: bytes,
# stderr: bytes | None,
# ) -> None:
# def __bytes__(self) -> bytes:
# def _indent_or_none(part: bytes | None) -> bytes:
# def __str__(self) -> str:
# def _setdefault_kwargs(kwargs: dict[str, Any]) -> None:
# def _oserror_to_output(e: OSError) -> tuple[int, bytes, None]:
# def cmd_output_b(
# *cmd: str,
# retcode: int | None = 0,
# **kwargs: Any,
# ) -> tuple[int, bytes, bytes | None]:
# def cmd_output(*cmd: str, **kwargs: Any) -> tuple[int, str, str | None]:
# def __init__(self) -> None:
# def __enter__(self) -> Pty:
# def close_w(self) -> None:
# def close_r(self) -> None:
# def __exit__(
# self,
# exc_type: type[BaseException] | None,
# exc_value: BaseException | None,
# traceback: TracebackType | None,
# ) -> None:
# def cmd_output_p(
# *cmd: str,
# retcode: int | None = 0,
# **kwargs: Any,
# ) -> tuple[int, bytes, bytes | None]:
# def rmtree(path: str) -> None:
# def handle_remove_readonly(
# func: Callable[..., Any],
# path: str,
# exc: tuple[type[OSError], OSError, TracebackType],
# ) -> None:
# def parse_version(s: str) -> tuple[int, ...]:
# def win_exe(s: str) -> str:
# class CalledProcessError(RuntimeError):
# class Pty:
, which may contain function names, class names, or code. Output only the next line. | cfgv.Optional('files', check_string_regex, ''), |
Here is a snippet: <|code_start|> cfgv.Optional('description', cfgv.check_string, ''),
cfgv.Optional('language_version', cfgv.check_string, C.DEFAULT),
cfgv.Optional('log_file', cfgv.check_string, ''),
cfgv.Optional('minimum_pre_commit_version', cfgv.check_string, '0'),
cfgv.Optional('require_serial', cfgv.check_bool, False),
cfgv.Optional('stages', cfgv.check_array(cfgv.check_one_of(C.STAGES)), []),
cfgv.Optional('verbose', cfgv.check_bool, False),
)
MANIFEST_SCHEMA = cfgv.Array(MANIFEST_HOOK_DICT)
class InvalidManifestError(FatalError):
pass
load_manifest = functools.partial(
cfgv.load_from_filename,
schema=MANIFEST_SCHEMA,
load_strategy=yaml_load,
exc_tp=InvalidManifestError,
)
def validate_manifest_main(argv: Sequence[str] | None = None) -> int:
parser = _make_argparser('Manifest filenames.')
args = parser.parse_args(argv)
with logging_handler(args.color):
ret = 0
for filename in args.filenames:
<|code_end|>
. Write the next line using the current file imports:
import argparse
import functools
import logging
import re
import shlex
import sys
import cfgv
import pre_commit.constants as C
from typing import Any
from typing import Sequence
from identify.identify import ALL_TAGS
from pre_commit.color import add_color_option
from pre_commit.errors import FatalError
from pre_commit.languages.all import all_languages
from pre_commit.logging_handler import logging_handler
from pre_commit.util import parse_version
from pre_commit.util import yaml_load
and context from other files:
# Path: pre_commit/color.py
# def add_color_option(parser: argparse.ArgumentParser) -> None:
# parser.add_argument(
# '--color', default=os.environ.get('PRE_COMMIT_COLOR', 'auto'),
# type=use_color,
# metavar='{' + ','.join(COLOR_CHOICES) + '}',
# help='Whether to use color in output. Defaults to `%(default)s`.',
# )
#
# Path: pre_commit/errors.py
# class FatalError(RuntimeError):
# pass
#
# Path: pre_commit/languages/all.py
# class Language(NamedTuple):
# ENVIRONMENT_DIR: str | None
#
# Path: pre_commit/logging_handler.py
# @contextlib.contextmanager
# def logging_handler(use_color: bool) -> Generator[None, None, None]:
# handler = LoggingHandler(use_color)
# logger.addHandler(handler)
# logger.setLevel(logging.INFO)
# try:
# yield
# finally:
# logger.removeHandler(handler)
#
# Path: pre_commit/util.py
# def parse_version(s: str) -> tuple[int, ...]:
# """poor man's version comparison"""
# return tuple(int(p) for p in s.split('.'))
#
# Path: pre_commit/util.py
# def yaml_dump(o: Any, **kwargs: Any) -> str:
# def force_bytes(exc: Any) -> bytes:
# def clean_path_on_failure(path: str) -> Generator[None, None, None]:
# def tmpdir() -> Generator[str, None, None]:
# def resource_bytesio(filename: str) -> IO[bytes]:
# def resource_text(filename: str) -> str:
# def make_executable(filename: str) -> None:
# def __init__(
# self,
# returncode: int,
# cmd: tuple[str, ...],
# expected_returncode: int,
# stdout: bytes,
# stderr: bytes | None,
# ) -> None:
# def __bytes__(self) -> bytes:
# def _indent_or_none(part: bytes | None) -> bytes:
# def __str__(self) -> str:
# def _setdefault_kwargs(kwargs: dict[str, Any]) -> None:
# def _oserror_to_output(e: OSError) -> tuple[int, bytes, None]:
# def cmd_output_b(
# *cmd: str,
# retcode: int | None = 0,
# **kwargs: Any,
# ) -> tuple[int, bytes, bytes | None]:
# def cmd_output(*cmd: str, **kwargs: Any) -> tuple[int, str, str | None]:
# def __init__(self) -> None:
# def __enter__(self) -> Pty:
# def close_w(self) -> None:
# def close_r(self) -> None:
# def __exit__(
# self,
# exc_type: type[BaseException] | None,
# exc_value: BaseException | None,
# traceback: TracebackType | None,
# ) -> None:
# def cmd_output_p(
# *cmd: str,
# retcode: int | None = 0,
# **kwargs: Any,
# ) -> tuple[int, bytes, bytes | None]:
# def rmtree(path: str) -> None:
# def handle_remove_readonly(
# func: Callable[..., Any],
# path: str,
# exc: tuple[type[OSError], OSError, TracebackType],
# ) -> None:
# def parse_version(s: str) -> tuple[int, ...]:
# def win_exe(s: str) -> str:
# class CalledProcessError(RuntimeError):
# class Pty:
, which may include functions, classes, or code. Output only the next line. | try: |
Given snippet: <|code_start|> logger.warning(
f'The {self.key!r} field of repo {dct["repo"]!r} '
f'appears to be a mutable reference '
f'(moving tag / branch). Mutable references are never '
f'updated after first install and are not supported. '
f'See https://pre-commit.com/#using-the-latest-version-for-a-repository ' # noqa: E501
f'for more details. '
f'Hint: `pre-commit autoupdate` often fixes this.',
)
class OptionalSensibleRegexAtHook(cfgv.OptionalNoDefault):
def check(self, dct: dict[str, Any]) -> None:
super().check(dct)
if '/*' in dct.get(self.key, ''):
logger.warning(
f'The {self.key!r} field in hook {dct.get("id")!r} is a '
f"regex, not a glob -- matching '/*' probably isn't what you "
f'want here',
)
for fwd_slash_re in (r'[\\/]', r'[\/]', r'[/\\]'):
if fwd_slash_re in dct.get(self.key, ''):
logger.warning(
fr'pre-commit normalizes slashes in the {self.key!r} '
fr'field in hook {dct.get("id")!r} to forward slashes, '
fr'so you can use / instead of {fwd_slash_re}',
)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import argparse
import functools
import logging
import re
import shlex
import sys
import cfgv
import pre_commit.constants as C
from typing import Any
from typing import Sequence
from identify.identify import ALL_TAGS
from pre_commit.color import add_color_option
from pre_commit.errors import FatalError
from pre_commit.languages.all import all_languages
from pre_commit.logging_handler import logging_handler
from pre_commit.util import parse_version
from pre_commit.util import yaml_load
and context:
# Path: pre_commit/color.py
# def add_color_option(parser: argparse.ArgumentParser) -> None:
# parser.add_argument(
# '--color', default=os.environ.get('PRE_COMMIT_COLOR', 'auto'),
# type=use_color,
# metavar='{' + ','.join(COLOR_CHOICES) + '}',
# help='Whether to use color in output. Defaults to `%(default)s`.',
# )
#
# Path: pre_commit/errors.py
# class FatalError(RuntimeError):
# pass
#
# Path: pre_commit/languages/all.py
# class Language(NamedTuple):
# ENVIRONMENT_DIR: str | None
#
# Path: pre_commit/logging_handler.py
# @contextlib.contextmanager
# def logging_handler(use_color: bool) -> Generator[None, None, None]:
# handler = LoggingHandler(use_color)
# logger.addHandler(handler)
# logger.setLevel(logging.INFO)
# try:
# yield
# finally:
# logger.removeHandler(handler)
#
# Path: pre_commit/util.py
# def parse_version(s: str) -> tuple[int, ...]:
# """poor man's version comparison"""
# return tuple(int(p) for p in s.split('.'))
#
# Path: pre_commit/util.py
# def yaml_dump(o: Any, **kwargs: Any) -> str:
# def force_bytes(exc: Any) -> bytes:
# def clean_path_on_failure(path: str) -> Generator[None, None, None]:
# def tmpdir() -> Generator[str, None, None]:
# def resource_bytesio(filename: str) -> IO[bytes]:
# def resource_text(filename: str) -> str:
# def make_executable(filename: str) -> None:
# def __init__(
# self,
# returncode: int,
# cmd: tuple[str, ...],
# expected_returncode: int,
# stdout: bytes,
# stderr: bytes | None,
# ) -> None:
# def __bytes__(self) -> bytes:
# def _indent_or_none(part: bytes | None) -> bytes:
# def __str__(self) -> str:
# def _setdefault_kwargs(kwargs: dict[str, Any]) -> None:
# def _oserror_to_output(e: OSError) -> tuple[int, bytes, None]:
# def cmd_output_b(
# *cmd: str,
# retcode: int | None = 0,
# **kwargs: Any,
# ) -> tuple[int, bytes, bytes | None]:
# def cmd_output(*cmd: str, **kwargs: Any) -> tuple[int, str, str | None]:
# def __init__(self) -> None:
# def __enter__(self) -> Pty:
# def close_w(self) -> None:
# def close_r(self) -> None:
# def __exit__(
# self,
# exc_type: type[BaseException] | None,
# exc_value: BaseException | None,
# traceback: TracebackType | None,
# ) -> None:
# def cmd_output_p(
# *cmd: str,
# retcode: int | None = 0,
# **kwargs: Any,
# ) -> tuple[int, bytes, bytes | None]:
# def rmtree(path: str) -> None:
# def handle_remove_readonly(
# func: Callable[..., Any],
# path: str,
# exc: tuple[type[OSError], OSError, TracebackType],
# ) -> None:
# def parse_version(s: str) -> tuple[int, ...]:
# def win_exe(s: str) -> str:
# class CalledProcessError(RuntimeError):
# class Pty:
which might include code, classes, or functions. Output only the next line. | class OptionalSensibleRegexAtTop(cfgv.OptionalNoDefault): |
Based on the snippet: <|code_start|> assert ACTUAL_GET_DEFAULT_VERSION() == 'system'
@pytest.mark.usefixtures('is_linux')
def test_uses_default_when_node_and_npm_are_not_available(find_exe_mck):
find_exe_mck.return_value = None
assert ACTUAL_GET_DEFAULT_VERSION() == C.DEFAULT
@pytest.mark.usefixtures('is_win32')
def test_sets_default_on_windows(find_exe_mck):
find_exe_mck.return_value = '/path/to/exe'
assert ACTUAL_GET_DEFAULT_VERSION() == C.DEFAULT
@xfailif_windows # pragma: win32 no cover
def test_healthy_system_node(tmpdir):
tmpdir.join('package.json').write('{"name": "t", "version": "1.0.0"}')
prefix = Prefix(str(tmpdir))
node.install_environment(prefix, 'system', ())
assert node.healthy(prefix, 'system')
@xfailif_windows # pragma: win32 no cover
def test_unhealthy_if_system_node_goes_missing(tmpdir):
bin_dir = tmpdir.join('bin').ensure_dir()
node_bin = bin_dir.join('node')
node_bin.mksymlinkto(shutil.which('node'))
<|code_end|>
, predict the immediate next line with the help of imports:
import json
import os
import shutil
import sys
import pytest
import pre_commit.constants as C
from unittest import mock
from pre_commit import envcontext
from pre_commit import parse_shebang
from pre_commit.languages import node
from pre_commit.prefix import Prefix
from pre_commit.util import cmd_output
from testing.util import xfailif_windows
and context (classes, functions, sometimes code) from other files:
# Path: pre_commit/envcontext.py
# @contextlib.contextmanager
# def envcontext(
# patch: PatchesT,
# _env: MutableMapping[str, str] | None = None,
# ) -> Generator[None, None, None]:
# """In this context, `os.environ` is modified according to `patch`.
#
# `patch` is an iterable of 2-tuples (key, value):
# `key`: string
# `value`:
# - string: `environ[key] == value` inside the context.
# - UNSET: `key not in environ` inside the context.
# - template: A template is a tuple of strings and Var which will be
# replaced with the previous environment
# """
# env = os.environ if _env is None else _env
# before = dict(env)
#
# for k, v in patch:
# if v is UNSET:
# env.pop(k, None)
# elif isinstance(v, tuple):
# env[k] = format_env(v, before)
# else:
# env[k] = v
#
# try:
# yield
# finally:
# env.clear()
# env.update(before)
#
# Path: pre_commit/parse_shebang.py
# class ExecutableNotFoundError(OSError):
# def to_output(self) -> tuple[int, bytes, None]:
# def parse_filename(filename: str) -> tuple[str, ...]:
# def find_executable(
# exe: str, _environ: Mapping[str, str] | None = None,
# ) -> str | None:
# def normexe(orig: str) -> str:
# def _error(msg: str) -> NoReturn:
# def normalize_cmd(cmd: tuple[str, ...]) -> tuple[str, ...]:
#
# Path: pre_commit/languages/node.py
# ENVIRONMENT_DIR = 'node_env'
# def get_default_version() -> str:
# def _envdir(prefix: Prefix, version: str) -> str:
# def get_env_patch(venv: str) -> PatchesT:
# def in_env(
# prefix: Prefix,
# language_version: str,
# ) -> Generator[None, None, None]:
# def healthy(prefix: Prefix, language_version: str) -> bool:
# def install_environment(
# prefix: Prefix, version: str, additional_dependencies: Sequence[str],
# ) -> None:
# def run_hook(
# hook: Hook,
# file_args: Sequence[str],
# color: bool,
# ) -> tuple[int, bytes]:
#
# Path: pre_commit/prefix.py
# class Prefix(NamedTuple):
# prefix_dir: str
#
# def path(self, *parts: str) -> str:
# return os.path.normpath(os.path.join(self.prefix_dir, *parts))
#
# def exists(self, *parts: str) -> bool:
# return os.path.exists(self.path(*parts))
#
# def star(self, end: str) -> tuple[str, ...]:
# paths = os.listdir(self.prefix_dir)
# return tuple(path for path in paths if path.endswith(end))
#
# Path: pre_commit/util.py
# def cmd_output(*cmd: str, **kwargs: Any) -> tuple[int, str, str | None]:
# returncode, stdout_b, stderr_b = cmd_output_b(*cmd, **kwargs)
# stdout = stdout_b.decode() if stdout_b is not None else None
# stderr = stderr_b.decode() if stderr_b is not None else None
# return returncode, stdout, stderr
#
# Path: testing/util.py
# TESTING_DIR = os.path.abspath(os.path.dirname(__file__))
# def docker_is_running() -> bool: # pragma: win32 no cover
# def get_resource_path(path):
# def cmd_output_mocked_pre_commit_home(
# *args, tempdir_factory, pre_commit_home=None, env=None, **kwargs,
# ):
# def run_opts(
# all_files=False,
# files=(),
# color=False,
# verbose=False,
# hook=None,
# remote_branch='',
# local_branch='',
# from_ref='',
# to_ref='',
# remote_name='',
# remote_url='',
# hook_stage='commit',
# show_diff_on_failure=False,
# commit_msg_filename='',
# checkout_type='',
# is_squash_merge='',
# rewrite_command='',
# ):
# def cwd(path):
# def git_commit(*args, fn=cmd_output, msg='commit!', all_files=True, **kwargs):
. Output only the next line. | prefix_dir = tmpdir.join('prefix').ensure_dir() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.