Blacken all Python files

Using the black code reformatter, pass it over all our Python files.
This allows for a consistent style across the code base.

Exception: lumps/dmxgus/stats.py, for readability.
This commit is contained in:
Mike Swanson 2019-09-04 19:36:23 -07:00
parent 6b486b6332
commit 4701d8f351
30 changed files with 2528 additions and 2102 deletions

View file

@ -7,11 +7,12 @@ import glob
import struct
import png
class Graphic(object):
def __init__(self, filepath):
self.filepath = filepath
self.filename = path.split(filepath)[1]
self.name = path.splitext(self.filename)[0].upper().replace('^', '\\')
self.name = path.splitext(self.filename)[0].upper().replace("^", "\\")
self.has_offset = False
self.get_png_offset()
@ -22,15 +23,20 @@ class Graphic(object):
self.xoffset, self.yoffset = struct.unpack(">II", chunk[1])
self.has_offset = True
def main():
dirname = path.split(path.abspath(__file__))[0]
graphics = []
files = []
if len(sys.argv) < 2:
print("This script takes the offsets stored in the \"grAb\" chunk of " +
"the specified PNGs and adjusts the graphics offsets in the build_cfg file.\n")
print(
'This script takes the offsets stored in the "grAb" chunk of '
+ "the specified PNGs and adjusts the graphics offsets in the build_cfg file.\n"
)
print("Usage:\n\t fix-sprite-offsets <names> [names] [...]\n")
print("example: \n\tfix-sprite-offsets sprites/vilea1.png sprites/vileb1.png")
print(
"example: \n\tfix-sprite-offsets sprites/vilea1.png sprites/vileb1.png"
)
print("You can also use wildcards:")
print("\t fix-sprite-offsets sprites/vile*.png")
exit()
@ -40,7 +46,7 @@ def main():
for filepath in files:
if not path.isfile(filepath):
print("Could not find" + filepath +", skipping...")
print("Could not find" + filepath + ", skipping...")
elif path.splitext(filepath)[1] == ".png":
graphics.append(Graphic(filepath))
for graphic in graphics:
@ -56,7 +62,11 @@ def main():
if graphic.has_offset is True:
thing = line.split()
if len(thing) > 0 and thing[0] == graphic.name:
new_string = "%s\t%i\t%i" %(graphic.name, graphic.xoffset, graphic.yoffset)
new_string = "%s\t%i\t%i" % (
graphic.name,
graphic.xoffset,
graphic.yoffset,
)
comments = line.split(";")
if len(comments) > 1:
new_string += "\t;" + "".join(comments[1:])
@ -72,5 +82,6 @@ def main():
f.writelines(newlines)
f.close()
if __name__ == '__main__':
if __name__ == "__main__":
main()

View file

