Extensions > API reference > ctx

ctx

A context object that is passed to the implementation function for a rule or aspect. It provides access to the information and methods needed to analyze the current target.

In particular, it lets the implementation function access the current target's label, attributes, configuration, and the providers of its dependencies. It has methods for declaring output files and the actions that produce them.

Context objects essentially live for the duration of the call to the implementation function. It is not useful to access these objects outside of their associated function. See the Rules page for more information.

action

None ctx.action(outputs, inputs=[], executable=None, tools=unbound, arguments=[], mnemonic=None, command=None, progress_message=None, use_default_shell_env=False, env=None, execution_requirements=None, input_manifests=None)

DEPRECATED. Use ctx.actions.run() or ctx.actions.run_shell().
Creates an action that runs an executable or a shell command. You must specify either command or executable. Actions and genrules are very similar, but have different use cases. Actions are used inside rules, and genrules are used inside macros. Genrules also have make variable expansion.

Parameters

Parameter Description
outputs

sequence of Files

List of the output files of the action.

inputs

sequence of Files; or depset of Files

List of the input files of the action.

executable

File; or string; or None

The executable file to be called by the action.

tools

sequence of Files; or depset of Files

List of the any tools needed by the action. Tools are inputs with additional runfiles that are automatically made available to the action.

arguments

sequence

Command line arguments of the action. Must be a list of strings or actions.args() objects.

mnemonic

string

A one-word description of the action, e.g. CppCompile or GoLink.

command

string; or sequence of strings; or None

Shell command to execute. It is usually preferable to use executable instead. Arguments are available with $1, $2, etc.

progress_message

string

Progress message to show to the user during the build, e.g. "Compiling foo.cc to create foo.o".

use_default_shell_env

bool

Whether the action should use the built in shell environment or not.

env

dict

Sets the dictionary of environment variables.

execution_requirements

dict

Information for scheduling the action. See tags for useful keys.

input_manifests

sequence

(Experimental) sets the input runfiles metadata; they are typically generated by resolve_command.

May return None.

actions

actions ctx.actions

Contains methods for declaring output files and the actions that produce them.

aspect_ids

list ctx.aspect_ids

Returns a list ids for all aspects applied to the target. Only available in aspect implementation functions.

attr

struct ctx.attr

A struct to access the values of the attributes. The values are provided by the user (if not, a default value is used). The attributes of the struct and the types of their values correspond to the keys and values of the attrs dict provided to the rule function. See example of use.

bin_dir

root ctx.bin_dir

The root corresponding to bin directory.

build_file_path

string ctx.build_file_path

Returns path to the BUILD file for this rule, relative to the source root.

build_setting_value

unknown ctx.build_setting_value

Experimental. This field is experimental and subject to change at any time. Do not depend on it.

Returns the value of the build setting that is represented by the current target. It is an error to access this field for rules that do not set the build_setting attribute in their rule definition.

configuration

configuration ctx.configuration

Returns the default configuration. See the configuration type for more details.

coverage_instrumented

bool ctx.coverage_instrumented(target=None)

Returns whether code coverage instrumentation should be generated when performing compilation actions for this rule or, if target is provided, the rule specified by that Target. (If a non-rule or a Starlark rule Target is provided, this returns False.) Checks if the sources of the current rule (if no Target is provided) or the sources of Target should be instrumented based on the --instrumentation_filter and --instrument_test_targets config settings. This differs from coverage_enabled in the configuration, which notes whether coverage data collection is enabled for the entire run, but not whether a specific target should be instrumented.

Parameters

Parameter Description
target

Target

A Target specifying a rule. If not provided, defaults to the current rule.

created_actions

StarlarkValue ctx.created_actions()

For rules with _skylark_testable set to True, this returns an Actions provider representing all actions created so far for the current rule. For all other rules, returns None. Note that the provider is not updated when subsequent actions are created, so you will have to call this function again if you wish to inspect them.

This is intended to help write tests for rule-implementation helper functions, which may take in a ctx object and create actions on it.

default_provider

Provider ctx.default_provider

Deprecated. Use DefaultInfo instead.

disabled_features

list ctx.disabled_features

Returns the set of features that are explicitly disabled by the user for this rule.

executable

struct ctx.executable

