Skip to content

publish

AYONPyblishPluginMixin

Source code in client/ayon_core/pipeline/publish/publish_plugins.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
class AYONPyblishPluginMixin:
    # TODO
    # executable_in_thread = False
    #
    # state_message = None
    # state_percent = None
    # _state_change_callbacks = []
    #
    # def set_state(self, percent=None, message=None):
    #     """Inner callback of plugin that would help to show in UI state.
    #
    #     Plugin have registered callbacks on state change which could trigger
    #     update message and percent in UI and repaint the change.
    #
    #     This part must be optional and should not be used to display errors
    #     or for logging.
    #
    #     Message should be short without details.
    #
    #     Args:
    #         percent(int): Percent of processing in range <1-100>.
    #         message(str): Message which will be shown to user (if in UI).
    #     """
    #     if percent is not None:
    #         self.state_percent = percent
    #
    #     if message:
    #         self.state_message = message
    #
    #     for callback in self._state_change_callbacks:
    #         callback(self)

    @classmethod
    def register_create_context_callbacks(
        cls, create_context: "CreateContext"
    ):
        """Register callbacks for create context.

        It is possible to register callbacks listening to changes happened
        in create context.

        Methods available on create context:
        - add_instances_added_callback
        - add_instances_removed_callback
        - add_value_changed_callback
        - add_pre_create_attr_defs_change_callback
        - add_create_attr_defs_change_callback
        - add_publish_attr_defs_change_callback

        Args:
            create_context (CreateContext): Create context.

        """
        pass

    @classmethod
    def get_attribute_defs(cls):
        """Publish attribute definitions.

        Attributes available for all families in plugin's `families` attribute.

        Returns:
            list[AbstractAttrDef]: Attribute definitions for plugin.

        """
        return []

    @classmethod
    def get_attr_defs_for_context(cls, create_context: "CreateContext"):
        """Publish attribute definitions for context.

        Attributes available for all families in plugin's `families` attribute.

        Args:
            create_context (CreateContext): Create context.

        Returns:
            list[AbstractAttrDef]: Attribute definitions for plugin.

        """
        if cls.__instanceEnabled__:
            return []
        return cls.get_attribute_defs()

    @classmethod
    def instance_matches_plugin_families(
        cls, instance: Optional["CreatedInstance"]
    ):
        """Check if instance matches families.

        Args:
            instance (Optional[CreatedInstance]): Instance to check. Or None
                for context.

        Returns:
            bool: True if instance matches plugin families.

        """
        if instance is None:
            return not cls.__instanceEnabled__

        if not cls.__instanceEnabled__:
            return False

        families = [instance.product_base_type]
        families.extend(instance.families)
        for _ in pyblish.logic.plugins_by_families([cls], families):
            return True
        return False

    @classmethod
    def get_attr_defs_for_instance(
        cls, create_context: "CreateContext", instance: "CreatedInstance"
    ):
        """Publish attribute definitions for an instance.

        Attributes available for all families in plugin's `families` attribute.

        Args:
            create_context (CreateContext): Create context.
            instance (CreatedInstance): Instance for which attributes are
                collected.

        Returns:
            list[AbstractAttrDef]: Attribute definitions for plugin.

        """
        if not cls.instance_matches_plugin_families(instance):
            return []
        return cls.get_attribute_defs()

    @classmethod
    def convert_attribute_values(
        cls, create_context: "CreateContext", instance: "CreatedInstance"
    ):
        """Convert attribute values for instance.

        Args:
            create_context (CreateContext): Create context.
            instance (CreatedInstance): Instance for which attributes are
                converted.

        """
        return

    @staticmethod
    def get_attr_values_from_data_for_plugin(plugin, data):
        """Get attribute values for attribute definitions from data.

        Args:
            plugin (Union[publish.api.Plugin, Type[publish.api.Plugin]]): The
                plugin for which attributes are extracted.
            data(dict): Data from instance or context.
        """

        if not inspect.isclass(plugin):
            plugin = plugin.__class__

        return (
            data
            .get("publish_attributes", {})
            .get(plugin.__name__, {})
        )

    def get_attr_values_from_data(self, data):
        """Get attribute values for attribute definitions from data.

        Args:
            data(dict): Data from instance or context.
        """

        return self.get_attr_values_from_data_for_plugin(self.__class__, data)

convert_attribute_values(create_context, instance) classmethod

Convert attribute values for instance.

Parameters:

Name Type Description Default
create_context CreateContext

Create context.

required
instance CreatedInstance

Instance for which attributes are converted.

required
Source code in client/ayon_core/pipeline/publish/publish_plugins.py
267
268
269
270
271
272
273
274
275
276
277
278
279
@classmethod
def convert_attribute_values(
    cls, create_context: "CreateContext", instance: "CreatedInstance"
):
    """Convert attribute values for instance.

    Args:
        create_context (CreateContext): Create context.
        instance (CreatedInstance): Instance for which attributes are
            converted.

    """
    return

get_attr_defs_for_context(create_context) classmethod

Publish attribute definitions for context.

Attributes available for all families in plugin's families attribute.

Parameters:

Name Type Description Default
create_context CreateContext

Create context.

required

Returns:

Type Description

list[AbstractAttrDef]: Attribute definitions for plugin.

Source code in client/ayon_core/pipeline/publish/publish_plugins.py
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
@classmethod
def get_attr_defs_for_context(cls, create_context: "CreateContext"):
    """Publish attribute definitions for context.

    Attributes available for all families in plugin's `families` attribute.

    Args:
        create_context (CreateContext): Create context.

    Returns:
        list[AbstractAttrDef]: Attribute definitions for plugin.

    """
    if cls.__instanceEnabled__:
        return []
    return cls.get_attribute_defs()

get_attr_defs_for_instance(create_context, instance) classmethod

Publish attribute definitions for an instance.

Attributes available for all families in plugin's families attribute.

Parameters:

Name Type Description Default
create_context CreateContext

Create context.

required
instance CreatedInstance

Instance for which attributes are collected.

required

Returns:

Type Description

list[AbstractAttrDef]: Attribute definitions for plugin.

Source code in client/ayon_core/pipeline/publish/publish_plugins.py
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
@classmethod
def get_attr_defs_for_instance(
    cls, create_context: "CreateContext", instance: "CreatedInstance"
):
    """Publish attribute definitions for an instance.

    Attributes available for all families in plugin's `families` attribute.

    Args:
        create_context (CreateContext): Create context.
        instance (CreatedInstance): Instance for which attributes are
            collected.

    Returns:
        list[AbstractAttrDef]: Attribute definitions for plugin.

    """
    if not cls.instance_matches_plugin_families(instance):
        return []
    return cls.get_attribute_defs()

get_attr_values_from_data(data)

Get attribute values for attribute definitions from data.

Parameters:

Name Type Description Default
data dict

Data from instance or context.

required
Source code in client/ayon_core/pipeline/publish/publish_plugins.py
300
301
302
303
304
305
306
307
def get_attr_values_from_data(self, data):
    """Get attribute values for attribute definitions from data.

    Args:
        data(dict): Data from instance or context.
    """

    return self.get_attr_values_from_data_for_plugin(self.__class__, data)

get_attr_values_from_data_for_plugin(plugin, data) staticmethod

Get attribute values for attribute definitions from data.

Parameters:

Name Type Description Default
plugin Union[Plugin, Type[Plugin]]

The plugin for which attributes are extracted.

required
data dict

Data from instance or context.

required
Source code in client/ayon_core/pipeline/publish/publish_plugins.py
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
@staticmethod
def get_attr_values_from_data_for_plugin(plugin, data):
    """Get attribute values for attribute definitions from data.

    Args:
        plugin (Union[publish.api.Plugin, Type[publish.api.Plugin]]): The
            plugin for which attributes are extracted.
        data(dict): Data from instance or context.
    """

    if not inspect.isclass(plugin):
        plugin = plugin.__class__

    return (
        data
        .get("publish_attributes", {})
        .get(plugin.__name__, {})
    )

get_attribute_defs() classmethod

Publish attribute definitions.

Attributes available for all families in plugin's families attribute.

Returns:

Type Description

list[AbstractAttrDef]: Attribute definitions for plugin.

Source code in client/ayon_core/pipeline/publish/publish_plugins.py
191
192
193
194
195
196
197
198
199
200
201
@classmethod
def get_attribute_defs(cls):
    """Publish attribute definitions.

    Attributes available for all families in plugin's `families` attribute.

    Returns:
        list[AbstractAttrDef]: Attribute definitions for plugin.

    """
    return []

instance_matches_plugin_families(instance) classmethod

Check if instance matches families.

Parameters:

Name Type Description Default
instance Optional[CreatedInstance]

Instance to check. Or None for context.

required

Returns:

Name Type Description
bool

True if instance matches plugin families.

Source code in client/ayon_core/pipeline/publish/publish_plugins.py
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
@classmethod
def instance_matches_plugin_families(
    cls, instance: Optional["CreatedInstance"]
):
    """Check if instance matches families.

    Args:
        instance (Optional[CreatedInstance]): Instance to check. Or None
            for context.

    Returns:
        bool: True if instance matches plugin families.

    """
    if instance is None:
        return not cls.__instanceEnabled__

    if not cls.__instanceEnabled__:
        return False

    families = [instance.product_base_type]
    families.extend(instance.families)
    for _ in pyblish.logic.plugins_by_families([cls], families):
        return True
    return False

register_create_context_callbacks(create_context) classmethod

Register callbacks for create context.

It is possible to register callbacks listening to changes happened in create context.

Methods available on create context: - add_instances_added_callback - add_instances_removed_callback - add_value_changed_callback - add_pre_create_attr_defs_change_callback - add_create_attr_defs_change_callback - add_publish_attr_defs_change_callback

Parameters:

Name Type Description Default
create_context CreateContext

Create context.

required
Source code in client/ayon_core/pipeline/publish/publish_plugins.py
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
@classmethod
def register_create_context_callbacks(
    cls, create_context: "CreateContext"
):
    """Register callbacks for create context.

    It is possible to register callbacks listening to changes happened
    in create context.

    Methods available on create context:
    - add_instances_added_callback
    - add_instances_removed_callback
    - add_value_changed_callback
    - add_pre_create_attr_defs_change_callback
    - add_create_attr_defs_change_callback
    - add_publish_attr_defs_change_callback

    Args:
        create_context (CreateContext): Create context.

    """
    pass

AbstractCollectRender

Bases: ContextPlugin

Gather all publishable render layers from renderSetup.

Source code in client/ayon_core/pipeline/publish/abstract_collect_render.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
class AbstractCollectRender(
    pyblish.api.ContextPlugin, metaclass=AbstractMetaContextPlugin
):
    """Gather all publishable render layers from renderSetup."""

    order = pyblish.api.CollectorOrder + 0.01
    label = "Collect Render"
    sync_workfile_version = False

    def __init__(self, *args, **kwargs):
        """Constructor."""
        super(AbstractCollectRender, self).__init__(*args, **kwargs)
        self._file_path = None
        self._context = None

    def process(self, context):
        """Entry point to collector."""
        self._context = context
        for instance in context:
            # make sure workfile instance publishing is enabled
            try:
                if "workfile" in instance.data["families"]:
                    instance.data["publish"] = True
                # TODO merge renderFarm and render.farm
                if ("renderFarm" in instance.data["families"] or
                        "render.farm" in instance.data["families"]):
                    instance.data["remove"] = True
            except KeyError:
                # be tolerant if 'families' is missing.
                pass

        self._file_path = context.data["currentFile"].replace("\\", "/")

        render_instances = self.get_instances(context)
        for render_instance in render_instances:
            exp_files = self.get_expected_files(render_instance)
            assert exp_files, "no file names were generated, this is bug"

            # if we want to attach render to product, check if we have AOV's
            # in expectedFiles. If so, raise error as we cannot attach AOV
            # (considered to be product on its own) to another product
            if render_instance.attachTo:
                assert isinstance(exp_files, list), (
                    "attaching multiple AOVs or renderable cameras to "
                    "product is not supported"
                )

            frame_start_render = int(render_instance.frameStart)
            frame_end_render = int(render_instance.frameEnd)
            # TODO: Refactor hacky frame range workaround below
            if (render_instance.ignoreFrameHandleCheck or
                    int(context.data['frameStartHandle']) == frame_start_render
                    and int(context.data['frameEndHandle']) == frame_end_render):  # noqa: W503, E501
                # only for Harmony where frame range cannot be set by DB
                handle_start = context.data['handleStart']
                handle_end = context.data['handleEnd']
                frame_start = context.data['frameStart']
                frame_end = context.data['frameEnd']
                frame_start_handle = context.data['frameStartHandle']
                frame_end_handle = context.data['frameEndHandle']
            elif (hasattr(render_instance, "frameStartHandle")
                  and hasattr(render_instance, "frameEndHandle")):
                handle_start = int(render_instance.handleStart)
                handle_end = int(render_instance.handleEnd)
                frame_start = int(render_instance.frameStart)
                frame_end = int(render_instance.frameEnd)
                frame_start_handle = int(render_instance.frameStartHandle)
                frame_end_handle = int(render_instance.frameEndHandle)
            else:
                handle_start = 0
                handle_end = 0
                frame_start = frame_start_render
                frame_end = frame_end_render
                frame_start_handle = frame_start_render
                frame_end_handle = frame_end_render

            data = {
                "handleStart": handle_start,
                "handleEnd": handle_end,
                "frameStart": frame_start,
                "frameEnd": frame_end,
                "frameStartHandle": frame_start_handle,
                "frameEndHandle": frame_end_handle,
                "byFrameStep": int(render_instance.frameStep),

                "author": context.data["user"],
                # Add source to allow tracing back to the scene from
                # which was submitted originally
                "expectedFiles": exp_files,
            }
            if self.sync_workfile_version:
                data["version"] = context.data["version"]

            # add additional data
            data = self.add_additional_data(data)

            instance = render_instance.source_instance
            if instance is None:
                instance = context.create_instance(render_instance.name)

            render_instance_dict = attr.asdict(render_instance)
            instance.data.update(render_instance_dict)
            instance.data.update(data)

        self.post_collecting_action()

    @abstractmethod
    def get_instances(self, context):
        """Get all renderable instances and their data.

        Args:
            context (pyblish.api.Context): Context object.

        Returns:
            list of :class:`RenderInstance`: All collected renderable instances
                (like render layers, write nodes, etc.)

        """
        pass

    @abstractmethod
    def get_expected_files(self, render_instance):
        """Get list of expected files.

        Returns:
            list: expected files. This can be either simple list of files with
                their paths, or list of dictionaries, where key is name of AOV
                for example and value is list of files for that AOV.

        Example::

            ['/path/to/file.001.exr', '/path/to/file.002.exr']

            or as dictionary:

            [
                {
                    "beauty": ['/path/to/beauty.001.exr', ...],
                    "mask": ['/path/to/mask.001.exr']
                }
            ]

        """
        pass

    def add_additional_data(self, data):
        """Add additional data to collected instance.

        This can be overridden by host implementation to add custom
        additional data.

        """
        return data

    def post_collecting_action(self):
        """Execute some code after collection is done.

        This is useful for example for restoring current render layer.

        """
        pass

