PageRenderTime 44ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/mercurial/encoding.py

https://bitbucket.org/mirror/mercurial/
Python | 380 lines | 322 code | 14 blank | 44 comment | 24 complexity | 54ac43d58802343f82da87c25ef7b0a8 MD5 | raw file
Possible License(s): GPL-2.0
  1. # encoding.py - character transcoding support for Mercurial
  2. #
  3. # Copyright 2005-2009 Matt Mackall <mpm@selenic.com> and others
  4. #
  5. # This software may be used and distributed according to the terms of the
  6. # GNU General Public License version 2 or any later version.
  7. import error
  8. import unicodedata, locale, os
  9. def _getpreferredencoding():
  10. '''
  11. On darwin, getpreferredencoding ignores the locale environment and
  12. always returns mac-roman. http://bugs.python.org/issue6202 fixes this
  13. for Python 2.7 and up. This is the same corrected code for earlier
  14. Python versions.
  15. However, we can't use a version check for this method, as some distributions
  16. patch Python to fix this. Instead, we use it as a 'fixer' for the mac-roman
  17. encoding, as it is unlikely that this encoding is the actually expected.
  18. '''
  19. try:
  20. locale.CODESET
  21. except AttributeError:
  22. # Fall back to parsing environment variables :-(
  23. return locale.getdefaultlocale()[1]
  24. oldloc = locale.setlocale(locale.LC_CTYPE)
  25. locale.setlocale(locale.LC_CTYPE, "")
  26. result = locale.nl_langinfo(locale.CODESET)
  27. locale.setlocale(locale.LC_CTYPE, oldloc)
  28. return result
  29. _encodingfixers = {
  30. '646': lambda: 'ascii',
  31. 'ANSI_X3.4-1968': lambda: 'ascii',
  32. 'mac-roman': _getpreferredencoding
  33. }
  34. try:
  35. encoding = os.environ.get("HGENCODING")
  36. if not encoding:
  37. encoding = locale.getpreferredencoding() or 'ascii'
  38. encoding = _encodingfixers.get(encoding, lambda: encoding)()
  39. except locale.Error:
  40. encoding = 'ascii'
  41. encodingmode = os.environ.get("HGENCODINGMODE", "strict")
  42. fallbackencoding = 'ISO-8859-1'
  43. class localstr(str):
  44. '''This class allows strings that are unmodified to be
  45. round-tripped to the local encoding and back'''
  46. def __new__(cls, u, l):
  47. s = str.__new__(cls, l)
  48. s._utf8 = u
  49. return s
  50. def __hash__(self):
  51. return hash(self._utf8) # avoid collisions in local string space
  52. def tolocal(s):
  53. """
  54. Convert a string from internal UTF-8 to local encoding
  55. All internal strings should be UTF-8 but some repos before the
  56. implementation of locale support may contain latin1 or possibly
  57. other character sets. We attempt to decode everything strictly
  58. using UTF-8, then Latin-1, and failing that, we use UTF-8 and
  59. replace unknown characters.
  60. The localstr class is used to cache the known UTF-8 encoding of
  61. strings next to their local representation to allow lossless
  62. round-trip conversion back to UTF-8.
  63. >>> u = 'foo: \\xc3\\xa4' # utf-8
  64. >>> l = tolocal(u)
  65. >>> l
  66. 'foo: ?'
  67. >>> fromlocal(l)
  68. 'foo: \\xc3\\xa4'
  69. >>> u2 = 'foo: \\xc3\\xa1'
  70. >>> d = { l: 1, tolocal(u2): 2 }
  71. >>> len(d) # no collision
  72. 2
  73. >>> 'foo: ?' in d
  74. False
  75. >>> l1 = 'foo: \\xe4' # historical latin1 fallback
  76. >>> l = tolocal(l1)
  77. >>> l
  78. 'foo: ?'
  79. >>> fromlocal(l) # magically in utf-8
  80. 'foo: \\xc3\\xa4'
  81. """
  82. try:
  83. try:
  84. # make sure string is actually stored in UTF-8
  85. u = s.decode('UTF-8')
  86. if encoding == 'UTF-8':
  87. # fast path
  88. return s
  89. r = u.encode(encoding, "replace")
  90. if u == r.decode(encoding):
  91. # r is a safe, non-lossy encoding of s
  92. return r
  93. return localstr(s, r)
  94. except UnicodeDecodeError:
  95. # we should only get here if we're looking at an ancient changeset
  96. try:
  97. u = s.decode(fallbackencoding)
  98. r = u.encode(encoding, "replace")
  99. if u == r.decode(encoding):
  100. # r is a safe, non-lossy encoding of s
  101. return r
  102. return localstr(u.encode('UTF-8'), r)
  103. except UnicodeDecodeError:
  104. u = s.decode("utf-8", "replace") # last ditch
  105. return u.encode(encoding, "replace") # can't round-trip
  106. except LookupError, k:
  107. raise error.Abort(k, hint="please check your locale settings")
  108. def fromlocal(s):
  109. """
  110. Convert a string from the local character encoding to UTF-8
  111. We attempt to decode strings using the encoding mode set by
  112. HGENCODINGMODE, which defaults to 'strict'. In this mode, unknown
  113. characters will cause an error message. Other modes include
  114. 'replace', which replaces unknown characters with a special
  115. Unicode character, and 'ignore', which drops the character.
  116. """
  117. # can we do a lossless round-trip?
  118. if isinstance(s, localstr):
  119. return s._utf8
  120. try:
  121. return s.decode(encoding, encodingmode).encode("utf-8")
  122. except UnicodeDecodeError, inst:
  123. sub = s[max(0, inst.start - 10):inst.start + 10]
  124. raise error.Abort("decoding near '%s': %s!" % (sub, inst))
  125. except LookupError, k:
  126. raise error.Abort(k, hint="please check your locale settings")
  127. # How to treat ambiguous-width characters. Set to 'wide' to treat as wide.
  128. wide = (os.environ.get("HGENCODINGAMBIGUOUS", "narrow") == "wide"
  129. and "WFA" or "WF")
  130. def colwidth(s):
  131. "Find the column width of a string for display in the local encoding"
  132. return ucolwidth(s.decode(encoding, 'replace'))
  133. def ucolwidth(d):
  134. "Find the column width of a Unicode string for display"
  135. eaw = getattr(unicodedata, 'east_asian_width', None)
  136. if eaw is not None:
  137. return sum([eaw(c) in wide and 2 or 1 for c in d])
  138. return len(d)
  139. def getcols(s, start, c):
  140. '''Use colwidth to find a c-column substring of s starting at byte
  141. index start'''
  142. for x in xrange(start + c, len(s)):
  143. t = s[start:x]
  144. if colwidth(t) == c:
  145. return t
  146. def trim(s, width, ellipsis='', leftside=False):
  147. """Trim string 's' to at most 'width' columns (including 'ellipsis').
  148. If 'leftside' is True, left side of string 's' is trimmed.
  149. 'ellipsis' is always placed at trimmed side.
  150. >>> ellipsis = '+++'
  151. >>> from mercurial import encoding
  152. >>> encoding.encoding = 'utf-8'
  153. >>> t= '1234567890'
  154. >>> print trim(t, 12, ellipsis=ellipsis)
  155. 1234567890
  156. >>> print trim(t, 10, ellipsis=ellipsis)
  157. 1234567890
  158. >>> print trim(t, 8, ellipsis=ellipsis)
  159. 12345+++
  160. >>> print trim(t, 8, ellipsis=ellipsis, leftside=True)
  161. +++67890
  162. >>> print trim(t, 8)
  163. 12345678
  164. >>> print trim(t, 8, leftside=True)
  165. 34567890
  166. >>> print trim(t, 3, ellipsis=ellipsis)
  167. +++
  168. >>> print trim(t, 1, ellipsis=ellipsis)
  169. +
  170. >>> u = u'\u3042\u3044\u3046\u3048\u304a' # 2 x 5 = 10 columns
  171. >>> t = u.encode(encoding.encoding)
  172. >>> print trim(t, 12, ellipsis=ellipsis)
  173. \xe3\x81\x82\xe3\x81\x84\xe3\x81\x86\xe3\x81\x88\xe3\x81\x8a
  174. >>> print trim(t, 10, ellipsis=ellipsis)
  175. \xe3\x81\x82\xe3\x81\x84\xe3\x81\x86\xe3\x81\x88\xe3\x81\x8a
  176. >>> print trim(t, 8, ellipsis=ellipsis)
  177. \xe3\x81\x82\xe3\x81\x84+++
  178. >>> print trim(t, 8, ellipsis=ellipsis, leftside=True)
  179. +++\xe3\x81\x88\xe3\x81\x8a
  180. >>> print trim(t, 5)
  181. \xe3\x81\x82\xe3\x81\x84
  182. >>> print trim(t, 5, leftside=True)
  183. \xe3\x81\x88\xe3\x81\x8a
  184. >>> print trim(t, 4, ellipsis=ellipsis)
  185. +++
  186. >>> print trim(t, 4, ellipsis=ellipsis, leftside=True)
  187. +++
  188. >>> t = '\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa' # invalid byte sequence
  189. >>> print trim(t, 12, ellipsis=ellipsis)
  190. \x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa
  191. >>> print trim(t, 10, ellipsis=ellipsis)
  192. \x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa
  193. >>> print trim(t, 8, ellipsis=ellipsis)
  194. \x11\x22\x33\x44\x55+++
  195. >>> print trim(t, 8, ellipsis=ellipsis, leftside=True)
  196. +++\x66\x77\x88\x99\xaa
  197. >>> print trim(t, 8)
  198. \x11\x22\x33\x44\x55\x66\x77\x88
  199. >>> print trim(t, 8, leftside=True)
  200. \x33\x44\x55\x66\x77\x88\x99\xaa
  201. >>> print trim(t, 3, ellipsis=ellipsis)
  202. +++
  203. >>> print trim(t, 1, ellipsis=ellipsis)
  204. +
  205. """
  206. try:
  207. u = s.decode(encoding)
  208. except UnicodeDecodeError:
  209. if len(s) <= width: # trimming is not needed
  210. return s
  211. width -= len(ellipsis)
  212. if width <= 0: # no enough room even for ellipsis
  213. return ellipsis[:width + len(ellipsis)]
  214. if leftside:
  215. return ellipsis + s[-width:]
  216. return s[:width] + ellipsis
  217. if ucolwidth(u) <= width: # trimming is not needed
  218. return s
  219. width -= len(ellipsis)
  220. if width <= 0: # no enough room even for ellipsis
  221. return ellipsis[:width + len(ellipsis)]
  222. if leftside:
  223. uslice = lambda i: u[i:]
  224. concat = lambda s: ellipsis + s
  225. else:
  226. uslice = lambda i: u[:-i]
  227. concat = lambda s: s + ellipsis
  228. for i in xrange(1, len(u)):
  229. usub = uslice(i)
  230. if ucolwidth(usub) <= width:
  231. return concat(usub.encode(encoding))
  232. return ellipsis # no enough room for multi-column characters
  233. def lower(s):
  234. "best-effort encoding-aware case-folding of local string s"
  235. try:
  236. s.decode('ascii') # throw exception for non-ASCII character
  237. return s.lower()
  238. except UnicodeDecodeError:
  239. pass
  240. try:
  241. if isinstance(s, localstr):
  242. u = s._utf8.decode("utf-8")
  243. else:
  244. u = s.decode(encoding, encodingmode)
  245. lu = u.lower()
  246. if u == lu:
  247. return s # preserve localstring
  248. return lu.encode(encoding)
  249. except UnicodeError:
  250. return s.lower() # we don't know how to fold this except in ASCII
  251. except LookupError, k:
  252. raise error.Abort(k, hint="please check your locale settings")
  253. def upper(s):
  254. "best-effort encoding-aware case-folding of local string s"
  255. try:
  256. s.decode('ascii') # throw exception for non-ASCII character
  257. return s.upper()
  258. except UnicodeDecodeError:
  259. pass
  260. try:
  261. if isinstance(s, localstr):
  262. u = s._utf8.decode("utf-8")
  263. else:
  264. u = s.decode(encoding, encodingmode)
  265. uu = u.upper()
  266. if u == uu:
  267. return s # preserve localstring
  268. return uu.encode(encoding)
  269. except UnicodeError:
  270. return s.upper() # we don't know how to fold this except in ASCII
  271. except LookupError, k:
  272. raise error.Abort(k, hint="please check your locale settings")
  273. def toutf8b(s):
  274. '''convert a local, possibly-binary string into UTF-8b
  275. This is intended as a generic method to preserve data when working
  276. with schemes like JSON and XML that have no provision for
  277. arbitrary byte strings. As Mercurial often doesn't know
  278. what encoding data is in, we use so-called UTF-8b.
  279. If a string is already valid UTF-8 (or ASCII), it passes unmodified.
  280. Otherwise, unsupported bytes are mapped to UTF-16 surrogate range,
  281. uDC00-uDCFF.
  282. Principles of operation:
  283. - ASCII and UTF-8 data successfully round-trips and is understood
  284. by Unicode-oriented clients
  285. - filenames and file contents in arbitrary other encodings can have
  286. be round-tripped or recovered by clueful clients
  287. - local strings that have a cached known UTF-8 encoding (aka
  288. localstr) get sent as UTF-8 so Unicode-oriented clients get the
  289. Unicode data they want
  290. - because we must preserve UTF-8 bytestring in places such as
  291. filenames, metadata can't be roundtripped without help
  292. (Note: "UTF-8b" often refers to decoding a mix of valid UTF-8 and
  293. arbitrary bytes into an internal Unicode format that can be
  294. re-encoded back into the original. Here we are exposing the
  295. internal surrogate encoding as a UTF-8 string.)
  296. '''
  297. if isinstance(s, localstr):
  298. return s._utf8
  299. try:
  300. if s.decode('utf-8'):
  301. return s
  302. except UnicodeDecodeError:
  303. # surrogate-encode any characters that don't round-trip
  304. s2 = s.decode('utf-8', 'ignore').encode('utf-8')
  305. r = ""
  306. pos = 0
  307. for c in s:
  308. if s2[pos:pos + 1] == c:
  309. r += c
  310. pos += 1
  311. else:
  312. r += unichr(0xdc00 + ord(c)).encode('utf-8')
  313. return r
  314. def fromutf8b(s):
  315. '''Given a UTF-8b string, return a local, possibly-binary string.
  316. return the original binary string. This
  317. is a round-trip process for strings like filenames, but metadata
  318. that's was passed through tolocal will remain in UTF-8.
  319. >>> m = "\\xc3\\xa9\\x99abcd"
  320. >>> n = toutf8b(m)
  321. >>> n
  322. '\\xc3\\xa9\\xed\\xb2\\x99abcd'
  323. >>> fromutf8b(n) == m
  324. True
  325. '''
  326. # fast path - look for uDxxx prefixes in s
  327. if "\xed" not in s:
  328. return s
  329. u = s.decode("utf-8")
  330. r = ""
  331. for c in u:
  332. if ord(c) & 0xff00 == 0xdc00:
  333. r += chr(ord(c) & 0xff)
  334. else:
  335. r += c.encode("utf-8")
  336. return r