[PATCH 2 of 2] template: add pad function for padding output
Durham Goode
durham at fb.com
Fri Jan 17 02:45:30 CST 2014
# HG changeset patch
# User Durham Goode <durham at fb.com>
# Date 1389946608 28800
# Fri Jan 17 00:16:48 2014 -0800
# Node ID 77cf62dd2af0b5631a2864744e720e61ad4cde6a
# Parent b18359a70b640d2aeb3f4afd1c8e47d775402b8e
template: add pad function for padding output
Adds a pad template function with the following signature:
pad(text, width, right=False, fillchar=' ')
This uses the standard python ljust and rjust functions to produce a string
that is at least a certain width. This is especially useful with the
introduction of a '{shortestnode}' keyword, since the output can be variable
length.
diff --git a/mercurial/templater.py b/mercurial/templater.py
--- a/mercurial/templater.py
+++ b/mercurial/templater.py
@@ -245,6 +245,31 @@
return templatefilters.fill(text, width, initindent, hangindent)
+def pad(context, mapping, args):
+ """usage: pad(text, width, right=False, fillchar=' ')
+ """
+ if not (2 <= len(args) <= 4):
+ raise error.ParseError(_("pad() expects two to four arguments"))
+
+ width = int(stringify(args[1][0](context, mapping, args[1][1])))
+
+ text = stringify(args[0][0](context, mapping, args[0][1]))
+ if args[0][0] == runstring:
+ text = stringify(runtemplate(context, mapping,
+ compiletemplate(text, context)))
+
+ right = False
+ fillchar = ' '
+ if len(args) > 2:
+ right = stringify(args[2][0](context, mapping, args[2][1])) == "True"
+ if len(args) > 3:
+ fillchar = stringify(args[3][0](context, mapping, args[3][1]))
+
+ if right:
+ return text.rjust(width, fillchar)
+ else:
+ return text.ljust(width, fillchar)
+
def get(context, mapping, args):
if len(args) != 2:
# i18n: "get" is a keyword
@@ -368,6 +393,7 @@
"ifeq": ifeq,
"join": join,
"label": label,
+ "pad": pad,
"rstdoc": rstdoc,
"strip": strip,
"sub": sub,
diff --git a/tests/test-command-template.t b/tests/test-command-template.t
--- a/tests/test-command-template.t
+++ b/tests/test-command-template.t
@@ -1635,3 +1635,16 @@
d97c
f776
+Test pad function
+
+ $ hg log --template '{pad("{shortestnode}", "20")} {author|user}\n'
+ d97c test
+ f776 test
+
+ $ hg log --template '{pad("{shortestnode}", "20", "True")} {author|user}\n'
+ d97c test
+ f776 test
+
+ $ hg log --template '{pad("{shortestnode}", "20", "False", "-")} {author|user}\n'
+ d97c---------------- test
+ f776---------------- test
More information about the Mercurial-devel
mailing list