@ -22,16 +22,16 @@ import sys
# Globals
args = {} # Command line arguments.
error_count = 0
fixes_needed = 0
freedoom_1_re = re.compile(r"^C(\d)M(\d)$") # FD #1 maps
freedoom_dm_re = re.compile(r"^DM(\d\d)$") # FD DM maps
header_shown = False
ignored_wads = set(["dummy.wad", "test_levels.wad"])
last_error = None
map_name_re = re.compile(r"^((E\dM\d)|(MAP\d\d))$")
output_line = "%-17s %-9s %-7s %s"
args = {} # Command line arguments.
error_count = 0
fixes_needed = 0
freedoom_1_re = re.compile(r"^C(\d)M(\d)$") # FD #1 maps
freedoom_dm_re = re.compile(r"^DM(\d\d)$") # FD DM maps
header_shown = False
ignored_wads = set(["dummy.wad", "test_levels.wad"])
last_error = None
map_name_re = re.compile(r"^((E\dM\d)|(MAP\d\d))$")
output_line = "%-17s %-9s %-7s %s"
# Functions
@ -44,6 +44,7 @@ def error(msg):
if msg:
error_count += 1
# Given WAD path 'wad' return the expected map name as a function of the
# filename.
def get_expected_map_name(wad):
@ -61,31 +62,51 @@ def get_expected_map_name(wad):
else:
return None
# Parse the command line arguments and store the result in 'args'.
def parse_args():
global args
parser = argparse.ArgumentParser(
description="Fix map names in WAD files.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
# The following is sorted by long argument.
parser.add_argument("-f", "--force", action="store_true",
help="Force. Fix map name regardless of the existing map name.")
parser.add_argument("-q", "--quiet", action="store_true",
help="Quiet (minimum output).")
parser.add_argument("-r", "--recursive", action="store_true",
help="Recurse into directories.")
parser.add_argument("-t", "--test", action="store_true",
help="Test mode. Don't make any changes.")
parser.add_argument("paths", metavar="PATH", nargs="+",
help="WAD paths, files and directories.")
parser.add_argument(
"-f",
"--force",
action="store_true",
help="Force. Fix map name regardless of the existing map name.",
)
parser.add_argument(
"-q", "--quiet", action="store_true", help="Quiet (minimum output)."
)
parser.add_argument(
"-r",
"--recursive",
action="store_true",
help="Recurse into directories.",
)
parser.add_argument(
"-t",
"--test",
action="store_true",
help="Test mode. Don't make any changes.",
)
parser.add_argument(
"paths",
metavar="PATH",
nargs="+",
help="WAD paths, files and directories.",
)
args = parser.parse_args()
return args
# Process path 'path' which is at depth 'depth'. If 'depth' is 0 then this is
# a top level path passed in on the command line.
def process_path(path, depth):
@ -103,11 +124,13 @@ def process_path(path, depth):
if (not depth) or path.lower().endswith(".wad"):
process_wad(path)
# Process the paths passed in on the command line.
def process_paths():
for path in args.paths:
process_path(path, 0)
# Process WAD path 'wad'.
def process_wad(wad):
global header_shown
@ -141,7 +164,8 @@ def process_wad(wad):
# The first lump in the directory, which should be the 0 byte map
# name one.
lump_data_offset, lump_size, lump_name = struct.unpack(
"<II8s", fhand.read(16))
"<II8s", fhand.read(16)
)
if not isinstance(lump_name, str):
# lump_name is bytes in Python 3.
lump_name = lump_name.decode("UTF-8")
@ -149,8 +173,11 @@ def process_wad(wad):
lump_name = lump_name.partition("\0")[0]
if lump_size:
# The first lump should be 0 bytes.
error("First lump size non-zero with " + str(lump_size) +
" bytes")
error(
"First lump size non-zero with "
+ str(lump_size)
+ " bytes"
)
elif not (args.force or map_name_re.match(lump_name)):
# A sanity check to make sure we read the right part.
error("Actual name unexpected")
@ -166,8 +193,12 @@ def process_wad(wad):
except IOError as err:
# Probably the WAD file couldn't be open for read (test) or read and
# write (default).
error("Unable to open for read" + (
"" if args.test else " and write") + ": " + str(err))
error(
"Unable to open for read"
+ ("" if args.test else " and write")
+ ": "
+ str(err)
)
except struct.error as err:
# This is probably the reason since seek silently succeeds even when
# the location is not possible, but then unpack fails due to the short
@ -179,26 +210,31 @@ def process_wad(wad):
if (last_error or fix_needed) and not args.quiet:
# Map None to "".
expected_name, lump_name, last_error = [x if x else "" for x in (
expected_name, lump_name, last_error)]
expected_name, lump_name, last_error = [
x if x else "" for x in (expected_name, lump_name, last_error)
]
if not header_shown:
print(output_line % ("WAD", "Expected", "Actual", "Error"))
print(output_line % ("---", "--------", "------", "-----"))
header_shown = True
print(output_line % (wad, expected_name, lump_name, last_error))
# Summarize what happened, and then exit with the appropriate exit code.
def summarize():
if not args.quiet:
if fixes_needed:
print("\n%s %d WADs with the incorrect map name." % (
"Found" if args.test else "Fixed", fixes_needed))
print(
"\n%s %d WADs with the incorrect map name."
% ("Found" if args.test else "Fixed", fixes_needed)
)
else:
print("\nAll WADs had the correct map name.")
if error_count:
print("There were %d errors." % error_count)
sys.exit(1 if (error_count or (args.test and fixes_needed)) else 0)
# Main
parse_args()

View file