__init__(*args, **kwargs)

Constructor.

Source code in client/ayon_core/pipeline/publish/abstract_collect_render.py
134
135
136
137
138
def __init__(self, *args, **kwargs):
    """Constructor."""
    super(AbstractCollectRender, self).__init__(*args, **kwargs)
    self._file_path = None
    self._context = None

add_additional_data(data)

Add additional data to collected instance.

This can be overridden by host implementation to add custom additional data.

Source code in client/ayon_core/pipeline/publish/abstract_collect_render.py
270
271
272
273
274
275
276
277
def add_additional_data(self, data):
    """Add additional data to collected instance.

    This can be overridden by host implementation to add custom
    additional data.

    """
    return data

get_expected_files(render_instance) abstractmethod

Get list of expected files.

Returns:

Name Type Description
list

expected files. This can be either simple list of files with their paths, or list of dictionaries, where key is name of AOV for example and value is list of files for that AOV.

Example::

['/path/to/file.001.exr', '/path/to/file.002.exr']

or as dictionary:

[
    {
        "beauty": ['/path/to/beauty.001.exr', ...],
        "mask": ['/path/to/mask.001.exr']
    }
]
Source code in client/ayon_core/pipeline/publish/abstract_collect_render.py
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
@abstractmethod
def get_expected_files(self, render_instance):
    """Get list of expected files.

    Returns:
        list: expected files. This can be either simple list of files with
            their paths, or list of dictionaries, where key is name of AOV
            for example and value is list of files for that AOV.

    Example::

        ['/path/to/file.001.exr', '/path/to/file.002.exr']

        or as dictionary:

        [
            {
                "beauty": ['/path/to/beauty.001.exr', ...],
                "mask": ['/path/to/mask.001.exr']
            }
        ]

    """
    pass

get_instances(context) abstractmethod

Get all renderable instances and their data.

Parameters:

Name Type Description Default
context Context

Context object.

required

Returns:

Type Description

list of :class:RenderInstance: All collected renderable instances (like render layers, write nodes, etc.)

Source code in client/ayon_core/pipeline/publish/abstract_collect_render.py
231
232
233
234
235
236
237
238
239
240
241
242
243
@abstractmethod
def get_instances(self, context):
    """Get all renderable instances and their data.

    Args:
        context (pyblish.api.Context): Context object.

    Returns:
        list of :class:`RenderInstance`: All collected renderable instances
            (like render layers, write nodes, etc.)

    """
    pass

post_collecting_action()

Execute some code after collection is done.

This is useful for example for restoring current render layer.

Source code in client/ayon_core/pipeline/publish/abstract_collect_render.py
279
280
281
282
283
284
285
def post_collecting_action(self):
    """Execute some code after collection is done.

    This is useful for example for restoring current render layer.

    """
    pass

process(context)

Entry point to collector.

Source code in client/ayon_core/pipeline/publish/abstract_collect_render.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
def process(self, context):
    """Entry point to collector."""
    self._context = context
    for instance in context:
        # make sure workfile instance publishing is enabled
        try:
            if "workfile" in instance.data["families"]:
                instance.data["publish"] = True
            # TODO merge renderFarm and render.farm
            if ("renderFarm" in instance.data["families"] or
                    "render.farm" in instance.data["families"]):
                instance.data["remove"] = True
        except KeyError:
            # be tolerant if 'families' is missing.
            pass

    self._file_path = context.data["currentFile"].replace("\\", "/")

    render_instances = self.get_instances(context)
    for render_instance in render_instances:
        exp_files = self.get_expected_files(render_instance)
        assert exp_files, "no file names were generated, this is bug"

        # if we want to attach render to product, check if we have AOV's
        # in expectedFiles. If so, raise error as we cannot attach AOV
        # (considered to be product on its own) to another product
        if render_instance.attachTo:
            assert isinstance(exp_files, list), (
                "attaching multiple AOVs or renderable cameras to "
                "product is not supported"
            )

        frame_start_render = int(render_instance.frameStart)
        frame_end_render = int(render_instance.frameEnd)
        # TODO: Refactor hacky frame range workaround below
        if (render_instance.ignoreFrameHandleCheck or
                int(context.data['frameStartHandle']) == frame_start_render
                and int(context.data['frameEndHandle']) == frame_end_render):  # noqa: W503, E501
            # only for Harmony where frame range cannot be set by DB
            handle_start = context.data['handleStart']
            handle_end = context.data['handleEnd']
            frame_start = context.data['frameStart']
            frame_end = context.data['frameEnd']
            frame_start_handle = context.data['frameStartHandle']
            frame_end_handle = context.data['frameEndHandle']
        elif (hasattr(render_instance, "frameStartHandle")
              and hasattr(render_instance, "frameEndHandle")):
            handle_start = int(render_instance.handleStart)
            handle_end = int(render_instance.handleEnd)
            frame_start = int(render_instance.frameStart)
            frame_end = int(render_instance.frameEnd)
            frame_start_handle = int(render_instance.frameStartHandle)
            frame_end_handle = int(render_instance.frameEndHandle)
        else:
            handle_start = 0
            handle_end = 0
            frame_start = frame_start_render
            frame_end = frame_end_render
            frame_start_handle = frame_start_render
            frame_end_handle = frame_end_render

        data = {
            "handleStart": handle_start,
            "handleEnd": handle_end,
            "frameStart": frame_start,
            "frameEnd": frame_end,
            "frameStartHandle": frame_start_handle,
            "frameEndHandle": frame_end_handle,
            "byFrameStep": int(render_instance.frameStep),

            "author": context.data["user"],
            # Add source to allow tracing back to the scene from
            # which was submitted originally
            "expectedFiles": exp_files,
        }
        if self.sync_workfile_version:
            data["version"] = context.data["version"]

        # add additional data
        data = self.add_additional_data(data)

        instance = render_instance.source_instance
        if instance is None:
            instance = context.create_instance(render_instance.name)

        render_instance_dict = attr.asdict(render_instance)
        instance.data.update(render_instance_dict)
        instance.data.update(data)

    self.post_collecting_action()

ColormanagedPyblishPluginMixin

Bases: object

Mixin for colormanaged plugins.

This class is used to set colorspace data to a publishing representation. It contains a static method, get_colorspace_settings, which returns config and file rules data for the host context. It also contains a method, set_representation_colorspace, which sets colorspace data to the representation. The allowed file extensions are listed in the allowed_ext variable. The method first checks if the file extension is in the list of allowed extensions. If it is, it then gets the colorspace settings from the host context and gets a matching colorspace from rules. Finally, it infuses this data into the representation.

Source code in client/ayon_core/pipeline/publish/publish_plugins.py
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
class ColormanagedPyblishPluginMixin(object):
    """Mixin for colormanaged plugins.

    This class is used to set colorspace data to a publishing
    representation. It contains a static method,
    get_colorspace_settings, which returns config and
    file rules data for the host context.
    It also contains a method, set_representation_colorspace,
    which sets colorspace data to the representation.
    The allowed file extensions are listed in the allowed_ext variable.
    The method first checks if the file extension is in
    the list of allowed extensions. If it is, it then gets the
    colorspace settings from the host context and gets a
    matching colorspace from rules. Finally, it infuses this
    data into the representation.
    """

    def get_colorspace_settings(self, context):
        """Returns solved settings for the host context.

        Args:
            context (publish.Context): publishing context

        Returns:
            tuple | bool: config, file rules or None
        """
        return get_colorspace_settings_from_publish_context(context.data)

    def set_representation_colorspace(
        self, representation, context,
        colorspace=None,
    ):
        """Sets colorspace data to representation.

        Args:
            representation (dict): publishing representation
            context (publish.Context): publishing context
            colorspace (str, optional): colorspace name. Defaults to None.

        Example:
            ```
            {
                # for other publish plugins and loaders
                "colorspace": "linear",
                "config": {
                    # for future references in case need
                    "path": "/abs/path/to/config.ocio",
                    # for other plugins within remote publish cases
                    "template": "{project[root]}/path/to/config.ocio"
                }
            }
            ```

        """

        # using cached settings if available
        set_colorspace_data_to_representation(
            representation, context.data,
            colorspace,
            log=self.log
        )

get_colorspace_settings(context)

Returns solved settings for the host context.

Parameters:

Name Type Description Default
context Context

publishing context

required

Returns:

Type Description

tuple | bool: config, file rules or None

Source code in client/ayon_core/pipeline/publish/publish_plugins.py
458
459
460
461
462
463
464
465
466
467
def get_colorspace_settings(self, context):
    """Returns solved settings for the host context.

    Args:
        context (publish.Context): publishing context

    Returns:
        tuple | bool: config, file rules or None
    """
    return get_colorspace_settings_from_publish_context(context.data)

set_representation_colorspace(representation, context, colorspace=None)

Sets colorspace data to representation.

Parameters:

Name Type Description Default
representation dict

publishing representation

required
context Context

publishing context

required
colorspace str

colorspace name. Defaults to None.

None
Example
{
    # for other publish plugins and loaders
    "colorspace": "linear",
    "config": {
        # for future references in case need
        "path": "/abs/path/to/config.ocio",
        # for other plugins within remote publish cases
        "template": "{project[root]}/path/to/config.ocio"
    }
}
Source code in client/ayon_core/pipeline/publish/publish_plugins.py
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
def set_representation_colorspace(
    self, representation, context,
    colorspace=None,
):
    """Sets colorspace data to representation.

    Args:
        representation (dict): publishing representation
        context (publish.Context): publishing context
        colorspace (str, optional): colorspace name. Defaults to None.

    Example:
        ```
        {
            # for other publish plugins and loaders
            "colorspace": "linear",
            "config": {
                # for future references in case need
                "path": "/abs/path/to/config.ocio",
                # for other plugins within remote publish cases
                "template": "{project[root]}/path/to/config.ocio"
            }
        }
        ```

    """

    # using cached settings if available
    set_colorspace_data_to_representation(
        representation, context.data,
        colorspace,
        log=self.log
    )

ExpectedFiles

Bases: ABC

Class grouping functionality for all supported renderers.

Attributes:

Name Type Description
multipart bool

Flag if multipart exrs are used.

Source code in client/ayon_core/pipeline/publish/abstract_expected_files.py
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class ExpectedFiles(ABC):
    """Class grouping functionality for all supported renderers.

    Attributes:
        multipart (bool): Flag if multipart exrs are used.

    """

    multipart = False

    @abstractmethod
    def get(self, render_instance):
        """Get expected files for given renderer and render layer.

        This method should return dictionary of all files we are expecting
        to be rendered from the host. Usually `render_instance` corresponds
        to *render layer*. Result can be either flat list with the file
        paths or it can be list of dictionaries. Each key corresponds to
        for example AOV name or channel, etc.

        Example::

            ['/path/to/file.001.exr', '/path/to/file.002.exr']

            or as dictionary:

            [
                {
                    "beauty": ['/path/to/beauty.001.exr', ...],
                    "mask": ['/path/to/mask.001.exr']
                }
            ]


        Args:
            render_instance (:class:`RenderInstance`): Data passed from
                collector to determine files. This should be instance of
                :class:`abstract_collect_render.RenderInstance`

        Returns:
            list: Full paths to expected rendered files.
            list of dict: Path to expected rendered files categorized by
                AOVs, etc.

        """
        raise NotImplementedError()

get(render_instance) abstractmethod

Get expected files for given renderer and render layer.

This method should return dictionary of all files we are expecting to be rendered from the host. Usually render_instance corresponds to render layer. Result can be either flat list with the file paths or it can be list of dictionaries. Each key corresponds to for example AOV name or channel, etc.

Example::

['/path/to/file.001.exr', '/path/to/file.002.exr']

or as dictionary:

[
    {
        "beauty": ['/path/to/beauty.001.exr', ...],
        "mask": ['/path/to/mask.001.exr']
    }
]

Parameters:

Name Type Description Default
render_instance (

class:RenderInstance): Data passed from collector to determine files. This should be instance of :class:abstract_collect_render.RenderInstance

required

Returns:

Name Type Description
list

Full paths to expected rendered files.

list of dict: Path to expected rendered files categorized by AOVs, etc.

Source code in client/ayon_core/pipeline/publish/abstract_expected_files.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
@abstractmethod
def get(self, render_instance):
    """Get expected files for given renderer and render layer.

    This method should return dictionary of all files we are expecting
    to be rendered from the host. Usually `render_instance` corresponds
    to *render layer*. Result can be either flat list with the file
    paths or it can be list of dictionaries. Each key corresponds to
    for example AOV name or channel, etc.

    Example::

        ['/path/to/file.001.exr', '/path/to/file.002.exr']

        or as dictionary:

        [
            {
                "beauty": ['/path/to/beauty.001.exr', ...],
                "mask": ['/path/to/mask.001.exr']
            }
        ]


    Args:
        render_instance (:class:`RenderInstance`): Data passed from
            collector to determine files. This should be instance of
            :class:`abstract_collect_render.RenderInstance`

    Returns:
        list: Full paths to expected rendered files.
        list of dict: Path to expected rendered files categorized by
            AOVs, etc.

    """
    raise NotImplementedError()

Extractor

Bases: InstancePlugin

Extractor base class.

The extractor base class implements a "staging_dir" function used to generate a temporary directory for an instance to extract to.

This temporary directory is generated through tempfile.mkdtemp()

Source code in client/ayon_core/pipeline/publish/publish_plugins.py
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
class Extractor(pyblish.api.InstancePlugin):
    """Extractor base class.

    The extractor base class implements a "staging_dir" function used to
    generate a temporary directory for an instance to extract to.

    This temporary directory is generated through `tempfile.mkdtemp()`

    """

    order = 2.0

    def staging_dir(self, instance):
        """Provide a temporary directory in which to store extracted files

        Upon calling this method the staging directory is stored inside
        the instance.data['stagingDir']
        """

        return get_instance_staging_dir(instance)

staging_dir(instance)

Provide a temporary directory in which to store extracted files

Upon calling this method the staging directory is stored inside the instance.data['stagingDir']

Source code in client/ayon_core/pipeline/publish/publish_plugins.py
431
432
433
434
435
436
437
438
def staging_dir(self, instance):
    """Provide a temporary directory in which to store extracted files

    Upon calling this method the staging directory is stored inside
    the instance.data['stagingDir']
    """

    return get_instance_staging_dir(instance)

IntegrationTemplateItem

Represents single template item.

Template path, template data that was used in the template.

Attributes:

Name Type Description
anatomy Anatomy

Anatomy object.

template_data dict[str, Any]

Template data.

template_object TemplateItem

Template object

