Any required environment types that are not built-in must be manually installed alongside Hatch or listed in the tool.hatch.env.requires array for automatic management:
All environment types should offer support for synchronized storage between the local file system and the environment. This functionality is used in the following scenarios:
classEnvironmentInterface(ABC):""" Example usage: ```python tab="plugin.py" from hatch.env.plugin.interface import EnvironmentInterface class SpecialEnvironment(EnvironmentInterface): PLUGIN_NAME = 'special' ... ``` ```python tab="hooks.py" from hatchling.plugin import hookimpl from .plugin import SpecialEnvironment @hookimpl def hatch_register_environment(): return SpecialEnvironment ``` """PLUGIN_NAME=''"""The name used for selection."""def__init__(self,root,metadata,name,config,matrix_variables,data_directory,isolated_data_directory,platform,verbosity,app,):self.__root=rootself.__metadata=metadataself.__name=nameself.__config=configself.__matrix_variables=matrix_variablesself.__data_directory=data_directoryself.__isolated_data_directory=isolated_data_directoryself.__platform=platformself.__verbosity=verbosityself.__app=app@propertydefmatrix_variables(self):returnself.__matrix_variables@propertydefapp(self):""" An instance of [Application](../utilities.md#hatchling.bridge.app.Application). """returnself.__app@cached_propertydefcontext(self):returnself.get_context()@propertydefverbosity(self):returnself.__verbosity@propertydefroot(self):""" The root of the local project tree as a path-like object. """returnself.__root@propertydefmetadata(self):returnself.__metadata@propertydefname(self)->str:""" The name of the environment. """returnself.__name@propertydefplatform(self):""" An instance of [Platform](../utilities.md#hatch.utils.platform.Platform). """returnself.__platform@propertydefdata_directory(self):""" The [directory](../../config/hatch.md#environments) this plugin should use for storage as a path-like object. If the user has not configured one then this will be the same as the [isolated data directory](reference.md#hatch.env.plugin.interface.EnvironmentInterface.isolated_data_directory). """returnself.__data_directory@propertydefisolated_data_directory(self):""" The default [directory](../../config/hatch.md#environments) reserved exclusively for this plugin as a path-like object. """returnself.__isolated_data_directory@propertydefconfig(self)->dict:""" ```toml config-example [tool.hatch.envs.<ENV_NAME>] ``` """returnself.__config@cached_propertydefproject_root(self)->str:""" The root of the project tree as a string. If the environment is not running locally, this should be the remote path to the project. """returnstr(self.root)@cached_propertydefsep(self)->str:""" The character used to separate directories in paths. By default, this is `\\` on Windows and `/` otherwise. """returnos.sep@cached_propertydefpathsep(self)->str:""" The character used to separate paths. By default, this is `;` on Windows and `:` otherwise. """returnos.pathsep@cached_propertydefsystem_python(self):system_python=os.environ.get(AppEnvVars.PYTHON)ifsystem_python=='self':system_python=sys.executablesystem_python=(system_pythonorself.platform.modules.shutil.which('python')orself.platform.modules.shutil.which('python3')orsys.executable)ifnotisabs(system_python):system_python=self.platform.modules.shutil.which(system_python)returnsystem_python@cached_propertydefenv_vars(self)->dict:""" ```toml config-example [tool.hatch.envs.<ENV_NAME>.env-vars] ``` """env_vars=self.config.get('env-vars',{})ifnotisinstance(env_vars,dict):message=f'Field `tool.hatch.envs.{self.name}.env-vars` must be a mapping'raiseTypeError(message)forkey,valueinenv_vars.items():ifnotisinstance(value,str):message=(f'Environment variable `{key}` of field `tool.hatch.envs.{self.name}.env-vars` must be a string')raiseTypeError(message)new_env_vars={}withself.metadata.context.apply_context(self.context):forkey,valueinenv_vars.items():new_env_vars[key]=self.metadata.context.format(value)new_env_vars[AppEnvVars.ENV_ACTIVE]=self.namereturnnew_env_vars@cached_propertydefenv_include(self)->list[str]:""" ```toml config-example [tool.hatch.envs.<ENV_NAME>] env-include = [...] ``` """env_include=self.config.get('env-include',[])ifnotisinstance(env_include,list):message=f'Field `tool.hatch.envs.{self.name}.env-include` must be an array'raiseTypeError(message)fori,patterninenumerate(env_include,1):ifnotisinstance(pattern,str):message=f'Pattern #{i} of field `tool.hatch.envs.{self.name}.env-include` must be a string'raiseTypeError(message)return['HATCH_BUILD_*',*env_include]ifenv_includeelseenv_include@cached_propertydefenv_exclude(self)->list[str]:""" ```toml config-example [tool.hatch.envs.<ENV_NAME>] env-exclude = [...] ``` """env_exclude=self.config.get('env-exclude',[])ifnotisinstance(env_exclude,list):message=f'Field `tool.hatch.envs.{self.name}.env-exclude` must be an array'raiseTypeError(message)fori,patterninenumerate(env_exclude,1):ifnotisinstance(pattern,str):message=f'Pattern #{i} of field `tool.hatch.envs.{self.name}.env-exclude` must be a string'raiseTypeError(message)returnenv_exclude@cached_propertydefenvironment_dependencies_complex(self):frompackaging.requirementsimportInvalidRequirement,Requirementdependencies_complex=[]withself.apply_context():foroptionin('dependencies','extra-dependencies'):dependencies=self.config.get(option,[])ifnotisinstance(dependencies,list):message=f'Field `tool.hatch.envs.{self.name}.{option}` must be an array'raiseTypeError(message)fori,entryinenumerate(dependencies,1):ifnotisinstance(entry,str):message=f'Dependency #{i} of field `tool.hatch.envs.{self.name}.{option}` must be a string'raiseTypeError(message)try:dependencies_complex.append(Requirement(self.metadata.context.format(entry)))exceptInvalidRequirementase:message=f'Dependency #{i} of field `tool.hatch.envs.{self.name}.{option}` is invalid: {e}'raiseValueError(message)fromNonereturndependencies_complex@cached_propertydefenvironment_dependencies(self)->list[str]:""" The list of all [environment dependencies](../../config/environment/overview.md#dependencies). """return[str(dependency)fordependencyinself.environment_dependencies_complex]@cached_propertydefdependencies_complex(self):all_dependencies_complex=list(self.environment_dependencies_complex)ifself.builder:all_dependencies_complex.extend(self.metadata.build.requires_complex)returnall_dependencies_complex# Ensure these are checked last to speed up initial environment creation since# they will already be installed along with the projectif(notself.skip_installandself.dev_mode)orself.features:fromhatch.utils.depimportget_complex_dependencies,get_complex_featuresdependencies,optional_dependencies=self.app.project.get_dependencies()dependencies_complex=get_complex_dependencies(dependencies)optional_dependencies_complex=get_complex_features(optional_dependencies)ifnotself.skip_installandself.dev_mode:all_dependencies_complex.extend(dependencies_complex.values())forfeatureinself.features:iffeaturenotinoptional_dependencies_complex:message=(f'Feature `{feature}` of field `tool.hatch.envs.{self.name}.features` is not 'f'defined in the dynamic field `project.optional-dependencies`')raiseValueError(message)all_dependencies_complex.extend(optional_dependencies_complex[feature].values())returnall_dependencies_complex@cached_propertydefdependencies(self)->list[str]:""" The list of all [project dependencies](../../config/metadata.md#dependencies) (if [installed](../../config/environment/overview.md#skip-install) and in [dev mode](../../config/environment/overview.md#dev-mode)), selected [optional dependencies](../../config/environment/overview.md#features), and [environment dependencies](../../config/environment/overview.md#dependencies). """return[str(dependency)fordependencyinself.dependencies_complex]@cached_propertydefplatforms(self)->list[str]:""" All names are stored as their lower-cased version. ```toml config-example [tool.hatch.envs.<ENV_NAME>] platforms = [...] ``` """platforms=self.config.get('platforms',[])ifnotisinstance(platforms,list):message=f'Field `tool.hatch.envs.{self.name}.platforms` must be an array'raiseTypeError(message)fori,commandinenumerate(platforms,1):ifnotisinstance(command,str):message=f'Platform #{i} of field `tool.hatch.envs.{self.name}.platforms` must be a string'raiseTypeError(message)return[platform.lower()forplatforminplatforms]@cached_propertydefskip_install(self)->bool:""" ```toml config-example [tool.hatch.envs.<ENV_NAME>] skip-install = ... ``` """skip_install=self.config.get('skip-install',notself.metadata.has_project_file())ifnotisinstance(skip_install,bool):message=f'Field `tool.hatch.envs.{self.name}.skip-install` must be a boolean'raiseTypeError(message)returnskip_install@cached_propertydefdev_mode(self)->bool:""" ```toml config-example [tool.hatch.envs.<ENV_NAME>] dev-mode = ... ``` """dev_mode=self.config.get('dev-mode',True)ifnotisinstance(dev_mode,bool):message=f'Field `tool.hatch.envs.{self.name}.dev-mode` must be a boolean'raiseTypeError(message)returndev_mode@cached_propertydefbuilder(self)->bool:""" ```toml config-example [tool.hatch.envs.<ENV_NAME>] builder = ... ``` """builder=self.config.get('builder',False)ifnotisinstance(builder,bool):message=f'Field `tool.hatch.envs.{self.name}.builder` must be a boolean'raiseTypeError(message)returnbuilder@cached_propertydeffeatures(self):fromhatchling.metadata.utilsimportnormalize_project_namefeatures=self.config.get('features',[])ifnotisinstance(features,list):message=f'Field `tool.hatch.envs.{self.name}.features` must be an array of strings'raiseTypeError(message)all_features=set()fori,featureinenumerate(features,1):ifnotisinstance(feature,str):message=f'Feature #{i} of field `tool.hatch.envs.{self.name}.features` must be a string'raiseTypeError(message)ifnotfeature:message=f'Feature #{i} of field `tool.hatch.envs.{self.name}.features` cannot be an empty string'raiseValueError(message)normalized_feature=(featureifself.metadata.hatch.metadata.allow_ambiguous_featureselsenormalize_project_name(feature))if(notself.metadata.hatch.metadata.hook_configandnormalized_featurenotinself.metadata.core.optional_dependencies):message=(f'Feature `{normalized_feature}` of field `tool.hatch.envs.{self.name}.features` is not 'f'defined in field `project.optional-dependencies`')raiseValueError(message)all_features.add(normalized_feature)returnsorted(all_features)@cached_propertydefdescription(self)->str:""" ```toml config-example [tool.hatch.envs.<ENV_NAME>] description = ... ``` """description=self.config.get('description','')ifnotisinstance(description,str):message=f'Field `tool.hatch.envs.{self.name}.description` must be a string'raiseTypeError(message)returndescription@cached_propertydefscripts(self):config={}# Extra scripts should come first to give less precedenceforfieldin('extra-scripts','scripts'):script_config=self.config.get(field,{})ifnotisinstance(script_config,dict):message=f'Field `tool.hatch.envs.{self.name}.{field}` must be a table'raiseTypeError(message)forname,datainscript_config.items():if' 'inname:message=(f'Script name `{name}` in field `tool.hatch.envs.{self.name}.{field}` 'f'must not contain spaces')raiseValueError(message)commands=[]ifisinstance(data,str):commands.append(data)elifisinstance(data,list):fori,commandinenumerate(data,1):ifnotisinstance(command,str):message=(f'Command #{i} in field `tool.hatch.envs.{self.name}.{field}.{name}` 'f'must be a string')raiseTypeError(message)commands.append(command)else:message=(f'Field `tool.hatch.envs.{self.name}.{field}.{name}` must be 'f'a string or an array of strings')raiseTypeError(message)config[name]=commandsseen={}active=[]forscript_name,commandsinconfig.items():commands[:]=expand_script_commands(self.name,script_name,commands,config,seen,active)returnconfig@cached_propertydefpre_install_commands(self):pre_install_commands=self.config.get('pre-install-commands',[])ifnotisinstance(pre_install_commands,list):message=f'Field `tool.hatch.envs.{self.name}.pre-install-commands` must be an array'raiseTypeError(message)fori,commandinenumerate(pre_install_commands,1):ifnotisinstance(command,str):message=f'Command #{i} of field `tool.hatch.envs.{self.name}.pre-install-commands` must be a string'raiseTypeError(message)returnlist(pre_install_commands)@cached_propertydefpost_install_commands(self):post_install_commands=self.config.get('post-install-commands',[])ifnotisinstance(post_install_commands,list):message=f'Field `tool.hatch.envs.{self.name}.post-install-commands` must be an array'raiseTypeError(message)fori,commandinenumerate(post_install_commands,1):ifnotisinstance(command,str):message=f'Command #{i} of field `tool.hatch.envs.{self.name}.post-install-commands` must be a string'raiseTypeError(message)returnlist(post_install_commands)defactivate(self):""" A convenience method called when using the environment as a context manager: ```python with environment: ... ``` """defdeactivate(self):""" A convenience method called after using the environment as a context manager: ```python with environment: ... ``` """@abstractmethoddeffind(self):""" :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right: This should return information about how to locate the environment or represent its ID in some way. Additionally, this is expected to return something even if the environment is [incompatible](reference.md#hatch.env.plugin.interface.EnvironmentInterface.check_compatibility). """@abstractmethoddefcreate(self):""" :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right: This should perform the necessary steps to set up the environment. """@abstractmethoddefremove(self):""" :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right: This should perform the necessary steps to completely remove the environment from the system and will only be triggered manually by users with the [`env remove`](../../cli/reference.md#hatch-env-remove) or [`env prune`](../../cli/reference.md#hatch-env-prune) commands. """@abstractmethoddefexists(self)->bool:""" :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right: This should indicate whether or not the environment has already been created. """@abstractmethoddefinstall_project(self):""" :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right: This should install the project in the environment. """@abstractmethoddefinstall_project_dev_mode(self):""" :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right: This should install the project in the environment such that the environment always reflects the current state of the project. """@abstractmethoddefdependencies_in_sync(self)->bool:""" :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right: This should indicate whether or not the environment is compatible with the current [dependencies](reference.md#hatch.env.plugin.interface.EnvironmentInterface.dependencies). """@abstractmethoddefsync_dependencies(self):""" :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right: This should install the [dependencies](reference.md#hatch.env.plugin.interface.EnvironmentInterface.dependencies) in the environment. """defdependency_hash(self):""" This should return a hash of the environment's [dependencies](reference.md#hatch.env.plugin.interface.EnvironmentInterface.dependencies) and any other data that is handled by the [sync_dependencies](reference.md#hatch.env.plugin.interface.EnvironmentInterface.sync_dependencies) and [dependencies_in_sync](reference.md#hatch.env.plugin.interface.EnvironmentInterface.dependencies_in_sync) methods. """fromhatch.utils.depimporthash_dependenciesreturnhash_dependencies(self.dependencies_complex)@contextmanagerdefapp_status_creation(self):""" See the [life cycle of environments](reference.md#life-cycle). """withself.app.status(f'Creating environment: {self.name}'):yield@contextmanagerdefapp_status_pre_installation(self):""" See the [life cycle of environments](reference.md#life-cycle). """withself.app.status('Running pre-installation commands'):yield@contextmanagerdefapp_status_post_installation(self):""" See the [life cycle of environments](reference.md#life-cycle). """withself.app.status('Running post-installation commands'):yield@contextmanagerdefapp_status_project_installation(self):""" See the [life cycle of environments](reference.md#life-cycle). """ifself.dev_mode:withself.app.status('Installing project in development mode'):yieldelse:withself.app.status('Installing project'):yield@contextmanagerdefapp_status_dependency_state_check(self):""" See the [life cycle of environments](reference.md#life-cycle). """ifnotself.skip_installand('dependencies'inself.metadata.dynamicor'optional-dependencies'inself.metadata.dynamic):withself.app.status('Polling dependency state'):yieldelse:yield@contextmanagerdefapp_status_dependency_installation_check(self):""" See the [life cycle of environments](reference.md#life-cycle). """withself.app.status('Checking dependencies'):yield@contextmanagerdefapp_status_dependency_synchronization(self):""" See the [life cycle of environments](reference.md#life-cycle). """withself.app.status('Syncing dependencies'):yield@contextmanagerdeffs_context(self)->Generator[FileSystemContext,None,None]:""" A context manager that must yield a subclass of [FileSystemContext](../utilities.md#hatch.env.plugin.interface.FileSystemContext). """fromhatch.utils.fsimporttemp_directorywithtemp_directory()astemp_dir:yieldFileSystemContext(self,local_path=temp_dir,env_path=str(temp_dir))defenter_shell(self,name:str,# noqa: ARG002path:str,args:Iterable[str],):""" Spawn a [shell](../../config/hatch.md#shell) within the environment. This should either use [command_context](reference.md#hatch.env.plugin.interface.EnvironmentInterface.command_context) directly or provide the same guarantee. """withself.command_context():self.platform.exit_with_command([path,*args])defrun_shell_command(self,command:str,**kwargs):""" This should return the standard library's [subprocess.CompletedProcess](https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess) and will always be called when the [command_context](reference.md#hatch.env.plugin.interface.EnvironmentInterface.command_context) is active, with the expectation of providing the same guarantee. """kwargs.setdefault('shell',True)returnself.platform.run_command(command,**kwargs)@contextmanagerdefcommand_context(self):""" A context manager that when active should make executed shell commands reflect any [environment variables](reference.md#hatch.env.plugin.interface.EnvironmentInterface.get_env_vars) the user defined either currently or at the time of [creation](reference.md#hatch.env.plugin.interface.EnvironmentInterface.create). For an example, open the default implementation below: """withself.get_env_vars():yielddefresolve_commands(self,commands:list[str]):""" This expands each command into one or more commands based on any [scripts](../../config/environment/overview.md#scripts) that the user defined. """forcommandincommands:yield fromself.expand_command(command)defexpand_command(self,command):possible_script,args,_ignore_exit_code=parse_script_command(command)# Indicate undefinedifnotargs:args=Nonewithself.apply_context():ifpossible_scriptinself.scripts:ifargsisnotNone:args=self.metadata.context.format(args)forcmdinself.scripts[possible_script]:yieldself.metadata.context.format(cmd,args=args).strip()else:yieldself.metadata.context.format(command,args=args).strip()defconstruct_pip_install_command(self,args:list[str]):""" A convenience method for constructing a [`pip install`](https://pip.pypa.io/en/stable/cli/pip_install/) command with the given verbosity. The default verbosity is set to one less than Hatch's verbosity. """command=['python','-u','-m','pip','install','--disable-pip-version-check']# Default to -1 verbosityadd_verbosity_flag(command,self.verbosity,adjustment=-1)command.extend(args)returncommanddefjoin_command_args(self,args:list[str]):""" This is used by the [`run`](../../cli/reference.md#hatch-run) command to construct the root command string from the received arguments. """returnself.platform.join_command_args(args)defapply_features(self,requirement:str):""" A convenience method that applies any user defined [features](../../config/environment/overview.md#features) to the given requirement. """ifself.features:features=','.join(self.features)returnf'{requirement}[{features}]'returnrequirementdefcheck_compatibility(self):""" This raises an exception if the environment is not compatible with the user's setup. The default behavior checks for [platform compatibility](../../config/environment/overview.md#supported-platforms) and any method override should keep this check. This check is never performed if the environment has been [created](reference.md#hatch.env.plugin.interface.EnvironmentInterface.create). """ifself.platformsandself.platform.namenotinself.platforms:message='unsupported platform'raiseOSError(message)defget_env_vars(self)->EnvVars:""" Returns a mapping of environment variables that should be available to the environment. The object can be used as a context manager to temporarily apply the environment variables to the current process. !!! note The environment variable `HATCH_ENV_ACTIVE` will always be set to the name of the environment. """returnEnvVars(self.env_vars,self.env_include,self.env_exclude)defget_env_var_option(self,option:str)->str:""" Returns the value of the upper-cased environment variable `HATCH_ENV_TYPE_<PLUGIN_NAME>_<option>`. """returnget_env_var_option(plugin_name=self.PLUGIN_NAME,option=option)defget_context(self):""" Returns a subclass of [EnvironmentContextFormatter](../utilities.md#hatch.env.context.EnvironmentContextFormatter). """fromhatch.env.contextimportEnvironmentContextFormatterreturnEnvironmentContextFormatter(self)@staticmethoddefget_option_types()->dict:""" Returns a mapping of supported options to their respective types so that they can be used by [overrides](../../config/environment/advanced.md#option-overrides). """return{}@contextmanagerdefapply_context(self):withself.get_env_vars(),self.metadata.context.apply_context(self.context):yielddef__enter__(self):self.activate()returnselfdef__exit__(self,exc_type,exc_value,traceback):self.deactivate()
The directory this plugin should use for storage as a path-like object. If the user has not configured one then this will be the same as the isolated data directory.
This should return information about how to locate the environment or represent its ID in some way. Additionally, this is expected to return something even if the environment is incompatible.
Source code in src/hatch/env/plugin/interface.py
@abstractmethoddeffind(self):""" :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right: This should return information about how to locate the environment or represent its ID in some way. Additionally, this is expected to return something even if the environment is [incompatible](reference.md#hatch.env.plugin.interface.EnvironmentInterface.check_compatibility). """
This should perform the necessary steps to set up the environment.
Source code in src/hatch/env/plugin/interface.py
@abstractmethoddefcreate(self):""" :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right: This should perform the necessary steps to set up the environment. """
This should perform the necessary steps to completely remove the environment from the system and will only be triggered manually by users with the env remove or env prune commands.
Source code in src/hatch/env/plugin/interface.py
@abstractmethoddefremove(self):""" :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right: This should perform the necessary steps to completely remove the environment from the system and will only be triggered manually by users with the [`env remove`](../../cli/reference.md#hatch-env-remove) or [`env prune`](../../cli/reference.md#hatch-env-prune) commands. """
This should indicate whether or not the environment has already been created.
Source code in src/hatch/env/plugin/interface.py
@abstractmethoddefexists(self)->bool:""" :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right: This should indicate whether or not the environment has already been created. """
This should install the project in the environment.
Source code in src/hatch/env/plugin/interface.py
@abstractmethoddefinstall_project(self):""" :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right: This should install the project in the environment. """
This should install the project in the environment such that the environment always reflects the current state of the project.
Source code in src/hatch/env/plugin/interface.py
@abstractmethoddefinstall_project_dev_mode(self):""" :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right: This should install the project in the environment such that the environment always reflects the current state of the project. """
This should indicate whether or not the environment is compatible with the current dependencies.
Source code in src/hatch/env/plugin/interface.py
@abstractmethoddefdependencies_in_sync(self)->bool:""" :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right: This should indicate whether or not the environment is compatible with the current [dependencies](reference.md#hatch.env.plugin.interface.EnvironmentInterface.dependencies). """
This should install the dependencies in the environment.
Source code in src/hatch/env/plugin/interface.py
@abstractmethoddefsync_dependencies(self):""" :material-align-horizontal-left: **REQUIRED** :material-align-horizontal-right: This should install the [dependencies](reference.md#hatch.env.plugin.interface.EnvironmentInterface.dependencies) in the environment. """
defdependency_hash(self):""" This should return a hash of the environment's [dependencies](reference.md#hatch.env.plugin.interface.EnvironmentInterface.dependencies) and any other data that is handled by the [sync_dependencies](reference.md#hatch.env.plugin.interface.EnvironmentInterface.sync_dependencies) and [dependencies_in_sync](reference.md#hatch.env.plugin.interface.EnvironmentInterface.dependencies_in_sync) methods. """fromhatch.utils.depimporthash_dependenciesreturnhash_dependencies(self.dependencies_complex)
@contextmanagerdeffs_context(self)->Generator[FileSystemContext,None,None]:""" A context manager that must yield a subclass of [FileSystemContext](../utilities.md#hatch.env.plugin.interface.FileSystemContext). """fromhatch.utils.fsimporttemp_directorywithtemp_directory()astemp_dir:yieldFileSystemContext(self,local_path=temp_dir,env_path=str(temp_dir))
@contextmanagerdefapp_status_creation(self):""" See the [life cycle of environments](reference.md#life-cycle). """withself.app.status(f'Creating environment: {self.name}'):yield
@contextmanagerdefapp_status_pre_installation(self):""" See the [life cycle of environments](reference.md#life-cycle). """withself.app.status('Running pre-installation commands'):yield
@contextmanagerdefapp_status_post_installation(self):""" See the [life cycle of environments](reference.md#life-cycle). """withself.app.status('Running post-installation commands'):yield
@contextmanagerdefapp_status_project_installation(self):""" See the [life cycle of environments](reference.md#life-cycle). """ifself.dev_mode:withself.app.status('Installing project in development mode'):yieldelse:withself.app.status('Installing project'):yield
@contextmanagerdefapp_status_dependency_state_check(self):""" See the [life cycle of environments](reference.md#life-cycle). """ifnotself.skip_installand('dependencies'inself.metadata.dynamicor'optional-dependencies'inself.metadata.dynamic):withself.app.status('Polling dependency state'):yieldelse:yield
@contextmanagerdefapp_status_dependency_installation_check(self):""" See the [life cycle of environments](reference.md#life-cycle). """withself.app.status('Checking dependencies'):yield
@contextmanagerdefapp_status_dependency_synchronization(self):""" See the [life cycle of environments](reference.md#life-cycle). """withself.app.status('Syncing dependencies'):yield
A context manager that when active should make executed shell commands reflect any environment variables the user defined either currently or at the time of creation.
For an example, open the default implementation below:
Source code in src/hatch/env/plugin/interface.py
@contextmanagerdefcommand_context(self):""" A context manager that when active should make executed shell commands reflect any [environment variables](reference.md#hatch.env.plugin.interface.EnvironmentInterface.get_env_vars) the user defined either currently or at the time of [creation](reference.md#hatch.env.plugin.interface.EnvironmentInterface.create). For an example, open the default implementation below: """withself.get_env_vars():yield
This should either use command_context directly or provide the same guarantee.
Source code in src/hatch/env/plugin/interface.py
defenter_shell(self,name:str,# noqa: ARG002path:str,args:Iterable[str],):""" Spawn a [shell](../../config/hatch.md#shell) within the environment. This should either use [command_context](reference.md#hatch.env.plugin.interface.EnvironmentInterface.command_context) directly or provide the same guarantee. """withself.command_context():self.platform.exit_with_command([path,*args])
This should return the standard library's subprocess.CompletedProcess and will always be called when the command_context is active, with the expectation of providing the same guarantee.
Source code in src/hatch/env/plugin/interface.py
defrun_shell_command(self,command:str,**kwargs):""" This should return the standard library's [subprocess.CompletedProcess](https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess) and will always be called when the [command_context](reference.md#hatch.env.plugin.interface.EnvironmentInterface.command_context) is active, with the expectation of providing the same guarantee. """kwargs.setdefault('shell',True)returnself.platform.run_command(command,**kwargs)
This expands each command into one or more commands based on any scripts that the user defined.
Source code in src/hatch/env/plugin/interface.py
defresolve_commands(self,commands:list[str]):""" This expands each command into one or more commands based on any [scripts](../../config/environment/overview.md#scripts) that the user defined. """forcommandincommands:yield fromself.expand_command(command)
Returns a mapping of environment variables that should be available to the environment. The object can be used as a context manager to temporarily apply the environment variables to the current process.
Note
The environment variable HATCH_ENV_ACTIVE will always be set to the name of the environment.
Source code in src/hatch/env/plugin/interface.py
defget_env_vars(self)->EnvVars:""" Returns a mapping of environment variables that should be available to the environment. The object can be used as a context manager to temporarily apply the environment variables to the current process. !!! note The environment variable `HATCH_ENV_ACTIVE` will always be set to the name of the environment. """returnEnvVars(self.env_vars,self.env_include,self.env_exclude)
A convenience method that applies any user defined features to the given requirement.
Source code in src/hatch/env/plugin/interface.py
defapply_features(self,requirement:str):""" A convenience method that applies any user defined [features](../../config/environment/overview.md#features) to the given requirement. """ifself.features:features=','.join(self.features)returnf'{requirement}[{features}]'returnrequirement
A convenience method for constructing a pip install command with the given verbosity. The default verbosity is set to one less than Hatch's verbosity.
Source code in src/hatch/env/plugin/interface.py
defconstruct_pip_install_command(self,args:list[str]):""" A convenience method for constructing a [`pip install`](https://pip.pypa.io/en/stable/cli/pip_install/) command with the given verbosity. The default verbosity is set to one less than Hatch's verbosity. """command=['python','-u','-m','pip','install','--disable-pip-version-check']# Default to -1 verbosityadd_verbosity_flag(command,self.verbosity,adjustment=-1)command.extend(args)returncommand
This is used by the run command to construct the root command string from the received arguments.
Source code in src/hatch/env/plugin/interface.py
defjoin_command_args(self,args:list[str]):""" This is used by the [`run`](../../cli/reference.md#hatch-run) command to construct the root command string from the received arguments. """returnself.platform.join_command_args(args)
This raises an exception if the environment is not compatible with the user's setup. The default behavior checks for platform compatibility and any method override should keep this check.
This check is never performed if the environment has been created.
Source code in src/hatch/env/plugin/interface.py
defcheck_compatibility(self):""" This raises an exception if the environment is not compatible with the user's setup. The default behavior checks for [platform compatibility](../../config/environment/overview.md#supported-platforms) and any method override should keep this check. This check is never performed if the environment has been [created](reference.md#hatch.env.plugin.interface.EnvironmentInterface.create). """ifself.platformsandself.platform.namenotinself.platforms:message='unsupported platform'raiseOSError(message)
Returns a mapping of supported options to their respective types so that they can be used by overrides.
Source code in src/hatch/env/plugin/interface.py
@staticmethoddefget_option_types()->dict:""" Returns a mapping of supported options to their respective types so that they can be used by [overrides](../../config/environment/advanced.md#option-overrides). """return{}
Returns the value of the upper-cased environment variable HATCH_ENV_TYPE_<PLUGIN_NAME>_<option>.
Source code in src/hatch/env/plugin/interface.py
defget_env_var_option(self,option:str)->str:""" Returns the value of the upper-cased environment variable `HATCH_ENV_TYPE_<PLUGIN_NAME>_<option>`. """returnget_env_var_option(plugin_name=self.PLUGIN_NAME,option=option)
defget_context(self):""" Returns a subclass of [EnvironmentContextFormatter](../utilities.md#hatch.env.context.EnvironmentContextFormatter). """fromhatch.env.contextimportEnvironmentContextFormatterreturnEnvironmentContextFormatter(self)