Debian Codegraph @

test/integration/targets/ansible-galaxy-role/files/create-role-archive.py

raw ◀ ▶
1 Debian patch touch this file
•1 #!/usr/bin/env python3
2 """Create a role archive which overwrites an arbitrary file."""
3 from __future__ import annotations
4
5 import argparse
6 import os
7 import pathlib
8 import tarfile
9 import tempfile
10
11
12 def main() -> None:
13 parser = argparse.ArgumentParser(description=__doc__)
14 parser.add_argument('archive', type=pathlib.Path, help='archive to create')
15 parser.add_argument('content', type=pathlib.Path, help='content to write')
16 parser.add_argument('target', type=pathlib.Path, help='file to overwrite')
17
18 args = parser.parse_args()
19
20 create_archive(args.archive, args.content, args.target)
21
22
23 def generate_files_from_path(path):
24 if os.path.isdir(path):
25 for subpath in os.listdir(path):
26 _path = os.path.join(path, subpath)
27 yield from generate_files_from_path(_path)
28 elif os.path.isfile(path):
29 yield pathlib.Path(path)
30
31
32 def create_archive(archive_path: pathlib.Path, content_path: pathlib.Path, target_path: pathlib.Path) -> None:
33 with (
34 tarfile.open(name=archive_path, mode='w') as role_archive,
35 tempfile.TemporaryDirectory() as temp_dir_name,
36 ):
37 temp_dir_path = pathlib.Path(temp_dir_name)
38
39 meta_main_path = temp_dir_path / 'meta' / 'main.yml'
40 meta_main_path.parent.mkdir()
41 meta_main_path.write_text('')
42
43 symlink_path = temp_dir_path / 'symlink'
44 symlink_path.symlink_to(target_path)
45
46 role_archive.add(meta_main_path)
47 role_archive.add(symlink_path)
48
49 for path in generate_files_from_path(content_path):
50 if path == content_path:
51 arcname = str(symlink_path)
52 else:
53 arcname = os.path.join(temp_dir_path, path)
54
55 content_tarinfo = role_archive.gettarinfo(path, arcname)
56 with path.open('rb') as file_content:
57 role_archive.addfile(content_tarinfo, file_content)
58
59
60 if __name__ == '__main__':
61 main()