A struct containing executable files defined in label type attributes marked as executable=True. The struct fields correspond to the attribute names. Each value in the struct is either a File or None. If an optional attribute is not specified in the rule then the corresponding struct value is None. If a label type is not marked as executable=True, no corresponding struct field is generated. See example of use.

expand_location

string ctx.expand_location(input, targets=[])

Expands all $(location ...) templates in the given string by replacing $(location //x) with the path of the output file of target //x. Expansion only works for labels that point to direct dependencies of this rule or that are explicitly listed in the optional argument targets.

$(location ...) will cause an error if the referenced target has multiple outputs. In this case, please use $(locations ...) since it produces a space-separated list of output paths. It can be safely used for a single output file, too.

This function is useful to let the user specify a command in a BUILD file (like for genrule). In other cases, it is often better to manipulate labels directly.

Parameters

Parameter Description
input

string

String to be expanded.

targets

sequence of Targets

List of targets for additional lookup information.

May return None.

expand_make_variables

string ctx.expand_make_variables(attribute_name, command, additional_substitutions)

Deprecated. Use ctx.var to access the variables instead.
Returns a string after expanding all references to "Make variables". The variables must have the following format: $(VAR_NAME). Also, $$VAR_NAME expands to $VAR_NAME. Examples:
ctx.expand_make_variables("cmd", "$(MY_VAR)", {"MY_VAR": "Hi"})  # == "Hi"
ctx.expand_make_variables("cmd", "$$PWD", {})  # == "$PWD"
Additional variables may come from other places, such as configurations. Note that this function is experimental.

Parameters

Parameter Description
attribute_name

string

The attribute name. Used for error reporting.

command

string

The expression to expand. It can contain references to "Make variables".

additional_substitutions

dict

Additional substitutions to make beyond the default make variables.

features

list ctx.features

Returns the set of features that are explicitly enabled by the user for this rule. See example of use.

file

struct ctx.file

A struct containing files defined in label type attributes marked as allow_single_file. The struct fields correspond to the attribute names. The struct value is always a File or None. If an optional attribute is not specified in the rule then the corresponding struct value is None. If a label type is not marked as allow_single_file, no corresponding struct field is generated. It is a shortcut for:
list(ctx.attr.<ATTR>.files)[0]
In other words, use file to access the (singular) default output of a dependency. See example of use.

file_action

None ctx.file_action(output, content, executable=False)

DEPRECATED. Use ctx.actions.write instead.
Creates a file write action.

Parameters

Parameter Description
output

File

The output file.

content

string

The contents of the file.

executable

bool

Whether the output file should be executable (default is False).

May return None.

files

struct ctx.files

A struct containing files defined in label or label list type attributes. The struct fields correspond to the attribute names. The struct values are list of Files. It is a shortcut for:
[f for t in ctx.attr.<ATTR> for f in t.files]
In other words, use files to access the default outputs of a dependency. See example of use.

fragments

fragments ctx.fragments

Allows access to configuration fragments in target configuration.

genfiles_dir

root ctx.genfiles_dir

The root corresponding to genfiles directory.

host_configuration

configuration ctx.host_configuration

Returns the host configuration. See the configuration type for more details.

host_fragments

fragments ctx.host_fragments

Allows access to configuration fragments in host configuration.

label

Label ctx.label

The label of the target currently being analyzed.

new_file

File ctx.new_file(var1, var2=unbound, var3=unbound)

DEPRECATED. Use ctx.actions.declare_file.
Creates a file object. There are four possible signatures to this method:
  • new_file(filename): Creates a file object with the given filename in the current package.
  • new_file(file_root, filename): Creates a file object with the given filename under the given file root.
  • new_file(sibling_file, filename): Creates a file object in the same directory as the given sibling file.
  • new_file(file_root, sibling_file, suffix): Creates a file object with same base name of the sibling_file but with different given suffix, under the given file root.

Does not actually create a file on the file system, just declares that some action will do so. You must create an action that generates the file. If the file should be visible to other rules, declare a rule output instead when possible. Doing so enables Bazel to associate a label with the file that rules can refer to (allowing finer dependency control) instead of referencing the whole rule.

Parameters

Parameter Description
var1

string; or root; or File

var2

string; or File

var3

string

outputs

ClassObject ctx.outputs

A pseudo-struct containing all the predeclared output files, represented by File objects. See the Rules page for more information and examples.

This field does not exist on aspect contexts, since aspects do not have predeclared outputs.

The fields of this object are defined as follows. It is an error if two outputs produce the same field name or have the same label.

  • If the rule declares an outputs dict, then for every entry in the dict, there is a field whose name is the key and whose value is the corresponding File.
  • For every attribute of type attr.output that the rule declares, there is a field whose name is the attribute's name. If the target specified a label for that attribute, then the field value is the corresponding File; otherwise the field value is None.
  • For every attribute of type attr.output_list that the rule declares, there is a field whose name is the attribute's name. The field value is a list of File objects corresponding to the labels given for that attribute in the target, or an empty list if the attribute was not specified in the target.
  • (Deprecated) If the rule is marked executable or test, there is a field named "executable", which is the default executable. It is recommended that instead of using this, you pass another file (either predeclared or not) to the executable arg of DefaultInfo.

resolve_command

tuple ctx.resolve_command(command='', attribute=None, expand_locations=False, make_variables=None, tools=[], label_dict={}, execution_requirements={})

(Experimental) Returns a tuple (inputs, command, input_manifests) of the list of resolved inputs, the argv list for the resolved command, and the runfiles metadata required to run the command, all of them suitable for passing as the same-named arguments of the ctx.action method.
Note for Windows users: this method requires Bash (MSYS2). Consider using resolve_tools() instead (if that fits your needs).

Parameters

Parameter Description
command

string

Command to resolve.

attribute

string

Name of the associated attribute for which to issue an error, or None.

expand_locations

bool

Shall we expand $(location) variables? See ctx.expand_location() for more details.

make_variables

dict

Make variables to expand, or None.

tools

sequence of Targets

List of tools (list of targets).

label_dict

dict

Dictionary of resolved labels and the corresponding list of Files (a dict of Label : list of Files).

execution_requirements

dict

Information for scheduling the action to resolve this command. See tags for useful keys.

resolve_tools

tuple ctx.resolve_tools(tools=[])

Returns a tuple (inputs, input_manifests) of the depset of resolved inputs and the runfiles metadata required to run the tools, both of them suitable for passing as the same-named arguments of the ctx.actions.run method.

In contrast to ctx.resolve_command, this method does not require that Bash be installed on the machine, so it's suitable for rules built on Windows.

Parameters

Parameter Description
tools

sequence of Targets

List of tools (list of targets).

rule

rule_attributes ctx.rule

Returns rule attributes descriptor for the rule that aspect is applied to. Only available in aspect implementation functions.

runfiles

runfiles ctx.runfiles(files=[], transitive_files=None, collect_data=False, collect_default=False, symlinks={}, root_symlinks={})

Creates a runfiles object.

Parameters

Parameter Description
files

sequence of Files

The list of files to be added to the runfiles.

transitive_files

depset of Files

The (transitive) set of files to be added to the runfiles. The depset should use the default order (which, as the name implies, is the default).

collect_data

bool

Use of this parameter is not recommended. See runfiles guide.

Whether to collect the data runfiles from the dependencies in srcs, data and deps attributes.

collect_default

bool

Use of this parameter is not recommended. See runfiles guide.

Whether to collect the default runfiles from the dependencies in srcs, data and deps attributes.

dict

The map of symlinks to be added to the runfiles, prefixed by workspace name.

dict

The map of symlinks to be added to the runfiles.

split_attr

struct ctx.split_attr

A struct to access the values of attributes with split configurations. If the attribute is a label list, the value of split_attr is a dict of the keys of the split (as strings) to lists of the ConfiguredTargets in that branch of the split. If the attribute is a label, then the value of split_attr is a dict of the keys of the split (as strings) to single ConfiguredTargets. Attributes with split configurations still appear in the attr struct, but their values will be single lists with all the branches of the split merged together.

target_platform_has_constraint

bool ctx.target_platform_has_constraint(constraintValue)

Returns true if the given constraint value is part of the current target platform.

Parameters

Parameter Description
constraintValue

ConstraintValueInfo

The constraint value to check the target platform against.

toolchains

ToolchainContext ctx.toolchains

Toolchains for the default exec group of this rule.

var

dict ctx.var

Dictionary (String to String) of configuration variables.

workspace_name

string ctx.workspace_name

Returns the workspace name as defined in the WORKSPACE file.