Skip to content

utils

ShimDeploymentError

Bases: Exception

Error related to deploying shim executable.

Source code in common/ayon_common/utils.py
39
40
class ShimDeploymentError(Exception):
    """Error related to deploying shim executable."""

ZipFileLongPaths

Bases: ZipFile

Allows longer paths in zip files.

Regular DOS paths are limited to MAX_PATH (260) characters, including the string's terminating NUL character. That limit can be exceeded by using an extended-length path that starts with the '\?' prefix.

Source code in common/ayon_common/utils.py
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
class ZipFileLongPaths(zipfile.ZipFile):
    """Allows longer paths in zip files.

    Regular DOS paths are limited to MAX_PATH (260) characters, including
    the string's terminating NUL character.
    That limit can be exceeded by using an extended-length path that
    starts with the '\\?\' prefix.
    """
    _is_windows = platform.system().lower() == "windows"

    def _extract_member(self, member, tpath, pwd):
        if self._is_windows:
            tpath = os.path.abspath(tpath)
            if tpath.startswith("\\\\"):
                tpath = "\\\\?\\UNC\\" + tpath[2:]
            else:
                tpath = "\\\\?\\" + tpath

        return super()._extract_member(member, tpath, pwd)

calculate_file_checksum(filepath, checksum_algorithm, chunk_size=10000)

Calculate file checksum for given algorithm.

Parameters:

Name Type Description Default
filepath str

Path to a file.

required
checksum_algorithm str

Algorithm to use. ('md5', 'sha1', 'sha256')

required
chunk_size Optional[int]

Chunk size to read file. Defaults to 10000.

10000

Returns:

Name Type Description
str

Calculated checksum.

Raises:

Type Description
ValueError

File not found or unknown checksum algorithm.

Source code in common/ayon_common/utils.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
def calculate_file_checksum(
    filepath: str, checksum_algorithm: str, chunk_size: Optional[int]=10000
):
    """Calculate file checksum for given algorithm.

    Args:
        filepath (str): Path to a file.
        checksum_algorithm (str): Algorithm to use. ('md5', 'sha1', 'sha256')
        chunk_size (Optional[int]): Chunk size to read file.
            Defaults to 10000.

    Returns:
        str: Calculated checksum.

    Raises:
        ValueError: File not found or unknown checksum algorithm.

    """
    import hashlib

    if not filepath:
        raise ValueError("Filepath is empty.")

    if not os.path.exists(filepath):
        raise ValueError("{} doesn't exist.".format(filepath))

    if not os.path.isfile(filepath):
        raise ValueError("{} is not a file.".format(filepath))

    func = getattr(hashlib, checksum_algorithm, None)
    if func is None:
        raise ValueError(
            "Unknown checksum algorithm '{}'".format(checksum_algorithm))

    hash_obj = func()
    with open(filepath, "rb") as f:
        for chunk in iter(lambda: f.read(chunk_size), b""):
            hash_obj.update(chunk)
    return hash_obj.hexdigest()

cleanup_executables_info()

Remove executables that do not exist anymore.

Source code in common/ayon_common/utils.py
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
def cleanup_executables_info():
    """Remove executables that do not exist anymore."""

    info = get_executables_info(check_cleanup=False)
    available_versions = info.setdefault("available_versions", [])

    new_executables = []
    for item in available_versions:
        executable = item.get("executable")
        if not executable or not os.path.exists(executable):
            continue

        version = load_executable_version(executable)
        if version and item.get("version") != version:
            item["version"] = version
        new_executables.append(item)

    info["available_versions"] = new_executables
    info["last_cleanup"] = {
        "value": datetime.datetime.now().strftime(DATE_FMT),
        "fmt": DATE_FMT,
    }
    store_executables_info(info)

deploy_ayon_launcher_shims(ensure_protocol_is_registered=False, create_desktop_icons=False)

Deploy shim executables for AYON launcher.

Argument 'validate_registers' is to fix registered protocol on Windows, issue caused in v1.1.0, since 1.1.1 is used different registry path.

Parameters:

Name Type Description Default
ensure_protocol_is_registered bool

