5395: Require Python 3.6 (f-strings) and fix pylints r=heinrich5991 a=def-

So far only done scripts directory, will do the rest if this is
considered good

<!-- What is the motivation for the changes of this pull request -->

## Checklist

- [ ] Tested the change ingame
- [ ] Provided screenshots if it is a visual change
- [ ] Tested in combination with possibly related configuration options
- [ ] Written a unit test if it works standalone, system.c especially
- [ ] Considered possible null pointers and out of bounds array indexing
- [x] Changed no physics that affect existing maps
- [ ] Tested the change with [ASan+UBSan or valgrind's memcheck](https://github.com/ddnet/ddnet/#using-addresssanitizer--undefinedbehavioursanitizer-or-valgrinds-memcheck) (optional)


Co-authored-by: def <dennis@felsin9.de>
Co-authored-by: Dennis Felsing <dennis@felsin9.de>
This commit is contained in:
bors[bot] 2022-07-27 11:03:48 +00:00 committed by GitHub
commit b4d6a988de
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
28 changed files with 329 additions and 337 deletions

View file

@ -19,7 +19,8 @@ jobs:
- name: Prepare - name: Prepare
run: | run: |
sudo apt-get update -y sudo apt-get update -y
sudo apt-get install clang-format imagemagick ddnet-tools shellcheck pkg-config cmake ninja-build libfreetype6-dev libnotify-dev libsdl2-dev libsqlite3-dev libavcodec-dev libavformat-dev libavutil-dev libswresample-dev libswscale-dev libx264-dev pylint3 python3-clang libvulkan-dev glslang-tools spirv-tools -y sudo apt-get install clang-format imagemagick ddnet-tools shellcheck pkg-config cmake ninja-build libfreetype6-dev libnotify-dev libsdl2-dev libsqlite3-dev libavcodec-dev libavformat-dev libavutil-dev libswresample-dev libswscale-dev libx264-dev python3-clang libvulkan-dev glslang-tools spirv-tools -y
pip3 install pylint
mkdir release mkdir release
cd release cd release
cmake -G Ninja -DCMAKE_BUILD_TYPE=Release -DDOWNLOAD_GTEST=OFF -DCMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE=. .. cmake -G Ninja -DCMAKE_BUILD_TYPE=Release -DDOWNLOAD_GTEST=OFF -DCMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE=. ..
@ -48,4 +49,4 @@ jobs:
- name: Pylint - name: Pylint
run: | run: |
pylint --version pylint --version
find . -type f -name "*.py" -not -path './ddnet-libs/*' -print0 | xargs -0 pylint find . -type f -name "*.py" -not -path './ddnet-libs/*' -not -path './googletest-src/*' -print0 | xargs -0 pylint

View file

@ -8,8 +8,8 @@ def create_enum_table(names, num):
lines = [] lines = []
lines += ["enum", "{"] lines += ["enum", "{"]
for name in names: for name in names:
lines += ["\t%s," % name] lines += [f"\t{name},"]
lines += ["\t%s" % num, "};"] lines += [f"\t{num}", "};"]
return lines return lines
@ -17,7 +17,7 @@ def create_flags_table(names):
lines = [] lines = []
lines += ["enum", "{"] lines += ["enum", "{"]
for i, name in enumerate(names): for i, name in enumerate(names):
lines += ["\t%s = 1<<%d," % (name, i)] lines += [f"\t{name} = 1<<{int(i)},"]
lines += ["};"] lines += ["};"]
return lines return lines
@ -25,10 +25,10 @@ def create_flags_table(names):
def EmitEnum(names, num): def EmitEnum(names, num):
print("enum") print("enum")
print("{") print("{")
print("\t%s=0," % names[0]) print(f"\t{names[0]}=0,")
for name in names[1:]: for name in names[1:]:
print("\t%s," % name) print(f"\t{name},")
print("\t%s" % num) print(f"\t{num}")
print("};") print("};")
@ -36,7 +36,7 @@ def EmitFlags(names):
print("enum") print("enum")
print("{") print("{")
for i, name in enumerate(names): for i, name in enumerate(names):
print("\t%s = 1<<%d," % (name, i)) print(f"\t{name} = 1<<{int(i)},")
print("};") print("};")
@ -48,12 +48,12 @@ def gen_network_header():
print(network.RawHeader) print(network.RawHeader)
for e in network.Enums: for e in network.Enums:
for line in create_enum_table(["%s_%s"%(e.name, v) for v in e.values], 'NUM_%sS'%e.name): # pylint: disable=E1101 for line in create_enum_table([f"{e.name}_{v}" for v in e.values], f'NUM_{e.name}S'): # pylint: disable=no-member
print(line) print(line)
print("") print("")
for e in network.Flags: for e in network.Flags:
for line in create_flags_table(["%s_%s" % (e.name, v) for v in e.values]): for line in create_flags_table([f"{e.name}_{v}" for v in e.values]):
print(line) print(line)
print("") print("")
@ -79,8 +79,8 @@ def gen_network_header():
print(line) print(line)
print("") print("")
EmitEnum(["SOUND_%s"%i.name.value.upper() for i in content.container.sounds.items], "NUM_SOUNDS") EmitEnum([f"SOUND_{i.name.value.upper()}" for i in content.container.sounds.items], "NUM_SOUNDS")
EmitEnum(["WEAPON_%s"%i.name.value.upper() for i in content.container.weapons.id.items], "NUM_WEAPONS") EmitEnum([f"WEAPON_{i.name.value.upper()}" for i in content.container.weapons.id.items], "NUM_WEAPONS")
print(""" print("""
class CNetObjHandler class CNetObjHandler
@ -160,37 +160,37 @@ int CNetObjHandler::ClampInt(const char *pErrorMsg, int Value, int Min, int Max)
lines = [] lines = []
lines += ["const char *CNetObjHandler::ms_apObjNames[] = {"] lines += ["const char *CNetObjHandler::ms_apObjNames[] = {"]
lines += ['\t"EX/UUID",'] lines += ['\t"EX/UUID",']
lines += ['\t"%s",' % o.name for o in network.Objects if o.ex is None] lines += [f'\t"{o.name}",' for o in network.Objects if o.ex is None]
lines += ['\t""', "};", ""] lines += ['\t""', "};", ""]
lines += ["const char *CNetObjHandler::ms_apExObjNames[] = {"] lines += ["const char *CNetObjHandler::ms_apExObjNames[] = {"]
lines += ['\t"invalid",'] lines += ['\t"invalid",']
lines += ['\t"%s",' % o.name for o in network.Objects if o.ex is not None] lines += [f'\t"{o.name}",' for o in network.Objects if o.ex is not None]
lines += ['\t""', "};", ""] lines += ['\t""', "};", ""]
lines += ["int CNetObjHandler::ms_aObjSizes[] = {"] lines += ["int CNetObjHandler::ms_aObjSizes[] = {"]
lines += ['\t0,'] lines += ['\t0,']
lines += ['\tsizeof(%s),' % o.struct_name for o in network.Objects if o.ex is None] lines += [f'\tsizeof({o.struct_name}),' for o in network.Objects if o.ex is None]
lines += ['\t0', "};", ""] lines += ['\t0', "};", ""]
lines += ["int CNetObjHandler::ms_aUnpackedObjSizes[] = {"] lines += ["int CNetObjHandler::ms_aUnpackedObjSizes[] = {"]
lines += ['\t16,'] lines += ['\t16,']
lines += ['\tsizeof(%s),' % o.struct_name for o in network.Objects if o.ex is None] lines += [f'\tsizeof({o.struct_name}),' for o in network.Objects if o.ex is None]
lines += ["};", ""] lines += ["};", ""]
lines += ["int CNetObjHandler::ms_aUnpackedExObjSizes[] = {"] lines += ["int CNetObjHandler::ms_aUnpackedExObjSizes[] = {"]
lines += ['\t0,'] lines += ['\t0,']
lines += ['\tsizeof(%s),' % o.struct_name for o in network.Objects if o.ex is not None] lines += [f'\tsizeof({o.struct_name}),' for o in network.Objects if o.ex is not None]
lines += ["};", ""] lines += ["};", ""]
lines += ['const char *CNetObjHandler::ms_apMsgNames[] = {'] lines += ['const char *CNetObjHandler::ms_apMsgNames[] = {']
lines += ['\t"invalid",'] lines += ['\t"invalid",']
lines += ['\t"%s",' % msg.name for msg in network.Messages if msg.ex is None] lines += [f'\t"{msg.name}",' for msg in network.Messages if msg.ex is None]
lines += ['\t""', "};", ""] lines += ['\t""', "};", ""]
lines += ['const char *CNetObjHandler::ms_apExMsgNames[] = {'] lines += ['const char *CNetObjHandler::ms_apExMsgNames[] = {']
lines += ['\t"invalid",'] lines += ['\t"invalid",']
lines += ['\t"%s",' % msg.name for msg in network.Messages if msg.ex is not None] lines += [f'\t"{msg.name}",' for msg in network.Messages if msg.ex is not None]
lines += ['\t""', "};", ""] lines += ['\t""', "};", ""]
for line in lines: for line in lines:
@ -332,7 +332,7 @@ bool CNetObjHandler::TeeHistorianRecordMsg(int Type)
empty = True empty = True
for msg in network.Messages: for msg in network.Messages:
if not msg.teehistorian: if not msg.teehistorian:
lines += ['\tcase %s:' % msg.enum_name] lines += [f'\tcase {msg.enum_name}:']
empty = False empty = False
if not empty: if not empty:
lines += ['\t\treturn false;'] lines += ['\t\treturn false;']
@ -355,7 +355,7 @@ void RegisterGameUuids(CUuidManager *pManager)
for item in network.Objects + network.Messages: for item in network.Objects + network.Messages:
if item.ex is not None: if item.ex is not None:
lines += ['\tpManager->RegisterName(%s, "%s");' % (item.enum_name, item.ex)] lines += [f'\tpManager->RegisterName({item.enum_name}, "{item.ex}");']
lines += [""" lines += ["""
RegisterMapItemTypeUuids(pManager); RegisterMapItemTypeUuids(pManager);
@ -384,9 +384,9 @@ def gen_common_content_header():
print('extern CDataContainer *g_pData;') print('extern CDataContainer *g_pData;')
# enums # enums
EmitEnum(["IMAGE_%s"%i.name.value.upper() for i in content.container.images.items], "NUM_IMAGES") EmitEnum([f"IMAGE_{i.name.value.upper()}" for i in content.container.images.items], "NUM_IMAGES")
EmitEnum(["ANIM_%s"%i.name.value.upper() for i in content.container.animations.items], "NUM_ANIMS") EmitEnum([f"ANIM_{i.name.value.upper()}" for i in content.container.animations.items], "NUM_ANIMS")
EmitEnum(["SPRITE_%s"%i.name.value.upper() for i in content.container.sprites.items], "NUM_SPRITES") EmitEnum([f"SPRITE_{i.name.value.upper()}" for i in content.container.sprites.items], "NUM_SPRITES")
def gen_common_content_source(): def gen_common_content_source():
EmitDefinition(content.container, "datacontainer") EmitDefinition(content.container, "datacontainer")

View file

@ -25,11 +25,11 @@ def generate_map(a, b):
return result return result
def output_map_header(name, m): def output_map_header(name, m):
print("extern const int gs_{}[{}];".format(name, len(m))) print(f"extern const int gs_{name}[{len(m)}];")
print("inline int {0}(int a) {{ if(a < 0 || a >= {1}) return -1; return gs_{0}[a]; }}".format(name, len(m))) print(f"inline int {name}(int a) {{ if(a < 0 || a >= {len(m)}) return -1; return gs_{name}[a]; }}")
def output_map_source(name, m): def output_map_source(name, m):
print("const int gs_{}[{}] = {{".format(name, len(m))) print(f"const int gs_{name}[{len(m)}] = {{")
print(*m, sep=',') print(*m, sep=',')
print("};") print("};")

View file

@ -4,7 +4,7 @@ def GetID():
GlobalIdCounter += 1 GlobalIdCounter += 1
return GlobalIdCounter return GlobalIdCounter
def GetUID(): def GetUID():
return "x%d"%GetID() return f"x{int(GetID())}"
def FixCasing(Str): def FixCasing(Str):
NewStr = "" NewStr = ""
@ -33,7 +33,7 @@ class BaseType:
self._target_name = "INVALID" self._target_name = "INVALID"
self._id = GetID() # this is used to remember what order the members have in structures etc self._id = GetID() # this is used to remember what order the members have in structures etc
def Identifyer(self): def Identifier(self):
return "x"+str(self._id) return "x"+str(self._id)
def TargetName(self): def TargetName(self):
return self._target_name return self._target_name
@ -43,7 +43,7 @@ class BaseType:
return self._id return self._id
def EmitDeclaration(self, name): def EmitDeclaration(self, name):
return ["%s %s;"%(self.TypeName(), FormatName(self.TypeName(), name))] return [f"{self.TypeName()} {FormatName(self.TypeName(), name)};"]
def EmitPreDefinition(self, target_name): def EmitPreDefinition(self, target_name):
self._target_name = target_name self._target_name = target_name
return [] return []
@ -62,10 +62,10 @@ class Struct(BaseType):
def sorter(a): def sorter(a):
return a.var.ID() return a.var.ID()
m = [] m = []
for name in self.__dict__: for name, value in self.__dict__.items():
if name[0] == "_": if name[0] == "_":
continue continue
m += [MemberType(name, self.__dict__[name])] m += [MemberType(name, value)]
m.sort(key = sorter) m.sort(key = sorter)
return m return m
@ -85,7 +85,7 @@ class Struct(BaseType):
lines += member.var.EmitPreDefinition(target_name+"."+member.name) lines += member.var.EmitPreDefinition(target_name+"."+member.name)
return lines return lines
def EmitDefinition(self, _name): def EmitDefinition(self, _name):
lines = ["/* %s */ {" % self.TargetName()] lines = [f"/* {self.TargetName()} */ {{"]
for member in self.Members(): for member in self.Members():
lines += ["\t" + " ".join(member.var.EmitDefinition("")) + ","] lines += ["\t" + " ".join(member.var.EmitDefinition("")) + ","]
lines += ["}"] lines += ["}"]
@ -98,32 +98,32 @@ class Array(BaseType):
self.items = [] self.items = []
def Add(self, instance): def Add(self, instance):
if instance.TypeName() != self.type.TypeName(): if instance.TypeName() != self.type.TypeName():
raise "bah" raise ValueError("bah")
self.items += [instance] self.items += [instance]
def EmitDeclaration(self, name): def EmitDeclaration(self, name):
return ["int m_Num%s;"%(FixCasing(name)), return [f"int m_Num{FixCasing(name)};",
"%s *%s;"%(self.TypeName(), FormatName("[]", name))] f"{self.TypeName()} *{FormatName('[]', name)};"]
def EmitPreDefinition(self, target_name): def EmitPreDefinition(self, target_name):
BaseType.EmitPreDefinition(self, target_name) BaseType.EmitPreDefinition(self, target_name)
lines = [] lines = []
i = 0 i = 0
for item in self.items: for item in self.items:
lines += item.EmitPreDefinition("%s[%d]"%(self.Identifyer(), i)) lines += item.EmitPreDefinition(f"{self.Identifier()}[{int(i)}]")
i += 1 i += 1
if self.items: if self.items:
lines += ["static %s %s[] = {"%(self.TypeName(), self.Identifyer())] lines += [f"static {self.TypeName()} {self.Identifier()}[] = {{"]
for item in self.items: for item in self.items:
itemlines = item.EmitDefinition("") itemlines = item.EmitDefinition("")
lines += ["\t" + " ".join(itemlines).replace("\t", " ") + ","] lines += ["\t" + " ".join(itemlines).replace("\t", " ") + ","]
lines += ["};"] lines += ["};"]
else: else:
lines += ["static %s *%s = 0;"%(self.TypeName(), self.Identifyer())] lines += [f"static {self.TypeName()} *{self.Identifier()} = 0;"]
return lines return lines
def EmitDefinition(self, _name): def EmitDefinition(self, _name):
return [str(len(self.items))+","+self.Identifyer()] return [str(len(self.items))+","+self.Identifier()]
# Basic Types # Basic Types
@ -134,7 +134,7 @@ class Int(BaseType):
def Set(self, value): def Set(self, value):
self.value = value self.value = value
def EmitDefinition(self, _name): def EmitDefinition(self, _name):
return ["%d"%self.value] return [f"{int(self.value)}"]
#return ["%d /* %s */"%(self.value, self._target_name)] #return ["%d /* %s */"%(self.value, self._target_name)]
class Float(BaseType): class Float(BaseType):
@ -144,7 +144,7 @@ class Float(BaseType):
def Set(self, value): def Set(self, value):
self.value = value self.value = value
def EmitDefinition(self, _name): def EmitDefinition(self, _name):
return ["%ff"%self.value] return [f"{self.value:f}f"]
#return ["%d /* %s */"%(self.value, self._target_name)] #return ["%d /* %s */"%(self.value, self._target_name)]
class String(BaseType): class String(BaseType):
@ -158,7 +158,7 @@ class String(BaseType):
class Pointer(BaseType): class Pointer(BaseType):
def __init__(self, typ, target): def __init__(self, typ, target):
BaseType.__init__(self, "%s*"%typ().TypeName()) BaseType.__init__(self, f"{typ().TypeName()}*")
self.target = target self.target = target
def Set(self, target): def Set(self, target):
self.target = target self.target = target
@ -180,7 +180,7 @@ def EmitTypeDeclaration(root):
def EmitDefinition(root, name): def EmitDefinition(root, name):
for l in root.EmitPreDefinition(name): for l in root.EmitPreDefinition(name):
print(l) print(l)
print("%s %s = " % (root.TypeName(), name)) print(f"{root.TypeName()} {name} = ")
for l in root.EmitDefinition(name): for l in root.EmitDefinition(name):
print(l) print(l)
print(";") print(";")
@ -207,9 +207,9 @@ class NetObject:
self.base = "" self.base = ""
if len(l) > 1: if len(l) > 1:
self.base = l[1] self.base = l[1]
self.base_struct_name = "CNetObj_%s" % self.base self.base_struct_name = f"CNetObj_{self.base}"
self.struct_name = "CNetObj_%s" % self.name self.struct_name = f"CNetObj_{self.name}"
self.enum_name = "NETOBJTYPE_%s" % self.name.upper() self.enum_name = f"NETOBJTYPE_{self.name.upper()}"
self.variables = variables self.variables = variables
self.ex = ex self.ex = ex
self.validate_size = validate_size self.validate_size = validate_size
@ -217,9 +217,9 @@ class NetObject:
def emit_declaration(self): def emit_declaration(self):
lines = [] lines = []
if self.base: if self.base:
lines += ["struct %s : public %s"%(self.struct_name,self.base_struct_name), "{"] lines += [f"struct {self.struct_name} : public {self.base_struct_name}", "{"]
else: else:
lines += ["struct %s"%self.struct_name, "{"] lines += [f"struct {self.struct_name}", "{"]
for v in self.variables: for v in self.variables:
lines += ["\t"+line for line in v.emit_declaration()] lines += ["\t"+line for line in v.emit_declaration()]
lines += ["};"] lines += ["};"]
@ -227,9 +227,9 @@ class NetObject:
def emit_uncompressed_unpack_and_validate(self, base_item): def emit_uncompressed_unpack_and_validate(self, base_item):
lines = [] lines = []
lines += ["case %s:" % self.enum_name] lines += [f"case {self.enum_name}:"]
lines += ["{"] lines += ["{"]
lines += ["\t%s *pData = (%s *)m_aUnpackedData;" % (self.struct_name, self.struct_name)] lines += [f"\t{self.struct_name} *pData = ({self.struct_name} *)m_aUnpackedData;"]
unpack_lines = [] unpack_lines = []
variables = [] variables = []
@ -253,23 +253,23 @@ class NetObject:
class NetEvent(NetObject): class NetEvent(NetObject):
def __init__(self, name, variables, ex=None): def __init__(self, name, variables, ex=None):
NetObject.__init__(self, name, variables, ex=ex) NetObject.__init__(self, name, variables, ex=ex)
self.base_struct_name = "CNetEvent_%s" % self.base self.base_struct_name = f"CNetEvent_{self.base}"
self.struct_name = "CNetEvent_%s" % self.name self.struct_name = f"CNetEvent_{self.name}"
self.enum_name = "NETEVENTTYPE_%s" % self.name.upper() self.enum_name = f"NETEVENTTYPE_{self.name.upper()}"
class NetMessage(NetObject): class NetMessage(NetObject):
def __init__(self, name, variables, ex=None, teehistorian=True): def __init__(self, name, variables, ex=None, teehistorian=True):
NetObject.__init__(self, name, variables, ex=ex) NetObject.__init__(self, name, variables, ex=ex)
self.base_struct_name = "CNetMsg_%s" % self.base self.base_struct_name = f"CNetMsg_{self.base}"
self.struct_name = "CNetMsg_%s" % self.name self.struct_name = f"CNetMsg_{self.name}"
self.enum_name = "NETMSGTYPE_%s" % self.name.upper() self.enum_name = f"NETMSGTYPE_{self.name.upper()}"
self.teehistorian = teehistorian self.teehistorian = teehistorian
def emit_unpack_msg(self): def emit_unpack_msg(self):
lines = [] lines = []
lines += ["case %s:" % self.enum_name] lines += [f"case {self.enum_name}:"]
lines += ["{"] lines += ["{"]
lines += ["\t%s *pData = (%s *)m_aUnpackedData;" % (self.struct_name, self.struct_name)] lines += [f"\t{self.struct_name} *pData = ({self.struct_name} *)m_aUnpackedData;"]
unpack_lines = [] unpack_lines = []
for v in self.variables: for v in self.variables:
@ -286,7 +286,7 @@ class NetMessage(NetObject):
def emit_declaration(self): def emit_declaration(self):
extra = [] extra = []
extra += ["\tint MsgID() const { return %s; }" % self.enum_name] extra += [f"\tint MsgID() const {{ return {self.enum_name}; }}"]
extra += ["\t"] extra += ["\t"]
extra += ["\tbool Pack(CMsgPacker *pPacker) const"] extra += ["\tbool Pack(CMsgPacker *pPacker) const"]
extra += ["\t{"] extra += ["\t{"]
@ -332,47 +332,47 @@ class NetVariable:
class NetString(NetVariable): class NetString(NetVariable):
def emit_declaration(self): def emit_declaration(self):
return ["const char *%s;"%self.name] return [f"const char *{self.name};"]
def emit_uncompressed_unpack_obj(self): def emit_uncompressed_unpack_obj(self):
return self.emit_unpack_msg() return self.emit_unpack_msg()
def emit_unpack_msg(self): def emit_unpack_msg(self):
return ["pData->%s = pUnpacker->GetString();" % self.name] return [f"pData->{self.name} = pUnpacker->GetString();"]
def emit_pack(self): def emit_pack(self):
return ["pPacker->AddString(%s, -1);" % self.name] return [f"pPacker->AddString({self.name}, -1);"]
class NetStringHalfStrict(NetVariable): class NetStringHalfStrict(NetVariable):
def emit_declaration(self): def emit_declaration(self):
return ["const char *%s;"%self.name] return [f"const char *{self.name};"]
def emit_uncompressed_unpack_obj(self): def emit_uncompressed_unpack_obj(self):
return self.emit_unpack_msg() return self.emit_unpack_msg()
def emit_unpack_msg(self): def emit_unpack_msg(self):
return ["pData->%s = pUnpacker->GetString(CUnpacker::SANITIZE_CC);" % self.name] return [f"pData->{self.name} = pUnpacker->GetString(CUnpacker::SANITIZE_CC);"]
def emit_pack(self): def emit_pack(self):
return ["pPacker->AddString(%s, -1);" % self.name] return [f"pPacker->AddString({self.name}, -1);"]
class NetStringStrict(NetVariable): class NetStringStrict(NetVariable):
def emit_declaration(self): def emit_declaration(self):
return ["const char *%s;"%self.name] return [f"const char *{self.name};"]
def emit_uncompressed_unpack_obj(self): def emit_uncompressed_unpack_obj(self):
return self.emit_unpack_msg() return self.emit_unpack_msg()
def emit_unpack_msg(self): def emit_unpack_msg(self):
return ["pData->%s = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);" % self.name] return [f"pData->{self.name} = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);"]
def emit_pack(self): def emit_pack(self):
return ["pPacker->AddString(%s, -1);" % self.name] return [f"pPacker->AddString({self.name}, -1);"]
class NetIntAny(NetVariable): class NetIntAny(NetVariable):
def emit_declaration(self): def emit_declaration(self):
return ["int %s;"%self.name] return [f"int {self.name};"]
def emit_uncompressed_unpack_obj(self): def emit_uncompressed_unpack_obj(self):
if self.default is None: if self.default is None:
return ["pData->%s = pUnpacker->GetUncompressedInt();" % self.name] return [f"pData->{self.name} = pUnpacker->GetUncompressedInt();"]
return ["pData->%s = pUnpacker->GetUncompressedIntOrDefault(%s);" % (self.name, self.default)] return [f"pData->{self.name} = pUnpacker->GetUncompressedIntOrDefault({self.default});"]
def emit_unpack_msg(self): def emit_unpack_msg(self):
if self.default is None: if self.default is None:
return ["pData->%s = pUnpacker->GetInt();" % self.name] return [f"pData->{self.name} = pUnpacker->GetInt();"]
return ["pData->%s = pUnpacker->GetIntOrDefault(%s);" % (self.name, self.default)] return [f"pData->{self.name} = pUnpacker->GetIntOrDefault({self.default});"]
def emit_pack(self): def emit_pack(self):
return ["pPacker->AddInt(%s);" % self.name] return [f"pPacker->AddInt({self.name});"]
class NetIntRange(NetIntAny): class NetIntRange(NetIntAny):
def __init__(self, name, min_val, max_val, default=None): def __init__(self, name, min_val, max_val, default=None):
@ -380,9 +380,9 @@ class NetIntRange(NetIntAny):
self.min = str(min_val) self.min = str(min_val)
self.max = str(max_val) self.max = str(max_val)
def emit_validate_obj(self): def emit_validate_obj(self):
return ["pData->%s = ClampInt(\"%s\", pData->%s, %s, %s);"%(self.name, self.name, self.name, self.min, self.max)] return [f"pData->{self.name} = ClampInt(\"{self.name}\", pData->{self.name}, {self.min}, {self.max});"]
def emit_unpack_msg_check(self): def emit_unpack_msg_check(self):
return ["if(pData->%s < %s || pData->%s > %s) { m_pMsgFailedOn = \"%s\"; break; }" % (self.name, self.min, self.name, self.max, self.name)] return [f"if(pData->{self.name} < {self.min} || pData->{self.name} > {self.max}) {{ m_pMsgFailedOn = \"{self.name}\"; break; }}"]
class NetBool(NetIntRange): class NetBool(NetIntRange):
def __init__(self, name, default=None): def __init__(self, name, default=None):
@ -399,37 +399,37 @@ class NetArray(NetVariable):
self.base_name = var.name self.base_name = var.name
self.var = var self.var = var
self.size = size self.size = size
self.name = self.base_name + "[%d]"%self.size self.name = self.base_name + f"[{int(self.size)}]"
def emit_declaration(self): def emit_declaration(self):
self.var.name = self.name self.var.name = self.name
return self.var.emit_declaration() return self.var.emit_declaration()
def emit_uncompressed_unpack_obj(self): def emit_uncompressed_unpack_obj(self):
lines = [] lines = []
for i in range(self.size): for i in range(self.size):
self.var.name = self.base_name + "[%d]"%i self.var.name = self.base_name + f"[{int(i)}]"
lines += self.var.emit_uncompressed_unpack_obj() lines += self.var.emit_uncompressed_unpack_obj()
return lines return lines
def emit_validate_obj(self): def emit_validate_obj(self):
lines = [] lines = []
for i in range(self.size): for i in range(self.size):
self.var.name = self.base_name + "[%d]"%i self.var.name = self.base_name + f"[{int(i)}]"
lines += self.var.emit_validate_obj() lines += self.var.emit_validate_obj()
return lines return lines
def emit_unpack_msg(self): def emit_unpack_msg(self):
lines = [] lines = []
for i in range(self.size): for i in range(self.size):
self.var.name = self.base_name + "[%d]"%i self.var.name = self.base_name + f"[{int(i)}]"
lines += self.var.emit_unpack_msg() lines += self.var.emit_unpack_msg()
return lines return lines
def emit_pack(self): def emit_pack(self):
lines = [] lines = []
for i in range(self.size): for i in range(self.size):
self.var.name = self.base_name + "[%d]"%i self.var.name = self.base_name + f"[{int(i)}]"
lines += self.var.emit_pack() lines += self.var.emit_pack()
return lines return lines
def emit_unpack_msg_check(self): def emit_unpack_msg_check(self):
lines = [] lines = []
for i in range(self.size): for i in range(self.size):
self.var.name = self.base_name + "[%d]"%i self.var.name = self.base_name + f"[{int(i)}]"
lines += self.var.emit_unpack_msg_check() lines += self.var.emit_unpack_msg_check()
return lines return lines

View file

@ -29,7 +29,7 @@ GameInfoFlags2 = [
"HUD_DDRACE", "HUD_DDRACE",
] ]
ExPlayerFlags = ["AFK", "PAUSED", "SPEC"] ExPlayerFlags = ["AFK", "PAUSED", "SPEC"]
ProjectileFlags = ["CLIENTID_BIT{}".format(i) for i in range(8)] + [ ProjectileFlags = [f"CLIENTID_BIT{i}" for i in range(8)] + [
"NO_OWNER", "IS_DDNET", "BOUNCE_HORIZONTAL", "BOUNCE_VERTICAL", "NO_OWNER", "IS_DDNET", "BOUNCE_HORIZONTAL", "BOUNCE_VERTICAL",
"EXPLOSIVE", "FREEZE", "EXPLOSIVE", "FREEZE",
] ]

View file

@ -1,15 +1,15 @@
import sys import sys
from .datatypes import EmitDefinition, EmitTypeDeclaration from .datatypes import EmitDefinition, EmitTypeDeclaration
from . import content from . import content # pylint: disable=no-name-in-module
from . import network from . import network # pylint: disable=no-name-in-module
def create_enum_table(names, num): def create_enum_table(names, num):
lines = [] lines = []
lines += ["enum", "{"] lines += ["enum", "{"]
lines += ["\t%s=0,"%names[0]] lines += [f"\t{names[0]}=0,"]
for name in names[1:]: for name in names[1:]:
lines += ["\t%s,"%name] lines += [f"\t{name},"]
lines += ["\t%s" % num, "};"] lines += [f"\t{num}", "};"]
return lines return lines
def create_flags_table(names): def create_flags_table(names):
@ -17,7 +17,7 @@ def create_flags_table(names):
lines += ["enum", "{"] lines += ["enum", "{"]
i = 0 i = 0
for name in names: for name in names:
lines += ["\t%s = 1<<%d," % (name,i)] lines += [f"\t{name} = 1<<{int(i)},"]
i += 1 i += 1
lines += ["};"] lines += ["};"]
return lines return lines
@ -25,10 +25,10 @@ def create_flags_table(names):
def EmitEnum(names, num): def EmitEnum(names, num):
print("enum") print("enum")
print("{") print("{")
print("\t%s=0," % names[0]) print(f"\t{names[0]}=0,")
for name in names[1:]: for name in names[1:]:
print("\t%s," % name) print(f"\t{name},")
print("\t%s" % num) print(f"\t{num}")
print("};") print("};")
def EmitFlags(names): def EmitFlags(names):
@ -36,7 +36,7 @@ def EmitFlags(names):
print("{") print("{")
i = 0 i = 0
for name in names: for name in names:
print("\t%s = 1<<%d," % (name,i)) print(f"\t{name} = 1<<{int(i)},")
i += 1 i += 1
print("};") print("};")
@ -64,7 +64,8 @@ def main():
print("namespace client_data7 {") print("namespace client_data7 {")
# emit the type declarations # emit the type declarations
contentlines = open("datasrc/content.py", "rb").readlines() with open("datasrc/content.py", "rb") as f:
contentlines = f.readlines()
order = [] order = []
for line in contentlines: for line in contentlines:
line = line.strip() line = line.strip()
@ -77,9 +78,9 @@ def main():
print('extern CDataContainer *g_pData;') print('extern CDataContainer *g_pData;')
# enums # enums
EmitEnum(["IMAGE_%s"%i.name.value.upper() for i in content.container.images.items], "NUM_IMAGES") EmitEnum([f"IMAGE_{i.name.value.upper()}" for i in content.container.images.items], "NUM_IMAGES")
EmitEnum(["ANIM_%s"%i.name.value.upper() for i in content.container.animations.items], "NUM_ANIMS") EmitEnum([f"ANIM_{i.name.value.upper()}" for i in content.container.animations.items], "NUM_ANIMS")
EmitEnum(["SPRITE_%s"%i.name.value.upper() for i in content.container.sprites.items], "NUM_SPRITES") EmitEnum([f"SPRITE_{i.name.value.upper()}" for i in content.container.sprites.items], "NUM_SPRITES")
if gen_client_content_source or gen_server_content_source: if gen_client_content_source or gen_server_content_source:
if gen_client_content_source: if gen_client_content_source:
@ -102,12 +103,12 @@ def main():
print(network.RawHeader) print(network.RawHeader)
for e in network.Enums: for e in network.Enums:
for l in create_enum_table(["%s_%s"%(e.name, v) for v in e.values], 'NUM_%sS'%e.name): for l in create_enum_table([f"{e.name}_{v}" for v in e.values], f'NUM_{e.name}S'):
print(l) print(l)
print("") print("")
for e in network.Flags: for e in network.Flags:
for l in create_flags_table(["%s_%s" % (e.name, v) for v in e.values]): for l in create_flags_table([f"{e.name}_{v}" for v in e.values]):
print(l) print(l)
print("") print("")
@ -138,8 +139,8 @@ def main():
print(line) print(line)
print("") print("")
EmitEnum(["SOUND_%s"%i.name.value.upper() for i in content.container.sounds.items], "NUM_SOUNDS") EmitEnum([f"SOUND_{i.name.value.upper()}" for i in content.container.sounds.items], "NUM_SOUNDS")
EmitEnum(["WEAPON_%s"%i.name.value.upper() for i in content.container.weapons.id.items], "NUM_WEAPONS") EmitEnum([f"WEAPON_{i.name.value.upper()}" for i in content.container.weapons.id.items], "NUM_WEAPONS")
print(""" print("""
@ -220,19 +221,19 @@ def main():
lines += ["const char *CNetObjHandler::ms_apObjNames[] = {"] lines += ["const char *CNetObjHandler::ms_apObjNames[] = {"]
lines += ['\t"invalid",'] lines += ['\t"invalid",']
lines += ['\t"%s",' % o.name for o in network.Objects] lines += [f'\t"{o.name}",' for o in network.Objects]
lines += ['\t""', "};", ""] lines += ['\t""', "};", ""]
lines += ["int CNetObjHandler::ms_aObjSizes[] = {"] lines += ["int CNetObjHandler::ms_aObjSizes[] = {"]
lines += ['\t0,'] lines += ['\t0,']
lines += ['\tsizeof(%s),' % o.struct_name for o in network.Objects] lines += [f'\tsizeof({o.struct_name}),' for o in network.Objects]
lines += ['\t0', "};", ""] lines += ['\t0', "};", ""]
lines += ['const char *CNetObjHandler::ms_apMsgNames[] = {'] lines += ['const char *CNetObjHandler::ms_apMsgNames[] = {']
lines += ['\t"invalid",'] lines += ['\t"invalid",']
for msg in network.Messages: for msg in network.Messages:
lines += ['\t"%s",' % msg.name] lines += [f'\t"{msg.name}",']
lines += ['\t""'] lines += ['\t""']
lines += ['};'] lines += ['};']
lines += [''] lines += ['']

View file

@ -4,7 +4,7 @@ def GetID():
GlobalIdCounter += 1 GlobalIdCounter += 1
return GlobalIdCounter return GlobalIdCounter
def GetUID(): def GetUID():
return "x%d"%GetID() return f"x{int(GetID())}"
def FixCasing(Str): def FixCasing(Str):
NewStr = "" NewStr = ""
@ -33,7 +33,7 @@ class BaseType:
self._target_name = "INVALID" self._target_name = "INVALID"
self._id = GetID() # this is used to remember what order the members have in structures etc self._id = GetID() # this is used to remember what order the members have in structures etc
def Identifyer(self): def Identifier(self):
return "x"+str(self._id) return "x"+str(self._id)
def TargetName(self): def TargetName(self):
return self._target_name return self._target_name
@ -43,7 +43,7 @@ class BaseType:
return self._id return self._id
def EmitDeclaration(self, name): def EmitDeclaration(self, name):
return ["%s %s;"%(self.TypeName(), FormatName(self.TypeName(), name))] return [f"{self.TypeName()} {FormatName(self.TypeName(), name)};"]
def EmitPreDefinition(self, target_name): def EmitPreDefinition(self, target_name):
self._target_name = target_name self._target_name = target_name
return [] return []
@ -62,10 +62,10 @@ class Struct(BaseType):
def sorter(a): def sorter(a):
return a.var.ID() return a.var.ID()
m = [] m = []
for name in self.__dict__: for name, value in self.__dict__.items():
if name[0] == "_": if name[0] == "_":
continue continue
m += [MemberType(name, self.__dict__[name])] m += [MemberType(name, value)]
m.sort(key = sorter) m.sort(key = sorter)
return m return m
@ -85,7 +85,7 @@ class Struct(BaseType):
lines += member.var.EmitPreDefinition(target_name+"."+member.name) lines += member.var.EmitPreDefinition(target_name+"."+member.name)
return lines return lines
def EmitDefinition(self, _name): def EmitDefinition(self, _name):
lines = ["/* %s */ {" % self.TargetName()] lines = [f"/* {self.TargetName()} */ {{"]
for member in self.Members(): for member in self.Members():
lines += ["\t" + " ".join(member.var.EmitDefinition("")) + ","] lines += ["\t" + " ".join(member.var.EmitDefinition("")) + ","]
lines += ["}"] lines += ["}"]
@ -98,32 +98,32 @@ class Array(BaseType):
self.items = [] self.items = []
def Add(self, instance): def Add(self, instance):
if instance.TypeName() != self.type.TypeName(): if instance.TypeName() != self.type.TypeName():
raise "bah" raise ValueError("bah")
self.items += [instance] self.items += [instance]
def EmitDeclaration(self, name): def EmitDeclaration(self, name):
return ["int m_Num%s;"%(FixCasing(name)), return [f"int m_Num{FixCasing(name)};",
"%s *%s;"%(self.TypeName(), FormatName("[]", name))] f"{self.TypeName()} *{FormatName('[]', name)};"]
def EmitPreDefinition(self, target_name): def EmitPreDefinition(self, target_name):
BaseType.EmitPreDefinition(self, target_name) BaseType.EmitPreDefinition(self, target_name)
lines = [] lines = []
i = 0 i = 0
for item in self.items: for item in self.items:
lines += item.EmitPreDefinition("%s[%d]"%(self.Identifyer(), i)) lines += item.EmitPreDefinition(f"{self.Identifier()}[{int(i)}]")
i += 1 i += 1
if self.items: if self.items:
lines += ["static %s %s[] = {"%(self.TypeName(), self.Identifyer())] lines += [f"static {self.TypeName()} {self.Identifier()}[] = {{"]
for item in self.items: for item in self.items:
itemlines = item.EmitDefinition("") itemlines = item.EmitDefinition("")
lines += ["\t" + " ".join(itemlines).replace("\t", " ") + ","] lines += ["\t" + " ".join(itemlines).replace("\t", " ") + ","]
lines += ["};"] lines += ["};"]
else: else:
lines += ["static %s *%s = nullptr;"%(self.TypeName(), self.Identifyer())] lines += [f"static {self.TypeName()} *{self.Identifier()} = nullptr;"]
return lines return lines
def EmitDefinition(self, _name): def EmitDefinition(self, _name):
return [str(len(self.items))+","+self.Identifyer()] return [str(len(self.items))+","+self.Identifier()]
# Basic Types # Basic Types
@ -134,7 +134,7 @@ class Int(BaseType):
def Set(self, value): def Set(self, value):
self.value = value self.value = value
def EmitDefinition(self, _name): def EmitDefinition(self, _name):
return ["%d"%self.value] return [f"{int(self.value)}"]
#return ["%d /* %s */"%(self.value, self._target_name)] #return ["%d /* %s */"%(self.value, self._target_name)]
class Float(BaseType): class Float(BaseType):
@ -144,7 +144,7 @@ class Float(BaseType):
def Set(self, value): def Set(self, value):
self.value = value self.value = value
def EmitDefinition(self, _name): def EmitDefinition(self, _name):
return ["%ff"%self.value] return [f"{self.value:f}f"]
#return ["%d /* %s */"%(self.value, self._target_name)] #return ["%d /* %s */"%(self.value, self._target_name)]
class String(BaseType): class String(BaseType):
@ -158,7 +158,7 @@ class String(BaseType):
class Pointer(BaseType): class Pointer(BaseType):
def __init__(self, typ, target): def __init__(self, typ, target):
BaseType.__init__(self, "%s*"%typ().TypeName()) BaseType.__init__(self, f"{typ().TypeName()}*")
self.target = target self.target = target
def Set(self, target): def Set(self, target):
self.target = target self.target = target
@ -186,7 +186,7 @@ def EmitTypeDeclaration(root):
def EmitDefinition(root, name): def EmitDefinition(root, name):
for l in root.EmitPreDefinition(name): for l in root.EmitPreDefinition(name):
print(l) print(l)
print("%s %s = " % (root.TypeName(), name)) print(f"{root.TypeName()} {name} = ")
for l in root.EmitDefinition(name): for l in root.EmitDefinition(name):
print(l) print(l)
print(";") print(";")
@ -213,23 +213,23 @@ class NetObject:
self.base = "" self.base = ""
if len(l) > 1: if len(l) > 1:
self.base = l[1] self.base = l[1]
self.base_struct_name = "CNetObj_%s" % self.base self.base_struct_name = f"CNetObj_{self.base}"
self.struct_name = "CNetObj_%s" % self.name self.struct_name = f"CNetObj_{self.name}"
self.enum_name = "NETOBJTYPE_%s" % self.name.upper() self.enum_name = f"NETOBJTYPE_{self.name.upper()}"
self.variables = variables self.variables = variables
def emit_declaration(self): def emit_declaration(self):
if self.base: if self.base:
lines = ["struct %s : public %s"%(self.struct_name,self.base_struct_name), "{"] lines = [f"struct {self.struct_name} : public {self.base_struct_name}", "{"]
else: else:
lines = ["struct %s"%self.struct_name, "{"] lines = [f"struct {self.struct_name}", "{"]
for v in self.variables: for v in self.variables:
lines += ["\t"+line for line in v.emit_declaration()] lines += ["\t"+line for line in v.emit_declaration()]
lines += ["};"] lines += ["};"]
return lines return lines
def emit_validate(self): def emit_validate(self):
lines = ["case %s:" % self.enum_name] lines = [f"case {self.enum_name}:"]
lines += ["{"] lines += ["{"]
lines += ["\t%s *pObj = (%s *)pData;"%(self.struct_name, self.struct_name)] lines += [f"\t{self.struct_name} *pObj = ({self.struct_name} *)pData;"]
lines += ["\tif(sizeof(*pObj) != Size) return -1;"] lines += ["\tif(sizeof(*pObj) != Size) return -1;"]
for v in self.variables: for v in self.variables:
lines += ["\t"+line for line in v.emit_validate()] lines += ["\t"+line for line in v.emit_validate()]
@ -241,21 +241,21 @@ class NetObject:
class NetEvent(NetObject): class NetEvent(NetObject):
def __init__(self, name, variables): def __init__(self, name, variables):
NetObject.__init__(self, name, variables) NetObject.__init__(self, name, variables)
self.base_struct_name = "CNetEvent_%s" % self.base self.base_struct_name = f"CNetEvent_{self.base}"
self.struct_name = "CNetEvent_%s" % self.name self.struct_name = f"CNetEvent_{self.name}"
self.enum_name = "NETEVENTTYPE_%s" % self.name.upper() self.enum_name = f"NETEVENTTYPE_{self.name.upper()}"
class NetMessage(NetObject): class NetMessage(NetObject):
def __init__(self, name, variables): def __init__(self, name, variables):
NetObject.__init__(self, name, variables) NetObject.__init__(self, name, variables)
self.base_struct_name = "CNetMsg_%s" % self.base self.base_struct_name = f"CNetMsg_{self.base}"
self.struct_name = "CNetMsg_%s" % self.name self.struct_name = f"CNetMsg_{self.name}"
self.enum_name = "NETMSGTYPE_%s" % self.name.upper() self.enum_name = f"NETMSGTYPE_{self.name.upper()}"
def emit_unpack(self): def emit_unpack(self):
lines = [] lines = []
lines += ["case %s:" % self.enum_name] lines += [f"case {self.enum_name}:"]
lines += ["{"] lines += ["{"]
lines += ["\t%s *pMsg = (%s *)m_aMsgData;" % (self.struct_name, self.struct_name)] lines += [f"\t{self.struct_name} *pMsg = ({self.struct_name} *)m_aMsgData;"]
lines += ["\t(void)pMsg;"] lines += ["\t(void)pMsg;"]
for v in self.variables: for v in self.variables:
lines += ["\t"+line for line in v.emit_unpack()] lines += ["\t"+line for line in v.emit_unpack()]
@ -266,7 +266,7 @@ class NetMessage(NetObject):
def emit_declaration(self): def emit_declaration(self):
extra = [] extra = []
extra += ["\tusing is_sixup = char;"] extra += ["\tusing is_sixup = char;"]
extra += ["\tint MsgID() const { return %s; }" % self.enum_name] extra += [f"\tint MsgID() const {{ return {self.enum_name}; }}"]
extra += ["\t"] extra += ["\t"]
extra += ["\tbool Pack(CMsgPacker *pPacker) const"] extra += ["\tbool Pack(CMsgPacker *pPacker) const"]
extra += ["\t{"] extra += ["\t{"]
@ -299,29 +299,29 @@ class NetVariable:
class NetString(NetVariable): class NetString(NetVariable):
def emit_declaration(self): def emit_declaration(self):
return ["const char *%s;"%self.name] return [f"const char *{self.name};"]
def emit_unpack(self): def emit_unpack(self):
return ["pMsg->%s = pUnpacker->GetString();" % self.name] return [f"pMsg->{self.name} = pUnpacker->GetString();"]
def emit_pack(self): def emit_pack(self):
return ["pPacker->AddString(%s, -1);" % self.name] return [f"pPacker->AddString({self.name}, -1);"]
class NetStringStrict(NetVariable): class NetStringStrict(NetVariable):
def emit_declaration(self): def emit_declaration(self):
return ["const char *%s;"%self.name] return [f"const char *{self.name};"]
def emit_unpack(self): def emit_unpack(self):
return ["pMsg->%s = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);" % self.name] return [f"pMsg->{self.name} = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);"]
def emit_pack(self): def emit_pack(self):
return ["pPacker->AddString(%s, -1);" % self.name] return [f"pPacker->AddString({self.name}, -1);"]
class NetIntAny(NetVariable): class NetIntAny(NetVariable):
def emit_declaration(self): def emit_declaration(self):
return ["int %s;"%self.name] return [f"int {self.name};"]
def emit_unpack(self): def emit_unpack(self):
if self.default is None: if self.default is None:
return ["pMsg->%s = pUnpacker->GetInt();" % self.name] return [f"pMsg->{self.name} = pUnpacker->GetInt();"]
return ["pMsg->%s = pUnpacker->GetIntOrDefault(%s);" % (self.name, self.default)] return [f"pMsg->{self.name} = pUnpacker->GetIntOrDefault({self.default});"]
def emit_pack(self): def emit_pack(self):
return ["pPacker->AddInt(%s);" % self.name] return [f"pPacker->AddInt({self.name});"]
class NetIntRange(NetIntAny): class NetIntRange(NetIntAny):
def __init__(self, name, min_val, max_val, default=None): def __init__(self, name, min_val, max_val, default=None):
@ -329,9 +329,9 @@ class NetIntRange(NetIntAny):
self.min = str(min_val) self.min = str(min_val)
self.max = str(max_val) self.max = str(max_val)
def emit_validate(self): def emit_validate(self):
return ["if(!CheckInt(\"%s\", pObj->%s, %s, %s)) return -1;"%(self.name, self.name, self.min, self.max)] return [f"if(!CheckInt(\"{self.name}\", pObj->{self.name}, {self.min}, {self.max})) return -1;"]
def emit_unpack_check(self): def emit_unpack_check(self):
return ["if(!CheckInt(\"%s\", pMsg->%s, %s, %s)) break;"%(self.name, self.name, self.min, self.max)] return [f"if(!CheckInt(\"{self.name}\", pMsg->{self.name}, {self.min}, {self.max})) break;"]
class NetEnum(NetIntRange): class NetEnum(NetIntRange):
def __init__(self, name, enum): def __init__(self, name, enum):
@ -341,15 +341,15 @@ class NetFlag(NetIntAny):
def __init__(self, name, flag): def __init__(self, name, flag):
NetIntAny.__init__(self, name) NetIntAny.__init__(self, name)
if len(flag.values) > 0: if len(flag.values) > 0:
self.mask = "%s_%s" % (flag.name, flag.values[0]) self.mask = f"{flag.name}_{flag.values[0]}"
for i in flag.values[1:]: for i in flag.values[1:]:
self.mask += "|%s_%s" % (flag.name, i) self.mask += f"|{flag.name}_{i}"
else: else:
self.mask = "0" self.mask = "0"
def emit_validate(self): def emit_validate(self):
return ["if(!CheckFlag(\"%s\", pObj->%s, %s)) return -1;"%(self.name, self.name, self.mask)] return [f"if(!CheckFlag(\"{self.name}\", pObj->{self.name}, {self.mask})) return -1;"]
def emit_unpack_check(self): def emit_unpack_check(self):
return ["if(!CheckFlag(\"%s\", pMsg->%s, %s)) break;"%(self.name, self.name, self.mask)] return [f"if(!CheckFlag(\"{self.name}\", pMsg->{self.name}, {self.mask})) break;"]
class NetBool(NetIntRange): class NetBool(NetIntRange):
def __init__(self, name, default=None): def __init__(self, name, default=None):
@ -366,31 +366,31 @@ class NetArray(NetVariable):
self.base_name = var.name self.base_name = var.name
self.var = var self.var = var
self.size = size self.size = size
self.name = self.base_name + "[%d]"%self.size self.name = self.base_name + f"[{int(self.size)}]"
def emit_declaration(self): def emit_declaration(self):
self.var.name = self.name self.var.name = self.name
return self.var.emit_declaration() return self.var.emit_declaration()
def emit_validate(self): def emit_validate(self):
lines = [] lines = []
for i in range(self.size): for i in range(self.size):
self.var.name = self.base_name + "[%d]"%i self.var.name = self.base_name + f"[{int(i)}]"
lines += self.var.emit_validate() lines += self.var.emit_validate()
return lines return lines
def emit_unpack(self): def emit_unpack(self):
lines = [] lines = []
for i in range(self.size): for i in range(self.size):
self.var.name = self.base_name + "[%d]"%i self.var.name = self.base_name + f"[{int(i)}]"
lines += self.var.emit_unpack() lines += self.var.emit_unpack()
return lines return lines
def emit_pack(self): def emit_pack(self):
lines = [] lines = []
for i in range(self.size): for i in range(self.size):
self.var.name = self.base_name + "[%d]"%i self.var.name = self.base_name + f"[{int(i)}]"
lines += self.var.emit_pack() lines += self.var.emit_pack()
return lines return lines
def emit_unpack_check(self): def emit_unpack_check(self):
lines = [] lines = []
for i in range(self.size): for i in range(self.size):
self.var.name = self.base_name + "[%d]"%i self.var.name = self.base_name + f"[{int(i)}]"
lines += self.var.emit_unpack_check() lines += self.var.emit_unpack_check()
return lines return lines

View file

@ -1,19 +1,12 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# pylint: disable=E0602 # pylint: disable=undefined-variable
from __future__ import unicode_literals from __future__ import unicode_literals
import os.path import os.path
import sys
# Before Python 3.4, use biplist; afterwards, use plistlib import plistlib
if sys.version_info < (3, 4): def read_plist(path):
import biplist # pylint: disable=E0401 with open(path, 'rb') as f:
def read_plist(path): return plistlib.load(f)
return biplist.readPlist(path)
else:
import plistlib # pylint: disable=E0401
def read_plist(path):
with open(path, 'rb') as f:
return plistlib.load(f)
# #
# Example settings file for dmgbuild # Example settings file for dmgbuild
@ -52,7 +45,7 @@ def icon_from_app(app_path):
# volume_name = 'DDNet' # volume_name = 'DDNet'
# Volume format (see hdiutil create -help) # Volume format (see hdiutil create -help)
format = defines.get('format', 'UDBZ') # pylint: disable=W0622 format = defines.get('format', 'UDBZ') # pylint: disable=redefined-builtin
# Compression level (if relevant) # Compression level (if relevant)
compression_level = 9 compression_level = 9

View file

@ -17,7 +17,7 @@ def check_file(filename):
if filename in EXCEPTIONS: if filename in EXCEPTIONS:
return False return False
error = False error = False
with open(filename) as file: with open(filename, encoding="utf-8") as file:
for line in file: for line in file:
if line == "// This file can be included several times.\n": if line == "// This file can be included several times.\n":
break break
@ -27,10 +27,10 @@ def check_file(filename):
if line.startswith("#ifndef"): if line.startswith("#ifndef"):
if line[:-1] != header_guard: if line[:-1] != header_guard:
error = True error = True
print("Wrong header guard in {}, is: {}, should be: {}".format(filename, line[:-1], header_guard)) print(f"Wrong header guard in {filename}, is: {line[:-1]}, should be: {header_guard}")
else: else:
error = True error = True
print("Missing header guard in {}, should be: {}".format(filename, header_guard)) print(f"Missing header guard in {filename}, should be: {header_guard}")
break break
return error return error

View file

@ -44,13 +44,13 @@ def check_variable_name(qualifiers, typ, name):
return None return None
prefix = "".join([qualifiers, "_" if qualifiers else "", typ]) prefix = "".join([qualifiers, "_" if qualifiers else "", typ])
if not name.startswith(prefix): if not name.startswith(prefix):
return "should start with {!r}".format(prefix) return f"should start with {prefix!r}"
if name in ALLOW: if name in ALLOW:
return None return None
name = name[len(prefix):] name = name[len(prefix):]
if not name[0].isupper(): if not name[0].isupper():
if prefix: if prefix:
return "should start with an uppercase letter after the prefix {!r}".format(prefix) return f"should start with an uppercase letter after the prefix {prefix!r}"
return "should start with an uppercase letter" return "should start with an uppercase letter"
return None return None
@ -65,7 +65,7 @@ def main():
error = check_name(i["kind"], i["qualifiers"], i["type"], i["name"]) error = check_name(i["kind"], i["qualifiers"], i["type"], i["name"])
if error: if error:
unclean = True unclean = True
print("{}:{}:{}: {}: {}".format(i["file"], i["line"], i["column"], i["name"], error)) print(f"{i['file']}:{i['line']}:{i['column']}: {i['name']}: {error}")
return unclean return unclean
if __name__ == "__main__": if __name__ == "__main__":

View file

@ -6,7 +6,7 @@ import os
os.chdir(os.path.dirname(__file__) + "/..") os.chdir(os.path.dirname(__file__) + "/..")
def hash_bytes(b): def hash_bytes(b):
return "0x{}".format(hashlib.sha256(b).hexdigest()[:8]) return f"0x{hashlib.sha256(b).hexdigest()[:8]}"
def hash_file(filename): def hash_file(filename):
with open(filename, "rb") as f: with open(filename, "rb") as f:
@ -18,7 +18,7 @@ def main():
p.add_argument("extra_file", metavar="EXTRA_FILE", help="File containing extra strings to be hashed") p.add_argument("extra_file", metavar="EXTRA_FILE", help="File containing extra strings to be hashed")
args = p.parse_args() args = p.parse_args()
with open(args.list_file) as f: with open(args.list_file, encoding="utf-8") as f:
files = f.read().splitlines() files = f.read().splitlines()
with open(args.extra_file, "rb") as f: with open(args.extra_file, "rb") as f:
extra = f.read().splitlines() extra = f.read().splitlines()
@ -31,10 +31,10 @@ def main():
void CChecksumData::InitFiles() void CChecksumData::InitFiles()
{ {
""", end="") """, end="")
print("\tm_NumFiles = {};".format(len(hashes_files))) print(f"\tm_NumFiles = {len(hashes_files)};")
print("\tm_NumExtra = {};".format(len(hashes_extra))) print(f"\tm_NumExtra = {len(hashes_extra)};")
for i, h in enumerate(hashes): for i, h in enumerate(hashes):
print("\tm_aFiles[0x{:03x}] = {};".format(i, h)) print(f"\tm_aFiles[0x{i:03x}] = {h};")
print("}") print("}")
if __name__ == "__main__": if __name__ == "__main__":

View file

@ -3,9 +3,9 @@ import csv
import os import os
import sys import sys
import clang.cindex import clang.cindex # pylint: disable=import-error
from clang.cindex import CursorKind, LinkageKind, StorageClass, TypeKind from clang.cindex import CursorKind, LinkageKind, StorageClass, TypeKind # pylint: disable=import-error
try: try:
from tqdm import tqdm from tqdm import tqdm
@ -92,20 +92,20 @@ class ParseError(RuntimeError):
def process_source_file(out, file, extra_args, break_on): def process_source_file(out, file, extra_args, break_on):
args = extra_args + ["-Isrc"] args = extra_args + ["-Isrc"]
if file.endswith(".c"): if file.endswith(".c"):
header = "{}.h".format(file[:-2]) header = f"{file[:-2]}.h"
elif file.endswith(".cpp"): elif file.endswith(".cpp"):
header = "{}.h".format(file[:-4]) header = f"{file[:-4]}.h"
else: else:
raise ValueError("unrecognized source file: {}".format(file)) raise ValueError(f"unrecognized source file: {file}")
index = clang.cindex.Index.create() index = clang.cindex.Index.create()
unit = index.parse(file, args=args) unit = index.parse(file, args=args)
errors = list(unit.diagnostics) errors = list(unit.diagnostics)
if errors: if errors:
for error in errors: for error in errors:
print("{}: {}".format(file, error.format()), file=sys.stderr) print(f"{file}: {error.format()}", file=sys.stderr)
print(args, file=sys.stderr) print(args, file=sys.stderr)
raise ParseError("failed parsing {}".format(file)) raise ParseError(f"failed parsing {file}")
filter_files = frozenset([file, header]) filter_files = frozenset([file, header])
@ -140,7 +140,7 @@ def process_source_file(out, file, extra_args, break_on):
"name": node.spelling, "name": node.spelling,
}) })
if node.spelling == break_on: if node.spelling == break_on:
breakpoint() breakpoint() # pylint: disable=forgotten-debug-statement
def main(): def main():
p = argparse.ArgumentParser(description="Extracts identifier data from a Teeworlds source file and its header, outputting the data as CSV to stdout") p = argparse.ArgumentParser(description="Extracts identifier data from a Teeworlds source file and its header, outputting the data as CSV to stdout")