Source code in client/ayon_core/pipeline/publish/lib.py
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
class IntegrationTemplateItem:
    """Represents single template item.

    Template path, template data that was used in the template.

    Attributes:
        anatomy (Anatomy): Anatomy object.
        template_data (dict[str, Any]): Template data.
        template_object (AnatomyTemplateItem): Template object
    """
    anatomy: Anatomy
    template_data: dict[str, Any]
    template_object: "AnatomyTemplateItem"

    def __init__(self,
        anatomy: "Anatomy",
        template_data: dict[str, Any],
        template_object: "AnatomyTemplateItem",
    ) -> None:
        """Initialize TemplateItem.

        Args:
            anatomy (Anatomy): Anatomy object.
            template_data (dict[str, Any]): Template data.
            template_object (AnatomyTemplateItem): Template object.

        """
        self.anatomy = anatomy
        self.template_data = template_data
        self.template_object = template_object

__init__(anatomy, template_data, template_object)

Initialize TemplateItem.

Parameters:

Name Type Description Default
anatomy Anatomy

Anatomy object.

required
template_data dict[str, Any]

Template data.

required
template_object TemplateItem

Template object.

required
Source code in client/ayon_core/pipeline/publish/lib.py
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
def __init__(self,
    anatomy: "Anatomy",
    template_data: dict[str, Any],
    template_object: "AnatomyTemplateItem",
) -> None:
    """Initialize TemplateItem.

    Args:
        anatomy (Anatomy): Anatomy object.
        template_data (dict[str, Any]): Template data.
        template_object (AnatomyTemplateItem): Template object.

    """
    self.anatomy = anatomy
    self.template_data = template_data
    self.template_object = template_object

KnownPublishError

Bases: Exception

Publishing crashed because of known error.

Artist can't affect source of the error.

Deprecated

Please use PublishError instead. Marked as deprecated 24/09/02.

Source code in client/ayon_core/pipeline/publish/publish_plugins.py
39
40
41
42
43
44
45
46
47
48
class KnownPublishError(Exception):
    """Publishing crashed because of known error.

    Artist can't affect source of the error.

    Deprecated:
        Please use `PublishError` instead. Marked as deprecated 24/09/02.

    """
    pass

OptionalPyblishPluginMixin

Bases: AYONPyblishPluginMixin

Prepare mixin for optional plugins.

Defined active attribute definition prepared for published and prepares method which will check if is active or not.

class ValidateScene(
    pyblish.api.InstancePlugin, OptionalPyblishPluginMixin
):
    def process(self, instance):
        # Skip the instance if is not active by data on the instance
        if not self.is_active(instance.data):
            return
Source code in client/ayon_core/pipeline/publish/publish_plugins.py
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
class OptionalPyblishPluginMixin(AYONPyblishPluginMixin):
    """Prepare mixin for optional plugins.

    Defined active attribute definition prepared for published and
    prepares method which will check if is active or not.

    ```
    class ValidateScene(
        pyblish.api.InstancePlugin, OptionalPyblishPluginMixin
    ):
        def process(self, instance):
            # Skip the instance if is not active by data on the instance
            if not self.is_active(instance.data):
                return
    ```
    """

    # Allow exposing tooltip from class with `optional_tooltip` attribute
    optional_tooltip: Optional[str] = None

    @classmethod
    def get_attribute_defs(cls):
        """Attribute definitions based on plugin's optional attribute."""

        # Empty list if plugin is not optional
        if not getattr(cls, "optional", None):
            return []

        # Get active value from class as default value
        active = getattr(cls, "active", True)
        # Return boolean stored under 'active' key with label of the class name
        label = cls.label or cls.__name__

        return [
            BoolDef(
                "active",
                default=active,
                label=label,
                tooltip=cls.optional_tooltip,
            )
        ]

    def is_active(self, data):
        """Check if plugins is active for instance/context based on their data.

        Args:
            data(dict): Data from instance or context.
        """
        # Skip if is not optional and return True
        if not getattr(self, "optional", None):
            return True
        attr_values = self.get_attr_values_from_data(data)
        active = attr_values.get("active")
        if active is None:
            active = getattr(self, "active", True)
        return active

get_attribute_defs() classmethod

Attribute definitions based on plugin's optional attribute.

Source code in client/ayon_core/pipeline/publish/publish_plugins.py
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
@classmethod
def get_attribute_defs(cls):
    """Attribute definitions based on plugin's optional attribute."""

    # Empty list if plugin is not optional
    if not getattr(cls, "optional", None):
        return []

    # Get active value from class as default value
    active = getattr(cls, "active", True)
    # Return boolean stored under 'active' key with label of the class name
    label = cls.label or cls.__name__

    return [
        BoolDef(
            "active",
            default=active,
            label=label,
            tooltip=cls.optional_tooltip,
        )
    ]

is_active(data)

Check if plugins is active for instance/context based on their data.

Parameters:

Name Type Description Default
data dict

Data from instance or context.

required
Source code in client/ayon_core/pipeline/publish/publish_plugins.py
352
353
354
355
356
357
358
359
360
361
362
363
364
365
def is_active(self, data):
    """Check if plugins is active for instance/context based on their data.

    Args:
        data(dict): Data from instance or context.
    """
    # Skip if is not optional and return True
    if not getattr(self, "optional", None):
        return True
    attr_values = self.get_attr_values_from_data(data)
    active = attr_values.get("active")
    if active is None:
        active = getattr(self, "active", True)
    return active

PublishActionResult dataclass

Result of triggered action.

Attributes:

Name Type Description
success bool

Whether action was successful.

action ActionType

Triggered action.

exception Exception | None

Exception that happened if success is 'False'.

Source code in client/ayon_core/pipeline/publish/logic.py
305
306
307
308
309
310
311
312
313
314
315
316
317
318
@dataclass
class PublishActionResult:
    """Result of triggered action.

    Attributes:
        success (bool): Whether action was successful.
        action (ActionType): Triggered action.
        exception (Exception | None): Exception that happened if success is
            'False'.

    """
    success: bool
    action: ActionType
    exception: Exception | None = None

PublishError

Bases: Exception

Publishing crashed because of known error.

Message will be shown in UI for artist.

Parameters:

Name Type Description Default
message str

Message of error. Short explanation an issue.

required
title Optional[str]

Title showed in UI.

None
description Optional[str]

Detailed description of an error. It is possible to use Markdown syntax.

None
Source code in client/ayon_core/pipeline/publish/publish_plugins.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class PublishError(Exception):
    """Publishing crashed because of known error.

    Message will be shown in UI for artist.

    Args:
        message (str): Message of error. Short explanation an issue.
        title (Optional[str]): Title showed in UI.
        description (Optional[str]): Detailed description of an error.
            It is possible to use Markdown syntax.

    """
    def __init__(self, message, title=None, description=None, detail=None):
        self.message = message
        self.title = title
        self.description = description or message
        self.detail = detail
        super().__init__(message)

PublishLogic

Wrapper for publising logic.

This class is used to manage publishing logic. Can be used to run publishing and then create publish report.

Parameters:

Name Type Description Default
reset bool

Reset publish logic with current context on initialization. If False, an explicit reset has to be called before publishing.

