Skip to content

logic

MessageHandler

Bases: Handler

Helper to collect log records during publishing.

This is used to collect log records during publishing and store them in a list. The list can be cleared and retrieved as needed.

This is needed to create the log message at the moment of their emit. The fill data may change during publishing and stored records might not reflect data at the moment of their emit.

data = {"key": 1}
log.info("Data: %s", data)
data["key"] = 2
log.info("Data: %s", data)

Without the handle would this code snippet product 2 records: - 'Data: {"key": 1}' -> But this should be 'Data: {"key": 2}' - 'Data: {"key": 1}'

Source code in client/ayon_core/pipeline/publish/logic.py
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
class MessageHandler(logging.Handler):
    """Helper to collect log records during publishing.

    This is used to collect log records during publishing and store them in
        a list. The list can be cleared and retrieved as needed.

    This is needed to create the log message at the moment of their emit. The
        fill data may change during publishing and stored records might not
        reflect data at the moment of their emit.

    ```python
    data = {"key": 1}
    log.info("Data: %s", data)
    data["key"] = 2
    log.info("Data: %s", data)
    ```
    Without the handle would this code snippet product 2 records:
    - 'Data: {"key": 1}' -> But this should be 'Data: {"key": 2}'
    - 'Data: {"key": 1}'

    """
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._records = []

    def clear_records(self):
        self._records = []

    def emit(self, record):
        try:
            record.msg = record.getMessage()
        except Exception:
            record.msg = str(record.msg)
        self._records.append(record)

    def get_records(self):
        return self._records

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

PublishErrorInfo dataclass

Data driven publish error item.

Prepared data container with information about publish error and it's source plugin.

Can be converted to raw data and recreated should be used for controller and UI connection.

Attributes:

Name Type Description
exception Exception

The exception that caused the publish error.

instance_id str | None

Pyblish instance id to which is publish error connected.

instance_label str | None

Prepared instance label.

plugin_id str

Pyblish plugin id which triggered the publish error.

is_context_plugin bool

Error happened on context.

is_validation_error bool

Error is a validation error.

title str | None

Error title.

description str | None

Error description.

detail str

Error detail.

Source code in client/ayon_core/pipeline/publish/logic.py
 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
123
124
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
@dataclass
class PublishErrorInfo:
    """Data driven publish error item.

    Prepared data container with information about publish error and it's
    source plugin.

    Can be converted to raw data and recreated should be used for controller
    and UI connection.

    Attributes:
        exception (Exception): The exception that caused the publish error.
        instance_id (str | None): Pyblish instance id to which is
            publish error connected.
        instance_label (str | None): Prepared instance label.
        plugin_id (str): Pyblish plugin id which triggered the publish
            error.
        is_context_plugin (bool): Error happened on context.
        is_validation_error (bool): Error is a validation error.
        title (str | None): Error title.
        description (str | None): Error description.
        detail (str): Error detail.

    """
    exception: Exception
    instance_id: str | None
    instance_label: str | None
    plugin_id: str
    is_context_plugin: bool
    is_validation_error: bool
    title: str | None
    description: str | None
    detail: str | None

    @classmethod
    def from_result(
        cls,
        plugin: PluginType,
        instance: pyblish.api.Instance | None,
        exception: Exception,
    ) -> "PublishErrorInfo":
        """Hold information about publishing error.

        Returns:
            PublishErrorInfo: New object with filled data.

        """
        plugin_id = PublishLogic.get_publish_plugin_id(plugin)
        instance_label = instance_id = title = description = detail = None
        if instance is not None:
            instance_label = (
                instance.data.get("label") or instance.data.get("name")
            )
            instance_id = instance.id

        if isinstance(exception, PublishError):
            title = exception.title
            description = exception.description
            detail = exception.detail

        if not title:
            if hasattr(plugin, "label") and plugin.label:
                plugin_label = plugin.label
            else:
                plugin_label = plugin.__name__
            title = plugin_label

        return cls(
            exception,
            instance_id,
            instance_label,
            plugin_id,
            instance is None,
            isinstance(exception, PublishValidationError),
            title,
            description,
            detail,
        )

from_result(plugin, instance, exception) classmethod

Hold information about publishing error.

Returns:

Name Type Description
PublishErrorInfo 'PublishErrorInfo'

New object with filled data.

Source code in client/ayon_core/pipeline/publish/logic.py
112
113
114
115
116
117
118
119
120
121
122
123
124
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
@classmethod
def from_result(
    cls,
    plugin: PluginType,
    instance: pyblish.api.Instance | None,
    exception: Exception,
) -> "PublishErrorInfo":
    """Hold information about publishing error.

    Returns:
        PublishErrorInfo: New object with filled data.

    """
    plugin_id = PublishLogic.get_publish_plugin_id(plugin)
    instance_label = instance_id = title = description = detail = None
    if instance is not None:
        instance_label = (
            instance.data.get("label") or instance.data.get("name")
        )
        instance_id = instance.id

    if isinstance(exception, PublishError):
        title = exception.title
        description = exception.description
        detail = exception.detail

    if not title:
        if hasattr(plugin, "label") and plugin.label:
            plugin_label = plugin.label
        else:
            plugin_label = plugin.__name__
        title = plugin_label

    return cls(
        exception,
        instance_id,
        instance_label,
        plugin_id,
        instance is None,
        isinstance(exception, PublishValidationError),
        title,
        description,
        detail,
    )

PublishFailReason

Bases: Enum

Reason why publishing failed.