View file

@ -29,15 +29,15 @@ def filter_cpp(filenames):
def find_clang_format(version): def find_clang_format(version):
for binary in ( for binary in (
"clang-format", "clang-format",
"clang-format-{}".format(version), f"clang-format-{version}",
"/opt/clang-format-static/clang-format-{}".format(version)): f"/opt/clang-format-static/clang-format-{version}"):
try: try:
out = subprocess.check_output([binary, "--version"]) out = subprocess.check_output([binary, "--version"])
except FileNotFoundError: except FileNotFoundError:
continue continue
if "clang-format version {}.".format(version) in out.decode("utf-8"): if f"clang-format version {version}." in out.decode("utf-8"):
return binary return binary
print("Found no clang-format {}".format(version)) print(f"Found no clang-format {version}")
sys.exit(-1) sys.exit(-1)
clang_format_bin = find_clang_format(10) clang_format_bin = find_clang_format(10)

View file

@ -4,7 +4,7 @@ f = open("src/engine/keys.h", "w")
keynames = [] keynames = []
for i in range(0, 512): for i in range(0, 512):
keynames += ["&%d"%i] keynames += [f"&{int(i)}"]
print("#ifndef ENGINE_KEYS_H", file=f) print("#ifndef ENGINE_KEYS_H", file=f)
print("#define ENGINE_KEYS_H", file=f) print("#define ENGINE_KEYS_H", file=f)
@ -28,7 +28,7 @@ for line in open("scripts/SDL_scancode.h"):
value = int(l[1].split(",")[0].strip()) value = int(l[1].split(",")[0].strip())
if key[0:2] == "/*": if key[0:2] == "/*":
continue continue
print("\t%s = %d,"%(key, value), file=f) print(f"\t{key} = {int(value)},", file=f)
keynames[value] = key.replace("KEY_", "").lower() keynames[value] = key.replace("KEY_", "").lower()
@ -37,74 +37,74 @@ for line in open("scripts/SDL_scancode.h"):
highestid += 1 highestid += 1
print("", file=f) print("", file=f)
print("\tKEY_MOUSE_1 = %d,"%(highestid), file=f); keynames[highestid] = "mouse1"; highestid += 1 print(f"\tKEY_MOUSE_1 = {int(highestid)},", file=f); keynames[highestid] = "mouse1"; highestid += 1
print("\tKEY_MOUSE_2 = %d,"%(highestid), file=f); keynames[highestid] = "mouse2"; highestid += 1 print(f"\tKEY_MOUSE_2 = {int(highestid)},", file=f); keynames[highestid] = "mouse2"; highestid += 1
print("\tKEY_MOUSE_3 = %d,"%(highestid), file=f); keynames[highestid] = "mouse3"; highestid += 1 print(f"\tKEY_MOUSE_3 = {int(highestid)},", file=f); keynames[highestid] = "mouse3"; highestid += 1
print("\tKEY_MOUSE_4 = %d,"%(highestid), file=f); keynames[highestid] = "mouse4"; highestid += 1 print(f"\tKEY_MOUSE_4 = {int(highestid)},", file=f); keynames[highestid] = "mouse4"; highestid += 1
print("\tKEY_MOUSE_5 = %d,"%(highestid), file=f); keynames[highestid] = "mouse5"; highestid += 1 print(f"\tKEY_MOUSE_5 = {int(highestid)},", file=f); keynames[highestid] = "mouse5"; highestid += 1
print("\tKEY_MOUSE_6 = %d,"%(highestid), file=f); keynames[highestid] = "mouse6"; highestid += 1 print(f"\tKEY_MOUSE_6 = {int(highestid)},", file=f); keynames[highestid] = "mouse6"; highestid += 1
print("\tKEY_MOUSE_7 = %d,"%(highestid), file=f); keynames[highestid] = "mouse7"; highestid += 1 print(f"\tKEY_MOUSE_7 = {int(highestid)},", file=f); keynames[highestid] = "mouse7"; highestid += 1
print("\tKEY_MOUSE_8 = %d,"%(highestid), file=f); keynames[highestid] = "mouse8"; highestid += 1 print(f"\tKEY_MOUSE_8 = {int(highestid)},", file=f); keynames[highestid] = "mouse8"; highestid += 1
print("\tKEY_MOUSE_9 = %d,"%(highestid), file=f); keynames[highestid] = "mouse9"; highestid += 1 print(f"\tKEY_MOUSE_9 = {int(highestid)},", file=f); keynames[highestid] = "mouse9"; highestid += 1
print("\tKEY_MOUSE_WHEEL_UP = %d,"%(highestid), file=f); keynames[highestid] = "mousewheelup"; highestid += 1 print(f"\tKEY_MOUSE_WHEEL_UP = {int(highestid)},", file=f); keynames[highestid] = "mousewheelup"; highestid += 1
print("\tKEY_MOUSE_WHEEL_DOWN = %d,"%(highestid), file=f); keynames[highestid] = "mousewheeldown"; highestid += 1 print(f"\tKEY_MOUSE_WHEEL_DOWN = {int(highestid)},", file=f); keynames[highestid] = "mousewheeldown"; highestid += 1
print("\tKEY_MOUSE_WHEEL_LEFT = %d,"%(highestid), file=f); keynames[highestid] = "mousewheelleft"; highestid += 1 print(f"\tKEY_MOUSE_WHEEL_LEFT = {int(highestid)},", file=f); keynames[highestid] = "mousewheelleft"; highestid += 1
print("\tKEY_MOUSE_WHEEL_RIGHT = %d,"%(highestid), file=f); keynames[highestid] = "mousewheelright"; highestid += 1 print(f"\tKEY_MOUSE_WHEEL_RIGHT = {int(highestid)},", file=f); keynames[highestid] = "mousewheelright"; highestid += 1
print("", file=f) print("", file=f)
print("\tKEY_JOYSTICK_BUTTON_0 = %d,"%(highestid), file=f); keynames[highestid] = "joystick0"; highestid += 1 print(f"\tKEY_JOYSTICK_BUTTON_0 = {int(highestid)},", file=f); keynames[highestid] = "joystick0"; highestid += 1
print("\tKEY_JOYSTICK_BUTTON_1 = %d,"%(highestid), file=f); keynames[highestid] = "joystick1"; highestid += 1 print(f"\tKEY_JOYSTICK_BUTTON_1 = {int(highestid)},", file=f); keynames[highestid] = "joystick1"; highestid += 1
print("\tKEY_JOYSTICK_BUTTON_2 = %d,"%(highestid), file=f); keynames[highestid] = "joystick2"; highestid += 1 print(f"\tKEY_JOYSTICK_BUTTON_2 = {int(highestid)},", file=f); keynames[highestid] = "joystick2"; highestid += 1
print("\tKEY_JOYSTICK_BUTTON_3 = %d,"%(highestid), file=f); keynames[highestid] = "joystick3"; highestid += 1 print(f"\tKEY_JOYSTICK_BUTTON_3 = {int(highestid)},", file=f); keynames[highestid] = "joystick3"; highestid += 1
print("\tKEY_JOYSTICK_BUTTON_4 = %d,"%(highestid), file=f); keynames[highestid] = "joystick4"; highestid += 1 print(f"\tKEY_JOYSTICK_BUTTON_4 = {int(highestid)},", file=f); keynames[highestid] = "joystick4"; highestid += 1
print("\tKEY_JOYSTICK_BUTTON_5 = %d,"%(highestid), file=f); keynames[highestid] = "joystick5"; highestid += 1 print(f"\tKEY_JOYSTICK_BUTTON_5 = {int(highestid)},", file=f); keynames[highestid] = "joystick5"; highestid += 1
print("\tKEY_JOYSTICK_BUTTON_6 = %d,"%(highestid), file=f); keynames[highestid] = "joystick6"; highestid += 1 print(f"\tKEY_JOYSTICK_BUTTON_6 = {int(highestid)},", file=f); keynames[highestid] = "joystick6"; highestid += 1
print("\tKEY_JOYSTICK_BUTTON_7 = %d,"%(highestid), file=f); keynames[highestid] = "joystick7"; highestid += 1 print(f"\tKEY_JOYSTICK_BUTTON_7 = {int(highestid)},", file=f); keynames[highestid] = "joystick7"; highestid += 1
print("\tKEY_JOYSTICK_BUTTON_8 = %d,"%(highestid), file=f); keynames[highestid] = "joystick8"; highestid += 1 print(f"\tKEY_JOYSTICK_BUTTON_8 = {int(highestid)},", file=f); keynames[highestid] = "joystick8"; highestid += 1
print("\tKEY_JOYSTICK_BUTTON_9 = %d,"%(highestid), file=f); keynames[highestid] = "joystick9"; highestid += 1 print(f"\tKEY_JOYSTICK_BUTTON_9 = {int(highestid)},", file=f); keynames[highestid] = "joystick9"; highestid += 1
print("\tKEY_JOYSTICK_BUTTON_10 = %d,"%(highestid), file=f); keynames[highestid] = "joystick10"; highestid += 1 print(f"\tKEY_JOYSTICK_BUTTON_10 = {int(highestid)},", file=f); keynames[highestid] = "joystick10"; highestid += 1
print("\tKEY_JOYSTICK_BUTTON_11 = %d,"%(highestid), file=f); keynames[highestid] = "joystick11"; highestid += 1 print(f"\tKEY_JOYSTICK_BUTTON_11 = {int(highestid)},", file=f); keynames[highestid] = "joystick11"; highestid += 1
print("", file=f) print("", file=f)
print("\tKEY_JOY_HAT0_LEFTUP = %d,"%(highestid), file=f); keynames[highestid] = "joy_hat0_leftup"; highestid += 1 print(f"\tKEY_JOY_HAT0_LEFTUP = {int(highestid)},", file=f); keynames[highestid] = "joy_hat0_leftup"; highestid += 1
print("\tKEY_JOY_HAT0_UP = %d,"%(highestid), file=f); keynames[highestid] = "joy_hat0_up"; highestid += 1 print(f"\tKEY_JOY_HAT0_UP = {int(highestid)},", file=f); keynames[highestid] = "joy_hat0_up"; highestid += 1
print("\tKEY_JOY_HAT0_RIGHTUP = %d,"%(highestid), file=f); keynames[highestid] = "joy_hat0_rightup"; highestid += 1 print(f"\tKEY_JOY_HAT0_RIGHTUP = {int(highestid)},", file=f); keynames[highestid] = "joy_hat0_rightup"; highestid += 1
print("\tKEY_JOY_HAT0_LEFT = %d,"%(highestid), file=f); keynames[highestid] = "joy_hat0_left"; highestid += 1 print(f"\tKEY_JOY_HAT0_LEFT = {int(highestid)},", file=f); keynames[highestid] = "joy_hat0_left"; highestid += 1
print("\tKEY_JOY_HAT0_RIGHT = %d,"%(highestid), file=f); keynames[highestid] = "joy_hat0_right"; highestid += 1 print(f"\tKEY_JOY_HAT0_RIGHT = {int(highestid)},", file=f); keynames[highestid] = "joy_hat0_right"; highestid += 1
print("\tKEY_JOY_HAT0_LEFTDOWN = %d,"%(highestid), file=f); keynames[highestid] = "joy_hat0_leftdown"; highestid += 1 print(f"\tKEY_JOY_HAT0_LEFTDOWN = {int(highestid)},", file=f); keynames[highestid] = "joy_hat0_leftdown"; highestid += 1
print("\tKEY_JOY_HAT0_DOWN = %d,"%(highestid), file=f); keynames[highestid] = "joy_hat0_down"; highestid += 1 print(f"\tKEY_JOY_HAT0_DOWN = {int(highestid)},", file=f); keynames[highestid] = "joy_hat0_down"; highestid += 1
print("\tKEY_JOY_HAT0_RIGHTDOWN = %d,"%(highestid), file=f); keynames[highestid] = "joy_hat0_rightdown"; highestid += 1 print(f"\tKEY_JOY_HAT0_RIGHTDOWN = {int(highestid)},", file=f); keynames[highestid] = "joy_hat0_rightdown"; highestid += 1
print("\tKEY_JOY_HAT1_LEFTUP = %d,"%(highestid), file=f); keynames[highestid] = "joy_hat1_leftup"; highestid += 1 print(f"\tKEY_JOY_HAT1_LEFTUP = {int(highestid)},", file=f); keynames[highestid] = "joy_hat1_leftup"; highestid += 1
print("\tKEY_JOY_HAT1_UP = %d,"%(highestid), file=f); keynames[highestid] = "joy_hat1_up"; highestid += 1 print(f"\tKEY_JOY_HAT1_UP = {int(highestid)},", file=f); keynames[highestid] = "joy_hat1_up"; highestid += 1
print("\tKEY_JOY_HAT1_RIGHTUP = %d,"%(highestid), file=f); keynames[highestid] = "joy_hat1_rightup"; highestid += 1 print(f"\tKEY_JOY_HAT1_RIGHTUP = {int(highestid)},", file=f); keynames[highestid] = "joy_hat1_rightup"; highestid += 1
print("\tKEY_JOY_HAT1_LEFT = %d,"%(highestid), file=f); keynames[highestid] = "joy_hat1_left"; highestid += 1 print(f"\tKEY_JOY_HAT1_LEFT = {int(highestid)},", file=f); keynames[highestid] = "joy_hat1_left"; highestid += 1
print("\tKEY_JOY_HAT1_RIGHT = %d,"%(highestid), file=f); keynames[highestid] = "joy_hat1_right"; highestid += 1 print(f"\tKEY_JOY_HAT1_RIGHT = {int(highestid)},", file=f); keynames[highestid] = "joy_hat1_right"; highestid += 1
print("\tKEY_JOY_HAT1_LEFTDOWN = %d,"%(highestid), file=f); keynames[highestid] = "joy_hat1_leftdown"; highestid += 1 print(f"\tKEY_JOY_HAT1_LEFTDOWN = {int(highestid)},", file=f); keynames[highestid] = "joy_hat1_leftdown"; highestid += 1
print("\tKEY_JOY_HAT1_DOWN = %d,"%(highestid), file=f); keynames[highestid] = "joy_hat1_down"; highestid += 1 print(f"\tKEY_JOY_HAT1_DOWN = {int(highestid)},", file=f); keynames[highestid] = "joy_hat1_down"; highestid += 1
print("\tKEY_JOY_HAT1_RIGHTDOWN = %d,"%(highestid), file=f); keynames[highestid] = "joy_hat1_rightdown"; highestid += 1 print(f"\tKEY_JOY_HAT1_RIGHTDOWN = {int(highestid)},", file=f); keynames[highestid] = "joy_hat1_rightdown"; highestid += 1
print("", file=f) print("", file=f)
print("\tKEY_JOY_AXIS_0_LEFT = %d,"%(highestid), file=f); keynames[highestid] = "joy_axis0_left"; highestid += 1 print(f"\tKEY_JOY_AXIS_0_LEFT = {int(highestid)},", file=f); keynames[highestid] = "joy_axis0_left"; highestid += 1
print("\tKEY_JOY_AXIS_0_RIGHT = %d,"%(highestid), file=f); keynames[highestid] = "joy_axis0_right"; highestid += 1 print(f"\tKEY_JOY_AXIS_0_RIGHT = {int(highestid)},", file=f); keynames[highestid] = "joy_axis0_right"; highestid += 1
print("\tKEY_JOY_AXIS_1_LEFT = %d,"%(highestid), file=f); keynames[highestid] = "joy_axis1_left"; highestid += 1 print(f"\tKEY_JOY_AXIS_1_LEFT = {int(highestid)},", file=f); keynames[highestid] = "joy_axis1_left"; highestid += 1
print("\tKEY_JOY_AXIS_1_RIGHT = %d,"%(highestid), file=f); keynames[highestid] = "joy_axis1_right"; highestid += 1 print(f"\tKEY_JOY_AXIS_1_RIGHT = {int(highestid)},", file=f); keynames[highestid] = "joy_axis1_right"; highestid += 1
print("\tKEY_JOY_AXIS_2_LEFT = %d,"%(highestid), file=f); keynames[highestid] = "joy_axis2_left"; highestid += 1 print(f"\tKEY_JOY_AXIS_2_LEFT = {int(highestid)},", file=f); keynames[highestid] = "joy_axis2_left"; highestid += 1
print("\tKEY_JOY_AXIS_2_RIGHT = %d,"%(highestid), file=f); keynames[highestid] = "joy_axis2_right"; highestid += 1 print(f"\tKEY_JOY_AXIS_2_RIGHT = {int(highestid)},", file=f); keynames[highestid] = "joy_axis2_right"; highestid += 1
print("\tKEY_JOY_AXIS_3_LEFT = %d,"%(highestid), file=f); keynames[highestid] = "joy_axis3_left"; highestid += 1 print(f"\tKEY_JOY_AXIS_3_LEFT = {int(highestid)},", file=f); keynames[highestid] = "joy_axis3_left"; highestid += 1
print("\tKEY_JOY_AXIS_3_RIGHT = %d,"%(highestid), file=f); keynames[highestid] = "joy_axis3_right"; highestid += 1 print(f"\tKEY_JOY_AXIS_3_RIGHT = {int(highestid)},", file=f); keynames[highestid] = "joy_axis3_right"; highestid += 1
print("\tKEY_JOY_AXIS_4_LEFT = %d,"%(highestid), file=f); keynames[highestid] = "joy_axis4_left"; highestid += 1 print(f"\tKEY_JOY_AXIS_4_LEFT = {int(highestid)},", file=f); keynames[highestid] = "joy_axis4_left"; highestid += 1
print("\tKEY_JOY_AXIS_4_RIGHT = %d,"%(highestid), file=f); keynames[highestid] = "joy_axis4_right"; highestid += 1 print(f"\tKEY_JOY_AXIS_4_RIGHT = {int(highestid)},", file=f); keynames[highestid] = "joy_axis4_right"; highestid += 1
print("\tKEY_JOY_AXIS_5_LEFT = %d,"%(highestid), file=f); keynames[highestid] = "joy_axis5_left"; highestid += 1 print(f"\tKEY_JOY_AXIS_5_LEFT = {int(highestid)},", file=f); keynames[highestid] = "joy_axis5_left"; highestid += 1
print("\tKEY_JOY_AXIS_5_RIGHT = %d,"%(highestid), file=f); keynames[highestid] = "joy_axis5_right"; highestid += 1 print(f"\tKEY_JOY_AXIS_5_RIGHT = {int(highestid)},", file=f); keynames[highestid] = "joy_axis5_right"; highestid += 1
print("\tKEY_JOY_AXIS_6_LEFT = %d,"%(highestid), file=f); keynames[highestid] = "joy_axis6_left"; highestid += 1 print(f"\tKEY_JOY_AXIS_6_LEFT = {int(highestid)},", file=f); keynames[highestid] = "joy_axis6_left"; highestid += 1
print("\tKEY_JOY_AXIS_6_RIGHT = %d,"%(highestid), file=f); keynames[highestid] = "joy_axis6_right"; highestid += 1 print(f"\tKEY_JOY_AXIS_6_RIGHT = {int(highestid)},", file=f); keynames[highestid] = "joy_axis6_right"; highestid += 1
print("\tKEY_JOY_AXIS_7_LEFT = %d,"%(highestid), file=f); keynames[highestid] = "joy_axis7_left"; highestid += 1 print(f"\tKEY_JOY_AXIS_7_LEFT = {int(highestid)},", file=f); keynames[highestid] = "joy_axis7_left"; highestid += 1
print("\tKEY_JOY_AXIS_7_RIGHT = %d,"%(highestid), file=f); keynames[highestid] = "joy_axis7_right"; highestid += 1 print(f"\tKEY_JOY_AXIS_7_RIGHT = {int(highestid)},", file=f); keynames[highestid] = "joy_axis7_right"; highestid += 1
print("\tKEY_JOY_AXIS_8_LEFT = %d,"%(highestid), file=f); keynames[highestid] = "joy_axis8_left"; highestid += 1 print(f"\tKEY_JOY_AXIS_8_LEFT = {int(highestid)},", file=f); keynames[highestid] = "joy_axis8_left"; highestid += 1
print("\tKEY_JOY_AXIS_8_RIGHT = %d,"%(highestid), file=f); keynames[highestid] = "joy_axis8_right"; highestid += 1 print(f"\tKEY_JOY_AXIS_8_RIGHT = {int(highestid)},", file=f); keynames[highestid] = "joy_axis8_right"; highestid += 1
print("\tKEY_JOY_AXIS_9_LEFT = %d,"%(highestid), file=f); keynames[highestid] = "joy_axis9_left"; highestid += 1 print(f"\tKEY_JOY_AXIS_9_LEFT = {int(highestid)},", file=f); keynames[highestid] = "joy_axis9_left"; highestid += 1
print("\tKEY_JOY_AXIS_9_RIGHT = %d,"%(highestid), file=f); keynames[highestid] = "joy_axis9_right"; highestid += 1 print(f"\tKEY_JOY_AXIS_9_RIGHT = {int(highestid)},", file=f); keynames[highestid] = "joy_axis9_right"; highestid += 1
print("\tKEY_JOY_AXIS_10_LEFT = %d,"%(highestid), file=f); keynames[highestid] = "joy_axis10_left"; highestid += 1 print(f"\tKEY_JOY_AXIS_10_LEFT = {int(highestid)},", file=f); keynames[highestid] = "joy_axis10_left"; highestid += 1
print("\tKEY_JOY_AXIS_10_RIGHT = %d,"%(highestid), file=f); keynames[highestid] = "joy_axis10_right"; highestid += 1 print(f"\tKEY_JOY_AXIS_10_RIGHT = {int(highestid)},", file=f); keynames[highestid] = "joy_axis10_right"; highestid += 1
print("\tKEY_JOY_AXIS_11_LEFT = %d,"%(highestid), file=f); keynames[highestid] = "joy_axis11_left"; highestid += 1 print(f"\tKEY_JOY_AXIS_11_LEFT = {int(highestid)},", file=f); keynames[highestid] = "joy_axis11_left"; highestid += 1
print("\tKEY_JOY_AXIS_11_RIGHT = %d,"%(highestid), file=f); keynames[highestid] = "joy_axis11_right"; highestid += 1 print(f"\tKEY_JOY_AXIS_11_RIGHT = {int(highestid)},", file=f); keynames[highestid] = "joy_axis11_right"; highestid += 1
print("", file=f) print("", file=f)
print("\tKEY_LAST = 512,", file=f) print("\tKEY_LAST = 512,", file=f)
print("", file=f) print("", file=f)
@ -133,7 +133,7 @@ print("", file=f)
print("const char g_aaKeyStrings[512][20] = // NOLINT(misc-definitions-in-headers)", file=f) print("const char g_aaKeyStrings[512][20] = // NOLINT(misc-definitions-in-headers)", file=f)
print("{", file=f) print("{", file=f)
for n in keynames: for n in keynames:
print('\t"%s",'%n, file=f) print(f'\t"{n}",', file=f)
print("};", file=f) print("};", file=f)
print("", file=f) print("", file=f)

