Patchwork D12404: templates: extract function to `stringutil` for getting first line of text

login
register
mail settings
Submitter phabricator
Date March 25, 2022, 5:38 a.m.
Message ID <differential-rev-PHID-DREV-3m3e4oyw7n2zzgncw5pa-req@mercurial-scm.org>
Download mbox | patch
Permalink /patch/50748/
State New
Headers show

Comments

phabricator - March 25, 2022, 5:38 a.m.
martinvonz created this revision.
Herald added a reviewer: hg-reviewers.
Herald added a subscriber: mercurial-patches.

REVISION SUMMARY
  It's surprisingly hard to get the first line from a string, so let's
  have our own function in `stringutil` for it.

REPOSITORY
  rHG Mercurial

BRANCH
  default

REVISION DETAIL
  https://phab.mercurial-scm.org/D12404

AFFECTED FILES
  mercurial/templatefilters.py
  mercurial/utils/stringutil.py

CHANGE DETAILS




To: martinvonz, #hg-reviewers
Cc: mercurial-patches, mercurial-devel

Patch

diff --git a/mercurial/utils/stringutil.py b/mercurial/utils/stringutil.py
--- a/mercurial/utils/stringutil.py
+++ b/mercurial/utils/stringutil.py
@@ -685,6 +685,14 @@ 
     return _correctauthorformat.match(author) is not None
 
 
+def firstline(text):
+    """Return the first line of the input"""
+    try:
+        return text.splitlines()[0]
+    except IndexError:
+        return b''
+
+
 def ellipsis(text, maxlength=400):
     """Trim string to at most maxlength (default: 400) columns in display."""
     return encoding.trim(text, maxlength, ellipsis=b'...')
diff --git a/mercurial/templatefilters.py b/mercurial/templatefilters.py
--- a/mercurial/templatefilters.py
+++ b/mercurial/templatefilters.py
@@ -268,10 +268,7 @@ 
 @templatefilter(b'firstline', intype=bytes)
 def firstline(text):
     """Any text. Returns the first line of text."""
-    try:
-        return text.splitlines()[0]
-    except IndexError:
-        return b''
+    return stringutil.firstline(text)
 
 
 @templatefilter(b'hex', intype=bytes)