Debian Codegraph @

ansible_collections/community/docker/plugins/module_utils/_api/utils/config.py

raw
1 # This code is part of the Ansible collection community.docker, but is an independent component.
2 # This particular file, and this file only, is based on the Docker SDK for Python (https://github.com/docker/docker-py/)
3 #
4 # Copyright (c) 2016-2022 Docker, Inc.
5 #
6 # It is licensed under the Apache 2.0 license (see LICENSES/Apache-2.0.txt in this collection)
7 # SPDX-License-Identifier: Apache-2.0
8
9 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
10 # Do not use this from other collections or standalone plugins/modules!
11
12 from __future__ import annotations
13
14 import json
15 import logging
16 import os
17 import typing as t
18
19 from ..constants import IS_WINDOWS_PLATFORM
20
21 DOCKER_CONFIG_FILENAME = os.path.join(".docker", "config.json")
22 LEGACY_DOCKER_CONFIG_FILENAME = ".dockercfg"
23
24 log = logging.getLogger(__name__)
25
26
27 def get_default_config_file() -> str:
28 return os.path.join(home_dir(), DOCKER_CONFIG_FILENAME)
29
30
31 def find_config_file(config_path: str | None = None) -> str | None:
32 homedir = home_dir()
33 paths = list(
34 filter(
35 None,
36 [
37 config_path, # 1
38 config_path_from_environment(), # 2
39 os.path.join(homedir, DOCKER_CONFIG_FILENAME), # 3
40 os.path.join(homedir, LEGACY_DOCKER_CONFIG_FILENAME), # 4
41 ],
42 )
43 )
44
45 log.debug("Trying paths: %s", repr(paths))
46
47 for path in paths:
48 if os.path.exists(path):
49 log.debug("Found file at path: %s", path)
50 return path
51
52 log.debug("No config file found")
53
54 return None
55
56
57 def config_path_from_environment() -> str | None:
58 config_dir = os.environ.get("DOCKER_CONFIG")
59 if not config_dir:
60 return None
61 return os.path.join(config_dir, os.path.basename(DOCKER_CONFIG_FILENAME))
62
63
64 def home_dir() -> str:
65 """
66 Get the user's home directory, using the same logic as the Docker Engine
67 client - use %USERPROFILE% on Windows, $HOME/getuid on POSIX.
68 """
69 if IS_WINDOWS_PLATFORM:
70 return os.environ.get("USERPROFILE", "")
71 return os.path.expanduser("~")
72
73
74 def load_general_config(config_path: str | None = None) -> dict[str, t.Any]:
75 config_file = find_config_file(config_path)
76
77 if not config_file:
78 return {}
79
80 try:
81 with open(config_file, "rt", encoding="utf-8") as f:
82 return json.load(f)
83 except (IOError, ValueError) as e:
84 # In the case of a legacy `.dockercfg` file, we will not
85 # be able to load any JSON data.
86 log.debug(e)
87
88 log.debug("All parsing attempts failed - returning empty config")
89 return {}