Skip to content

Commit

Permalink
implement R<old>/<new>/ format option (#318)
Browse files Browse the repository at this point in the history
  • Loading branch information
mikf committed Jun 23, 2019
1 parent 18a1f8c commit 95b1e4c
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
16 changes: 16 additions & 0 deletions gallery_dl/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,7 @@ class Formatter():
- "c": calls str.capitalize
- "C": calls string.capwords
- "U": calls urllib.parse.unquote
- "S": calls util.to_string()
- Example: {f!l} -> "example"; {f!u} -> "EXAMPLE"
Extra Format Specifiers:
Expand All @@ -359,6 +360,10 @@ class Formatter():
- "J<separator>/":
Joins elements of a list (or string) using <separator>
Example: {f:J - /} -> "a - b - c" (if "f" is ["a", "b", "c"])
- "R<old>/<new>/":
Replaces all occurrences of <old> with <new>
Example: {f:R /_/} -> "f_o_o_b_a_r" (if "f" is "f o o b a r")
"""
CONVERSIONS = {
"l": str.lower,
Expand Down Expand Up @@ -417,6 +422,8 @@ def _field_access(self, field_name, format_spec, conversion):
func = self._format_maxlen
elif format_spec[0] == "J":
func = self._format_join
elif format_spec[0] == "R":
func = self._format_replace
else:
func = self._format_default
fmt = func(format_spec)
Expand Down Expand Up @@ -484,6 +491,15 @@ def wrap(obj):
separator = separator[1:]
return wrap

@staticmethod
def _format_replace(format_spec):
def wrap(obj):
obj = obj.replace(old, new)
return format(obj, format_spec)
old, new, format_spec = format_spec.split("/", 2)
old = old[1:]
return wrap

@staticmethod
def _format_default(format_spec):
def wrap(obj):
Expand Down
1 change: 0 additions & 1 deletion test/test_results.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
# temporary issues, etc.
BROKEN = {
"mangapark",
"pixnet",
}


Expand Down
9 changes: 9 additions & 0 deletions test/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,15 @@ def test_join(self):
self._run_test("{a:J/}" , self.kwdict["a"])
self._run_test("{a:J, /}" , ", ".join(self.kwdict["a"]))

def test_replace(self):
self._run_test("{a:Rh/C/}" , "CElLo wOrLd")
self._run_test("{a!l:Rh/C/}", "Cello world")
self._run_test("{a!u:Rh/C/}", "HELLO WORLD")

self._run_test("{a!l:Rl/_/}", "he__o wor_d")
self._run_test("{a!l:Rl//}" , "heo word")
self._run_test("{name:Rame/othing/}", "Nothing")

def _run_test(self, format_string, result, default=None):
formatter = util.Formatter(format_string, default)
output = formatter.format_map(self.kwdict)
Expand Down

0 comments on commit 95b1e4c

Please sign in to comment.