Validate if protocol is registered on windows.

False
create_desktop_icons bool

Create desktop shortcuts. Used only on windows.

False
Source code in common/ayon_common/utils.py
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
def deploy_ayon_launcher_shims(
    ensure_protocol_is_registered: bool = False,
    create_desktop_icons: bool = False,
):
    """Deploy shim executables for AYON launcher.

    Argument 'validate_registers' is to fix registered protocol on Windows,
        issue caused in v1.1.0, since 1.1.1 is used different registry path.

    Args:
        ensure_protocol_is_registered (bool): Validate if protocol is
            registered on windows.
        create_desktop_icons (bool): Create desktop shortcuts. Used
            only on windows.

    """
    if not IS_BUILT_APPLICATION:
        return

    # Validate platform name
    platform_name = platform.system().lower()
    if platform_name not in ("windows", "linux", "darwin"):
        raise ValueError("Unsupported platform {}".format(platform_name))

    _cleanup_shims()

    executable_root = os.path.dirname(sys.executable)
    installer_shim_root = os.path.join(executable_root, "shim")

    with open(os.path.join(installer_shim_root, "shim.json"), "r") as stream:
        shim_data = json.load(stream)

    src_shim_version = semver.VersionInfo.parse(shim_data["version"])

    # Read existing shim version (if there is any)
    dst_shim_version = _get_installed_shim_version()

    # Skip if shim is same or lower
    if src_shim_version <= semver.VersionInfo.parse(dst_shim_version):
        # Make sure windows registers are correctly set for each user
        if ensure_protocol_is_registered:
            register_ayon_launcher_protocol()
        if platform_name == "windows" and create_desktop_icons:
            _create_windows_shortcut()
        return

    platform_name = platform.system().lower()
    if platform_name == "windows":
        _deploy_shim_windows(
            installer_shim_root,
            create_desktop_icons,
        )

    elif platform_name == "linux":
        _deploy_shim_linux(installer_shim_root)

    elif platform_name == "darwin":
        _deploy_shim_macos(installer_shim_root)
    register_ayon_launcher_protocol()

extract_archive_file(archive_file, dst_folder=None)

Extract archived file to a directory.

Parameters:

Name Type Description Default
archive_file str

Path to a archive file.

required
dst_folder Optional[str]

Directory where content will be extracted. By default, same folder where archive file is.

None
Source code in common/ayon_common/utils.py
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
def extract_archive_file(archive_file: str, dst_folder: Optional[str] = None):
    """Extract archived file to a directory.

    Args:
        archive_file (str): Path to a archive file.
        dst_folder (Optional[str]): Directory where content will be extracted.
            By default, same folder where archive file is.

    """
    if not dst_folder:
        dst_folder = os.path.dirname(archive_file)

    archive_ext, archive_type = get_archive_ext_and_type(archive_file)

    print("Extracting {} -> {}".format(archive_file, dst_folder))
    if archive_type is None:
        _, ext = os.path.splitext(archive_file)
        raise ValueError((
            f"Invalid file extension \"{ext}\"."
            f" Expected {', '.join(IMPLEMENTED_ARCHIVE_FORMATS)}"
        ))

    if archive_type == "zip":
        zip_file = ZipFileLongPaths(archive_file)
        try:
            zip_file.extractall(dst_folder)
        finally:
            zip_file.close()

    elif archive_type == "tar":
        if archive_ext == ".tar":
            tar_type = "r:"
        elif archive_ext.endswith(".xz"):
            tar_type = "r:xz"
        elif archive_ext.endswith(".gz"):
            tar_type = "r:gz"
        elif archive_ext.endswith(".bz2"):
            tar_type = "r:bz2"
        else:
            tar_type = "r:*"

        try:
            tar_file = tarfile.open(archive_file, tar_type)
        except tarfile.ReadError:
            raise SystemExit("corrupted archive")

        try:
            tar_file.extractall(dst_folder)
        finally:
            tar_file.close()

get_archive_ext_and_type(archive_file)

Get archive extension and type.

Parameters:

Name Type Description Default
archive_file str

Path to archive file.

required

Returns:

Type Description
Tuple[Optional[str], Optional[str]]

Tuple[str, str]: Archive extension and type.

Source code in common/ayon_common/utils.py
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
def get_archive_ext_and_type(
    archive_file: str
) -> Tuple[Optional[str], Optional[str]]:
    """Get archive extension and type.

    Args:
        archive_file (str): Path to archive file.

    Returns:
        Tuple[str, str]: Archive extension and type.

    """
    tmp_name = archive_file.lower()
    if tmp_name.endswith(".zip"):
        return ".zip", "zip"

    for ext in (
        ".tar",
        ".tgz",
        ".tar.gz",
        ".tar.xz",
        ".tar.bz2",
    ):
        if tmp_name.endswith(ext):
            return ext, "tar"

    return None, None

get_ayon_appdirs(*args)

Local app data directory of AYON launcher.

Deprecated

The function was replaced with 'get_launcher_local_dir' or 'get_launcher_storage_dir' based on usage. Deprecated since 1.1.0 .

Parameters:

Name Type Description Default
*args Iterable[str]

Subdirectories/files in local app data dir.

()

Returns:

Name Type Description
str

Path to directory/file in local app data dir.

Source code in common/ayon_common/utils.py
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def get_ayon_appdirs(*args):
    """Local app data directory of AYON launcher.

    Deprecated:
        The function was replaced with 'get_launcher_local_dir'
            or 'get_launcher_storage_dir' based on usage.
        Deprecated since 1.1.0 .

    Args:
        *args (Iterable[str]): Subdirectories/files in local app data dir.

    Returns:
        str: Path to directory/file in local app data dir.

    """
    warnings.warn(
        (
            "Function 'get_ayon_appdirs' is deprecated. Should be replaced"
            " with 'get_launcher_local_dir' or 'get_launcher_storage_dir'"
            " based on use-case."
        ),
        DeprecationWarning
    )
    return _get_ayon_appdirs(*args)

get_ayon_launch_args(*args)

Launch arguments that can be used to launch ayon process.

Parameters:

Name Type Description Default
*args str

Additional arguments.

()

Returns:

Type Description
List[str]

list[str]: Launch arguments.

Source code in common/ayon_common/utils.py
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
def get_ayon_launch_args(*args: str) -> List[str]:
    """Launch arguments that can be used to launch ayon process.

    Args:
        *args (str): Additional arguments.

    Returns:
        list[str]: Launch arguments.

    """
    output = [sys.executable]
    if not IS_BUILT_APPLICATION:
        output.append(os.path.join(os.environ["AYON_ROOT"], "start.py"))
    output.extend(args)
    return output

get_downloads_dir()

Downloads directory path.

Each platform may use different approach how the downloads directory is received. This function will try to find the directory and return it.

Returns:

Type Description
str

Union[str, None]: Path to downloads directory or None if not found.

Source code in common/ayon_common/utils.py
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
def get_downloads_dir() -> str:
    """Downloads directory path.

    Each platform may use different approach how the downloads directory is
    received. This function will try to find the directory and return it.

    Returns:
        Union[str, None]: Path to downloads directory or None if not found.

    """
    if _Cache.downloads_dir != 0:
        return _Cache.downloads_dir

    path = None
    try:
        platform_name = platform.system().lower()
        if platform_name == "linux":
            path = _get_linux_downloads_dir()
        elif platform_name == "windows":
            path = _get_windows_downloads_dir()
        elif platform_name == "darwin":
            path = _get_macos_downloads_dir()

    except Exception:
        pass

    if path is None:
        default = os.path.expanduser("~/Downloads")
        if os.path.exists(default):
            path = default

    _Cache.downloads_dir = path
    return path

get_executable_paths_by_version(version)

Get executable paths by version.

Returns:

Type Description
List[str]

list[str]: Paths to executables.

Source code in common/ayon_common/utils.py
466
467
468
469
470
471
472
473
474
475
476
def get_executable_paths_by_version(version: str) -> List[str]:
    """Get executable paths by version.

    Returns:
        list[str]: Paths to executables.

    """
    return [
        item["executable"]
        for item in get_executables_info_by_version(version, validate=True)
    ]

