Skip to content

Commit

Permalink
format using default configuration
Browse files Browse the repository at this point in the history
This lets us "normalize" CPython source code so that we can now reformat
just the code snippets. That in turn will let us look at the code
snippet formatting diff more carefully.
  • Loading branch information
BurntSushi committed Nov 22, 2023
1 parent 1619f43 commit b911e9a
Show file tree
Hide file tree
Showing 1,668 changed files with 268,585 additions and 209,276 deletions.
533 changes: 278 additions & 255 deletions Doc/conf.py

Large diffs are not rendered by default.

13 changes: 6 additions & 7 deletions Doc/includes/dbpickle.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
# Simple class representing a record in our database.
MemoRecord = namedtuple("MemoRecord", "key, task")

class DBPickler(pickle.Pickler):

class DBPickler(pickle.Pickler):
def persistent_id(self, obj):
# Instead of pickling MemoRecord as a regular class instance, we emit a
# persistent ID.
Expand All @@ -24,7 +24,6 @@ def persistent_id(self, obj):


class DBUnpickler(pickle.Unpickler):

def __init__(self, file, connection):
super().__init__(file)
self.connection = connection
Expand Down Expand Up @@ -55,10 +54,10 @@ def main():
cursor = conn.cursor()
cursor.execute("CREATE TABLE memos(key INTEGER PRIMARY KEY, task TEXT)")
tasks = (
'give food to fish',
'prepare group meeting',
'fight with a zebra',
)
"give food to fish",
"prepare group meeting",
"fight with a zebra",
)
for task in tasks:
cursor.execute("INSERT INTO memos VALUES(NULL, ?)", (task,))

Expand All @@ -83,5 +82,5 @@ def main():
pprint.pprint(memos)


if __name__ == '__main__':
if __name__ == "__main__":
main()
61 changes: 41 additions & 20 deletions Doc/includes/diff.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,27 +10,41 @@
import sys, os, difflib, argparse
from datetime import datetime, timezone


def file_mtime(path):
t = datetime.fromtimestamp(os.stat(path).st_mtime,
timezone.utc)
t = datetime.fromtimestamp(os.stat(path).st_mtime, timezone.utc)
return t.astimezone().isoformat()

def main():

def main():
parser = argparse.ArgumentParser()
parser.add_argument('-c', action='store_true', default=False,
help='Produce a context format diff (default)')
parser.add_argument('-u', action='store_true', default=False,
help='Produce a unified format diff')
parser.add_argument('-m', action='store_true', default=False,
help='Produce HTML side by side diff '
'(can use -c and -l in conjunction)')
parser.add_argument('-n', action='store_true', default=False,
help='Produce a ndiff format diff')
parser.add_argument('-l', '--lines', type=int, default=3,
help='Set number of context lines (default 3)')
parser.add_argument('fromfile')
parser.add_argument('tofile')
parser.add_argument(
"-c",
action="store_true",
default=False,
help="Produce a context format diff (default)",
)
parser.add_argument(
"-u", action="store_true", default=False, help="Produce a unified format diff"
)
parser.add_argument(
"-m",
action="store_true",
default=False,
help="Produce HTML side by side diff " "(can use -c and -l in conjunction)",
)
parser.add_argument(
"-n", action="store_true", default=False, help="Produce a ndiff format diff"
)
parser.add_argument(
"-l",
"--lines",
type=int,
default=3,
help="Set number of context lines (default 3)",
)
parser.add_argument("fromfile")
parser.add_argument("tofile")
options = parser.parse_args()

n = options.lines
Expand All @@ -45,15 +59,22 @@ def main():
tolines = tf.readlines()

if options.u:
diff = difflib.unified_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n)
diff = difflib.unified_diff(
fromlines, tolines, fromfile, tofile, fromdate, todate, n=n
)
elif options.n:
diff = difflib.ndiff(fromlines, tolines)
elif options.m:
diff = difflib.HtmlDiff().make_file(fromlines,tolines,fromfile,tofile,context=options.c,numlines=n)
diff = difflib.HtmlDiff().make_file(
fromlines, tolines, fromfile, tofile, context=options.c, numlines=n
)
else:
diff = difflib.context_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n)
diff = difflib.context_diff(
fromlines, tolines, fromfile, tofile, fromdate, todate, n=n
)