Source code in client/ayon_core/pipeline/publish/logic.py
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
class PublishFailReason(Enum):
    """Reason why publishing failed.

    Attributes:
        No - Publishing did not fail.
        BlockingPaths - Strict validation of crashed publish plugin paths
            during discovery.
        ValidationErrors - Publishing failed because of validation errors.
        Error - An error happened during publishing.

    """
    No = auto()
    Error = auto()
    ValidationErrors = auto()
    BlockingPaths = auto()

PublishIterTask dataclass

Information about next processing function in publishing.

Holds reference to PublishLogic that defined the next processing function.

This wrapper is needed for UI purposes as the UI has to have access to currently processed plugin and instance, also has to trigger the process in between UI updates, but in main thread.

Attributes 'plugin', 'instance' and 'item_label'.

Attributes:

Name Type Description
logic PublishLogic

PublishLogic that defined the next processing function.

plugin PluginType

Currently processed plugin.

instance Instance | None

Currently processed instance.

item_label str

Label of currently processed item. Can be plugin or instance label.

Source code in client/ayon_core/pipeline/publish/logic.py
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
@dataclass
class PublishIterTask:
    """Information about next processing function in publishing.

    Holds reference to PublishLogic that defined the next processing function.

    This wrapper is needed for UI purposes as the UI has to have access to
        currently processed plugin and instance, also has to trigger the
        process in between UI updates, but in main thread.

    Attributes 'plugin', 'instance' and 'item_label'.

    Attributes:
        logic (PublishLogic): PublishLogic that defined the next processing
            function.
        plugin (PluginType): Currently processed plugin.
        instance (pyblish.api.Instance | None): Currently processed instance.
        item_label (str): Label of currently processed item. Can be
            plugin or instance label.

    """
    logic: "PublishLogic"
    plugin: PluginType
    instance: pyblish.api.Instance | None
    item_label: str
    executed: bool = False

    def __call__(self) -> None:
        self.executed = True
        self.logic._process_plugin(self.plugin, self.instance)

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
    )

PublishState dataclass

Keep state of PublishLogic at one place.

Source code in client/ayon_core/pipeline/publish/logic.py
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
@dataclass
class PublishState:
    """Keep state of PublishLogic at one place."""
    # Publishing should stop at validation stage
    stop_after_validation: bool = False
    # 'PublishValidationError' won't stop the publishing until the end of
    #   the validation order if set to 'False'. Other exceptions will stop
    #   the publishing.
    strict_validation_error_handling: bool = True
    comment_is_set: bool = False

    # Publishing started -> can prevent some actions
    started: bool = False
    # Publishing is in progress -> can be used to stop/pause publishing
    is_running: bool = False
    # Publishing is over validation order
    validated: bool = False
    # Finished successfully
    finished: bool = False

    progress: int = 0
    max_progress: int = 0

    fail_reason: PublishFailReason = PublishFailReason.No
    error_info: PublishErrorInfo | None = None
    validation_errors: list[PublishErrorInfo] = field(
        default_factory=list
    )

    def can_continue(self) -> bool:
        """Check if publishing can continue.

        Does not respect 'is_running' and 'stop_after_validation' values
            as this should tell if publishing can be continued.

        Returns:
            bool: Can publishing continue.

        """
        if self.finished:
            return False

        if self.fail_reason == PublishFailReason.No:
            return True

        if self.fail_reason == PublishFailReason.ValidationErrors:
            if self.strict_validation_error_handling or self.validated:
                return False
            return True
        return False

    def should_stop(self) -> bool:
        """Check if publishing should stop."""
        if not self.can_continue():
            return True

        # Stop if validation is over and validation errors happened
        #   or publishing should stop at validation
        if self.validated and self.stop_after_validation:
            return True
        return False

can_continue()

Check if publishing can continue.

Does not respect 'is_running' and 'stop_after_validation' values as this should tell if publishing can be continued.

Returns:

Name Type Description
bool bool

Can publishing continue.

Source code in client/ayon_core/pipeline/publish/logic.py
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
def can_continue(self) -> bool:
    """Check if publishing can continue.

    Does not respect 'is_running' and 'stop_after_validation' values
        as this should tell if publishing can be continued.

    Returns:
        bool: Can publishing continue.

    """
    if self.finished:
        return False

    if self.fail_reason == PublishFailReason.No:
        return True

    if self.fail_reason == PublishFailReason.ValidationErrors:
        if self.strict_validation_error_handling or self.validated:
            return False
        return True
    return False

should_stop()

Check if publishing should stop.

Source code in client/ayon_core/pipeline/publish/logic.py
257
258
259
260
261
262
263
264
265
266
def should_stop(self) -> bool:
    """Check if publishing should stop."""
    if not self.can_continue():
        return True

    # Stop if validation is over and validation errors happened
    #   or publishing should stop at validation
    if self.validated and self.stop_after_validation:
        return True
    return False

collect_families_from_instances(instances, only_active=False)

Collect all families for passed publish instances.

Parameters:

Name Type Description Default
instances list[Instance]

List of publish instances from which are families collected.

required
only_active bool

Return families only for active instances.

False

Returns:

Type Description
set[str]

set[str]: Families available on instances.

Source code in client/ayon_core/pipeline/publish/logic.py
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
def collect_families_from_instances(
    instances: list[pyblish.api.Instance],
    only_active: bool = False,
) -> set[str]:
    """Collect all families for passed publish instances.

    Args:
        instances (list[pyblish.api.Instance]): List of publish instances from
            which are families collected.
        only_active (bool): Return families only for active instances.

    Returns:
        set[str]: Families available on instances.

    """
    all_families = set()
    for instance in instances:
        if only_active:
            if instance.data.get("publish") is False:
                continue
        family = instance.data.get("family")
        if family:
            all_families.add(family)

        families = instance.data.get("families") or tuple()
        for family in families:
            all_families.add(family)

    return all_families