Skip to content

Commit

Permalink
initial support for conditional filenames (#1394)
Browse files Browse the repository at this point in the history
  • Loading branch information
mikf committed Jun 4, 2021
1 parent 0abad8b commit 4cf4043
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 1 deletion.
22 changes: 22 additions & 0 deletions docs/configuration.rst
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,28 @@ Description
a valid filename extension.


extractor.*.filename-conditions
-------------------------------
Type
``object``
Example
.. code:: json
{
"extension == 'mp4'" : "{id}_video.{extension}",
"extension in ('zip','rar')": "{id}_archive.{extension}",
"'nature' in title" : "{id}_{title}.{extension}"
}
Description
An object containing Python expressions mapping to the
filename format strings to use.

When none of the given conditions match, `extractor.*.filename`_ is used.

Expressions are evaluated in the order as specified in Python 3.6+
and in an undetermined order in Python 3.4 and 3.5.


extractor.*.directory
---------------------
Type
Expand Down
22 changes: 22 additions & 0 deletions gallery_dl/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -756,6 +756,7 @@ class PathFormat():

def __init__(self, extractor):
filename_fmt = extractor.config("filename")
filename_conditions = extractor.config("filename-conditions")
if filename_fmt is None:
filename_fmt = extractor.filename_fmt

Expand All @@ -770,6 +771,14 @@ def __init__(self, extractor):

kwdefault = extractor.config("keywords-default")
try:
if filename_conditions:
self.build_filename = self.build_filename_conditional
self.filename_conditions = [
(compile_expression(expr),
Formatter(fmt, kwdefault).format_map)
for expr, fmt in filename_conditions.items()
]

self.filename_formatter = Formatter(
filename_fmt, kwdefault).format_map
except Exception as exc:
Expand Down Expand Up @@ -933,6 +942,19 @@ def build_filename(self):
except Exception as exc:
raise exception.FilenameFormatError(exc)

def build_filename_conditional(self):
kwdict = self.kwdict

try:
for condition, formatter in self.filename_conditions:
if condition(kwdict):
break
else:
formatter = self.filename_formatter
return self.clean_path(self.clean_segment(formatter(kwdict)))
except Exception as exc:
raise exception.FilenameFormatError(exc)

def build_path(self):
"""Combine directory and filename to full paths"""
if self._create_directory:
Expand Down
2 changes: 1 addition & 1 deletion gallery_dl/version.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.

__version__ = "1.17.6-dev"
__version__ = "1.18.0-dev"

0 comments on commit 4cf4043

Please sign in to comment.