sys.stdout.writelines(diff)

if __name__ == '__main__':

if __name__ == "__main__":
main()
32 changes: 19 additions & 13 deletions Doc/includes/email-alternative.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,25 +8,30 @@

# Create the base text message.
msg = EmailMessage()
msg['Subject'] = "Pourquoi pas des asperges pour ce midi ?"
msg['From'] = Address("Pepé Le Pew", "pepe", "example.com")
msg['To'] = (Address("Penelope Pussycat", "penelope", "example.com"),
Address("Fabrette Pussycat", "fabrette", "example.com"))
msg.set_content("""\
msg["Subject"] = "Pourquoi pas des asperges pour ce midi ?"
msg["From"] = Address("Pepé Le Pew", "pepe", "example.com")
msg["To"] = (
Address("Penelope Pussycat", "penelope", "example.com"),
Address("Fabrette Pussycat", "fabrette", "example.com"),
)
msg.set_content(
"""\
Salut!
Cette recette [1] sera sûrement un très bon repas.
[1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718
--Pepé
""")
"""
)

# Add the html version. This converts the message into a multipart/alternative
# container, with the original text message as the first part and the new html
# message as the second part.
asparagus_cid = make_msgid()
msg.add_alternative("""\
msg.add_alternative(
"""\
<html>
<head></head>
<body>
Expand All @@ -39,18 +44,19 @@
<img src="cid:{asparagus_cid}" />
</body>
</html>
""".format(asparagus_cid=asparagus_cid[1:-1]), subtype='html')
""".format(asparagus_cid=asparagus_cid[1:-1]),
subtype="html",
)
# note that we needed to peel the <> off the msgid for use in the html.

# Now add the related image to the html part.
with open("roasted-asparagus.jpg", 'rb') as img:
msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg',
cid=asparagus_cid)
with open("roasted-asparagus.jpg", "rb") as img:
msg.get_payload()[1].add_related(img.read(), "image", "jpeg", cid=asparagus_cid)

# Make a local copy of what we are going to send.
with open('outgoing.msg', 'wb') as f:
with open("outgoing.msg", "wb") as f:
f.write(bytes(msg))

# Send the message via local SMTP server.
with smtplib.SMTP('localhost') as s:
with smtplib.SMTP("localhost") as s:
s.send_message(msg)
75 changes: 45 additions & 30 deletions Doc/includes/email-dir.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import os
import smtplib

# For guessing MIME type based on file name extension
import mimetypes

Expand All @@ -14,37 +15,52 @@


def main():
parser = ArgumentParser(description="""\
parser = ArgumentParser(
description="""\
Send the contents of a directory as a MIME message.
Unless the -o option is given, the email is sent by forwarding to your local
SMTP server, which then does the normal delivery process. Your local machine
must be running an SMTP server.
""")
parser.add_argument('-d', '--directory',
help="""Mail the contents of the specified directory,
"""
)
parser.add_argument(
"-d",
"--directory",
help="""Mail the contents of the specified directory,
otherwise use the current directory. Only the regular
files in the directory are sent, and we don't recurse to
subdirectories.""")
parser.add_argument('-o', '--output',
metavar='FILE',
help="""Print the composed message to FILE instead of
sending the message to the SMTP server.""")
parser.add_argument('-s', '--sender', required=True,
help='The value of the From: header (required)')
parser.add_argument('-r', '--recipient', required=True,
action='append', metavar='RECIPIENT',
default=[], dest='recipients',
help='A To: header value (at least one required)')
subdirectories.""",
)
parser.add_argument(
"-o",
"--output",
metavar="FILE",
help="""Print the composed message to FILE instead of
sending the message to the SMTP server.""",
)
parser.add_argument(
"-s", "--sender", required=True, help="The value of the From: header (required)"
)
parser.add_argument(
"-r",
"--recipient",
required=True,
action="append",
metavar="RECIPIENT",
default=[],
dest="recipients",
help="A To: header value (at least one required)",
)
args = parser.parse_args()
directory = args.directory
if not directory:
directory = '.'
directory = "."
# Create the message
msg = EmailMessage()
msg['Subject'] = f'Contents of directory {os.path.abspath(directory)}'
msg['To'] = ', '.join(args.recipients)
msg['From'] = args.sender
msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'
msg["Subject"] = f"Contents of directory {os.path.abspath(directory)}"
msg["To"] = ", ".join(args.recipients)
msg["From"] = args.sender
msg.preamble = "You will not see this in a MIME-aware mail reader.\n"