View file

@ -18,7 +18,7 @@ def get_curl_calls(path):
if (filename.endswith(".cpp") or if (filename.endswith(".cpp") or
filename.endswith(".c") or filename.endswith(".c") or
filename.endswith(".h")): filename.endswith(".h")):
with open(os.path.join(directory, filename)) as f: with open(os.path.join(directory, filename), encoding="utf-8") as f:
contents = f.read() contents = f.read()
names = names.union(CURL_RE.findall(contents)) names = names.union(CURL_RE.findall(contents))
return names return names
@ -27,11 +27,11 @@ def assembly_source(names):
names = sorted(names) names = sorted(names)
result = [] result = []
for name in names: for name in names:
result.append(".type {},@function".format(name)) result.append(f".type {name},@function")
for name in names: for name in names:
result.append(".global {}".format(name)) result.append(f".global {name}")
for name in names: for name in names:
result.append("{}:".format(name)) result.append(f"{name}:")
return "\n".join(result + [""]) return "\n".join(result + [""])
DEFAULT_OUTPUT="libcurl.so" DEFAULT_OUTPUT="libcurl.so"
@ -40,8 +40,8 @@ DEFAULT_SONAME="libcurl.so.4"
def main(): def main():
p = argparse.ArgumentParser(description="Create a stub shared object for linking") p = argparse.ArgumentParser(description="Create a stub shared object for linking")
p.add_argument("-k", "--keep", action="store_true", help="Keep the intermediary assembly file") p.add_argument("-k", "--keep", action="store_true", help="Keep the intermediary assembly file")
p.add_argument("--output", help="Output filename (default: {})".format(DEFAULT_OUTPUT), default=DEFAULT_OUTPUT) p.add_argument("--output", help=f"Output filename (default: {DEFAULT_OUTPUT})", default=DEFAULT_OUTPUT)
p.add_argument("--soname", help="soname of the produced shared object (default: {})".format(DEFAULT_SONAME), default=DEFAULT_SONAME) p.add_argument("--soname", help=f"soname of the produced shared object (default: {DEFAULT_SONAME})", default=DEFAULT_SONAME)
p.add_argument("--functions", metavar="FUNCTION", nargs="+", help="Function symbols that should be put into the shared object (default: look for curl_* names in the source code)") p.add_argument("--functions", metavar="FUNCTION", nargs="+", help="Function symbols that should be put into the shared object (default: look for curl_* names in the source code)")
p.add_argument("--link-args", help="Colon-separated list of additional linking arguments") p.add_argument("--link-args", help="Colon-separated list of additional linking arguments")
args = p.parse_args() args = p.parse_args()
@ -56,7 +56,7 @@ def main():
with tempfile.NamedTemporaryFile("w", suffix=".s", delete=not args.keep) as f: with tempfile.NamedTemporaryFile("w", suffix=".s", delete=not args.keep) as f:
if args.keep: if args.keep:
print("using {} as temporary file".format(f.name)) print(f"using {f.name} as temporary file")
f.write(assembly_source(functions)) f.write(assembly_source(functions))
f.flush() f.flush()
subprocess.check_call([ subprocess.check_call([
@ -64,7 +64,7 @@ def main():
] + extra_link_args + [ ] + extra_link_args + [
"-shared", "-shared",
"-nostdlib", # don't need to link to libc "-nostdlib", # don't need to link to libc
"-Wl,-soname,{}".format(args.soname), f"-Wl,-soname,{args.soname}",
"-o", args.output, "-o", args.output,
f.name, f.name,
]) ])