get_executables_info_by_version(version, validate=True)

Get available executable info by version.

Parameters:

Name Type Description Default
version str

Version of executable.

required
validate bool

Validate if 'version.py' contains same version.

True

Returns:

Type Description
List[Dict[str, Any]]

list[dict[str, Any]]: Executable info matching version.

Source code in common/ayon_common/utils.py
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
def get_executables_info_by_version(
    version: str, validate: Optional[bool] = True
) -> List[Dict[str, Any]]:
    """Get available executable info by version.

    Args:
        version (str): Version of executable.
        validate (bool): Validate if 'version.py' contains same version.

    Returns:
        list[dict[str, Any]]: Executable info matching version.

    """
    info = get_executables_info()
    available_versions = info.setdefault("available_versions", [])
    if validate:
        _available_versions = []
        for item in available_versions:
            executable = item.get("executable")
            if not executable or not os.path.exists(executable):
                continue

            executable_version = load_executable_version(executable)
            if executable_version == version:
                _available_versions.append(item)
        available_versions = _available_versions
    return [
        item
        for item in available_versions
        if item.get("version") == version
    ]

get_executables_info_filepath()

Get path to file where information about executables is stored.

Returns:

Name Type Description
str str

Path to json file where executables info are stored.

Source code in common/ayon_common/utils.py
233
234
235
236
237
238
239
240
def get_executables_info_filepath() -> str:
    """Get path to file where information about executables is stored.

    Returns:
        str: Path to json file where executables info are stored.

    """
    return get_launcher_local_dir("executables.json")

get_launcher_local_dir(*subdirs, create=False)

Get local directory for launcher.

Local directory is used for storing machine or user specific data.

The location is user specific.

Note

This function should be called at least once on bootstrap.

Parameters:

Name Type Description Default
*subdirs str

Subdirectories relative to local dir.

()
create Optional[bool]

Create the folder if it does not exist.

False

Returns:

Name Type Description
str str

Path to local directory.

Source code in common/ayon_common/utils.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
def get_launcher_local_dir(
    *subdirs: str,
    create: Optional[bool] = False
) -> str:
    """Get local directory for launcher.

    Local directory is used for storing machine or user specific data.

    The location is user specific.

    Note:
        This function should be called at least once on bootstrap.

    Args:
        *subdirs (str): Subdirectories relative to local dir.
        create (Optional[bool]): Create the folder if it does not exist.

    Returns:
        str: Path to local directory.

    """
    storage_dir = os.getenv("AYON_LAUNCHER_LOCAL_DIR")
    if not storage_dir:
        storage_dir = _get_ayon_appdirs()
        os.environ["AYON_LAUNCHER_LOCAL_DIR"] = storage_dir

    path = os.path.join(storage_dir, *subdirs)
    if create:
        os.makedirs(path, exist_ok=True)
    return path

get_launcher_storage_dir(*subdirs, create=False)

Get storage directory for launcher.

Storage directory is used for storing shims, addons, dependencies, etc.

It is not recommended, but the location can be shared across multiple machines.

Note

This function should be called at least once on bootstrap.

Parameters:

Name Type Description Default
*subdirs str

Subdirectories relative to storage dir.

()
create Optional[bool]

Create the folder if it does not exist.

False

Returns:

Name Type Description
str str

Path to storage directory.

Source code in common/ayon_common/utils.py
 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
def get_launcher_storage_dir(
    *subdirs: str,
    create: Optional[bool] = False
) -> str:
    """Get storage directory for launcher.

    Storage directory is used for storing shims, addons, dependencies, etc.

    It is not recommended, but the location can be shared across
        multiple machines.

    Note:
        This function should be called at least once on bootstrap.

    Args:
        *subdirs (str): Subdirectories relative to storage dir.
        create (Optional[bool]): Create the folder if it does not exist.

    Returns:
        str: Path to storage directory.

    """
    storage_dir = os.getenv("AYON_LAUNCHER_STORAGE_DIR")
    if not storage_dir:
        storage_dir = _get_ayon_appdirs()
        os.environ["AYON_LAUNCHER_STORAGE_DIR"] = storage_dir

    path = os.path.join(storage_dir, *subdirs)
    if create and not os.path.exists(path):
        os.makedirs(path, exist_ok=True)
    return path

