Debian Codegraph @

ansible_collections/hetzner/hcloud/scripts/vendor.py

raw
1 #!/usr/bin/env python3
2
3 """
4 Fetch and bundles the hcloud package inside the collection.
5
6 Fetch the desired version `HCLOUD_VERSION` from https://github.com/hetznercloud/hcloud-python
7 `HCLOUD_SOURCE_URL` using git, apply some code modifications to comply with ansible,
8 move the modified files at the vendor location `HCLOUD_VENDOR_PATH`.
9 """
10
11 from __future__ import annotations
12
13 import logging
14 import re
15 from argparse import ArgumentParser
16 from pathlib import Path
17 from shutil import move, rmtree
18 from subprocess import check_call
19 from tempfile import TemporaryDirectory
20 from textwrap import dedent
21
22 logger = logging.getLogger("vendor")
23
24 HCLOUD_SOURCE_URL = "https://github.com/hetznercloud/hcloud-python"
25 HCLOUD_VERSION = "v2.19.0"
26 HCLOUD_VENDOR_PATH = "plugins/module_utils/_vendor/hcloud"
27
28
29 def apply_code_modifications(source_path: Path):
30 for file in source_path.rglob("*.py"):
31 content = file.read_text()
32 content_orig = content
33
34 # Wrap requests imports
35 content = re.sub(
36 r"import requests",
37 dedent(r"""
38 try:
39 import requests
40 except ImportError:
41 requests = None
42 """).strip(),
43 content,
44 )
45
46 # Wrap dateutil imports
47 content = re.sub(
48 r"from dateutil.parser import isoparse",
49 dedent(r"""
50 try:
51 from dateutil.parser import isoparse
52 except ImportError:
53 isoparse = None
54 """).strip(),
55 content,
56 )
57
58 # Remove requests.Response typings
59 content = re.sub(
60 r": requests\.Response",
61 r"",
62 content,
63 )
64
65 if content != content_orig:
66 logger.info("Applied code modifications on %s", file)
67
68 file.write_text(content)
69
70
71 def main(check: bool = False) -> int:
72 with TemporaryDirectory() as tmp_dir:
73 tmp_dir_path = Path(tmp_dir)
74 logger.info("Created temporary directory %s", tmp_dir_path)
75
76 check_call(["git", "clone", "--depth=1", "--branch", HCLOUD_VERSION, HCLOUD_SOURCE_URL, tmp_dir_path])
77 logger.info("Cloned the source files in %s", tmp_dir_path)
78
79 apply_code_modifications(tmp_dir_path / "hcloud")
80 logger.info("Applied code modifications on the source files")
81
82 rmtree(HCLOUD_VENDOR_PATH)
83 move(tmp_dir_path / "hcloud", HCLOUD_VENDOR_PATH)
84 logger.info("Bundled the modified sources files in the collection")
85
86 if check:
87 check_call(["git", "diff", "--exit-code", "--", HCLOUD_VENDOR_PATH])
88
89 return 0
90
91
92 if __name__ == "__main__":
93 logging.basicConfig(level=logging.INFO, format="%(levelname)-8s: %(message)s")
94
95 parser = ArgumentParser()
96 parser.add_argument("--check", action="store_true", default=False)
97 args = parser.parse_args()
98
99 raise SystemExit(main(check=args.check))