awlsim-symtab 4.11 KB
Newer Older
1 2 3 4 5
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# AWL simulator - Symbol table parser
#
Michael Büsch's avatar
Michael Büsch committed
6
# Copyright 2014-2016 Michael Buesch <m@bues.ch>
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#

from __future__ import division, absolute_import, print_function, unicode_literals

import sys
import getopt

28 29
from awlsim_loader.common import *
from awlsim_loader.core import *
30 31 32


def usage():
33
	print("awlsim-symtab symbol table parser, version %s" %\
Michael Büsch's avatar
Michael Büsch committed
34
		  VERSION_STRING)
35
	print("")
36
	print("Usage: awlsim-symtab [OPTIONS] [inputfile] [outputfile]")
37
	print("")
38
	print("If inputfile is - or omitted, stdin is used.")
39 40 41 42 43 44 45 46 47 48 49 50
	print("If outputfile is - or omitted, stdout is used.")
	print("")
	print("Options:")
	print(" -I|--input-format FMT     Input file format.")
	print("                           FMT may be one of: auto, csv, asc")
	print("                           Default: auto")
	print(" -O|--output-format FMT    Input file format.")
	print("                           FMT may be one of: csv, readable-csv, asc")
	print("                           Default: readable-csv")
	print("")
	print("Example usage for converting .ASC to readable .CSV:")
	print(" awlsim-symtab -I asc -O readable-csv symbols.asc symbols.csv")
51 52 53 54 55 56 57 58 59 60 61 62 63 64

def main():
	opt_inputParser = None
	opt_outputFormat = "readable-csv"
	opt_infile = "-"
	opt_outfile = "-"

	try:
		(opts, args) = getopt.getopt(sys.argv[1:],
			"hI:O:",
			[ "help", "input-format=", "output-format=", ])
	except getopt.GetoptError as e:
		printError(str(e))
		usage()
Michael Büsch's avatar
Michael Büsch committed
65
		return ExitCodes.EXIT_ERR_CMDLINE
66 67 68
	for (o, v) in opts:
		if o in ("-h", "--help"):
			usage()
Michael Büsch's avatar
Michael Büsch committed
69
			return ExitCodes.EXIT_OK
70 71 72 73 74 75 76 77 78
		if o in ("-I", "--input-format"):
			if v.lower() == "auto":
				opt_inputParser = None
			elif v.lower() in ("csv", "readable-csv"):
				opt_inputParser = SymTabParser_CSV
			elif v.lower() == "asc":
				opt_inputParser = SymTabParser_ASC
			else:
				printError("Invalid --input-format")
Michael Büsch's avatar
Michael Büsch committed
79
				return ExitCodes.EXIT_ERR_CMDLINE
80 81 82 83
		if o in ("-O", "--output-format"):
			opt_outputFormat = v.lower()
			if opt_outputFormat not in ("csv", "readable-csv", "asc"):
				printError("Invalid --output-format")
Michael Büsch's avatar
Michael Büsch committed
84
				return ExitCodes.EXIT_ERR_CMDLINE
85 86 87 88 89
	if len(args) == 1:
		opt_infile = args[0]
	elif len(args) == 2:
		opt_infile = args[0]
		opt_outfile = args[1]
90
	elif len(args) > 2:
91
		usage()
Michael Büsch's avatar
Michael Büsch committed
92
		return ExitCodes.EXIT_ERR_CMDLINE
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134

	try:
		if opt_infile == "-":
			if isPy2Compat:
				inDataBytes = sys.stdin.read()
			else:
				inDataBytes = sys.stdin.buffer.read()
		else:
			inDataBytes = awlFileRead(opt_infile,
						  encoding="binary")

		if opt_inputParser:
			tab = opt_inputParser.parseData(inDataBytes,
							autodetectFormat=False)
		else:
			tab = SymTabParser.parseData(inDataBytes,
						     autodetectFormat=True)

		if opt_outputFormat == "csv":
			outDataBytes = tab.toCSV()
		elif opt_outputFormat == "readable-csv":
			outDataBytes = tab.toReadableCSV()
		elif opt_outputFormat == "asc":
			outDataBytes = tab.toASC()
		else:
			assert(0)

		if opt_outfile == "-":
			if isPy2Compat:
				sys.stdout.write(outDataBytes)
				sys.stdout.flush()
			else:
				sys.stdout.buffer.write(outDataBytes)
				sys.stdout.buffer.flush()
		else:
			try:
				fd = open(opt_outfile, "wb")
				fd.write(outDataBytes)
				fd.close()
			except IOError as e:
				printError("Failed to write output file '%s': %s" %\
					   (opt_outfile, str(e)))
Michael Büsch's avatar
Michael Büsch committed
135
				return ExitCodes.EXIT_ERR_IO
136 137
	except AwlSimError as e:
		printError(e.getReport())
Michael Büsch's avatar
Michael Büsch committed
138 139
		return ExitCodes.EXIT_ERR_SIM
	return ExitCodes.EXIT_OK
140 141 142

if __name__ == "__main__":
	sys.exit(main())