True
Source code in client/ayon_core/pipeline/publish/logic.py
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
class PublishLogic:
    """Wrapper for publising logic.

    This class is used to manage publishing logic. Can be used to run
        publishing and then create publish report.

    Args:
        reset (bool): Reset publish logic with current context
            on initialization. If False, an explicit reset has to be called
            before publishing.

    """
    def __init__(self, *, reset=True) -> None:
        self._log_handler: MessageHandler = MessageHandler()

        self._log_to_console: bool = True

        self._publish_state: PublishState = PublishState()

        self._publish_plugins: list[PluginType] = []
        self._publish_plugins_by_id: dict[str, PluginType] = {}
        self._publish_plugins_by_name: dict[str, PluginType] = {}

        # pyblish.api.Context
        self._pyblish_context: pyblish.api.Context = pyblish.api.Context()
        # Pyblish report
        self._publish_report: PublishReportMaker = PublishReportMaker()

        # Plugin iterator
        self._publish_iterator: _PublishIterator = _PublishIterator()

        if reset:
            self.reset_with_current_context()

    def reset_with_current_context(self) -> None:
        """Reset publish logic with current context."""
        from ayon_core.pipeline.create import CreateContext
        from ayon_core.pipeline.context_tools import (
            registered_host,
            get_current_project_name,
        )

        host = registered_host()
        create_context = None
        if host is not None:
            create_context = CreateContext(host)

        if create_context is not None:
            self.reset_from_create_context(create_context)
            return

        project_name = get_current_project_name()
        self.reset(project_name)

    def reset(
        self,
        project_name: str,
        context: pyblish.api.Context | None = None,
        plugins: list[PluginType] | None = None,
        targets: list[str] | None = None,
        create_context: CreateContext | None = None,
        publish_discover_result: DiscoverResult | None = None,
        project_settings: dict[str, Any] | None = None,
    ) -> None:
        """Reset publish logic with given parameters.

        Args:
            project_name (str): Name of the project.
            context (pyblish.api.Context | None): Pyblish context to use.
                If None, a new context will be created.
            plugins (list[PluginType] | None): List of publish plugins to use.
                If None, plugins will be discovered.
            targets (list[str] | None): List of publish targets to use.
                If None, all registered targets will be used.
            create_context (CreateContext | None): Create context to use.
                If None, a new create context will be created if possible.
            publish_discover_result (DiscoverResult | None): Discover result
                for publish plugins. If None, plugins will be discovered.

        """
        if plugins is not None and publish_discover_result is None:
            publish_discover_result = DiscoverResult(pyblish.api.Plugin)
            publish_discover_result.plugins = plugins

        self._reset(
            project_name,
            publish_context=context,
            publish_targets=targets,
            create_context=create_context,
            publish_discover_result=publish_discover_result,
            project_settings=project_settings,
        )

    def reset_from_create_context(
        self,
        create_context: CreateContext,
        context: pyblish.api.Context | None = None,
        targets: list[str] | None = None,
    ) -> None:
        """Reset publish logic with given create context.

        Args:
            create_context (CreateContext): Create context to use.
            context (pyblish.api.Context | None): Pyblish context to use.
                If None, a new context will be created.
            targets (list[str] | None): List of publish targets to use.
                If None, all registered targets will be used.

        """
        self._reset(
            create_context.project_name,
            publish_context=context,
            publish_targets=targets,
            publish_discover_result=create_context.publish_discover_result,
            creator_discover_result=create_context.creator_discover_result,
            convertor_discover_result=create_context.convertor_discover_result,
            create_context=create_context,
        )

    @staticmethod
    def get_publish_plugin_id(plugin: PluginType) -> str:
        """Get id of plugin based on plugin object.

        It's used for validation errors report.

        Args:
            plugin (PluginType): Publish plugin for which id should
                be returned.

        Returns:
            str: Plugin id.

        """
        return plugin.id

    def get_pyblish_context(self) -> pyblish.api.Context:
        """Get pyblish context used for publishing."""
        return self._pyblish_context

    pyblish_context: pyblish.api.Context = property(get_pyblish_context)

    def get_publish_plugin_by_id(
        self, plugin_id: str
    ) -> PluginType | None:
        return self._publish_plugins_by_id.get(plugin_id)

    def get_publish_plugin_by_name(
        self, plugin_name: str
    ) -> PluginType | None:
        return self._publish_plugins_by_name.get(plugin_name)

    def set_log_to_console(self, value: bool) -> None:
        """Set whether to log to console."""
        self._log_to_console = value

    def iter_publish_plugins(self) -> Iterable[PluginType]:
        """Iterate over publish plugins.

        Give developers access to publish plugins that are used in current
            publishing process. Can be used to change their attributes, e.g.
            to disable them.

        Returns:
            Iterable[PluginType]: Iterable with publish plugins.

        """
        yield from self._publish_plugins

    def publish(self) -> None:
        for info in self.publish_iter():
            info()

    def publish_iter(self) -> Generator[PublishIterTask, None, None]:
        """Publish iteration generator.

        Yields:
            PublishIterTask: Information about next processing function in
                publishing. Can be called to process the next function.

        """
        self._publish_state.is_running = True
        self._publish_state.started = True
        for task in self._publish_iterator:
            yield task

    def get_stop_after_validation(self) -> bool:
        """Check if publishing will stop after validation.

        Returns:
            bool: True if publishing will stop after validation,
                False otherwise.

        """
        return self._publish_state.stop_after_validation

    def set_stop_after_validation(self, value: bool) -> None:
        """Publishing will stop after validation.

        Args:
            value (bool): If True, publishing will stop after validation.

        """
        self._publish_state.stop_after_validation = value

    def set_strict_validation_error_handling(self, value: bool) -> None:
        """Set strict validation error handling.

        Args:
            value (bool): If True, publishing will stop after validation.

        """
        self._publish_state.strict_validation_error_handling = value

    def stop_publish(self) -> None:
        """Mark publishing to stop on next iteration.

        This is useful for UI purposes.
        """
        self._publish_state.is_running = False

    def is_running(self) -> bool:
        """Check if publishing is currently meant to be running.

        It is possible that publishing is currently in process of stopping,
            but this method will return False.

        Returns:
            bool: True if publishing is currently meant to be running,
                False otherwise.

        """
        return self._publish_state.is_running

    def has_started(self) -> bool:
        """Publishing has started."""
        return self._publish_state.started

    def has_finished(self) -> bool:
        """Publishing has successfully finished.

        It is not possible that 'has_finished' is True and 'has_failed'
            is True at the same time.

        Returns:
            bool: True if publishing has successfully finished,
                False otherwise.

        """
        return self._publish_state.finished

    def has_validated(self) -> bool:
        """Validation order passed.

        Returns:
            bool: True if validation order passed, False otherwise.

        """
        return self._publish_state.validated

    def publish_can_continue(self) -> bool:
        """Publishing can continue.

        Returns:
            bool: True if publishing still can continue, False otherwise.

        """
        return self._publish_state.can_continue()

    def get_progress(self) -> int:
        """Get current progress of publishing.

        Returns:
            int: Current progress of publishing. Value is between 0 and
                max progress. 0 means no plugin was processed yet.

        """
        return self._publish_state.progress

    def get_max_progress(self) -> int:
        """Get max progress of publishing."""
        return self._publish_state.max_progress

    def has_validation_errors(self) -> bool:
        """Check if publishing has validation errors."""
        return bool(self._publish_state.validation_errors)

    def has_failed(self) -> bool:
        """Check if publishing has failed.

        It is possible that publishing even didn't start, or still can
            continue even if publishing has crashed. Don't use this method
            to check if publishing should be running.

        Returns:
            bool: True if publishing has crashed, False otherwise.

        """
        return self._publish_state.fail_reason != PublishFailReason.No

    def get_fail_reason(self) -> PublishFailReason:
        """Get the reason for publishing failure.

        Returns:
            PublishFailReason: The reason for publishing failure.

        """
        return self._publish_state.fail_reason

    def get_publish_report(self) -> PublishReport:
        """Get report for the current state of publishing."""
        self._publish_report.update_publish_instances(self._pyblish_context)
        return self._publish_report.get_report()

    def get_publish_report_data(self) -> dict[str, Any]:
        """Extract publish report data for the current state of publishing.

        This method should be used if report data are being stored to a file.
            It does mark the current plugin as 'passed' for UI report viewer.

        Returns:
            dict[str, Any]: Publish report data.

        """
        report: PublishReport = self.get_publish_report()
        return report.to_data(self._publish_report.current_plugin_id)

    def store_publish_report(self, filepath: str) -> None:
        """Store publish report to a file."""
        report: PublishReport = self.get_publish_report()
        report.store_to_file(
            filepath,
            self._publish_report.current_plugin_id
        )

    def get_error_info(self) -> PublishErrorInfo | None:
        """Get information about publish error.

        Use to get error if fail reason is 'Error'.

        Returns:
            PublishErrorInfo | None: Information about publish error or None
                if no error happened.

        """
        return self._publish_state.error_info

    def get_validation_errors_info(self) -> list[PublishErrorInfo]:
        """Get information about validation errors.

        Use to get errors if fail reason is 'ValidationErrors'.

        Returns:
            list[PublishErrorInfo]: Validation errors info.

        """
        return self._publish_state.validation_errors

    def iter_all_error_info(self) -> Iterable[PublishErrorInfo]:
        """Iterate over all error information."""
        if self._publish_state.error_info is not None:
            yield self._publish_state.error_info
        yield from self._publish_state.validation_errors

    def set_comment(self, comment: str) -> None:
        # Ignore change of comment when publishing started
        if self._publish_state.started:
            raise ValueError(
                "Cannot change comment when publishing started."
            )
        self._pyblish_context.data["comment"] = comment
        self._publish_state.comment_is_set = True

    @staticmethod
    def get_publish_plugin_actions(
        plugin: PluginType
    ) -> list[ActionType]:
        actions = getattr(plugin, "actions", None)
        if isinstance(actions, list):
            return actions
        return []

    def run_action(
        self,
        plugin: PluginType | str,
        action: ActionType | str,
    ) -> PublishActionResult:
        if isinstance(plugin, str):
            _plugin = self._publish_plugins_by_id.get(plugin)
            if _plugin is None:
                _plugin = self._publish_plugins_by_name[plugin]
            plugin = _plugin

        if isinstance(action, str):
            action_id = action
            action = None
            for plugin_action in self.get_publish_plugin_actions(plugin):
                if plugin_action.id == action_id:
                    action = plugin_action
                    break

            if action is None:
                raise ValueError(
                    f"Action '{action_id}' not found in plugin '{plugin}'"
                )

        result = pyblish.plugin.process(
            plugin, self._pyblish_context, None, action.id
        )
        self._publish_report.add_action_result(action, result)

        exception = result.get("error")
        if not exception:
            return PublishActionResult(True, action)
        return PublishActionResult(False, action, exception)

    def _reset(
        self,
        project_name: str,
        publish_context: pyblish.api.Context | None = None,
        publish_targets: list[str] | None = None,
        # Hosts filtering is embedded into pyblish register and discover.
        # - hard to change how it works, can be changed only for paths
        #   discovery
        # publish_hosts: list[str] | None = None,
        publish_discover_result: DiscoverResult | None = None,
        creator_discover_result: DiscoverResult | None = None,
        convertor_discover_result: DiscoverResult | None = None,
        create_context: CreateContext | None = None,
        project_settings: dict[str, Any] | None = None,
    ) -> None:
        # Publish context preparation
        if publish_context is None:
            publish_context = pyblish.api.Context()

        if publish_context.data.get("comment") is None:
            publish_context.data["comment"] = ""

        # Plugins preparation
        if create_context is not None:
            publish_context.data["create_context"] = create_context

            # Use discover results from create context
            if publish_discover_result is None:
                publish_discover_result = (
                    create_context.publish_discover_result
                )
            if creator_discover_result is None:
                creator_discover_result = (
                    create_context.creator_discover_result
                )
            if convertor_discover_result is None:
                convertor_discover_result = (
                    create_context.convertor_discover_result
                )

            if project_settings is None:
                project_settings = (
                    create_context.get_current_project_settings()
                )

        if publish_discover_result is None:
            publish_discover_result: DiscoverResult = (
                publish_plugins_discover()
            )

        if creator_discover_result is None:
            creator_discover_result = DiscoverResult(None)

        if convertor_discover_result is None:
            convertor_discover_result = DiscoverResult(None)

        if project_settings is None:
            project_settings = get_project_settings(project_name)

        discovered_publish_plugins = publish_discover_result.plugins
        crashed_file_paths = publish_discover_result.crashed_file_paths

        if publish_targets is None:
            publish_targets = pyblish.logic.registered_targets()

        publish_targets = list(publish_targets)
        if "default" not in publish_targets:
            publish_targets.append("default")

        plugins_by_targets = pyblish.logic.plugins_by_targets(
            discovered_publish_plugins, publish_targets
        )

        blocking_crashed_paths = filter_crashed_publish_paths(
            project_name,
            set(crashed_file_paths),
            project_settings=project_settings,
        )

        self._publish_report.reset_with_discover_results(
            creator_discover_result,
            convertor_discover_result,
            publish_discover_result,
            blocking_crashed_paths,
        )

        plugins_by_targets_set = set(plugins_by_targets)
        for plugin in discovered_publish_plugins:
            if plugin not in plugins_by_targets_set:
                self._publish_report.set_plugin_skipped(
                    self.get_publish_plugin_id(plugin)
                )

        self._pyblish_context = publish_context
        self._publish_plugins = plugins_by_targets
        self._publish_plugins_by_id = {
            self.get_publish_plugin_id(plugin): plugin
            for plugin in plugins_by_targets
        }
        self._publish_plugins_by_name = {
            plugin.__name__: plugin
            for plugin in plugins_by_targets
        }
        strict_validation_error_handling = (
            self._publish_state.strict_validation_error_handling
        )
        self._publish_state = PublishState()
        self._publish_state.strict_validation_error_handling = (
            strict_validation_error_handling
        )
        self._publish_state.max_progress = len(plugins_by_targets)
        if blocking_crashed_paths:
            self._publish_state.fail_reason = PublishFailReason.BlockingPaths

        self._publish_iterator.update_iter(self._inner_publish_iter())

    def _inner_publish_iter(self) -> PublishIterGen:
        """Main logic center of publishing.

        Iterator returns `PublishIterTask` objects with callbacks that should
        be processed in main thread (threaded in future?). Cares about
        changing states of currently processed publish plugin and instance.
        Also change state of processed orders like validation order
        has passed etc.

        Also stops publishing, if should stop on validation.

        Yields:
            PublishIterTask: Information about next processing function in
                publishing.
            None: If publishing should stop, yields None to indicate
                that publishing should stop.

        Raises:
            ValueError: If a previous item did not execute and the next one
                was requested.

        """
        for idx, plugin in enumerate(self._publish_plugins):
            if self._publish_state.should_stop():
                self.stop_publish()

            while not self.is_running():
                yield None

            plugin_id = self.get_publish_plugin_id(plugin)
            self._publish_state.progress = idx

            # Check if plugin is over validation order and stop if needed
            if (
                not self._publish_state.validated
                and plugin.order >= VALIDATION_ORDER
            ):
                self._publish_state.validated = True
                if (
                    self._publish_state.stop_after_validation
                    or self.has_validation_errors()
                ):
                    self.stop_publish()
                    yield None

            # Add plugin to publish report
            self._publish_report.add_plugin_iter(
                plugin_id, self._pyblish_context
            )

            # Check if plugin should be skipped because is not enabled
            #   or active.
            if self._should_skip_plugin(plugin):
                self._publish_report.set_plugin_skipped(plugin_id)
                continue

            # Plugin is instance plugin
            if plugin.__instanceEnabled__:
                instances = pyblish.logic.instances_by_plugin(
                    self._pyblish_context, plugin
                )
                if not instances:
                    self._publish_report.set_plugin_skipped(plugin_id)
                    continue

                for instance in instances:
                    while not self.is_running():
                        yield None

                    if instance.data.get("publish") is False:
                        continue

                    item_label = (
                        instance.data.get("label")
                        or instance.data["name"]
                    )
                    task = PublishIterTask(
                        self,
                        plugin,
                        instance,
                        item_label,
                    )
                    yield task

                    if not task.executed:
                        raise ValueError("Previous task did not execute")

            else:
                families = collect_families_from_instances(
                    self._pyblish_context, only_active=True
                )
                plugins = pyblish.logic.plugins_by_families(
                    [plugin], families
                )
                if not plugins:
                    self._publish_report.set_plugin_skipped(plugin_id)
                    continue

                item_label = (
                    self._pyblish_context.data.get("label")
                    or self._pyblish_context.data.get("name")
                    or "Context"
                )
                task = PublishIterTask(
                    self,
                    plugin,
                    None,
                    item_label,
                )
                yield task
                if not task.executed:
                    raise ValueError("Previous task did not execute")

            self._publish_report.set_plugin_passed(plugin_id)

        # Cleanup of publishing process
        self._publish_state.finished = True
        self._publish_state.progress = self._publish_state.max_progress

        self.stop_publish()
        while True:
            yield None

    @contextmanager
    def _log_manager(self, plugin: PluginType):
        root = logging.getLogger()
        ayon_root = Logger.get_root_logger()
        plugin_log_has_handler = False
        orig_propagate = plugin.log.propagate
        if not self._log_to_console:
            plugin.log.propagate = False

        if not plugin.log.propagate:
            plugin_log_has_handler = True
            plugin.log.addHandler(self._log_handler)
        root.addHandler(self._log_handler)
        ayon_root.addHandler(self._log_handler)

        try:
            yield self._log_handler

        finally:
            if plugin_log_has_handler:
                plugin.log.removeHandler(self._log_handler)
            plugin.log.propagate = orig_propagate
            root.removeHandler(self._log_handler)
            ayon_root.removeHandler(self._log_handler)
            self._log_handler.clear_records()

    def _process_plugin(
        self,
        plugin: PluginType,
        instance: pyblish.api.Instance | None
    ) -> None:
        plugin_id = self.get_publish_plugin_id(plugin)
        with self._log_manager(plugin) as log_handler:
            result = pyblish.plugin.process(
                plugin, self._pyblish_context, instance
            )
            if log_handler is not None:
                records = log_handler.get_records()
                exception = result.get("error")
                if exception is not None and records:
                    last_record = records[-1]
                    if (
                        last_record.name == "pyblish.plugin"
                        and last_record.levelno == logging.ERROR
                    ):
                        # Remove last record made by pyblish
                        # - `log.exception(formatted_traceback)`
                        records.pop(-1)
                result["records"] = records

        exception = result.get("error")
        if exception:
            error_info = PublishErrorInfo.from_result(
                plugin, instance, exception
            )
            is_validation_error = False
            if (
                isinstance(exception, PublishValidationError)
                and not self._publish_state.validated
            ):
                is_validation_error = True
                self._publish_state.validation_errors.append(error_info)
                self._publish_state.fail_reason = (
                    PublishFailReason.ValidationErrors
                )

            else:
                if (
                    isinstance(exception, PublishError)
                    and not exception.title
                ):
                    exception.title = plugin.label or plugin.__name__

                self._publish_state.error_info = error_info
                self._publish_state.fail_reason = PublishFailReason.Error

            # Store additional metadata to result for report maker
            result["is_validation_error"] = is_validation_error

        self._publish_report.add_result(plugin_id, result)

    def _should_skip_plugin(self, plugin: PluginType) -> bool:
        """Decide if publish plugin should be skipped.

        The pyblish base does define 'active' on plugin which is used to mark
            plugin as active or not. But if plugin is also 'optional' it is
            possible to change the 'active' value.

        AYON does use 'optional' to mark plugin as optional. But the
            optional logic does not change 'active', instead it is handled by
            'process' logic. So AYON's 'OptionalPyblishPluginMixin' will
            always be 'active'.

        With that AYON plugins have to somehow mark plugin as disabled, that
            is why 'enabled' can be set on plugins. If plugin is disabled
            it is skipped no matter what.

        Args:
            plugin (PluginType): Plugin which should be checked
                if it should be skipped.

        Returns:
            bool: Skip the plugin.

        """
        if getattr(plugin, "enabled", True) is False:
            return True

        if plugin.active:
            return False

        # Custom handling of AYON's optional plugins
        if (
            plugin.optional
            and OptionalPyblishPluginMixin in inspect.getmro(plugin)
        ):
            return False
        return True

get_error_info()

Get information about publish error.

Use to get error if fail reason is 'Error'.

Returns:

Type Description
PublishErrorInfo | None

PublishErrorInfo | None: Information about publish error or None if no error happened.

Source code in client/ayon_core/pipeline/publish/logic.py
699
700
701
702
703
704
705
706
707
708
709
def get_error_info(self) -> PublishErrorInfo | None:
    """Get information about publish error.

    Use to get error if fail reason is 'Error'.

    Returns:
        PublishErrorInfo | None: Information about publish error or None
            if no error happened.

    """
    return self._publish_state.error_info

get_fail_reason()

Get the reason for publishing failure.

Returns:

Name Type Description
PublishFailReason PublishFailReason

The reason for publishing failure.

Source code in client/ayon_core/pipeline/publish/logic.py
664
665
666
667
668
669
670
671
def get_fail_reason(self) -> PublishFailReason:
    """Get the reason for publishing failure.

    Returns:
        PublishFailReason: The reason for publishing failure.

    """
    return self._publish_state.fail_reason

get_max_progress()

Get max progress of publishing.

Source code in client/ayon_core/pipeline/publish/logic.py
643
644
645
def get_max_progress(self) -> int:
    """Get max progress of publishing."""
    return self._publish_state.max_progress

get_progress()

Get current progress of publishing.

Returns:

Name Type Description
int int

Current progress of publishing. Value is between 0 and max progress. 0 means no plugin was processed yet.

Source code in client/ayon_core/pipeline/publish/logic.py
633
634
635
636
637
638
639
640
641
def get_progress(self) -> int:
    """Get current progress of publishing.

    Returns:
        int: Current progress of publishing. Value is between 0 and
            max progress. 0 means no plugin was processed yet.

    """
    return self._publish_state.progress

get_publish_plugin_id(plugin) staticmethod

Get id of plugin based on plugin object.

It's used for validation errors report.

Parameters:

Name Type Description Default
plugin PluginType

Publish plugin for which id should be returned.

required

Returns:

Name Type Description
str str

Plugin id.

Source code in client/ayon_core/pipeline/publish/logic.py
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
@staticmethod
def get_publish_plugin_id(plugin: PluginType) -> str:
    """Get id of plugin based on plugin object.

    It's used for validation errors report.

    Args:
        plugin (PluginType): Publish plugin for which id should
            be returned.

    Returns:
        str: Plugin id.

    """
    return plugin.id

get_publish_report()

Get report for the current state of publishing.

Source code in client/ayon_core/pipeline/publish/logic.py
673
674
675
676
def get_publish_report(self) -> PublishReport:
    """Get report for the current state of publishing."""
    self._publish_report.update_publish_instances(self._pyblish_context)
    return self._publish_report.get_report()

get_publish_report_data()

Extract publish report data for the current state of publishing.

This method should be used if report data are being stored to a file. It does mark the current plugin as 'passed' for UI report viewer.

Returns:

Type Description
dict[str, Any]

