Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given the following code snippet before the placeholder: <|code_start|> @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')) prefix_dir = tmpdir.join('prefix').ensure_dir() <|code_end|> , predict the next line using imports from the current file: 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 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/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.join('package.json').write('{"name": "t", "version": "1.0.0"}')
Given snippet: <|code_start|>def is_linux(): with mock.patch.object(sys, 'platform', 'linux'): yield @pytest.fixture def is_win32(): with mock.patch.object(sys, 'platform', 'win32'): yield @pytest.fixture def find_exe_mck(): with mock.patch.object(parse_shebang, 'find_executable') as mck: yield mck @pytest.mark.usefixtures('is_linux') def test_sets_system_when_node_and_npm_are_available(find_exe_mck): find_exe_mck.return_value = '/path/to/exe' 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') <|code_end|> , continue by predicting the next line. Consider current file 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: # 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): which might include code, classes, or functions. Output only the next line.
def test_sets_default_on_windows(find_exe_mck):
Using the snippet: <|code_start|>def is_win32(): with mock.patch.object(sys, 'platform', 'win32'): yield @pytest.fixture def find_exe_mck(): with mock.patch.object(parse_shebang, 'find_executable') as mck: yield mck @pytest.mark.usefixtures('is_linux') def test_sets_system_when_node_and_npm_are_available(find_exe_mck): find_exe_mck.return_value = '/path/to/exe' 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 <|code_end|> , determine the next line of code. You have 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 (class names, function names, or code) available: # 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.
def test_healthy_system_node(tmpdir):
Given snippet: <|code_start|>from __future__ import annotations ACTUAL_GET_DEFAULT_VERSION = node.get_default_version.__wrapped__ @pytest.fixture def is_linux(): with mock.patch.object(sys, 'platform', 'linux'): yield @pytest.fixture def is_win32(): with mock.patch.object(sys, 'platform', 'win32'): yield @pytest.fixture <|code_end|> , continue by predicting the next line. Consider current file 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: # 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): which might include code, classes, or functions. Output only the next line.
def find_exe_mck():
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 <|code_end|> . Use current file imports: from typing import Sequence from pre_commit.hook import Hook from pre_commit.languages import helpers from pre_commit.languages.docker import docker_cmd 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]: # # Path: pre_commit/languages/docker.py # def docker_cmd() -> tuple[str, ...]: # pragma: win32 no cover # return ( # 'docker', 'run', # '--rm', # *get_docker_user(), # # https://docs.docker.com/engine/reference/commandline/run/#mount-volumes-from-container-volumes-from # # The `Z` option tells Docker to label the content with a private # # unshared label. Only the current container can use a private volume. # '-v', f'{_get_docker_path(os.getcwd())}:/src:rw,Z', # '--workdir', '/src', # ) . Output only the next line.
def run_hook(
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 <|code_end|> . Use current file imports: from typing import Sequence from pre_commit.hook import Hook from pre_commit.languages import helpers from pre_commit.languages.docker import docker_cmd 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]: # # Path: pre_commit/languages/docker.py # def docker_cmd() -> tuple[str, ...]: # pragma: win32 no cover # return ( # 'docker', 'run', # '--rm', # *get_docker_user(), # # https://docs.docker.com/engine/reference/commandline/run/#mount-volumes-from-container-volumes-from # # The `Z` option tells Docker to label the content with a private # # unshared label. Only the current container can use a private volume. # '-v', f'{_get_docker_path(os.getcwd())}:/src:rw,Z', # '--workdir', '/src', # ) . Output only the next line.
def run_hook(
Based on the snippet: <|code_start|> foo_file.write(FOO_CONTENTS.replace('1', 'a')) _test_foo_state(foo_staged, FOO_CONTENTS.replace('1', 'a'), 'AM') with staged_files_only(patch_dir): _test_foo_state(foo_staged) # Modify in the same place as the stashed diff with open(foo_staged.foo_filename, 'w') as foo_file: foo_file.write(FOO_CONTENTS.replace('1', 'b')) _test_foo_state(foo_staged, FOO_CONTENTS.replace('1', 'b'), 'AM') _test_foo_state(foo_staged, FOO_CONTENTS.replace('1', 'a'), 'AM') @pytest.fixture def img_staged(in_git_dir): img = in_git_dir.join('img.jpg') shutil.copy(get_resource_path('img1.jpg'), img.strpath) cmd_output('git', 'add', 'img.jpg') yield auto_namedtuple(path=in_git_dir.strpath, img_filename=img.strpath) def _test_img_state(path, expected_file='img1.jpg', status='A'): assert os.path.exists(path.img_filename) with open(path.img_filename, 'rb') as f1: with open(get_resource_path(expected_file), 'rb') as f2: assert f1.read() == f2.read() actual_status = get_short_git_status()['img.jpg'] <|code_end|> , predict the immediate next line with the help of imports: import itertools import os.path import shutil import pytest from pre_commit import git from pre_commit.staged_files_only import staged_files_only from pre_commit.util import cmd_output from testing.auto_namedtuple import auto_namedtuple from testing.fixtures import git_dir from testing.util import cwd from testing.util import get_resource_path from testing.util import git_commit and context (classes, functions, sometimes code) from other files: # Path: pre_commit/git.py # NO_FS_MONITOR = ('-c', 'core.useBuiltinFSMonitor=false') # def zsplit(s: str) -> list[str]: # def no_git_env( # _env: MutableMapping[str, str] | None = None, # ) -> dict[str, str]: # def get_root() -> str: # def get_git_dir(git_root: str = '.') -> str: # def get_remote_url(git_root: str) -> str: # def is_in_merge_conflict() -> bool: # def parse_merge_msg_for_conflicts(merge_msg: bytes) -> list[str]: # def get_conflicted_files() -> set[str]: # def get_staged_files(cwd: str | None = None) -> list[str]: # def intent_to_add_files() -> list[str]: # def get_all_files() -> list[str]: # def get_changed_files(old: str, new: str) -> list[str]: # def head_rev(remote: str) -> str: # def has_diff(*args: str, repo: str = '.') -> bool: # def has_core_hookpaths_set() -> bool: # def init_repo(path: str, remote: str) -> None: # def commit(repo: str = '.') -> None: # def git_path(name: str, repo: str = '.') -> str: # def check_for_cygwin_mismatch() -> None: # # Path: pre_commit/staged_files_only.py # @contextlib.contextmanager # def staged_files_only(patch_dir: str) -> Generator[None, None, None]: # """Clear any unstaged changes from the git working directory inside this # context. # """ # with _intent_to_add_cleared(), _unstaged_changes_cleared(patch_dir): # yield # # 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/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)) # # Path: testing/fixtures.py # def git_dir(tempdir_factory): # path = tempdir_factory.get() # cmd_output('git', 'init', path) # return path # # 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 get_resource_path(path): # return os.path.join(TESTING_DIR, 'resources', path) # # 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 status == actual_status
Given snippet: <|code_start|> test_foo_something_unstaged(foo_staged, patch_dir) def test_foo_something_unstaged_diff_color_always(foo_staged, patch_dir): cmd_output('git', 'config', '--local', 'color.diff', 'always') test_foo_something_unstaged(foo_staged, patch_dir) def test_foo_both_modify_non_conflicting(foo_staged, patch_dir): with open(foo_staged.foo_filename, 'w') as foo_file: foo_file.write(f'{FOO_CONTENTS}9\n') _test_foo_state(foo_staged, f'{FOO_CONTENTS}9\n', 'AM') with staged_files_only(patch_dir): _test_foo_state(foo_staged) # Modify the file as part of the "pre-commit" with open(foo_staged.foo_filename, 'w') as foo_file: foo_file.write(FOO_CONTENTS.replace('1', 'a')) _test_foo_state(foo_staged, FOO_CONTENTS.replace('1', 'a'), 'AM') _test_foo_state(foo_staged, f'{FOO_CONTENTS.replace("1", "a")}9\n', 'AM') def test_foo_both_modify_conflicting(foo_staged, patch_dir): with open(foo_staged.foo_filename, 'w') as foo_file: foo_file.write(FOO_CONTENTS.replace('1', 'a')) <|code_end|> , continue by predicting the next line. Consider current file imports: import itertools import os.path import shutil import pytest from pre_commit import git from pre_commit.staged_files_only import staged_files_only from pre_commit.util import cmd_output from testing.auto_namedtuple import auto_namedtuple from testing.fixtures import git_dir from testing.util import cwd from testing.util import get_resource_path from testing.util import git_commit and context: # Path: pre_commit/git.py # NO_FS_MONITOR = ('-c', 'core.useBuiltinFSMonitor=false') # def zsplit(s: str) -> list[str]: # def no_git_env( # _env: MutableMapping[str, str] | None = None, # ) -> dict[str, str]: # def get_root() -> str: # def get_git_dir(git_root: str = '.') -> str: # def get_remote_url(git_root: str) -> str: # def is_in_merge_conflict() -> bool: # def parse_merge_msg_for_conflicts(merge_msg: bytes) -> list[str]: # def get_conflicted_files() -> set[str]: # def get_staged_files(cwd: str | None = None) -> list[str]: # def intent_to_add_files() -> list[str]: # def get_all_files() -> list[str]: # def get_changed_files(old: str, new: str) -> list[str]: # def head_rev(remote: str) -> str: # def has_diff(*args: str, repo: str = '.') -> bool: # def has_core_hookpaths_set() -> bool: # def init_repo(path: str, remote: str) -> None: # def commit(repo: str = '.') -> None: # def git_path(name: str, repo: str = '.') -> str: # def check_for_cygwin_mismatch() -> None: # # Path: pre_commit/staged_files_only.py # @contextlib.contextmanager # def staged_files_only(patch_dir: str) -> Generator[None, None, None]: # """Clear any unstaged changes from the git working directory inside this # context. # """ # with _intent_to_add_cleared(), _unstaged_changes_cleared(patch_dir): # yield # # 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/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)) # # Path: testing/fixtures.py # def git_dir(tempdir_factory): # path = tempdir_factory.get() # cmd_output('git', 'init', path) # return path # # 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 get_resource_path(path): # return os.path.join(TESTING_DIR, 'resources', path) # # 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 might include code, classes, or functions. Output only the next line.
_test_foo_state(foo_staged, FOO_CONTENTS.replace('1', 'a'), 'AM')
Using the snippet: <|code_start|> FOO_CONTENTS = '\n'.join(('1', '2', '3', '4', '5', '6', '7', '8', '')) @pytest.fixture def patch_dir(tempdir_factory): return tempdir_factory.get() def get_short_git_status(): git_status = cmd_output('git', 'status', '-s')[1] line_parts = [line.split() for line in git_status.splitlines()] return {v: k for k, v in line_parts} @pytest.fixture def foo_staged(in_git_dir): foo = in_git_dir.join('foo') foo.write(FOO_CONTENTS) cmd_output('git', 'add', 'foo') yield auto_namedtuple(path=in_git_dir.strpath, foo_filename=foo.strpath) def _test_foo_state( path, foo_contents=FOO_CONTENTS, status='A', encoding='UTF-8', <|code_end|> , determine the next line of code. You have imports: import itertools import os.path import shutil import pytest from pre_commit import git from pre_commit.staged_files_only import staged_files_only from pre_commit.util import cmd_output from testing.auto_namedtuple import auto_namedtuple from testing.fixtures import git_dir from testing.util import cwd from testing.util import get_resource_path from testing.util import git_commit and context (class names, function names, or code) available: # Path: pre_commit/git.py # NO_FS_MONITOR = ('-c', 'core.useBuiltinFSMonitor=false') # def zsplit(s: str) -> list[str]: # def no_git_env( # _env: MutableMapping[str, str] | None = None, # ) -> dict[str, str]: # def get_root() -> str: # def get_git_dir(git_root: str = '.') -> str: # def get_remote_url(git_root: str) -> str: # def is_in_merge_conflict() -> bool: # def parse_merge_msg_for_conflicts(merge_msg: bytes) -> list[str]: # def get_conflicted_files() -> set[str]: # def get_staged_files(cwd: str | None = None) -> list[str]: # def intent_to_add_files() -> list[str]: # def get_all_files() -> list[str]: # def get_changed_files(old: str, new: str) -> list[str]: # def head_rev(remote: str) -> str: # def has_diff(*args: str, repo: str = '.') -> bool: # def has_core_hookpaths_set() -> bool: # def init_repo(path: str, remote: str) -> None: # def commit(repo: str = '.') -> None: # def git_path(name: str, repo: str = '.') -> str: # def check_for_cygwin_mismatch() -> None: # # Path: pre_commit/staged_files_only.py # @contextlib.contextmanager # def staged_files_only(patch_dir: str) -> Generator[None, None, None]: # """Clear any unstaged changes from the git working directory inside this # context. # """ # with _intent_to_add_cleared(), _unstaged_changes_cleared(patch_dir): # yield # # 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/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)) # # Path: testing/fixtures.py # def git_dir(tempdir_factory): # path = tempdir_factory.get() # cmd_output('git', 'init', path) # return path # # 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 get_resource_path(path): # return os.path.join(TESTING_DIR, 'resources', path) # # 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.
):
Predict the next line after this snippet: <|code_start|> FOO_CONTENTS = '\n'.join(('1', '2', '3', '4', '5', '6', '7', '8', '')) @pytest.fixture def patch_dir(tempdir_factory): return tempdir_factory.get() def get_short_git_status(): git_status = cmd_output('git', 'status', '-s')[1] line_parts = [line.split() for line in git_status.splitlines()] return {v: k for k, v in line_parts} @pytest.fixture def foo_staged(in_git_dir): foo = in_git_dir.join('foo') foo.write(FOO_CONTENTS) cmd_output('git', 'add', 'foo') yield auto_namedtuple(path=in_git_dir.strpath, foo_filename=foo.strpath) def _test_foo_state( path, foo_contents=FOO_CONTENTS, status='A', <|code_end|> using the current file's imports: import itertools import os.path import shutil import pytest from pre_commit import git from pre_commit.staged_files_only import staged_files_only from pre_commit.util import cmd_output from testing.auto_namedtuple import auto_namedtuple from testing.fixtures import git_dir from testing.util import cwd from testing.util import get_resource_path from testing.util import git_commit and any relevant context from other files: # Path: pre_commit/git.py # NO_FS_MONITOR = ('-c', 'core.useBuiltinFSMonitor=false') # def zsplit(s: str) -> list[str]: # def no_git_env( # _env: MutableMapping[str, str] | None = None, # ) -> dict[str, str]: # def get_root() -> str: # def get_git_dir(git_root: str = '.') -> str: # def get_remote_url(git_root: str) -> str: # def is_in_merge_conflict() -> bool: # def parse_merge_msg_for_conflicts(merge_msg: bytes) -> list[str]: # def get_conflicted_files() -> set[str]: # def get_staged_files(cwd: str | None = None) -> list[str]: # def intent_to_add_files() -> list[str]: # def get_all_files() -> list[str]: # def get_changed_files(old: str, new: str) -> list[str]: # def head_rev(remote: str) -> str: # def has_diff(*args: str, repo: str = '.') -> bool: # def has_core_hookpaths_set() -> bool: # def init_repo(path: str, remote: str) -> None: # def commit(repo: str = '.') -> None: # def git_path(name: str, repo: str = '.') -> str: # def check_for_cygwin_mismatch() -> None: # # Path: pre_commit/staged_files_only.py # @contextlib.contextmanager # def staged_files_only(patch_dir: str) -> Generator[None, None, None]: # """Clear any unstaged changes from the git working directory inside this # context. # """ # with _intent_to_add_cleared(), _unstaged_changes_cleared(patch_dir): # yield # # 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/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)) # # Path: testing/fixtures.py # def git_dir(tempdir_factory): # path = tempdir_factory.get() # cmd_output('git', 'init', path) # return path # # 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 get_resource_path(path): # return os.path.join(TESTING_DIR, 'resources', path) # # 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.
encoding='UTF-8',
Next line prediction: <|code_start|> with open(foo_staged.foo_filename, 'w') as foo_file: foo_file.write(f'{FOO_CONTENTS}9\n') _test_foo_state(foo_staged, f'{FOO_CONTENTS}9\n', 'AM') with staged_files_only(patch_dir): _test_foo_state(foo_staged) # Modify the file as part of the "pre-commit" with open(foo_staged.foo_filename, 'w') as foo_file: foo_file.write(FOO_CONTENTS.replace('1', 'a')) _test_foo_state(foo_staged, FOO_CONTENTS.replace('1', 'a'), 'AM') _test_foo_state(foo_staged, f'{FOO_CONTENTS.replace("1", "a")}9\n', 'AM') def test_foo_both_modify_conflicting(foo_staged, patch_dir): with open(foo_staged.foo_filename, 'w') as foo_file: foo_file.write(FOO_CONTENTS.replace('1', 'a')) _test_foo_state(foo_staged, FOO_CONTENTS.replace('1', 'a'), 'AM') with staged_files_only(patch_dir): _test_foo_state(foo_staged) # Modify in the same place as the stashed diff with open(foo_staged.foo_filename, 'w') as foo_file: foo_file.write(FOO_CONTENTS.replace('1', 'b')) <|code_end|> . Use current file imports: (import itertools import os.path import shutil import pytest from pre_commit import git from pre_commit.staged_files_only import staged_files_only from pre_commit.util import cmd_output from testing.auto_namedtuple import auto_namedtuple from testing.fixtures import git_dir from testing.util import cwd from testing.util import get_resource_path from testing.util import git_commit) and context including class names, function names, or small code snippets from other files: # Path: pre_commit/git.py # NO_FS_MONITOR = ('-c', 'core.useBuiltinFSMonitor=false') # def zsplit(s: str) -> list[str]: # def no_git_env( # _env: MutableMapping[str, str] | None = None, # ) -> dict[str, str]: # def get_root() -> str: # def get_git_dir(git_root: str = '.') -> str: # def get_remote_url(git_root: str) -> str: # def is_in_merge_conflict() -> bool: # def parse_merge_msg_for_conflicts(merge_msg: bytes) -> list[str]: # def get_conflicted_files() -> set[str]: # def get_staged_files(cwd: str | None = None) -> list[str]: # def intent_to_add_files() -> list[str]: # def get_all_files() -> list[str]: # def get_changed_files(old: str, new: str) -> list[str]: # def head_rev(remote: str) -> str: # def has_diff(*args: str, repo: str = '.') -> bool: # def has_core_hookpaths_set() -> bool: # def init_repo(path: str, remote: str) -> None: # def commit(repo: str = '.') -> None: # def git_path(name: str, repo: str = '.') -> str: # def check_for_cygwin_mismatch() -> None: # # Path: pre_commit/staged_files_only.py # @contextlib.contextmanager # def staged_files_only(patch_dir: str) -> Generator[None, None, None]: # """Clear any unstaged changes from the git working directory inside this # context. # """ # with _intent_to_add_cleared(), _unstaged_changes_cleared(patch_dir): # yield # # 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/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)) # # Path: testing/fixtures.py # def git_dir(tempdir_factory): # path = tempdir_factory.get() # cmd_output('git', 'init', path) # return path # # 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 get_resource_path(path): # return os.path.join(TESTING_DIR, 'resources', path) # # 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.
_test_foo_state(foo_staged, FOO_CONTENTS.replace('1', 'b'), 'AM')
Next line prediction: <|code_start|> FOO_CONTENTS = '\n'.join(('1', '2', '3', '4', '5', '6', '7', '8', '')) @pytest.fixture def patch_dir(tempdir_factory): return tempdir_factory.get() def get_short_git_status(): git_status = cmd_output('git', 'status', '-s')[1] line_parts = [line.split() for line in git_status.splitlines()] return {v: k for k, v in line_parts} @pytest.fixture def foo_staged(in_git_dir): foo = in_git_dir.join('foo') foo.write(FOO_CONTENTS) cmd_output('git', 'add', 'foo') yield auto_namedtuple(path=in_git_dir.strpath, foo_filename=foo.strpath) def _test_foo_state( path, foo_contents=FOO_CONTENTS, status='A', <|code_end|> . Use current file imports: (import itertools import os.path import shutil import pytest from pre_commit import git from pre_commit.staged_files_only import staged_files_only from pre_commit.util import cmd_output from testing.auto_namedtuple import auto_namedtuple from testing.fixtures import git_dir from testing.util import cwd from testing.util import get_resource_path from testing.util import git_commit) and context including class names, function names, or small code snippets from other files: # Path: pre_commit/git.py # NO_FS_MONITOR = ('-c', 'core.useBuiltinFSMonitor=false') # def zsplit(s: str) -> list[str]: # def no_git_env( # _env: MutableMapping[str, str] | None = None, # ) -> dict[str, str]: # def get_root() -> str: # def get_git_dir(git_root: str = '.') -> str: # def get_remote_url(git_root: str) -> str: # def is_in_merge_conflict() -> bool: # def parse_merge_msg_for_conflicts(merge_msg: bytes) -> list[str]: # def get_conflicted_files() -> set[str]: # def get_staged_files(cwd: str | None = None) -> list[str]: # def intent_to_add_files() -> list[str]: # def get_all_files() -> list[str]: # def get_changed_files(old: str, new: str) -> list[str]: # def head_rev(remote: str) -> str: # def has_diff(*args: str, repo: str = '.') -> bool: # def has_core_hookpaths_set() -> bool: # def init_repo(path: str, remote: str) -> None: # def commit(repo: str = '.') -> None: # def git_path(name: str, repo: str = '.') -> str: # def check_for_cygwin_mismatch() -> None: # # Path: pre_commit/staged_files_only.py # @contextlib.contextmanager # def staged_files_only(patch_dir: str) -> Generator[None, None, None]: # """Clear any unstaged changes from the git working directory inside this # context. # """ # with _intent_to_add_cleared(), _unstaged_changes_cleared(patch_dir): # yield # # 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/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)) # # Path: testing/fixtures.py # def git_dir(tempdir_factory): # path = tempdir_factory.get() # cmd_output('git', 'init', path) # return path # # 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 get_resource_path(path): # return os.path.join(TESTING_DIR, 'resources', path) # # 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.
encoding='UTF-8',
Predict the next line for this snippet: <|code_start|> foo_contents=FOO_CONTENTS, status='A', encoding='UTF-8', ): assert os.path.exists(path.foo_filename) with open(path.foo_filename, encoding=encoding) as f: assert f.read() == foo_contents actual_status = get_short_git_status()['foo'] assert status == actual_status def test_foo_staged(foo_staged): _test_foo_state(foo_staged) def test_foo_nothing_unstaged(foo_staged, patch_dir): with staged_files_only(patch_dir): _test_foo_state(foo_staged) _test_foo_state(foo_staged) def test_foo_something_unstaged(foo_staged, patch_dir): with open(foo_staged.foo_filename, 'w') as foo_file: foo_file.write('herp\nderp\n') _test_foo_state(foo_staged, 'herp\nderp\n', 'AM') with staged_files_only(patch_dir): _test_foo_state(foo_staged) <|code_end|> with the help of current file imports: import itertools import os.path import shutil import pytest from pre_commit import git from pre_commit.staged_files_only import staged_files_only from pre_commit.util import cmd_output from testing.auto_namedtuple import auto_namedtuple from testing.fixtures import git_dir from testing.util import cwd from testing.util import get_resource_path from testing.util import git_commit and context from other files: # Path: pre_commit/git.py # NO_FS_MONITOR = ('-c', 'core.useBuiltinFSMonitor=false') # def zsplit(s: str) -> list[str]: # def no_git_env( # _env: MutableMapping[str, str] | None = None, # ) -> dict[str, str]: # def get_root() -> str: # def get_git_dir(git_root: str = '.') -> str: # def get_remote_url(git_root: str) -> str: # def is_in_merge_conflict() -> bool: # def parse_merge_msg_for_conflicts(merge_msg: bytes) -> list[str]: # def get_conflicted_files() -> set[str]: # def get_staged_files(cwd: str | None = None) -> list[str]: # def intent_to_add_files() -> list[str]: # def get_all_files() -> list[str]: # def get_changed_files(old: str, new: str) -> list[str]: # def head_rev(remote: str) -> str: # def has_diff(*args: str, repo: str = '.') -> bool: # def has_core_hookpaths_set() -> bool: # def init_repo(path: str, remote: str) -> None: # def commit(repo: str = '.') -> None: # def git_path(name: str, repo: str = '.') -> str: # def check_for_cygwin_mismatch() -> None: # # Path: pre_commit/staged_files_only.py # @contextlib.contextmanager # def staged_files_only(patch_dir: str) -> Generator[None, None, None]: # """Clear any unstaged changes from the git working directory inside this # context. # """ # with _intent_to_add_cleared(), _unstaged_changes_cleared(patch_dir): # yield # # 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/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)) # # Path: testing/fixtures.py # def git_dir(tempdir_factory): # path = tempdir_factory.get() # cmd_output('git', 'init', path) # return path # # 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 get_resource_path(path): # return os.path.join(TESTING_DIR, 'resources', path) # # 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.
_test_foo_state(foo_staged, 'herp\nderp\n', 'AM')
Given the following code snippet before the placeholder: <|code_start|> return tempdir_factory.get() def get_short_git_status(): git_status = cmd_output('git', 'status', '-s')[1] line_parts = [line.split() for line in git_status.splitlines()] return {v: k for k, v in line_parts} @pytest.fixture def foo_staged(in_git_dir): foo = in_git_dir.join('foo') foo.write(FOO_CONTENTS) cmd_output('git', 'add', 'foo') yield auto_namedtuple(path=in_git_dir.strpath, foo_filename=foo.strpath) def _test_foo_state( path, foo_contents=FOO_CONTENTS, status='A', encoding='UTF-8', ): assert os.path.exists(path.foo_filename) with open(path.foo_filename, encoding=encoding) as f: assert f.read() == foo_contents actual_status = get_short_git_status()['foo'] assert status == actual_status <|code_end|> , predict the next line using imports from the current file: import itertools import os.path import shutil import pytest from pre_commit import git from pre_commit.staged_files_only import staged_files_only from pre_commit.util import cmd_output from testing.auto_namedtuple import auto_namedtuple from testing.fixtures import git_dir from testing.util import cwd from testing.util import get_resource_path from testing.util import git_commit and context including class names, function names, and sometimes code from other files: # Path: pre_commit/git.py # NO_FS_MONITOR = ('-c', 'core.useBuiltinFSMonitor=false') # def zsplit(s: str) -> list[str]: # def no_git_env( # _env: MutableMapping[str, str] | None = None, # ) -> dict[str, str]: # def get_root() -> str: # def get_git_dir(git_root: str = '.') -> str: # def get_remote_url(git_root: str) -> str: # def is_in_merge_conflict() -> bool: # def parse_merge_msg_for_conflicts(merge_msg: bytes) -> list[str]: # def get_conflicted_files() -> set[str]: # def get_staged_files(cwd: str | None = None) -> list[str]: # def intent_to_add_files() -> list[str]: # def get_all_files() -> list[str]: # def get_changed_files(old: str, new: str) -> list[str]: # def head_rev(remote: str) -> str: # def has_diff(*args: str, repo: str = '.') -> bool: # def has_core_hookpaths_set() -> bool: # def init_repo(path: str, remote: str) -> None: # def commit(repo: str = '.') -> None: # def git_path(name: str, repo: str = '.') -> str: # def check_for_cygwin_mismatch() -> None: # # Path: pre_commit/staged_files_only.py # @contextlib.contextmanager # def staged_files_only(patch_dir: str) -> Generator[None, None, None]: # """Clear any unstaged changes from the git working directory inside this # context. # """ # with _intent_to_add_cleared(), _unstaged_changes_cleared(patch_dir): # yield # # 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/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)) # # Path: testing/fixtures.py # def git_dir(tempdir_factory): # path = tempdir_factory.get() # cmd_output('git', 'init', path) # return path # # 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 get_resource_path(path): # return os.path.join(TESTING_DIR, 'resources', path) # # 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.
def test_foo_staged(foo_staged):
Here is a snippet: <|code_start|>from __future__ import annotations def _test(*, before, patch, expected): env = before.copy() with envcontext(patch, _env=env): assert env == expected assert env == before def test_trivial(): _test(before={}, patch={}, expected={}) def test_noop(): _test(before={'foo': 'bar'}, patch=(), expected={'foo': 'bar'}) def test_adds(): _test(before={}, patch=[('foo', 'bar')], expected={'foo': 'bar'}) def test_overrides(): _test( before={'foo': 'baz'}, <|code_end|> . Write the next line using the current file imports: import os import pytest from unittest import mock from pre_commit.envcontext import envcontext from pre_commit.envcontext import UNSET from pre_commit.envcontext import Var 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 # # Path: pre_commit/envcontext.py # class Var(NamedTuple): # name: str # default: str = '' , which may include functions, classes, or code. Output only the next line.
patch=[('foo', 'bar')],
Given the following code snippet before the placeholder: <|code_start|> _test( before={}, patch=[('PATH', ('~/bin:', Var('PATH')))], expected={'PATH': '~/bin:'}, ) def test_templated_environment_variable_defaults(): _test( before={}, patch=[('PATH', ('~/bin:', Var('PATH', default='/bin')))], expected={'PATH': '~/bin:/bin'}, ) def test_templated_environment_variable_there(): _test( before={'PATH': '/usr/local/bin:/usr/bin'}, patch=[('PATH', ('~/bin:', Var('PATH')))], expected={'PATH': '~/bin:/usr/local/bin:/usr/bin'}, ) def test_templated_environ_sources_from_previous(): _test( before={'foo': 'bar'}, patch=( ('foo', 'baz'), ('herp', ('foo: ', Var('foo'))), ), <|code_end|> , predict the next line using imports from the current file: import os import pytest from unittest import mock from pre_commit.envcontext import envcontext from pre_commit.envcontext import UNSET from pre_commit.envcontext import Var 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 # # Path: pre_commit/envcontext.py # class Var(NamedTuple): # name: str # default: str = '' . Output only the next line.
expected={'foo': 'baz', 'herp': 'foo: bar'},
Given the code snippet: <|code_start|> expected={'PATH': '~/bin:/usr/local/bin:/usr/bin'}, ) def test_templated_environ_sources_from_previous(): _test( before={'foo': 'bar'}, patch=( ('foo', 'baz'), ('herp', ('foo: ', Var('foo'))), ), expected={'foo': 'baz', 'herp': 'foo: bar'}, ) def test_exception_safety(): class MyError(RuntimeError): pass env = {'hello': 'world'} with pytest.raises(MyError): with envcontext((('foo', 'bar'),), _env=env): raise MyError() assert env == {'hello': 'world'} def test_integration_os_environ(): with mock.patch.dict(os.environ, {'FOO': 'bar'}, clear=True): assert os.environ == {'FOO': 'bar'} with envcontext((('HERP', 'derp'),)): <|code_end|> , generate the next line using the imports in this file: import os import pytest from unittest import mock from pre_commit.envcontext import envcontext from pre_commit.envcontext import UNSET from pre_commit.envcontext import Var and context (functions, classes, or occasionally 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 # # Path: pre_commit/envcontext.py # class Var(NamedTuple): # name: str # default: str = '' . Output only the next line.
assert os.environ == {'FOO': 'bar', 'HERP': 'derp'}
Based on the snippet: <|code_start|>from __future__ import annotations @pytest.mark.parametrize( ('ctx', 'expected'), ( pytest.param( ( ('PRE_COMMIT_USE_MICROMAMBA', envcontext.UNSET), ('PRE_COMMIT_USE_MAMBA', envcontext.UNSET), ), 'conda', id='default', <|code_end|> , predict the immediate next line with the help of imports: import pytest from pre_commit import envcontext from pre_commit.languages.conda import _conda_exe 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/languages/conda.py # def _conda_exe() -> str: # if os.environ.get('PRE_COMMIT_USE_MICROMAMBA'): # return 'micromamba' # elif os.environ.get('PRE_COMMIT_USE_MAMBA'): # return 'mamba' # else: # return 'conda' . Output only the next line.
),
Given the code snippet: <|code_start|>from __future__ import annotations @pytest.mark.parametrize( ('ctx', 'expected'), ( pytest.param( ( ('PRE_COMMIT_USE_MICROMAMBA', envcontext.UNSET), ('PRE_COMMIT_USE_MAMBA', envcontext.UNSET), ), 'conda', id='default', ), pytest.param( ( ('PRE_COMMIT_USE_MICROMAMBA', '1'), ('PRE_COMMIT_USE_MAMBA', ''), ), 'micromamba', id='default', ), pytest.param( <|code_end|> , generate the next line using the imports in this file: import pytest from pre_commit import envcontext from pre_commit.languages.conda import _conda_exe and context (functions, classes, or occasionally 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/languages/conda.py # def _conda_exe() -> str: # if os.environ.get('PRE_COMMIT_USE_MICROMAMBA'): # return 'micromamba' # elif os.environ.get('PRE_COMMIT_USE_MAMBA'): # return 'mamba' # else: # return 'conda' . Output only the next line.
(
Next line prediction: <|code_start|>from __future__ import annotations ENVIRONMENT_DIR = 'dotnetenv' BIN_DIR = 'bin' get_default_version = helpers.basic_get_default_version healthy = helpers.basic_healthy def get_env_patch(venv: str) -> PatchesT: return ( ('PATH', (os.path.join(venv, BIN_DIR), os.pathsep, Var('PATH'))), ) <|code_end|> . Use current file imports: (import contextlib import os.path import pre_commit.constants as C 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, or small code snippets 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.
@contextlib.contextmanager
Given the code snippet: <|code_start|>from __future__ import annotations ENVIRONMENT_DIR = 'dotnetenv' BIN_DIR = 'bin' get_default_version = helpers.basic_get_default_version healthy = helpers.basic_healthy def get_env_patch(venv: str) -> PatchesT: return ( ('PATH', (os.path.join(venv, BIN_DIR), os.pathsep, Var('PATH'))), ) <|code_end|> , generate the next line using the imports in this file: import contextlib import os.path import pre_commit.constants as C 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 (functions, classes, or occasionally 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.
@contextlib.contextmanager
Next line prediction: <|code_start|>from __future__ import annotations @pytest.mark.parametrize( ('url', 'expected'), ( ('/im/a/path/on/disk', 'unknown_src_dir'), ('file:///im/a/path/on/disk', 'unknown_src_dir'), ('git@github.com:golang/lint', 'github.com/golang/lint'), ('git://github.com/golang/lint', 'github.com/golang/lint'), ('http://github.com/golang/lint', 'github.com/golang/lint'), ('https://github.com/golang/lint', 'github.com/golang/lint'), <|code_end|> . Use current file imports: (import pytest from pre_commit.languages.golang import guess_go_dir) and context including class names, function names, or small code snippets from other files: # Path: pre_commit/languages/golang.py # def guess_go_dir(remote_url: str) -> str: # if remote_url.endswith('.git'): # remote_url = remote_url[:-1 * len('.git')] # looks_like_url = ( # not remote_url.startswith('file://') and # ('//' in remote_url or '@' in remote_url) # ) # remote_url = remote_url.replace(':', '/') # if looks_like_url: # _, _, remote_url = remote_url.rpartition('//') # _, _, remote_url = remote_url.rpartition('@') # return remote_url # else: # return 'unknown_src_dir' . Output only the next line.
('ssh://git@github.com/golang/lint', 'github.com/golang/lint'),
Here is a snippet: <|code_start|>from __future__ import annotations def test_read_pyvenv_cfg(tmpdir): pyvenv_cfg = tmpdir.join('pyvenv.cfg') pyvenv_cfg.write( '# I am a comment\n' '\n' 'foo = bar\n' 'version-info=123\n', ) <|code_end|> . Write the next line using the current file imports: import os.path import sys import pytest import pre_commit.constants as C from unittest import mock from pre_commit.envcontext import envcontext from pre_commit.languages import python from pre_commit.prefix import Prefix from pre_commit.util import make_executable from pre_commit.util import win_exe 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/languages/python.py # ENVIRONMENT_DIR = 'py_env' # def _version_info(exe: str) -> str: # def _read_pyvenv_cfg(filename: str) -> dict[str, str]: # def bin_dir(venv: str) -> str: # def get_env_patch(venv: str) -> PatchesT: # def _find_by_py_launcher( # version: str, # ) -> str | None: # pragma: no cover (windows only) # def _find_by_sys_executable() -> str | None: # def _norm(path: str) -> str | None: # def get_default_version() -> str: # pragma: no cover (platform dependent) # def _sys_executable_matches(version: str) -> bool: # def norm_version(version: str) -> str | None: # 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 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) # # Path: pre_commit/util.py # def win_exe(s: str) -> str: # return s if sys.platform != 'win32' else f'{s}.exe' , which may include functions, classes, or code. Output only the next line.
expected = {'foo': 'bar', 'version-info': '123'}
Next line prediction: <|code_start|> expected_path = fr'{home}\python343' else: # pragma: nt no cover path = '~/.pyenv/versions/3.4.3/bin/python' expected_path = f'{home}/.pyenv/versions/3.4.3/bin/python' result = python.norm_version(path) assert result == expected_path def test_norm_version_of_default_is_sys_executable(): assert python.norm_version('default') is None @pytest.mark.parametrize('v', ('python3.9', 'python3', 'python')) def test_sys_executable_matches(v): with mock.patch.object(sys, 'version_info', (3, 9, 10)): assert python._sys_executable_matches(v) assert python.norm_version(v) is None @pytest.mark.parametrize('v', ('notpython', 'python3.x')) def test_sys_executable_matches_does_not_match(v): with mock.patch.object(sys, 'version_info', (3, 9, 10)): assert not python._sys_executable_matches(v) @pytest.mark.parametrize( ('exe', 'realpath', 'expected'), ( ('/usr/bin/python3', '/usr/bin/python3.7', 'python3'), ('/usr/bin/python', '/usr/bin/python3.7', 'python3.7'), ('/usr/bin/python', '/usr/bin/python', None), <|code_end|> . Use current file imports: (import os.path import sys import pytest import pre_commit.constants as C from unittest import mock from pre_commit.envcontext import envcontext from pre_commit.languages import python from pre_commit.prefix import Prefix from pre_commit.util import make_executable from pre_commit.util import win_exe) and context including class names, function names, or small code snippets 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/languages/python.py # ENVIRONMENT_DIR = 'py_env' # def _version_info(exe: str) -> str: # def _read_pyvenv_cfg(filename: str) -> dict[str, str]: # def bin_dir(venv: str) -> str: # def get_env_patch(venv: str) -> PatchesT: # def _find_by_py_launcher( # version: str, # ) -> str | None: # pragma: no cover (windows only) # def _find_by_sys_executable() -> str | None: # def _norm(path: str) -> str | None: # def get_default_version() -> str: # pragma: no cover (platform dependent) # def _sys_executable_matches(version: str) -> bool: # def norm_version(version: str) -> str | None: # 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 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) # # Path: pre_commit/util.py # def win_exe(s: str) -> str: # return s if sys.platform != 'win32' else f'{s}.exe' . Output only the next line.
('/usr/bin/python3.7m', '/usr/bin/python3.7m', 'python3.7m'),
Next line prediction: <|code_start|>) def test_find_by_sys_executable(exe, realpath, expected): with mock.patch.object(sys, 'executable', exe): with mock.patch.object(os.path, 'realpath', return_value=realpath): with mock.patch.object(python, 'find_executable', lambda x: x): assert python._find_by_sys_executable() == expected @pytest.fixture def python_dir(tmpdir): with tmpdir.as_cwd(): prefix = tmpdir.join('prefix').ensure_dir() prefix.join('setup.py').write('import setuptools; setuptools.setup()') prefix = Prefix(str(prefix)) yield prefix, tmpdir def test_healthy_default_creator(python_dir): prefix, tmpdir = python_dir python.install_environment(prefix, C.DEFAULT, ()) # should be healthy right after creation assert python.healthy(prefix, C.DEFAULT) is True # even if a `types.py` file exists, should still be healthy tmpdir.join('types.py').ensure() assert python.healthy(prefix, C.DEFAULT) is True <|code_end|> . Use current file imports: (import os.path import sys import pytest import pre_commit.constants as C from unittest import mock from pre_commit.envcontext import envcontext from pre_commit.languages import python from pre_commit.prefix import Prefix from pre_commit.util import make_executable from pre_commit.util import win_exe) and context including class names, function names, or small code snippets 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/languages/python.py # ENVIRONMENT_DIR = 'py_env' # def _version_info(exe: str) -> str: # def _read_pyvenv_cfg(filename: str) -> dict[str, str]: # def bin_dir(venv: str) -> str: # def get_env_patch(venv: str) -> PatchesT: # def _find_by_py_launcher( # version: str, # ) -> str | None: # pragma: no cover (windows only) # def _find_by_sys_executable() -> str | None: # def _norm(path: str) -> str | None: # def get_default_version() -> str: # pragma: no cover (platform dependent) # def _sys_executable_matches(version: str) -> bool: # def norm_version(version: str) -> str | None: # 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 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) # # Path: pre_commit/util.py # def win_exe(s: str) -> str: # return s if sys.platform != 'win32' else f'{s}.exe' . Output only the next line.
def test_healthy_venv_creator(python_dir):
Given snippet: <|code_start|> pyvenv_cfg = tmpdir.join('pyvenv.cfg') pyvenv_cfg.write( '# I am a comment\n' '\n' 'foo = bar\n' 'version-info=123\n', ) expected = {'foo': 'bar', 'version-info': '123'} assert python._read_pyvenv_cfg(pyvenv_cfg) == expected def test_read_pyvenv_cfg_non_utf8(tmpdir): pyvenv_cfg = tmpdir.join('pyvenv_cfg') pyvenv_cfg.write_binary('hello = hello john.š\n'.encode()) expected = {'hello': 'hello john.š'} assert python._read_pyvenv_cfg(pyvenv_cfg) == expected def test_norm_version_expanduser(): home = os.path.expanduser('~') if os.name == 'nt': # pragma: nt cover path = r'~\python343' expected_path = fr'{home}\python343' else: # pragma: nt no cover path = '~/.pyenv/versions/3.4.3/bin/python' expected_path = f'{home}/.pyenv/versions/3.4.3/bin/python' result = python.norm_version(path) assert result == expected_path <|code_end|> , continue by predicting the next line. Consider current file imports: import os.path import sys import pytest import pre_commit.constants as C from unittest import mock from pre_commit.envcontext import envcontext from pre_commit.languages import python from pre_commit.prefix import Prefix from pre_commit.util import make_executable from pre_commit.util import win_exe and context: # 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/languages/python.py # ENVIRONMENT_DIR = 'py_env' # def _version_info(exe: str) -> str: # def _read_pyvenv_cfg(filename: str) -> dict[str, str]: # def bin_dir(venv: str) -> str: # def get_env_patch(venv: str) -> PatchesT: # def _find_by_py_launcher( # version: str, # ) -> str | None: # pragma: no cover (windows only) # def _find_by_sys_executable() -> str | None: # def _norm(path: str) -> str | None: # def get_default_version() -> str: # pragma: no cover (platform dependent) # def _sys_executable_matches(version: str) -> bool: # def norm_version(version: str) -> str | None: # 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 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) # # Path: pre_commit/util.py # def win_exe(s: str) -> str: # return s if sys.platform != 'win32' else f'{s}.exe' which might include code, classes, or functions. Output only the next line.
def test_norm_version_of_default_is_sys_executable():
Given snippet: <|code_start|> hook_id = 'parse-file-no-opts-args' expected_args = ['--no-cache'] _test_r_parsing( tempdir_factory, store, hook_id, expected_args=expected_args, ) def test_r_parsing_expr_no_opts_no_args1(tempdir_factory, store): hook_id = 'parse-expr-no-opts-no-args-1' _test_r_parsing( tempdir_factory, store, hook_id, expected_hook_expr=('-e', '1+1'), ) def test_r_parsing_expr_no_opts_no_args2(tempdir_factory, store): with pytest.raises(ValueError) as execinfo: r._entry_validate(['Rscript', '-e', '1+1', '-e', 'letters']) msg = execinfo.value.args assert msg == ('You can supply at most one expression.',) def test_r_parsing_expr_opts_no_args2(tempdir_factory, store): with pytest.raises(ValueError) as execinfo: r._entry_validate( [ 'Rscript', '--vanilla', '-e', '1+1', '-e', 'letters', ], ) msg = execinfo.value.args assert msg == ( <|code_end|> , continue by predicting the next line. Consider current file imports: import os.path import pytest from pre_commit.languages import r from testing.fixtures import make_config_from_repo from testing.fixtures import make_repo from tests.repository_test import _get_hook_no_install and context: # Path: pre_commit/languages/r.py # ENVIRONMENT_DIR = 'renv' # RSCRIPT_OPTS = ('--no-save', '--no-restore', '--no-site-file', '--no-environ') # def get_env_patch(venv: str) -> PatchesT: # def in_env( # prefix: Prefix, # language_version: str, # ) -> Generator[None, None, None]: # def _get_env_dir(prefix: Prefix, version: str) -> str: # def _prefix_if_non_local_file_entry( # entry: Sequence[str], # prefix: Prefix, # src: str, # ) -> Sequence[str]: # def _rscript_exec() -> str: # def _entry_validate(entry: Sequence[str]) -> None: # def _cmd_from_hook(hook: Hook) -> tuple[str, ...]: # def install_environment( # prefix: Prefix, # version: str, # additional_dependencies: Sequence[str], # ) -> None: # def _inline_r_setup(code: str) -> str: # def run_hook( # hook: Hook, # file_args: Sequence[str], # color: bool, # ) -> tuple[int, bytes]: # # Path: testing/fixtures.py # def make_config_from_repo(repo_path, rev=None, hooks=None, check=True): # manifest = load_manifest(os.path.join(repo_path, C.MANIFEST_FILE)) # config = { # 'repo': f'file://{repo_path}', # 'rev': rev or git.head_rev(repo_path), # 'hooks': hooks or [{'id': hook['id']} for hook in manifest], # } # # if check: # wrapped = validate({'repos': [config]}, CONFIG_SCHEMA) # wrapped = apply_defaults(wrapped, CONFIG_SCHEMA) # config, = wrapped['repos'] # return config # else: # return config # # Path: testing/fixtures.py # def make_repo(tempdir_factory, repo_source): # path = git_dir(tempdir_factory) # copy_tree_to_path(get_resource_path(repo_source), path) # cmd_output('git', 'add', '.', cwd=path) # git_commit(msg=make_repo.__name__, cwd=path) # return path # # Path: tests/repository_test.py # def _get_hook_no_install(repo_config, store, hook_id): # config = {'repos': [repo_config]} # config = cfgv.validate(config, CONFIG_SCHEMA) # config = cfgv.apply_defaults(config, CONFIG_SCHEMA) # hooks = all_hooks(config, store) # hook, = (hook for hook in hooks if hook.id == hook_id) # return hook which might include code, classes, or functions. Output only the next line.
'The only valid syntax is `Rscript -e {expr}`',
Given the code snippet: <|code_start|>from __future__ import annotations def _test_r_parsing( tempdir_factory, store, hook_id, expected_hook_expr={}, expected_args={}, config={}, expect_path_prefix=True, ): repo_path = 'r_hooks_repo' path = make_repo(tempdir_factory, repo_path) config = config or make_config_from_repo(path) hook = _get_hook_no_install(config, store, hook_id) ret = r._cmd_from_hook(hook) expected_cmd = 'Rscript' expected_opts = ( '--no-save', '--no-restore', '--no-site-file', '--no-environ', ) expected_path = os.path.join( hook.prefix.prefix_dir if expect_path_prefix else '', f'{hook_id}.R', ) expected = ( <|code_end|> , generate the next line using the imports in this file: import os.path import pytest from pre_commit.languages import r from testing.fixtures import make_config_from_repo from testing.fixtures import make_repo from tests.repository_test import _get_hook_no_install and context (functions, classes, or occasionally code) from other files: # Path: pre_commit/languages/r.py # ENVIRONMENT_DIR = 'renv' # RSCRIPT_OPTS = ('--no-save', '--no-restore', '--no-site-file', '--no-environ') # def get_env_patch(venv: str) -> PatchesT: # def in_env( # prefix: Prefix, # language_version: str, # ) -> Generator[None, None, None]: # def _get_env_dir(prefix: Prefix, version: str) -> str: # def _prefix_if_non_local_file_entry( # entry: Sequence[str], # prefix: Prefix, # src: str, # ) -> Sequence[str]: # def _rscript_exec() -> str: # def _entry_validate(entry: Sequence[str]) -> None: # def _cmd_from_hook(hook: Hook) -> tuple[str, ...]: # def install_environment( # prefix: Prefix, # version: str, # additional_dependencies: Sequence[str], # ) -> None: # def _inline_r_setup(code: str) -> str: # def run_hook( # hook: Hook, # file_args: Sequence[str], # color: bool, # ) -> tuple[int, bytes]: # # Path: testing/fixtures.py # def make_config_from_repo(repo_path, rev=None, hooks=None, check=True): # manifest = load_manifest(os.path.join(repo_path, C.MANIFEST_FILE)) # config = { # 'repo': f'file://{repo_path}', # 'rev': rev or git.head_rev(repo_path), # 'hooks': hooks or [{'id': hook['id']} for hook in manifest], # } # # if check: # wrapped = validate({'repos': [config]}, CONFIG_SCHEMA) # wrapped = apply_defaults(wrapped, CONFIG_SCHEMA) # config, = wrapped['repos'] # return config # else: # return config # # Path: testing/fixtures.py # def make_repo(tempdir_factory, repo_source): # path = git_dir(tempdir_factory) # copy_tree_to_path(get_resource_path(repo_source), path) # cmd_output('git', 'add', '.', cwd=path) # git_commit(msg=make_repo.__name__, cwd=path) # return path # # Path: tests/repository_test.py # def _get_hook_no_install(repo_config, store, hook_id): # config = {'repos': [repo_config]} # config = cfgv.validate(config, CONFIG_SCHEMA) # config = cfgv.apply_defaults(config, CONFIG_SCHEMA) # hooks = all_hooks(config, store) # hook, = (hook for hook in hooks if hook.id == hook_id) # return hook . Output only the next line.
expected_cmd,
Predict the next line after this snippet: <|code_start|> def test_r_parsing_expr_args_in_entry2(tempdir_factory, store): with pytest.raises(ValueError) as execinfo: r._entry_validate(['Rscript', '-e', 'expr1', '--another-arg']) msg = execinfo.value.args assert msg == ('You can supply at most one expression.',) def test_r_parsing_expr_non_Rscirpt(tempdir_factory, store): with pytest.raises(ValueError) as execinfo: r._entry_validate(['AnotherScript', '-e', '{{}}']) msg = execinfo.value.args assert msg == ('entry must start with `Rscript`.',) def test_r_parsing_file_local(tempdir_factory, store): path = 'path/to/script.R' hook_id = 'local-r' config = { 'repo': 'local', 'hooks': [{ 'id': hook_id, 'name': 'local-r', 'entry': f'Rscript {path}', 'language': 'r', }], } <|code_end|> using the current file's imports: import os.path import pytest from pre_commit.languages import r from testing.fixtures import make_config_from_repo from testing.fixtures import make_repo from tests.repository_test import _get_hook_no_install and any relevant context from other files: # Path: pre_commit/languages/r.py # ENVIRONMENT_DIR = 'renv' # RSCRIPT_OPTS = ('--no-save', '--no-restore', '--no-site-file', '--no-environ') # def get_env_patch(venv: str) -> PatchesT: # def in_env( # prefix: Prefix, # language_version: str, # ) -> Generator[None, None, None]: # def _get_env_dir(prefix: Prefix, version: str) -> str: # def _prefix_if_non_local_file_entry( # entry: Sequence[str], # prefix: Prefix, # src: str, # ) -> Sequence[str]: # def _rscript_exec() -> str: # def _entry_validate(entry: Sequence[str]) -> None: # def _cmd_from_hook(hook: Hook) -> tuple[str, ...]: # def install_environment( # prefix: Prefix, # version: str, # additional_dependencies: Sequence[str], # ) -> None: # def _inline_r_setup(code: str) -> str: # def run_hook( # hook: Hook, # file_args: Sequence[str], # color: bool, # ) -> tuple[int, bytes]: # # Path: testing/fixtures.py # def make_config_from_repo(repo_path, rev=None, hooks=None, check=True): # manifest = load_manifest(os.path.join(repo_path, C.MANIFEST_FILE)) # config = { # 'repo': f'file://{repo_path}', # 'rev': rev or git.head_rev(repo_path), # 'hooks': hooks or [{'id': hook['id']} for hook in manifest], # } # # if check: # wrapped = validate({'repos': [config]}, CONFIG_SCHEMA) # wrapped = apply_defaults(wrapped, CONFIG_SCHEMA) # config, = wrapped['repos'] # return config # else: # return config # # Path: testing/fixtures.py # def make_repo(tempdir_factory, repo_source): # path = git_dir(tempdir_factory) # copy_tree_to_path(get_resource_path(repo_source), path) # cmd_output('git', 'add', '.', cwd=path) # git_commit(msg=make_repo.__name__, cwd=path) # return path # # Path: tests/repository_test.py # def _get_hook_no_install(repo_config, store, hook_id): # config = {'repos': [repo_config]} # config = cfgv.validate(config, CONFIG_SCHEMA) # config = cfgv.apply_defaults(config, CONFIG_SCHEMA) # hooks = all_hooks(config, store) # hook, = (hook for hook in hooks if hook.id == hook_id) # return hook . Output only the next line.
_test_r_parsing(
Predict the next line after this snippet: <|code_start|> assert ret == expected def test_r_parsing_file_no_opts_no_args(tempdir_factory, store): hook_id = 'parse-file-no-opts-no-args' _test_r_parsing(tempdir_factory, store, hook_id) def test_r_parsing_file_opts_no_args(tempdir_factory, store): with pytest.raises(ValueError) as excinfo: r._entry_validate(['Rscript', '--no-init', '/path/to/file']) msg = excinfo.value.args assert msg == ( 'The only valid syntax is `Rscript -e {expr}`', 'or `Rscript path/to/hook/script`', ) def test_r_parsing_file_no_opts_args(tempdir_factory, store): hook_id = 'parse-file-no-opts-args' expected_args = ['--no-cache'] _test_r_parsing( tempdir_factory, store, hook_id, expected_args=expected_args, ) def test_r_parsing_expr_no_opts_no_args1(tempdir_factory, store): hook_id = 'parse-expr-no-opts-no-args-1' _test_r_parsing( <|code_end|> using the current file's imports: import os.path import pytest from pre_commit.languages import r from testing.fixtures import make_config_from_repo from testing.fixtures import make_repo from tests.repository_test import _get_hook_no_install and any relevant context from other files: # Path: pre_commit/languages/r.py # ENVIRONMENT_DIR = 'renv' # RSCRIPT_OPTS = ('--no-save', '--no-restore', '--no-site-file', '--no-environ') # def get_env_patch(venv: str) -> PatchesT: # def in_env( # prefix: Prefix, # language_version: str, # ) -> Generator[None, None, None]: # def _get_env_dir(prefix: Prefix, version: str) -> str: # def _prefix_if_non_local_file_entry( # entry: Sequence[str], # prefix: Prefix, # src: str, # ) -> Sequence[str]: # def _rscript_exec() -> str: # def _entry_validate(entry: Sequence[str]) -> None: # def _cmd_from_hook(hook: Hook) -> tuple[str, ...]: # def install_environment( # prefix: Prefix, # version: str, # additional_dependencies: Sequence[str], # ) -> None: # def _inline_r_setup(code: str) -> str: # def run_hook( # hook: Hook, # file_args: Sequence[str], # color: bool, # ) -> tuple[int, bytes]: # # Path: testing/fixtures.py # def make_config_from_repo(repo_path, rev=None, hooks=None, check=True): # manifest = load_manifest(os.path.join(repo_path, C.MANIFEST_FILE)) # config = { # 'repo': f'file://{repo_path}', # 'rev': rev or git.head_rev(repo_path), # 'hooks': hooks or [{'id': hook['id']} for hook in manifest], # } # # if check: # wrapped = validate({'repos': [config]}, CONFIG_SCHEMA) # wrapped = apply_defaults(wrapped, CONFIG_SCHEMA) # config, = wrapped['repos'] # return config # else: # return config # # Path: testing/fixtures.py # def make_repo(tempdir_factory, repo_source): # path = git_dir(tempdir_factory) # copy_tree_to_path(get_resource_path(repo_source), path) # cmd_output('git', 'add', '.', cwd=path) # git_commit(msg=make_repo.__name__, cwd=path) # return path # # Path: tests/repository_test.py # def _get_hook_no_install(repo_config, store, hook_id): # config = {'repos': [repo_config]} # config = cfgv.validate(config, CONFIG_SCHEMA) # config = cfgv.apply_defaults(config, CONFIG_SCHEMA) # hooks = all_hooks(config, store) # hook, = (hook for hook in hooks if hook.id == hook_id) # return hook . Output only the next line.
tempdir_factory, store, hook_id, expected_hook_expr=('-e', '1+1'),
Next line prediction: <|code_start|>from __future__ import annotations Loader = getattr(yaml, 'CSafeLoader', yaml.SafeLoader) yaml_load = functools.partial(yaml.load, Loader=Loader) Dumper = getattr(yaml, 'CSafeDumper', yaml.SafeDumper) def yaml_dump(o: Any, **kwargs: Any) -> str: # when python/mypy#1484 is solved, this can be `functools.partial` return yaml.dump( o, Dumper=Dumper, default_flow_style=False, indent=4, sort_keys=False, **kwargs, ) def force_bytes(exc: Any) -> bytes: with contextlib.suppress(TypeError): return bytes(exc) with contextlib.suppress(Exception): return str(exc).encode() <|code_end|> . Use current file imports: (import contextlib import errno import functools import importlib.resources import os.path import shutil import stat import subprocess import sys import tempfile import yaml import termios from types import TracebackType from typing import Any from typing import Callable from typing import Generator from typing import IO from pre_commit import parse_shebang from os import openpty) and context including class names, function names, or small code snippets 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, ...]: . Output only the next line.
return f'<unprintable {type(exc).__name__} object>'.encode()
Given the code snippet: <|code_start|>from __future__ import annotations def norm_slash(*args): return tuple(x.replace('/', os.sep) for x in args) @pytest.mark.parametrize( ('prefix', 'path_end', 'expected_output'), ( norm_slash('foo', '', 'foo'), <|code_end|> , generate the next line using the imports in this file: import os.path import pytest from pre_commit.prefix import Prefix and context (functions, classes, or occasionally code) 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)) . Output only the next line.
norm_slash('foo', 'bar', 'foo/bar'),
Next line prediction: <|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]: out = f'{hook.entry}\n\n'.encode() <|code_end|> . Use current file imports: (from typing import Sequence from pre_commit.hook import Hook from pre_commit.languages import helpers) and context including class names, function names, or small code snippets 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.
out += b'\n'.join(f.encode() for f in file_args) + b'\n'
Next line prediction: <|code_start|>from __future__ import annotations @pytest.mark.parametrize( ('in_text', 'in_color', 'in_use_color', 'expected'), ( ('foo', GREEN, True, f'{GREEN}foo\033[m'), ('foo', GREEN, False, 'foo'), ), ) def test_format_color(in_text, in_color, in_use_color, expected): ret = format_color(in_text, in_color, in_use_color) assert ret == expected def test_use_color_never(): assert use_color('never') is False def test_use_color_always(): assert use_color('always') is True <|code_end|> . Use current file imports: (import sys import pytest from unittest import mock from pre_commit import envcontext from pre_commit.color import format_color from pre_commit.color import GREEN from pre_commit.color import use_color) and context including class names, function names, or small code snippets 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/color.py # def format_color(text: str, color: str, use_color_setting: bool) -> str: # """Format text with color. # # Args: # text - Text to be formatted with color if `use_color` # color - The color start string # use_color_setting - Whether or not to color # """ # if use_color_setting: # return f'{color}{text}{NORMAL}' # else: # return text # # Path: pre_commit/color.py # GREEN = '\033[42m' # # Path: pre_commit/color.py # def use_color(setting: str) -> bool: # """Choose whether to use color based on the command argument. # # Args: # setting - Either `auto`, `always`, or `never` # """ # if setting not in COLOR_CHOICES: # raise ValueError(setting) # # return ( # setting == 'always' or ( # setting == 'auto' and # sys.stderr.isatty() and # terminal_supports_color and # os.getenv('TERM') != 'dumb' # ) # ) . Output only the next line.
def test_use_color_no_tty():
Given the code snippet: <|code_start|>from __future__ import annotations @pytest.mark.parametrize( ('in_text', 'in_color', 'in_use_color', 'expected'), ( ('foo', GREEN, True, f'{GREEN}foo\033[m'), ('foo', GREEN, False, 'foo'), <|code_end|> , generate the next line using the imports in this file: import sys import pytest from unittest import mock from pre_commit import envcontext from pre_commit.color import format_color from pre_commit.color import GREEN from pre_commit.color import use_color and context (functions, classes, or occasionally 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/color.py # def format_color(text: str, color: str, use_color_setting: bool) -> str: # """Format text with color. # # Args: # text - Text to be formatted with color if `use_color` # color - The color start string # use_color_setting - Whether or not to color # """ # if use_color_setting: # return f'{color}{text}{NORMAL}' # else: # return text # # Path: pre_commit/color.py # GREEN = '\033[42m' # # Path: pre_commit/color.py # def use_color(setting: str) -> bool: # """Choose whether to use color based on the command argument. # # Args: # setting - Either `auto`, `always`, or `never` # """ # if setting not in COLOR_CHOICES: # raise ValueError(setting) # # return ( # setting == 'always' or ( # setting == 'auto' and # sys.stderr.isatty() and # terminal_supports_color and # os.getenv('TERM') != 'dumb' # ) # ) . Output only the next line.
),
Given snippet: <|code_start|> assert ret == expected def test_use_color_never(): assert use_color('never') is False def test_use_color_always(): assert use_color('always') is True def test_use_color_no_tty(): with mock.patch.object(sys.stderr, 'isatty', return_value=False): assert use_color('auto') is False def test_use_color_tty_with_color_support(): with mock.patch.object(sys.stderr, 'isatty', return_value=True): with mock.patch('pre_commit.color.terminal_supports_color', True): with envcontext.envcontext((('TERM', envcontext.UNSET),)): assert use_color('auto') is True def test_use_color_tty_without_color_support(): with mock.patch.object(sys.stderr, 'isatty', return_value=True): with mock.patch('pre_commit.color.terminal_supports_color', False): with envcontext.envcontext((('TERM', envcontext.UNSET),)): assert use_color('auto') is False <|code_end|> , continue by predicting the next line. Consider current file imports: import sys import pytest from unittest import mock from pre_commit import envcontext from pre_commit.color import format_color from pre_commit.color import GREEN from pre_commit.color import use_color and context: # 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/color.py # def format_color(text: str, color: str, use_color_setting: bool) -> str: # """Format text with color. # # Args: # text - Text to be formatted with color if `use_color` # color - The color start string # use_color_setting - Whether or not to color # """ # if use_color_setting: # return f'{color}{text}{NORMAL}' # else: # return text # # Path: pre_commit/color.py # GREEN = '\033[42m' # # Path: pre_commit/color.py # def use_color(setting: str) -> bool: # """Choose whether to use color based on the command argument. # # Args: # setting - Either `auto`, `always`, or `never` # """ # if setting not in COLOR_CHOICES: # raise ValueError(setting) # # return ( # setting == 'always' or ( # setting == 'auto' and # sys.stderr.isatty() and # terminal_supports_color and # os.getenv('TERM') != 'dumb' # ) # ) which might include code, classes, or functions. Output only the next line.
def test_use_color_dumb_term():
Given the code snippet: <|code_start|>from __future__ import annotations @pytest.mark.parametrize( ('in_text', 'in_color', 'in_use_color', 'expected'), ( ('foo', GREEN, True, f'{GREEN}foo\033[m'), ('foo', GREEN, False, 'foo'), ), ) def test_format_color(in_text, in_color, in_use_color, expected): ret = format_color(in_text, in_color, in_use_color) assert ret == expected def test_use_color_never(): assert use_color('never') is False def test_use_color_always(): assert use_color('always') is True def test_use_color_no_tty(): with mock.patch.object(sys.stderr, 'isatty', return_value=False): assert use_color('auto') is False <|code_end|> , generate the next line using the imports in this file: import sys import pytest from unittest import mock from pre_commit import envcontext from pre_commit.color import format_color from pre_commit.color import GREEN from pre_commit.color import use_color and context (functions, classes, or occasionally 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/color.py # def format_color(text: str, color: str, use_color_setting: bool) -> str: # """Format text with color. # # Args: # text - Text to be formatted with color if `use_color` # color - The color start string # use_color_setting - Whether or not to color # """ # if use_color_setting: # return f'{color}{text}{NORMAL}' # else: # return text # # Path: pre_commit/color.py # GREEN = '\033[42m' # # Path: pre_commit/color.py # def use_color(setting: str) -> bool: # """Choose whether to use color based on the command argument. # # Args: # setting - Either `auto`, `always`, or `never` # """ # if setting not in COLOR_CHOICES: # raise ValueError(setting) # # return ( # setting == 'always' or ( # setting == 'auto' and # sys.stderr.isatty() and # terminal_supports_color and # os.getenv('TERM') != 'dumb' # ) # ) . Output only the next line.
def test_use_color_tty_with_color_support():
Based on the snippet: <|code_start|>from __future__ import annotations def _log_record(message, level): return logging.LogRecord('name', level, '', 1, message, {}, None) def test_logging_handler_color(cap_out): handler = LoggingHandler(True) <|code_end|> , predict the immediate next line with the help of imports: import logging from pre_commit import color from pre_commit.logging_handler import LoggingHandler and context (classes, functions, sometimes code) from other files: # Path: pre_commit/color.py # def _enable() -> None: # def bool_errcheck(result, func, args): # def format_color(text: str, color: str, use_color_setting: bool) -> str: # def use_color(setting: str) -> bool: # def add_color_option(parser: argparse.ArgumentParser) -> None: # STD_ERROR_HANDLE = -12 # ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4 # RED = '\033[41m' # GREEN = '\033[42m' # YELLOW = '\033[43;30m' # TURQUOISE = '\033[46;30m' # SUBTLE = '\033[2m' # NORMAL = '\033[m' # COLOR_CHOICES = ('auto', 'always', 'never') # # Path: pre_commit/logging_handler.py # class LoggingHandler(logging.Handler): # def __init__(self, use_color: bool) -> None: # super().__init__() # self.use_color = use_color # # def emit(self, record: logging.LogRecord) -> None: # level_msg = color.format_color( # f'[{record.levelname}]', # LOG_LEVEL_COLORS[record.levelname], # self.use_color, # ) # output.write_line(f'{level_msg} {record.getMessage()}') . Output only the next line.
handler.emit(_log_record('hi', logging.WARNING))
Continue the code snippet: <|code_start|> return len(full_cmd.encode('utf-16le')) // 2 else: return len(full_cmd.encode(sys.getfilesystemencoding())) class ArgumentTooLongError(RuntimeError): pass def partition( cmd: Sequence[str], varargs: Sequence[str], target_concurrency: int, _max_length: int | None = None, ) -> tuple[tuple[str, ...], ...]: _max_length = _max_length or _get_platform_max_length() # Generally, we try to partition evenly into at least `target_concurrency` # partitions, but we don't want a bunch of tiny partitions. max_args = max(4, math.ceil(len(varargs) / target_concurrency)) cmd = tuple(cmd) ret = [] ret_cmd: list[str] = [] # Reversed so arguments are in order varargs = list(reversed(varargs)) total_length = _command_length(*cmd) + 1 while varargs: <|code_end|> . Use current file imports: import concurrent.futures import contextlib import math import os import subprocess import sys from typing import Any from typing import Callable from typing import Generator from typing import Iterable from typing import MutableMapping from typing import Sequence from typing import TypeVar from pre_commit import parse_shebang from pre_commit.util import cmd_output_b from pre_commit.util import cmd_output_p 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 # 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: pre_commit/util.py # def cmd_output_p( # *cmd: str, # retcode: int | None = 0, # **kwargs: Any, # ) -> tuple[int, bytes, bytes | None]: # assert retcode is None # assert kwargs['stderr'] == subprocess.STDOUT, kwargs['stderr'] # _setdefault_kwargs(kwargs) # # try: # cmd = parse_shebang.normalize_cmd(cmd) # except parse_shebang.ExecutableNotFoundError as e: # return e.to_output() # # with open(os.devnull) as devnull, Pty() as pty: # assert pty.r is not None # kwargs.update({'stdin': devnull, 'stdout': pty.w, 'stderr': pty.w}) # try: # proc = subprocess.Popen(cmd, **kwargs) # except OSError as e: # return _oserror_to_output(e) # # pty.close_w() # # buf = b'' # while True: # try: # bts = os.read(pty.r, 4096) # except OSError as e: # if e.errno == errno.EIO: # bts = b'' # else: # raise # else: # buf += bts # if not bts: # break # # return proc.wait(), buf, None . Output only the next line.
arg = varargs.pop()
Given the following code snippet before the placeholder: <|code_start|>from __future__ import annotations TArg = TypeVar('TArg') TRet = TypeVar('TRet') def _environ_size(_env: MutableMapping[str, str] | None = None) -> int: environ = _env if _env is not None else getattr(os, 'environb', os.environ) size = 8 * len(environ) # number of pointers in `envp` for k, v in environ.items(): size += len(k) + len(v) + 2 # c strings in `envp` <|code_end|> , predict the next line using imports from the current file: import concurrent.futures import contextlib import math import os import subprocess import sys from typing import Any from typing import Callable from typing import Generator from typing import Iterable from typing import MutableMapping from typing import Sequence from typing import TypeVar from pre_commit import parse_shebang from pre_commit.util import cmd_output_b from pre_commit.util import cmd_output_p 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 # 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: pre_commit/util.py # def cmd_output_p( # *cmd: str, # retcode: int | None = 0, # **kwargs: Any, # ) -> tuple[int, bytes, bytes | None]: # assert retcode is None # assert kwargs['stderr'] == subprocess.STDOUT, kwargs['stderr'] # _setdefault_kwargs(kwargs) # # try: # cmd = parse_shebang.normalize_cmd(cmd) # except parse_shebang.ExecutableNotFoundError as e: # return e.to_output() # # with open(os.devnull) as devnull, Pty() as pty: # assert pty.r is not None # kwargs.update({'stdin': devnull, 'stdout': pty.w, 'stderr': pty.w}) # try: # proc = subprocess.Popen(cmd, **kwargs) # except OSError as e: # return _oserror_to_output(e) # # pty.close_w() # # buf = b'' # while True: # try: # bts = os.read(pty.r, 4096) # except OSError as e: # if e.errno == errno.EIO: # bts = b'' # else: # raise # else: # buf += bts # if not bts: # break # # return proc.wait(), buf, None . Output only the next line.
return size
Given the following code snippet before the placeholder: <|code_start|>from __future__ import annotations TArg = TypeVar('TArg') TRet = TypeVar('TRet') def _environ_size(_env: MutableMapping[str, str] | None = None) -> int: environ = _env if _env is not None else getattr(os, 'environb', os.environ) size = 8 * len(environ) # number of pointers in `envp` for k, v in environ.items(): size += len(k) + len(v) + 2 # c strings in `envp` return size def _get_platform_max_length() -> int: # pragma: no cover (platform specific) if os.name == 'posix': maximum = os.sysconf('SC_ARG_MAX') - 2048 - _environ_size() maximum = max(min(maximum, 2 ** 17), 2 ** 12) return maximum elif os.name == 'nt': return 2 ** 15 - 2048 # UNICODE_STRING max - headroom else: # posix minimum <|code_end|> , predict the next line using imports from the current file: import concurrent.futures import contextlib import math import os import subprocess import sys from typing import Any from typing import Callable from typing import Generator from typing import Iterable from typing import MutableMapping from typing import Sequence from typing import TypeVar from pre_commit import parse_shebang from pre_commit.util import cmd_output_b from pre_commit.util import cmd_output_p 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 # 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: pre_commit/util.py # def cmd_output_p( # *cmd: str, # retcode: int | None = 0, # **kwargs: Any, # ) -> tuple[int, bytes, bytes | None]: # assert retcode is None # assert kwargs['stderr'] == subprocess.STDOUT, kwargs['stderr'] # _setdefault_kwargs(kwargs) # # try: # cmd = parse_shebang.normalize_cmd(cmd) # except parse_shebang.ExecutableNotFoundError as e: # return e.to_output() # # with open(os.devnull) as devnull, Pty() as pty: # assert pty.r is not None # kwargs.update({'stdin': devnull, 'stdout': pty.w, 'stderr': pty.w}) # try: # proc = subprocess.Popen(cmd, **kwargs) # except OSError as e: # return _oserror_to_output(e) # # pty.close_w() # # buf = b'' # while True: # try: # bts = os.read(pty.r, 4096) # except OSError as e: # if e.errno == errno.EIO: # bts = b'' # else: # raise # else: # buf += bts # if not bts: # break # # return proc.wait(), buf, None . Output only the next line.
return 2 ** 12
Using the snippet: <|code_start|>from __future__ import annotations @pytest.fixture def find_exe_mck(): with mock.patch.object(parse_shebang, 'find_executable') as mck: yield mck @pytest.fixture def homedir_mck(): def fake_expanduser(pth): assert pth == '~' <|code_end|> , determine the next line of code. You have imports: import multiprocessing import os.path import sys import pytest import pre_commit.constants as C from unittest import mock from pre_commit import parse_shebang from pre_commit.languages import helpers from pre_commit.prefix import Prefix from pre_commit.util import CalledProcessError 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/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 # 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: 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.
return os.path.normpath('/home/me')
Here is a snippet: <|code_start|>from __future__ import annotations @pytest.fixture def find_exe_mck(): with mock.patch.object(parse_shebang, 'find_executable') as mck: yield mck @pytest.fixture def homedir_mck(): def fake_expanduser(pth): assert pth == '~' return os.path.normpath('/home/me') <|code_end|> . Write the next line using the current file imports: import multiprocessing import os.path import sys import pytest import pre_commit.constants as C from unittest import mock from pre_commit import parse_shebang from pre_commit.languages import helpers from pre_commit.prefix import Prefix from pre_commit.util import CalledProcessError 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/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 # 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: 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 include functions, classes, or code. Output only the next line.
with mock.patch.object(os.path, 'expanduser', fake_expanduser):
Continue the code snippet: <|code_start|>from __future__ import annotations @pytest.fixture def find_exe_mck(): with mock.patch.object(parse_shebang, 'find_executable') as mck: yield mck @pytest.fixture def homedir_mck(): def fake_expanduser(pth): assert pth == '~' return os.path.normpath('/home/me') <|code_end|> . Use current file imports: import multiprocessing import os.path import sys import pytest import pre_commit.constants as C from unittest import mock from pre_commit import parse_shebang from pre_commit.languages import helpers from pre_commit.prefix import Prefix from pre_commit.util import CalledProcessError 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/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 # 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: 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.
with mock.patch.object(os.path, 'expanduser', fake_expanduser):
Predict the next line after this snippet: <|code_start|>def find_exe_mck(): with mock.patch.object(parse_shebang, 'find_executable') as mck: yield mck @pytest.fixture def homedir_mck(): def fake_expanduser(pth): assert pth == '~' return os.path.normpath('/home/me') with mock.patch.object(os.path, 'expanduser', fake_expanduser): yield def test_exe_exists_does_not_exist(find_exe_mck, homedir_mck): find_exe_mck.return_value = None assert helpers.exe_exists('ruby') is False def test_exe_exists_exists(find_exe_mck, homedir_mck): find_exe_mck.return_value = os.path.normpath('/usr/bin/ruby') assert helpers.exe_exists('ruby') is True def test_exe_exists_false_if_shim(find_exe_mck, homedir_mck): find_exe_mck.return_value = os.path.normpath('/foo/shims/ruby') assert helpers.exe_exists('ruby') is False <|code_end|> using the current file's imports: import multiprocessing import os.path import sys import pytest import pre_commit.constants as C from unittest import mock from pre_commit import parse_shebang from pre_commit.languages import helpers from pre_commit.prefix import Prefix from pre_commit.util import CalledProcessError from testing.auto_namedtuple import auto_namedtuple and any relevant 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/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 # 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: 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.
def test_exe_exists_false_if_homedir(find_exe_mck, homedir_mck):
Continue the code snippet: <|code_start|>@pytest.fixture def homedir_mck(): def fake_expanduser(pth): assert pth == '~' return os.path.normpath('/home/me') with mock.patch.object(os.path, 'expanduser', fake_expanduser): yield def test_exe_exists_does_not_exist(find_exe_mck, homedir_mck): find_exe_mck.return_value = None assert helpers.exe_exists('ruby') is False def test_exe_exists_exists(find_exe_mck, homedir_mck): find_exe_mck.return_value = os.path.normpath('/usr/bin/ruby') assert helpers.exe_exists('ruby') is True def test_exe_exists_false_if_shim(find_exe_mck, homedir_mck): find_exe_mck.return_value = os.path.normpath('/foo/shims/ruby') assert helpers.exe_exists('ruby') is False def test_exe_exists_false_if_homedir(find_exe_mck, homedir_mck): find_exe_mck.return_value = os.path.normpath('/home/me/somedir/ruby') assert helpers.exe_exists('ruby') is False <|code_end|> . Use current file imports: import multiprocessing import os.path import sys import pytest import pre_commit.constants as C from unittest import mock from pre_commit import parse_shebang from pre_commit.languages import helpers from pre_commit.prefix import Prefix from pre_commit.util import CalledProcessError 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/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 # 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: 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.
def test_exe_exists_commonpath_raises_ValueError(find_exe_mck, homedir_mck):
Predict the next line for this snippet: <|code_start|> src = tmpdir.join('src').ensure_dir() cmd_output('git', 'init', str(src)) git_commit(cwd=str(src)) cmd_output('git', 'worktree', 'add', '.git/trees/foo', 'HEAD', cwd=src) with src.join('.git/trees/foo').as_cwd(): assert git.get_root() == os.path.abspath('.') def test_get_staged_files_deleted(in_git_dir): in_git_dir.join('test').ensure() cmd_output('git', 'add', 'test') git_commit() cmd_output('git', 'rm', '--cached', 'test') assert git.get_staged_files() == [] def test_is_not_in_merge_conflict(in_git_dir): assert git.is_in_merge_conflict() is False def test_is_in_merge_conflict(in_merge_conflict): assert git.is_in_merge_conflict() is True def test_is_in_merge_conflict_submodule(in_conflicting_submodule): assert git.is_in_merge_conflict() is True <|code_end|> with the help of current file imports: import os.path import pytest from pre_commit import git from pre_commit.error_handler import FatalError from pre_commit.util import cmd_output from testing.util import git_commit and context from other files: # Path: pre_commit/git.py # NO_FS_MONITOR = ('-c', 'core.useBuiltinFSMonitor=false') # def zsplit(s: str) -> list[str]: # def no_git_env( # _env: MutableMapping[str, str] | None = None, # ) -> dict[str, str]: # def get_root() -> str: # def get_git_dir(git_root: str = '.') -> str: # def get_remote_url(git_root: str) -> str: # def is_in_merge_conflict() -> bool: # def parse_merge_msg_for_conflicts(merge_msg: bytes) -> list[str]: # def get_conflicted_files() -> set[str]: # def get_staged_files(cwd: str | None = None) -> list[str]: # def intent_to_add_files() -> list[str]: # def get_all_files() -> list[str]: # def get_changed_files(old: str, new: str) -> list[str]: # def head_rev(remote: str) -> str: # def has_diff(*args: str, repo: str = '.') -> bool: # def has_core_hookpaths_set() -> bool: # def init_repo(path: str, remote: str) -> None: # def commit(repo: str = '.') -> None: # def git_path(name: str, repo: str = '.') -> str: # def check_for_cygwin_mismatch() -> None: # # Path: pre_commit/error_handler.py # def _log_and_exit( # msg: str, # ret_code: int, # exc: BaseException, # formatted: str, # ) -> None: # def error_handler() -> Generator[None, None, None]: # # 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 # 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_cherry_pick_conflict(in_merge_conflict):
Using the snippet: <|code_start|> def test_is_in_merge_conflict(in_merge_conflict): assert git.is_in_merge_conflict() is True def test_is_in_merge_conflict_submodule(in_conflicting_submodule): assert git.is_in_merge_conflict() is True def test_cherry_pick_conflict(in_merge_conflict): cmd_output('git', 'merge', '--abort') foo_ref = cmd_output('git', 'rev-parse', 'foo')[1].strip() cmd_output('git', 'cherry-pick', foo_ref, retcode=None) assert git.is_in_merge_conflict() is False def resolve_conflict(): with open('conflict_file', 'w') as conflicted_file: conflicted_file.write('herp\nderp\n') cmd_output('git', 'add', 'conflict_file') def test_get_conflicted_files(in_merge_conflict): resolve_conflict() with open('other_file', 'w') as other_file: other_file.write('oh hai') cmd_output('git', 'add', 'other_file') ret = set(git.get_conflicted_files()) <|code_end|> , determine the next line of code. You have imports: import os.path import pytest from pre_commit import git from pre_commit.error_handler import FatalError from pre_commit.util import cmd_output from testing.util import git_commit and context (class names, function names, or code) available: # Path: pre_commit/git.py # NO_FS_MONITOR = ('-c', 'core.useBuiltinFSMonitor=false') # def zsplit(s: str) -> list[str]: # def no_git_env( # _env: MutableMapping[str, str] | None = None, # ) -> dict[str, str]: # def get_root() -> str: # def get_git_dir(git_root: str = '.') -> str: # def get_remote_url(git_root: str) -> str: # def is_in_merge_conflict() -> bool: # def parse_merge_msg_for_conflicts(merge_msg: bytes) -> list[str]: # def get_conflicted_files() -> set[str]: # def get_staged_files(cwd: str | None = None) -> list[str]: # def intent_to_add_files() -> list[str]: # def get_all_files() -> list[str]: # def get_changed_files(old: str, new: str) -> list[str]: # def head_rev(remote: str) -> str: # def has_diff(*args: str, repo: str = '.') -> bool: # def has_core_hookpaths_set() -> bool: # def init_repo(path: str, remote: str) -> None: # def commit(repo: str = '.') -> None: # def git_path(name: str, repo: str = '.') -> str: # def check_for_cygwin_mismatch() -> None: # # Path: pre_commit/error_handler.py # def _log_and_exit( # msg: str, # ret_code: int, # exc: BaseException, # formatted: str, # ) -> None: # def error_handler() -> Generator[None, None, None]: # # 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 # 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 ret == {'conflict_file', 'other_file'}
Continue the code snippet: <|code_start|> cmd_output('git', 'rm', '--cached', 'test') assert git.get_staged_files() == [] def test_is_not_in_merge_conflict(in_git_dir): assert git.is_in_merge_conflict() is False def test_is_in_merge_conflict(in_merge_conflict): assert git.is_in_merge_conflict() is True def test_is_in_merge_conflict_submodule(in_conflicting_submodule): assert git.is_in_merge_conflict() is True def test_cherry_pick_conflict(in_merge_conflict): cmd_output('git', 'merge', '--abort') foo_ref = cmd_output('git', 'rev-parse', 'foo')[1].strip() cmd_output('git', 'cherry-pick', foo_ref, retcode=None) assert git.is_in_merge_conflict() is False def resolve_conflict(): with open('conflict_file', 'w') as conflicted_file: conflicted_file.write('herp\nderp\n') cmd_output('git', 'add', 'conflict_file') def test_get_conflicted_files(in_merge_conflict): <|code_end|> . Use current file imports: import os.path import pytest from pre_commit import git from pre_commit.error_handler import FatalError from pre_commit.util import cmd_output from testing.util import git_commit and context (classes, functions, or code) from other files: # Path: pre_commit/git.py # NO_FS_MONITOR = ('-c', 'core.useBuiltinFSMonitor=false') # def zsplit(s: str) -> list[str]: # def no_git_env( # _env: MutableMapping[str, str] | None = None, # ) -> dict[str, str]: # def get_root() -> str: # def get_git_dir(git_root: str = '.') -> str: # def get_remote_url(git_root: str) -> str: # def is_in_merge_conflict() -> bool: # def parse_merge_msg_for_conflicts(merge_msg: bytes) -> list[str]: # def get_conflicted_files() -> set[str]: # def get_staged_files(cwd: str | None = None) -> list[str]: # def intent_to_add_files() -> list[str]: # def get_all_files() -> list[str]: # def get_changed_files(old: str, new: str) -> list[str]: # def head_rev(remote: str) -> str: # def has_diff(*args: str, repo: str = '.') -> bool: # def has_core_hookpaths_set() -> bool: # def init_repo(path: str, remote: str) -> None: # def commit(repo: str = '.') -> None: # def git_path(name: str, repo: str = '.') -> str: # def check_for_cygwin_mismatch() -> None: # # Path: pre_commit/error_handler.py # def _log_and_exit( # msg: str, # ret_code: int, # exc: BaseException, # formatted: str, # ) -> None: # def error_handler() -> Generator[None, None, None]: # # 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 # 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.
resolve_conflict()
Next line prediction: <|code_start|> config = { 'repos': [ { 'repo': 'meta', 'hooks': [ { 'id': 'check-useless-excludes', 'types': ['python'], }, ], }, ], } add_config_to_repo(in_git_dir.strpath, config) assert check_hooks_apply.main(()) == 1 out, _ = capsys.readouterr() assert 'check-useless-excludes does not apply to this repository' in out def test_hook_types_excludes_everything(capsys, in_git_dir, mock_store_dir): config = { 'repos': [ { 'repo': 'meta', 'hooks': [ { 'id': 'check-useless-excludes', <|code_end|> . Use current file imports: (from pre_commit.meta_hooks import check_hooks_apply from testing.fixtures import add_config_to_repo) and context including class names, function names, or small code snippets from other files: # Path: pre_commit/meta_hooks/check_hooks_apply.py # def check_all_hooks_match_files(config_file: str) -> int: # def main(argv: Sequence[str] | None = None) -> int: # # Path: testing/fixtures.py # def add_config_to_repo(git_path, config, config_file=C.CONFIG_FILE): # write_config(git_path, config, config_file=config_file) # cmd_output('git', 'add', config_file, cwd=git_path) # git_commit(msg=add_config_to_repo.__name__, cwd=git_path) # return git_path . Output only the next line.
'exclude_types': ['yaml'],
Using the snippet: <|code_start|> out, _ = capsys.readouterr() assert 'check-useless-excludes does not apply to this repository' in out def test_hook_types_excludes_everything(capsys, in_git_dir, mock_store_dir): config = { 'repos': [ { 'repo': 'meta', 'hooks': [ { 'id': 'check-useless-excludes', 'exclude_types': ['yaml'], }, ], }, ], } add_config_to_repo(in_git_dir.strpath, config) assert check_hooks_apply.main(()) == 1 out, _ = capsys.readouterr() assert 'check-useless-excludes does not apply to this repository' in out def test_valid_exceptions(capsys, in_git_dir, mock_store_dir): config = { 'repos': [ <|code_end|> , determine the next line of code. You have imports: from pre_commit.meta_hooks import check_hooks_apply from testing.fixtures import add_config_to_repo and context (class names, function names, or code) available: # Path: pre_commit/meta_hooks/check_hooks_apply.py # def check_all_hooks_match_files(config_file: str) -> int: # def main(argv: Sequence[str] | None = None) -> int: # # Path: testing/fixtures.py # def add_config_to_repo(git_path, config, config_file=C.CONFIG_FILE): # write_config(git_path, config, config_file=config_file) # cmd_output('git', 'add', config_file, cwd=git_path) # git_commit(msg=add_config_to_repo.__name__, cwd=git_path) # return git_path . Output only the next line.
{
Here is a snippet: <|code_start|> ACTUAL_GET_DEFAULT_VERSION = ruby.get_default_version.__wrapped__ @pytest.fixture def find_exe_mck(): with mock.patch.object(parse_shebang, 'find_executable') as mck: yield mck def test_uses_default_version_when_not_available(find_exe_mck): find_exe_mck.return_value = None assert ACTUAL_GET_DEFAULT_VERSION() == C.DEFAULT def test_uses_system_if_both_gem_and_ruby_are_available(find_exe_mck): find_exe_mck.return_value = '/path/to/exe' assert ACTUAL_GET_DEFAULT_VERSION() == 'system' @pytest.fixture def fake_gem_prefix(tmpdir): gemspec = '''\ Gem::Specification.new do |s| s.name = 'pre_commit_placeholder_package' s.version = '0.0.0' s.summary = 'placeholder gem for pre-commit hooks' s.authors = ['Anthony Sottile'] <|code_end|> . Write the next line using the current file imports: import os.path import tarfile import pytest import pre_commit.constants as C from unittest import mock from pre_commit import parse_shebang from pre_commit.languages import ruby from pre_commit.prefix import Prefix from pre_commit.util import cmd_output from pre_commit.util import resource_bytesio from testing.util import xfailif_windows 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/languages/ruby.py # ENVIRONMENT_DIR = 'rbenv' # def get_default_version() -> str: # def get_env_patch( # venv: str, # language_version: str, # ) -> PatchesT: # def in_env( # prefix: Prefix, # language_version: str, # ) -> Generator[None, None, None]: # def _extract_resource(filename: str, dest: str) -> None: # def _install_rbenv( # prefix: Prefix, # version: str, # ) -> None: # pragma: win32 no cover # def _install_ruby( # prefix: Prefix, # version: str, # ) -> None: # pragma: win32 no cover # 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: pre_commit/util.py # def resource_bytesio(filename: str) -> IO[bytes]: # return importlib.resources.open_binary('pre_commit.resources', filename) # # 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): , which may include functions, classes, or code. Output only the next line.
end
Next line prediction: <|code_start|>from __future__ import annotations ACTUAL_GET_DEFAULT_VERSION = ruby.get_default_version.__wrapped__ @pytest.fixture def find_exe_mck(): with mock.patch.object(parse_shebang, 'find_executable') as mck: yield mck def test_uses_default_version_when_not_available(find_exe_mck): find_exe_mck.return_value = None assert ACTUAL_GET_DEFAULT_VERSION() == C.DEFAULT def test_uses_system_if_both_gem_and_ruby_are_available(find_exe_mck): find_exe_mck.return_value = '/path/to/exe' assert ACTUAL_GET_DEFAULT_VERSION() == 'system' @pytest.fixture def fake_gem_prefix(tmpdir): gemspec = '''\ <|code_end|> . Use current file imports: (import os.path import tarfile import pytest import pre_commit.constants as C from unittest import mock from pre_commit import parse_shebang from pre_commit.languages import ruby from pre_commit.prefix import Prefix from pre_commit.util import cmd_output from pre_commit.util import resource_bytesio from testing.util import xfailif_windows) and context including class names, function names, or small code snippets 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/languages/ruby.py # ENVIRONMENT_DIR = 'rbenv' # def get_default_version() -> str: # def get_env_patch( # venv: str, # language_version: str, # ) -> PatchesT: # def in_env( # prefix: Prefix, # language_version: str, # ) -> Generator[None, None, None]: # def _extract_resource(filename: str, dest: str) -> None: # def _install_rbenv( # prefix: Prefix, # version: str, # ) -> None: # pragma: win32 no cover # def _install_ruby( # prefix: Prefix, # version: str, # ) -> None: # pragma: win32 no cover # 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: pre_commit/util.py # def resource_bytesio(filename: str) -> IO[bytes]: # return importlib.resources.open_binary('pre_commit.resources', filename) # # 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.
Gem::Specification.new do |s|
Using the snippet: <|code_start|>from __future__ import annotations ACTUAL_GET_DEFAULT_VERSION = ruby.get_default_version.__wrapped__ @pytest.fixture def find_exe_mck(): with mock.patch.object(parse_shebang, 'find_executable') as mck: yield mck def test_uses_default_version_when_not_available(find_exe_mck): find_exe_mck.return_value = None assert ACTUAL_GET_DEFAULT_VERSION() == C.DEFAULT def test_uses_system_if_both_gem_and_ruby_are_available(find_exe_mck): find_exe_mck.return_value = '/path/to/exe' assert ACTUAL_GET_DEFAULT_VERSION() == 'system' @pytest.fixture def fake_gem_prefix(tmpdir): gemspec = '''\ Gem::Specification.new do |s| s.name = 'pre_commit_placeholder_package' <|code_end|> , determine the next line of code. You have imports: import os.path import tarfile import pytest import pre_commit.constants as C from unittest import mock from pre_commit import parse_shebang from pre_commit.languages import ruby from pre_commit.prefix import Prefix from pre_commit.util import cmd_output from pre_commit.util import resource_bytesio from testing.util import xfailif_windows 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/languages/ruby.py # ENVIRONMENT_DIR = 'rbenv' # def get_default_version() -> str: # def get_env_patch( # venv: str, # language_version: str, # ) -> PatchesT: # def in_env( # prefix: Prefix, # language_version: str, # ) -> Generator[None, None, None]: # def _extract_resource(filename: str, dest: str) -> None: # def _install_rbenv( # prefix: Prefix, # version: str, # ) -> None: # pragma: win32 no cover # def _install_ruby( # prefix: Prefix, # version: str, # ) -> None: # pragma: win32 no cover # 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: pre_commit/util.py # def resource_bytesio(filename: str) -> IO[bytes]: # return importlib.resources.open_binary('pre_commit.resources', filename) # # 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.
s.version = '0.0.0'
Here is a snippet: <|code_start|>from __future__ import annotations ACTUAL_GET_DEFAULT_VERSION = ruby.get_default_version.__wrapped__ @pytest.fixture def find_exe_mck(): with mock.patch.object(parse_shebang, 'find_executable') as mck: yield mck def test_uses_default_version_when_not_available(find_exe_mck): find_exe_mck.return_value = None assert ACTUAL_GET_DEFAULT_VERSION() == C.DEFAULT def test_uses_system_if_both_gem_and_ruby_are_available(find_exe_mck): <|code_end|> . Write the next line using the current file imports: import os.path import tarfile import pytest import pre_commit.constants as C from unittest import mock from pre_commit import parse_shebang from pre_commit.languages import ruby from pre_commit.prefix import Prefix from pre_commit.util import cmd_output from pre_commit.util import resource_bytesio from testing.util import xfailif_windows 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/languages/ruby.py # ENVIRONMENT_DIR = 'rbenv' # def get_default_version() -> str: # def get_env_patch( # venv: str, # language_version: str, # ) -> PatchesT: # def in_env( # prefix: Prefix, # language_version: str, # ) -> Generator[None, None, None]: # def _extract_resource(filename: str, dest: str) -> None: # def _install_rbenv( # prefix: Prefix, # version: str, # ) -> None: # pragma: win32 no cover # def _install_ruby( # prefix: Prefix, # version: str, # ) -> None: # pragma: win32 no cover # 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: pre_commit/util.py # def resource_bytesio(filename: str) -> IO[bytes]: # return importlib.resources.open_binary('pre_commit.resources', filename) # # 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): , which may include functions, classes, or code. Output only the next line.
find_exe_mck.return_value = '/path/to/exe'
Based on the snippet: <|code_start|>from __future__ import annotations ACTUAL_GET_DEFAULT_VERSION = ruby.get_default_version.__wrapped__ @pytest.fixture def find_exe_mck(): with mock.patch.object(parse_shebang, 'find_executable') as mck: yield mck def test_uses_default_version_when_not_available(find_exe_mck): find_exe_mck.return_value = None assert ACTUAL_GET_DEFAULT_VERSION() == C.DEFAULT def test_uses_system_if_both_gem_and_ruby_are_available(find_exe_mck): find_exe_mck.return_value = '/path/to/exe' assert ACTUAL_GET_DEFAULT_VERSION() == 'system' <|code_end|> , predict the immediate next line with the help of imports: import os.path import tarfile import pytest import pre_commit.constants as C from unittest import mock from pre_commit import parse_shebang from pre_commit.languages import ruby from pre_commit.prefix import Prefix from pre_commit.util import cmd_output from pre_commit.util import resource_bytesio from testing.util import xfailif_windows 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/languages/ruby.py # ENVIRONMENT_DIR = 'rbenv' # def get_default_version() -> str: # def get_env_patch( # venv: str, # language_version: str, # ) -> PatchesT: # def in_env( # prefix: Prefix, # language_version: str, # ) -> Generator[None, None, None]: # def _extract_resource(filename: str, dest: str) -> None: # def _install_rbenv( # prefix: Prefix, # version: str, # ) -> None: # pragma: win32 no cover # def _install_ruby( # prefix: Prefix, # version: str, # ) -> None: # pragma: win32 no cover # 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: pre_commit/util.py # def resource_bytesio(filename: str) -> IO[bytes]: # return importlib.resources.open_binary('pre_commit.resources', filename) # # 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.
@pytest.fixture
Here is a snippet: <|code_start|>from __future__ import annotations def test_sample_config(capsys): ret = sample_config() <|code_end|> . Write the next line using the current file imports: from pre_commit.commands.sample_config import sample_config and context from other files: # Path: pre_commit/commands/sample_config.py # def sample_config() -> int: # print(SAMPLE_CONFIG, end='') # return 0 , which may include functions, classes, or code. Output only the next line.
assert ret == 0
Given snippet: <|code_start|>def test_negate_by_line_all_match(cap_out): ret = pygrep.main(('pattern', 'f4', 'f5', 'f6', '--negate')) out = cap_out.get() assert ret == 0 assert out == '' @pytest.mark.usefixtures('some_files') def test_negate_by_file_no_match(cap_out): ret = pygrep.main(('baz', 'f4', 'f5', 'f6', '--negate', '--multiline')) out = cap_out.get() assert ret == 1 assert out == 'f4\nf5\nf6\n' @pytest.mark.usefixtures('some_files') def test_negate_by_file_one_match(cap_out): ret = pygrep.main( ('foo\npattern', 'f4', 'f5', 'f6', '--negate', '--multiline'), ) out = cap_out.get() assert ret == 1 assert out == 'f5\nf6\n' @pytest.mark.usefixtures('some_files') def test_negate_by_file_all_match(cap_out): ret = pygrep.main( ('pattern\nbar', 'f4', 'f5', 'f6', '--negate', '--multiline'), ) <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest from pre_commit.languages import pygrep and context: # Path: pre_commit/languages/pygrep.py # ENVIRONMENT_DIR = None # FNS = { # Choice(multiline=True, negate=True): _process_filename_at_once_negated, # Choice(multiline=True, negate=False): _process_filename_at_once, # Choice(multiline=False, negate=True): _process_filename_by_line_negated, # Choice(multiline=False, negate=False): _process_filename_by_line, # } # def _process_filename_by_line(pattern: Pattern[bytes], filename: str) -> int: # def _process_filename_at_once(pattern: Pattern[bytes], filename: str) -> int: # def _process_filename_by_line_negated( # pattern: Pattern[bytes], # filename: str, # ) -> int: # def _process_filename_at_once_negated( # pattern: Pattern[bytes], # filename: str, # ) -> int: # def run_hook( # hook: Hook, # file_args: Sequence[str], # color: bool, # ) -> tuple[int, bytes]: # def main(argv: Sequence[str] | None = None) -> int: # class Choice(NamedTuple): which might include code, classes, or functions. Output only the next line.
out = cap_out.get()
Predict the next line for this snippet: <|code_start|>from __future__ import annotations logger = logging.getLogger('pre_commit') LOG_LEVEL_COLORS = { 'DEBUG': '', <|code_end|> with the help of current file imports: import contextlib import logging from typing import Generator from pre_commit import color from pre_commit import output and context from other files: # Path: pre_commit/color.py # def _enable() -> None: # def bool_errcheck(result, func, args): # def format_color(text: str, color: str, use_color_setting: bool) -> str: # def use_color(setting: str) -> bool: # def add_color_option(parser: argparse.ArgumentParser) -> None: # STD_ERROR_HANDLE = -12 # ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4 # RED = '\033[41m' # GREEN = '\033[42m' # YELLOW = '\033[43;30m' # TURQUOISE = '\033[46;30m' # SUBTLE = '\033[2m' # NORMAL = '\033[m' # COLOR_CHOICES = ('auto', 'always', 'never') # # 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: , which may contain function names, class names, or code. Output only the next line.
'INFO': '',
Given the following code snippet before the placeholder: <|code_start|># Author: Trevor Perrin # See the LICENSE file for legal information regarding use of this file. #This code is shared with tackpy (somewhat), so I'd rather make minimal #changes, and preserve the use of a2b_base64 throughout. def a2b_base64(s): return base64ToBytes(s) def b2a_base64(b): <|code_end|> , predict the next line using imports from the current file: from .cryptomath import base64ToBytes import binascii and context including class names, function names, and sometimes code from other files: # Path: tlslite/utils/cryptomath.py # def base64ToBytes(s): # s = base64ToString(s) # return stringToBytes(s) . Output only the next line.
return bytesToBase64(b)
Given the following code snippet before the placeholder: <|code_start|> alertStr = str(self.description) return alertStr class TLSAuthenticationError(TLSError): """The handshake succeeded, but the other party's authentication was inadequate. This exception will only be raised when a L{tlslite.Checker.Checker} has been passed to a handshake function. The Checker will be invoked once the handshake completes, and if the Checker objects to how the other party authenticated, a subclass of this exception will be raised. """ pass class TLSNoAuthenticationError(TLSAuthenticationError): """The Checker was expecting the other party to authenticate with a certificate chain, but this did not occur.""" pass class TLSAuthenticationTypeError(TLSAuthenticationError): """The Checker was expecting the other party to authenticate with a different type of certificate chain.""" pass class TLSFingerprintError(TLSAuthenticationError): """The Checker was expecting the other party to authenticate with a certificate chain that matches a different fingerprint.""" pass <|code_end|> , predict the next line using imports from the current file: from .constants import AlertDescription, AlertLevel and context including class names, function names, and sometimes code from other files: # Path: tlslite/constants.py # class AlertDescription: # """ # @cvar bad_record_mac: A TLS record failed to decrypt properly. # # If this occurs during a SRP handshake it most likely # indicates a bad password. It may also indicate an implementation # error, or some tampering with the data in transit. # # This alert will be signalled by the server if the SRP password is bad. It # may also be signalled by the server if the SRP username is unknown to the # server, but it doesn't wish to reveal that fact. # # # @cvar handshake_failure: A problem occurred while handshaking. # # This typically indicates a lack of common ciphersuites between client and # server, or some other disagreement (about SRP parameters or key sizes, # for example). # # @cvar protocol_version: The other party's SSL/TLS version was unacceptable. # # This indicates that the client and server couldn't agree on which version # of SSL or TLS to use. # # @cvar user_canceled: The handshake is being cancelled for some reason. # # """ # # close_notify = 0 # unexpected_message = 10 # bad_record_mac = 20 # decryption_failed = 21 # record_overflow = 22 # decompression_failure = 30 # handshake_failure = 40 # no_certificate = 41 #SSLv3 # bad_certificate = 42 # unsupported_certificate = 43 # certificate_revoked = 44 # certificate_expired = 45 # certificate_unknown = 46 # illegal_parameter = 47 # unknown_ca = 48 # access_denied = 49 # decode_error = 50 # decrypt_error = 51 # export_restriction = 60 # protocol_version = 70 # insufficient_security = 71 # internal_error = 80 # user_canceled = 90 # no_renegotiation = 100 # unknown_psk_identity = 115 # # class AlertLevel: # warning = 1 # fatal = 2 . Output only the next line.
class TLSAuthorizationError(TLSAuthenticationError):
Here is a snippet: <|code_start|> memAvailable = 0 memInfo = os.popen('free -t -m').read() for line in memInfo.splitlines(): if line.rstrip().startswith('Mem:'): memAvailable = int(line.split()[1]) # Give room for swap space if memAvailable < 900: sys.exit('Less than 1GB of memory. You need more than this to continue.') if installType == '1': if memAvailable < 1800: sys.exit('Less than 2GB of memory available. Consider splitting installs across multiple devices.') # Install prerequisites packages.install(installType) interfaces = os.listdir('/sys/class/net/') userQuestion = "Available Interfaces: \n" availableInts = [] availableIntNames = [] availableIntIPs = [] d = 0 for interface in interfaces: if interface != "lo": if len(getIP(interface)) > 0: availableInts.append(str(d)) availableIntNames.append(interface) availableIntIPs.append(getIP(interface)) userQuestion += " %d: %s (%s)\n" % (d, interface, getIP(interface)) d = d + 1 <|code_end|> . Write the next line using the current file imports: import argparse, fcntl, getpass, json, os, re, shutil, socket, sqlite3, struct, sys from time import sleep from install import packages from install import bro from install import criticalStack from install import elasticSearch from install import logstash from install import kibana from install import sweetSecurity from install import apache from install import fail2ban and context from other files: # Path: install/packages.py # def install(installType): # # Path: install/bro.py # def install(chosenInterface,webServer): # # Path: install/criticalStack.py # def get_user_input(input_string): # def install(csKey): # # Path: install/logstash.py # def get_user_input(input_string): # def install(esServer,esUser,esPass): # # Path: install/kibana.py # def install(chosenInterfaceIP): # def importDashboard(jsonFileName): # def importIndexMapping(jsonFileName): # # Path: install/sweetSecurity.py # def installClient(chosenInterface): # def installServer(): # def addWebCreds(address,user,pwd,location): # # Path: install/apache.py # def get_user_input(input_string): # def install(installType,chosenInterface,chosenIP): # # Path: install/fail2ban.py # def install(): , which may include functions, classes, or code. Output only the next line.
userQuestion += "\033[1mWhich Interface Should be Used(web admin and spoofing)\033[0m: "
Here is a snippet: <|code_start|> else: break bro.install(chosenInterface, 'localhost') if criticalStackInstalled == False and installCriticalStack.lower() == 'y': criticalStack.install(csKey) else: print "Skipping Critical Stack Install" # Check if We Should Install Fail2Ban # while True: # installFail2Ban = get_user_input("\033[1mInstall Fail2Ban (Y/n)\033[0m: ") # if installFail2Ban.lower() not in ('y', 'n', ''): # print "Must choose Y or N." # else: # break # if installFail2Ban == 'y' or installFail2Ban == '': # fail2ban.install() apache.install(installType, chosenInterface, chosenInterfaceIP) print " Creating web portal credentials" os.popen('sudo htpasswd -cb /etc/apache2/.htpasswd %s "%s"' % (httpUser, httpPass)).read() os.popen('sudo htpasswd -cb /etc/apache2/.elasticsearch %s "%s"' % (elasticUser, elasticPass)).read() # Get system default configurations fileCheckKey = None while True: installFileCheck = get_user_input("\033[1mCheck Files Against FileCheck.IO (y/N)\033[0m: ") if installFileCheck.lower() not in ('y', 'n', ''): print "Must choose Y or N." else: break if installFileCheck.lower() == 'y': installFileCheck = 'y' <|code_end|> . Write the next line using the current file imports: import argparse, fcntl, getpass, json, os, re, shutil, socket, sqlite3, struct, sys from time import sleep from install import packages from install import bro from install import criticalStack from install import elasticSearch from install import logstash from install import kibana from install import sweetSecurity from install import apache from install import fail2ban and context from other files: # Path: install/packages.py # def install(installType): # # Path: install/bro.py # def install(chosenInterface,webServer): # # Path: install/criticalStack.py # def get_user_input(input_string): # def install(csKey): # # Path: install/logstash.py # def get_user_input(input_string): # def install(esServer,esUser,esPass): # # Path: install/kibana.py # def install(chosenInterfaceIP): # def importDashboard(jsonFileName): # def importIndexMapping(jsonFileName): # # Path: install/sweetSecurity.py # def installClient(chosenInterface): # def installServer(): # def addWebCreds(address,user,pwd,location): # # Path: install/apache.py # def get_user_input(input_string): # def install(installType,chosenInterface,chosenIP): # # Path: install/fail2ban.py # def install(): , which may include functions, classes, or code. Output only the next line.
while True:
Given the code snippet: <|code_start|> def getIP(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))[20:24]) except: return '' def validateIP(ip): if re.match(r'^(\d{1,3}\.){3}\d{1,3}$', ip): return True elif re.match(r'^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](\.[a-zA-Z]{2,})+$', ip): return True elif re.match(r'^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]$', ip): return True else: return False if __name__ == "__main__": # Check if user is root first... if os.getuid() != 0: sys.exit("Must run as root/sudo") while True: question = "\033[1m1 - \033[4mFull Install\033[0m: Bro IDS, Critical Stack, ELK Stack, Apache, Sweet Security\n" question += "\033[1m2 - \033[4mSensor Only\033[0m: Bro IDS, Critical Stack, Logstash, Sweet Security\n" <|code_end|> , generate the next line using the imports in this file: import argparse, fcntl, getpass, json, os, re, shutil, socket, sqlite3, struct, sys from time import sleep from install import packages from install import bro from install import criticalStack from install import elasticSearch from install import logstash from install import kibana from install import sweetSecurity from install import apache from install import fail2ban and context (functions, classes, or occasionally code) from other files: # Path: install/packages.py # def install(installType): # # Path: install/bro.py # def install(chosenInterface,webServer): # # Path: install/criticalStack.py # def get_user_input(input_string): # def install(csKey): # # Path: install/logstash.py # def get_user_input(input_string): # def install(esServer,esUser,esPass): # # Path: install/kibana.py # def install(chosenInterfaceIP): # def importDashboard(jsonFileName): # def importIndexMapping(jsonFileName): # # Path: install/sweetSecurity.py # def installClient(chosenInterface): # def installServer(): # def addWebCreds(address,user,pwd,location): # # Path: install/apache.py # def get_user_input(input_string): # def install(installType,chosenInterface,chosenIP): # # Path: install/fail2ban.py # def install(): . Output only the next line.
question += "\033[1m3 - \033[4mWeb Server Only\033[0m: Elasticsearch, Kibana, Apache\n"
Given snippet: <|code_start|> if installFileCheck.lower() not in ('y', 'n', ''): print "Must choose Y or N." else: break if installFileCheck.lower() == 'y': installFileCheck = 'y' while True: fileCheckKey = get_user_input(" \033[1mEnter Your FileCheckIO API Key\033[0m: ") if not re.match(r'[0-9a-fA-F]{56}', fileCheckKey): print(" Not a valid API key.") else: break elasticSearch.install(fileCheckKey) kibana.install(chosenInterfaceIP) print "Restarting Apache" os.popen('sudo service apache2 restart').read() logstash.install('localhost', elasticUser, elasticPass) sweetSecurity.installClient(chosenInterface) sweetSecurity.addWebCreds('localhost', httpUser, httpPass,'client') print "Starting SweetSecurity Client" os.popen('sudo service sweetsecurity restart').read() sweetSecurity.installServer() sweetSecurity.addWebCreds('localhost', httpUser, httpPass, 'server') print "Starting SweetSecurity Server" os.popen('sudo service sweetsecurity_server restart').read() elif installType == '2': # Bro IDS, Critical Stack, Logstash, Sweet Security esServer = get_user_input('\033[1mEnter Server IP:\033[0m ') criticalStackInstalled = False if os.path.isfile('/usr/bin/critical-stack-intel'): <|code_end|> , continue by predicting the next line. Consider current file imports: import argparse, fcntl, getpass, json, os, re, shutil, socket, sqlite3, struct, sys from time import sleep from install import packages from install import bro from install import criticalStack from install import elasticSearch from install import logstash from install import kibana from install import sweetSecurity from install import apache from install import fail2ban and context: # Path: install/packages.py # def install(installType): # # Path: install/bro.py # def install(chosenInterface,webServer): # # Path: install/criticalStack.py # def get_user_input(input_string): # def install(csKey): # # Path: install/logstash.py # def get_user_input(input_string): # def install(esServer,esUser,esPass): # # Path: install/kibana.py # def install(chosenInterfaceIP): # def importDashboard(jsonFileName): # def importIndexMapping(jsonFileName): # # Path: install/sweetSecurity.py # def installClient(chosenInterface): # def installServer(): # def addWebCreds(address,user,pwd,location): # # Path: install/apache.py # def get_user_input(input_string): # def install(installType,chosenInterface,chosenIP): # # Path: install/fail2ban.py # def install(): which might include code, classes, or functions. Output only the next line.
criticalStackInstalled = True
Next line prediction: <|code_start|>#!/usr/bin/env python # Local Installer Scripts # Issue: When using OpenDNS, no hostname resolution class color: PURPLE = '\033[95m' CYAN = '\033[96m' DARKCYAN = '\033[36m' BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' BOLD = '\033[1m' UNDERLINE = '\033[4m' END = '\033[0m' def get_user_input(input_string): if sys.version_info[0] > 2: return input(input_string) else: return raw_input(input_string) def getIP(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) <|code_end|> . Use current file imports: (import argparse, fcntl, getpass, json, os, re, shutil, socket, sqlite3, struct, sys from time import sleep from install import packages from install import bro from install import criticalStack from install import elasticSearch from install import logstash from install import kibana from install import sweetSecurity from install import apache from install import fail2ban) and context including class names, function names, or small code snippets from other files: # Path: install/packages.py # def install(installType): # # Path: install/bro.py # def install(chosenInterface,webServer): # # Path: install/criticalStack.py # def get_user_input(input_string): # def install(csKey): # # Path: install/logstash.py # def get_user_input(input_string): # def install(esServer,esUser,esPass): # # Path: install/kibana.py # def install(chosenInterfaceIP): # def importDashboard(jsonFileName): # def importIndexMapping(jsonFileName): # # Path: install/sweetSecurity.py # def installClient(chosenInterface): # def installServer(): # def addWebCreds(address,user,pwd,location): # # Path: install/apache.py # def get_user_input(input_string): # def install(installType,chosenInterface,chosenIP): # # Path: install/fail2ban.py # def install(): . Output only the next line.
try:
Using the snippet: <|code_start|> memAvailable = 0 memInfo = os.popen('free -t -m').read() for line in memInfo.splitlines(): if line.rstrip().startswith('Mem:'): memAvailable = int(line.split()[1]) # Give room for swap space if memAvailable < 900: sys.exit('Less than 1GB of memory. You need more than this to continue.') if installType == '1': if memAvailable < 1800: sys.exit('Less than 2GB of memory available. Consider splitting installs across multiple devices.') # Install prerequisites packages.install(installType) interfaces = os.listdir('/sys/class/net/') userQuestion = "Available Interfaces: \n" availableInts = [] availableIntNames = [] availableIntIPs = [] d = 0 for interface in interfaces: if interface != "lo": if len(getIP(interface)) > 0: availableInts.append(str(d)) availableIntNames.append(interface) availableIntIPs.append(getIP(interface)) userQuestion += " %d: %s (%s)\n" % (d, interface, getIP(interface)) d = d + 1 <|code_end|> , determine the next line of code. You have imports: import argparse, fcntl, getpass, json, os, re, shutil, socket, sqlite3, struct, sys from time import sleep from install import packages from install import bro from install import criticalStack from install import elasticSearch from install import logstash from install import kibana from install import sweetSecurity from install import apache from install import fail2ban and context (class names, function names, or code) available: # Path: install/packages.py # def install(installType): # # Path: install/bro.py # def install(chosenInterface,webServer): # # Path: install/criticalStack.py # def get_user_input(input_string): # def install(csKey): # # Path: install/logstash.py # def get_user_input(input_string): # def install(esServer,esUser,esPass): # # Path: install/kibana.py # def install(chosenInterfaceIP): # def importDashboard(jsonFileName): # def importIndexMapping(jsonFileName): # # Path: install/sweetSecurity.py # def installClient(chosenInterface): # def installServer(): # def addWebCreds(address,user,pwd,location): # # Path: install/apache.py # def get_user_input(input_string): # def install(installType,chosenInterface,chosenIP): # # Path: install/fail2ban.py # def install(): . Output only the next line.
userQuestion += "\033[1mWhich Interface Should be Used(web admin and spoofing)\033[0m: "
Using the snippet: <|code_start|> def getIP(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))[20:24]) except: return '' def validateIP(ip): if re.match(r'^(\d{1,3}\.){3}\d{1,3}$', ip): return True elif re.match(r'^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](\.[a-zA-Z]{2,})+$', ip): return True elif re.match(r'^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]$', ip): return True else: return False if __name__ == "__main__": # Check if user is root first... if os.getuid() != 0: sys.exit("Must run as root/sudo") while True: question = "\033[1m1 - \033[4mFull Install\033[0m: Bro IDS, Critical Stack, ELK Stack, Apache, Sweet Security\n" question += "\033[1m2 - \033[4mSensor Only\033[0m: Bro IDS, Critical Stack, Logstash, Sweet Security\n" <|code_end|> , determine the next line of code. You have imports: import argparse, fcntl, getpass, json, os, re, shutil, socket, sqlite3, struct, sys from time import sleep from install import packages from install import bro from install import criticalStack from install import elasticSearch from install import logstash from install import kibana from install import sweetSecurity from install import apache from install import fail2ban and context (class names, function names, or code) available: # Path: install/packages.py # def install(installType): # # Path: install/bro.py # def install(chosenInterface,webServer): # # Path: install/criticalStack.py # def get_user_input(input_string): # def install(csKey): # # Path: install/logstash.py # def get_user_input(input_string): # def install(esServer,esUser,esPass): # # Path: install/kibana.py # def install(chosenInterfaceIP): # def importDashboard(jsonFileName): # def importIndexMapping(jsonFileName): # # Path: install/sweetSecurity.py # def installClient(chosenInterface): # def installServer(): # def addWebCreds(address,user,pwd,location): # # Path: install/apache.py # def get_user_input(input_string): # def install(installType,chosenInterface,chosenIP): # # Path: install/fail2ban.py # def install(): . Output only the next line.
question += "\033[1m3 - \033[4mWeb Server Only\033[0m: Elasticsearch, Kibana, Apache\n"
Given snippet: <|code_start|> installCriticalStack = get_user_input( "\033[1mInstall Critical Stack Threat Intel For Bro IDS (Y/n)\033[0m: ") if installCriticalStack.lower() not in ('y', 'n', ''): print("Must choose Y or N.") else: break if installCriticalStack.lower() == 'y' or len(installCriticalStack) == 0: installCriticalStack = 'y' while True: csKey = get_user_input(" \033[1mEnter Your Critical Stack API Key\033[0m: ") if not re.match(r'[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}', csKey): print(" Not a valid API key.") else: break if not validateIP(esServer): sys.exit('Not a valid IP Address') bro.install(chosenInterface, esServer) if criticalStackInstalled == False and installCriticalStack.lower() == 'y': criticalStack.install(csKey) logstash.install(esServer, elasticUser, elasticPass) sweetSecurity.installClient(chosenInterface) sweetSecurity.addWebCreds(esServer, httpUser, httpPass,'client') print "Starting SweetSecurity" os.popen('sudo service sweetsecurity restart').read() elif installType == '3': # Elasticsearch, Kibana, Apache # Check if We Should Install Fail2Ban while True: installFail2Ban = get_user_input("\033[1mInstall Fail2Ban (Y/n)\033[0m: ") <|code_end|> , continue by predicting the next line. Consider current file imports: import argparse, fcntl, getpass, json, os, re, shutil, socket, sqlite3, struct, sys from time import sleep from install import packages from install import bro from install import criticalStack from install import elasticSearch from install import logstash from install import kibana from install import sweetSecurity from install import apache from install import fail2ban and context: # Path: install/packages.py # def install(installType): # # Path: install/bro.py # def install(chosenInterface,webServer): # # Path: install/criticalStack.py # def get_user_input(input_string): # def install(csKey): # # Path: install/logstash.py # def get_user_input(input_string): # def install(esServer,esUser,esPass): # # Path: install/kibana.py # def install(chosenInterfaceIP): # def importDashboard(jsonFileName): # def importIndexMapping(jsonFileName): # # Path: install/sweetSecurity.py # def installClient(chosenInterface): # def installServer(): # def addWebCreds(address,user,pwd,location): # # Path: install/apache.py # def get_user_input(input_string): # def install(installType,chosenInterface,chosenIP): # # Path: install/fail2ban.py # def install(): which might include code, classes, or functions. Output only the next line.
if installFail2Ban.lower() not in ('y', 'n', ''):
Given the following code snippet before the placeholder: <|code_start|> class GoogleCloudDatastore(Storage): def __init__(self, namespace=None): self._logger = logging.getLogger("flask-blogging") self._client = datastore.Client(namespace=namespace) def _get_new_post_id(self): key = self._client.key('PostIDCounter', 'Counter') query = self._client.get(key) if query: counter = dict(query) else: counter = None if counter: counter = counter["value"]+1 key = self._client.key('PostIDCounter', 'Counter') task = self._client.get(key) task['value'] = counter self._client.put(task) <|code_end|> , predict the next line using imports from the current file: import logging import datetime from .storage import Storage from google.cloud import datastore from shortuuid import ShortUUID from operator import itemgetter and context including class names, function names, and sometimes code from other files: # Path: flask_blogging/storage.py # class Storage(object): # # def save_post(self, title, text, user_id, tags, draft=False, # post_date=None, last_modified_date=None, meta_data=None, # post_id=None): # """ # Persist the blog post data. If ``post_id`` is ``None`` or ``post_id`` # is invalid, the post must be inserted into the storage. If ``post_id`` # is a valid id, then the data must be updated. # # :param title: The title of the blog post # :type title: str # :param text: The text of the blog post # :type text: str # :param user_id: The user identifier # :type user_id: str # :param tags: A list of tags # :type tags: list # :param draft: If the post is a draft of if needs to be published. # :type draft: bool # :param post_date: (Optional) The date the blog was posted (default # datetime.datetime.utcnow()) # :type post_date: datetime.datetime # :param last_modified_date: (Optional) The date when blog was last # modified (default datetime.datetime.utcnow()) # :type last_modified_date: datetime.datetime # :param meta_data: The meta data for the blog post # :type meta_data: dict # :param post_id: The post identifier. This should be ``None`` for an # insert call, and a valid value for update. # :type post_id: int # # :return: The post_id value, in case of a successful insert or update. # Return ``None`` if there were errors. # """ # raise NotImplementedError("This method needs to be implemented by " # "the inheriting class") # # def get_post_by_id(self, post_id): # """ # Fetch the blog post given by ``post_id`` # # :param post_id: The post identifier for the blog post # :type post_id: int # :return: If the ``post_id`` is valid, the post data is retrieved, # else returns ``None``. # """ # raise NotImplementedError("This method needs to be implemented by the " # "inheriting class") # # def get_posts(self, count=10, offset=0, recent=True, tag=None, # user_id=None, include_draft=False): # """ # Get posts given by filter criteria # # :param count: The number of posts to retrieve (default 10). If count # is ``None``, all posts are returned. # :type count: int # :param offset: The number of posts to offset (default 0) # :type offset: int # :param recent: Order by recent posts or not # :type recent: bool # :param tag: Filter by a specific tag # :type tag: str # :param user_id: Filter by a specific user # :type user_id: str # :param include_draft: Whether to include posts marked as draft or not # :type include_draft: bool # # :return: A list of posts, with each element a dict containing values # for the following keys: (title, text, draft, post_date, # last_modified_date). If count is ``None``, then all the posts are # returned. # """ # raise NotImplementedError("This method needs to be implemented by the " # "inheriting class") # # def count_posts(self, tag=None, user_id=None, include_draft=False): # """ # Returns the total number of posts for the give filter # # :param tag: Filter by a specific tag # :type tag: str # :param user_id: Filter by a specific user # :type user_id: str # :param include_draft: Whether to include posts marked as draft or not # :type include_draft: bool # :return: The number of posts for the given filter. # """ # raise NotImplementedError("This method needs to be implemented by the " # "inheriting class") # # def delete_post(self, post_id): # """ # Delete the post defined by ``post_id`` # # :param post_id: The identifier corresponding to a post # :type post_id: int # :return: Returns True if the post was successfully deleted and False # otherwise. # """ # raise NotImplementedError("This method needs to be implemented by the " # "inheriting class") # # @classmethod # def normalize_tags(cls, tags): # return [cls.normalize_tag(tag) for tag in tags] # # @staticmethod # def normalize_tag(tag): # return tag.upper().strip() . Output only the next line.
return int(counter)
Continue the code snippet: <|code_start|>try: except ImportError: pass <|code_end|> . Use current file imports: from builtins import str from collections import defaultdict, OrderedDict from sqlalchemy.ext.automap import automap_base from .storage import Storage from .signals import sqla_initialized import sys import logging import sqlalchemy as sqla import datetime and context (classes, functions, or code) from other files: # Path: flask_blogging/storage.py # class Storage(object): # # def save_post(self, title, text, user_id, tags, draft=False, # post_date=None, last_modified_date=None, meta_data=None, # post_id=None): # """ # Persist the blog post data. If ``post_id`` is ``None`` or ``post_id`` # is invalid, the post must be inserted into the storage. If ``post_id`` # is a valid id, then the data must be updated. # # :param title: The title of the blog post # :type title: str # :param text: The text of the blog post # :type text: str # :param user_id: The user identifier # :type user_id: str # :param tags: A list of tags # :type tags: list # :param draft: If the post is a draft of if needs to be published. # :type draft: bool # :param post_date: (Optional) The date the blog was posted (default # datetime.datetime.utcnow()) # :type post_date: datetime.datetime # :param last_modified_date: (Optional) The date when blog was last # modified (default datetime.datetime.utcnow()) # :type last_modified_date: datetime.datetime # :param meta_data: The meta data for the blog post # :type meta_data: dict # :param post_id: The post identifier. This should be ``None`` for an # insert call, and a valid value for update. # :type post_id: int # # :return: The post_id value, in case of a successful insert or update. # Return ``None`` if there were errors. # """ # raise NotImplementedError("This method needs to be implemented by " # "the inheriting class") # # def get_post_by_id(self, post_id): # """ # Fetch the blog post given by ``post_id`` # # :param post_id: The post identifier for the blog post # :type post_id: int # :return: If the ``post_id`` is valid, the post data is retrieved, # else returns ``None``. # """ # raise NotImplementedError("This method needs to be implemented by the " # "inheriting class") # # def get_posts(self, count=10, offset=0, recent=True, tag=None, # user_id=None, include_draft=False): # """ # Get posts given by filter criteria # # :param count: The number of posts to retrieve (default 10). If count # is ``None``, all posts are returned. # :type count: int # :param offset: The number of posts to offset (default 0) # :type offset: int # :param recent: Order by recent posts or not # :type recent: bool # :param tag: Filter by a specific tag # :type tag: str # :param user_id: Filter by a specific user # :type user_id: str # :param include_draft: Whether to include posts marked as draft or not # :type include_draft: bool # # :return: A list of posts, with each element a dict containing values # for the following keys: (title, text, draft, post_date, # last_modified_date). If count is ``None``, then all the posts are # returned. # """ # raise NotImplementedError("This method needs to be implemented by the " # "inheriting class") # # def count_posts(self, tag=None, user_id=None, include_draft=False): # """ # Returns the total number of posts for the give filter # # :param tag: Filter by a specific tag # :type tag: str # :param user_id: Filter by a specific user # :type user_id: str # :param include_draft: Whether to include posts marked as draft or not # :type include_draft: bool # :return: The number of posts for the given filter. # """ # raise NotImplementedError("This method needs to be implemented by the " # "inheriting class") # # def delete_post(self, post_id): # """ # Delete the post defined by ``post_id`` # # :param post_id: The identifier corresponding to a post # :type post_id: int # :return: Returns True if the post was successfully deleted and False # otherwise. # """ # raise NotImplementedError("This method needs to be implemented by the " # "inheriting class") # # @classmethod # def normalize_tags(cls, tags): # return [cls.normalize_tag(tag) for tag in tags] # # @staticmethod # def normalize_tag(tag): # return tag.upper().strip() # # Path: flask_blogging/signals.py . Output only the next line.
this = sys.modules[__name__]
Using the snippet: <|code_start|>try: except ImportError: pass this = sys.modules[__name__] this.Post = None this.Tag = None def _as_int(s): try: n = int(s) if s is not None else None return n except ValueError: <|code_end|> , determine the next line of code. You have imports: from builtins import str from collections import defaultdict, OrderedDict from sqlalchemy.ext.automap import automap_base from .storage import Storage from .signals import sqla_initialized import sys import logging import sqlalchemy as sqla import datetime and context (class names, function names, or code) available: # Path: flask_blogging/storage.py # class Storage(object): # # def save_post(self, title, text, user_id, tags, draft=False, # post_date=None, last_modified_date=None, meta_data=None, # post_id=None): # """ # Persist the blog post data. If ``post_id`` is ``None`` or ``post_id`` # is invalid, the post must be inserted into the storage. If ``post_id`` # is a valid id, then the data must be updated. # # :param title: The title of the blog post # :type title: str # :param text: The text of the blog post # :type text: str # :param user_id: The user identifier # :type user_id: str # :param tags: A list of tags # :type tags: list # :param draft: If the post is a draft of if needs to be published. # :type draft: bool # :param post_date: (Optional) The date the blog was posted (default # datetime.datetime.utcnow()) # :type post_date: datetime.datetime # :param last_modified_date: (Optional) The date when blog was last # modified (default datetime.datetime.utcnow()) # :type last_modified_date: datetime.datetime # :param meta_data: The meta data for the blog post # :type meta_data: dict # :param post_id: The post identifier. This should be ``None`` for an # insert call, and a valid value for update. # :type post_id: int # # :return: The post_id value, in case of a successful insert or update. # Return ``None`` if there were errors. # """ # raise NotImplementedError("This method needs to be implemented by " # "the inheriting class") # # def get_post_by_id(self, post_id): # """ # Fetch the blog post given by ``post_id`` # # :param post_id: The post identifier for the blog post # :type post_id: int # :return: If the ``post_id`` is valid, the post data is retrieved, # else returns ``None``. # """ # raise NotImplementedError("This method needs to be implemented by the " # "inheriting class") # # def get_posts(self, count=10, offset=0, recent=True, tag=None, # user_id=None, include_draft=False): # """ # Get posts given by filter criteria # # :param count: The number of posts to retrieve (default 10). If count # is ``None``, all posts are returned. # :type count: int # :param offset: The number of posts to offset (default 0) # :type offset: int # :param recent: Order by recent posts or not # :type recent: bool # :param tag: Filter by a specific tag # :type tag: str # :param user_id: Filter by a specific user # :type user_id: str # :param include_draft: Whether to include posts marked as draft or not # :type include_draft: bool # # :return: A list of posts, with each element a dict containing values # for the following keys: (title, text, draft, post_date, # last_modified_date). If count is ``None``, then all the posts are # returned. # """ # raise NotImplementedError("This method needs to be implemented by the " # "inheriting class") # # def count_posts(self, tag=None, user_id=None, include_draft=False): # """ # Returns the total number of posts for the give filter # # :param tag: Filter by a specific tag # :type tag: str # :param user_id: Filter by a specific user # :type user_id: str # :param include_draft: Whether to include posts marked as draft or not # :type include_draft: bool # :return: The number of posts for the given filter. # """ # raise NotImplementedError("This method needs to be implemented by the " # "inheriting class") # # def delete_post(self, post_id): # """ # Delete the post defined by ``post_id`` # # :param post_id: The identifier corresponding to a post # :type post_id: int # :return: Returns True if the post was successfully deleted and False # otherwise. # """ # raise NotImplementedError("This method needs to be implemented by the " # "inheriting class") # # @classmethod # def normalize_tags(cls, tags): # return [cls.normalize_tag(tag) for tag in tags] # # @staticmethod # def normalize_tag(tag): # return tag.upper().strip() # # Path: flask_blogging/signals.py . Output only the next line.
return None
Given the following code snippet before the placeholder: <|code_start|> { 'AttributeName': 'post_id', 'AttributeType': 'S' }, { 'AttributeName': 'user_id', 'AttributeType': 'S' }, { 'AttributeName': 'post_date', 'AttributeType': 'S' }, { 'AttributeName': 'draft', 'AttributeType': 'N' }, ], ProvisionedThroughput={ 'ReadCapacityUnits': 10, 'WriteCapacityUnits': 10 } ) self._blog_posts_table = self._db.Table(bp_table_name) def _create_tag_posts_table(self, table_names): tp_table_name = self._table_name("tag_posts") if tp_table_name not in table_names: self._client.create_table( TableName=tp_table_name, KeySchema=[{ <|code_end|> , predict the next line using imports from the current file: import logging import boto3 import datetime import copy from .storage import Storage from boto3.dynamodb.conditions import Key from shortuuid import ShortUUID and context including class names, function names, and sometimes code from other files: # Path: flask_blogging/storage.py # class Storage(object): # # def save_post(self, title, text, user_id, tags, draft=False, # post_date=None, last_modified_date=None, meta_data=None, # post_id=None): # """ # Persist the blog post data. If ``post_id`` is ``None`` or ``post_id`` # is invalid, the post must be inserted into the storage. If ``post_id`` # is a valid id, then the data must be updated. # # :param title: The title of the blog post # :type title: str # :param text: The text of the blog post # :type text: str # :param user_id: The user identifier # :type user_id: str # :param tags: A list of tags # :type tags: list # :param draft: If the post is a draft of if needs to be published. # :type draft: bool # :param post_date: (Optional) The date the blog was posted (default # datetime.datetime.utcnow()) # :type post_date: datetime.datetime # :param last_modified_date: (Optional) The date when blog was last # modified (default datetime.datetime.utcnow()) # :type last_modified_date: datetime.datetime # :param meta_data: The meta data for the blog post # :type meta_data: dict # :param post_id: The post identifier. This should be ``None`` for an # insert call, and a valid value for update. # :type post_id: int # # :return: The post_id value, in case of a successful insert or update. # Return ``None`` if there were errors. # """ # raise NotImplementedError("This method needs to be implemented by " # "the inheriting class") # # def get_post_by_id(self, post_id): # """ # Fetch the blog post given by ``post_id`` # # :param post_id: The post identifier for the blog post # :type post_id: int # :return: If the ``post_id`` is valid, the post data is retrieved, # else returns ``None``. # """ # raise NotImplementedError("This method needs to be implemented by the " # "inheriting class") # # def get_posts(self, count=10, offset=0, recent=True, tag=None, # user_id=None, include_draft=False): # """ # Get posts given by filter criteria # # :param count: The number of posts to retrieve (default 10). If count # is ``None``, all posts are returned. # :type count: int # :param offset: The number of posts to offset (default 0) # :type offset: int # :param recent: Order by recent posts or not # :type recent: bool # :param tag: Filter by a specific tag # :type tag: str # :param user_id: Filter by a specific user # :type user_id: str # :param include_draft: Whether to include posts marked as draft or not # :type include_draft: bool # # :return: A list of posts, with each element a dict containing values # for the following keys: (title, text, draft, post_date, # last_modified_date). If count is ``None``, then all the posts are # returned. # """ # raise NotImplementedError("This method needs to be implemented by the " # "inheriting class") # # def count_posts(self, tag=None, user_id=None, include_draft=False): # """ # Returns the total number of posts for the give filter # # :param tag: Filter by a specific tag # :type tag: str # :param user_id: Filter by a specific user # :type user_id: str # :param include_draft: Whether to include posts marked as draft or not # :type include_draft: bool # :return: The number of posts for the given filter. # """ # raise NotImplementedError("This method needs to be implemented by the " # "inheriting class") # # def delete_post(self, post_id): # """ # Delete the post defined by ``post_id`` # # :param post_id: The identifier corresponding to a post # :type post_id: int # :return: Returns True if the post was successfully deleted and False # otherwise. # """ # raise NotImplementedError("This method needs to be implemented by the " # "inheriting class") # # @classmethod # def normalize_tags(cls, tags): # return [cls.normalize_tag(tag) for tag in tags] # # @staticmethod # def normalize_tag(tag): # return tag.upper().strip() . Output only the next line.
'AttributeName': 'tag_id',
Here is a snippet: <|code_start|> <div> <div> <div>selected</div> </div> </div> <!-- comment --> <div>not selected</div> <p>not selected</p>""" expected = expected_result(""" <div> <div> selected </div> </div> <div> selected </div>""") assert query_html_doc(html_body, '/html/body/div/descendant::div') == expected assert query_html_doc(html_body, '/html/body/div/~::div') == expected def test_descendant_or_self_axis_returns_all_descendants_and_context_node_if_it_matches_node_test(): html_body = """ <div> <div>foo</div> </div> <div>bar</div>""" assert query_html_doc(html_body, '/html/body/descendant-or-self::div') == expected_result(""" <div> <|code_end|> . Write the next line using the current file imports: import os import re import sys from hq.hquery.syntax_error import HquerySyntaxError from pytest import raises from ..common_test_util import expected_result from test.hquery.hquery_test_util import query_html_doc and context from other files: # Path: hq/hquery/syntax_error.py # class HquerySyntaxError(ValueError): # pass # # Path: test/common_test_util.py # def expected_result(contents): # return dedent(contents.lstrip('\n')) # # Path: test/hquery/hquery_test_util.py # def query_html_doc(html_body, hquery, preserve_space=False, wrap_body=True): # soup = soup_with_body(html_body) if wrap_body else make_soup(html_body) # raw_result = HqueryProcessor(hquery, preserve_space=preserve_space).query(soup) # return eliminate_blank_lines(convert_results_to_output_text(raw_result, preserve_space=preserve_space).strip()) , which may include functions, classes, or code. Output only the next line.
<div>
Predict the next line for this snippet: <|code_start|> <div> <div> selected </div> </div> <div> selected </div>""") assert query_html_doc(html_body, '/html/body/div/descendant::div') == expected assert query_html_doc(html_body, '/html/body/div/~::div') == expected def test_descendant_or_self_axis_returns_all_descendants_and_context_node_if_it_matches_node_test(): html_body = """ <div> <div>foo</div> </div> <div>bar</div>""" assert query_html_doc(html_body, '/html/body/descendant-or-self::div') == expected_result(""" <div> <div> foo </div> </div> <div> foo </div> <div> bar <|code_end|> with the help of current file imports: import os import re import sys from hq.hquery.syntax_error import HquerySyntaxError from pytest import raises from ..common_test_util import expected_result from test.hquery.hquery_test_util import query_html_doc and context from other files: # Path: hq/hquery/syntax_error.py # class HquerySyntaxError(ValueError): # pass # # Path: test/common_test_util.py # def expected_result(contents): # return dedent(contents.lstrip('\n')) # # Path: test/hquery/hquery_test_util.py # def query_html_doc(html_body, hquery, preserve_space=False, wrap_body=True): # soup = soup_with_body(html_body) if wrap_body else make_soup(html_body) # raw_result = HqueryProcessor(hquery, preserve_space=preserve_space).query(soup) # return eliminate_blank_lines(convert_results_to_output_text(raw_result, preserve_space=preserve_space).strip()) , which may contain function names, class names, or code. Output only the next line.
</div>""")
Predict the next line for this snippet: <|code_start|> <p> daughter </p> </div>""") def test_parent_axis_returns_parents_for_multiple_matching_nodes(): html_body = """ <div id="first"> <p> </p> </div> <div id="second"> <p> </p> </div>""" assert query_html_doc(html_body, '//p/parent::*') == expected_result(html_body) def test_parent_axis_produces_nothing_for_root_element(): assert query_html_doc('', '/html/parent::*') == expected_result('') assert query_html_doc('<div></div>', 'div/parent::*', wrap_body=False) == expected_result('') def test_ancestor_axis_selects_all_matching_ancestors(): html_body = """ <div> <section> <div> <p>text</p> <|code_end|> with the help of current file imports: import os import re import sys from hq.hquery.syntax_error import HquerySyntaxError from pytest import raises from ..common_test_util import expected_result from test.hquery.hquery_test_util import query_html_doc and context from other files: # Path: hq/hquery/syntax_error.py # class HquerySyntaxError(ValueError): # pass # # Path: test/common_test_util.py # def expected_result(contents): # return dedent(contents.lstrip('\n')) # # Path: test/hquery/hquery_test_util.py # def query_html_doc(html_body, hquery, preserve_space=False, wrap_body=True): # soup = soup_with_body(html_body) if wrap_body else make_soup(html_body) # raw_result = HqueryProcessor(hquery, preserve_space=preserve_space).query(soup) # return eliminate_blank_lines(convert_results_to_output_text(raw_result, preserve_space=preserve_space).strip()) , which may contain function names, class names, or code. Output only the next line.
</div>
Given the code snippet: <|code_start|> actual_without = query_context_node(html_without, 'child::para[position()=5][attribute::type="warning"]') assert actual_with == expected_result(""" <para type="warning"> para five </para>""") assert actual_without == expected_result('') def test_selects_the_chapter_children_of_the_context_node_that_have_one_or_more_title_children_with_string_value_equal_to_Introduction(): html = """ <context> <chapter>No Title</chapter> <chapter> <title>Wrong Title</title> </chapter> <chapter> <title>Introduction</title> </chapter> </context>""" assert query_context_node(html, "child::chapter[child::title='Introduction']") == expected_result(""" <chapter> <title> Introduction </title> </chapter>""") def test_selects_the_chapter_children_of_the_context_node_that_have_one_or_more_title_children(): html = """ <|code_end|> , generate the next line using the imports in this file: import os import sys from hq.soup_util import make_soup from ..common_test_util import expected_result from test.hquery.hquery_test_util import query_html_doc, query_context_node and context (functions, classes, or occasionally code) from other files: # Path: hq/soup_util.py # def make_soup(source): # soup = BeautifulSoup(source, 'html.parser') # counter = [0] # # def visit_node(node): # node.hq_doc_index = counter[0] # counter[0] += 1 # if is_tag_node(node): # attr_names = sorted(node.attrs.keys(), key=lambda name: name.lower()) # node.hq_attrs = [AttributeNode(name, node.attrs[name]) for name in attr_names] # for attr in node.hq_attrs: # visit_node(attr) # # preorder_traverse_node_tree(soup, visit_node, filter=is_any_node) # verbose_print('Loaded HTML document containing {0} indexed nodes.'.format(counter[0])) # return soup # # Path: test/common_test_util.py # def expected_result(contents): # return dedent(contents.lstrip('\n')) # # Path: test/hquery/hquery_test_util.py # def query_html_doc(html_body, hquery, preserve_space=False, wrap_body=True): # soup = soup_with_body(html_body) if wrap_body else make_soup(html_body) # raw_result = HqueryProcessor(hquery, preserve_space=preserve_space).query(soup) # return eliminate_blank_lines(convert_results_to_output_text(raw_result, preserve_space=preserve_space).strip()) # # def query_context_node(node_or_source, hquery): # if not is_any_node(node_or_source): # node_or_source = root_tag_from_soup(make_soup(node_or_source)) # raw_result = HqueryProcessor(hquery).query(node_or_source) # return eliminate_blank_lines(convert_results_to_output_text(raw_result).strip()) . Output only the next line.
<context>
Given snippet: <|code_start|> html = """ <root> <notpara/> <para>selected</para> </root>""" soup = make_soup(html) assert query_context_node(soup.root.notpara, '/descendant::para') == expected_result(""" <para> selected </para>""") def test_selects_all_the_item_elements_that_have_an_olist_parent_and_that_are_in_the_same_document_as_the_context_node(): html = """ <root> <notolist/> <olist> <notitem>not selected</notitem> <item>selected</item> <olist> </root>""" soup = make_soup(html) assert query_context_node(soup.root.notolist, '/descendant::olist/child::item') == expected_result(""" <item> selected </item>""") def test_selects_the_first_para_child_of_the_context_node(): html = """ <|code_end|> , continue by predicting the next line. Consider current file imports: import os import sys from hq.soup_util import make_soup from ..common_test_util import expected_result from test.hquery.hquery_test_util import query_html_doc, query_context_node and context: # Path: hq/soup_util.py # def make_soup(source): # soup = BeautifulSoup(source, 'html.parser') # counter = [0] # # def visit_node(node): # node.hq_doc_index = counter[0] # counter[0] += 1 # if is_tag_node(node): # attr_names = sorted(node.attrs.keys(), key=lambda name: name.lower()) # node.hq_attrs = [AttributeNode(name, node.attrs[name]) for name in attr_names] # for attr in node.hq_attrs: # visit_node(attr) # # preorder_traverse_node_tree(soup, visit_node, filter=is_any_node) # verbose_print('Loaded HTML document containing {0} indexed nodes.'.format(counter[0])) # return soup # # Path: test/common_test_util.py # def expected_result(contents): # return dedent(contents.lstrip('\n')) # # Path: test/hquery/hquery_test_util.py # def query_html_doc(html_body, hquery, preserve_space=False, wrap_body=True): # soup = soup_with_body(html_body) if wrap_body else make_soup(html_body) # raw_result = HqueryProcessor(hquery, preserve_space=preserve_space).query(soup) # return eliminate_blank_lines(convert_results_to_output_text(raw_result, preserve_space=preserve_space).strip()) # # def query_context_node(node_or_source, hquery): # if not is_any_node(node_or_source): # node_or_source = root_tag_from_soup(make_soup(node_or_source)) # raw_result = HqueryProcessor(hquery).query(node_or_source) # return eliminate_blank_lines(convert_results_to_output_text(raw_result).strip()) which might include code, classes, or functions. Output only the next line.
<context>
Next line prediction: <|code_start|> selected </item>""") def test_selects_the_first_para_child_of_the_context_node(): html = """ <context> <para>selected</para> <para>not selected</para> </context>""" assert query_context_node(html, 'child::para[position()=1]') == expected_result(""" <para> selected </para>""") def test_selects_the_last_para_child_of_the_context_node(): html = """ <context> <para>not selected</para> <para>selected</para> </context>""" assert query_context_node(html, 'child::para[position()=last()]') == expected_result(""" <para> selected </para>""") def test_selects_the_last_but_one_para_child_of_the_context_node(): html = """ <|code_end|> . Use current file imports: (import os import sys from hq.soup_util import make_soup from ..common_test_util import expected_result from test.hquery.hquery_test_util import query_html_doc, query_context_node) and context including class names, function names, or small code snippets from other files: # Path: hq/soup_util.py # def make_soup(source): # soup = BeautifulSoup(source, 'html.parser') # counter = [0] # # def visit_node(node): # node.hq_doc_index = counter[0] # counter[0] += 1 # if is_tag_node(node): # attr_names = sorted(node.attrs.keys(), key=lambda name: name.lower()) # node.hq_attrs = [AttributeNode(name, node.attrs[name]) for name in attr_names] # for attr in node.hq_attrs: # visit_node(attr) # # preorder_traverse_node_tree(soup, visit_node, filter=is_any_node) # verbose_print('Loaded HTML document containing {0} indexed nodes.'.format(counter[0])) # return soup # # Path: test/common_test_util.py # def expected_result(contents): # return dedent(contents.lstrip('\n')) # # Path: test/hquery/hquery_test_util.py # def query_html_doc(html_body, hquery, preserve_space=False, wrap_body=True): # soup = soup_with_body(html_body) if wrap_body else make_soup(html_body) # raw_result = HqueryProcessor(hquery, preserve_space=preserve_space).query(soup) # return eliminate_blank_lines(convert_results_to_output_text(raw_result, preserve_space=preserve_space).strip()) # # def query_context_node(node_or_source, hquery): # if not is_any_node(node_or_source): # node_or_source = root_tag_from_soup(make_soup(node_or_source)) # raw_result = HqueryProcessor(hquery).query(node_or_source) # return eliminate_blank_lines(convert_results_to_output_text(raw_result).strip()) . Output only the next line.
<context>
Using the snippet: <|code_start|> <context> <para>not selected</para> <foo> <notpara>not selected</notpara> <para>selected</para> </foo> <bar> <para>also selected</para> </bar> </context>""" assert query_context_node(html, 'child::*/child::para') == expected_result(""" <para> selected </para> <para> also selected </para>""") def test_selects_the_document_root_which_is_always_the_parent_of_the_document_element(): html = """ <!-- comment --> <root-tag> </root-tag>""" assert query_context_node(html, '/') == expected_result(html) def test_selects_all_the_para_elements_in_the_same_document_as_the_context_node(): html = """ <root> <|code_end|> , determine the next line of code. You have imports: import os import sys from hq.soup_util import make_soup from ..common_test_util import expected_result from test.hquery.hquery_test_util import query_html_doc, query_context_node and context (class names, function names, or code) available: # Path: hq/soup_util.py # def make_soup(source): # soup = BeautifulSoup(source, 'html.parser') # counter = [0] # # def visit_node(node): # node.hq_doc_index = counter[0] # counter[0] += 1 # if is_tag_node(node): # attr_names = sorted(node.attrs.keys(), key=lambda name: name.lower()) # node.hq_attrs = [AttributeNode(name, node.attrs[name]) for name in attr_names] # for attr in node.hq_attrs: # visit_node(attr) # # preorder_traverse_node_tree(soup, visit_node, filter=is_any_node) # verbose_print('Loaded HTML document containing {0} indexed nodes.'.format(counter[0])) # return soup # # Path: test/common_test_util.py # def expected_result(contents): # return dedent(contents.lstrip('\n')) # # Path: test/hquery/hquery_test_util.py # def query_html_doc(html_body, hquery, preserve_space=False, wrap_body=True): # soup = soup_with_body(html_body) if wrap_body else make_soup(html_body) # raw_result = HqueryProcessor(hquery, preserve_space=preserve_space).query(soup) # return eliminate_blank_lines(convert_results_to_output_text(raw_result, preserve_space=preserve_space).strip()) # # def query_context_node(node_or_source, hquery): # if not is_any_node(node_or_source): # node_or_source = root_tag_from_soup(make_soup(node_or_source)) # raw_result = HqueryProcessor(hquery).query(node_or_source) # return eliminate_blank_lines(convert_results_to_output_text(raw_result).strip()) . Output only the next line.
<notpara/>
Predict the next line for this snippet: <|code_start|> exports = ('class_', 'even', 'odd') def class_(*args): if len(args) == 1: tag = get_context_node() name = args[0] elif len(args) == 2: HqueryEvaluationError.must_be_node_set(args[0]) tag = args[0][0] name = args[1] else: raise HqueryEvaluationError('class() expects one or two arguments; got {0}'.format(len(args))) return boolean(name in tag['class']) def even(): return boolean(peek_context().position % 2 == 0) <|code_end|> with the help of current file imports: from hq.hquery.evaluation_error import HqueryEvaluationError from hq.hquery.expression_context import get_context_node, peek_context from hq.hquery.functions.core_boolean import boolean and context from other files: # Path: hq/hquery/evaluation_error.py # class HqueryEvaluationError(RuntimeError): # # @classmethod # def must_be_node_set(cls, obj): # if not is_node_set(obj): # raise HqueryEvaluationError('Expected a node set, but found a(n) {0}'.format(obj.__class__.__name__)) # # @classmethod # def must_be_node_set_or_sequence(cls, obj): # if not (is_node_set(obj) or is_sequence(obj)): # raise HqueryEvaluationError('Expected a node set or sequence, but found a(n) {0}'.format( # obj.__class__.__name__ # )) # # Path: hq/hquery/expression_context.py # def get_context_node(): # return peek_context().node # # def peek_context(): # try: # return context_stack[-1] # except IndexError: # raise ExpressionStackEmptyError('tried to peek while expression stack was empty') # # Path: hq/hquery/functions/core_boolean.py # class boolean: # # def __init__(self, obj): # if is_node_set(obj): # self.value = len(obj) > 0 # elif is_number(obj): # f = float(obj) # self.value = bool(f) and not isnan(f) # else: # self.value = bool(obj) # # def __bool__(self): # return self.value # # def __nonzero__(self): # return self.__bool__() # # def __str__(self): # return str(self.value).lower() # # def __eq__(self, other): # return is_boolean(other) and self.value == other.value # # def __repr__(self): # return 'boolean({0})'.format(self.value) , which may contain function names, class names, or code. Output only the next line.
def odd():
Given the following code snippet before the placeholder: <|code_start|> raise HqueryEvaluationError('replace() expects 3 or 4 arguments; was passed {0}'.format(argc)) input = string_value(args[0]) pattern = args[1] replacement = args[2] if argc == 4: flags = _xpath_flags_to_re_flags(args[3]) else: flags = 0 return re.sub(pattern, replacement, input, flags=flags) def string_join(sequence, *args): if len(args) > 0: delimiter = args[0] else: delimiter = '' return delimiter.join([string_value(x) for x in sequence]) def tokenize(*args): argc = len(args) if argc < 2 or argc > 3: raise HqueryEvaluationError('replace() expects 2 or 3 arguments; was passed {0}'.format(argc)) input = string_value(args[0]) pattern = args[1] if argc == 3: flags = _xpath_flags_to_re_flags(args[2]) <|code_end|> , predict the next line using imports from the current file: import re from hq.hquery.evaluation_error import HqueryEvaluationError from hq.hquery.expression_context import get_context_node from hq.hquery.functions.core_boolean import boolean from hq.hquery.object_type import string_value and context including class names, function names, and sometimes code from other files: # Path: hq/hquery/evaluation_error.py # class HqueryEvaluationError(RuntimeError): # # @classmethod # def must_be_node_set(cls, obj): # if not is_node_set(obj): # raise HqueryEvaluationError('Expected a node set, but found a(n) {0}'.format(obj.__class__.__name__)) # # @classmethod # def must_be_node_set_or_sequence(cls, obj): # if not (is_node_set(obj) or is_sequence(obj)): # raise HqueryEvaluationError('Expected a node set or sequence, but found a(n) {0}'.format( # obj.__class__.__name__ # )) # # Path: hq/hquery/expression_context.py # def get_context_node(): # return peek_context().node # # Path: hq/hquery/functions/core_boolean.py # class boolean: # # def __init__(self, obj): # if is_node_set(obj): # self.value = len(obj) > 0 # elif is_number(obj): # f = float(obj) # self.value = bool(f) and not isnan(f) # else: # self.value = bool(obj) # # def __bool__(self): # return self.value # # def __nonzero__(self): # return self.__bool__() # # def __str__(self): # return str(self.value).lower() # # def __eq__(self, other): # return is_boolean(other) and self.value == other.value # # def __repr__(self): # return 'boolean({0})'.format(self.value) # # Path: hq/hquery/object_type.py # def string_value(obj): # if is_tag_node(obj) or is_attribute_node(obj) or is_text_node(obj): # return derive_text_from_node(obj, peek_context().preserve_space) # elif is_number(obj) or is_boolean(obj): # return str(obj) # elif is_node_set(obj): # return string_value(obj[0]) if len(obj) > 0 else '' # elif is_sequence(obj): # return ''.join(string_value(item) for item in obj) # elif is_string(obj): # return obj # else: # raise NotImplementedError('string_value not implemented for type "{0}"'.format(obj.__class__.__name__)) . Output only the next line.
else:
Given the following code snippet before the placeholder: <|code_start|> return re.sub(pattern, replacement, input, flags=flags) def string_join(sequence, *args): if len(args) > 0: delimiter = args[0] else: delimiter = '' return delimiter.join([string_value(x) for x in sequence]) def tokenize(*args): argc = len(args) if argc < 2 or argc > 3: raise HqueryEvaluationError('replace() expects 2 or 3 arguments; was passed {0}'.format(argc)) input = string_value(args[0]) pattern = args[1] if argc == 3: flags = _xpath_flags_to_re_flags(args[2]) else: flags = 0 return re.split(pattern, input, flags=flags) def upper_case(value): return string_value(value).upper() <|code_end|> , predict the next line using imports from the current file: import re from hq.hquery.evaluation_error import HqueryEvaluationError from hq.hquery.expression_context import get_context_node from hq.hquery.functions.core_boolean import boolean from hq.hquery.object_type import string_value and context including class names, function names, and sometimes code from other files: # Path: hq/hquery/evaluation_error.py # class HqueryEvaluationError(RuntimeError): # # @classmethod # def must_be_node_set(cls, obj): # if not is_node_set(obj): # raise HqueryEvaluationError('Expected a node set, but found a(n) {0}'.format(obj.__class__.__name__)) # # @classmethod # def must_be_node_set_or_sequence(cls, obj): # if not (is_node_set(obj) or is_sequence(obj)): # raise HqueryEvaluationError('Expected a node set or sequence, but found a(n) {0}'.format( # obj.__class__.__name__ # )) # # Path: hq/hquery/expression_context.py # def get_context_node(): # return peek_context().node # # Path: hq/hquery/functions/core_boolean.py # class boolean: # # def __init__(self, obj): # if is_node_set(obj): # self.value = len(obj) > 0 # elif is_number(obj): # f = float(obj) # self.value = bool(f) and not isnan(f) # else: # self.value = bool(obj) # # def __bool__(self): # return self.value # # def __nonzero__(self): # return self.__bool__() # # def __str__(self): # return str(self.value).lower() # # def __eq__(self, other): # return is_boolean(other) and self.value == other.value # # def __repr__(self): # return 'boolean({0})'.format(self.value) # # Path: hq/hquery/object_type.py # def string_value(obj): # if is_tag_node(obj) or is_attribute_node(obj) or is_text_node(obj): # return derive_text_from_node(obj, peek_context().preserve_space) # elif is_number(obj) or is_boolean(obj): # return str(obj) # elif is_node_set(obj): # return string_value(obj[0]) if len(obj) > 0 else '' # elif is_sequence(obj): # return ''.join(string_value(item) for item in obj) # elif is_string(obj): # return obj # else: # raise NotImplementedError('string_value not implemented for type "{0}"'.format(obj.__class__.__name__)) . Output only the next line.
def _xpath_flags_to_re_flags(flags):
Given the following code snippet before the placeholder: <|code_start|> input = string_value(get_context_node()) pattern = args[0] else: input = string_value(args[0]) pattern = args[1] if scenario == 3: flags = _xpath_flags_to_re_flags(args[2]) return boolean(re.search(pattern, input, flags)) def replace(*args): argc = len(args) if argc < 3 or argc > 4: raise HqueryEvaluationError('replace() expects 3 or 4 arguments; was passed {0}'.format(argc)) input = string_value(args[0]) pattern = args[1] replacement = args[2] if argc == 4: flags = _xpath_flags_to_re_flags(args[3]) else: flags = 0 return re.sub(pattern, replacement, input, flags=flags) def string_join(sequence, *args): if len(args) > 0: delimiter = args[0] <|code_end|> , predict the next line using imports from the current file: import re from hq.hquery.evaluation_error import HqueryEvaluationError from hq.hquery.expression_context import get_context_node from hq.hquery.functions.core_boolean import boolean from hq.hquery.object_type import string_value and context including class names, function names, and sometimes code from other files: # Path: hq/hquery/evaluation_error.py # class HqueryEvaluationError(RuntimeError): # # @classmethod # def must_be_node_set(cls, obj): # if not is_node_set(obj): # raise HqueryEvaluationError('Expected a node set, but found a(n) {0}'.format(obj.__class__.__name__)) # # @classmethod # def must_be_node_set_or_sequence(cls, obj): # if not (is_node_set(obj) or is_sequence(obj)): # raise HqueryEvaluationError('Expected a node set or sequence, but found a(n) {0}'.format( # obj.__class__.__name__ # )) # # Path: hq/hquery/expression_context.py # def get_context_node(): # return peek_context().node # # Path: hq/hquery/functions/core_boolean.py # class boolean: # # def __init__(self, obj): # if is_node_set(obj): # self.value = len(obj) > 0 # elif is_number(obj): # f = float(obj) # self.value = bool(f) and not isnan(f) # else: # self.value = bool(obj) # # def __bool__(self): # return self.value # # def __nonzero__(self): # return self.__bool__() # # def __str__(self): # return str(self.value).lower() # # def __eq__(self, other): # return is_boolean(other) and self.value == other.value # # def __repr__(self): # return 'boolean({0})'.format(self.value) # # Path: hq/hquery/object_type.py # def string_value(obj): # if is_tag_node(obj) or is_attribute_node(obj) or is_text_node(obj): # return derive_text_from_node(obj, peek_context().preserve_space) # elif is_number(obj) or is_boolean(obj): # return str(obj) # elif is_node_set(obj): # return string_value(obj[0]) if len(obj) > 0 else '' # elif is_sequence(obj): # return ''.join(string_value(item) for item in obj) # elif is_string(obj): # return obj # else: # raise NotImplementedError('string_value not implemented for type "{0}"'.format(obj.__class__.__name__)) . Output only the next line.
else:
Continue the code snippet: <|code_start|> if scenario == 1: input = string_value(get_context_node()) pattern = args[0] else: input = string_value(args[0]) pattern = args[1] if scenario == 3: flags = _xpath_flags_to_re_flags(args[2]) return boolean(re.search(pattern, input, flags)) def replace(*args): argc = len(args) if argc < 3 or argc > 4: raise HqueryEvaluationError('replace() expects 3 or 4 arguments; was passed {0}'.format(argc)) input = string_value(args[0]) pattern = args[1] replacement = args[2] if argc == 4: flags = _xpath_flags_to_re_flags(args[3]) else: flags = 0 return re.sub(pattern, replacement, input, flags=flags) def string_join(sequence, *args): if len(args) > 0: <|code_end|> . Use current file imports: import re from hq.hquery.evaluation_error import HqueryEvaluationError from hq.hquery.expression_context import get_context_node from hq.hquery.functions.core_boolean import boolean from hq.hquery.object_type import string_value and context (classes, functions, or code) from other files: # Path: hq/hquery/evaluation_error.py # class HqueryEvaluationError(RuntimeError): # # @classmethod # def must_be_node_set(cls, obj): # if not is_node_set(obj): # raise HqueryEvaluationError('Expected a node set, but found a(n) {0}'.format(obj.__class__.__name__)) # # @classmethod # def must_be_node_set_or_sequence(cls, obj): # if not (is_node_set(obj) or is_sequence(obj)): # raise HqueryEvaluationError('Expected a node set or sequence, but found a(n) {0}'.format( # obj.__class__.__name__ # )) # # Path: hq/hquery/expression_context.py # def get_context_node(): # return peek_context().node # # Path: hq/hquery/functions/core_boolean.py # class boolean: # # def __init__(self, obj): # if is_node_set(obj): # self.value = len(obj) > 0 # elif is_number(obj): # f = float(obj) # self.value = bool(f) and not isnan(f) # else: # self.value = bool(obj) # # def __bool__(self): # return self.value # # def __nonzero__(self): # return self.__bool__() # # def __str__(self): # return str(self.value).lower() # # def __eq__(self, other): # return is_boolean(other) and self.value == other.value # # def __repr__(self): # return 'boolean({0})'.format(self.value) # # Path: hq/hquery/object_type.py # def string_value(obj): # if is_tag_node(obj) or is_attribute_node(obj) or is_text_node(obj): # return derive_text_from_node(obj, peek_context().preserve_space) # elif is_number(obj) or is_boolean(obj): # return str(obj) # elif is_node_set(obj): # return string_value(obj[0]) if len(obj) > 0 else '' # elif is_sequence(obj): # return ''.join(string_value(item) for item in obj) # elif is_string(obj): # return obj # else: # raise NotImplementedError('string_value not implemented for type "{0}"'.format(obj.__class__.__name__)) . Output only the next line.
delimiter = args[0]
Predict the next line after this snippet: <|code_start|> def test_union_decomposition_with_parentheses(): html_body = """ <h1>heading</h1> <p>content</p> <h1>another heading</h1>""" assert query_html_doc(html_body, '(//h1 | //p) => ("fizz" | "buzz")') == expected_result(""" fizz buzz fizz""") def test_union_decomposition_naked(): html_body = """ <h1>heading</h1> <p>content</p> <h1>another heading</h1>""" assert query_html_doc(html_body, '(//h1 | //p) => `h1 $_` | `p $_`') == expected_result(""" <|code_end|> using the current file's imports: from test.common_test_util import expected_result from test.hquery.hquery_test_util import query_html_doc and any relevant context from other files: # Path: test/common_test_util.py # def expected_result(contents): # return dedent(contents.lstrip('\n')) # # Path: test/hquery/hquery_test_util.py # def query_html_doc(html_body, hquery, preserve_space=False, wrap_body=True): # soup = soup_with_body(html_body) if wrap_body else make_soup(html_body) # raw_result = HqueryProcessor(hquery, preserve_space=preserve_space).query(soup) # return eliminate_blank_lines(convert_results_to_output_text(raw_result, preserve_space=preserve_space).strip()) . Output only the next line.
h1 heading
Continue the code snippet: <|code_start|> <h1>heading</h1> <p>content</p> <h1>another heading</h1>""" assert query_html_doc(html_body, '(//h1 | //p) => ("fizz" | "buzz")') == expected_result(""" fizz buzz fizz""") def test_union_decomposition_naked(): html_body = """ <h1>heading</h1> <p>content</p> <h1>another heading</h1>""" assert query_html_doc(html_body, '(//h1 | //p) => `h1 $_` | `p $_`') == expected_result(""" h1 heading p content h1 another heading""") def test_union_decomposition_applies_first_matching_clause(): html_body = """ <div>div1</div> <p>p1</p> <div> <p>p2</p> </div>""" query = '(//p | /html/body/div | /html/body//*) => "one" | "two" | "three"' assert query_html_doc(html_body, query) == expected_result(""" two <|code_end|> . Use current file imports: from test.common_test_util import expected_result from test.hquery.hquery_test_util import query_html_doc and context (classes, functions, or code) from other files: # Path: test/common_test_util.py # def expected_result(contents): # return dedent(contents.lstrip('\n')) # # Path: test/hquery/hquery_test_util.py # def query_html_doc(html_body, hquery, preserve_space=False, wrap_body=True): # soup = soup_with_body(html_body) if wrap_body else make_soup(html_body) # raw_result = HqueryProcessor(hquery, preserve_space=preserve_space).query(soup) # return eliminate_blank_lines(convert_results_to_output_text(raw_result, preserve_space=preserve_space).strip()) . Output only the next line.
one
Continue the code snippet: <|code_start|> context_stack = [] class ExpressionContext: def __init__(self, node, position=1, size=1, preserve_space=None): self.node = node self.position = position self.size = size if preserve_space is not None: self.preserve_space = preserve_space else: try: self.preserve_space = peek_context().preserve_space <|code_end|> . Use current file imports: from hq.verbosity import verbose_print from ..soup_util import debug_dump_node and context (classes, functions, or code) from other files: # Path: hq/verbosity.py # def verbose_print(text, indent_after=False, outdent_before=False): # if settings.VERBOSE: # if outdent_before: # pop_indent() # if not is_a_string(text): # text = text() # print(u'{0}{1}'.format(' ' * indent_level, text), file=sys.stderr) # if indent_after: # push_indent() # # Path: hq/soup_util.py # def debug_dump_node(obj): # if is_root_node(obj): # return 'ROOT DOCUMENT' # elif is_tag_node(obj): # return u'ELEMENT {0}'.format(debug_dump_long_string(str(obj))) # elif is_attribute_node(obj): # return 'ATTRIBUTE {0}="{1}"'.format(obj.name, debug_dump_long_string(obj.value)) # elif is_text_node(obj): # return u'TEXT "{0}"'.format(debug_dump_long_string(obj.string)) # elif is_comment_node(obj): # return u'COMMENT "{0}"'.format(debug_dump_long_string(obj.string)) # else: # return 'NODE type {0}'.format(obj.__class__.__name__) . Output only the next line.
except ExpressionStackEmptyError:
Given the following code snippet before the placeholder: <|code_start|>class ExpressionContext: def __init__(self, node, position=1, size=1, preserve_space=None): self.node = node self.position = position self.size = size if preserve_space is not None: self.preserve_space = preserve_space else: try: self.preserve_space = peek_context().preserve_space except ExpressionStackEmptyError: self.preserve_space = False def __str__(self): return 'context(node={0})'.format(str(self.node)) class ExpressionStackEmptyError(RuntimeError): pass def get_context_node(): return peek_context().node def peek_context(): try: return context_stack[-1] <|code_end|> , predict the next line using imports from the current file: from hq.verbosity import verbose_print from ..soup_util import debug_dump_node and context including class names, function names, and sometimes code from other files: # Path: hq/verbosity.py # def verbose_print(text, indent_after=False, outdent_before=False): # if settings.VERBOSE: # if outdent_before: # pop_indent() # if not is_a_string(text): # text = text() # print(u'{0}{1}'.format(' ' * indent_level, text), file=sys.stderr) # if indent_after: # push_indent() # # Path: hq/soup_util.py # def debug_dump_node(obj): # if is_root_node(obj): # return 'ROOT DOCUMENT' # elif is_tag_node(obj): # return u'ELEMENT {0}'.format(debug_dump_long_string(str(obj))) # elif is_attribute_node(obj): # return 'ATTRIBUTE {0}="{1}"'.format(obj.name, debug_dump_long_string(obj.value)) # elif is_text_node(obj): # return u'TEXT "{0}"'.format(debug_dump_long_string(obj.string)) # elif is_comment_node(obj): # return u'COMMENT "{0}"'.format(debug_dump_long_string(obj.string)) # else: # return 'NODE type {0}'.format(obj.__class__.__name__) . Output only the next line.
except IndexError:
Continue the code snippet: <|code_start|> self.return_expression = None self.sequence_expression = None self.sequence_variable = None def __str__(self): return '{0}{1}return <expr>'.format( '' if self.sequence_expression is None else 'for ${0}:=<expr> '.format(self.sequence_variable), (' '.join('let ${0} := <expr>'.format(v[0]) for v in self.per_iteration_variables) + ' ') if len(self.per_iteration_variables) else '' ) def append_let(self, variable_name, expression_fn): var_tuple = (variable_name, expression_fn) if self.sequence_expression is None: self.global_variables.append(var_tuple) else: self.per_iteration_variables.append(var_tuple) def debug_dump(self): return debug_dump_long_string(str(self)) def evaluate(self): verbose_print('Evaluating FLWOR {0}'.format(self), indent_after=True) if self.sequence_expression is not None: result = self._evaluate_iteration() else: <|code_end|> . Use current file imports: from hq.hquery.object_type import debug_dump_anything from hq.hquery.sequences import make_sequence, sequence_concat from hq.hquery.syntax_error import HquerySyntaxError from hq.hquery.variables import push_variable, variable_scope from hq.soup_util import debug_dump_long_string from hq.verbosity import verbose_print and context (classes, functions, or code) from other files: # Path: hq/hquery/object_type.py # def debug_dump_anything(obj): # if is_any_node(obj): # result = debug_dump_node(obj) # elif is_boolean(obj) or is_number(obj) or is_hash(obj) or is_array(obj): # result = repr(obj) # elif is_string(obj): # result = u'string("{0}")'.format(obj) # elif is_node_set(obj): # result = u'node-set({0})'.format(', '.join(truncate_string(debug_dump_node(node), 20) for node in obj)) # elif is_sequence(obj): # result = u'sequence({0})'.format(', '.join(truncate_string(debug_dump_anything(item), 20) for item in obj)) # else: # raise RuntimeError("debug_dump_anything doesn't know how to handle {0}".format(obj.__class__.__name__)) # return debug_dump_long_string(result) # # Path: hq/hquery/sequences.py # def make_sequence(sequence): # if not isinstance(sequence, list): # sequence = [sequence] # return sequence # # def sequence_concat(first, second): # first = make_sequence(first) # first.extend(make_sequence(second)) # return first # # Path: hq/hquery/syntax_error.py # class HquerySyntaxError(ValueError): # pass # # Path: hq/hquery/variables.py # def push_variable(name, value): # global variable_stack # verbose_print(lambda: u'Pushing variable onto stack: let ${0} := {1}'.format(name, debug_dump_anything(value))) # variable_stack.append((name, value)) # # class variable_scope: # def __enter__(self): # self.mark = len(variable_stack) # # def __exit__(self, *args): # del variable_stack[self.mark:] # # Path: hq/soup_util.py # def debug_dump_long_string(s, length=50, one_line=True, suffix='...'): # return truncate_string(s, length, one_line, suffix) # # Path: hq/verbosity.py # def verbose_print(text, indent_after=False, outdent_before=False): # if settings.VERBOSE: # if outdent_before: # pop_indent() # if not is_a_string(text): # text = text() # print(u'{0}{1}'.format(' ' * indent_level, text), file=sys.stderr) # if indent_after: # push_indent() . Output only the next line.
result = self._evaluate_without_iteration()
Given snippet: <|code_start|> class Flwor: def __init__(self): self.global_variables = [] self.per_iteration_variables = [] self.return_expression = None self.sequence_expression = None self.sequence_variable = None def __str__(self): <|code_end|> , continue by predicting the next line. Consider current file imports: from hq.hquery.object_type import debug_dump_anything from hq.hquery.sequences import make_sequence, sequence_concat from hq.hquery.syntax_error import HquerySyntaxError from hq.hquery.variables import push_variable, variable_scope from hq.soup_util import debug_dump_long_string from hq.verbosity import verbose_print and context: # Path: hq/hquery/object_type.py # def debug_dump_anything(obj): # if is_any_node(obj): # result = debug_dump_node(obj) # elif is_boolean(obj) or is_number(obj) or is_hash(obj) or is_array(obj): # result = repr(obj) # elif is_string(obj): # result = u'string("{0}")'.format(obj) # elif is_node_set(obj): # result = u'node-set({0})'.format(', '.join(truncate_string(debug_dump_node(node), 20) for node in obj)) # elif is_sequence(obj): # result = u'sequence({0})'.format(', '.join(truncate_string(debug_dump_anything(item), 20) for item in obj)) # else: # raise RuntimeError("debug_dump_anything doesn't know how to handle {0}".format(obj.__class__.__name__)) # return debug_dump_long_string(result) # # Path: hq/hquery/sequences.py # def make_sequence(sequence): # if not isinstance(sequence, list): # sequence = [sequence] # return sequence # # def sequence_concat(first, second): # first = make_sequence(first) # first.extend(make_sequence(second)) # return first # # Path: hq/hquery/syntax_error.py # class HquerySyntaxError(ValueError): # pass # # Path: hq/hquery/variables.py # def push_variable(name, value): # global variable_stack # verbose_print(lambda: u'Pushing variable onto stack: let ${0} := {1}'.format(name, debug_dump_anything(value))) # variable_stack.append((name, value)) # # class variable_scope: # def __enter__(self): # self.mark = len(variable_stack) # # def __exit__(self, *args): # del variable_stack[self.mark:] # # Path: hq/soup_util.py # def debug_dump_long_string(s, length=50, one_line=True, suffix='...'): # return truncate_string(s, length, one_line, suffix) # # Path: hq/verbosity.py # def verbose_print(text, indent_after=False, outdent_before=False): # if settings.VERBOSE: # if outdent_before: # pop_indent() # if not is_a_string(text): # text = text() # print(u'{0}{1}'.format(' ' * indent_level, text), file=sys.stderr) # if indent_after: # push_indent() which might include code, classes, or functions. Output only the next line.
return '{0}{1}return <expr>'.format(
Given the code snippet: <|code_start|> class Flwor: def __init__(self): self.global_variables = [] <|code_end|> , generate the next line using the imports in this file: from hq.hquery.object_type import debug_dump_anything from hq.hquery.sequences import make_sequence, sequence_concat from hq.hquery.syntax_error import HquerySyntaxError from hq.hquery.variables import push_variable, variable_scope from hq.soup_util import debug_dump_long_string from hq.verbosity import verbose_print and context (functions, classes, or occasionally code) from other files: # Path: hq/hquery/object_type.py # def debug_dump_anything(obj): # if is_any_node(obj): # result = debug_dump_node(obj) # elif is_boolean(obj) or is_number(obj) or is_hash(obj) or is_array(obj): # result = repr(obj) # elif is_string(obj): # result = u'string("{0}")'.format(obj) # elif is_node_set(obj): # result = u'node-set({0})'.format(', '.join(truncate_string(debug_dump_node(node), 20) for node in obj)) # elif is_sequence(obj): # result = u'sequence({0})'.format(', '.join(truncate_string(debug_dump_anything(item), 20) for item in obj)) # else: # raise RuntimeError("debug_dump_anything doesn't know how to handle {0}".format(obj.__class__.__name__)) # return debug_dump_long_string(result) # # Path: hq/hquery/sequences.py # def make_sequence(sequence): # if not isinstance(sequence, list): # sequence = [sequence] # return sequence # # def sequence_concat(first, second): # first = make_sequence(first) # first.extend(make_sequence(second)) # return first # # Path: hq/hquery/syntax_error.py # class HquerySyntaxError(ValueError): # pass # # Path: hq/hquery/variables.py # def push_variable(name, value): # global variable_stack # verbose_print(lambda: u'Pushing variable onto stack: let ${0} := {1}'.format(name, debug_dump_anything(value))) # variable_stack.append((name, value)) # # class variable_scope: # def __enter__(self): # self.mark = len(variable_stack) # # def __exit__(self, *args): # del variable_stack[self.mark:] # # Path: hq/soup_util.py # def debug_dump_long_string(s, length=50, one_line=True, suffix='...'): # return truncate_string(s, length, one_line, suffix) # # Path: hq/verbosity.py # def verbose_print(text, indent_after=False, outdent_before=False): # if settings.VERBOSE: # if outdent_before: # pop_indent() # if not is_a_string(text): # text = text() # print(u'{0}{1}'.format(' ' * indent_level, text), file=sys.stderr) # if indent_after: # push_indent() . Output only the next line.
self.per_iteration_variables = []
Given the following code snippet before the placeholder: <|code_start|> class Flwor: def __init__(self): self.global_variables = [] self.per_iteration_variables = [] self.return_expression = None self.sequence_expression = None self.sequence_variable = None def __str__(self): return '{0}{1}return <expr>'.format( '' if self.sequence_expression is None else 'for ${0}:=<expr> '.format(self.sequence_variable), (' '.join('let ${0} := <expr>'.format(v[0]) for v in self.per_iteration_variables) + ' ') if len(self.per_iteration_variables) else '' <|code_end|> , predict the next line using imports from the current file: from hq.hquery.object_type import debug_dump_anything from hq.hquery.sequences import make_sequence, sequence_concat from hq.hquery.syntax_error import HquerySyntaxError from hq.hquery.variables import push_variable, variable_scope from hq.soup_util import debug_dump_long_string from hq.verbosity import verbose_print and context including class names, function names, and sometimes code from other files: # Path: hq/hquery/object_type.py # def debug_dump_anything(obj): # if is_any_node(obj): # result = debug_dump_node(obj) # elif is_boolean(obj) or is_number(obj) or is_hash(obj) or is_array(obj): # result = repr(obj) # elif is_string(obj): # result = u'string("{0}")'.format(obj) # elif is_node_set(obj): # result = u'node-set({0})'.format(', '.join(truncate_string(debug_dump_node(node), 20) for node in obj)) # elif is_sequence(obj): # result = u'sequence({0})'.format(', '.join(truncate_string(debug_dump_anything(item), 20) for item in obj)) # else: # raise RuntimeError("debug_dump_anything doesn't know how to handle {0}".format(obj.__class__.__name__)) # return debug_dump_long_string(result) # # Path: hq/hquery/sequences.py # def make_sequence(sequence): # if not isinstance(sequence, list): # sequence = [sequence] # return sequence # # def sequence_concat(first, second): # first = make_sequence(first) # first.extend(make_sequence(second)) # return first # # Path: hq/hquery/syntax_error.py # class HquerySyntaxError(ValueError): # pass # # Path: hq/hquery/variables.py # def push_variable(name, value): # global variable_stack # verbose_print(lambda: u'Pushing variable onto stack: let ${0} := {1}'.format(name, debug_dump_anything(value))) # variable_stack.append((name, value)) # # class variable_scope: # def __enter__(self): # self.mark = len(variable_stack) # # def __exit__(self, *args): # del variable_stack[self.mark:] # # Path: hq/soup_util.py # def debug_dump_long_string(s, length=50, one_line=True, suffix='...'): # return truncate_string(s, length, one_line, suffix) # # Path: hq/verbosity.py # def verbose_print(text, indent_after=False, outdent_before=False): # if settings.VERBOSE: # if outdent_before: # pop_indent() # if not is_a_string(text): # text = text() # print(u'{0}{1}'.format(' ' * indent_level, text), file=sys.stderr) # if indent_after: # push_indent() . Output only the next line.
)
Given snippet: <|code_start|> self.sequence_variable = variable_name self.sequence_expression = expression_fn def set_return_expression(self, expression_fn): if self.return_expression is not None: raise HquerySyntaxError('More than one return clause found for FLWOR {0}'.format(self.debug_dump())) self.return_expression = expression_fn def _evaluate_iteration(self): with variable_scope(): self._push_global_variables() sequence = make_sequence(self.sequence_expression()) verbose_print('Iterating over sequence containing {0} items'.format(len(sequence))) result = [] for item in sequence: verbose_print(lambda: u'Visiting item {0}'.format(debug_dump_anything(item)), indent_after=True) with variable_scope(): push_variable(self.sequence_variable, make_sequence(item)) self._push_iteration_variables() this_result = make_sequence(self.return_expression()) verbose_print('Return clause yielded {0} results for this visit'.format(len(this_result))) result = sequence_concat(result, this_result) verbose_print('Visit finished', outdent_before=True) <|code_end|> , continue by predicting the next line. Consider current file imports: from hq.hquery.object_type import debug_dump_anything from hq.hquery.sequences import make_sequence, sequence_concat from hq.hquery.syntax_error import HquerySyntaxError from hq.hquery.variables import push_variable, variable_scope from hq.soup_util import debug_dump_long_string from hq.verbosity import verbose_print and context: # Path: hq/hquery/object_type.py # def debug_dump_anything(obj): # if is_any_node(obj): # result = debug_dump_node(obj) # elif is_boolean(obj) or is_number(obj) or is_hash(obj) or is_array(obj): # result = repr(obj) # elif is_string(obj): # result = u'string("{0}")'.format(obj) # elif is_node_set(obj): # result = u'node-set({0})'.format(', '.join(truncate_string(debug_dump_node(node), 20) for node in obj)) # elif is_sequence(obj): # result = u'sequence({0})'.format(', '.join(truncate_string(debug_dump_anything(item), 20) for item in obj)) # else: # raise RuntimeError("debug_dump_anything doesn't know how to handle {0}".format(obj.__class__.__name__)) # return debug_dump_long_string(result) # # Path: hq/hquery/sequences.py # def make_sequence(sequence): # if not isinstance(sequence, list): # sequence = [sequence] # return sequence # # def sequence_concat(first, second): # first = make_sequence(first) # first.extend(make_sequence(second)) # return first # # Path: hq/hquery/syntax_error.py # class HquerySyntaxError(ValueError): # pass # # Path: hq/hquery/variables.py # def push_variable(name, value): # global variable_stack # verbose_print(lambda: u'Pushing variable onto stack: let ${0} := {1}'.format(name, debug_dump_anything(value))) # variable_stack.append((name, value)) # # class variable_scope: # def __enter__(self): # self.mark = len(variable_stack) # # def __exit__(self, *args): # del variable_stack[self.mark:] # # Path: hq/soup_util.py # def debug_dump_long_string(s, length=50, one_line=True, suffix='...'): # return truncate_string(s, length, one_line, suffix) # # Path: hq/verbosity.py # def verbose_print(text, indent_after=False, outdent_before=False): # if settings.VERBOSE: # if outdent_before: # pop_indent() # if not is_a_string(text): # text = text() # print(u'{0}{1}'.format(' ' * indent_level, text), file=sys.stderr) # if indent_after: # push_indent() which might include code, classes, or functions. Output only the next line.
return result
Based on the snippet: <|code_start|> self.global_variables.append(var_tuple) else: self.per_iteration_variables.append(var_tuple) def debug_dump(self): return debug_dump_long_string(str(self)) def evaluate(self): verbose_print('Evaluating FLWOR {0}'.format(self), indent_after=True) if self.sequence_expression is not None: result = self._evaluate_iteration() else: result = self._evaluate_without_iteration() verbose_print(lambda: 'FLWOR evaluation completed; returning {0}'.format(debug_dump_anything(result)), outdent_before=True) return result def set_iteration_expression(self, variable_name, expression_fn): if self.sequence_expression is not None: raise HquerySyntaxError('More than one "for" clause found in FLWOR "{0}"'.format(self.debug_dump())) self.sequence_variable = variable_name self.sequence_expression = expression_fn def set_return_expression(self, expression_fn): <|code_end|> , predict the immediate next line with the help of imports: from hq.hquery.object_type import debug_dump_anything from hq.hquery.sequences import make_sequence, sequence_concat from hq.hquery.syntax_error import HquerySyntaxError from hq.hquery.variables import push_variable, variable_scope from hq.soup_util import debug_dump_long_string from hq.verbosity import verbose_print and context (classes, functions, sometimes code) from other files: # Path: hq/hquery/object_type.py # def debug_dump_anything(obj): # if is_any_node(obj): # result = debug_dump_node(obj) # elif is_boolean(obj) or is_number(obj) or is_hash(obj) or is_array(obj): # result = repr(obj) # elif is_string(obj): # result = u'string("{0}")'.format(obj) # elif is_node_set(obj): # result = u'node-set({0})'.format(', '.join(truncate_string(debug_dump_node(node), 20) for node in obj)) # elif is_sequence(obj): # result = u'sequence({0})'.format(', '.join(truncate_string(debug_dump_anything(item), 20) for item in obj)) # else: # raise RuntimeError("debug_dump_anything doesn't know how to handle {0}".format(obj.__class__.__name__)) # return debug_dump_long_string(result) # # Path: hq/hquery/sequences.py # def make_sequence(sequence): # if not isinstance(sequence, list): # sequence = [sequence] # return sequence # # def sequence_concat(first, second): # first = make_sequence(first) # first.extend(make_sequence(second)) # return first # # Path: hq/hquery/syntax_error.py # class HquerySyntaxError(ValueError): # pass # # Path: hq/hquery/variables.py # def push_variable(name, value): # global variable_stack # verbose_print(lambda: u'Pushing variable onto stack: let ${0} := {1}'.format(name, debug_dump_anything(value))) # variable_stack.append((name, value)) # # class variable_scope: # def __enter__(self): # self.mark = len(variable_stack) # # def __exit__(self, *args): # del variable_stack[self.mark:] # # Path: hq/soup_util.py # def debug_dump_long_string(s, length=50, one_line=True, suffix='...'): # return truncate_string(s, length, one_line, suffix) # # Path: hq/verbosity.py # def verbose_print(text, indent_after=False, outdent_before=False): # if settings.VERBOSE: # if outdent_before: # pop_indent() # if not is_a_string(text): # text = text() # print(u'{0}{1}'.format(' ' * indent_level, text), file=sys.stderr) # if indent_after: # push_indent() . Output only the next line.
if self.return_expression is not None:
Predict the next line for this snippet: <|code_start|> self._push_global_variables() sequence = make_sequence(self.sequence_expression()) verbose_print('Iterating over sequence containing {0} items'.format(len(sequence))) result = [] for item in sequence: verbose_print(lambda: u'Visiting item {0}'.format(debug_dump_anything(item)), indent_after=True) with variable_scope(): push_variable(self.sequence_variable, make_sequence(item)) self._push_iteration_variables() this_result = make_sequence(self.return_expression()) verbose_print('Return clause yielded {0} results for this visit'.format(len(this_result))) result = sequence_concat(result, this_result) verbose_print('Visit finished', outdent_before=True) return result def _evaluate_without_iteration(self): with variable_scope(): self._push_global_variables() verbose_print('Evaluating return expression.', indent_after=True) result = self.return_expression() verbose_print('Return expression produced {0}'.format(str(result)), outdent_before=True) return result <|code_end|> with the help of current file imports: from hq.hquery.object_type import debug_dump_anything from hq.hquery.sequences import make_sequence, sequence_concat from hq.hquery.syntax_error import HquerySyntaxError from hq.hquery.variables import push_variable, variable_scope from hq.soup_util import debug_dump_long_string from hq.verbosity import verbose_print and context from other files: # Path: hq/hquery/object_type.py # def debug_dump_anything(obj): # if is_any_node(obj): # result = debug_dump_node(obj) # elif is_boolean(obj) or is_number(obj) or is_hash(obj) or is_array(obj): # result = repr(obj) # elif is_string(obj): # result = u'string("{0}")'.format(obj) # elif is_node_set(obj): # result = u'node-set({0})'.format(', '.join(truncate_string(debug_dump_node(node), 20) for node in obj)) # elif is_sequence(obj): # result = u'sequence({0})'.format(', '.join(truncate_string(debug_dump_anything(item), 20) for item in obj)) # else: # raise RuntimeError("debug_dump_anything doesn't know how to handle {0}".format(obj.__class__.__name__)) # return debug_dump_long_string(result) # # Path: hq/hquery/sequences.py # def make_sequence(sequence): # if not isinstance(sequence, list): # sequence = [sequence] # return sequence # # def sequence_concat(first, second): # first = make_sequence(first) # first.extend(make_sequence(second)) # return first # # Path: hq/hquery/syntax_error.py # class HquerySyntaxError(ValueError): # pass # # Path: hq/hquery/variables.py # def push_variable(name, value): # global variable_stack # verbose_print(lambda: u'Pushing variable onto stack: let ${0} := {1}'.format(name, debug_dump_anything(value))) # variable_stack.append((name, value)) # # class variable_scope: # def __enter__(self): # self.mark = len(variable_stack) # # def __exit__(self, *args): # del variable_stack[self.mark:] # # Path: hq/soup_util.py # def debug_dump_long_string(s, length=50, one_line=True, suffix='...'): # return truncate_string(s, length, one_line, suffix) # # Path: hq/verbosity.py # def verbose_print(text, indent_after=False, outdent_before=False): # if settings.VERBOSE: # if outdent_before: # pop_indent() # if not is_a_string(text): # text = text() # print(u'{0}{1}'.format(' ' * indent_level, text), file=sys.stderr) # if indent_after: # push_indent() , which may contain function names, class names, or code. Output only the next line.
def _push_global_variables(self):
Given the following code snippet before the placeholder: <|code_start|> def test_escapes_work_in_string_literals(): assert query_html_doc('', '"foo&#10;bar"') == expected_result(""" foo bar""") assert query_html_doc('', "'foo&#10;bar'") == expected_result(""" foo <|code_end|> , predict the next line using imports from the current file: from test.common_test_util import expected_result from test.hquery.hquery_test_util import query_html_doc and context including class names, function names, and sometimes code from other files: # Path: test/common_test_util.py # def expected_result(contents): # return dedent(contents.lstrip('\n')) # # Path: test/hquery/hquery_test_util.py # def query_html_doc(html_body, hquery, preserve_space=False, wrap_body=True): # soup = soup_with_body(html_body) if wrap_body else make_soup(html_body) # raw_result = HqueryProcessor(hquery, preserve_space=preserve_space).query(soup) # return eliminate_blank_lines(convert_results_to_output_text(raw_result, preserve_space=preserve_space).strip()) . Output only the next line.
bar""")
Predict the next line for this snippet: <|code_start|> def test_escapes_work_in_string_literals(): assert query_html_doc('', '"foo&#10;bar"') == expected_result(""" foo <|code_end|> with the help of current file imports: from test.common_test_util import expected_result from test.hquery.hquery_test_util import query_html_doc and context from other files: # Path: test/common_test_util.py # def expected_result(contents): # return dedent(contents.lstrip('\n')) # # Path: test/hquery/hquery_test_util.py # def query_html_doc(html_body, hquery, preserve_space=False, wrap_body=True): # soup = soup_with_body(html_body) if wrap_body else make_soup(html_body) # raw_result = HqueryProcessor(hquery, preserve_space=preserve_space).query(soup) # return eliminate_blank_lines(convert_results_to_output_text(raw_result, preserve_space=preserve_space).strip()) , which may contain function names, class names, or code. Output only the next line.
bar""")
Given the code snippet: <|code_start|> variable_stack = [] NAME, VALUE = range(2) class variable_scope: def __enter__(self): self.mark = len(variable_stack) def __exit__(self, *args): del variable_stack[self.mark:] def push_variable(name, value): global variable_stack verbose_print(lambda: u'Pushing variable onto stack: let ${0} := {1}'.format(name, debug_dump_anything(value))) variable_stack.append((name, value)) def value_of_variable(name): if len(variable_stack) > 0: for index in range(len(variable_stack) - 1, -1, -1): if variable_stack[index][NAME] == name: reverse_index = len(variable_stack) - (index + 1) verbose_print('Variable "${0}" found on stack (position {1}).'.format(name, reverse_index)) <|code_end|> , generate the next line using the imports in this file: from hq.hquery.object_type import debug_dump_anything from hq.verbosity import verbose_print and context (functions, classes, or occasionally code) from other files: # Path: hq/hquery/object_type.py # def debug_dump_anything(obj): # if is_any_node(obj): # result = debug_dump_node(obj) # elif is_boolean(obj) or is_number(obj) or is_hash(obj) or is_array(obj): # result = repr(obj) # elif is_string(obj): # result = u'string("{0}")'.format(obj) # elif is_node_set(obj): # result = u'node-set({0})'.format(', '.join(truncate_string(debug_dump_node(node), 20) for node in obj)) # elif is_sequence(obj): # result = u'sequence({0})'.format(', '.join(truncate_string(debug_dump_anything(item), 20) for item in obj)) # else: # raise RuntimeError("debug_dump_anything doesn't know how to handle {0}".format(obj.__class__.__name__)) # return debug_dump_long_string(result) # # Path: hq/verbosity.py # def verbose_print(text, indent_after=False, outdent_before=False): # if settings.VERBOSE: # if outdent_before: # pop_indent() # if not is_a_string(text): # text = text() # print(u'{0}{1}'.format(' ' * indent_level, text), file=sys.stderr) # if indent_after: # push_indent() . Output only the next line.
return variable_stack[index][VALUE]
Continue the code snippet: <|code_start|> assert query_html_doc('', 'string(1 = -1)') == expected_result('false') def test_string_value_of_an_element_with_mixed_content_inserts_proper_spaces_between_text_runs(): html_body = '<p>once <a href>twice</a> thrice</p>' assert query_html_doc(html_body, 'string(//p)') == expected_result('once twice thrice') def test_string_length_function_returns_expected_values(): assert query_html_doc('', 'string-length("foo")') == expected_result('3') assert query_html_doc('', 'string-length("")') == expected_result('0') def test_sum_function_sums_number_interpretation_of_items_in_sequence(): html_body = """ <span>30</span> <div value="10.42"></div> <span>2</span>""" assert query_html_doc(html_body, 'sum(//span)') == '32' assert query_html_doc(html_body, 'sum((//span, //div/@value))') == '42.42' def test_sum_function_supports_zero_value_for_empty_sequence_as_second_argument(): assert query_html_doc('', 'sum(//span, "zero")') == 'zero' def test_various_functions_use_context_node_when_no_argument_passed(): html_body = """ <p>first</p> <|code_end|> . Use current file imports: import os import sys from ..common_test_util import expected_result from test.hquery.hquery_test_util import query_html_doc and context (classes, functions, or code) from other files: # Path: test/common_test_util.py # def expected_result(contents): # return dedent(contents.lstrip('\n')) # # Path: test/hquery/hquery_test_util.py # def query_html_doc(html_body, hquery, preserve_space=False, wrap_body=True): # soup = soup_with_body(html_body) if wrap_body else make_soup(html_body) # raw_result = HqueryProcessor(hquery, preserve_space=preserve_space).query(soup) # return eliminate_blank_lines(convert_results_to_output_text(raw_result, preserve_space=preserve_space).strip()) . Output only the next line.
<p>foo bar</p>