Debian Codegraph @

gallery_dl/config.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2015-2026 Mike Fährmann
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License version 2 as
7 # published by the Free Software Foundation.
8
9 """Global configuration module"""
10
11 import sys
12 import os.path
13 import logging
14 from . import util
15
16 log = logging.getLogger("config")
17
18
19 # --------------------------------------------------------------------
20 # internals
21
22 _config = {}
23 _files = []
24 _type = "json"
25 _load = util.json_loads
26 _default_configs = ()
27
28
29 # --------------------------------------------------------------------
30 # public interface
31
32
33 def default(type=None):
34 global _type
35 global _load
36 global _default_configs
37
38 if not type or (type := type.lower()) == "json":
39 _type = type = "json"
40 _load = util.json_loads
41 elif type == "yaml":
42 _type = "yaml"
43 from yaml import safe_load as _load
44 elif type == "toml":
45 _type = "toml"
46 try:
47 from tomllib import loads as _load
48 except ImportError:
49 from toml import loads as _load
50 else:
51 raise ValueError(f"Unsupported config file type '{type}'")
52
53 if util.WINDOWS:
54 _default_configs = [
55 r"%APPDATA%\gallery-dl\config." + type,
56 r"%USERPROFILE%\gallery-dl\config." + type,
57 r"%USERPROFILE%\gallery-dl.conf",
58 ]
59 else:
60 _default_configs = [
61 "/etc/gallery-dl.conf",
62 "${XDG_CONFIG_HOME}/gallery-dl/config." + type
63 if os.environ.get("XDG_CONFIG_HOME") else
64 "${HOME}/.config/gallery-dl/config." + type,
65 "${HOME}/.gallery-dl.conf",
66 ]
67
68 if util.EXECUTABLE:
69 # look for config file in PyInstaller executable directory (#682)
70 _default_configs.append(os.path.join(
71 os.path.dirname(sys.executable),
72 "gallery-dl.conf",
73 ))
74
75
76 default(os.environ.get("GDL_CONFIG_TYPE"))
77
78
79 def initialize():
80 paths = list(map(util.expand_path, _default_configs))
81
82 for path in paths:
83 if os.access(path, os.R_OK | os.W_OK):
84 log.error("There is already a configuration file at '%s'", path)
85 return 1
86
87 for path in paths:
88 try:
89 os.makedirs(os.path.dirname(path), exist_ok=True)
90 with open(path, "x", encoding="utf-8") as fp:
91 fp.write("""\
92 {
93 "extractor": {
94
95 },
96 "downloader": {
97
98 },
99 "output": {
100
101 },
102 "postprocessor": {
103
104 }
105 }
106 """)
107 break
108 except OSError as exc:
109 log.debug("%s: %s", exc.__class__.__name__, exc)
110 else:
111 log.error("Unable to create a new configuration file "
112 "at any of the default paths")
113 return 1
114
115 log.info("Created a basic configuration file at '%s'", path)
116 return 0
117
118
119 def open_extern():
120 for path in _default_configs:
121 path = util.expand_path(path)
122 if os.access(path, os.R_OK | os.W_OK):
123 break
124 else:
125 log.warning("Unable to find any writable configuration file")
126 return 1
127
128 if util.WINDOWS:
129 openers = ("explorer", "notepad")
130 else:
131 openers = ("xdg-open", "open")
132 if editor := os.environ.get("EDITOR"):
133 openers = (editor,) + openers
134
135 import shutil
136 for opener in openers:
137 if opener := shutil.which(opener):
138 break
139 else:
140 log.warning("Unable to find a program to open '%s' with", path)
141 return 1
142
143 log.info("Running '%s %s'", opener, path)
144 retcode = util.Popen((opener, path)).wait()
145
146 if not retcode:
147 try:
148 with open(path, encoding="utf-8") as fp:
149 _load(fp.read())
150 except Exception as exc:
151 log.warning("%s when parsing '%s': %s",
152 exc.__class__.__name__, path, exc)
153 return 2
154
155 return retcode
156
157
158 def status():
159 from .output import stdout_write
160
161 paths = []
162 for path in _default_configs:
163 path = util.expand_path(path)
164
165 try:
166 with open(path, encoding="utf-8") as fp:
167 _load(fp.read())
168 except FileNotFoundError:
169 status = ""
170 except OSError as exc:
171 log.debug("%s: %s", exc.__class__.__name__, exc)
172 status = "Inaccessible"
173 except ValueError as exc:
174 log.debug("%s: %s", exc.__class__.__name__, exc)
175 status = "Invalid " + _type.upper()
176 except Exception as exc:
177 log.debug("%s: %s", exc.__class__.__name__, exc)
178 status = "Unknown"
179 else:
180 status = "OK"
181
182 paths.append((path, status))
183
184 fmt = f"{{:<{max(len(p[0]) for p in paths)}}} : {{}}\n".format
185 for path, status in paths:
186 stdout_write(fmt(path, status))
187
188
189 def remap_categories():
190 opts = _config.get("extractor")
191 if not opts:
192 return
193
194 cmap = opts.get("config-map")
195 if cmap is None:
196 cmap = (
197 ("coomerparty" , "coomer"),
198 ("kemonoparty" , "kemono"),
199 ("giantessbooru", "sizebooru"),
200 ("koharu" , "schalenetwork"),
201 ("naver" , "naver-blog"),
202 ("chzzk" , "naver-chzzk"),
203 ("naverwebtoon", "naver-webtoon"),
204 ("pixiv" , "pixiv-novel"),
205 ("saint" , "turbo"),
206 )
207 elif not cmap:
208 return
209 elif isinstance(cmap, dict):
210 cmap = cmap.items()
211
212 for old, new in cmap:
213 if old in opts:
214 opts[new] = ({**opts[old], **opts[new]} if new in opts else
215 opts[old])
216
217
218 def load(files=None, strict=False, loads=None, conf=_config):
219 """Load configuration files"""
220 if loads is None:
221 loads = _load
222
223 for pathfmt in files or _default_configs:
224 path = util.expand_path(pathfmt)
225 try:
226 with open(path, encoding="utf-8") as fp:
227 config = loads(fp.read())
228 except OSError as exc:
229 if strict:
230 log.error(exc)
231 raise SystemExit(1)
232 except Exception as exc:
233 log.error("%s when loading '%s': %s",
234 exc.__class__.__name__, path, exc)
235 if strict:
236 raise SystemExit(2)
237 else:
238 if not conf:
239 conf.update(config)
240 else:
241 util.combine_dict(conf, config)
242 _files.append(pathfmt)
243
244 if "subconfigs" in config:
245 if subconfigs := config["subconfigs"]:
246 if isinstance(subconfigs, str):
247 subconfigs = (subconfigs,)
248 load(subconfigs, strict, loads, conf)
249
250
251 def clear():
252 """Reset configuration to an empty state"""
253 _config.clear()
254
255
256 getg = _config.get
257
258
259 def get(path, key, default=None, conf=_config):
260 """Get the value of property 'key' or a default value"""
261 try:
262 for p in path:
263 conf = conf[p]
264 return conf[key]
265 except Exception:
266 return default
267
268
269 def interpolate(path, key, default=None, conf=_config):
270 """Interpolate the value of 'key'"""
271 if key in conf:
272 return conf[key]
273 try:
274 for p in path:
275 conf = conf[p]
276 if key in conf:
277 default = conf[key]
278 except Exception:
279 pass
280 return default
281
282
283 def interpolate_common(common, paths, key, default=None, conf=_config):
284 """Interpolate the value of 'key'
285 using multiple 'paths' along a 'common' ancestor
286 """
287 if key in conf:
288 return conf[key]
289
290 # follow the common path
291 try:
292 for p in common:
293 conf = conf[p]
294 if key in conf:
295 default = conf[key]
296 except Exception:
297 return default
298
299 # try all paths until a value is found
300 value = util.SENTINEL
301 for path in paths:
302 c = conf
303 try:
304 for p in path:
305 c = c[p]
306 if key in c:
307 value = c[key]
308 except Exception:
309 pass
310 if value is not util.SENTINEL:
311 return value
312 return default
313
314
315 def accumulate(path, key, conf=_config):
316 """Accumulate the values of 'key' along 'path'"""
317 result = []
318 try:
319 if key in conf:
320 if value := conf[key]:
321 if isinstance(value, list):
322 result.extend(value)
323 else:
324 result.append(value)
325 for p in path:
326 conf = conf[p]
327 if key in conf:
328 if value := conf[key]:
329 if isinstance(value, list):
330 result[:0] = value
331 else:
332 result.insert(0, value)
333 except Exception:
334 pass
335 return result
336
337
338 def set(path, key, value, conf=_config):
339 """Set the value of property 'key' for this session"""
340 for p in path:
341 try:
342 conf = conf[p]
343 except KeyError:
344 conf[p] = conf = {}
345 conf[key] = value
346
347
348 def setdefault(path, key, value, conf=_config):
349 """Set the value of property 'key' if it doesn't exist"""
350 for p in path:
351 try:
352 conf = conf[p]
353 except KeyError:
354 conf[p] = conf = {}
355 return conf.setdefault(key, value)
356
357
358 def unset(path, key, conf=_config):
359 """Unset the value of property 'key'"""
360 try:
361 for p in path:
362 conf = conf[p]
363 del conf[key]
364 except Exception:
365 pass
366
367
368 class apply():
369 """Context Manager: apply a collection of key-value pairs"""
370
371 def __init__(self, kvlist):
372 self.original = []
373 self.kvlist = kvlist
374
375 def __enter__(self):
376 for path, key, value in self.kvlist:
377 self.original.append((path, key, get(path, key, util.SENTINEL)))
378 set(path, key, value)
379
380 def __exit__(self, exc_type, exc_value, traceback):
381 self.original.reverse()
382 for path, key, value in self.original:
383 if value is util.SENTINEL:
384 unset(path, key)
385 else:
386 set(path, key, value)