summaryrefslogtreecommitdiffhomepage
path: root/gbp/format.py
diff options
context:
space:
mode:
authorMarkus Lehtonen <markus.lehtonen@linux.intel.com>2017-12-16 00:15:57 +0200
committerGuido Günther <agx@sigxcpu.org>2018-01-12 13:18:02 +0100
commit4868442b8d724a24aaed681eda76559b0da0e0e3 (patch)
tree0d23f326bcbcc135019a67872d2003c5d22d9229 /gbp/format.py
parentf1694df5c8948fbe3866fdfb92c947a2d380e640 (diff)
gbp.git: Python compatibility fixes
Make gbp compatible with older versions of Python 3. As 'bytes' objects do not support the '%' operator until Python v3.5 we introduce a format_b() wrapper that handles this. NOTE: This change should be reverted when Python v3.5 (or newer) has been widely adopted. Signed-off-by: Markus Lehtonen <markus.lehtonen@linux.intel.com>
Diffstat (limited to 'gbp/format.py')
-rw-r--r--gbp/format.py22
1 files changed, 22 insertions, 0 deletions
diff --git a/gbp/format.py b/gbp/format.py
index 2edf4ebd..541ab7b0 100644
--- a/gbp/format.py
+++ b/gbp/format.py
@@ -42,3 +42,25 @@ def format_str(msg, args):
except KeyError as e:
raise GbpError("Failed to format %s: Missing value %s in %s" %
(msg, e, args))
+
+
+def format_b(fmtstr, *args):
+ """String-like interpolation for bytes objects.
+
+ NOTE: This is a compatibility wrapper for older versions (<3.5) of Python 3
+ which do not support the percent operator ('%') for bytes objects. This
+ function should be removed (and replaced by simple '%') when Python 3.5
+ has gained wide enough adoption.
+
+ >>> format_b(b'%s %d', b'foo', 123)
+ b'foo 123'
+ >>> format_b(b'foo 123')
+ b'foo 123'
+ >>> format_b('%s %d', b'foo', 123)
+ Traceback (most recent call last):
+ ...
+ AttributeError: 'str' object has no attribute 'decode'
+ """
+ fmtstr = fmtstr.decode()
+ strargs = tuple([(a.decode() if isinstance(a, bytes) else a) for a in args])
+ return (fmtstr % strargs).encode()