Debian Codegraph @

scripts/click-hook-build-helper-db

raw
1 #!/usr/bin/python3
2 # -*- python -*-
3 """Collect helpers hook data into a single json file"""
4
5 import argparse
6 import json
7 import os
8 import sys
9 import logging
10 import tempfile
11 from pathlib import Path
12
13 import xdg.BaseDirectory
14
15 HOOK_EXT = ".json"
16
17 logging.basicConfig(level=logging.INFO)
18
19
20 def collect_helpers(helpers_data_path, hooks_path):
21 if not hooks_path.is_dir():
22 logging.warning(
23 f"failed to collect helpers: hooks directory {hooks_path} "
24 f"does not exist"
25 )
26 return {}
27
28 helpers_data = {}
29 for hook_file in hooks_path.iterdir():
30 if not hook_file.suffix == HOOK_EXT:
31 continue
32
33 logging.debug(f"parsing hook file {hook_file}...")
34 try:
35 with hook_file.open() as fd:
36 data = json.load(fd)
37 except (os.Error, json.JSONDecodeError) as e:
38 logging.warning(f"failed to load hook file {hook_full_path}: {e}")
39 continue
40
41 helper_id = hook_file.stem
42 exec_path = data["exec"]
43 if exec_path != "":
44 exec_path = hook_file.resolve().parent / exec_path
45 app_id = data.get("app_id", None)
46 if app_id is None:
47 # no app_id, use the package name from the helper_id
48 app_id = helper_id.split("_")[0]
49 elif app_id.count("_") >= 3:
50 # remove the version from the app_id
51 app_id = app_id.rsplit("_", 1)[0]
52 helpers_data[app_id] = {"exec": str(exec_path), "helper_id": helper_id}
53
54 return helpers_data
55
56 def build_helper_db(helpers_data_path, hooks_path):
57 logging.debug(f"building helper database...")
58 helpers_data = collect_helpers(helpers_data_path, hooks_path)
59
60 # write the collected data to a temp file and rename the original once
61 # everything is on disk
62 tmp = tempfile.NamedTemporaryFile(
63 mode="w",
64 dir=Path(helpers_data_path).parent,
65 prefix=".helpers_data_",
66 delete=False
67 )
68 tmp_path = Path(tmp.name)
69 try:
70 with tmp:
71 json.dump(helpers_data, tmp)
72 tmp_path = Path(tmp.name)
73 tmp_path.rename(helpers_data_path)
74 except OSError as e:
75 logging.warning(f"failed to save helper database: {e}")
76 return 1
77 finally:
78 tmp_path.unlink(missing_ok=True)
79 logging.debug(f"saved herlper database {helpers_data_path}")
80 return 0
81
82
83 if __name__ == "__main__":
84 xdg_data_home = xdg.BaseDirectory.xdg_data_home
85
86 parser = argparse.ArgumentParser(description=__doc__)
87 parser.add_argument("-D", "--debug",
88 help="Enable debug logging",
89 action="store_true",
90 default=False)
91 parser.add_argument("-d", "--data-home",
92 help="The Path to the (xdg) data home",
93 default=xdg_data_home)
94 args = parser.parse_args()
95 if args.debug:
96 logging.getLogger().setLevel(logging.DEBUG)
97
98 xdg_data_home = Path(args.data_home)
99 helpers_data_path = (
100 xdg_data_home / "lomiri-push-service" / "helpers_data.json"
101 )
102 hooks_path = xdg_data_home / "lomiri-push-service" / "helpers"
103 sys.exit(build_helper_db(helpers_data_path, hooks_path))