View file

@ -15,7 +15,8 @@ def generate_decompositions():
ud = unicode.data() ud = unicode.data()
con = unicode.confusables() con = unicode.confusables()
category = lambda x: {unicode.unhex(u["Value"]) for u in ud if u["General_Category"].startswith(x)} def category(x):
return {unicode.unhex(u["Value"]) for u in ud if u["General_Category"].startswith(x)}
# TODO: Is this correct? They changed the decompositioning format # TODO: Is this correct? They changed the decompositioning format
nfd = {unicode.unhex(u["Value"]): unicode.unhex_sequence(u["Decomposition_Type"]) for u in ud} nfd = {unicode.unhex(u["Value"]): unicode.unhex_sequence(u["Decomposition_Type"]) for u in ud}
@ -62,8 +63,8 @@ struct DECOMP_SLICE
""") """)
print("enum") print("enum")
print("{") print("{")
print("\tNUM_DECOMP_LENGTHS = {},".format(len(len_set))) print(f"\tNUM_DECOMP_LENGTHS = {len(len_set)},")
print("\tNUM_DECOMPS = {},".format(len(decompositions))) print(f"\tNUM_DECOMPS = {len(decompositions)},")
print("};") print("};")
print() print()
@ -81,13 +82,13 @@ def gen_data(decompositions, decomposition_set, decomposition_offsets, len_set):
print("const uint8_t decomp_lengths[NUM_DECOMP_LENGTHS] = {") print("const uint8_t decomp_lengths[NUM_DECOMP_LENGTHS] = {")
for l in len_set: for l in len_set:
print("\t{},".format(l)) print(f"\t{l},")
print("};") print("};")
print() print()
print("const int32_t decomp_chars[NUM_DECOMPS] = {") print("const int32_t decomp_chars[NUM_DECOMPS] = {")
for k in sorted(decompositions): for k in sorted(decompositions):
print("\t0x{:x},".format(k)) print(f"\t0x{k:x},")
print("};") print("};")
print() print()
@ -96,14 +97,14 @@ def gen_data(decompositions, decomposition_set, decomposition_offsets, len_set):
d = decompositions[k] d = decompositions[k]
i = decomposition_set.index(tuple(d)) i = decomposition_set.index(tuple(d))
l = len_set.index(len(d)) l = len_set.index(len(d))
print("\t{{{}, {}}},".format(decomposition_offsets[i], l)) print(f"\t{{{decomposition_offsets[i]}, {l}}},")
print("};") print("};")
print() print()
print("const int32_t decomp_data[] = {") print("const int32_t decomp_data[] = {")
for d in decomposition_set: for d in decomposition_set:
for c in d: for c in d:
print("\t0x{:x},".format(c)) print(f"\t0x{c:x},")
print("};") print("};")
def main(): def main():

