Added checks for OS to determine target directory
parent
71ba2de1e2
commit
8904632b06
|
@ -7,12 +7,20 @@ import os
|
|||
import argparse
|
||||
import tempfile
|
||||
import yaml
|
||||
from platform import system as getOS, release
|
||||
|
||||
try:
|
||||
import winreg
|
||||
except ModuleNotFoundError:
|
||||
# Not running on windows
|
||||
pass
|
||||
|
||||
# Local libraries
|
||||
import tfscript
|
||||
from tfscript import verify
|
||||
|
||||
args = {}
|
||||
targetDir = ""
|
||||
|
||||
def parseFile(inputFile):
|
||||
"""Parse, verify, and do the conversion."""
|
||||
|
@ -29,18 +37,18 @@ def parseFile(inputFile):
|
|||
def writeOutput(scriptString, className):
|
||||
"""Given the string of stuff to write, write it out to the given handle."""
|
||||
global args
|
||||
prefix = './cfg'
|
||||
global targetDir
|
||||
chunksize = 2**20 # 1Mb maximum cfg file size
|
||||
chunk = 1
|
||||
# Make sure ./cfg exists before we try to use it
|
||||
if os.path.isdir( prefix ) == False:
|
||||
# Make sure the target exists before we try to use it
|
||||
if os.path.isdir( targetDir ) == False:
|
||||
try:
|
||||
os.mkdir( prefix )
|
||||
os.mkdir( targetDir )
|
||||
if args.debug:
|
||||
print( f'DEBUG: created {prefix}')
|
||||
print( f'DEBUG: created {targetDir}')
|
||||
except Exception as fileExcept:
|
||||
print( f'WARN: Failed to create {prefix}: {fileExcept.strerror}\nUsing current directory instead.' )
|
||||
prefix = '.'
|
||||
print( f'WARN: Failed to create {targetDir}: {fileExcept.strerror}\nUsing current directory instead.' )
|
||||
targetDir = '.'
|
||||
# If the string is more than 1048576 bytes, we need divide it into files that each
|
||||
# are less than 1048576 bytes
|
||||
chunksneeded = int( 1 + len(scriptString) / chunksize )
|
||||
|
@ -53,12 +61,12 @@ def writeOutput(scriptString, className):
|
|||
outfile.write(scriptString.encode("utf8"))
|
||||
outfile.close()
|
||||
if( args.dry_run != True ):
|
||||
os.replace(outfile.name, f'{prefix}/{className}_script_{chunk:02d}.cfg')
|
||||
os.replace(outfile.name, f'{targetDir}/{className}_script_{chunk:02d}.cfg')
|
||||
if args.debug:
|
||||
print( f'DEBUG: Created {prefix}/{className}_script_{chunk:02d}.cfg')
|
||||
print( f'DEBUG: Created {targetDir}/{className}_script_{chunk:02d}.cfg')
|
||||
else:
|
||||
if args.debug:
|
||||
print( f'DEBUG: {outfile.name} would be {prefix}/{className}_script_{chunk:02d}.cfg')
|
||||
print( f'DEBUG: {outfile.name} would be {targetDir}/{className}_script_{chunk:02d}.cfg')
|
||||
else:
|
||||
# Gotta do it in multiple chunks
|
||||
classLines = scriptString.splitlines()
|
||||
|
@ -69,7 +77,7 @@ def writeOutput(scriptString, className):
|
|||
pieces = {}
|
||||
while( chunk <= chunksneeded ):
|
||||
outfile = tempfile.NamedTemporaryFile( prefix=className, delete=False )
|
||||
pieces[outfile.name] = f'{prefix}/{className}_script_{chunk:02d}.cfg'
|
||||
pieces[outfile.name] = f'{targetDir}/{className}_script_{chunk:02d}.cfg'
|
||||
byteswritten = 0
|
||||
while( n < len(classLines) and (byteswritten + len(classLines[n]) + reservedSpace) < chunksize ):
|
||||
line = classLines[n].encode("utf8") + os.linesep.encode("utf8")
|
||||
|
@ -88,10 +96,10 @@ def writeOutput(scriptString, className):
|
|||
for tmpname, realname in pieces.items():
|
||||
if( args.dry_run ):
|
||||
if( args.debug ):
|
||||
print( f'DEBUG: {outfile.name} would be {prefix}/{className}_script_{chunk:02d}.cfg')
|
||||
print( f'DEBUG: {outfile.name} would be {targetDir}/{className}_script_{chunk:02d}.cfg')
|
||||
else:
|
||||
os.replace(tmpname, realname)
|
||||
print( f'DEBUG: Created {prefix}/{className}_script_{chunk:02d}.cfg')
|
||||
print( f'DEBUG: Created {targetDir}/{className}_script_{chunk:02d}.cfg')
|
||||
|
||||
def parseConfig(config):
|
||||
"""With validated data structure, write out all the files."""
|
||||
|
@ -103,6 +111,7 @@ def parseConfig(config):
|
|||
def main():
|
||||
"""Run as a CLI tool"""
|
||||
global args
|
||||
global targetDir
|
||||
# Handle command line
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Parse YAML file and produce TF2 config script."
|
||||
|
@ -111,11 +120,44 @@ def main():
|
|||
help="Enable debugging messages.")
|
||||
parser.add_argument( '-n', '--dry-run', action='store_true',
|
||||
help="Parse input file, but don't write anything.")
|
||||
parser.add_argument( '--directory', action='store', type=str,
|
||||
help='Change output directory')
|
||||
# positional argument: first non-hyphenated argument is input file
|
||||
parser.add_argument( 'infile', type=argparse.FileType('r'),
|
||||
help='File containing YAML to convert.')
|
||||
args = parser.parse_args()
|
||||
if args.directory is None:
|
||||
systemName = getOS()
|
||||
if systemName == "Darwin":
|
||||
if float( '.'.join(release().split('.')[0:2]) ) >= 10.15:
|
||||
print(
|
||||
"As of macOS Catalina (v10.15), 32-bit applications "
|
||||
"such as tf2 do not work, so tfscript does not function",
|
||||
file=sys.stderr
|
||||
)
|
||||
return 2
|
||||
targetDir = os.path.expanduser("~/Library/Application Support/Steam/")
|
||||
|
||||
if systemName == "Windows":
|
||||
# Oh god why do we have to use the registry!
|
||||
# "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Valve\Steam\InstallPath" "InstallPath"
|
||||
accessReg = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
|
||||
accessKey = winreg.OpenKey(accessReg, "SOFTWARE\WOW6432Node\Valve\Steam\InstallPath")
|
||||
targetDir = winreg.QueryValue(accessKey, "InstallPath")
|
||||
|
||||
if systemName == "Linux":
|
||||
targetDir = os.path.expanduser("~/.local/Steam")
|
||||
|
||||
if systemName == "Java":
|
||||
print("Java-based OSes are not supported yet by tfscript.", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
targetDir += "steamapps/common/Team Fortress 2/tf/cfg"
|
||||
else:
|
||||
targetDir = args.directory
|
||||
print(targetDir)
|
||||
parseFile(args.infile)
|
||||
return 0
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
exit(main())
|
||||
|
|
Loading…
Reference in New Issue