Skip to content

integrate_traits

Integrate representations with traits.

IntegrateTraits

Bases: InstancePlugin

Integrate representations with traits.

Source code in client/ayon_core/plugins/publish/integrate_traits.py
 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
 358
 359
 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
 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
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
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
class IntegrateTraits(pyblish.api.InstancePlugin):
    """Integrate representations with traits."""

    label = "Integrate Traits of an Asset"
    order = pyblish.api.IntegratorOrder
    log: "logging.Logger"

    def process(self, instance: pyblish.api.Instance) -> None:
        """Integrate representations with traits.

        Todo:
            Refactor this method to be more readable and maintainable.

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

        """
        # 1) skip farm and integrate ==  False

        if instance.data.get("integrate", True) is False:
            self.log.debug("Instance is marked to skip integrating. Skipping")
            return

        if instance.data.get("farm"):
            self.log.debug(
                "Instance is marked to be processed on farm. Skipping")
            return

        # TODO (antirotor): Find better name for the key
        if not has_trait_representations(instance):
            self.log.debug(
                "Instance has no representations with traits. Skipping")
            return

        # 2) filter representations based on LifeCycle traits
        set_trait_representations(
            instance,
            self.filter_lifecycle(get_trait_representations(instance))
        )

        representations: list[Representation] = get_trait_representations(
            instance
        )
        if not representations:
            self.log.debug(
                "Instance has no persistent representations. Skipping")
            return

        op_session = OperationsSession()

        product_entity = self.prepare_product(instance, op_session)

        version_entity = self.prepare_version(
            instance, op_session, product_entity
        )
        instance.data["versionEntity"] = version_entity

        transfers = self.get_transfers_from_representations(
            instance, representations)

        # 8) Transfer files
        file_transactions = FileTransaction(
            log=self.log,
            # Enforce unique transfers
            allow_queue_replacements=False)
        for transfer in transfers:
            self.log.debug(
                "Transferring file: %s -> %s",
                transfer.source,
                transfer.destination
            )
            file_transactions.add(
                transfer.source.as_posix(),
                transfer.destination.as_posix(),
                mode=FileTransaction.MODE_COPY,
            )
        file_transactions.process()
        self.log.debug(
            "Transferred files %s", [file_transactions.transferred])

        # replace original paths with the destination in traits.
        for transfer in transfers:
            transfer.related_trait.file_path = transfer.destination

        # 9) Create representation entities
        for representation in representations:
            representation_entity = new_representation_entity(
                representation.name,
                version_entity["id"],
                files=self._get_legacy_files_for_representation(
                    transfers,
                    representation,
                    anatomy=instance.context.data["anatomy"]),
                attribs={},
                data="",
                tags=[],
                status="",
            )
            # add traits to representation entity
            representation_entity["traits"] = representation.traits_as_dict()
            op_session.create_entity(
                project_name=instance.context.data["projectName"],
                entity_type="representation",
                data=prepare_for_json(representation_entity),
            )

        # 10) Commit the session to AYON
        self.log.debug("{}".format(op_session.to_data()))
        op_session.commit()

    def get_transfers_from_representations(
            self,
            instance: pyblish.api.Instance,
            representations: list[Representation]) -> list[TransferItem]:
        """Get transfers from representations.

        This method will go through all representations and prepare transfers
        based on the traits they contain. First it will validate the
        representation, and then it will prepare template data for the
        representation. It specifically handles FileLocations, FileLocation,
        Bundle, Sequence and UDIM traits.

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

        Returns:
            list[TransferItem]: List of transfers.

        Raises:
            PublishError: If representation is invalid.

        """
        template: str = self.get_publish_template(instance)
        instance_template_data: dict[str, str] = {}
        transfers: list[TransferItem] = []
        # prepare template and data to format it
        for representation in representations:

            # validate representation first, this will go through all traits
            # and check if they are valid
            try:
                representation.validate()
            except TraitValidationError as e:
                msg = f"Representation '{representation.name}' is invalid: {e}"
                raise PublishError(msg) from e

            template_data = self.get_template_data_from_representation(
                representation, instance)
            # add instance based template data

            template_data.update(instance_template_data)

            # treat Variant as `output` in template data
            with contextlib.suppress(MissingTraitError):
                template_data["output"] = (
                    representation.get_trait(Variant).variant
                )

            template_item = TemplateItem(
                anatomy=instance.context.data["anatomy"],
                template=template,
                template_data=copy.deepcopy(template_data),
                template_object=self.get_publish_template_object(instance),
            )

            if representation.contains_trait(FileLocations):
                # If representation has FileLocations trait (list of files)
                # it can be either Sequence or UDIM tile set.
                # We do not allow unrelated files in the single representation.
                # Note: we do not support yet frame sequence of multiple UDIM
                # tiles in the same representation
                self.get_transfers_from_file_locations(
                    representation, template_item, transfers
                )
            elif representation.contains_trait(FileLocation):
                # This is just a single file representation
                self.get_transfers_from_file_location(
                    representation, template_item, transfers
                )

            elif representation.contains_trait(Bundle):
                # Bundle groups multiple "sub-representations" together.
                # It has a list of lists with traits, some might be
                # FileLocations,but some might be "file-less" representations
                # or even other bundles.
                self.get_transfers_from_bundle(
                    representation, template_item, transfers
                )
        return transfers

    def _get_relative_to_root_original_dirname(
            self, instance: pyblish.api.Instance) -> str:
        """Get path stripped of root of the original directory name.

        If `originalDirname` or `stagingDir` is set in instance data,
        this will return it as rootless path. The path must reside
        within the project directory.

        Returns:
            str: Relative path to the root of the project directory.

        Raises:
            PublishError: If the path is not within the project directory.

        """
        original_directory = (
                instance.data.get("originalDirname") or
                instance.data.get("stagingDir"))
        anatomy = instance.context.data["anatomy"]

        rootless = self.get_rootless_path(anatomy, original_directory)
        # this check works because _rootless will be the same as
        # original_directory if the original_directory cannot be transformed
        # to the rootless path.
        if rootless == original_directory:
            msg = (
                f"Destination path '{original_directory}' must "
                "be in project directory.")
            raise PublishError(msg)
        # the root is at the beginning - {root[work]}/rest/of/the/path
        relative_path_start = rootless.rfind("}") + 2
        return rootless[relative_path_start:]

        # 8) Transfer files
        # 9) Commit the session to AYON
        # 10) Finalize represetations - add integrated path Trait etc.

    @staticmethod
    def filter_lifecycle(
            representations: list[Representation]
    ) -> list[Representation]:
        """Filter representations based on LifeCycle traits.

        Args:
            representations (list): List of representations.

        Returns:
            list: Filtered representations.

        """
        return [
            representation
            for representation in representations
            if representation.contains_trait(Persistent)
        ]

    def get_template_name(self, 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"]
        task_info = anatomy_data.get("task") or {}

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

    def get_publish_template(self, 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
        template_name = self.get_template_name(instance)
        anatomy = instance.context.data["anatomy"]
        publish_template = anatomy.get_template_item("publish", template_name)
        path_template_obj = publish_template["path"]
        return path_template_obj.template.replace("\\", "/")

    def get_publish_template_object(
            self, instance: pyblish.api.Instance) -> "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.

        Returns:
            AnatomyTemplateItem: Anatomy template object

        """
        # Anatomy data is pre-filled by Collectors
        template_name = self.get_template_name(instance)
        anatomy = instance.context.data["anatomy"]
        return anatomy.get_template_item("publish", template_name)

    def prepare_product(
            self,
            instance: pyblish.api.Instance,
            op_session: OperationsSession) -> dict:
        """Prepare product for integration.

        Args:
            instance (pyblish.api.Instance): Instance to process.
            op_session (OperationsSession): Operations session.

        Returns:
            dict: Product entity.

        """
        project_name = instance.context.data["projectName"]
        folder_entity = instance.data["folderEntity"]
        product_name = instance.data["productName"]
        product_type = instance.data["productType"]
        self.log.debug("Product: %s", product_name)

        # Get existing product if it exists
        existing_product_entity = get_product_by_name(
            project_name, product_name, folder_entity["id"]
        )

        # Define product data
        data = {
            "families": get_instance_families(instance)
        }
        attributes = {}

        product_group = instance.data.get("productGroup")
        if product_group:
            attributes["productGroup"] = product_group
        elif existing_product_entity:
            # Preserve previous product group if new version does not set it
            product_group = existing_product_entity.get("attrib", {}).get(
                "productGroup"
            )
            if product_group is not None:
                attributes["productGroup"] = product_group

        product_id = existing_product_entity["id"] if existing_product_entity else None  # noqa: E501
        product_entity = new_product_entity(
            product_name,
            product_type,
            folder_entity["id"],
            data=data,
            attribs=attributes,
            entity_id=product_id
        )

        if existing_product_entity is None:
            # Create a new product
            self.log.info(
                "Product '%s' not found, creating ...",
                product_name
            )
            op_session.create_entity(
                project_name, "product", product_entity
            )

        else:
            # Update existing product data with new data and set in database.
            # We also change the found product in-place so we don't need to
            # re-query the product afterward
            update_data = get_changed_attributes(
                existing_product_entity, product_entity
            )
            op_session.update_entity(
                project_name,
                "product",
                product_entity["id"],
                update_data
            )

        self.log.debug("Prepared product: %s", product_name)
        return product_entity

    def prepare_version(
            self,
            instance: pyblish.api.Instance,
            op_session: OperationsSession,
            product_entity: dict) -> dict:
        """Prepare version for integration.

        Args:
            instance (pyblish.api.Instance): Instance to process.
            op_session (OperationsSession): Operations session.
            product_entity (dict): Product entity.

        Returns:
            dict: Version entity.

        """
        project_name = instance.context.data["projectName"]
        version_number = instance.data["version"]
        task_entity = instance.data.get("taskEntity")
        task_id = task_entity["id"] if task_entity else None
        existing_version = get_version_by_name(
            project_name,
            version_number,
            product_entity["id"]
        )
        version_id = existing_version["id"] if existing_version else None
        all_version_data = self.get_version_data_from_instance(instance)
        version_data = {}
        version_attributes = {}
        attr_defs = self.get_attributes_for_type(instance.context, "version")
        for key, value in all_version_data.items():
            if key in attr_defs:
                version_attributes[key] = value
            else:
                version_data[key] = value

        version_entity = new_version_entity(
            version_number,
            product_entity["id"],
            task_id=task_id,
            status=instance.data.get("status"),
            data=version_data,
            attribs=version_attributes,
            entity_id=version_id,
        )

        if existing_version:
            self.log.debug("Updating existing version ...")
            update_data = get_changed_attributes(
                existing_version, version_entity)
            op_session.update_entity(
                project_name,
                "version",
                version_entity["id"],
                update_data
            )
        else:
            self.log.debug("Creating new version ...")
            op_session.create_entity(
                project_name, "version", version_entity
            )

        self.log.debug(
            "Prepared version: v%s",
            "{:03d}".format(version_entity["version"])
        )

        return version_entity

    def get_version_data_from_instance(
            self, 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 = self.get_rootless_path(anatomy, source)
        self.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

    def get_rootless_path(self, 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:
            self.log.warning((
                'Could not find root path for remapping "%s".'
                " This may cause issues on farm."
            ), path)
        return path

    def get_attributes_for_type(
            self,
            context: pyblish.api.Context,
            entity_type: str) -> dict:
        """Get AYON attributes for the given entity type.

        Args:
            context (pyblish.api.Context): Context to get attributes from.
            entity_type (str): Entity type to get attributes for.

        Returns:
            dict: AYON attributes for the given entity type.

        """
        return self.get_attributes_by_type(context)[entity_type]

    @staticmethod
    def get_attributes_by_type(
            context: pyblish.api.Context) -> dict:
        """Gets AYON attributes from the given context.

        Args:
            context (pyblish.api.Context): Context to get attributes from.

        Returns:
            dict: AYON attributes.

        """
        attributes = context.data.get("ayonAttributes")
        if attributes is None:
            attributes = {
                key: get_attributes_for_type(key)
                for key in (
                    "project",
                    "folder",
                    "product",
                    "version",
                    "representation",
                )
            }
            context.data["ayonAttributes"] = attributes
        return attributes

    def get_template_data_from_representation(
            self,
            representation: Representation,
            instance: pyblish.api.Instance) -> dict:
        """Get template data from representation.

        Using representation traits and data on instance
        prepare data for formatting template.

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

        Returns:
            dict: Template data.

        """
        template_data = copy.deepcopy(instance.data["anatomyData"])
        template_data["representation"] = representation.name
        template_data["version"] = instance.data["version"]
        # template_data["hierarchy"] = instance.data["hierarchy"]

        # add colorspace data to template data
        if representation.contains_trait(ColorManaged):
            colorspace_data: ColorManaged = representation.get_trait(
                ColorManaged)

            template_data["colorspace"] = {
                "colorspace": colorspace_data.color_space,
                "config": colorspace_data.config
            }

            # add explicit list of traits properties to template data
            # there must be some better way to handle this
            try:
                # resolution from PixelBased trait
                template_data["resolution_width"] = representation.get_trait(
                    PixelBased).display_window_width
                template_data["resolution_height"] = representation.get_trait(
                    PixelBased).display_window_height
                # get fps from representation traits
                template_data["fps"] = representation.get_trait(
                    FrameRanged).frames_per_second

                # Note: handle "output" and "originalBasename"

            except MissingTraitError as e:
                self.log.debug("Missing traits: %s", e)

        return template_data

    @staticmethod
    def get_transfers_from_file_locations(
            representation: Representation,
            template_item: TemplateItem,
            transfers: list[TransferItem]) -> None:
        """Get transfers from FileLocations trait.

        Args:
            representation (Representation): Representation to process.
            template_item (TemplateItem): Template item.
            transfers (list): List of transfers.

        Mutates:
            transfers (list): List of transfers.
            template_item (TemplateItem): Template item.

        Raises:
            PublishError: If representation is invalid.

        """
        if representation.contains_trait(Sequence):
            IntegrateTraits.get_transfers_from_sequence(
                representation, template_item, transfers
            )

        elif representation.contains_trait(UDIM) and \
                not representation.contains_trait(Sequence):
            # handle UDIM not in sequence
            IntegrateTraits.get_transfers_from_udim(
                representation, template_item, transfers
            )

        else:
            # This should never happen because the representation
            # validation should catch this.
            msg = (
                "Representation contains FileLocations trait, but "
                "is not a Sequence or UDIM."
            )
            raise PublishError(msg)

    @staticmethod
    def get_transfers_from_sequence(
            representation: Representation,
            template_item: TemplateItem,
            transfers: list[TransferItem]
    ) -> None:
        """Get transfers from Sequence trait.

        Args:
            representation (Representation): Representation to process.
            template_item (TemplateItem): Template item.
            transfers (list): List of transfers.

        Mutates:
            transfers (list): List of transfers.
            template_item (TemplateItem): Template item.

        """
        sequence: Sequence = representation.get_trait(Sequence)
        path_template_object = template_item.template_object["path"]

        # get the padding from the sequence if the padding on the
        # template is higher, us the one from the template
        dst_padding = representation.get_trait(
            Sequence).frame_padding
        frames: list[int] = sequence.get_frame_list(
            representation.get_trait(FileLocations),
            regex=sequence.frame_regex)
        template_padding = template_item.anatomy.templates_obj.frame_padding
        dst_padding = max(template_padding, dst_padding)

        # Go through all frames in the sequence and
        # find their corresponding file locations, then
        # format their template and add them to transfers.
        for frame in frames:
            file_loc: FileLocation = representation.get_trait(
                FileLocations).get_file_location_for_frame(
                frame, sequence)

            template_item.template_data["frame"] = frame
            template_item.template_data["ext"] = (
                file_loc.file_path.suffix.lstrip("."))
            template_filled = path_template_object.format_strict(
                template_item.template_data
            )

            # add used values to the template data
            used_values: dict = template_filled.used_values
            template_item.template_data.update(used_values)

            transfers.append(
                TransferItem(
                    source=file_loc.file_path,
                    destination=Path(template_filled),
                    size=file_loc.file_size or TransferItem.get_size(
                        file_loc.file_path),
                    checksum=file_loc.file_hash or TransferItem.get_checksum(
                        file_loc.file_path),
                    template=template_item.template,
                    template_data=template_item.template_data,
                    representation=representation,
                    related_trait=file_loc
                )
            )

        # add template path and the data to resolve it
        if not representation.contains_trait(TemplatePath):
            representation.add_trait(TemplatePath(
                template=template_item.template,
                data=template_item.template_data
            ))

    @staticmethod
    def get_transfers_from_udim(
            representation: Representation,
            template_item: TemplateItem,
            transfers: list[TransferItem]
    ) -> None:
        """Get transfers from UDIM trait.

        Args:
            representation (Representation): Representation to process.
            template_item (TemplateItem): Template item.
            transfers (list): List of transfers.

        Mutates:
            transfers (list): List of transfers.
            template_item (TemplateItem): Template item.

        """
        udim: UDIM = representation.get_trait(UDIM)
        path_template_object: "AnatomyStringTemplate" = (
            template_item.template_object["path"]
        )
        for file_loc in representation.get_trait(
                FileLocations).file_paths:
            template_item.template_data["udim"] = (
                udim.get_udim_from_file_location(file_loc)
            )

            template_filled = path_template_object.format_strict(
                template_item.template_data
            )

            # add used values to the template data
            used_values: dict = template_filled.used_values
            template_item.template_data.update(used_values)

            transfers.append(
                TransferItem(
                    source=file_loc.file_path,
                    destination=Path(template_filled),
                    size=file_loc.file_size or TransferItem.get_size(
                        file_loc.file_path),
                    checksum=file_loc.file_hash or TransferItem.get_checksum(
                        file_loc.file_path),
                    template=template_item.template,
                    template_data=template_item.template_data,
                    representation=representation,
                    related_trait=file_loc
                )
            )
        # add template path and the data to resolve it
        representation.add_trait(TemplatePath(
            template=template_item.template,
            data=template_item.template_data
        ))

    @staticmethod
    def get_transfers_from_file_location(
            representation: Representation,
            template_item: TemplateItem,
            transfers: list[TransferItem]
    ) -> None:
        """Get transfers from FileLocation trait.

        Args:
            representation (Representation): Representation to process.
            template_item (TemplateItem): Template item.
            transfers (list): List of transfers.

        Mutates:
            transfers (list): List of transfers.
            template_item (TemplateItem): Template item.

        """
        path_template_object: "AnatomyStringTemplate" = (
            template_item.template_object["path"]
        )
        template_item.template_data["ext"] = (
            representation.get_trait(FileLocation).file_path.suffix.lstrip(".")
        )
        template_item.template_data.pop("frame", None)
        with contextlib.suppress(MissingTraitError):
            udim = representation.get_trait(UDIM)
            template_item.template_data["udim"] = udim.udim[0]

        template_filled = path_template_object.format_strict(
            template_item.template_data
        )

        # add used values to the template data
        used_values: dict = template_filled.used_values
        template_item.template_data.update(used_values)

        file_loc: FileLocation = representation.get_trait(FileLocation)
        transfers.append(
            TransferItem(
                source=file_loc.file_path,
                destination=Path(template_filled),
                size=file_loc.file_size or TransferItem.get_size(
                    file_loc.file_path),
                checksum=file_loc.file_hash or TransferItem.get_checksum(
                    file_loc.file_path),
                template=template_item.template,
                template_data=template_item.template_data,
                representation=representation,
                related_trait=file_loc
            )
        )
        # add template path and the data to resolve it
        representation.add_trait(TemplatePath(
            template=template_item.template,
            data=template_item.template_data
        ))

    @staticmethod
    def get_transfers_from_bundle(
            representation: Representation,
            template_item: TemplateItem,
            transfers: list[TransferItem]
    ) -> None:
        """Get transfers from Bundle trait.

        This will be called recursively for each sub-representation in the
        bundle that is a Bundle itself.

        Args:
            representation (Representation): Representation to process.
            template_item (TemplateItem): Template item.
            transfers (list): List of transfers.

        Mutates:
            transfers (list): List of transfers.
            template_item (TemplateItem): Template item.

        """
        bundle: Bundle = representation.get_trait(Bundle)
        for idx, sub_representation_traits in enumerate(bundle.items):
            sub_representation = Representation(
                name=f"{representation.name}_{idx}",
                traits=sub_representation_traits)
            # sub presentation transient:
            sub_representation.add_trait(Transient())
            if sub_representation.contains_trait(FileLocations):
                IntegrateTraits.get_transfers_from_file_locations(
                    sub_representation, template_item, transfers
                )
            elif sub_representation.contains_trait(FileLocation):
                IntegrateTraits.get_transfers_from_file_location(
                    sub_representation, template_item, transfers
                )
            elif sub_representation.contains_trait(Bundle):
                IntegrateTraits.get_transfers_from_bundle(
                    sub_representation, template_item, transfers
                )

    def _prepare_file_info(
            self, path: Path, anatomy: "Anatomy") -> dict[str, Any]:
        """Prepare information for one file (asset or resource).

        Arguments:
            path (Path): Destination url of published file.
            anatomy (Anatomy): Project anatomy part from instance.

        Raises:
            PublishError: If file does not exist.

        Returns:
            dict[str, Any]: Representation file info dictionary.

        """
        if not path.exists():
            msg = f"File '{path}' does not exist."
            raise PublishError(msg)

        return {
            "id": create_entity_id(),
            "name": path.name,
            "path": self.get_rootless_path(anatomy, path.as_posix()),
            "size": path.stat().st_size,
            "hash": source_hash(path.as_posix()),
            "hash_type": "op3",
        }

    def _get_legacy_files_for_representation(
            self,
            transfer_items: list[TransferItem],
            representation: Representation,
            anatomy: "Anatomy",
        ) -> list[dict[str, str]]:
        """Get legacy files for a given representation.

        This expects the file to exist - it must run after the transfer
        is done.

        Returns:
            list: List of legacy files.

        """
        selected: list[TransferItem] = []
        selected.extend(
            item
            for item in transfer_items
            if item.representation == representation
        )
        files: list[dict[str, str]] = []
        files.extend(
            self._prepare_file_info(item.destination, anatomy)
            for item in selected
        )
        return files

filter_lifecycle(representations) staticmethod

Filter representations based on LifeCycle traits.

Parameters:

Name Type Description Default
representations list

List of representations.

required

Returns:

Name Type Description
list list[Representation]

Filtered representations.

Source code in client/ayon_core/plugins/publish/integrate_traits.py
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
@staticmethod
def filter_lifecycle(
        representations: list[Representation]
) -> list[Representation]:
    """Filter representations based on LifeCycle traits.

    Args:
        representations (list): List of representations.

    Returns:
        list: Filtered representations.

    """
    return [
        representation
        for representation in representations
        if representation.contains_trait(Persistent)
    ]

get_attributes_by_type(context) staticmethod

Gets AYON attributes from the given context.

Parameters:

Name Type Description Default
context Context

Context to get attributes from.

required

Returns:

Name Type Description
dict dict

AYON attributes.

Source code in client/ayon_core/plugins/publish/integrate_traits.py
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
@staticmethod
def get_attributes_by_type(
        context: pyblish.api.Context) -> dict:
    """Gets AYON attributes from the given context.

    Args:
        context (pyblish.api.Context): Context to get attributes from.

    Returns:
        dict: AYON attributes.

    """
    attributes = context.data.get("ayonAttributes")
    if attributes is None:
        attributes = {
            key: get_attributes_for_type(key)
            for key in (
                "project",
                "folder",
                "product",
                "version",
                "representation",
            )
        }
        context.data["ayonAttributes"] = attributes
    return attributes

get_attributes_for_type(context, entity_type)

Get AYON attributes for the given entity type.

Parameters:

Name Type Description Default
context Context

Context to get attributes from.

required
entity_type str

Entity type to get attributes for.

required

Returns:

Name Type Description
dict dict

AYON attributes for the given entity type.

Source code in client/ayon_core/plugins/publish/integrate_traits.py
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
def get_attributes_for_type(
        self,
        context: pyblish.api.Context,
        entity_type: str) -> dict:
    """Get AYON attributes for the given entity type.

    Args:
        context (pyblish.api.Context): Context to get attributes from.
        entity_type (str): Entity type to get attributes for.

    Returns:
        dict: AYON attributes for the given entity type.

    """
    return self.get_attributes_by_type(context)[entity_type]

get_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/plugins/publish/integrate_traits.py
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
def get_publish_template(self, 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
    template_name = self.get_template_name(instance)
    anatomy = instance.context.data["anatomy"]
    publish_template = anatomy.get_template_item("publish", template_name)
    path_template_obj = publish_template["path"]
    return path_template_obj.template.replace("\\", "/")

get_publish_template_object(instance)

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

Returns:

Name Type Description
AnatomyTemplateItem 'AnatomyTemplateItem'

Anatomy template object

Source code in client/ayon_core/plugins/publish/integrate_traits.py
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
def get_publish_template_object(
        self, instance: pyblish.api.Instance) -> "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.

    Returns:
        AnatomyTemplateItem: Anatomy template object

    """
    # Anatomy data is pre-filled by Collectors
    template_name = self.get_template_name(instance)
    anatomy = instance.context.data["anatomy"]
    return anatomy.get_template_item("publish", 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/plugins/publish/integrate_traits.py
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
def get_rootless_path(self, 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:
        self.log.warning((
            'Could not find root path for remapping "%s".'
            " This may cause issues on farm."
        ), path)
    return path

get_template_data_from_representation(representation, instance)

Get template data from representation.

Using representation traits and data on instance prepare data for formatting template.

Parameters:

Name Type Description Default
representation Representation

Representation to process.

required
instance Instance

Instance to process.

required

Returns:

Name Type Description
dict dict

Template data.

Source code in client/ayon_core/plugins/publish/integrate_traits.py
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
def get_template_data_from_representation(
        self,
        representation: Representation,
        instance: pyblish.api.Instance) -> dict:
    """Get template data from representation.

    Using representation traits and data on instance
    prepare data for formatting template.

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

    Returns:
        dict: Template data.

    """
    template_data = copy.deepcopy(instance.data["anatomyData"])
    template_data["representation"] = representation.name
    template_data["version"] = instance.data["version"]
    # template_data["hierarchy"] = instance.data["hierarchy"]

    # add colorspace data to template data
    if representation.contains_trait(ColorManaged):
        colorspace_data: ColorManaged = representation.get_trait(
            ColorManaged)

        template_data["colorspace"] = {
            "colorspace": colorspace_data.color_space,
            "config": colorspace_data.config
        }

        # add explicit list of traits properties to template data
        # there must be some better way to handle this
        try:
            # resolution from PixelBased trait
            template_data["resolution_width"] = representation.get_trait(
                PixelBased).display_window_width
            template_data["resolution_height"] = representation.get_trait(
                PixelBased).display_window_height
            # get fps from representation traits
            template_data["fps"] = representation.get_trait(
                FrameRanged).frames_per_second

            # Note: handle "output" and "originalBasename"

        except MissingTraitError as e:
            self.log.debug("Missing traits: %s", e)

    return template_data

get_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/plugins/publish/integrate_traits.py
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
def get_template_name(self, 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"]
    task_info = anatomy_data.get("task") or {}

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

get_transfers_from_bundle(representation, template_item, transfers) staticmethod

Get transfers from Bundle trait.

This will be called recursively for each sub-representation in the bundle that is a Bundle itself.

Parameters:

Name Type Description Default
representation Representation

Representation to process.

required
template_item TemplateItem

Template item.

required
transfers list

List of transfers.

required
Mutates

transfers (list): List of transfers. template_item (TemplateItem): Template item.

Source code in client/ayon_core/plugins/publish/integrate_traits.py
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
@staticmethod
def get_transfers_from_bundle(
        representation: Representation,
        template_item: TemplateItem,
        transfers: list[TransferItem]
) -> None:
    """Get transfers from Bundle trait.

    This will be called recursively for each sub-representation in the
    bundle that is a Bundle itself.

    Args:
        representation (Representation): Representation to process.
        template_item (TemplateItem): Template item.
        transfers (list): List of transfers.

    Mutates:
        transfers (list): List of transfers.
        template_item (TemplateItem): Template item.

    """
    bundle: Bundle = representation.get_trait(Bundle)
    for idx, sub_representation_traits in enumerate(bundle.items):
        sub_representation = Representation(
            name=f"{representation.name}_{idx}",
            traits=sub_representation_traits)
        # sub presentation transient:
        sub_representation.add_trait(Transient())
        if sub_representation.contains_trait(FileLocations):
            IntegrateTraits.get_transfers_from_file_locations(
                sub_representation, template_item, transfers
            )
        elif sub_representation.contains_trait(FileLocation):
            IntegrateTraits.get_transfers_from_file_location(
                sub_representation, template_item, transfers
            )
        elif sub_representation.contains_trait(Bundle):
            IntegrateTraits.get_transfers_from_bundle(
                sub_representation, template_item, transfers
            )

get_transfers_from_file_location(representation, template_item, transfers) staticmethod

Get transfers from FileLocation trait.

Parameters:

Name Type Description Default
representation Representation

Representation to process.

required
template_item TemplateItem

Template item.

required
transfers list

List of transfers.

required
Mutates

transfers (list): List of transfers. template_item (TemplateItem): Template item.

Source code in client/ayon_core/plugins/publish/integrate_traits.py
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
@staticmethod
def get_transfers_from_file_location(
        representation: Representation,
        template_item: TemplateItem,
        transfers: list[TransferItem]
) -> None:
    """Get transfers from FileLocation trait.

    Args:
        representation (Representation): Representation to process.
        template_item (TemplateItem): Template item.
        transfers (list): List of transfers.

    Mutates:
        transfers (list): List of transfers.
        template_item (TemplateItem): Template item.

    """
    path_template_object: "AnatomyStringTemplate" = (
        template_item.template_object["path"]
    )
    template_item.template_data["ext"] = (
        representation.get_trait(FileLocation).file_path.suffix.lstrip(".")
    )
    template_item.template_data.pop("frame", None)
    with contextlib.suppress(MissingTraitError):
        udim = representation.get_trait(UDIM)
        template_item.template_data["udim"] = udim.udim[0]

    template_filled = path_template_object.format_strict(
        template_item.template_data
    )

    # add used values to the template data
    used_values: dict = template_filled.used_values
    template_item.template_data.update(used_values)

    file_loc: FileLocation = representation.get_trait(FileLocation)
    transfers.append(
        TransferItem(
            source=file_loc.file_path,
            destination=Path(template_filled),
            size=file_loc.file_size or TransferItem.get_size(
                file_loc.file_path),
            checksum=file_loc.file_hash or TransferItem.get_checksum(
                file_loc.file_path),
            template=template_item.template,
            template_data=template_item.template_data,
            representation=representation,
            related_trait=file_loc
        )
    )
    # add template path and the data to resolve it
    representation.add_trait(TemplatePath(
        template=template_item.template,
        data=template_item.template_data
    ))

get_transfers_from_file_locations(representation, template_item, transfers) staticmethod

Get transfers from FileLocations trait.

Parameters:

Name Type Description Default
representation Representation

Representation to process.

required
template_item TemplateItem

Template item.

required
transfers list

List of transfers.

required
Mutates

transfers (list): List of transfers. template_item (TemplateItem): Template item.

Raises:

Type Description
PublishError

If representation is invalid.

Source code in client/ayon_core/plugins/publish/integrate_traits.py
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
@staticmethod
def get_transfers_from_file_locations(
        representation: Representation,
        template_item: TemplateItem,
        transfers: list[TransferItem]) -> None:
    """Get transfers from FileLocations trait.

    Args:
        representation (Representation): Representation to process.
        template_item (TemplateItem): Template item.
        transfers (list): List of transfers.

    Mutates:
        transfers (list): List of transfers.
        template_item (TemplateItem): Template item.

    Raises:
        PublishError: If representation is invalid.

    """
    if representation.contains_trait(Sequence):
        IntegrateTraits.get_transfers_from_sequence(
            representation, template_item, transfers
        )

    elif representation.contains_trait(UDIM) and \
            not representation.contains_trait(Sequence):
        # handle UDIM not in sequence
        IntegrateTraits.get_transfers_from_udim(
            representation, template_item, transfers
        )

    else:
        # This should never happen because the representation
        # validation should catch this.
        msg = (
            "Representation contains FileLocations trait, but "
            "is not a Sequence or UDIM."
        )
        raise PublishError(msg)

get_transfers_from_representations(instance, representations)

Get transfers from representations.

This method will go through all representations and prepare transfers based on the traits they contain. First it will validate the representation, and then it will prepare template data for the representation. It specifically handles FileLocations, FileLocation, Bundle, Sequence and UDIM traits.

Parameters:

Name Type Description Default
instance Instance

Instance to process.

required
representations list[Representation]

List of representations.

required

Returns:

Type Description
list[TransferItem]

list[TransferItem]: List of transfers.

Raises:

Type Description
PublishError

If representation is invalid.

Source code in client/ayon_core/plugins/publish/integrate_traits.py
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
def get_transfers_from_representations(
        self,
        instance: pyblish.api.Instance,
        representations: list[Representation]) -> list[TransferItem]:
    """Get transfers from representations.

    This method will go through all representations and prepare transfers
    based on the traits they contain. First it will validate the
    representation, and then it will prepare template data for the
    representation. It specifically handles FileLocations, FileLocation,
    Bundle, Sequence and UDIM traits.

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

    Returns:
        list[TransferItem]: List of transfers.

    Raises:
        PublishError: If representation is invalid.

    """
    template: str = self.get_publish_template(instance)
    instance_template_data: dict[str, str] = {}
    transfers: list[TransferItem] = []
    # prepare template and data to format it
    for representation in representations:

        # validate representation first, this will go through all traits
        # and check if they are valid
        try:
            representation.validate()
        except TraitValidationError as e:
            msg = f"Representation '{representation.name}' is invalid: {e}"
            raise PublishError(msg) from e

        template_data = self.get_template_data_from_representation(
            representation, instance)
        # add instance based template data

        template_data.update(instance_template_data)

        # treat Variant as `output` in template data
        with contextlib.suppress(MissingTraitError):
            template_data["output"] = (
                representation.get_trait(Variant).variant
            )

        template_item = TemplateItem(
            anatomy=instance.context.data["anatomy"],
            template=template,
            template_data=copy.deepcopy(template_data),
            template_object=self.get_publish_template_object(instance),
        )

        if representation.contains_trait(FileLocations):
            # If representation has FileLocations trait (list of files)
            # it can be either Sequence or UDIM tile set.
            # We do not allow unrelated files in the single representation.
            # Note: we do not support yet frame sequence of multiple UDIM
            # tiles in the same representation
            self.get_transfers_from_file_locations(
                representation, template_item, transfers
            )
        elif representation.contains_trait(FileLocation):
            # This is just a single file representation
            self.get_transfers_from_file_location(
                representation, template_item, transfers
            )

        elif representation.contains_trait(Bundle):
            # Bundle groups multiple "sub-representations" together.
            # It has a list of lists with traits, some might be
            # FileLocations,but some might be "file-less" representations
            # or even other bundles.
            self.get_transfers_from_bundle(
                representation, template_item, transfers
            )
    return transfers

get_transfers_from_sequence(representation, template_item, transfers) staticmethod

Get transfers from Sequence trait.

Parameters:

Name Type Description Default
representation Representation

Representation to process.

required
template_item TemplateItem

Template item.

required
transfers list

List of transfers.

required
Mutates

transfers (list): List of transfers. template_item (TemplateItem): Template item.

Source code in client/ayon_core/plugins/publish/integrate_traits.py
 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
@staticmethod
def get_transfers_from_sequence(
        representation: Representation,
        template_item: TemplateItem,
        transfers: list[TransferItem]
) -> None:
    """Get transfers from Sequence trait.

    Args:
        representation (Representation): Representation to process.
        template_item (TemplateItem): Template item.
        transfers (list): List of transfers.

    Mutates:
        transfers (list): List of transfers.
        template_item (TemplateItem): Template item.

    """
    sequence: Sequence = representation.get_trait(Sequence)
    path_template_object = template_item.template_object["path"]

    # get the padding from the sequence if the padding on the
    # template is higher, us the one from the template
    dst_padding = representation.get_trait(
        Sequence).frame_padding
    frames: list[int] = sequence.get_frame_list(
        representation.get_trait(FileLocations),
        regex=sequence.frame_regex)
    template_padding = template_item.anatomy.templates_obj.frame_padding
    dst_padding = max(template_padding, dst_padding)

    # Go through all frames in the sequence and
    # find their corresponding file locations, then
    # format their template and add them to transfers.
    for frame in frames:
        file_loc: FileLocation = representation.get_trait(
            FileLocations).get_file_location_for_frame(
            frame, sequence)

        template_item.template_data["frame"] = frame
        template_item.template_data["ext"] = (
            file_loc.file_path.suffix.lstrip("."))
        template_filled = path_template_object.format_strict(
            template_item.template_data
        )

        # add used values to the template data
        used_values: dict = template_filled.used_values
        template_item.template_data.update(used_values)

        transfers.append(
            TransferItem(
                source=file_loc.file_path,
                destination=Path(template_filled),
                size=file_loc.file_size or TransferItem.get_size(
                    file_loc.file_path),
                checksum=file_loc.file_hash or TransferItem.get_checksum(
                    file_loc.file_path),
                template=template_item.template,
                template_data=template_item.template_data,
                representation=representation,
                related_trait=file_loc
            )
        )

    # add template path and the data to resolve it
    if not representation.contains_trait(TemplatePath):
        representation.add_trait(TemplatePath(
            template=template_item.template,
            data=template_item.template_data
        ))

get_transfers_from_udim(representation, template_item, transfers) staticmethod

Get transfers from UDIM trait.

Parameters:

Name Type Description Default
representation Representation

Representation to process.

required
template_item TemplateItem

Template item.

required
transfers list

List of transfers.

required
Mutates

transfers (list): List of transfers. template_item (TemplateItem): Template item.

Source code in client/ayon_core/plugins/publish/integrate_traits.py
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
@staticmethod
def get_transfers_from_udim(
        representation: Representation,
        template_item: TemplateItem,
        transfers: list[TransferItem]
) -> None:
    """Get transfers from UDIM trait.

    Args:
        representation (Representation): Representation to process.
        template_item (TemplateItem): Template item.
        transfers (list): List of transfers.

    Mutates:
        transfers (list): List of transfers.
        template_item (TemplateItem): Template item.

    """
    udim: UDIM = representation.get_trait(UDIM)
    path_template_object: "AnatomyStringTemplate" = (
        template_item.template_object["path"]
    )
    for file_loc in representation.get_trait(
            FileLocations).file_paths:
        template_item.template_data["udim"] = (
            udim.get_udim_from_file_location(file_loc)
        )

        template_filled = path_template_object.format_strict(
            template_item.template_data
        )

        # add used values to the template data
        used_values: dict = template_filled.used_values
        template_item.template_data.update(used_values)

        transfers.append(
            TransferItem(
                source=file_loc.file_path,
                destination=Path(template_filled),
                size=file_loc.file_size or TransferItem.get_size(
                    file_loc.file_path),
                checksum=file_loc.file_hash or TransferItem.get_checksum(
                    file_loc.file_path),
                template=template_item.template,
                template_data=template_item.template_data,
                representation=representation,
                related_trait=file_loc
            )
        )
    # add template path and the data to resolve it
    representation.add_trait(TemplatePath(
        template=template_item.template,
        data=template_item.template_data
    ))

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/plugins/publish/integrate_traits.py
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
def get_version_data_from_instance(
        self, 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 = self.get_rootless_path(anatomy, source)
    self.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

prepare_product(instance, op_session)

Prepare product for integration.

Parameters:

Name Type Description Default
instance Instance

Instance to process.

required
op_session OperationsSession

Operations session.

required

Returns:

Name Type Description
dict dict

Product entity.

Source code in client/ayon_core/plugins/publish/integrate_traits.py
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
def prepare_product(
        self,
        instance: pyblish.api.Instance,
        op_session: OperationsSession) -> dict:
    """Prepare product for integration.

    Args:
        instance (pyblish.api.Instance): Instance to process.
        op_session (OperationsSession): Operations session.

    Returns:
        dict: Product entity.

    """
    project_name = instance.context.data["projectName"]
    folder_entity = instance.data["folderEntity"]
    product_name = instance.data["productName"]
    product_type = instance.data["productType"]
    self.log.debug("Product: %s", product_name)

    # Get existing product if it exists
    existing_product_entity = get_product_by_name(
        project_name, product_name, folder_entity["id"]
    )

    # Define product data
    data = {
        "families": get_instance_families(instance)
    }
    attributes = {}

    product_group = instance.data.get("productGroup")
    if product_group:
        attributes["productGroup"] = product_group
    elif existing_product_entity:
        # Preserve previous product group if new version does not set it
        product_group = existing_product_entity.get("attrib", {}).get(
            "productGroup"
        )
        if product_group is not None:
            attributes["productGroup"] = product_group

    product_id = existing_product_entity["id"] if existing_product_entity else None  # noqa: E501
    product_entity = new_product_entity(
        product_name,
        product_type,
        folder_entity["id"],
        data=data,
        attribs=attributes,
        entity_id=product_id
    )

    if existing_product_entity is None:
        # Create a new product
        self.log.info(
            "Product '%s' not found, creating ...",
            product_name
        )
        op_session.create_entity(
            project_name, "product", product_entity
        )

    else:
        # Update existing product data with new data and set in database.
        # We also change the found product in-place so we don't need to
        # re-query the product afterward
        update_data = get_changed_attributes(
            existing_product_entity, product_entity
        )
        op_session.update_entity(
            project_name,
            "product",
            product_entity["id"],
            update_data
        )

    self.log.debug("Prepared product: %s", product_name)
    return product_entity

prepare_version(instance, op_session, product_entity)

Prepare version for integration.

Parameters:

Name Type Description Default
instance Instance

Instance to process.

required
op_session OperationsSession

Operations session.

required
product_entity dict

Product entity.

required

Returns:

Name Type Description
dict dict

Version entity.

Source code in client/ayon_core/plugins/publish/integrate_traits.py
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
def prepare_version(
        self,
        instance: pyblish.api.Instance,
        op_session: OperationsSession,
        product_entity: dict) -> dict:
    """Prepare version for integration.

    Args:
        instance (pyblish.api.Instance): Instance to process.
        op_session (OperationsSession): Operations session.
        product_entity (dict): Product entity.

    Returns:
        dict: Version entity.

    """
    project_name = instance.context.data["projectName"]
    version_number = instance.data["version"]
    task_entity = instance.data.get("taskEntity")
    task_id = task_entity["id"] if task_entity else None
    existing_version = get_version_by_name(
        project_name,
        version_number,
        product_entity["id"]
    )
    version_id = existing_version["id"] if existing_version else None
    all_version_data = self.get_version_data_from_instance(instance)
    version_data = {}
    version_attributes = {}
    attr_defs = self.get_attributes_for_type(instance.context, "version")
    for key, value in all_version_data.items():
        if key in attr_defs:
            version_attributes[key] = value
        else:
            version_data[key] = value

    version_entity = new_version_entity(
        version_number,
        product_entity["id"],
        task_id=task_id,
        status=instance.data.get("status"),
        data=version_data,
        attribs=version_attributes,
        entity_id=version_id,
    )

    if existing_version:
        self.log.debug("Updating existing version ...")
        update_data = get_changed_attributes(
            existing_version, version_entity)
        op_session.update_entity(
            project_name,
            "version",
            version_entity["id"],
            update_data
        )
    else:
        self.log.debug("Creating new version ...")
        op_session.create_entity(
            project_name, "version", version_entity
        )

    self.log.debug(
        "Prepared version: v%s",
        "{:03d}".format(version_entity["version"])
    )

    return version_entity

process(instance)

Integrate representations with traits.

Todo

Refactor this method to be more readable and maintainable.

Parameters:

Name Type Description Default
instance Instance

Instance to process.

required
Source code in client/ayon_core/plugins/publish/integrate_traits.py
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
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
def process(self, instance: pyblish.api.Instance) -> None:
    """Integrate representations with traits.

    Todo:
        Refactor this method to be more readable and maintainable.

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

    """
    # 1) skip farm and integrate ==  False

    if instance.data.get("integrate", True) is False:
        self.log.debug("Instance is marked to skip integrating. Skipping")
        return

    if instance.data.get("farm"):
        self.log.debug(
            "Instance is marked to be processed on farm. Skipping")
        return

    # TODO (antirotor): Find better name for the key
    if not has_trait_representations(instance):
        self.log.debug(
            "Instance has no representations with traits. Skipping")
        return

    # 2) filter representations based on LifeCycle traits
    set_trait_representations(
        instance,
        self.filter_lifecycle(get_trait_representations(instance))
    )

    representations: list[Representation] = get_trait_representations(
        instance
    )
    if not representations:
        self.log.debug(
            "Instance has no persistent representations. Skipping")
        return

    op_session = OperationsSession()

    product_entity = self.prepare_product(instance, op_session)

    version_entity = self.prepare_version(
        instance, op_session, product_entity
    )
    instance.data["versionEntity"] = version_entity

    transfers = self.get_transfers_from_representations(
        instance, representations)

    # 8) Transfer files
    file_transactions = FileTransaction(
        log=self.log,
        # Enforce unique transfers
        allow_queue_replacements=False)
    for transfer in transfers:
        self.log.debug(
            "Transferring file: %s -> %s",
            transfer.source,
            transfer.destination
        )
        file_transactions.add(
            transfer.source.as_posix(),
            transfer.destination.as_posix(),
            mode=FileTransaction.MODE_COPY,
        )
    file_transactions.process()
    self.log.debug(
        "Transferred files %s", [file_transactions.transferred])

    # replace original paths with the destination in traits.
    for transfer in transfers:
        transfer.related_trait.file_path = transfer.destination

    # 9) Create representation entities
    for representation in representations:
        representation_entity = new_representation_entity(
            representation.name,
            version_entity["id"],
            files=self._get_legacy_files_for_representation(
                transfers,
                representation,
                anatomy=instance.context.data["anatomy"]),
            attribs={},
            data="",
            tags=[],
            status="",
        )
        # add traits to representation entity
        representation_entity["traits"] = representation.traits_as_dict()
        op_session.create_entity(
            project_name=instance.context.data["projectName"],
            entity_type="representation",
            data=prepare_for_json(representation_entity),
        )

    # 10) Commit the session to AYON
    self.log.debug("{}".format(op_session.to_data()))
    op_session.commit()

RepresentationEntity

Representation entity data.

Source code in client/ayon_core/plugins/publish/integrate_traits.py
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
class RepresentationEntity:
    """Representation entity data."""
    id: str
    versionId: str  # noqa: N815
    name: str
    files: dict[str, Any]
    attrib: dict[str, Any]
    data: str
    tags: list[str]
    status: str

    def __init__(self,
        id: str,
        versionId: str,  # noqa: N815
        name: str,
        files: dict[str, Any],
        attrib: dict[str, Any],
        data: str,
        tags: list[str],
        status: str):
        """Initialize RepresentationEntity.

        Args:
            id (str): Entity ID.
            versionId (str): Version ID.
            name (str): Representation name.
            files (dict[str, Any]): Files in the representation.
            attrib (dict[str, Any]): Attributes of the representation.
            data (str): Data of the representation.
            tags (list[str]): Tags of the representation.
            status (str): Status of the representation.

        """
        self.id = id
        self.versionId = versionId
        self.name = name
        self.files = files
        self.attrib = attrib
        self.data = data
        self.tags = tags
        self.status = status

__init__(id, versionId, name, files, attrib, data, tags, status)

Initialize RepresentationEntity.

Parameters:

Name Type Description Default
id str

Entity ID.

required
versionId str

Version ID.

required
name str

Representation name.

required
files dict[str, Any]

Files in the representation.

required
attrib dict[str, Any]

Attributes of the representation.

required
data str

Data of the representation.

required
tags list[str]

Tags of the representation.

required
status str

Status of the representation.

required
Source code in client/ayon_core/plugins/publish/integrate_traits.py
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
def __init__(self,
    id: str,
    versionId: str,  # noqa: N815
    name: str,
    files: dict[str, Any],
    attrib: dict[str, Any],
    data: str,
    tags: list[str],
    status: str):
    """Initialize RepresentationEntity.

    Args:
        id (str): Entity ID.
        versionId (str): Version ID.
        name (str): Representation name.
        files (dict[str, Any]): Files in the representation.
        attrib (dict[str, Any]): Attributes of the representation.
        data (str): Data of the representation.
        tags (list[str]): Tags of the representation.
        status (str): Status of the representation.

    """
    self.id = id
    self.versionId = versionId
    self.name = name
    self.files = files
    self.attrib = attrib
    self.data = data
    self.tags = tags
    self.status = status

TemplateItem

Represents single template item.

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

Attributes:

Name Type Description
anatomy Anatomy

Anatomy object.

template str

Template path.

template_data dict[str, Any]

Template data.

template_object TemplateItem

Template object

Source code in client/ayon_core/plugins/publish/integrate_traits.py
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
class TemplateItem:
    """Represents single template item.

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

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

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

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

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

__init__(anatomy, template, template_data, template_object)

Initialize TemplateItem.

Parameters:

Name Type Description Default
anatomy Anatomy

Anatomy object.

required
template str

Template path.

required
template_data dict[str, Any]

Template data.

required
template_object TemplateItem

Template object.

required
Source code in client/ayon_core/plugins/publish/integrate_traits.py
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
def __init__(self,
    anatomy: "Anatomy",
    template: str,
    template_data: dict[str, Any],
    template_object: "AnatomyTemplateItem"):
    """Initialize TemplateItem.

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

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

TransferItem

Represents a single transfer item.

Source file path, destination file path, template that was used to construct the destination path, template data that was used in the template, size of the file, checksum of the file.

Attributes:

Name Type Description
source Path

Source file path.

destination Path

Destination file path.

size int

Size of the file.

checksum str

Checksum of the file.

template str

Template path.

template_data dict[str, Any]

Template data.

representation Representation

Reference to representation

Source code in client/ayon_core/plugins/publish/integrate_traits.py
 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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
class TransferItem:
    """Represents a single transfer item.

    Source file path, destination file path, template that was used to
    construct the destination path, template data that was used in the
    template, size of the file, checksum of the file.

    Attributes:
        source (Path): Source file path.
        destination (Path): Destination file path.
        size (int): Size of the file.
        checksum (str): Checksum of the file.
        template (str): Template path.
        template_data (dict[str, Any]): Template data.
        representation (Representation): Reference to representation

    """
    source: Path
    destination: Path
    size: int
    checksum: str
    template: str
    template_data: dict[str, Any]
    representation: Representation
    related_trait: FileLocation

    def __init__(self,
        source: Path,
        destination: Path,
        size: int,
        checksum: str,
        template: str,
        template_data: dict[str, Any],
        representation: Representation,
        related_trait: FileLocation):

        self.source = source
        self.destination = destination
        self.size = size
        self.checksum = checksum
        self.template = template
        self.template_data = template_data
        self.representation = representation
        self.related_trait = related_trait

    @staticmethod
    def get_size(file_path: Path) -> int:
        """Get the size of the file.

        Args:
            file_path (Path): File path.

        Returns:
            int: Size of the file.

        """
        return file_path.stat().st_size

    @staticmethod
    def get_checksum(file_path: Path) -> str:
        """Get checksum of the file.

        Args:
            file_path (Path): File path.

        Returns:
            str: Checksum of the file.

        """
        return hashlib.sha256(
            file_path.read_bytes()
        ).hexdigest()

get_checksum(file_path) staticmethod

Get checksum of the file.

Parameters:

Name Type Description Default
file_path Path

File path.

required

Returns:

Name Type Description
str str

Checksum of the file.

Source code in client/ayon_core/plugins/publish/integrate_traits.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
@staticmethod
def get_checksum(file_path: Path) -> str:
    """Get checksum of the file.

    Args:
        file_path (Path): File path.

    Returns:
        str: Checksum of the file.

    """
    return hashlib.sha256(
        file_path.read_bytes()
    ).hexdigest()

get_size(file_path) staticmethod

Get the size of the file.

Parameters:

Name Type Description Default
file_path Path

File path.

required

Returns:

Name Type Description
int int

Size of the file.

Source code in client/ayon_core/plugins/publish/integrate_traits.py
110
111
112
113
114
115
116
117
118
119
120
121
@staticmethod
def get_size(file_path: Path) -> int:
    """Get the size of the file.

    Args:
        file_path (Path): File path.

    Returns:
        int: Size of the file.

    """
    return file_path.stat().st_size

get_changed_attributes(old_entity, new_entity)

Prepare changes for entity update.

Todo

Move to the library.

Parameters:

Name Type Description Default
old_entity dict[str, Any]

Existing entity.

required
new_entity dict[str, Any]

New entity.

required

Returns:

Type Description
dict[str, Any]

dict[str, Any]: Changes that have new entity.

Source code in client/ayon_core/plugins/publish/integrate_traits.py
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
def get_changed_attributes(
        old_entity: dict, new_entity: dict) -> dict[str, Any]:
    """Prepare changes for entity update.

    Todo:
        Move to the library.

    Args:
        old_entity (dict[str, Any]): Existing entity.
        new_entity (dict[str, Any]): New entity.

    Returns:
        dict[str, Any]: Changes that have new entity.

    """
    changes = {}
    for key in set(new_entity.keys()):
        if key == "attrib":
            continue

        if key in new_entity and new_entity[key] != old_entity.get(key):
            changes[key] = new_entity[key]
            continue

    attrib_changes = {}
    if "attrib" in new_entity:
        attrib_changes = {
            key: value
            for key, value in new_entity["attrib"].items()
            if value != old_entity["attrib"].get(key)
        }
    if attrib_changes:
        changes["attrib"] = attrib_changes
    return changes

get_instance_families(instance)

Get all families of the instance.

Todo

Move to the library.

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/plugins/publish/integrate_traits.py
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
def get_instance_families(instance: pyblish.api.Instance) -> list[str]:
    """Get all families of the instance.

    Todo:
        Move to the library.

    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

prepare_for_json(data)

Prepare data for JSON serialization.

If there are values that json cannot serialize, this function will convert them to strings.

Parameters:

Name Type Description Default
data dict[str, Any]

Data to prepare.

required

Returns:

Type Description
dict[str, Any]

dict[str, Any]: Prepared data.

Raises:

Type Description
TypeError

If the data cannot be converted to JSON.

Source code in client/ayon_core/plugins/publish/integrate_traits.py
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
def prepare_for_json(data: dict[str, Any]) -> dict[str, Any]:
    """Prepare data for JSON serialization.

    If there are values that json cannot serialize, this function will
    convert them to strings.

    Args:
        data (dict[str, Any]): Data to prepare.

    Returns:
        dict[str, Any]: Prepared data.

    Raises:
        TypeError: If the data cannot be converted to JSON.

    """
    prepared = {}
    for key, value in data.items():
        if isinstance(value, dict):
            value = prepare_for_json(value)
        try:
            json.dumps(value)
        except TypeError:
            value = value.as_posix() if issubclass(
                value.__class__, Path) else str(value)
        prepared[key] = value
    return prepared