text.py 14 KB

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