View file

@ -15,7 +15,7 @@ def generate_cases():
return [(unicode.unhex(u["Value"]), unicode.unhex(u["Simple_Lowercase_Mapping"])) for u in ud if u["Simple_Lowercase_Mapping"]] return [(unicode.unhex(u["Value"]), unicode.unhex(u["Simple_Lowercase_Mapping"])) for u in ud if u["Simple_Lowercase_Mapping"]]
def gen_header(cases): def gen_header(cases):
print("""\ print(f"""\
#include <stdint.h> #include <stdint.h>
struct UPPER_LOWER struct UPPER_LOWER
@ -26,10 +26,10 @@ struct UPPER_LOWER
enum enum
{{ {{
\tNUM_TOLOWER = {}, \tNUM_TOLOWER = {len(cases)},
}}; }};
extern const struct UPPER_LOWER tolowermap[];""".format(len(cases))) extern const struct UPPER_LOWER tolowermap[];""")
def gen_data(cases): def gen_data(cases):
print("""\ print("""\
@ -39,7 +39,7 @@ def gen_data(cases):
const struct UPPER_LOWER tolowermap[] = {""") const struct UPPER_LOWER tolowermap[] = {""")
for upper_code, lower_code in cases: for upper_code, lower_code in cases:
print("\t{{{}, {}}},".format(upper_code, lower_code)) print(f"\t{{{upper_code}, {lower_code}}},")
print("};") print("};")
def main(): def main():

View file

@ -1,17 +1,12 @@
import errno import errno
import subprocess import subprocess
try: try:
from subprocess import DEVNULL git_hash = subprocess.check_output(["git", "rev-parse", "--short=16", "HEAD"], stderr=subprocess.DEVNULL).decode().strip()
except ImportError: definition = f'"{git_hash}"'
import os
DEVNULL = open(os.devnull, 'wb')
try:
git_hash = subprocess.check_output(["git", "rev-parse", "--short=16", "HEAD"], stderr=DEVNULL).decode().strip()
definition = '"{}"'.format(git_hash)
except FileNotFoundError as e: except FileNotFoundError as e:
if e.errno != errno.ENOENT: if e.errno != errno.ENOENT:
raise raise
definition = "0" definition = "0"
except subprocess.CalledProcessError: except subprocess.CalledProcessError:
definition = "0" definition = "0"
print("const char *GIT_SHORTREV_HASH = {};".format(definition)) print(f"const char *GIT_SHORTREV_HASH = {definition};")

View file

@ -18,15 +18,15 @@ def hash_password(password):
def auth_add_p_line(username, level, pwhash, salt): def auth_add_p_line(username, level, pwhash, salt):
if level not in ('admin', 'mod', 'moderator', 'helper'): if level not in ('admin', 'mod', 'moderator', 'helper'):
print("Warning: level ({}) not one of admin, mod or helper.".format(level), file=sys.stderr) print(f"Warning: level ({level}) not one of admin, mod or helper.", file=sys.stderr)
if repr(level) != "'{}'".format(level): if repr(level) != f"'{level}'":
print("Warning: level ({}) contains weird symbols, config line is possibly malformed.".format(level), file=sys.stderr) print(f"Warning: level ({level}) contains weird symbols, config line is possibly malformed.", file=sys.stderr)
if repr(username) != "'{}'".format(username): if repr(username) != f"'{username}'":
print("Warning: username ({}) contains weird symbols, config line is possibly malformed.".format(username), file=sys.stderr) print(f"Warning: username ({username}) contains weird symbols, config line is possibly malformed.", file=sys.stderr)
username = username.replace('"', '\\"') username = username.replace('"', '\\"')
if ' ' in username or ';' in username: if ' ' in username or ';' in username:
username = '"{}"'.format(username) username = f'"{username}"'
return "auth_add_p {} {} {} {}".format(username, level, pwhash, salt) return f"auth_add_p {username} {level} {pwhash} {salt}"
def auth_add_p_line_from_pw(username, level, password): def auth_add_p_line_from_pw(username, level, password):
if len(password) < 8: if len(password) < 8:
@ -57,13 +57,13 @@ def main():
use_stdio = args.config is None or args.config == '-' use_stdio = args.config is None or args.config == '-'
if use_stdio: if use_stdio:
if args.config is None: if args.config is None:
input_file = open(os.devnull) input_file = open(os.devnull, encoding="utf-8")
else: else:
input_file = sys.stdin input_file = sys.stdin
output_file = sys.stdout output_file = sys.stdout
else: else:
input_file = open(args.config) input_file = open(args.config, encoding="utf-8") # pylint: disable=consider-using-with
output_file = tempfile.NamedTemporaryFile('w', dir=os.getcwd(), prefix="{}.".format(args.config), delete=False) output_file = tempfile.NamedTemporaryFile('w', dir=os.getcwd(), prefix=f"{args.config}.", delete=False) # pylint: disable=consider-using-with
for line in input_file: for line in input_file:
parsed = parse_line(line) parsed = parse_line(line)

View file

@ -21,7 +21,7 @@ class Record(namedtuple('Record', 'name time checkpoints')):
time = Decimal(lines[1]) time = Decimal(lines[1])
checkpoints_str = lines[2].split(' ') checkpoints_str = lines[2].split(' ')
if len(checkpoints_str) != 26 or checkpoints_str[25] != "": if len(checkpoints_str) != 26 or checkpoints_str[25] != "":
raise ValueError("wrong amount of checkpoint times: {}".format(len(checkpoints_str))) raise ValueError(f"wrong amount of checkpoint times: {len(checkpoints_str)}")
checkpoints_str = checkpoints_str[:25] checkpoints_str = checkpoints_str[:25]
checkpoints = tuple(Decimal(c) for c in checkpoints_str) checkpoints = tuple(Decimal(c) for c in checkpoints_str)
return Record(name=name, time=time, checkpoints=checkpoints) return Record(name=name, time=time, checkpoints=checkpoints)
@ -46,11 +46,11 @@ def main():
for in_ in args.in_: for in_ in args.in_:
match = MAP_RE.match(os.path.basename(in_)) match = MAP_RE.match(os.path.basename(in_))
if not match: if not match:
raise ValueError("Invalid text score database name, does not end in '_record.dtb': {}".format(in_)) raise ValueError(f"Invalid text score database name, does not end in '_record.dtb': {in_}")
m = match.group("map") m = match.group("map")
if m in records: if m in records:
raise ValueError("Two text score databases refer to the same map: {}".format(in_)) raise ValueError(f"Two text score databases refer to the same map: {in_}")
with open(in_) as f: with open(in_, encoding="utf-8") as f:
records[m] = read_records(f) records[m] = read_records(f)
if not args.dry_run: if not args.dry_run:
@ -62,23 +62,23 @@ def main():
"Timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, " "Timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
"Time FLOAT DEFAULT 0, " "Time FLOAT DEFAULT 0, "
"Server CHAR(4), " + "Server CHAR(4), " +
"".join("cp{} FLOAT DEFAULT 0, ".format(i + 1) for i in range(25)) + "".join(f"cp{i + 1} FLOAT DEFAULT 0, " for i in range(25)) +
"GameID VARCHAR(64), " "GameID VARCHAR(64), "
"DDNet7 BOOL DEFAULT FALSE" "DDNet7 BOOL DEFAULT FALSE"
");") ");")
c.executemany( c.executemany(
"INSERT INTO record_race (Map, Name, Time, Server, " + "INSERT INTO record_race (Map, Name, Time, Server, " +
"".join("cp{}, ".format(i + 1) for i in range(25)) + "".join(f"cp{i + 1}, " for i in range(25)) +
"GameID, DDNet7) " + "GameID, DDNet7) " +
"VALUES ({})".format(",".join("?" * 31)), f"VALUES ({','.join('?' * 31)})",
[(map, r.name, float(r.time), "TEXT", *[float(c) for c in r.checkpoints], None, False) for map in records for r in records[map]] [(map, r.name, float(r.time), "TEXT", *[float(c) for c in r.checkpoints], None, False) for map, record in records.items() for r in record]
) )
conn.commit() conn.commit()
conn.close() conn.close()
if args.stats: if args.stats:
print("Number of imported text databases: {}".format(len(records)), file=sys.stderr) print(f"Number of imported text databases: {len(records)}", file=sys.stderr)
print("Number of imported ranks: {}".format(sum(len(r) for r in records.values()), file=sys.stderr)) print(f"Number of imported ranks: {sum(len(r) for r in records.values())}", file=sys.stderr)
if __name__ == '__main__': if __name__ == '__main__':
sys.exit(main()) sys.exit(main())

