Debian Codegraph @

gallery_dl/config.py

raw symbols SCIP
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 and new not in opts:
214 opts[new] = opts[old]
215
216
217 def load(files=None, strict=False, loads=None, conf=_config):
218 """Load configuration files"""
219 if loads is None:
220 loads = _load
221
222 for pathfmt in files or _default_configs:
223 path = util.expand_path(pathfmt)
224 try:
225 with open(path, encoding="utf-8") as fp:
226 config = loads(fp.read())
227 except OSError as exc:
228 if strict:
229 log.error(exc)
230 raise SystemExit(1)
231 except Exception as exc:
232 log.error("%s when loading '%s': %s",
233 exc.__class__.__name__, path, exc)
234 if strict:
235 raise SystemExit(2)
236 else:
237 if not conf:
238 conf.update(config)
239 else:
240 util.combine_dict(conf, config)
241 _files.append(pathfmt)
242
243 if "subconfigs" in config:
244 if subconfigs := config["subconfigs"]:
245 if isinstance(subconfigs, str):
246 subconfigs = (subconfigs,)
247 load(subconfigs, strict, loads, conf)
248
249
250 def clear():
251 """Reset configuration to an empty state"""
252 _config.clear()
253
254
255 def get(path, key, default=None, conf=_config):
256 """Get the value of property 'key' or a default value"""
257 try:
258 for p in path:
259 conf = conf[p]
260 return conf[key]
261 except Exception:
262 return default
263
264
265 def interpolate(path, key, default=None, conf=_config):
266 """Interpolate the value of 'key'"""
267 if key in conf:
268 return conf[key]
269 try:
270 for p in path:
271 conf = conf[p]
272 if key in conf:
273 default = conf[key]
274 except Exception:
275 pass
276 return default
277
278
279 def interpolate_common(common, paths, key, default=None, conf=_config):
280 """Interpolate the value of 'key'
281 using multiple 'paths' along a 'common' ancestor
282 """
283 if key in conf:
284 return conf[key]
285
286 # follow the common path
287 try:
288 for p in common:
289 conf = conf[p]
290 if key in conf:
291 default = conf[key]
292 except Exception:
293 return default
294
295 # try all paths until a value is found
296 value = util.SENTINEL
297 for path in paths:
298 c = conf
299 try:
300 for p in path:
301 c = c[p]
302 if key in c:
303 value = c[key]
304 except Exception:
305 pass
306 if value is not util.SENTINEL:
307 return value
308 return default
309
310
311 def accumulate(path, key, conf=_config):
312 """Accumulate the values of 'key' along 'path'"""
313 result = []
314 try:
315 if key in conf:
316 if value := conf[key]:
317 if isinstance(value, list):
318 result.extend(value)
319 else:
320 result.append(value)
321 for p in path:
322 conf = conf[p]
323 if key in conf:
324 if value := conf[key]:
325 if isinstance(value, list):
326 result[:0] = value
327 else:
328 result.insert(0, value)
329 except Exception:
330 pass
331 return result
332
333
334 def set(path, key, value, conf=_config):
335 """Set the value of property 'key' for this session"""
336 for p in path:
337 try:
338 conf = conf[p]
339 except KeyError:
340 conf[p] = conf = {}
341 conf[key] = value
342
343
344 def setdefault(path, key, value, conf=_config):
345 """Set the value of property 'key' if it doesn't exist"""
346 for p in path:
347 try:
348 conf = conf[p]
349 except KeyError:
350 conf[p] = conf = {}
351 return conf.setdefault(key, value)
352
353
354 def unset(path, key, conf=_config):
355 """Unset the value of property 'key'"""
356 try:
357 for p in path:
358 conf = conf[p]
359 del conf[key]
360 except Exception:
361 pass
362
363
364 class apply():
365 """Context Manager: apply a collection of key-value pairs"""
366
367 def __init__(self, kvlist):
368 self.original = []
369 self.kvlist = kvlist
370
371 def __enter__(self):
372 for path, key, value in self.kvlist:
373 self.original.append((path, key, get(path, key, util.SENTINEL)))
374 set(path, key, value)
375
376 def __exit__(self, exc_type, exc_value, traceback):
377 self.original.reverse()
378 for path, key, value in self.original:
379 if value is util.SENTINEL:
380 unset(path, key)
381 else:
382 set(path, key, value)