@ -12,15 +12,16 @@ import sys
# expands or switches web host.
iwads = {
"freedm.wad": {
"description": "Deathmatch IWAD",
"name": "FreeDM"},
"freedm.wad": {"description": "Deathmatch IWAD", "name": "FreeDM"},
"freedoom1.wad": {
"description": "Ultimate Doom compatible IWAD",
"name": "Freedoom: Phase 1"},
"name": "Freedoom: Phase 1",
},
"freedoom2.wad": {
"description": "Doom II compatible IWAD",
"name": "Freedoom: Phase 2"}}
"name": "Freedoom: Phase 2",
},
}
# Find the version to generate JSON for:
@ -33,7 +34,7 @@ json_file = os.getenv("JSON")
if version is None:
sys.stderr.write("Version is not specified for release\n")
sys.exit(1)
if version[0] is 'v':
if version[0] is "v":
# Strip the leading 'v' from versioning
version = version[1:]
@ -50,11 +51,29 @@ with open("wads/freedoom2.wad", "rb") as f:
with open("wads/freedm.wad", "rb") as f:
iwads["freedm.wad"]["md5"] = hashlib.md5(f.read()).hexdigest()
iwads["freedoom1.wad"]["url"] = "https://github.com/freedoom/freedoom/releases/download/v" + version + "/freedoom-" + version + ".zip"
iwads["freedoom1.wad"]["url"] = (
"https://github.com/freedoom/freedoom/releases/download/v"
+ version
+ "/freedoom-"
+ version
+ ".zip"
)
iwads["freedoom1.wad"]["version"] = version
iwads["freedoom2.wad"]["url"] = "https://github.com/freedoom/freedoom/releases/download/v" + version + "/freedoom-" + version + ".zip"
iwads["freedoom2.wad"]["url"] = (
"https://github.com/freedoom/freedoom/releases/download/v"
+ version
+ "/freedoom-"
+ version
+ ".zip"
)
iwads["freedoom2.wad"]["version"] = version
iwads["freedm.wad"]["url"] = "https://github.com/freedoom/freedoom/releases/download/v" + version + "/freedm-" + version + ".zip"
iwads["freedm.wad"]["url"] = (
"https://github.com/freedoom/freedoom/releases/download/v"
+ version
+ "/freedm-"
+ version
+ ".zip"
)
iwads["freedm.wad"]["version"] = version
with open(json_file, "w") as f:

View file

@ -6,15 +6,17 @@ import sys
# Documentation files included with distributions.
GAME_NAME=sys.argv[1]
FILES=sys.argv[2:]
GAME_NAME = sys.argv[1]
FILES = sys.argv[2:]
# Run a command, displaying it before executing it.
def run_command(command):
print("> " + command)
os.system(command)
# Find the version to build:
version = os.getenv("VERSION")
@ -22,7 +24,7 @@ version = os.getenv("VERSION")
if version is None:
sys.stderr.write("Version not specified for release\n")
sys.exit(1)
if version[0] is 'v':
if version[0] is "v":
# Strip the leading 'v' from versioning
version = version[1:]

View file