View file

@ -30,6 +30,6 @@ table.sort(key=lambda l: l[3])
table = [["filename", "total", "empty", "missing", "unused"]] + table table = [["filename", "total", "empty", "missing", "unused"]] + table
s = [[str(e) for e in row] for row in table] s = [[str(e) for e in row] for row in table]
lens = [max(map(len, col)) for col in zip(*s)] lens = [max(map(len, col)) for col in zip(*s)]
fmt = " ".join("{{:{}}}".format(x) for x in lens) fmt = " ".join(f"{{:{x}}}" for x in lens)
t = [fmt.format(*row) for row in s] t = [fmt.format(*row) for row in s]
print("\n".join(t)) print("\n".join(t))

View file

@ -5,7 +5,8 @@ import sys
import twlang import twlang
def copy_fix(infile, delete_unused, append_missing, delete_empty): def copy_fix(infile, delete_unused, append_missing, delete_empty):
content = open(infile).readlines() with open(infile, encoding="utf-8") as f:
content = f.readlines()
trans = twlang.translations(infile) trans = twlang.translations(infile)
if delete_unused or append_missing: if delete_unused or append_missing:
local = twlang.localizes() local = twlang.localizes()
@ -59,7 +60,8 @@ def main(argv):
content = copy_fix(infile, delete_unused, append_missing, delete_empty) content = copy_fix(infile, delete_unused, append_missing, delete_empty)
open(outfile, "w").write("".join(content)) with open(outfile, "w", encoding="utf-8") as f:
f.write("".join(content))
print("Successfully created '" + outfile + "'.") print("Successfully created '" + outfile + "'.")
if __name__ == '__main__': if __name__ == '__main__':

