text.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. import gzip
  2. import re
  3. import secrets
  4. import textwrap
  5. import unicodedata
  6. from collections import deque
  7. from gzip import GzipFile
  8. from gzip import compress as gzip_compress
  9. from html import escape
  10. from html.parser import HTMLParser
  11. from io import BytesIO
  12. from django.core.exceptions import SuspiciousFileOperation
  13. from django.utils.functional import (
  14. SimpleLazyObject,
  15. cached_property,
  16. keep_lazy_text,
  17. lazy,
  18. )
  19. from django.utils.regex_helper import _lazy_re_compile
  20. from django.utils.translation import gettext as _
  21. from django.utils.translation import gettext_lazy, pgettext
  22. @keep_lazy_text
  23. def capfirst(x):
  24. """Capitalize the first letter of a string."""
  25. if not x:
  26. return x
  27. if not isinstance(x, str):
  28. x = str(x)
  29. return x[0].upper() + x[1:]
  30. # Set up regular expressions
  31. re_newlines = _lazy_re_compile(r"\r\n|\r") # Used in normalize_newlines
  32. re_camel_case = _lazy_re_compile(r"(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))")
  33. @keep_lazy_text
  34. def wrap(text, width):
  35. """
  36. A word-wrap function that preserves existing line breaks. Expects that
  37. existing line breaks are posix newlines.
  38. Preserve all white space except added line breaks consume the space on
  39. which they break the line.
  40. Don't wrap long words, thus the output text may have lines longer than
  41. ``width``.
  42. """
  43. wrapper = textwrap.TextWrapper(
  44. width=width,
  45. break_long_words=False,
  46. break_on_hyphens=False,
  47. replace_whitespace=False,
  48. )
  49. result = []
  50. for line in text.splitlines():
  51. wrapped = wrapper.wrap(line)
  52. if not wrapped:
  53. # If `line` contains only whitespaces that are dropped, restore it.
  54. result.append(line)
  55. else:
  56. result.extend(wrapped)
  57. if text.endswith("\n"):
  58. # If `text` ends with a newline, preserve it.
  59. result.append("")
  60. return "\n".join(result)
  61. def add_truncation_text(text, truncate=None):
  62. if truncate is None:
  63. truncate = pgettext(
  64. "String to return when truncating text", "%(truncated_text)s…"
  65. )
  66. if "%(truncated_text)s" in truncate:
  67. return truncate % {"truncated_text": text}
  68. # The truncation text didn't contain the %(truncated_text)s string
  69. # replacement argument so just append it to the text.
  70. if text.endswith(truncate):
  71. # But don't append the truncation text if the current text already ends
  72. # in this.
  73. return text
  74. return f"{text}{truncate}"
  75. def calculate_truncate_chars_length(length, replacement):
  76. truncate_len = length
  77. for char in add_truncation_text("", replacement):
  78. if not unicodedata.combining(char):
  79. truncate_len -= 1
  80. if truncate_len == 0:
  81. break
  82. return truncate_len
  83. class TruncateHTMLParser(HTMLParser):
  84. class TruncationCompleted(Exception):
  85. pass
  86. def __init__(self, *, length, replacement, convert_charrefs=True):
  87. super().__init__(convert_charrefs=convert_charrefs)
  88. self.tags = deque()
  89. self.output = []
  90. self.remaining = length
  91. self.replacement = replacement
  92. @cached_property
  93. def void_elements(self):
  94. from django.utils.html import VOID_ELEMENTS
  95. return VOID_ELEMENTS
  96. def handle_startendtag(self, tag, attrs):
  97. self.handle_starttag(tag, attrs)
  98. if tag not in self.void_elements:
  99. self.handle_endtag(tag)
  100. def handle_starttag(self, tag, attrs):
  101. self.output.append(self.get_starttag_text())
  102. if tag not in self.void_elements:
  103. self.tags.appendleft(tag)
  104. def handle_endtag(self, tag):
  105. if tag not in self.void_elements:
  106. self.output.append(f"</{tag}>")
  107. # Remove from the stack only if the tag matches the most recently
  108. # opened tag (LIFO). This avoids O(n) linear scans for unmatched
  109. # end tags if `deque.remove()` would be called.
  110. if self.tags and self.tags[0] == tag:
  111. self.tags.popleft()
  112. def handle_data(self, data):
  113. data, output = self.process(data)
  114. data_len = len(data)
  115. if self.remaining < data_len:
  116. self.remaining = 0
  117. self.output.append(add_truncation_text(output, self.replacement))
  118. raise self.TruncationCompleted
  119. self.remaining -= data_len
  120. self.output.append(output)
  121. def feed(self, data):
  122. try:
  123. super().feed(data)
  124. except self.TruncationCompleted:
  125. self.output.extend([f"</{tag}>" for tag in self.tags])
  126. self.tags.clear()
  127. self.reset()
  128. else:
  129. # No data was handled.
  130. self.reset()
  131. class TruncateCharsHTMLParser(TruncateHTMLParser):
  132. def __init__(self, *, length, replacement, convert_charrefs=True):
  133. self.length = length
  134. self.processed_chars = 0
  135. super().__init__(
  136. length=calculate_truncate_chars_length(length, replacement),
  137. replacement=replacement,
  138. convert_charrefs=convert_charrefs,
  139. )
  140. def process(self, data):
  141. self.processed_chars += len(data)
  142. if (self.processed_chars == self.length) and (
  143. sum(len(p) for p in self.output) + len(data) == len(self.rawdata)
  144. ):
  145. self.output.append(data)
  146. raise self.TruncationCompleted
  147. output = escape("".join(data[: self.remaining]))
  148. return data, output
  149. class TruncateWordsHTMLParser(TruncateHTMLParser):
  150. def process(self, data):
  151. data = re.split(r"(?<=\S)\s+(?=\S)", data)
  152. output = escape(" ".join(data[: self.remaining]))
  153. return data, output
  154. class Truncator(SimpleLazyObject):
  155. """
  156. An object used to truncate text, either by characters or words.
  157. """
  158. def __init__(self, text):
  159. super().__init__(lambda: str(text))
  160. def chars(self, num, truncate=None, html=False):
  161. """
  162. Return the text truncated to be no longer than the specified number
  163. of characters.
  164. `truncate` specifies what should be used to notify that the string has
  165. been truncated, defaulting to a translatable string of an ellipsis.
  166. """
  167. self._setup()
  168. length = int(num)
  169. if length <= 0:
  170. return ""
  171. text = unicodedata.normalize("NFC", self._wrapped)
  172. if html:
  173. parser = TruncateCharsHTMLParser(length=length, replacement=truncate)
  174. parser.feed(text)
  175. parser.close()
  176. return "".join(parser.output)
  177. return self._text_chars(length, truncate, text)
  178. def _text_chars(self, length, truncate, text):
  179. """Truncate a string after a certain number of chars."""
  180. truncate_len = calculate_truncate_chars_length(length, truncate)
  181. s_len = 0
  182. end_index = None
  183. for i, char in enumerate(text):
  184. if unicodedata.combining(char):
  185. # Don't consider combining characters
  186. # as adding to the string length
  187. continue
  188. s_len += 1
  189. if end_index is None and s_len > truncate_len:
  190. end_index = i
  191. if s_len > length:
  192. # Return the truncated string
  193. return add_truncation_text(text[: end_index or 0], truncate)
  194. # Return the original string since no truncation was necessary
  195. return text
  196. def words(self, num, truncate=None, html=False):
  197. """
  198. Truncate a string after a certain number of words. `truncate` specifies
  199. what should be used to notify that the string has been truncated,
  200. defaulting to ellipsis.
  201. """
  202. self._setup()
  203. length = int(num)
  204. if length <= 0:
  205. return ""
  206. if html:
  207. parser = TruncateWordsHTMLParser(length=length, replacement=truncate)
  208. parser.feed(self._wrapped)
  209. parser.close()
  210. return "".join(parser.output)
  211. return self._text_words(length, truncate)
  212. def _text_words(self, length, truncate):
  213. """
  214. Truncate a string after a certain number of words.
  215. Strip newlines in the string.
  216. """
  217. words = self._wrapped.split()
  218. if len(words) > length:
  219. words = words[:length]
  220. return add_truncation_text(" ".join(words), truncate)
  221. return " ".join(words)
  222. @keep_lazy_text
  223. def get_valid_filename(name):
  224. """
  225. Return the given string converted to a string that can be used for a clean
  226. filename. Remove leading and trailing spaces; convert other spaces to
  227. underscores; and remove anything that is not an alphanumeric, dash,
  228. underscore, or dot.
  229. >>> get_valid_filename("john's portrait in 2004.jpg")
  230. 'johns_portrait_in_2004.jpg'
  231. """
  232. s = str(name).strip().replace(" ", "_")
  233. s = re.sub(r"(?u)[^-\w.]", "", s)
  234. if s in {"", ".", ".."}:
  235. raise SuspiciousFileOperation("Could not derive file name from '%s'" % name)
  236. return s
  237. @keep_lazy_text
  238. def get_text_list(list_, last_word=gettext_lazy("or")):
  239. """
  240. >>> get_text_list(['a', 'b', 'c', 'd'])
  241. 'a, b, c or d'
  242. >>> get_text_list(['a', 'b', 'c'], 'and')
  243. 'a, b and c'
  244. >>> get_text_list(['a', 'b'], 'and')
  245. 'a and b'
  246. >>> get_text_list(['a'])
  247. 'a'
  248. >>> get_text_list([])
  249. ''
  250. """
  251. if not list_:
  252. return ""
  253. if len(list_) == 1:
  254. return str(list_[0])
  255. return "%s %s %s" % (
  256. # Translators: This string is used as a separator between list elements
  257. _(", ").join(str(i) for i in list_[:-1]),
  258. str(last_word),
  259. str(list_[-1]),
  260. )
  261. @keep_lazy_text
  262. def normalize_newlines(text):
  263. """Normalize CRLF and CR newlines to just LF."""
  264. return re_newlines.sub("\n", str(text))
  265. @keep_lazy_text
  266. def phone2numeric(phone):
  267. """Convert a phone number with letters into its numeric equivalent."""
  268. char2number = {
  269. "a": "2",
  270. "b": "2",
  271. "c": "2",
  272. "d": "3",
  273. "e": "3",
  274. "f": "3",
  275. "g": "4",
  276. "h": "4",
  277. "i": "4",
  278. "j": "5",
  279. "k": "5",
  280. "l": "5",
  281. "m": "6",
  282. "n": "6",
  283. "o": "6",
  284. "p": "7",
  285. "q": "7",
  286. "r": "7",
  287. "s": "7",
  288. "t": "8",
  289. "u": "8",
  290. "v": "8",
  291. "w": "9",
  292. "x": "9",
  293. "y": "9",
  294. "z": "9",
  295. }
  296. return "".join(char2number.get(c, c) for c in phone.lower())
  297. def _get_random_filename(max_random_bytes):
  298. return b"a" * secrets.randbelow(max_random_bytes)
  299. def compress_string(s, *, max_random_bytes=None):
  300. compressed_data = gzip_compress(s, compresslevel=6, mtime=0)
  301. if not max_random_bytes:
  302. return compressed_data
  303. compressed_view = memoryview(compressed_data)
  304. header = bytearray(compressed_view[:10])
  305. header[3] = gzip.FNAME
  306. filename = _get_random_filename(max_random_bytes) + b"\x00"
  307. return bytes(header) + filename + compressed_view[10:]
  308. class StreamingBuffer(BytesIO):
  309. def read(self):
  310. ret = self.getvalue()
  311. self.seek(0)
  312. self.truncate()
  313. return ret
  314. # Like compress_string, but for iterators of strings.
  315. def compress_sequence(sequence, *, max_random_bytes=None):
  316. buf = StreamingBuffer()
  317. filename = _get_random_filename(max_random_bytes) if max_random_bytes else None
  318. with GzipFile(
  319. filename=filename, mode="wb", compresslevel=6, fileobj=buf, mtime=0
  320. ) as zfile:
  321. # Output headers...
  322. yield buf.read()
  323. for item in sequence:
  324. zfile.write(item)
  325. zfile.flush()
  326. data = buf.read()
  327. if data:
  328. yield data
  329. yield buf.read()
  330. async def acompress_sequence(sequence, *, max_random_bytes=None):
  331. buf = StreamingBuffer()
  332. filename = _get_random_filename(max_random_bytes) if max_random_bytes else None
  333. with GzipFile(
  334. filename=filename, mode="wb", compresslevel=6, fileobj=buf, mtime=0
  335. ) as zfile:
  336. # Output headers...
  337. yield buf.read()
  338. async for item in sequence:
  339. zfile.write(item)
  340. zfile.flush()
  341. data = buf.read()
  342. if data:
  343. yield data
  344. yield buf.read()
  345. # Expression to match some_token and some_token="with spaces" (and similarly
  346. # for single-quoted strings).
  347. smart_split_re = _lazy_re_compile(
  348. r"""
  349. ((?:
  350. [^\s'"]*
  351. (?:
  352. (?:"(?:[^"\\]|\\.)*" | '(?:[^'\\]|\\.)*')
  353. [^\s'"]*
  354. )+
  355. ) | \S+)
  356. """,
  357. re.VERBOSE,
  358. )
  359. def smart_split(text):
  360. r"""
  361. Generator that splits a string by spaces, leaving quoted phrases together.
  362. Supports both single and double quotes, and supports escaping quotes with
  363. backslashes. In the output, strings will keep their initial and trailing
  364. quote marks and escaped quotes will remain escaped (the results can then
  365. be further processed with unescape_string_literal()).
  366. >>> list(smart_split(r'This is "a person\'s" test.'))
  367. ['This', 'is', '"a person\\\'s"', 'test.']
  368. >>> list(smart_split(r"Another 'person\'s' test."))
  369. ['Another', "'person\\'s'", 'test.']
  370. >>> list(smart_split(r'A "\"funky\" style" test.'))
  371. ['A', '"\\"funky\\" style"', 'test.']
  372. """
  373. for bit in smart_split_re.finditer(str(text)):
  374. yield bit[0]
  375. @keep_lazy_text
  376. def unescape_string_literal(s):
  377. r"""
  378. Convert quoted string literals to unquoted strings with escaped quotes and
  379. backslashes unquoted::
  380. >>> unescape_string_literal('"abc"')
  381. 'abc'
  382. >>> unescape_string_literal("'abc'")
  383. 'abc'
  384. >>> unescape_string_literal('"a \"bc\""')
  385. 'a "bc"'
  386. >>> unescape_string_literal("'\'ab\' c'")
  387. "'ab' c"
  388. """
  389. if not s or s[0] not in "\"'" or s[-1] != s[0]:
  390. raise ValueError("Not a string literal: %r" % s)
  391. quote = s[0]
  392. return s[1:-1].replace(r"\%s" % quote, quote).replace(r"\\", "\\")
  393. @keep_lazy_text
  394. def slugify(value, allow_unicode=False):
  395. """
  396. Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated
  397. dashes to single dashes. Remove characters that aren't alphanumerics,
  398. underscores, or hyphens. Convert to lowercase. Also strip leading and
  399. trailing whitespace, dashes, and underscores.
  400. """
  401. value = str(value)
  402. if allow_unicode:
  403. value = unicodedata.normalize("NFKC", value)
  404. else:
  405. value = (
  406. unicodedata.normalize("NFKD", value)
  407. .encode("ascii", "ignore")
  408. .decode("ascii")
  409. )
  410. value = re.sub(r"[^\w\s-]", "", value.lower())
  411. return re.sub(r"[-\s]+", "-", value).strip("-_")
  412. def camel_case_to_spaces(value):
  413. """
  414. Split CamelCase and convert to lowercase. Strip surrounding whitespace.
  415. """
  416. return re_camel_case.sub(r" \1", value).strip().lower()
  417. def _format_lazy(format_string, *args, **kwargs):
  418. """
  419. Apply str.format() on 'format_string' where format_string, args,
  420. and/or kwargs might be lazy.
  421. """
  422. return format_string.format(*args, **kwargs)
  423. format_lazy = lazy(_format_lazy, str)