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 def get(path, key, default=None, conf=_config):
257 """Get the value of property 'key' or a default value"""
258 try:
259 for p in path:
260 conf = conf[p]
261 return conf[key]
262 except Exception:
263 return default
264
265
266 def interpolate(path, key, default=None, conf=_config):
267 """Interpolate the value of 'key'"""
268 if key in conf:
269 return conf[key]
270 try:
271 for p in path:
272 conf = conf[p]
273 if key in conf:
274 default = conf[key]
275 except Exception:
276 pass
277 return default
278
279
280 def interpolate_common(common, paths, key, default=None, conf=_config):
281 """Interpolate the value of 'key'
282 using multiple 'paths' along a 'common' ancestor
283 """
284 if key in conf:
285 return conf[key]
286
287 # follow the common path
288 try:
289 for p in common:
290 conf = conf[p]
291 if key in conf:
292 default = conf[key]
293 except Exception:
294 return default
295
296 # try all paths until a value is found
297 value = util.SENTINEL
298 for path in paths:
299 c = conf
300 try:
301 for p in path:
302 c = c[p]
303 if key in c:
304 value = c[key]
305 except Exception:
306 pass
307 if value is not util.SENTINEL:
308 return value
309 return default
310
311
312 def accumulate(path, key, conf=_config):
313 """Accumulate the values of 'key' along 'path'"""
314 result = []
315 try:
316 if key in conf:
317 if value := conf[key]:
318 if isinstance(value, list):
319 result.extend(value)
320 else:
321 result.append(value)
322 for p in path:
323 conf = conf[p]
324 if key in conf:
325 if value := conf[key]:
326 if isinstance(value, list):
327 result[:0] = value
328 else:
329 result.insert(0, value)
330 except Exception:
331 pass
332 return result
333
334
335 def set(path, key, value, conf=_config):
336 """Set the value of property 'key' for this session"""
337 for p in path:
338 try:
339 conf = conf[p]
340 except KeyError:
341 conf[p] = conf = {}
342 conf[key] = value
343
344
345 def setdefault(path, key, value, conf=_config):
346 """Set the value of property 'key' if it doesn't exist"""
347 for p in path:
348 try:
349 conf = conf[p]
350 except KeyError:
351 conf[p] = conf = {}
352 return conf.setdefault(key, value)
353
354
355 def unset(path, key, conf=_config):
356 """Unset the value of property 'key'"""
357 try:
358 for p in path:
359 conf = conf[p]
360 del conf[key]
361 except Exception:
362 pass
363
364
365 class apply():
366 """Context Manager: apply a collection of key-value pairs"""
367
368 def __init__(self, kvlist):
369 self.original = []
370 self.kvlist = kvlist
371
372 def __enter__(self):
373 for path, key, value in self.kvlist:
374 self.original.append((path, key, get(path, key, util.SENTINEL)))
375 set(path, key, value)
376
377 def __exit__(self, exc_type, exc_value, traceback):
378 self.original.reverse()
379 for path, key, value in self.original:
380 if value is util.SENTINEL:
381 unset(path, key)
382 else:
383 set(path, key, value)