View file

@ -4,7 +4,7 @@ from collections import OrderedDict
class LanguageDecodeError(Exception): class LanguageDecodeError(Exception):
def __init__(self, message, filename, line): def __init__(self, message, filename, line):
error = "File \"{1}\", line {2}: {0}".format(message, filename, line+1) error = f"File \"{filename}\", line {line+1}: {message}"
super().__init__(error) super().__init__(error)
@ -45,7 +45,7 @@ def decode(fileobj, elements_per_key):
if len(data[current_key]) >= 1+elements_per_key: if len(data[current_key]) >= 1+elements_per_key:
raise LanguageDecodeError("Wrong number of elements per key", fileobj.name, index) raise LanguageDecodeError("Wrong number of elements per key", fileobj.name, index)
if current_key: if current_key:
original = current_key[0] # pylint: disable=E1136 original = current_key[0] # pylint: disable=unsubscriptable-object
translation = line[3:] translation = line[3:]
if translation and [m.group(1) for m in re.finditer(cfmt, original, flags=re.X)] != [m.group(1) for m in re.finditer(cfmt, translation, flags=re.X)]: if translation and [m.group(1) for m in re.finditer(cfmt, original, flags=re.X)] != [m.group(1) for m in re.finditer(cfmt, translation, flags=re.X)]:
raise LanguageDecodeError("Non-matching formatting string", fileobj.name, index) raise LanguageDecodeError("Non-matching formatting string", fileobj.name, index)
@ -68,7 +68,7 @@ def decode(fileobj, elements_per_key):
def check_file(path): def check_file(path):
with open(path) as fileobj: with open(path, encoding="utf-8") as fileobj:
matches = re.findall(r"Localize\s*\(\s*\"([^\"]+)\"(?:\s*,\s*\"([^\"]+)\")?\s*\)", fileobj.read()) matches = re.findall(r"Localize\s*\(\s*\"([^\"]+)\"(?:\s*,\s*\"([^\"]+)\")?\s*\)", fileobj.read())
return matches return matches
@ -86,13 +86,15 @@ def check_folder(path):
def languages(): def languages():
index = decode(open("data/languages/index.txt"), 2) with open("data/languages/index.txt", encoding="utf-8") as f:
index = decode(f, 2)
langs = {"data/languages/"+key[0]+".txt" : [key[0]]+elements for key, elements in index.items()} langs = {"data/languages/"+key[0]+".txt" : [key[0]]+elements for key, elements in index.items()}
return langs return langs
def translations(filename): def translations(filename):
return decode(open(filename), 1) with open(filename, encoding="utf-8") as f:
return decode(f, 1)
def localizes(): def localizes():

