sort of works with OOP

class_based_refactor
Nicholas Hope 2022-08-21 21:21:09 -04:00
parent 9ba82add22
commit c3b816c532
1 changed files with 38 additions and 38 deletions

View File

@ -1,13 +1,13 @@
""" '''
Command line module for making Team Fortress 2 macro scripts from Command line module for making Team Fortress 2 macro scripts from
YAML source code. YAML source code.
""" '''
__all__ = ['parseFile'] __all__ = ['parseFile']
__author__ = "Nicholas Hope <tfscript@nickhope.world" __author__ = 'Nicholas Hope <tfscript@nickhope.world'
__date__ = "26 August 2022" __date__ = '26 August 2022'
__version__ = "1.0" __version__ = '1.0'
__copyright__ = "Copyright © 2022 Nicholas Hope. See LICENSE for details." __copyright__ = 'Copyright © 2022 Nicholas Hope. See LICENSE for details.'
# Standard libraries # Standard libraries
from sys import stderr from sys import stderr
@ -31,38 +31,38 @@ from tfscript import verify
from tfscript import writing from tfscript import writing
args = {} args = {}
targetDir = "" targetDir = ''
def parseFile(inputFile) -> (dict, dict): def parseFile(inputFile) -> (dict, dict):
"""Parse, verify, and do the conversion.""" '''Parse, verify, and do the conversion.'''
config = yaml.safe_load(inputFile) config = yaml.safe_load(inputFile)
# See verify.py # See verify.py
config, aliases = verify.verifyConfig(config) config, defaults = verify.verifyConfig(config)
if "errors" in config: if 'errors' in config:
for cclass, messages in config["errors"].items(): for cclass, messages in config['errors'].items():
print(f"Error in {cclass}:") print(f'Error in {cclass}:')
for msg in messages: for msg in messages:
print(f" {msg}") print(f' {msg}')
return None, None return None, None
else: else:
return config, aliases return config, defaults
def parseConfig(config, defaults): def parseConfig(config, defaults):
"""With validated data structure, write out all the files.""" '''With validated data structure, write out all the files.'''
global args global args
global targetDir global targetDir
if isdir(targetDir) == False: if isdir(targetDir) == False:
mkdir(targetDir) mkdir(targetDir)
if args.debug: if args.debug:
print( f"DEBUG: Created directory {targetDir}", file=stderr) print( f'DEBUG: Created directory {targetDir}', file=stderr)
tempsAndReals = {} tempsAndReals = {}
if defaults is not None: if defaults is not None:
stringToWrite = tfscript.makeCFG(defaults, default=True) stringToWrite = tfscript.makeCFG(defaults, default=True)
replaceDict = writing.writeOutput(stringToWrite, "default", args) replaceDict = writing.writeOutput(stringToWrite, 'default', args)
tempsAndReals.update(replaceDict) tempsAndReals.update(replaceDict)
for currentClass in config: for currentClass in config:
@ -76,56 +76,56 @@ def parseConfig(config, defaults):
def parseCLI(): def parseCLI():
# Handle command line # Handle command line
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
description="Parse YAML file and produce TF2 config script." description='Parse YAML file and produce TF2 config script.'
) )
parser.add_argument( '-d', '--debug', action='store_true', parser.add_argument( '-d', '--debug', action='store_true',
help="Enable debugging messages.") help='Enable debugging messages.')
parser.add_argument( '-n', '--dry-run', action='store_true', parser.add_argument( '-n', '--dry-run', action='store_true',
help="Parse input file, but don't write anything.") help='Parse input file, but don\'t write anything.')
parser.add_argument( '-f', '--force', action='store_true', parser.add_argument( '-f', '--force', action='store_true',
help="Force tfscript to continue until catastrophic failure") help='Force tfscript to continue until catastrophic failure')
parser.add_argument( '-D', '--directory', action='store', type=str, parser.add_argument( '-D', '--directory', action='store', type=str,
help="Change output directory") help='Change output directory')
# positional argument: first non-hyphenated argument is input file # positional argument: first non-hyphenated argument is input file
parser.add_argument( 'infile', type=argparse.FileType('r'), parser.add_argument( 'infile', type=argparse.FileType('r'),
help='File containing YAML to convert.') help='File containing YAML to convert.')
return parser return parser
def getTargetDir(systemName): def getTargetDir(systemName):
if systemName == "Darwin": if systemName == 'Darwin':
if float( '.'.join( GetOSRelease().split('.')[0:2] ) ) >= 10.15: if float( '.'.join( GetOSRelease().split('.')[0:2] ) ) >= 10.15:
warn( warn(
"As of macOS Catalina (v10.15), 32-bit applications " 'As of macOS Catalina (v10.15), 32-bit applications '
"like TF2 do not run. tfscript will run, but you can't run TF2 " 'like TF2 do not run. tfscript will run, but you can\'t run TF2 '
"on this system", 'on this system',
category=RuntimeWarning ) category=RuntimeWarning )
return expanduser("~/Library/Application Support/Steam") return expanduser('~/Library/Application Support/Steam')
elif systemName == "Windows": elif systemName == 'Windows':
# oh god why do we have to use the registry # oh god why do we have to use the registry
accessReg = ConnectRegistry(None, HKEY_LOCAL_MACHINE) accessReg = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
accessKey = OpenKey(accessReg, "SOFTWARE\\WOW6432Node\\Valve\\Steam") accessKey = OpenKey(accessReg, 'SOFTWARE\\WOW6432Node\\Valve\\Steam')
keyNum = 0 keyNum = 0
while True: while True:
try: try:
accessSubkeyName, data, _ = EnumValue(accessKey, keyNum) accessSubkeyName, data, _ = EnumValue(accessKey, keyNum)
if accessSubkeyName == "InstallPath": if accessSubkeyName == 'InstallPath':
return data return data
except EnvironmentError: except EnvironmentError:
break break
keyNum += 1 keyNum += 1
return None return None
elif systemName == "Linux": elif systemName == 'Linux':
return expanduser("~/.local/Steam") return expanduser('~/.local/Steam')
elif systemName == "Java": elif systemName == 'Java':
warn("Java-based OSes are not supported yet by tfscript.", category=RuntimeWarning) warn('Java-based OSes are not supported yet by tfscript.', category=RuntimeWarning)
return None return None
def main() -> int: def main() -> int:
""" Command line interface. """ ''' Command line interface. '''
global args global args
global targetDir global targetDir
parser = parseCLI() parser = parseCLI()
@ -139,11 +139,11 @@ def main() -> int:
targetDir = getTargetDir(systemName) targetDir = getTargetDir(systemName)
if targetDir is not None: if targetDir is not None:
# Supported OS: add steamapps path # Supported OS: add steamapps path
targetDir += normpath("/steamapps/common/Team Fortress 2/tf/cfg") + dirsep targetDir += normpath('/steamapps/common/Team Fortress 2/tf/cfg') + dirsep
elif args.force: elif args.force:
# Unsupported OS but -f specified # Unsupported OS but -f specified
if args.debug: if args.debug:
print("DEBUG: forced to continue, output set to current directory", file=stderr) print('DEBUG: forced to continue, output set to current directory', file=stderr)
targetDir = '.' targetDir = '.'
else: else:
# Unsupported OS and not forced to continue # Unsupported OS and not forced to continue
@ -160,5 +160,5 @@ def main() -> int:
return 0 return 0
if __name__ == "__main__": if __name__ == '__main__':
exit(main()) exit(main())