测试gitnore

This commit is contained in:
ladeng07
2022-05-06 15:45:57 +08:00
parent 12f390949b
commit 51552904f9
2347 changed files with 120102 additions and 53549 deletions
+73 -102
View File
@@ -1,33 +1,29 @@
import html.entities
import re
import unicodedata
import warnings
from gzip import GzipFile
from gzip import compress as gzip_compress
from io import BytesIO
from django.core.exceptions import SuspiciousFileOperation
from django.utils.deprecation import RemovedInDjango40Warning
from django.utils.functional import SimpleLazyObject, keep_lazy_text, lazy
from django.utils.regex_helper import _lazy_re_compile
from django.utils.translation import gettext as _
from django.utils.translation import gettext_lazy, pgettext
from django.utils.translation import gettext as _, gettext_lazy, pgettext
@keep_lazy_text
def capfirst(x):
"""Capitalize the first letter of a string."""
if not x:
return x
if not isinstance(x, str):
x = str(x)
return x[0].upper() + x[1:]
return x and str(x)[0].upper() + str(x)[1:]
# Set up regular expressions
re_words = _lazy_re_compile(r"<[^>]+?>|([^<>\s]+)", re.S)
re_chars = _lazy_re_compile(r"<[^>]+?>|(.)", re.S)
re_tag = _lazy_re_compile(r"<(/)?(\S+?)(?:(\s*/)|\s.*?)?>", re.S)
re_newlines = _lazy_re_compile(r"\r\n|\r") # Used in normalize_newlines
re_camel_case = _lazy_re_compile(r"(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))")
re_words = _lazy_re_compile(r'<[^>]+?>|([^<>\s]+)', re.S)
re_chars = _lazy_re_compile(r'<[^>]+?>|(.)', re.S)
re_tag = _lazy_re_compile(r'<(/)?(\S+?)(?:(\s*/)|\s.*?)?>', re.S)
re_newlines = _lazy_re_compile(r'\r\n|\r') # Used in normalize_newlines
re_camel_case = _lazy_re_compile(r'(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))')
@keep_lazy_text
@@ -42,49 +38,46 @@ def wrap(text, width):
Don't wrap long words, thus the output text may have lines longer than
``width``.
"""
def _generator():
for line in text.splitlines(True): # True keeps trailing linebreaks
max_width = min((line.endswith("\n") and width + 1 or width), width)
max_width = min((line.endswith('\n') and width + 1 or width), width)
while len(line) > max_width:
space = line[: max_width + 1].rfind(" ") + 1
space = line[:max_width + 1].rfind(' ') + 1
if space == 0:
space = line.find(" ") + 1
space = line.find(' ') + 1
if space == 0:
yield line
line = ""
line = ''
break
yield "%s\n" % line[: space - 1]
yield '%s\n' % line[:space - 1]
line = line[space:]
max_width = min((line.endswith("\n") and width + 1 or width), width)
max_width = min((line.endswith('\n') and width + 1 or width), width)
if line:
yield line
return "".join(_generator())
return ''.join(_generator())
class Truncator(SimpleLazyObject):
"""
An object used to truncate text, either by characters or words.
"""
def __init__(self, text):
super().__init__(lambda: str(text))
def add_truncation_text(self, text, truncate=None):
if truncate is None:
truncate = pgettext(
"String to return when truncating text", "%(truncated_text)s"
)
if "%(truncated_text)s" in truncate:
return truncate % {"truncated_text": text}
'String to return when truncating text',
'%(truncated_text)s')
if '%(truncated_text)s' in truncate:
return truncate % {'truncated_text': text}
# The truncation text didn't contain the %(truncated_text)s string
# replacement argument so just append it to the text.
if text.endswith(truncate):
# But don't append the truncation text if the current text already
# ends in this.
return text
return "%s%s" % (text, truncate)
return '%s%s' % (text, truncate)
def chars(self, num, truncate=None, html=False):
"""
@@ -96,11 +89,11 @@ class Truncator(SimpleLazyObject):
"""
self._setup()
length = int(num)
text = unicodedata.normalize("NFC", self._wrapped)
text = unicodedata.normalize('NFC', self._wrapped)
# Calculate the length to truncate to (max length - end_text length)
truncate_len = length
for char in self.add_truncation_text("", truncate):
for char in self.add_truncation_text('', truncate):
if not unicodedata.combining(char):
truncate_len -= 1
if truncate_len == 0:
@@ -123,7 +116,8 @@ class Truncator(SimpleLazyObject):
end_index = i
if s_len > length:
# Return the truncated string
return self.add_truncation_text(text[: end_index or 0], truncate)
return self.add_truncation_text(text[:end_index or 0],
truncate)
# Return the original string since no truncation was necessary
return text
@@ -149,8 +143,8 @@ class Truncator(SimpleLazyObject):
words = self._wrapped.split()
if len(words) > length:
words = words[:length]
return self.add_truncation_text(" ".join(words), truncate)
return " ".join(words)
return self.add_truncation_text(' '.join(words), truncate)
return ' '.join(words)
def _truncate_html(self, length, truncate, text, truncate_len, words):
"""
@@ -161,18 +155,11 @@ class Truncator(SimpleLazyObject):
Preserve newlines in the HTML.
"""
if words and length <= 0:
return ""
return ''
html4_singlets = (
"br",
"col",
"link",
"base",
"img",
"param",
"area",
"hr",
"input",
'br', 'col', 'link', 'base', 'img',
'param', 'area', 'hr', 'input'
)
# Count non-HTML chars/words and keep note of open tags
@@ -214,7 +201,7 @@ class Truncator(SimpleLazyObject):
else:
# SGML: An end tag closes, back to the matching start tag,
# all unclosed intervening start tags with omitted end tags
open_tags = open_tags[i + 1 :]
open_tags = open_tags[i + 1:]
else:
# Add it to the start of the open tags list
open_tags.insert(0, tagname)
@@ -222,12 +209,12 @@ class Truncator(SimpleLazyObject):
if current_len <= length:
return text
out = text[:end_text_pos]
truncate_text = self.add_truncation_text("", truncate)
truncate_text = self.add_truncation_text('', truncate)
if truncate_text:
out += truncate_text
# Close any tags still open
for tag in open_tags:
out += "</%s>" % tag
out += '</%s>' % tag
# Return string
return out
@@ -242,15 +229,15 @@ def get_valid_filename(name):
>>> get_valid_filename("john's portrait in 2004.jpg")
'johns_portrait_in_2004.jpg'
"""
s = str(name).strip().replace(" ", "_")
s = re.sub(r"(?u)[^-\w.]", "", s)
if s in {"", ".", ".."}:
s = str(name).strip().replace(' ', '_')
s = re.sub(r'(?u)[^-\w.]', '', s)
if s in {'', '.', '..'}:
raise SuspiciousFileOperation("Could not derive file name from '%s'" % name)
return s
@keep_lazy_text
def get_text_list(list_, last_word=gettext_lazy("or")):
def get_text_list(list_, last_word=gettext_lazy('or')):
"""
>>> get_text_list(['a', 'b', 'c', 'd'])
'a, b, c or d'
@@ -264,59 +251,40 @@ def get_text_list(list_, last_word=gettext_lazy("or")):
''
"""
if not list_:
return ""
return ''
if len(list_) == 1:
return str(list_[0])
return "%s %s %s" % (
return '%s %s %s' % (
# Translators: This string is used as a separator between list elements
_(", ").join(str(i) for i in list_[:-1]),
str(last_word),
str(list_[-1]),
_(', ').join(str(i) for i in list_[:-1]), str(last_word), str(list_[-1])
)
@keep_lazy_text
def normalize_newlines(text):
"""Normalize CRLF and CR newlines to just LF."""
return re_newlines.sub("\n", str(text))
return re_newlines.sub('\n', str(text))
@keep_lazy_text
def phone2numeric(phone):
"""Convert a phone number with letters into its numeric equivalent."""
char2number = {
"a": "2",
"b": "2",
"c": "2",
"d": "3",
"e": "3",
"f": "3",
"g": "4",
"h": "4",
"i": "4",
"j": "5",
"k": "5",
"l": "5",
"m": "6",
"n": "6",
"o": "6",
"p": "7",
"q": "7",
"r": "7",
"s": "7",
"t": "8",
"u": "8",
"v": "8",
"w": "9",
"x": "9",
"y": "9",
"z": "9",
'a': '2', 'b': '2', 'c': '2', 'd': '3', 'e': '3', 'f': '3', 'g': '4',
'h': '4', 'i': '4', 'j': '5', 'k': '5', 'l': '5', 'm': '6', 'n': '6',
'o': '6', 'p': '7', 'q': '7', 'r': '7', 's': '7', 't': '8', 'u': '8',
'v': '8', 'w': '9', 'x': '9', 'y': '9', 'z': '9',
}
return "".join(char2number.get(c, c) for c in phone.lower())
return ''.join(char2number.get(c, c) for c in phone.lower())
# From http://www.xhaus.com/alan/python/httpcomp.html#gzip
# Used with permission.
def compress_string(s):
return gzip_compress(s, compresslevel=6, mtime=0)
zbuf = BytesIO()
with GzipFile(mode='wb', compresslevel=6, fileobj=zbuf, mtime=0) as zfile:
zfile.write(s)
return zbuf.getvalue()
class StreamingBuffer(BytesIO):
@@ -330,7 +298,7 @@ class StreamingBuffer(BytesIO):
# Like compress_string, but for iterators of strings.
def compress_sequence(sequence):
buf = StreamingBuffer()
with GzipFile(mode="wb", compresslevel=6, fileobj=buf, mtime=0) as zfile:
with GzipFile(mode='wb', compresslevel=6, fileobj=buf, mtime=0) as zfile:
# Output headers...
yield buf.read()
for item in sequence:
@@ -343,8 +311,7 @@ def compress_sequence(sequence):
# Expression to match some_token and some_token="with spaces" (and similarly
# for single-quoted strings).
smart_split_re = _lazy_re_compile(
r"""
smart_split_re = _lazy_re_compile(r"""
((?:
[^\s'"]*
(?:
@@ -352,9 +319,7 @@ smart_split_re = _lazy_re_compile(
[^\s'"]*
)+
) | \S+)
""",
re.VERBOSE,
)
""", re.VERBOSE)
def smart_split(text):
@@ -378,10 +343,10 @@ def smart_split(text):
def _replace_entity(match):
text = match[1]
if text[0] == "#":
if text[0] == '#':
text = text[1:]
try:
if text[0] in "xX":
if text[0] in 'xX':
c = int(text[1:], 16)
else:
c = int(text)
@@ -398,6 +363,16 @@ def _replace_entity(match):
_entity_re = _lazy_re_compile(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));")
@keep_lazy_text
def unescape_entities(text):
warnings.warn(
'django.utils.text.unescape_entities() is deprecated in favor of '
'html.unescape().',
RemovedInDjango40Warning, stacklevel=2,
)
return _entity_re.sub(_replace_entity, str(text))
@keep_lazy_text
def unescape_string_literal(s):
r"""
@@ -416,7 +391,7 @@ def unescape_string_literal(s):
if s[0] not in "\"'" or s[-1] != s[0]:
raise ValueError("Not a string literal: %r" % s)
quote = s[0]
return s[1:-1].replace(r"\%s" % quote, quote).replace(r"\\", "\\")
return s[1:-1].replace(r'\%s' % quote, quote).replace(r'\\', '\\')
@keep_lazy_text
@@ -429,22 +404,18 @@ def slugify(value, allow_unicode=False):
"""
value = str(value)
if allow_unicode:
value = unicodedata.normalize("NFKC", value)
value = unicodedata.normalize('NFKC', value)
else:
value = (
unicodedata.normalize("NFKD", value)
.encode("ascii", "ignore")
.decode("ascii")
)
value = re.sub(r"[^\w\s-]", "", value.lower())
return re.sub(r"[-\s]+", "-", value).strip("-_")
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')
value = re.sub(r'[^\w\s-]', '', value.lower())
return re.sub(r'[-\s]+', '-', value).strip('-_')
def camel_case_to_spaces(value):
"""
Split CamelCase and convert to lowercase. Strip surrounding whitespace.
"""
return re_camel_case.sub(r" \1", value).strip().lower()
return re_camel_case.sub(r' \1', value).strip().lower()
def _format_lazy(format_string, *args, **kwargs):