hgext/mq.py
changeset 23442 a5c94ea3b8af
parent 23412 94092019e839
child 23443 3b653c2fd6ba
--- a/hgext/mq.py	Sun Nov 30 23:30:31 2014 -0500
+++ b/hgext/mq.py	Fri Nov 28 03:09:06 2014 +0100
@@ -114,6 +114,12 @@
     '# Node ID ',
     '# Parent  ', # can occur twice for merges - but that is not relevant for mq
     ]
+# The order of headers in plain 'mail style' patches:
+PLAINHEADERS = {
+    'from': 0,
+    'date': 1,
+    'subject': 2,
+    }
 
 def inserthgheader(lines, header, value):
     """Assuming lines contains a HG patch header, add a header line with value.
@@ -156,9 +162,40 @@
     return lines
 
 def insertplainheader(lines, header, value):
-    if lines and lines[0] and ':' not in lines[0]:
-        lines.insert(0, '')
-    lines.insert(0, '%s: %s' % (header, value))
+    """For lines containing a plain patch header, add a header line with value.
+    >>> insertplainheader([], 'Date', 'z')
+    ['Date: z']
+    >>> insertplainheader([''], 'Date', 'z')
+    ['Date: z', '']
+    >>> insertplainheader(['x'], 'Date', 'z')
+    ['Date: z', '', 'x']
+    >>> insertplainheader(['From: y', 'x'], 'Date', 'z')
+    ['From: y', 'Date: z', '', 'x']
+    >>> insertplainheader([' date : x', ' from : y', ''], 'From', 'z')
+    [' date : x', 'From: z', '']
+    >>> insertplainheader(['', 'Date: y'], 'Date', 'z')
+    ['Date: z', '', 'Date: y']
+    >>> insertplainheader(['foo: bar', 'DATE: z', 'x'], 'From', 'y')
+    ['From: y', 'foo: bar', 'DATE: z', '', 'x']
+    """
+    newprio = PLAINHEADERS[header.lower()]
+    bestpos = len(lines)
+    for i, line in enumerate(lines):
+        if ':' in line:
+            lheader = line.split(':', 1)[0].strip().lower()
+            lprio = PLAINHEADERS.get(lheader, newprio + 1)
+            if lprio == newprio:
+                lines[i] = '%s: %s' % (header, value)
+                return lines
+            if lprio > newprio and i < bestpos:
+                bestpos = i
+        else:
+            if line:
+                lines.insert(i, '')
+            if i < bestpos:
+                bestpos = i
+            break
+    lines.insert(bestpos, '%s: %s' % (header, value))
     return lines
 
 class patchheader(object):