Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: provide example how to convert target addresses to source files in rules API #20524

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ class MyTarget(Target):
Then, to resolve the addresses, you can use `UnparsedAddressInputs`:

```python
from pants.engine.addresses import Address, Addresses, UnparsedAddressInputs
from pants.engine.addresses import Addresses, UnparsedAddressInputs
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unused import

from pants.engine.target import Targets
from pants.engine.rules import Get, rule

Expand Down Expand Up @@ -291,6 +291,30 @@ async def demo(...) -> Foo:

`SourceFilesRequest` expects an iterable of `SourcesField` objects. `SourceFiles` has a field `snapshot: Snapshot` with the merged snapshot of all resolved input sources fields.

To convert a list of target addresses to existing source file names, you can request `HydratedSources` for every input target:

```python
from itertools import chain
from pants.engine.addresses import Addresses
from pants.engine.collection import DeduplicatedCollection
from pants.engine.rules import Get, MultiGet, rule
from pants.engine.target import (HydratedSources, HydrateSourcesRequest, SourcesField, UnexpandedTargets)


class ProjectSources(DeduplicatedCollection[str]):
pass


@rule
async def addresses_to_source_files(addresses: Addresses) -> ProjectSources:
targets = await Get(UnexpandedTargets, Addresses, addresses)
all_sources = await MultiGet(Get(HydratedSources, HydrateSourcesRequest(tgt.get(SourcesField))) for tgt in targets)
return ProjectSources(chain.from_iterable(sources.snapshot.files for sources in all_sources))
```

This is often useful when you need to pass target addresses to commands that are not Pants goals and would not
be able to interpret them properly.

### Enabling codegen

If you want your plugin to work with code generation, you must set the argument `enable_codegen=True`, along with `for_sources_types` with the types of `SourcesField` you're expecting.
Expand Down
Loading