summaryrefslogtreecommitdiffstats
path: root/awlsim/project.py
blob: 85114676330be70f5b9599afde55244b010670d7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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
135
136
137
138
139
140
141
142
143
144
145
146
147
# -*- coding: utf-8 -*-
#
# AWL simulator - project
#
# Copyright 2014 Michael Buesch <m@bues.ch>
#
# 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 awlsim.util import *

import datetime
import os
import io

if isPy2Compat:
	from ConfigParser import SafeConfigParser as _ConfigParser
	from ConfigParser import Error as _ConfigParserError
else:
	from configparser import ConfigParser as _ConfigParser
	from configparser import Error as _ConfigParserError


class Project(object):
	def __init__(self, projectFile, awlFiles=[], symTabFiles=[]):
		self.projectFile = projectFile
		self.awlFiles = awlFiles
		self.symTabFiles = symTabFiles

	@classmethod
	def dataIsProject(cls, data):
		return data.lstrip().startswith(b"[AWLSIM_PROJECT]")

	@classmethod
	def fileIsProject(cls, filename):
		return cls.dataIsProject(awlFileRead(filename, encoding="binary"))

	@classmethod
	def fromText(cls, text, projectFile):
		if not cls.dataIsProject(text.encode("utf-8")):
			raise AwlSimError("Project file: The data is "\
				"not an awlsim project.")
		projectDir = os.path.dirname(projectFile)
		awlFiles = []
		symTabFiles = []
		try:
			p = _ConfigParser()
			p.readfp(io.StringIO(text), projectFile)
			version = p.getint("AWLSIM_PROJECT", "file_version")
			expectedVersion = 0
			if version != expectedVersion:
				raise AwlSimError("Project file: Unsupported version. "\
					"File version is %d, but expected %d." %\
					(version, expectedVersion))

			nrAwl = p.getint("CPU", "nr_awl_files")
			if nrAwl < 0 or nrAwl > 0xFFFF:
				raise AwlSimError("Project file: Invalid number of "\
					"AWL files: %d" % nrAwl)
			for i in range(nrAwl):
				path = p.get("CPU", "awl_file_%d" % i)
				awlFiles.append(cls.__generic2path(path, projectDir))

			nrSymTab = p.getint("SYMBOLS", "nr_sym_tab_files")
			if nrSymTab < 0 or nrSymTab > 0xFFFF:
				raise AwlSimError("Project file: Invalid number of "
					"symbol table files: %d" % nrSymTab)
			for i in range(nrSymTab):
				path = p.get("SYMBOLS", "sym_tab_file_%d" % i)
				symTabFiles.append(cls.__generic2path(path, projectDir))

		except _ConfigParserError as e:
			raise AwlSimError("Project parser error: " + str(e))

		return cls(projectFile = projectFile,
			   awlFiles = awlFiles,
			   symTabFiles = symTabFiles)

	@classmethod
	def fromFile(cls, filename):
		return cls.fromText(awlFileRead(filename, encoding="utf8"), filename)

	@classmethod
	def __path2generic(cls, path, relativeToDir):
		"""Generate an OS-independent string from a path."""
		if "\r" in path or "\n" in path:
			# The project file format cannot handle these
			raise AwlSimError("Project file: Path '%s' contains invalid "\
				"characters (line breaks)." % path)
		path = os.path.relpath(path, relativeToDir)
		if os.path.splitdrive(path)[0]:
			raise AwlSimError("Project file: Failed to strip drive letter. "\
				"Please make sure the project file, AWL code files and "\
				"symbol tables files all reside on the same drive.")
		path = path.replace(os.path.sep, "/")
		return path

	@classmethod
	def __generic2path(cls, path, relativeToDir):
		"""Generate a path from an OS-independent string."""
		path = path.replace("/", os.path.sep)
		path = os.path.join(relativeToDir, path)
		return path

	def toText(self, projectFile=None):
		if not projectFile:
			projectFile = self.projectFile
		projectDir = os.path.dirname(projectFile)

		lines = []
		lines.append("[AWLSIM_PROJECT]")
		lines.append("file_version=0")
		lines.append("date=%s" % str(datetime.datetime.utcnow()))
		lines.append("")
		lines.append("[CPU]")
		lines.append("nr_awl_files=%d" % len(self.awlFiles))
		for i, awlFile in enumerate(self.awlFiles):
			path = self.__path2generic(awlFile, projectDir)
			lines.append("awl_file_%d=%s" % (i, path))
		lines.append("")
		lines.append("[SYMBOLS]")
		lines.append("nr_sym_tab_files=%d" % len(self.symTabFiles))
		for i, symTabFile in enumerate(self.symTabFiles):
			path = self.__path2generic(symTabFile, projectDir)
			lines.append("sym_tab_file_%d=%s" % (i, symTabFile))
		return "\r\n".join(lines)

	def toFile(self, projectFile=None):
		if not projectFile:
			projectFile = self.projectFile
		if not projectFile:
			raise AwlSimError("Project file: Cannot generate project file. "
				"No file name specified.")
		text = self.toText(projectFile)
		awlFileWrite(projectFile, text, encoding="utf8")
bues.ch cgit interface