get_local_site_id()

Get local site identifier.

Site id is created if does not exist yet.

Returns:

Name Type Description
str str

Site id.

Source code in common/ayon_common/utils.py
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
def get_local_site_id() -> str:
    """Get local site identifier.

    Site id is created if does not exist yet.

    Returns:
        str: Site id.

    """
    # used for background syncing
    site_id = os.environ.get(SITE_ID_ENV_KEY)
    if site_id:
        return site_id

    site_id_path = get_launcher_local_dir("site_id")
    if os.path.exists(site_id_path):
        with open(site_id_path, "r") as stream:
            site_id = stream.read()

    if not site_id:
        os.makedirs(os.path.dirname(site_id_path), exist_ok=True)
        site_id = _create_local_site_id()
        with open(site_id_path, "w") as stream:
            stream.write(site_id)
    return site_id

get_shim_executable_path()

Path to shim executable.

It is not validated if shim exists.

Returns:

Name Type Description
str str

Path where shim executable should be found.

Source code in common/ayon_common/utils.py
885
886
887
888
889
890
891
892
893
894
895
896
897
def get_shim_executable_path() -> str:
    """Path to shim executable.

    It is not validated if shim exists.

    Returns:
        str: Path where shim executable should be found.

    """
    filename = "ayon"
    if platform.system().lower() == "windows":
        filename += ".exe"
    return os.path.join(_get_shim_executable_root(), filename)

is_dev_mode_enabled()

Check if dev is enabled.

A dev bundle is used when dev is enabled.

Returns:

Name Type Description
bool bool

Dev is enabled.

Source code in common/ayon_common/utils.py
160
161
162
163
164
165
166
167
168
169
def is_dev_mode_enabled() -> bool:
    """Check if dev is enabled.

    A dev bundle is used when dev is enabled.

    Returns:
        bool: Dev is enabled.

    """
    return os.getenv("AYON_USE_DEV") == "1"

is_staging_enabled()

Check if staging is enabled.

Returns:

Name Type Description
bool bool

True if staging is enabled.

Source code in common/ayon_common/utils.py
150
151
152
153
154
155
156
157
def is_staging_enabled() -> bool:
    """Check if staging is enabled.

    Returns:
        bool: True if staging is enabled.

    """
    return os.getenv("AYON_USE_STAGING") == "1"

load_executable_version(executable)

Get version of executable.

Parameters:

Name Type Description Default
executable str

Path to executable.

required

Returns:

Type Description
Optional[str]

Union[str, None]: Version of executable.

Source code in common/ayon_common/utils.py
349
350
351
352
353
354
355
356
357
358
359
360
361
def load_executable_version(executable: str) -> Optional[str]:
    """Get version of executable.

    Args:
        executable (str): Path to executable.

    Returns:
        Union[str, None]: Version of executable.

    """
    if not executable:
        return None
    return load_version_from_root(os.path.dirname(executable))

load_version_from_file(filepath)

Execute python file and return 'version' variable.

Source code in common/ayon_common/utils.py
298
299
300
301
302
303
def load_version_from_file(filepath: Path) -> str:
    """Execute python file and return '__version__' variable."""
    version_content = filepath.read_text(encoding="utf-8")
    version_globals = {}
    exec(version_content, version_globals)
    return version_globals["__version__"]

load_version_from_root(root)

Get version of executable.

Parameters:

Name Type Description Default
root str

Path to executable.

required

Returns:

Type Description
Optional[str]

Union[str, None]: Version of executable.