@ -10,65 +10,71 @@ import os
import re
import sys
PHASE1_MATCH_RE = re.compile(r'(e\dm\d)', re.I)
PHASE2_MATCH_RE = re.compile(r'(map\d\d)', re.I)
FREEDM_MATCH_RE = re.compile(r'(dm\d\d)', re.I)
PHASE1_MATCH_RE = re.compile(r"(e\dm\d)", re.I)
PHASE2_MATCH_RE = re.compile(r"(map\d\d)", re.I)
FREEDM_MATCH_RE = re.compile(r"(dm\d\d)", re.I)
def get_music_tracks():
"""Returns a dictionary mapping from MIDI file SHA1
"""Returns a dictionary mapping from MIDI file SHA1
to a list of game tracks that use that MIDI."""
result = {}
musics_path = os.path.join(os.path.dirname(sys.argv[0]), '../musics')
for mus in glob('%s/*.mid' % musics_path):
with open(mus, 'rb') as f:
contents = f.read()
m = hashlib.sha1()
m.update(contents)
digest = m.digest()
basename = os.path.basename(mus)
result.setdefault(digest, []).append(basename)
return result
result = {}
musics_path = os.path.join(os.path.dirname(sys.argv[0]), "../musics")
for mus in glob("%s/*.mid" % musics_path):
with open(mus, "rb") as f:
contents = f.read()
m = hashlib.sha1()
m.update(contents)
digest = m.digest()
basename = os.path.basename(mus)
result.setdefault(digest, []).append(basename)
return result
def get_prime_track(tracks):
"""Given a list of tracks that all use the same MIDI, find the
"""Given a list of tracks that all use the same MIDI, find the
"prime" one (the one that isn't a reuse/duplicate)."""
# We have almost all Phase 2 tracks fulfilled. So if the same
# track is used in Phase 1 and Phase 2, or Phase 2 and FreeDM,
# the Phase 2 track is probably the leader.
phase2_tracks = [x for x in tracks if PHASE2_MATCH_RE.search(x)]
if len(phase2_tracks) == 1:
return phase2_tracks[0]
# We have almost all Phase 2 tracks fulfilled. So if the same
# track is used in Phase 1 and Phase 2, or Phase 2 and FreeDM,
# the Phase 2 track is probably the leader.
phase2_tracks = [x for x in tracks if PHASE2_MATCH_RE.search(x)]
if len(phase2_tracks) == 1:
return phase2_tracks[0]
# FreeDM music has been hand-picked. So if it is used for both
# Phase 1 and FreeDM, assume it's probably a FreeDM track.
freedm_tracks = [x for x in tracks if FREEDM_MATCH_RE.search(x)]
if len(freedm_tracks) == 1:
return freedm_tracks[0]
# FreeDM music has been hand-picked. So if it is used for both
# Phase 1 and FreeDM, assume it's probably a FreeDM track.
freedm_tracks = [x for x in tracks if FREEDM_MATCH_RE.search(x)]
if len(freedm_tracks) == 1:
return freedm_tracks[0]
# We're out of options. Pick the first one in the list.
# print "Warning: Don't know which of %s is the leader." % tracks
return sorted(tracks)[0]
# We're out of options. Pick the first one in the list.
#print "Warning: Don't know which of %s is the leader." % tracks
return sorted(tracks)[0]
def find_missing_tracks(tracks):
"""Given a dictionary of tracks, get a list of "missing" tracks."""
result = []
for midi, tracks in tracks.items():
if len(tracks) < 2:
continue
prime_track = get_prime_track(tracks)
result.extend(x for x in tracks if x != prime_track)
return result
"""Given a dictionary of tracks, get a list of "missing" tracks."""
result = []
for midi, tracks in tracks.items():
if len(tracks) < 2:
continue
prime_track = get_prime_track(tracks)
result.extend(x for x in tracks if x != prime_track)
return result
def tracks_matching_regexp(tracks, regexp):
return set([x for x in tracks if regexp.search(x)])
return set([x for x in tracks if regexp.search(x)])
def print_report(title, tracks):
if len(tracks) == 0:
return
print(title)
for track in sorted(tracks):
print('\t%s' % track.replace('.mid', '').upper())
print('')
if len(tracks) == 0:
return
print(title)
for track in sorted(tracks):
print("\t%s" % track.replace(".mid", "").upper())
print("")
missing_tracks = set(find_missing_tracks(get_music_tracks()))
phase1_tracks = tracks_matching_regexp(missing_tracks, PHASE1_MATCH_RE)
@ -76,8 +82,8 @@ phase2_tracks = tracks_matching_regexp(missing_tracks, PHASE2_MATCH_RE)
freedm_tracks = tracks_matching_regexp(missing_tracks, FREEDM_MATCH_RE)
other_tracks = missing_tracks - phase1_tracks - phase2_tracks - freedm_tracks
print('=== Missing tracks (tracks currently using duplicates):\n')
print_report('Phase 1 tracks:', phase1_tracks)
print_report('Phase 2 tracks:', phase2_tracks)
print_report('FreeDM tracks:', freedm_tracks)
print_report('Other tracks:', other_tracks)
print("=== Missing tracks (tracks currently using duplicates):\n")
print_report("Phase 1 tracks:", phase1_tracks)
print_report("Phase 2 tracks:", phase2_tracks)
print_report("FreeDM tracks:", freedm_tracks)
print_report("Other tracks:", other_tracks)