| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# Copyright 2014-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 |
import os |
| 10 |
import sys |
| 11 |
import logging |
| 12 |
from . import version, config, option, output, extractor, job, util, exception |
| 13 |
|
| 14 |
__author__ = "Mike Fährmann" |
| 15 |
__copyright__ = "Copyright 2014-2026 Mike Fährmann" |
| 16 |
__license__ = "GPLv2" |
| 17 |
__maintainer__ = "Mike Fährmann" |
| 18 |
__email__ = "[email protected]" |
| 19 |
__version__ = version.__version__ |
| 20 |
|
| 21 |
|
| 22 |
def main(): |
| 23 |
try: |
| 24 |
parser = option.build_parser() |
| 25 |
args = parser.parse_args() |
| 26 |
log = output.initialize_logging(args.loglevel) |
| 27 |
|
| 28 |
# configuration |
| 29 |
if args.config_type: |
| 30 |
try: |
| 31 |
config.default(args.config_type) |
| 32 |
except Exception as exc: |
| 33 |
config.log.error(exc) |
| 34 |
if args.config_load: |
| 35 |
config.load() |
| 36 |
if args.configs_extra: |
| 37 |
config.load(args.configs_extra, strict=True) |
| 38 |
if args.configs_json: |
| 39 |
config.load(args.configs_json, strict=True, loads=util.json_loads) |
| 40 |
if args.configs_yaml: |
| 41 |
import yaml |
| 42 |
config.load(args.configs_yaml, strict=True, loads=yaml.safe_load) |
| 43 |
if args.configs_toml: |
| 44 |
try: |
| 45 |
import tomllib as toml |
| 46 |
except ImportError: |
| 47 |
import toml |
| 48 |
config.load(args.configs_toml, strict=True, loads=toml.loads) |
| 49 |
if not args.colors: |
| 50 |
output.ANSI = False |
| 51 |
config.set((), "colors", False) |
| 52 |
if util.WINDOWS: |
| 53 |
config.set(("output",), "ansi", False) |
| 54 |
if args.filename: |
| 55 |
filename = args.filename |
| 56 |
if filename == "/O": |
| 57 |
filename = "{filename}.{extension}" |
| 58 |
elif filename.startswith("\\f"): |
| 59 |
filename = f"\f{filename[2:]}" |
| 60 |
config.set((), "filename", filename) |
| 61 |
if args.directory is not None: |
| 62 |
config.set((), "base-directory", args.directory) |
| 63 |
config.set((), "directory", ()) |
| 64 |
if args.postprocessors: |
| 65 |
config.set((), "postprocessors", args.postprocessors) |
| 66 |
if args.abort: |
| 67 |
config.set((), "skip", "abort:" + args.abort) |
| 68 |
if args.terminate: |
| 69 |
config.set((), "skip", "terminate:" + args.terminate) |
| 70 |
if args.cookies_from_browser: |
| 71 |
browser, _, profile = args.cookies_from_browser.partition(":") |
| 72 |
browser, _, keyring = browser.partition("+") |
| 73 |
browser, _, domain = browser.partition("/") |
| 74 |
if profile and profile[0] == ":": |
| 75 |
container = profile[1:] |
| 76 |
profile = None |
| 77 |
else: |
| 78 |
profile, _, container = profile.partition("::") |
| 79 |
config.set((), "cookies", ( |
| 80 |
browser, profile, keyring, container, domain)) |
| 81 |
if args.options_pp: |
| 82 |
config.set((), "postprocessor-options", args.options_pp) |
| 83 |
for opts in args.options: |
| 84 |
config.set(*opts) |
| 85 |
|
| 86 |
# environment variables |
| 87 |
if env := config.get((), "environment"): |
| 88 |
if isinstance(env, dict): |
| 89 |
env = env.dicts() |
| 90 |
environ = os.environ |
| 91 |
if config.get((), "environment-expand", True): |
| 92 |
for key, value in env: |
| 93 |
environ[key] = util.expand_path(value) |
| 94 |
else: |
| 95 |
for key, value in env: # faster than '.update()' |
| 96 |
environ[key] = value |
| 97 |
|
| 98 |
output.configure_standard_streams() |
| 99 |
output.configure_units() |
| 100 |
|
| 101 |
# signals |
| 102 |
if signals := config.get((), "signals-ignore"): |
| 103 |
import signal |
| 104 |
if isinstance(signals, str): |
| 105 |
signals = signals.split(",") |
| 106 |
for signal_name in signals: |
| 107 |
signal_num = getattr(signal, signal_name, None) |
| 108 |
if signal_num is None: |
| 109 |
log.warning("signal '%s' is not defined", signal_name) |
| 110 |
else: |
| 111 |
signal.signal(signal_num, signal.SIG_IGN) |
| 112 |
|
| 113 |
if signals := config.get((), "signals-actions"): |
| 114 |
from . import actions |
| 115 |
actions.parse_signals(signals) |
| 116 |
|
| 117 |
# enable ANSI escape sequences on Windows |
| 118 |
if util.WINDOWS and config.get(("output",), "ansi", output.COLORS): |
| 119 |
from ctypes import windll, wintypes, byref |
| 120 |
kernel32 = windll.kernel32 |
| 121 |
mode = wintypes.DWORD() |
| 122 |
|
| 123 |
for handle_id in (-11, -12): # stdout and stderr |
| 124 |
handle = kernel32.GetStdHandle(handle_id) |
| 125 |
kernel32.GetConsoleMode(handle, byref(mode)) |
| 126 |
if not mode.value & 0x4: |
| 127 |
mode.value |= 0x4 |
| 128 |
kernel32.SetConsoleMode(handle, mode) |
| 129 |
|
| 130 |
output.ANSI = True |
| 131 |
|
| 132 |
# filter environment |
| 133 |
filterenv = config.get((), "filters-environment", True) |
| 134 |
if filterenv is True: |
| 135 |
pass |
| 136 |
elif not filterenv: |
| 137 |
util.compile_expression = util.compile_expression_raw |
| 138 |
elif isinstance(filterenv, str): |
| 139 |
if filterenv == "raw": |
| 140 |
util.compile_expression = util.compile_expression_raw |
| 141 |
elif filterenv.startswith("default"): |
| 142 |
util.compile_expression = util.compile_expression_defaultdict |
| 143 |
|
| 144 |
# format string options |
| 145 |
if not config.get((), "format-operator-dot", True): |
| 146 |
from . import formatter |
| 147 |
formatter._attrgetter = formatter.operator.attrgetter |
| 148 |
if separator := config.get((), "format-separator"): |
| 149 |
from . import formatter |
| 150 |
formatter._SEPARATOR = separator |
| 151 |
|
| 152 |
# eval globals |
| 153 |
if path := config.get((), "globals"): |
| 154 |
util.GLOBALS.update(util.import_file(path).__dict__) |
| 155 |
|
| 156 |
# loglevels |
| 157 |
output.configure_logging(args.loglevel) |
| 158 |
if args.loglevel >= logging.WARNING: |
| 159 |
config.set(("output",), "mode", "null") |
| 160 |
config.set(("downloader",), "progress", None) |
| 161 |
elif args.loglevel <= logging.DEBUG: |
| 162 |
import platform |
| 163 |
import requests |
| 164 |
|
| 165 |
if util.EXECUTABLE: |
| 166 |
extra = f" - Executable ({version.__variant__})" |
| 167 |
elif git_head := util.git_head(): |
| 168 |
extra = " - Git HEAD: " + git_head |
| 169 |
else: |
| 170 |
extra = "" |
| 171 |
|
| 172 |
log.debug("Version %s%s", __version__, extra) |
| 173 |
log.debug("Python %s - %s", |
| 174 |
platform.python_version(), platform.platform()) |
| 175 |
try: |
| 176 |
log.debug("requests %s - urllib3 %s", |
| 177 |
requests.__version__, |
| 178 |
requests.packages.urllib3.__version__) |
| 179 |
except AttributeError: |
| 180 |
pass |
| 181 |
|
| 182 |
log.debug("Configuration Files %s", config._files) |
| 183 |
|
| 184 |
if args.cache_file: |
| 185 |
config.set(("cache",), "file", args.cache_file) |
| 186 |
|
| 187 |
if args.cache_status: |
| 188 |
from . import cache, text |
| 189 |
from collections import defaultdict |
| 190 |
|
| 191 |
path = cache.path() |
| 192 |
rows = cache.get("ALL") |
| 193 |
if rows is None: |
| 194 |
return cache.error() |
| 195 |
|
| 196 |
try: |
| 197 |
size = os.stat(path).st_size |
| 198 |
except Exception: |
| 199 |
size = 0 |
| 200 |
|
| 201 |
cnts = defaultdict(int) |
| 202 |
for row in rows: |
| 203 |
key = row[0].split(".") |
| 204 |
if key[2] == "utils": |
| 205 |
key = key[3].partition("_")[0] |
| 206 |
elif key[1] == "oauth": |
| 207 |
key = text.extr(key[2], "'", "'") |
| 208 |
else: |
| 209 |
key = key[2] |
| 210 |
cnts[key] += 1 |
| 211 |
cnts["Total"] += 1 |
| 212 |
|
| 213 |
key_max = 0 |
| 214 |
cnt_max = len(str(cnts["Total"])) |
| 215 |
for key in cnts: |
| 216 |
if key_max < (key_len := len(key)): |
| 217 |
key_max = key_len |
| 218 |
if key_max > 24: |
| 219 |
key_max = 24 |
| 220 |
|
| 221 |
write = sys.stdout.write |
| 222 |
write(f"""\ |
| 223 |
File: |
| 224 |
{cache.path()} |
| 225 |
Size: |
| 226 |
{output.format_bytes(size)} |
| 227 |
Entries: |
| 228 |
""") |
| 229 |
for key, cnt in sorted(cnts.items(), key=lambda i: (-i[1], i[0])): |
| 230 |
write(f" {key}{' ' * (key_max-len(key))}: {cnt:>{cnt_max}}\n") |
| 231 |
|
| 232 |
return 0 |
| 233 |
|
| 234 |
if args.cache_show: |
| 235 |
from . import cache |
| 236 |
rows = cache.get(args.cache_show) |
| 237 |
if rows is None: |
| 238 |
return cache.error() |
| 239 |
import pickle |
| 240 |
cut = 2 if args.cache_show in {"ALL", "EXP", "VAL"} else 3 |
| 241 |
for key, value, expires in rows: |
| 242 |
try: |
| 243 |
value = util.json_dumps(pickle.loads(value)) |
| 244 |
except Exception: |
| 245 |
value = "<Invalid Value>" |
| 246 |
expires = f" ({expires})" if expires else "" |
| 247 |
key = ".".join(key.split(".")[cut:]) |
| 248 |
sys.stdout.write(f"{key}{expires}:\n {value}\n\n") |
| 249 |
return 0 |
| 250 |
|
| 251 |
if args.cache_clear: |
| 252 |
from . import cache |
| 253 |
cnt = cache.clear(args.cache_clear) |
| 254 |
if cnt is None: |
| 255 |
return cache.error() |
| 256 |
|
| 257 |
cache.log.info("Deleted %d entr%s from '%s'", |
| 258 |
cnt, "y" if cnt == 1 else "ies", cache.path()) |
| 259 |
return 0 |
| 260 |
|
| 261 |
if args.cache_vacuum: |
| 262 |
from . import cache |
| 263 |
if (db := cache.database()) is None: |
| 264 |
return cache.error() |
| 265 |
path = cache.path() |
| 266 |
before = os.stat(path).st_size |
| 267 |
cache.log.info("Running 'VACUUM'") |
| 268 |
db.execute("VACUUM") |
| 269 |
after = os.stat(path).st_size |
| 270 |
if before - after: |
| 271 |
cache.log.info("Reduced database size by %s bytes", |
| 272 |
output.format_bytes(before - after)) |
| 273 |
return 0 |
| 274 |
|
| 275 |
if args.config: |
| 276 |
if args.config == "init": |
| 277 |
return config.initialize() |
| 278 |
elif args.config == "status": |
| 279 |
return config.status() |
| 280 |
else: |
| 281 |
return config.open_extern() |
| 282 |
|
| 283 |
if args.print_traffic: |
| 284 |
import requests |
| 285 |
requests.packages.urllib3.connection.HTTPConnection.debuglevel = 1 |
| 286 |
|
| 287 |
if args.update: |
| 288 |
from . import update |
| 289 |
extr = update.UpdateExtractor.from_url("update:" + args.update) |
| 290 |
ujob = update.UpdateJob(extr) |
| 291 |
return ujob.run() |
| 292 |
|
| 293 |
# category renaming |
| 294 |
config.remap_categories() |
| 295 |
|
| 296 |
# extractor modules |
| 297 |
modules = config.get(("extractor",), "modules") |
| 298 |
if modules is not None: |
| 299 |
if isinstance(modules, str): |
| 300 |
modules = modules.split(",") |
| 301 |
extractor.modules = modules |
| 302 |
|
| 303 |
# external modules |
| 304 |
if args.extractor_sources: |
| 305 |
sources = args.extractor_sources |
| 306 |
sources.append(None) |
| 307 |
else: |
| 308 |
sources = config.get(("extractor",), "module-sources") |
| 309 |
|
| 310 |
if sources: |
| 311 |
modules = [] |
| 312 |
|
| 313 |
for source in sources: |
| 314 |
if isinstance(source, str): |
| 315 |
path = util.expand_path(source) |
| 316 |
try: |
| 317 |
files = [name[:-3] for name in os.listdir(path) |
| 318 |
if name.endswith(".py")] |
| 319 |
modules.append(extractor._modules_path(path, files)) |
| 320 |
except Exception as exc: |
| 321 |
log.warning("Unable to load modules from %s (%s: %s)", |
| 322 |
path, exc.__class__.__name__, exc) |
| 323 |
elif isinstance(source, dict): |
| 324 |
path = util.expand_path(source["from"]) |
| 325 |
files = source["import"] |
| 326 |
try: |
| 327 |
modules.append(extractor._modules_path(path, files)) |
| 328 |
except Exception as exc: |
| 329 |
log.warning("Unable to load modules [%s] " |
| 330 |
"from %s (%s: %s)", |
| 331 |
files, path, exc.__class__.__name__, exc) |
| 332 |
else: |
| 333 |
modules.append(extractor._modules_internal()) |
| 334 |
|
| 335 |
if len(modules) > 1: |
| 336 |
import itertools |
| 337 |
extractor._module_iter = itertools.chain(*modules) |
| 338 |
elif not modules: |
| 339 |
extractor._module_iter = () |
| 340 |
else: |
| 341 |
extractor._module_iter = iter(modules[0]) |
| 342 |
|
| 343 |
if args.list_modules: |
| 344 |
extractor.modules.append("") |
| 345 |
sys.stdout.write("\n".join(extractor.modules)) |
| 346 |
|
| 347 |
elif args.list_extractors is not None: |
| 348 |
write = sys.stdout.write |
| 349 |
fmt = ("{}{}\nCategory: {} - Subcategory: {}" |
| 350 |
"\nExample : {}\n\n").format |
| 351 |
|
| 352 |
extractors = extractor.extractors() |
| 353 |
if args.list_extractors: |
| 354 |
fltr = util.build_extractor_filter( |
| 355 |
args.list_extractors, negate=False) |
| 356 |
extractors = filter(fltr, extractors) |
| 357 |
|
| 358 |
for extr in extractors: |
| 359 |
write(fmt( |
| 360 |
extr.__name__, |
| 361 |
"\n" + extr.__doc__ if extr.__doc__ else "", |
| 362 |
extr.category, extr.subcategory, |
| 363 |
extr.example, |
| 364 |
)) |
| 365 |
|
| 366 |
else: |
| 367 |
if input_files := config.get((), "input-files"): |
| 368 |
for input_file in input_files: |
| 369 |
if isinstance(input_file, str): |
| 370 |
input_file = (input_file, None) |
| 371 |
args.input_files.append(input_file) |
| 372 |
|
| 373 |
nourls = (not args.urls and not args.input_files) |
| 374 |
if not args.server: |
| 375 |
if nourls: |
| 376 |
if args.cookies_from_browser or config.interpolate( |
| 377 |
("extractor",), "cookies"): |
| 378 |
args.urls.append("noop") |
| 379 |
else: |
| 380 |
parser.error( |
| 381 |
"The following arguments are required: URL\n" |
| 382 |
"Use 'gallery-dl --help' to get a list of all " |
| 383 |
"options.") |
| 384 |
else: |
| 385 |
args.server = config.get(("server",), "enabled", False) |
| 386 |
|
| 387 |
if args.list_urls: |
| 388 |
jobtype = job.UrlJob |
| 389 |
jobtype.maxdepth = args.list_urls |
| 390 |
if config.get(("output",), "fallback", True): |
| 391 |
jobtype.handle_url = jobtype.handle_url_fallback |
| 392 |
elif args.dump_json: |
| 393 |
jobtype = job.DataJob |
| 394 |
jobtype.resolve = args.dump_json - 1 |
| 395 |
else: |
| 396 |
jobtype = args.jobtype or job.DownloadJob |
| 397 |
|
| 398 |
if args.server: |
| 399 |
from . import server |
| 400 |
input_manager = server.start() if nourls else InputManager() |
| 401 |
else: |
| 402 |
input_manager = InputManager() |
| 403 |
input_manager.log = input_log = logging.getLogger("inputfile") |
| 404 |
|
| 405 |
# unsupported file logging handler |
| 406 |
if handler := output.setup_logging_handler( |
| 407 |
"unsupportedfile", fmt="{message}", defer=True): |
| 408 |
ulog = job.Job.ulog = logging.getLogger("unsupported") |
| 409 |
ulog.addHandler(handler) |
| 410 |
ulog.propagate = False |
| 411 |
|
| 412 |
# error file logging handler |
| 413 |
if handler := output.setup_logging_handler( |
| 414 |
"errorfile", fmt="{message}", mode="a", defer=True): |
| 415 |
elog = input_manager.err = logging.getLogger("errorfile") |
| 416 |
elog.addHandler(handler) |
| 417 |
elog.propagate = False |
| 418 |
|
| 419 |
# collect input URLs |
| 420 |
input_manager.add_list(args.urls) |
| 421 |
|
| 422 |
if args.input_files: |
| 423 |
for input_file, action in args.input_files: |
| 424 |
try: |
| 425 |
path = util.expand_path(input_file) |
| 426 |
input_manager.add_file(path, action) |
| 427 |
except Exception as exc: |
| 428 |
input_log.error(exc) |
| 429 |
return getattr(exc, "code", 128) |
| 430 |
|
| 431 |
if args.server and not nourls and input_manager.urls: |
| 432 |
return server.send([ |
| 433 |
url[0] if isinstance(url, tuple) else url |
| 434 |
for url in input_manager.urls |
| 435 |
]) |
| 436 |
|
| 437 |
pformat = config.get(("output",), "progress", True) |
| 438 |
if pformat and args.loglevel < logging.ERROR and ( |
| 439 |
args.server or len(input_manager.urls) > 1): |
| 440 |
input_manager.progress(pformat) |
| 441 |
|
| 442 |
if catmap := config.interpolate(("extractor",), "category-map"): |
| 443 |
if catmap == "compat": |
| 444 |
catmap = { |
| 445 |
"coomer" : "coomerparty", |
| 446 |
"kemono" : "kemonoparty", |
| 447 |
"turbo" : "saint", |
| 448 |
"schalenetwork": "koharu", |
| 449 |
"naver-blog" : "naver", |
| 450 |
"naver-chzzk" : "chzzk", |
| 451 |
"naver-webtoon": "naverwebtoon", |
| 452 |
"pixiv-novel" : "pixiv", |
| 453 |
"pixiv-novel:novel" : ("pixiv", "novel"), |
| 454 |
"pixiv-novel:user" : ("pixiv", "novel-user"), |
| 455 |
"pixiv-novel:series" : ("pixiv", "novel-series"), |
| 456 |
"pixiv-novel:bookmark": ("pixiv", "novel-bookmark"), |
| 457 |
} |
| 458 |
from .extractor import common |
| 459 |
common.CATEGORY_MAP = catmap |
| 460 |
|
| 461 |
# process input URLs |
| 462 |
retval = 0 |
| 463 |
for url in input_manager: |
| 464 |
try: |
| 465 |
log.debug("Starting %s for '%s'", jobtype.__name__, url) |
| 466 |
|
| 467 |
if isinstance(url, ExtendedUrl): |
| 468 |
for opts in url.gconfig: |
| 469 |
config.set(*opts) |
| 470 |
with config.apply(url.lconfig): |
| 471 |
status = jobtype(url.value).run() |
| 472 |
else: |
| 473 |
status = jobtype(url).run() |
| 474 |
|
| 475 |
if status: |
| 476 |
retval |= status |
| 477 |
input_manager.error() |
| 478 |
else: |
| 479 |
input_manager.success() |
| 480 |
|
| 481 |
except exception.RestartExtraction: |
| 482 |
log.debug("Restarting '%s'", url) |
| 483 |
continue |
| 484 |
except exception.ControlException: |
| 485 |
pass |
| 486 |
except exception.NoExtractorError: |
| 487 |
log.error("Unsupported URL '%s'", url) |
| 488 |
retval |= 64 |
| 489 |
input_manager.error() |
| 490 |
|
| 491 |
input_manager.next() |
| 492 |
return retval |
| 493 |
return 0 |
| 494 |
|
| 495 |
except KeyboardInterrupt: |
| 496 |
raise SystemExit("\nKeyboardInterrupt") |
| 497 |
except BrokenPipeError: |
| 498 |
pass |
| 499 |
except OSError as exc: |
| 500 |
import errno |
| 501 |
if exc.errno != errno.EPIPE: |
| 502 |
raise |
| 503 |
return 1 |
| 504 |
|
| 505 |
|
| 506 |
class InputManager(): |
| 507 |
|
| 508 |
def __init__(self): |
| 509 |
self.urls = [] |
| 510 |
self.files = () |
| 511 |
self.log = self.err = None |
| 512 |
|
| 513 |
self._url = "" |
| 514 |
self._item = None |
| 515 |
self._index = 0 |
| 516 |
self._pformat = None |
| 517 |
|
| 518 |
def add_url(self, url): |
| 519 |
self.urls.append(url) |
| 520 |
|
| 521 |
def add_list(self, urls): |
| 522 |
self.urls += urls |
| 523 |
|
| 524 |
def add_file(self, path, action=None): |
| 525 |
"""Process an input file. |
| 526 |
|
| 527 |
Lines starting with '#' and empty lines will be ignored. |
| 528 |
Lines starting with '-' will be interpreted as a key-value pair |
| 529 |
separated by an '='. where |
| 530 |
'key' is a dot-separated option name and |
| 531 |
'value' is a JSON-parsable string. |
| 532 |
These configuration options will be applied |
| 533 |
while processing the next URL only. |
| 534 |
Lines starting with '-G' are the same as above, except these options |
| 535 |
will be applied for *all* following URLs, i.e. they are Global. |
| 536 |
Everything else will be used as a potential URL. |
| 537 |
|
| 538 |
Example input file: |
| 539 |
|
| 540 |
# settings global options |
| 541 |
-G base-directory = "/tmp/" |
| 542 |
-G skip = false |
| 543 |
|
| 544 |
# setting local options for the next URL |
| 545 |
-filename="spaces_are_optional.jpg" |
| 546 |
-skip = true |
| 547 |
|
| 548 |
https://example.org/ |
| 549 |
|
| 550 |
# next URL uses default filename and 'skip' is false. |
| 551 |
https://example.com/index.htm # comment1 |
| 552 |
https://example.com/404.htm # comment2 |
| 553 |
""" |
| 554 |
if path == "-" and not action: |
| 555 |
try: |
| 556 |
lines = sys.stdin.readlines() |
| 557 |
except Exception: |
| 558 |
raise exception.InputFileError("stdin is not readable") |
| 559 |
path = None |
| 560 |
else: |
| 561 |
try: |
| 562 |
with open(path, encoding="utf-8") as fp: |
| 563 |
lines = fp.readlines() |
| 564 |
except Exception as exc: |
| 565 |
raise exception.InputFileError(str(exc)) |
| 566 |
|
| 567 |
if self.files: |
| 568 |
self.files[path] = lines |
| 569 |
else: |
| 570 |
self.files = {path: lines} |
| 571 |
|
| 572 |
if action == "c": |
| 573 |
action = self._action_comment |
| 574 |
elif action == "d": |
| 575 |
action = self._action_delete |
| 576 |
else: |
| 577 |
action = None |
| 578 |
|
| 579 |
gconf = [] |
| 580 |
lconf = [] |
| 581 |
indicies = [] |
| 582 |
strip_comment = None |
| 583 |
append = self.urls.append |
| 584 |
|
| 585 |
for n, line in enumerate(lines): |
| 586 |
line = line.strip() |
| 587 |
|
| 588 |
if not line or line[0] == "#": |
| 589 |
# empty line or comment |
| 590 |
continue |
| 591 |
|
| 592 |
elif line[0] == "-": |
| 593 |
# config spec |
| 594 |
if len(line) >= 2 and line[1] == "G": |
| 595 |
conf = gconf |
| 596 |
line = line[2:] |
| 597 |
else: |
| 598 |
conf = lconf |
| 599 |
line = line[1:] |
| 600 |
if action: |
| 601 |
indicies.append(n) |
| 602 |
|
| 603 |
key, sep, value = line.partition("=") |
| 604 |
if not sep: |
| 605 |
raise exception.InputFileError( |
| 606 |
f"Invalid KEY=VALUE pair '{line}' " |
| 607 |
f"on line {n+1} in {path}") |
| 608 |
|
| 609 |
try: |
| 610 |
value = util.json_loads(value.strip()) |
| 611 |
except ValueError as exc: |
| 612 |
self.log.debug("%s: %s", exc.__class__.__name__, exc) |
| 613 |
raise exception.InputFileError( |
| 614 |
f"Unable to parse '{value}' on line {n+1} in {path}") |
| 615 |
|
| 616 |
key = key.strip().split(".") |
| 617 |
conf.append((key[:-1], key[-1], value)) |
| 618 |
|
| 619 |
else: |
| 620 |
# url |
| 621 |
if " #" in line or "\t#" in line: |
| 622 |
if strip_comment is None: |
| 623 |
strip_comment = util.re(r"\s+#.*").sub |
| 624 |
line = strip_comment("", line) |
| 625 |
if gconf or lconf: |
| 626 |
url = ExtendedUrl(line, gconf, lconf) |
| 627 |
gconf = [] |
| 628 |
lconf = [] |
| 629 |
else: |
| 630 |
url = line |
| 631 |
|
| 632 |
if action: |
| 633 |
indicies.append(n) |
| 634 |
append((url, path, action, indicies)) |
| 635 |
indicies = [] |
| 636 |
else: |
| 637 |
append(url) |
| 638 |
|
| 639 |
def progress(self, pformat=True): |
| 640 |
if pformat is True: |
| 641 |
pformat = "[{current}/{total}] {url}\n" |
| 642 |
else: |
| 643 |
pformat += "\n" |
| 644 |
self._pformat = pformat.format_map |
| 645 |
|
| 646 |
def next(self): |
| 647 |
self._index += 1 |
| 648 |
|
| 649 |
def success(self): |
| 650 |
if self._item: |
| 651 |
self._rewrite() |
| 652 |
|
| 653 |
def error(self): |
| 654 |
if self.err: |
| 655 |
if self._item: |
| 656 |
url, path, action, indicies = self._item |
| 657 |
lines = self.files[path] |
| 658 |
out = "".join(lines[i] for i in indicies) |
| 659 |
if out and out[-1] == "\n": |
| 660 |
out = out[:-1] |
| 661 |
self._rewrite() |
| 662 |
else: |
| 663 |
out = str(self._url) |
| 664 |
self.err.info(out) |
| 665 |
|
| 666 |
def _rewrite(self): |
| 667 |
url, path, action, indicies = self._item |
| 668 |
path_tmp = path + ".tmp" |
| 669 |
lines = self.files[path] |
| 670 |
action(lines, indicies) |
| 671 |
|
| 672 |
try: |
| 673 |
with open(path_tmp, "w", encoding="utf-8") as fp: |
| 674 |
fp.writelines(lines) |
| 675 |
os.replace(path_tmp, path) |
| 676 |
except Exception as exc: |
| 677 |
self.log.warning( |
| 678 |
"Unable to update '%s' (%s: %s)", |
| 679 |
path, exc.__class__.__name__, exc) |
| 680 |
|
| 681 |
def _action_comment(self, lines, indicies): |
| 682 |
for i in indicies: |
| 683 |
lines[i] = "# " + lines[i] |
| 684 |
|
| 685 |
def _action_delete(self, lines, indicies): |
| 686 |
for i in indicies: |
| 687 |
lines[i] = "" |
| 688 |
|
| 689 |
def __iter__(self): |
| 690 |
self._index = 0 |
| 691 |
return self |
| 692 |
|
| 693 |
def __next__(self): |
| 694 |
try: |
| 695 |
url = self.urls[self._index] |
| 696 |
except IndexError: |
| 697 |
raise StopIteration |
| 698 |
|
| 699 |
if isinstance(url, tuple): |
| 700 |
self._item = url |
| 701 |
url = url[0] |
| 702 |
else: |
| 703 |
self._item = None |
| 704 |
self._url = url |
| 705 |
|
| 706 |
if self._pformat: |
| 707 |
output.stderr_write(self._pformat({ |
| 708 |
"total" : len(self.urls), |
| 709 |
"current": self._index + 1, |
| 710 |
"url" : url, |
| 711 |
})) |
| 712 |
return url |
| 713 |
|
| 714 |
|
| 715 |
class ExtendedUrl(): |
| 716 |
"""URL with attached config key-value pairs""" |
| 717 |
__slots__ = ("value", "gconfig", "lconfig") |
| 718 |
|
| 719 |
def __init__(self, url, gconf, lconf): |
| 720 |
self.value = url |
| 721 |
self.gconfig = gconf |
| 722 |
self.lconfig = lconf |
| 723 |
|
| 724 |
def __str__(self): |
| 725 |
return self.value |