dict[str, Any]: Publish report data.

Source code in client/ayon_core/pipeline/publish/logic.py
678
679
680
681
682
683
684
685
686
687
688
689
def get_publish_report_data(self) -> dict[str, Any]:
    """Extract publish report data for the current state of publishing.

    This method should be used if report data are being stored to a file.
        It does mark the current plugin as 'passed' for UI report viewer.

    Returns:
        dict[str, Any]: Publish report data.

    """
    report: PublishReport = self.get_publish_report()
    return report.to_data(self._publish_report.current_plugin_id)

get_pyblish_context()

Get pyblish context used for publishing.

Source code in client/ayon_core/pipeline/publish/logic.py
500
501
502
def get_pyblish_context(self) -> pyblish.api.Context:
    """Get pyblish context used for publishing."""
    return self._pyblish_context

get_stop_after_validation()

Check if publishing will stop after validation.

Returns:

Name Type Description
bool bool

True if publishing will stop after validation, False otherwise.

Source code in client/ayon_core/pipeline/publish/logic.py
550
551
552
553
554
555
556
557
558
def get_stop_after_validation(self) -> bool:
    """Check if publishing will stop after validation.

    Returns:
        bool: True if publishing will stop after validation,
            False otherwise.

    """
    return self._publish_state.stop_after_validation

get_validation_errors_info()

Get information about validation errors.

Use to get errors if fail reason is 'ValidationErrors'.

Returns:

Type Description
list[PublishErrorInfo]

list[PublishErrorInfo]: Validation errors info.

Source code in client/ayon_core/pipeline/publish/logic.py
711
712
713
714
715
716
717
718
719
720
def get_validation_errors_info(self) -> list[PublishErrorInfo]:
    """Get information about validation errors.

    Use to get errors if fail reason is 'ValidationErrors'.

    Returns:
        list[PublishErrorInfo]: Validation errors info.

    """
    return self._publish_state.validation_errors

has_failed()

Check if publishing has failed.

It is possible that publishing even didn't start, or still can continue even if publishing has crashed. Don't use this method to check if publishing should be running.

Returns:

Name Type Description
bool bool

True if publishing has crashed, False otherwise.

Source code in client/ayon_core/pipeline/publish/logic.py
651
652
653
654
655
656
657
658
659
660
661
662
def has_failed(self) -> bool:
    """Check if publishing has failed.

    It is possible that publishing even didn't start, or still can
        continue even if publishing has crashed. Don't use this method
        to check if publishing should be running.

    Returns:
        bool: True if publishing has crashed, False otherwise.

    """
    return self._publish_state.fail_reason != PublishFailReason.No

has_finished()

Publishing has successfully finished.

It is not possible that 'has_finished' is True and 'has_failed' is True at the same time.

Returns:

Name Type Description
bool bool

True if publishing has successfully finished, False otherwise.

Source code in client/ayon_core/pipeline/publish/logic.py
602
603
604
605
606
607
608
609
610
611
612
613
def has_finished(self) -> bool:
    """Publishing has successfully finished.

    It is not possible that 'has_finished' is True and 'has_failed'
        is True at the same time.

    Returns:
        bool: True if publishing has successfully finished,
            False otherwise.

    """
    return self._publish_state.finished

has_started()

Publishing has started.

Source code in client/ayon_core/pipeline/publish/logic.py
598
599
600
def has_started(self) -> bool:
    """Publishing has started."""
    return self._publish_state.started

has_validated()

Validation order passed.

Returns:

Name Type Description
bool bool

True if validation order passed, False otherwise.

Source code in client/ayon_core/pipeline/publish/logic.py
615
616
617
618
619
620
621
622
def has_validated(self) -> bool:
    """Validation order passed.

    Returns:
        bool: True if validation order passed, False otherwise.

    """
    return self._publish_state.validated

has_validation_errors()

Check if publishing has validation errors.

Source code in client/ayon_core/pipeline/publish/logic.py
647
648
649
def has_validation_errors(self) -> bool:
    """Check if publishing has validation errors."""
    return bool(self._publish_state.validation_errors)

is_running()

Check if publishing is currently meant to be running.

It is possible that publishing is currently in process of stopping, but this method will return False.

Returns:

Name Type Description
bool bool

True if publishing is currently meant to be running, False otherwise.

Source code in client/ayon_core/pipeline/publish/logic.py
585
586
587
588
589
590
591
592
593
594
595
596
def is_running(self) -> bool:
    """Check if publishing is currently meant to be running.

    It is possible that publishing is currently in process of stopping,
        but this method will return False.

    Returns:
        bool: True if publishing is currently meant to be running,
            False otherwise.

    """
    return self._publish_state.is_running

iter_all_error_info()

Iterate over all error information.

Source code in client/ayon_core/pipeline/publish/logic.py
722
723
724
725
726
def iter_all_error_info(self) -> Iterable[PublishErrorInfo]:
    """Iterate over all error information."""
    if self._publish_state.error_info is not None:
        yield self._publish_state.error_info
    yield from self._publish_state.validation_errors

iter_publish_plugins()

Iterate over publish plugins.

Give developers access to publish plugins that are used in current publishing process. Can be used to change their attributes, e.g. to disable them.

Returns:

Type Description
Iterable[PluginType]

Iterable[PluginType]: Iterable with publish plugins.

Source code in client/ayon_core/pipeline/publish/logic.py
520
521
522
523
524
525
526
527
528
529
530
531
def iter_publish_plugins(self) -> Iterable[PluginType]:
    """Iterate over publish plugins.

    Give developers access to publish plugins that are used in current
        publishing process. Can be used to change their attributes, e.g.
        to disable them.

    Returns:
        Iterable[PluginType]: Iterable with publish plugins.

    """
    yield from self._publish_plugins

publish_can_continue()

Publishing can continue.

Returns:

Name Type Description
bool bool

True if publishing still can continue, False otherwise.

Source code in client/ayon_core/pipeline/publish/logic.py
624
625
626
627
628
629
630
631
def publish_can_continue(self) -> bool:
    """Publishing can continue.

    Returns:
        bool: True if publishing still can continue, False otherwise.

    """
    return self._publish_state.can_continue()

publish_iter()

Publish iteration generator.

Yields:

Name Type Description
PublishIterTask PublishIterTask

Information about next processing function in publishing. Can be called to process the next function.

Source code in client/ayon_core/pipeline/publish/logic.py
537
538
539
540
541
542
543
544
545
546
547
548
def publish_iter(self) -> Generator[PublishIterTask, None, None]:
    """Publish iteration generator.

    Yields:
        PublishIterTask: Information about next processing function in
            publishing. Can be called to process the next function.

    """
    self._publish_state.is_running = True
    self._publish_state.started = True
    for task in self._publish_iterator:
        yield task

reset(project_name, context=None, plugins=None, targets=None, create_context=None, publish_discover_result=None, project_settings=None)

Reset publish logic with given parameters.

Parameters:

Name Type Description Default
project_name str

Name of the project.

required
context Context | None

Pyblish context to use. If None, a new context will be created.

None
plugins list[PluginType] | None

List of publish plugins to use. If None, plugins will be discovered.

None
targets list[str] | None

List of publish targets to use. If None, all registered targets will be used.

None
create_context CreateContext | None

Create context to use. If None, a new create context will be created if possible.

None
publish_discover_result DiscoverResult | None

Discover result for publish plugins. If None, plugins will be discovered.

None
Source code in client/ayon_core/pipeline/publish/logic.py
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
def reset(
    self,
    project_name: str,
    context: pyblish.api.Context | None = None,
    plugins: list[PluginType] | None = None,
    targets: list[str] | None = None,
    create_context: CreateContext | None = None,
    publish_discover_result: DiscoverResult | None = None,
    project_settings: dict[str, Any] | None = None,
) -> None:
    """Reset publish logic with given parameters.

    Args:
        project_name (str): Name of the project.
        context (pyblish.api.Context | None): Pyblish context to use.
            If None, a new context will be created.
        plugins (list[PluginType] | None): List of publish plugins to use.
            If None, plugins will be discovered.
        targets (list[str] | None): List of publish targets to use.
            If None, all registered targets will be used.
        create_context (CreateContext | None): Create context to use.
            If None, a new create context will be created if possible.
        publish_discover_result (DiscoverResult | None): Discover result
            for publish plugins. If None, plugins will be discovered.

    """
    if plugins is not None and publish_discover_result is None:
        publish_discover_result = DiscoverResult(pyblish.api.Plugin)
        publish_discover_result.plugins = plugins

    self._reset(
        project_name,
        publish_context=context,
        publish_targets=targets,
        create_context=create_context,
        publish_discover_result=publish_discover_result,
        project_settings=project_settings,
    )

reset_from_create_context(create_context, context=None, targets=None)

Reset publish logic with given create context.

Parameters:

Name Type Description Default
create_context CreateContext

Create context to use.

required
context Context | None

Pyblish context to use. If None, a new context will be created.

None
targets list[str] | None

List of publish targets to use. If None, all registered targets will be used.

None
Source code in client/ayon_core/pipeline/publish/logic.py
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
def reset_from_create_context(
    self,
    create_context: CreateContext,
    context: pyblish.api.Context | None = None,
    targets: list[str] | None = None,
) -> None:
    """Reset publish logic with given create context.

    Args:
        create_context (CreateContext): Create context to use.
        context (pyblish.api.Context | None): Pyblish context to use.
            If None, a new context will be created.
        targets (list[str] | None): List of publish targets to use.
            If None, all registered targets will be used.

    """
    self._reset(
        create_context.project_name,
        publish_context=context,
        publish_targets=targets,
        publish_discover_result=create_context.publish_discover_result,
        creator_discover_result=create_context.creator_discover_result,
        convertor_discover_result=create_context.convertor_discover_result,
        create_context=create_context,
    )

reset_with_current_context()

Reset publish logic with current context.

Source code in client/ayon_core/pipeline/publish/logic.py
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
def reset_with_current_context(self) -> None:
    """Reset publish logic with current context."""
    from ayon_core.pipeline.create import CreateContext
    from ayon_core.pipeline.context_tools import (
        registered_host,
        get_current_project_name,
    )

    host = registered_host()
    create_context = None
    if host is not None:
        create_context = CreateContext(host)

    if create_context is not None:
        self.reset_from_create_context(create_context)
        return

    project_name = get_current_project_name()
    self.reset(project_name)

set_log_to_console(value)

Set whether to log to console.

Source code in client/ayon_core/pipeline/publish/logic.py
516
517
518
def set_log_to_console(self, value: bool) -> None:
    """Set whether to log to console."""
    self._log_to_console = value

set_stop_after_validation(value)

Publishing will stop after validation.

Parameters:

Name Type Description Default
value bool

If True, publishing will stop after validation.

required
Source code in client/ayon_core/pipeline/publish/logic.py
560
561
562
563
564
565
566
567
def set_stop_after_validation(self, value: bool) -> None:
    """Publishing will stop after validation.

    Args:
        value (bool): If True, publishing will stop after validation.

    """
    self._publish_state.stop_after_validation = value

set_strict_validation_error_handling(value)

Set strict validation error handling.

Parameters:

Name Type Description Default
value bool

If True, publishing will stop after validation.

required
Source code in client/ayon_core/pipeline/publish/logic.py
569
570
571
572
573
574
575
576
def set_strict_validation_error_handling(self, value: bool) -> None:
    """Set strict validation error handling.

    Args:
        value (bool): If True, publishing will stop after validation.

    """
    self._publish_state.strict_validation_error_handling = value

stop_publish()

Mark publishing to stop on next iteration.

This is useful for UI purposes.

Source code in client/ayon_core/pipeline/publish/logic.py
578
579
580
581
582
583
def stop_publish(self) -> None:
    """Mark publishing to stop on next iteration.

    This is useful for UI purposes.
    """
    self._publish_state.is_running = False

store_publish_report(filepath)

Store publish report to a file.

Source code in client/ayon_core/pipeline/publish/logic.py
691
692
693
694
695
696
697
def store_publish_report(self, filepath: str) -> None:
    """Store publish report to a file."""
    report: PublishReport = self.get_publish_report()
    report.store_to_file(
        filepath,
        self._publish_report.current_plugin_id
    )

PublishValidationError

Bases: PublishError

Validation error happened during publishing.

This exception should be used when validation publishing failed.

Publishing does not stop during validation order if this exception is raised.

Has additional UI specific attributes that may be handy for artist.

Argument 'title' is used to group errors.

Source code in client/ayon_core/pipeline/publish/publish_plugins.py
71
72
73
74
75
76
77
78
79
80
81
82
83
84
class PublishValidationError(PublishError):
    """Validation error happened during publishing.

    This exception should be used when validation publishing failed.

    Publishing does not stop during validation order if this
        exception is raised.

    Has additional UI specific attributes that may be handy for artist.

    Argument 'title' is used to group errors.

    """
    pass

PublishXmlValidationError

Bases: PublishValidationError

Raise an error from a dedicated xml file.

Can be useful to have one xml file with different possible messages that helps to avoid flood code with dedicated artist messages.

XML files should live relative to the plugin file location

'{plugin dir}/help/some_plugin.xml'.

Parameters:

Name Type Description Default
plugin Plugin

Plugin that raised an error. Is used to get path to xml file.

required
message str

Exception message, can be technical, is used for console output.

required
key Optional[str]

XML file can contain multiple error messages, key is used to get one of them. By default is used 'main'.