Source code in common/ayon_common/utils.py
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
def load_version_from_root(root: str) -> Optional[str]:
    """Get version of executable.

    Args:
        root (str): Path to executable.

    Returns:
        Union[str, None]: Version of executable.

    """
    if not root:
        return None

    p_root: Path = Path(root)
    if not p_root.exists():
        return None

    roots: list[Path] = [p_root]

    # On macOS, the version file is located in 'Resources' folder inside
    #   the 'MacOs' where executable is. Can be next to executable if is not
    #   yet bundled (dev of build).
    if platform.system().lower() == "darwin":
        roots.insert(0, p_root.parent / "Resources")

    for root_obj in roots:
        version_filepath = root_obj / "version"
        if version_filepath.exists():
            content = version_filepath.read_text(encoding="utf-8")
            return content.strip()

        version_filepath = root_obj / "version.py"
        if version_filepath.exists():
            try:
                return load_version_from_file(version_filepath)
            except Exception as exc:
                print(
                    f"Failed to load version file {version_filepath}. {exc}"
                )

    return None

store_current_executable_info()

Store information about current executable to a file for future usage.

Use information about current executable and version of executable and add it to a list of available executables.

The function won't do anything if the application is not built or if version is not set or the executable is already available.

Todos

Don't store executable if is located inside 'ayon-launcher' codebase?

Source code in common/ayon_common/utils.py
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
def store_current_executable_info():
    """Store information about current executable to a file for future usage.

    Use information about current executable and version of executable and
    add it to a list of available executables.

    The function won't do anything if the application is not built or if
    version is not set or the executable is already available.

    Todos:
        Don't store executable if is located inside 'ayon-launcher' codebase?

    """
    if not IS_BUILT_APPLICATION:
        return

    store_executables([sys.executable])

store_executables(executables)

Store information about executables.

Parameters:

Name Type Description Default
executables Iterable[str]

Paths to executables.

required
Source code in common/ayon_common/utils.py
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
def store_executables(executables: Iterable[str]):
    """Store information about executables.

    Args:
        executables (Iterable[str]): Paths to executables.

    """
    info = get_executables_info(check_cleanup=False)
    info.setdefault("available_versions", [])

    for executable in executables:
        if not executable or not os.path.exists(executable):
            continue

        root, filename = os.path.split(executable)
        # Store only 'ayon.exe' executable
        if filename == "ayon_console.exe":
            filename = "ayon.exe"
            executable = os.path.join(root, filename)

        version = load_version_from_root(root)

        match_item = None
        item_is_new = True
        for item in info["available_versions"]:
            # 'executable' is unique identifier if available versions
            item_executable = item.get("executable")
            if not item_executable or item_executable != executable:
                continue

            # Version has changed, update it
            if item.get("version") != version:
                match_item = item
            item_is_new = False
            break

        if match_item is None:
            if not item_is_new:
                continue
            match_item = {}
            info["available_versions"].append(match_item)

        match_item.update({
            "version": version,
            "executable": executable,
            "added": datetime.datetime.now().strftime("%y-%m-%d-%H%M"),
        })
    store_executables_info(info)

store_executables_info(info)

Store information about executables.

This will override existing information so use it wisely.

Source code in common/ayon_common/utils.py
285
286
287
288
289
290
291
292
293
294
295
def store_executables_info(info: ExecutablesInfo):
    """Store information about executables.

    This will override existing information so use it wisely.

    """
    filepath = get_executables_info_filepath()
    os.makedirs(os.path.dirname(filepath), exist_ok=True)

    with open(filepath, "w") as stream:
        json.dump(info, stream, indent=4)

validate_file_checksum(filepath, checksum, checksum_algorithm)

Validate file checksum.

Parameters:

Name Type Description Default
filepath str

Path to file.

required
checksum str

Hash of file.

required
checksum_algorithm str

Type of checksum.

required

Returns:

Name Type Description
bool bool

Hash is valid/invalid.

Raises:

Type Description
ValueError

File not found or unknown checksum algorithm.

Source code in common/ayon_common/utils.py
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
def validate_file_checksum(
    filepath: str, checksum: str, checksum_algorithm: str
) -> bool:
    """Validate file checksum.

    Args:
        filepath (str): Path to file.
        checksum (str): Hash of file.
        checksum_algorithm (str): Type of checksum.

    Returns:
        bool: Hash is valid/invalid.

    Raises:
        ValueError: File not found or unknown checksum algorithm.

    """
    return checksum == calculate_file_checksum(filepath, checksum_algorithm)