for filename in os.listdir(directory):
path = os.path.join(directory, filename)
Expand All @@ -57,21 +73,20 @@ def main():
if ctype is None or encoding is not None:
# No guess could be made, or the file is encoded (compressed), so
# use a generic bag-of-bits type.
ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
with open(path, 'rb') as fp:
msg.add_attachment(fp.read(),
maintype=maintype,
subtype=subtype,
filename=filename)
ctype = "application/octet-stream"
maintype, subtype = ctype.split("/", 1)
with open(path, "rb") as fp:
msg.add_attachment(
fp.read(), maintype=maintype, subtype=subtype, filename=filename
)
# Now send or store the message
if args.output:
with open(args.output, 'wb') as fp:
with open(args.output, "wb") as fp:
fp.write(msg.as_bytes(policy=SMTP))
else:
with smtplib.SMTP('localhost') as s:
with smtplib.SMTP("localhost") as s:
s.send_message(msg)


if __name__ == '__main__':
if __name__ == "__main__":
main()
23 changes: 12 additions & 11 deletions Doc/includes/email-headers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Import the email modules we'll need
#from email.parser import BytesParser
# from email.parser import BytesParser
from email.parser import Parser
from email.policy import default

Expand All @@ -9,17 +9,18 @@

# Or for parsing headers in a string (this is an uncommon operation), use:
headers = Parser(policy=default).parsestr(
'From: Foo Bar <user@example.com>\n'
'To: <someone_else@example.com>\n'
'Subject: Test message\n'
'\n'
'Body would go here\n')
"From: Foo Bar <user@example.com>\n"
"To: <someone_else@example.com>\n"
"Subject: Test message\n"
"\n"
"Body would go here\n"
)

# Now the header items can be accessed as a dictionary:
print('To: {}'.format(headers['to']))
print('From: {}'.format(headers['from']))
print('Subject: {}'.format(headers['subject']))
print("To: {}".format(headers["to"]))
print("From: {}".format(headers["from"]))
print("Subject: {}".format(headers["subject"]))

# You can also access the parts of the addresses:
print('Recipient username: {}'.format(headers['to'].addresses[0].username))
print('Sender name: {}'.format(headers['from'].addresses[0].display_name))
print("Recipient username: {}".format(headers["to"].addresses[0].username))
print("Sender name: {}".format(headers["from"].addresses[0].display_name))
15 changes: 7 additions & 8 deletions Doc/includes/email-mime.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,20 @@

# Create the container email message.
msg = EmailMessage()
msg['Subject'] = 'Our family reunion'
msg["Subject"] = "Our family reunion"
# me == the sender's email address
# family = the list of all recipients' email addresses
msg['From'] = me
msg['To'] = ', '.join(family)
msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'
msg["From"] = me
msg["To"] = ", ".join(family)
msg.preamble = "You will not see this in a MIME-aware mail reader.\n"

# Open the files in binary mode. You can also omit the subtype
# if you want MIMEImage to guess it.
for file in pngfiles:
with open(file, 'rb') as fp:
with open(file, "rb") as fp:
img_data = fp.read()
msg.add_attachment(img_data, maintype='image',
subtype='png')
msg.add_attachment(img_data, maintype="image", subtype="png")

# Send the email via our own SMTP server.
with smtplib.SMTP('localhost') as s:
with smtplib.SMTP("localhost") as s:
s.send_message(msg)
Loading

0 comments on commit b911e9a

Please sign in to comment.