1# -------------------------------------------------------------------------
2# Copyright (c) Microsoft Corporation. All rights reserved.
3# Licensed under the MIT License. See License.txt in the project root for
4# license information.
5# --------------------------------------------------------------------------
6
7from datetime import datetime, timedelta
8
9_ERROR_TOO_MANY_FILE_PERMISSIONS = 'file_permission and file_permission_key should not be set at the same time'
10_FILE_PERMISSION_TOO_LONG = 'Size of file_permission is too large. file_permission should be <=8KB, else' \
11                            'please use file_permission_key'
12
13
14def _get_file_permission(file_permission, file_permission_key, default_permission):
15    # if file_permission and file_permission_key are both empty, then use the default_permission
16    # value as file permission, file_permission size should be <= 8KB, else file permission_key should be used
17    if file_permission and len(str(file_permission).encode('utf-8')) > 8 * 1024:
18        raise ValueError(_FILE_PERMISSION_TOO_LONG)
19
20    if not file_permission:
21        if not file_permission_key:
22            return default_permission
23        return None
24
25    if not file_permission_key:
26        return file_permission
27
28    raise ValueError(_ERROR_TOO_MANY_FILE_PERMISSIONS)
29
30
31def _parse_datetime_from_str(string_datetime):
32    if not string_datetime:
33        return None
34    dt, _, us = string_datetime.partition(".")
35    dt = datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S")
36    us = int(us[:-2])  # microseconds
37    datetime_obj = dt + timedelta(microseconds=us)
38    return datetime_obj
39
40
41def _datetime_to_str(datetime_obj):
42    return datetime_obj if isinstance(datetime_obj, str) else datetime_obj.isoformat() + '0Z'
43