None
formatting_data Optional[dict[str, Any]

Error message can have variables to fill.

None
help_filename Optional[str]

Name of xml file with messages. By default, is used filename where plugin lives with .xml extension.

None
Source code in client/ayon_core/pipeline/publish/publish_plugins.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
class PublishXmlValidationError(PublishValidationError):
    """Raise an error from a dedicated xml file.

    Can be useful to have one xml file with different possible messages that
        helps to avoid flood code with dedicated artist messages.

    XML files should live relative to the plugin file location:
        '{plugin dir}/help/some_plugin.xml'.

    Args:
        plugin (pyblish.api.Plugin): Plugin that raised an error. Is used
            to get path to xml file.
        message (str): Exception message, can be technical, is used for
            console output.
        key (Optional[str]): XML file can contain multiple error messages, key
            is used to get one of them. By default is used 'main'.
        formatting_data (Optional[dict[str, Any]): Error message can have
            variables to fill.
        help_filename (Optional[str]): Name of xml file with messages. By
            default, is used filename where plugin lives with .xml extension.

    """
    def __init__(
        self,
        plugin: pyblish.api.Plugin,
        message: str,
        key: Optional[str] = None,
        formatting_data: Optional[dict[str, Any]] = None,
        help_filename: Optional[str] = None,
    ) -> None:
        if key is None:
            key = "main"

        if not formatting_data:
            formatting_data = {}
        result = load_help_content_from_plugin(plugin, help_filename)
        content_obj = result["errors"][key]
        description = content_obj.description.format_map(formatting_data)
        detail = content_obj.detail
        if detail:
            detail = detail.format_map(formatting_data)
        super().__init__(
            message,
            content_obj.title,
            description,
            detail
        )

RenderInstance

Bases: object

Data collected by collectors.

This data class later on passed to collected instances. Those attributes are required later on.

Source code in client/ayon_core/pipeline/publish/abstract_collect_render.py
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
@attr.s
class RenderInstance(object):
    """Data collected by collectors.

    This data class later on passed to collected instances.
    Those attributes are required later on.

    """

    # metadata
    version = attr.ib()  # instance version
    time = attr.ib()  # time of instance creation (get_formatted_current_time)
    source = attr.ib()  # path to source scene file
    label = attr.ib()  # label to show in GUI
    family = attr.ib()  # product base type used for pyblish filtering
    productType = attr.ib()  # product type
    productName = attr.ib()  # product name
    folderPath = attr.ib()  # folder path
    task = attr.ib()  # task name
    attachTo = attr.ib()  # product name to attach render to
    setMembers = attr.ib()  # list of nodes/members producing render output
    publish = attr.ib()  # bool, True to publish instance
    name = attr.ib()  # instance name

    # format settings
    resolutionWidth = attr.ib()  # resolution width (1920)
    resolutionHeight = attr.ib()  # resolution height (1080)
    pixelAspect = attr.ib()  # pixel aspect (1.0)

    # time settings
    frameStart = attr.ib()  # start frame
    frameEnd = attr.ib()  # start end
    frameStep = attr.ib()  # frame step

    productBaseType = attr.ib(default=None)  # product base type

    handleStart = attr.ib(default=None)  # start frame
    handleEnd = attr.ib(default=None)  # start frame

    # for software (like Harmony) where frame range cannot be set by DB
    # handles need to be propagated if exist
    ignoreFrameHandleCheck = attr.ib(default=False)

    # --------------------
    # With default values
    # metadata
    renderer = attr.ib(default="")  # renderer - can be used in Deadline
    review = attr.ib(default=None)  # False - explicitly skip review
    priority = attr.ib(default=50)  # job priority on farm

    # family = attr.ib(default="renderlayer")
    families = attr.ib(default=["renderlayer"])  # list of families
    # True if should be rendered on farm, eg not integrate
    farm = attr.ib(default=False)

    # format settings
    multipartExr = attr.ib(default=False)  # flag for multipart exrs
    convertToScanline = attr.ib(default=False)  # flag for exr conversion

    tileRendering = attr.ib(default=False)  # bool: treat render as tiles
    tilesX = attr.ib(default=0)  # number of tiles in X
    tilesY = attr.ib(default=0)  # number of tiles in Y

    # submit_publish_job
    deadlineSubmissionJob = attr.ib(default=None)
    anatomyData = attr.ib(default=None)
    outputDir = attr.ib(default=None)
    context = attr.ib(default=None)
    deadline = attr.ib(default=None)

    # The source instance the data of this render instance should merge into
    source_instance = attr.ib(default=None, type=pyblish.api.Instance)

    @frameStart.validator
    def check_frame_start(self, _, value):
        """Validate if frame start is not larger then end."""
        if value > self.frameEnd:
            raise ValueError("frameStart must be smaller "
                             "or equal then frameEnd")

    @frameEnd.validator
    def check_frame_end(self, _, value):
        """Validate if frame end is not less then start."""
        if value < self.frameStart:
            raise ValueError("frameEnd must be smaller "
                             "or equal then frameStart")

    @tilesX.validator
    def check_tiles_x(self, _, value):
        """Validate if tile x isn't less then 1."""
        if not self.tileRendering:
            return
        if value < 1:
            raise ValueError("tile X size cannot be less then 1")

        if value == 1 and self.tilesY == 1:
            raise ValueError("both tiles X a Y sizes are set to 1")

    @tilesY.validator
    def check_tiles_y(self, _, value):
        """Validate if tile y isn't less then 1."""
        if not self.tileRendering:
            return
        if value < 1:
            raise ValueError("tile Y size cannot be less then 1")

        if value == 1 and self.tilesX == 1:
            raise ValueError("both tiles X a Y sizes are set to 1")

check_frame_end(_, value)

Validate if frame end is not less then start.

Source code in client/ayon_core/pipeline/publish/abstract_collect_render.py
 95
 96
 97
 98
 99
100
@frameEnd.validator
def check_frame_end(self, _, value):
    """Validate if frame end is not less then start."""
    if value < self.frameStart:
        raise ValueError("frameEnd must be smaller "
                         "or equal then frameStart")

check_frame_start(_, value)

Validate if frame start is not larger then end.

Source code in client/ayon_core/pipeline/publish/abstract_collect_render.py
88
89
90
91
92
93
@frameStart.validator
def check_frame_start(self, _, value):
    """Validate if frame start is not larger then end."""
    if value > self.frameEnd:
        raise ValueError("frameStart must be smaller "
                         "or equal then frameEnd")

check_tiles_x(_, value)

Validate if tile x isn't less then 1.

Source code in client/ayon_core/pipeline/publish/abstract_collect_render.py
102
103
104
105
106
107
108
109
110
111
@tilesX.validator
def check_tiles_x(self, _, value):
    """Validate if tile x isn't less then 1."""
    if not self.tileRendering:
        return
    if value < 1:
        raise ValueError("tile X size cannot be less then 1")

    if value == 1 and self.tilesY == 1:
        raise ValueError("both tiles X a Y sizes are set to 1")

check_tiles_y(_, value)

Validate if tile y isn't less then 1.

Source code in client/ayon_core/pipeline/publish/abstract_collect_render.py
113
114
115
116
117
118
119
120
121
122
@tilesY.validator
def check_tiles_y(self, _, value):
    """Validate if tile y isn't less then 1."""
    if not self.tileRendering:
        return
    if value < 1:
        raise ValueError("tile Y size cannot be less then 1")

    if value == 1 and self.tilesX == 1:
        raise ValueError("both tiles X a Y sizes are set to 1")

RepairAction

Bases: Action

Repairs the action

To process the repairing this requires a static repair(instance) method is available on the plugin.

Source code in client/ayon_core/pipeline/publish/publish_plugins.py
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
class RepairAction(pyblish.api.Action):
    """Repairs the action

    To process the repairing this requires a static `repair(instance)` method
    is available on the plugin.
    """

    label = "Repair"
    on = "failed"  # This action is only available on a failed plug-in
    icon = "wrench"  # Icon from Awesome Icon

    def process(self, context, plugin):
        if not hasattr(plugin, "repair"):
            raise RuntimeError("Plug-in does not have repair method.")

        # Get the errored instances
        self.log.debug("Finding failed instances..")
        errored_instances = get_errored_instances_from_context(context,
                                                               plugin=plugin)
        for instance in errored_instances:
            self.log.debug(
                "Attempting repair for instance: {} ...".format(instance)
            )
            plugin.repair(instance)

RepairContextAction

Bases: Action

Repairs the action

To process the repairing this requires a static repair(context) method is available on the plugin.

Source code in client/ayon_core/pipeline/publish/publish_plugins.py
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
class RepairContextAction(pyblish.api.Action):
    """Repairs the action

    To process the repairing this requires a static `repair(context)` method
    is available on the plugin.
    """

    label = "Repair"
    on = "failed"  # This action is only available on a failed plug-in
    icon = "wrench"  # Icon from Awesome Icon

    def process(self, context, plugin):
        if not hasattr(plugin, "repair"):
            raise RuntimeError("Plug-in does not have repair method.")

        # Get the failed instances
        self.log.debug("Finding failed plug-ins..")
        failed_plugins = get_errored_plugins_from_context(context)

        # Apply pyblish.logic to get the instances for the plug-in
        if plugin in failed_plugins:
            self.log.debug("Attempting repair ...")
            plugin.repair(context)

add_trait_representations(instance, representations)

Add trait representations to instance.

Parameters:

Name Type Description Default
instance Instance

Instance to add trait representations to.

required
representations list[Representation]

List of representation trait based representations to add.

required
Source code in client/ayon_core/pipeline/publish/lib.py
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
def add_trait_representations(
    instance: pyblish.api.Instance,
    representations: list[Representation],
) -> None:
    """Add trait representations to instance.

    Args:
        instance (pyblish.api.Instance): Instance to add trait
            representations to.
        representations (list[Representation]): List of representation
            trait based representations to add.

    """
    repres = instance.data.setdefault(TRAIT_INSTANCE_KEY, [])
    repres.extend(representations)

apply_plugin_settings_automatically(plugin, settings, logger=None)

Automatically apply plugin settings to a plugin object.

Note

This function was created to be able to use it in custom overrides of 'apply_settings' class method.

Parameters:

Name Type Description Default
plugin PluginType

Class of a plugin.

required
settings dict[str, Any]

Plugin specific settings.

required
logger Logger | None

Logger to log debug messages about applied settings values.

None
Source code in client/ayon_core/pipeline/publish/lib.py
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
def apply_plugin_settings_automatically(
    plugin: PluginType,
    settings: dict[str, Any],
    logger: logging.Logger | None = None,
) -> None:
    """Automatically apply plugin settings to a plugin object.

    Note:
        This function was created to be able to use it in custom overrides of
            'apply_settings' class method.

    Args:
        plugin (PluginType): Class of a plugin.
        settings (dict[str, Any]): Plugin specific settings.
        logger (logging.Logger | None): Logger to log debug messages about
            applied settings values.

    """
    for option, value in settings.items():
        if logger:
            logger.debug(
                "Plugin %s - Attr: %s -> %s", plugin.__name__, option, value
            )
        setattr(plugin, option, value)

context_plugin_should_run(plugin, context)

Return whether the ContextPlugin should run on the given context.

This is a helper function to work around a bug pyblish-base#250 Whenever a ContextPlugin sets specific families it will still trigger even when no instances are present that have those families.

This actually checks it correctly and returns whether it should run.

Parameters:

Name Type Description Default
plugin Plugin

Plugin with filters.

required
context Context

Pyblish context with instances.

required

Returns:

Name Type Description
bool bool

Context plugin should run based on valid instances.

Source code in client/ayon_core/pipeline/publish/lib.py
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
def context_plugin_should_run(
    plugin: PluginType,
    context: pyblish.api.Context,
) -> bool:
    """Return whether the ContextPlugin should run on the given context.

    This is a helper function to work around a bug pyblish-base#250
    Whenever a ContextPlugin sets specific families it will still trigger even
    when no instances are present that have those families.

    This actually checks it correctly and returns whether it should run.

    Args:
        plugin (pyblish.api.Plugin): Plugin with filters.
        context (pyblish.api.Context): Pyblish context with instances.

    Returns:
        bool: Context plugin should run based on valid instances.
    """

    for _ in filter_instances_for_context_plugin(plugin, context):
        return True
    return False

filter_crashed_publish_paths(project_name, crashed_paths, *, project_settings=None)

Filter crashed paths happened during plugins discovery.

Check if plugins discovery has enabled strict mode and filter crashed paths that happened during discover based on regexes from settings.

Publishing should not start if any paths are returned.

Parameters:

Name Type Description Default
project_name str

Project name in which context plugins discovery happened.

required
crashed_paths set[str]

Crashed paths from plugins discovery report.

required
project_settings dict[str, Any] | None

Project settings.

None

Returns:

Type Description
set[str]

set[str]: Filtered crashed paths.

Source code in client/ayon_core/pipeline/publish/lib.py
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
def filter_crashed_publish_paths(
    project_name: str,
    crashed_paths: set[str],
    *,
    project_settings: dict[str, Any] | None = None,
) -> set[str]:
    """Filter crashed paths happened during plugins discovery.

    Check if plugins discovery has enabled strict mode and filter crashed
        paths that happened during discover based on regexes from settings.

    Publishing should not start if any paths are returned.

    Args:
        project_name (str): Project name in which context plugins discovery
            happened.
        crashed_paths (set[str]): Crashed paths from plugins discovery report.
        project_settings (dict[str, Any] | None): Project settings.

    Returns:
        set[str]: Filtered crashed paths.

    """
    filtered_paths = set()
    # Nothing crashed all good...
    if not crashed_paths:
        return filtered_paths

    if project_settings is None:
        project_settings = get_project_settings(project_name)

    discover_validation = (
        project_settings["core"]["tools"]["publish"]["discover_validation"]
    )
    # Strict mode is not enabled.
    if not discover_validation["enabled"]:
        return filtered_paths

    regexes = [
        re.compile(value, re.IGNORECASE)
        for value in discover_validation["ignore_paths"]
        if value
    ]
    is_windows = platform.system().lower() == "windows"
    # Fitler path with regexes from settings
    for path in crashed_paths:
        # Normalize paths to use forward slashes on windows
        if is_windows:
            path = path.replace("\\", "/")
        is_invalid = True
        for regex in regexes:
            if regex.match(path):
                is_invalid = False
                break

        if is_invalid:
            filtered_paths.add(path)

    return filtered_paths

filter_instances_for_context_plugin(plugin, context)

Filter instances on context by context plugin filters.

This is for cases when context plugin need similar filtering like instance plugin have, but for some reason must run on context or should find out if there is at least one instance with a family.

Parameters:

Name Type Description Default
plugin PluginType

Plugin with filters.

required
context Context

Pyblish context with instances.

required

Returns:

Type Description
None

Generator[pyblish.lib.Instance, None, None]: Iteration of valid instances.

Source code in client/ayon_core/pipeline/publish/lib.py
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
def filter_instances_for_context_plugin(
    plugin: PluginType,
    context: pyblish.api.Context,
) -> Generator[pyblish.lib.Instance, None, None]:
    """Filter instances on context by context plugin filters.

    This is for cases when context plugin need similar filtering like instance
    plugin have, but for some reason must run on context or should find out
    if there is at least one instance with a family.

    Args:
        plugin (PluginType): Plugin with filters.
        context (pyblish.api.Context): Pyblish context with instances.

    Returns:
        Generator[pyblish.lib.Instance, None, None]: Iteration of valid
            instances.

    """
    instances = []
    plugin_families = set()
    all_families = False
    if plugin.families:
        instances = context
        plugin_families = set(plugin.families)
        all_families = "*" in plugin_families

    for instance in instances:
        # Ignore inactive instances
        if (
            not instance.data.get("publish", True)
            or not instance.data.get("active", True)
        ):
            continue

        family = instance.data.get("family")
        families = instance.data.get("families") or []
        if (
            all_families
            or (family and family in plugin_families)
            or any(f in plugin_families for f in families)
        ):
            yield instance

get_default_reviewable_layers(project_settings)

Get default reviewable layers from project settings.

Parameters:

Name Type Description Default
project_settings dict

Project settings.

required

Returns:

Type Description
list[str]

list[str]: List of default reviewable layers.

Source code in client/ayon_core/pipeline/publish/lib.py
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
def get_default_reviewable_layers(project_settings: dict) -> list[str]:
    """Get default reviewable layers from project settings.

    Args:
        project_settings (dict): Project settings.

    Returns:
        list[str]: List of default reviewable layers.

    """
    return project_settings["core"]["reviewable_layers"]["review_layers"]

get_errored_instances_from_context(context, plugin=None)

Collect failed instances from pyblish context.

Parameters:

Name Type Description Default
context Context

Publish context where we're looking for failed instances.

required
plugin PluginType | None

If provided then only consider errors related to that plug-in.

None

Returns:

Type Description
list[Instance]

list[pyblish.lib.Instance]: Instances which failed during processing.

Source code in client/ayon_core/pipeline/publish/lib.py
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
def get_errored_instances_from_context(
    context: pyblish.api.Context,
    plugin: PluginType | None = None,
) -> list[pyblish.lib.Instance]:
    """Collect failed instances from pyblish context.

    Args:
        context (pyblish.api.Context): Publish context where we're looking
            for failed instances.
        plugin (PluginType | None): If provided then only consider errors
            related to that plug-in.

    Returns:
        list[pyblish.lib.Instance]: Instances which failed during processing.

    """
    instances = list()
    for result in context.data["results"]:
        if result["instance"] is None:
            # When instance is None we are on the "context" result
            continue

        if plugin is not None and result.get("plugin") != plugin:
            continue

        if result["error"]:
            instances.append(result["instance"])

    return instances

get_errored_plugins_from_context(context)

Collect failed plugins from pyblish context.

Parameters:

Name Type Description Default
context Context

Publish context where we're looking for failed plugins.

required

Returns:

Type Description
list[PluginType]

list[PluginType]: Plugins which failed during processing.

Source code in client/ayon_core/pipeline/publish/lib.py
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
def get_errored_plugins_from_context(
    context: pyblish.api.Context
) -> list[PluginType]:
    """Collect failed plugins from pyblish context.

    Args:
        context (pyblish.api.Context): Publish context where we're looking
            for failed plugins.

    Returns:
        list[PluginType]: Plugins which failed during processing.

    """
    plugins = list()
    results = context.data.get("results", [])
    for result in results:
        if result["success"] is True:
            continue
        plugins.append(result["plugin"])

    return plugins

get_instance_families(instance)

Get all families of the instance.

Parameters:

Name Type Description Default
instance Instance

Instance to get families from.

required

Returns:

Type Description
list[str]

list[str]: List of families.

Source code in client/ayon_core/pipeline/publish/lib.py
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
def get_instance_families(instance: pyblish.api.Instance) -> list[str]:
    """Get all families of the instance.

    Args:
        instance (pyblish.api.Instance): Instance to get families from.

    Returns:
        list[str]: List of families.

    """
    family = instance.data.get("family")
    families = []
    if family:
        families.append(family)

    for _family in (instance.data.get("families") or []):
        if _family not in families:
            families.append(_family)

    return families

get_instance_publish_template(instance)

Return anatomy template name to use for integration.

Parameters:

Name Type Description Default
instance Instance

Instance to process.

required

Returns:

Name Type Description
str str

Anatomy template name

Source code in client/ayon_core/pipeline/publish/lib.py
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
def get_instance_publish_template(instance: pyblish.api.Instance) -> str:
    """Return anatomy template name to use for integration.

    Args:
        instance (pyblish.api.Instance): Instance to process.

    Returns:
        str: Anatomy template name

    """
    # Anatomy data is pre-filled by Collectors
    publish_template = get_publish_template_object(instance)
    return publish_template["path"].template.replace("\\", "/")

get_instance_staging_dir(instance)

Unified way how staging dir is stored and created on instances.

First check if 'stagingDir' is already set in instance data. In case there already is new tempdir will not be created.

Returns:

Name Type Description
str str

Path to staging dir

Source code in client/ayon_core/pipeline/publish/lib.py
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
def get_instance_staging_dir(
    instance: pyblish.api.Instance
) -> str:
    """Unified way how staging dir is stored and created on instances.

    First check if 'stagingDir' is already set in instance data.
    In case there already is new tempdir will not be created.

    Returns:
        str: Path to staging dir
    """
    staging_dir = instance.data.get("stagingDir")

    if staging_dir:
        return staging_dir

    anatomy_data = instance.data["anatomyData"]
    template_data = copy.deepcopy(anatomy_data)

    # context data based variables
    context = instance.context

    # add current file as workfile name into formatting data
    current_file = context.data.get("currentFile")
    if current_file:
        workfile = os.path.basename(current_file)
        workfile_name, _ = os.path.splitext(workfile)
        template_data["workfile_name"] = workfile_name

    product_type = instance.data["productType"]
    product_base_type = instance.data.get("productBaseType")
    if not product_base_type:
        product_base_type = product_type
    staging_dir_info = get_staging_dir_info(
        context.data["projectEntity"],
        instance.data.get("folderEntity"),
        instance.data.get("taskEntity"),
        product_base_type=product_base_type,
        product_type=product_type,
        product_name=instance.data["productName"],
        host_name=context.data["hostName"],
        anatomy=context.data["anatomy"],
        project_settings=context.data["project_settings"],
        template_data=template_data,
        always_return_path=True,
        username=context.data["user"],
    )

    staging_dir_path = staging_dir_info.directory

    # path might be already created by get_staging_dir_info
    os.makedirs(staging_dir_path, exist_ok=True)
    instance.data.update({
        "stagingDir": staging_dir_path,
        "stagingDir_persistent": staging_dir_info.is_persistent,
        "stagingDir_is_custom": staging_dir_info.is_custom
    })

    return staging_dir_path

get_instance_template_name(instance)

Return anatomy template name to use for integration.

Parameters:

Name Type Description Default
instance Instance

Instance to process.

required

Returns:

Name Type Description
str str

Anatomy template name

Source code in client/ayon_core/pipeline/publish/lib.py
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
def get_instance_template_name(instance: pyblish.api.Instance) -> str:
    """Return anatomy template name to use for integration.

    Args:
        instance (pyblish.api.Instance): Instance to process.

    Returns:
        str: Anatomy template name

    """
    # Anatomy data is pre-filled by Collectors
    context = instance.context
    project_name = context.data["projectName"]

    # Task can be optional in anatomy data
    host_name = context.data["hostName"]
    anatomy_data = instance.data["anatomyData"]
    product_type = instance.data["productType"]
    product_base_type = instance.data.get("productBaseType")
    if not product_base_type:
        product_base_type = product_type
    task_info = anatomy_data.get("task") or {}

    return get_publish_template_name(
        project_name,
        host_name,
        product_base_type=product_base_type,
        task_name=task_info.get("name"),
        task_type=task_info.get("type"),
        project_settings=context.data["project_settings"],
        logger=log,
    )

get_plugin_settings(plugin, project_settings, log, category=None)

Get plugin settings based on host name and plugin name.

Note

Default implementation of automated settings is passing host name into 'category'.

Parameters:

Name Type Description Default
plugin PluginType

Plugin where settings are applied.

required
project_settings dict[str, Any]

Project settings.

required
log Logger

Logger to log messages.

required
category str | None

Settings category key where to look for plugin settings.

None

Returns:

Type Description
dict[str, Any]

dict[str, Any]: Plugin settings {'attribute': 'value'}.

Source code in client/ayon_core/pipeline/publish/lib.py
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
def get_plugin_settings(
    plugin: PluginType,
    project_settings: dict[str, Any],
    log: logging.Logger,
    category: str | None = None,
) -> dict[str, Any]:
    """Get plugin settings based on host name and plugin name.

    Note:
        Default implementation of automated settings is passing host name
            into 'category'.

    Args:
        plugin (PluginType): Plugin where settings are applied.
        project_settings (dict[str, Any]): Project settings.
        log (logging.Logger): Logger to log messages.
        category (str | None): Settings category key where to look
            for plugin settings.

    Returns:
        dict[str, Any]: Plugin settings {'attribute': 'value'}.

    """
    # Plugin can define settings category by class attribute
    # - it's impossible to set `settings_category` via settings because
    #     obviously settings are not applied before it.
    # - if `settings_category` is set the fallback category method is ignored
    settings_category = getattr(plugin, "settings_category", None)
    if settings_category:
        try:
            category_settings = project_settings[settings_category]
        except KeyError:
            log.warning((
                "Couldn't find settings category '{}' in project settings"
            ).format(settings_category))
            return {}

        try:
            return category_settings["publish"][plugin.__name__]
        except KeyError:
            return {}

    # Use project settings based on a category name
    if category:
        try:
            output = (
                project_settings
                [category]
                ["publish"]
                [plugin.__name__]
            )
            warnings.warn(
                "Please fill 'settings_category'"
                f" for plugin '{plugin.__name__}'.",
                DeprecationWarning
            )
            return output
        except KeyError:
            pass

    # Settings category determined from path
    # - usually path is './<category>/plugins/publish/<plugin file>'
    # - category can be host name of addon name ('maya', 'deadline', ...)
    filepath = os.path.normpath(inspect.getfile(plugin))

    split_path = filepath.rsplit(os.path.sep, 5)
    if len(split_path) < 4:
        log.debug((
            "Plugin path is too short to automatically"
            " extract settings category. {}"
        ).format(filepath))
        return {}

    category_from_file = split_path[-4]
    plugin_kind = split_path[-2]

    # TODO: change after all plugins are moved one level up
    if category_from_file == "ayon_core":
        category_from_file = "core"

    try:
        output = (
            project_settings
            [category_from_file]
            [plugin_kind]
            [plugin.__name__]
        )
        warnings.warn(
            "Please fill 'settings_category'"
            f" for plugin '{plugin.__name__}'.",
            DeprecationWarning
        )
        return output
    except KeyError:
        pass
    return {}

get_publish_instance_families(instance)

Get all families of the instance.

Look for families under 'productType' and 'families' keys in instance data. Value of 'productType' is used as first family and then all other families in random order.

Parameters:

Name Type Description Default
instance Instance

Instance to get families from.

required

Returns:

Type Description
list[str]

list[str]: List of families.

Source code in client/ayon_core/pipeline/publish/lib.py
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
def get_publish_instance_families(
    instance: pyblish.api.Instance
) -> list[str]:
    """Get all families of the instance.

    Look for families under 'productType' and 'families' keys in instance data.
    Value of 'productType' is used as first family and then all other families
    in random order.

    Args:
        instance (pyblish.api.Instance): Instance to get families from.

    Returns:
        list[str]: List of families.
    """

    family = instance.data.get("family")
    families = set(instance.data.get("families") or [])
    output = []
    if family:
        output.append(family)
        families.discard(family)
    output.extend(families)
    return output

get_publish_instance_label(instance)

Try to get label from pyblish instance.

First are used values in instance data under 'label' and 'name' keys. Then is used string conversion of instance object -> 'instance._name'.

Todos

Maybe 'productName' key could be used too.

Parameters:

Name Type Description Default
instance Instance

Pyblish instance.

required

Returns:

Name Type Description
str str

Instance label.

Source code in client/ayon_core/pipeline/publish/lib.py
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
def get_publish_instance_label(instance: pyblish.api.Instance) -> str:
    """Try to get label from pyblish instance.

    First are used values in instance data under 'label' and 'name' keys. Then
    is used string conversion of instance object -> 'instance._name'.

    Todos:
        Maybe 'productName' key could be used too.

    Args:
        instance (pyblish.api.Instance): Pyblish instance.

    Returns:
        str: Instance label.
    """

    return (
        instance.data.get("label")
        or instance.data.get("name")
        or str(instance)
    )

get_publish_repre_path(instance, repre, only_published=False)

Get representation path that can be used for integration.

When 'only_published' is set to true the validation of path is not relevant. In that case we just need what is set in 'published_path' as "reference". The reference is not used to get or upload the file but for reference where the file was published.

Parameters:

Name Type Description Default
instance Instance

Processed instance object. Used for source of staging dir if representation does not have filled it.

required
repre dict

Representation on instance which could be and could not be integrated with main integrator.

required
only_published bool

Care only about published paths and ignore if filepath is not existing anymore.

False

Returns:

Name Type Description
str str | None

Path to representation file.

None str | None

Path is not filled or does not exists.

Source code in client/ayon_core/pipeline/publish/lib.py
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
def get_publish_repre_path(
    instance: pyblish.api.Instance,
    repre: dict[str, Any],
    only_published: bool = False,
) -> str | None:
    """Get representation path that can be used for integration.

    When 'only_published' is set to true the validation of path is not
    relevant. In that case we just need what is set in 'published_path'
    as "reference". The reference is not used to get or upload the file but
    for reference where the file was published.

    Args:
        instance (pyblish.api.Instance): Processed instance object. Used
            for source of staging dir if representation does not have
            filled it.
        repre (dict): Representation on instance which could be and
            could not be integrated with main integrator.
        only_published (bool): Care only about published paths and
            ignore if filepath is not existing anymore.

    Returns:
        str: Path to representation file.
        None: Path is not filled or does not exists.

    """
    published_path = repre.get("published_path")
    if published_path:
        published_path = os.path.normpath(published_path)
        if os.path.exists(published_path):
            return published_path

    if only_published:
        return published_path

    comp_files = repre["files"]
    if isinstance(comp_files, (tuple, list, set)):
        filename = comp_files[0]
    else:
        filename = comp_files

    staging_dir = repre.get("stagingDir")
    if not staging_dir:
        staging_dir = get_instance_staging_dir(instance)

    # Expand the staging dir path in case it's been stored with the root
    # template syntax
    anatomy = instance.context.data["anatomy"]
    staging_dir = anatomy.fill_root(staging_dir)

    src_path = os.path.normpath(os.path.join(staging_dir, filename))
    if os.path.exists(src_path):
        return src_path
    return None

get_publish_template_name(project_name, host_name, product_base_type, task_name, task_type, *, project_settings=None, hero=False, logger=None)

Get template name which should be used for passed context.

Publish templates are filtered by host name, family, task name and task type.

Default template which is used at if profiles are not available or profile has empty value is defined by 'DEFAULT_PUBLISH_TEMPLATE' constant.

Parameters:

Name Type Description Default
project_name str

Name of project where to look for settings.

required
host_name str

Name of host integration.

required
product_base_type str

Product base type for which should be found template.

required
task_name str

Task name on which is instance working.

required
task_type str

Task type on which is instance working.

required
project_settings dict[str, Any] | None

Prepared project settings.

None
hero bool

Template is for hero version publishing.

False
logger Logger | None

Custom logger used for 'filter_profiles' function.

None

Returns:

Name Type Description
str str

Template name which should be used for integration.

Source code in client/ayon_core/pipeline/publish/lib.py
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
@_get_publish_template_name_wrap
def get_publish_template_name(
    project_name: str,
    host_name: str,
    product_base_type: str,
    task_name: str | None,
    task_type: str | None,
    *,
    project_settings: dict[str, Any] | None = None,
    hero: bool = False,
    logger: logging.Logger | None = None,
) -> str:
    """Get template name which should be used for passed context.

    Publish templates are filtered by host name, family, task name and
    task type.

    Default template which is used at if profiles are not available or profile
    has empty value is defined by 'DEFAULT_PUBLISH_TEMPLATE' constant.

    Args:
        project_name (str): Name of project where to look for settings.
        host_name (str): Name of host integration.
        product_base_type (str): Product base type for which should be
            found template.
        task_name (str): Task name on which is instance working.
        task_type (str): Task type on which is instance working.
        project_settings (dict[str, Any] | None): Prepared project settings.
        hero (bool): Template is for hero version publishing.
        logger (logging.Logger | None): Custom logger used for
            'filter_profiles' function.

    Returns:
        str: Template name which should be used for integration.

    """
    template = None
    filter_criteria = {
        "host_names": host_name,
        "product_base_types": product_base_type,
        "task_names": task_name,
        "task_types": task_type,
    }
    if hero:
        default_template = DEFAULT_HERO_PUBLISH_TEMPLATE
        profiles = get_hero_template_name_profiles(
            project_name, project_settings
        )

    else:
        profiles = get_template_name_profiles(
            project_name, project_settings
        )
        default_template = DEFAULT_PUBLISH_TEMPLATE

    profile = filter_profiles(profiles, filter_criteria, logger=logger)
    if profile:
        template = profile["template_name"]
    return template or default_template

get_publish_template_object(instance, category_name='publish', template_name=None)

Return anatomy template object to use for integration.

Note: What is the actual type of the object?

Parameters:

Name Type Description Default
instance Instance

Instance to process.

required
category_name str

Category name of the template to use. Defaults to "publish".

'publish'
template_name str | None

Template name to use. If not provided, it will get the template name from the provided instance.

None

Returns:

Name Type Description
AnatomyTemplateItem 'AnatomyTemplateItem'

Anatomy template object

Source code in client/ayon_core/pipeline/publish/lib.py
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
def get_publish_template_object(
    instance: pyblish.api.Instance,
    category_name: str = "publish",
    template_name: str | None = None,
) -> "AnatomyTemplateItem":
    """Return anatomy template object to use for integration.

    Note: What is the actual type of the object?

    Args:
        instance (pyblish.api.Instance): Instance to process.
        category_name (str): Category name of the template to use.
            Defaults to "publish".
        template_name (str | None): Template name to use.
            If not provided, it will get the template name from
            the provided instance.

    Returns:
        AnatomyTemplateItem: Anatomy template object

    """
    # Anatomy data is pre-filled by Collectors
    if not template_name:
        template_name = get_instance_template_name(instance)
    anatomy: Anatomy = instance.context.data["anatomy"]
    return anatomy.get_template_item(
        category_name=category_name,
        template_name=template_name
    )

get_rootless_path(anatomy, path)

Get rootless variant of the path.

Returns, if possible, a path without an absolute portion from the root (e.g. 'c:\' or '/opt/..'). This is basically a wrapper for the meth:Anatomy.find_root_template_from_path method that displays a warning if the root path is not found.

This information is platform-dependent and shouldn't be captured. For example::

 'c:/projects/MyProject1/Assets/publish...'
 will be transformed to:
 '{root}/MyProject1/Assets...'

Parameters:

Name Type Description Default
anatomy Anatomy

Project anatomy.

required
path str

Absolute path.

required

Returns:

Name Type Description
str str

Path where root path is replaced by formatting string.

Source code in client/ayon_core/pipeline/publish/lib.py
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
def get_rootless_path(anatomy: "Anatomy", path: str) -> str:
    r"""Get rootless variant of the path.

    Returns, if possible, a path without an absolute portion from the root
    (e.g. 'c:\' or '/opt/..'). This is basically a wrapper for the
    meth:`Anatomy.find_root_template_from_path` method that displays
    a warning if the root path is not found.

     This information is platform-dependent and shouldn't be captured.
     For example::

         'c:/projects/MyProject1/Assets/publish...'
         will be transformed to:
         '{root}/MyProject1/Assets...'

    Args:
        anatomy (Anatomy): Project anatomy.
        path (str): Absolute path.

    Returns:
        str: Path where root path is replaced by formatting string.

    """
    success, rootless_path = anatomy.find_root_template_from_path(path)
    if success:
        path = rootless_path
    else:
        log.warning((
            'Could not find root path for remapping "%s".'
            " This may cause issues on farm."
        ), path)
    return path

get_trait_representations(instance)

Get trait representations from instance.

Parameters:

Name Type Description Default
instance Instance

Instance to get trait representations from.

required

Returns:

Type Description
list[Representation]

list[Representation]: List of representation names.

Source code in client/ayon_core/pipeline/publish/lib.py
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
def get_trait_representations(
    instance: pyblish.api.Instance
) -> list[Representation]:
    """Get trait representations from instance.

    Args:
        instance (pyblish.api.Instance): Instance to get trait
            representations from.

    Returns:
        list[Representation]: List of representation names.

    """
    return instance.data.get(TRAIT_INSTANCE_KEY, [])

get_version_data_from_instance(instance)

Get version data from the Instance.

Parameters:

Name Type Description Default
instance Instance

the current instance being published.

required

Returns:

Name Type Description
dict dict

the required information for version["data"]

Source code in client/ayon_core/pipeline/publish/lib.py
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
def get_version_data_from_instance(
    instance: pyblish.api.Instance
) -> dict:
    """Get version data from the Instance.

    Args:
        instance (pyblish.api.Instance): the current instance
            being published.

    Returns:
        dict: the required information for ``version["data"]``

    """
    context = instance.context

    # create relative source path for DB
    if "source" in instance.data:
        source = instance.data["source"]
    else:
        source = context.data["currentFile"]
        anatomy = instance.context.data["anatomy"]
        source = get_rootless_path(anatomy, source)
    log.debug("Source: %s", source)

    version_data = {
        "families": get_instance_families(instance),
        "time": context.data["time"],
        "author": context.data["user"],
        "source": source,
        "comment": instance.data["comment"],
        "machine": context.data.get("machine"),
        "fps": instance.data.get("fps", context.data.get("fps"))
    }

    intent_value = context.data.get("intent")
    if intent_value and isinstance(intent_value, dict):
        intent_value = intent_value.get("value")

    if intent_value:
        version_data["intent"] = intent_value

    # Include optional data if present in
    optionals = [
        "frameStart", "frameEnd", "step",
        "handleEnd", "handleStart", "sourceHashes"
    ]
    for key in optionals:
        if key in instance.data:
            version_data[key] = instance.data[key]

    # Include instance.data[versionData] directly
    version_data_instance = instance.data.get("versionData")
    if version_data_instance:
        version_data.update(version_data_instance)

    return version_data

has_trait_representations(instance)

Check if instance has trait representation.

Parameters:

Name Type Description Default
instance Instance

Instance to check.

required

Returns:

Name Type Description
True bool

Instance has trait representation.

False bool

Instance does not have trait representation.

Source code in client/ayon_core/pipeline/publish/lib.py
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
def has_trait_representations(
    instance: pyblish.api.Instance
) -> bool:
    """Check if instance has trait representation.

    Args:
        instance (pyblish.api.Instance): Instance to check.

    Returns:
        True: Instance has trait representation.
        False: Instance does not have trait representation.

    """
    return TRAIT_INSTANCE_KEY in instance.data

load_help_content_from_filepath(filepath)

Load help content from xml file. Xml file may contain errors and warnings.

Source code in client/ayon_core/pipeline/publish/lib.py
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
def load_help_content_from_filepath(
    filepath: str
) -> dict[str, dict[str, HelpContent]]:
    """Load help content from xml file.
    Xml file may contain errors and warnings.
    """
    errors = {}
    warnings = {}
    output = {
        "errors": errors,
        "warnings": warnings
    }
    if not os.path.exists(filepath):
        return output
    tree = xml.etree.ElementTree.parse(filepath)
    root = tree.getroot()
    for child in root:
        child_id = child.attrib.get("id")
        if child_id is None:
            continue

        # Make sure ID is string
        child_id = str(child_id)

        title = child.find("title").text
        description = child.find("description").text
        detail_node = child.find("detail")
        detail = None
        if detail_node is not None:
            detail = detail_node.text
        if child.tag == "error":
            errors[child_id] = HelpContent(title, description, detail)
        elif child.tag == "warning":
            warnings[child_id] = HelpContent(title, description, detail)
    return output

main_cli_publish(path, targets=None, addons_manager=None)

Start headless publishing.

Publish use json from passed path argument.

Parameters:

Name Type Description Default
path str

Path to JSON.

required
targets list[str] | None

List of pyblish targets.

None
addons_manager AddonsManager | None

Addons manager instance.

None

Raises:

Type Description
RuntimeError

When there is no path to process or when executed with list of JSON paths.

Source code in client/ayon_core/pipeline/publish/lib.py
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
def main_cli_publish(
    path: str,
    targets: list[str] | None = None,
    addons_manager: AddonsManager | None = None,
) -> None:
    """Start headless publishing.

    Publish use json from passed path argument.

    Args:
        path (str): Path to JSON.
        targets (list[str] | None): List of pyblish targets.
        addons_manager (AddonsManager | None): Addons manager instance.

    Raises:
        RuntimeError: When there is no path to process or when executed with
            list of JSON paths.

    """
    from ayon_core.pipeline import (
        install_ayon_plugins,
        get_global_context,
    )
    from ayon_core.pipeline.publish import PublishLogic

    # Register target and host
    if not isinstance(path, str):
        raise RuntimeError("Path to JSON must be a string.")

    log = Logger.get_logger("CLI-publish")

    # Make public ayon api behave as other user
    # - this works only if public ayon api is using service user
    username = os.environ.get("AYON_USERNAME")
    if username:
        # NOTE: ayon-python-api does not have public api function to find
        #   out if is used service user. So we need to have try > except
        #   block.
        con = get_server_api_connection()
        try:
            con.set_default_service_username(username)
        except ValueError:
            pass

    context = get_global_context()
    project_settings = get_project_settings(context["project_name"])

    install_ayon_plugins()

    if addons_manager is None:
        addons_manager = AddonsManager(project_settings)

    applications_addon = addons_manager.get_enabled_addon("applications")
    if applications_addon is not None:
        env = applications_addon.get_farm_publish_environment_variables(
            context["project_name"],
            context["folder_path"],
            context["task_name"],
        )
        os.environ.update(env)

    pyblish.api.register_host("shell")

    if not targets:
        targets = ["farm"]

    os.environ["AYON_PUBLISH_DATA"] = path
    os.environ["HEADLESS_PUBLISH"] = "true"  # to use in app lib

    log.info("Running publish ...")

    discover_result = publish_plugins_discover()
    print(discover_result.get_report(only_errors=False))

    logic = PublishLogic(reset=False)
    logic.reset(
        project_name=context["project_name"],
        publish_discover_result=discover_result,
        targets=targets,
    )
    if logic.has_failed():
        report = logic.get_publish_report()
        if report.blocking_crashed_paths:
            joined_paths = "\n".join([
                f"- {path}"
                for path in report.blocking_crashed_paths
            ])
            log.error(
                "Plugin discovery strict mode is enabled."
                " Crashed plugin paths that prevent from publishing:"
                f"\n{joined_paths}"
            )
            sys.exit(1)

        fail_reason = logic.get_fail_reason()
        log.error(
            "Failed before publishing started."
            f" Probably because of unhandled reason '{fail_reason}'."
        )
        sys.exit(1)

    logic.publish()
    if logic.has_failed():
        sys.exit(1)

    log.info("Publish finished.")

publish_plugins_discover(paths=None)

Find and return available pyblish plug-ins.

Overridden function from pyblish module to be able to collect crashed files and reason of their crash.

Parameters:

Name Type Description Default
paths list[str] | None

Paths to discover plug-ins from. If no paths are provided, all paths are searched.

None
Source code in client/ayon_core/pipeline/publish/lib.py
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
def publish_plugins_discover(
    paths: list[str] | None = None,
) -> DiscoverResult:
    """Find and return available pyblish plug-ins.

    Overridden function from `pyblish` module to be able to collect
        crashed files and reason of their crash.

    Arguments:
        paths (list[str] | None): Paths to discover plug-ins from.
            If no paths are provided, all paths are searched.

    """
    # The only difference with `pyblish.api.discover`
    result = DiscoverResult(pyblish.api.Plugin)

    plugins = {}
    plugin_names = []

    allow_duplicates = pyblish.plugin.ALLOW_DUPLICATES
    log = pyblish.plugin.log

    # Include plug-ins from registered paths
    if not paths:
        paths = pyblish.plugin.plugin_paths()

    for path in paths:
        path = os.path.normpath(path)
        filenames = []
        if os.path.isdir(path):
            filenames.extend(
                name
                for name in os.listdir(path)
                if (
                    os.path.isfile(os.path.join(path, name))
                    and not name.startswith("_")
                )
            )
        else:
            filenames.append(os.path.basename(path))
            path = os.path.dirname(path)

        dirpath_hash = hashlib.md5(path.encode("utf-8")).hexdigest()
        for filename in filenames:
            basename, ext = os.path.splitext(filename)
            if ext.lower() != ".py":
                continue

            filepath = os.path.join(path, filename)
            module_name = f"{dirpath_hash}.{basename}"
            try:
                module = import_filepath(
                    filepath, module_name, sys_module_name=module_name
                )

            except Exception as err:  # noqa: BLE001
                # we need broad exception to catch all possible errors.
                result.crashed_file_paths[filepath] = sys.exc_info()

                log.debug('Skipped: "%s" (%s)', filepath, err)
                continue

            for plugin in pyblish.plugin.plugins_from_module(module):
                # Ignore base plugin classes
                # NOTE 'pyblish.api.discover' does not ignore them!
                if (
                    plugin is pyblish.api.Plugin
                    or plugin is pyblish.api.ContextPlugin
                    or plugin is pyblish.api.InstancePlugin
                ):
                    continue
                if not allow_duplicates and plugin.__name__ in plugin_names:
                    result.duplicated_plugins.append(plugin)
                    log.debug("Duplicate plug-in found: %s", plugin)
                    continue

                plugin_names.append(plugin.__name__)
                plugin.__file__ = module.__file__
                key = f"{module.__file__}.{plugin.__name__}"
                plugins[key] = plugin

    # Include plug-ins from registration.
    # Directly registered plug-ins take precedence.
    for plugin in pyblish.plugin.registered_plugins():
        if not allow_duplicates and plugin.__name__ in plugin_names:
            result.duplicated_plugins.append(plugin)
            log.debug("Duplicate plug-in found: %s", plugin)
            continue

        plugin_names.append(plugin.__name__)

        plugins[plugin.__name__] = plugin

    plugins = list(plugins.values())
    pyblish.plugin.sort(plugins)  # In-place

    # In-place user-defined filter
    for filter_ in pyblish.plugin._registered_plugin_filters:
        filter_(plugins)

    result.plugins = plugins

    return result

set_trait_representations(instance, representations)

Set trait representations to instance.

Parameters:

Name Type Description Default
instance Instance

Instance to set trait representations to.

required
representations list[Representation]

List of trait based representations.

required
Source code in client/ayon_core/pipeline/publish/lib.py
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
def set_trait_representations(
    instance: pyblish.api.Instance,
    representations: list[Representation]
) -> None:
    """Set trait representations to instance.

    Args:
        instance (pyblish.api.Instance): Instance to set trait
            representations to.
        representations (list[Representation]): List of trait
            based representations.

    """
    instance.data[TRAIT_INSTANCE_KEY] = representations