View file

@ -7,4 +7,5 @@ os.chdir(os.path.dirname(__file__) + "/../..")
for lang in twlang.languages(): for lang in twlang.languages():
content = copy_fix(lang, delete_unused=True, append_missing=True, delete_empty=False) content = copy_fix(lang, delete_unused=True, append_missing=True, delete_empty=False)
open(lang, "w").write(content) with open(lang, "w", encoding="utf-8") as f:
f.write(content)

View file

@ -18,14 +18,14 @@ from time import strftime
import os import os
def sqlite_table_exists(cursor, table): def sqlite_table_exists(cursor, table):
cursor.execute("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='{}'".format(table)) cursor.execute(f"SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='{table}'")
return cursor.fetchone()[0] != 0 return cursor.fetchone()[0] != 0
def sqlite_num_transfer(conn, table): def sqlite_num_transfer(conn, table):
c = conn.cursor() c = conn.cursor()
if not sqlite_table_exists(c, table): if not sqlite_table_exists(c, table):
return 0 return 0
c.execute('SELECT COUNT(*) FROM {}'.format(table)) c.execute(f'SELECT COUNT(*) FROM {table}')
num = c.fetchone()[0] num = c.fetchone()[0]
return num return num
@ -66,7 +66,7 @@ def main():
args = parser.parse_args() args = parser.parse_args()
if not os.path.exists(args.f): if not os.path.exists(args.f):
print("Warning: '{}' does not exist (yet). Is the path specified correctly?".format(args.f)) print(f"Warning: '{args.f}' does not exist (yet). Is the path specified correctly?")
return return
conn = sqlite3.connect(args.f) conn = sqlite3.connect(args.f)
@ -78,22 +78,18 @@ def main():
if num == 0: if num == 0:
return return
print('{} new entries in backup database found ({} ranks, {} teamranks, {} saves'.format(num, num_ranks, num_teamranks, num_saves)) print(f'{num} new entries in backup database found ({num_ranks} ranks, {num_teamranks} teamranks, {num_saves} saves')
print('Moving entries from {} to {}'.format( print('Moving entries from {os.path.abspath(args.f)} to {os.path.abspath(args.to)}')
os.path.abspath(args.f),
os.path.abspath(args.to)))
sql_file = 'ddnet-server-' + strftime('%Y-%m-%d') + '.sql' sql_file = 'ddnet-server-' + strftime('%Y-%m-%d') + '.sql'
print("You can use the following commands to import the entries to MySQL (use sed 's/record_/prefix_/' for other database prefixes):") print("You can use the following commands to import the entries to MySQL (use sed 's/record_/prefix_/' for other database prefixes):")
print() print()
print((" echo '.dump --preserve-rowids' | sqlite3 {} | " + # including rowids, this forces sqlite to name all columns in each INSERT statement print((f" echo '.dump --preserve-rowids' | sqlite3 {os.path.abspath(args.to)} | " + # including rowids, this forces sqlite to name all columns in each INSERT statement
"grep -E '^INSERT INTO record_(race|teamrace|saves)' | " + # filter out inserts "grep -E '^INSERT INTO record_(race|teamrace|saves)' | " + # filter out inserts
"sed -e 's/INSERT INTO/INSERT IGNORE INTO/' | " + # ignore duplicate rows "sed -e 's/INSERT INTO/INSERT IGNORE INTO/' | " + # ignore duplicate rows
"sed -e 's/rowid,//' -e 's/VALUES([0-9]*,/VALUES(/' > {}") # filter out rowids again f"sed -e 's/rowid,//' -e 's/VALUES([0-9]*,/VALUES(/' > {sql_file}")) # filter out rowids again
.format(os.path.abspath(args.to), sql_file)) print(f" mysql -u teeworlds -p'PW2' teeworlds < {sql_file}")
print(" mysql -u teeworlds -p'PW2' teeworlds < {}".format(sql_file))
print() print()
print("When the ranks are transfered successfully to mysql, {} can be removed".format( print(f"When the ranks are transfered successfully to mysql, {os.path.abspath(args.to)} can be removed")
os.path.abspath(args.to)))
print() print()
print("Log of the transfer:") print("Log of the transfer:")
print() print()

View file

@ -226,7 +226,7 @@ def get_list2(address):
master_servers = [] master_servers = []
for i in range(1, NUM_MASTERSERVERS+1): for i in range(1, NUM_MASTERSERVERS+1):
m = Master_Server_Info(("master%d.teeworlds.com"%i, MASTERSERVER_PORT)) m = Master_Server_Info((f"master{int(i)}.teeworlds.com", MASTERSERVER_PORT))
master_servers.append(m) master_servers.append(m)
m.start() m.start()
time.sleep(0.001) # avoid issues time.sleep(0.001) # avoid issues

View file

@ -25,7 +25,7 @@ UNICODEDATA_FIELDS = (
) )
def data(): def data():
with open('UnicodeData.txt') as f: with open('UnicodeData.txt', encoding='utf-8') as f:
return list(csv.DictReader(f, fieldnames=UNICODEDATA_FIELDS, delimiter=';')) return list(csv.DictReader(f, fieldnames=UNICODEDATA_FIELDS, delimiter=';'))
def unhex(s): def unhex(s):

View file

@ -1,9 +1,9 @@
print("#ifndef GENERATED_WORDLIST_H") print("#ifndef GENERATED_WORDLIST_H")
print("#define GENERATED_WORDLIST_H") print("#define GENERATED_WORDLIST_H")
print("const char g_aFallbackWordlist[][32] = {") print("const char g_aFallbackWordlist[][32] = {")
with open("data/wordlist.txt") as f: with open("data/wordlist.txt", encoding="utf-8") as f:
for line in f: for line in f:
word = line.strip().split("\t")[1] word = line.strip().split("\t")[1]
print("\t\"%s\", " % word) print(f"\t\"{word}\", ")
print("};") print("};")
print("#endif // GENERATED_WORDLIST_H") print("#endif // GENERATED_WORDLIST_H")