summaryrefslogtreecommitdiffstats
path: root/setup.py
blob: c77f6c1a22978f7886e2a2df39d0b4b7a1359110 (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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
#!/usr/bin/env python3

import sys
import os
import platform
import errno
import re
import shutil
import hashlib
from distutils.core import setup
from distutils.extension import Extension
from awlsim.version import VERSION_MAJOR, VERSION_MINOR


def makedirs(path, mode):
	try:
		os.makedirs(path, mode)
	except OSError as e:
		if e.errno == errno.EEXIST:
			return
		raise

def hashFile(path):
	if sys.version_info[0] < 3:
		ExpectedException = IOError
	else:
		ExpectedException = FileNotFoundError
	try:
		return hashlib.sha1(open(path, "rb").read()).hexdigest()
	except ExpectedException as e:
		return None

def pyCythonPatch(toFile, fromFile):
	print("cython-patch: patching file '%s' to '%s'" %\
	      (fromFile, toFile))
	tmpFile = toFile + ".TMP"
	infd = open(fromFile, "r")
	outfd = open(tmpFile, "w")
	for line in infd.readlines():
		stripLine = line.strip()

		if not stripLine.endswith("#<no-cython-patch"):
			# Uncomment all lines containing <cython>
			if "<cython>" in stripLine:
				line = re.sub(r'#?<cython>\s*', "", line)
				if line.startswith("#"):
					line = line[1:]
				if not line.endswith("\n"):
					line += "\n"

			# Comment all lines containing <no-cython>
			if "<no-cython>" in stripLine:
				line = "#" + line

			# Patch the import statements
			line = re.sub(r'^from awlsim\.', "from awlsim_cython.", line)
			line = re.sub(r'^import awlsim\.', "import awlsim_cython.", line)

		outfd.write(line)
	infd.close()
	outfd.flush()
	outfd.close()
	toFileHash = hashFile(toFile)
	newFileHash = hashFile(tmpFile)
	if toFileHash is not None and\
	   toFileHash == newFileHash:
		print("(already up to date)")
		os.unlink(tmpFile)
		return
	os.rename(tmpFile, toFile)

def addCythonModules(Cython_build_ext):
	global cmdclass
	global ext_modules

	modDir = os.path.join(os.curdir, "awlsim")
	buildDir = os.path.join(os.curdir, "build", "awlsim_cython-patched.%s-%s-%d.%d" %\
		(platform.system().lower(),
		 platform.machine().lower(),
		 sys.version_info[0], sys.version_info[1])
	)

	if not os.path.exists(os.path.join(os.curdir, "setup.py")) or\
	   not os.path.exists(modDir) or\
	   not os.path.isdir(modDir):
		raise Exception("Wrong directory. "
			"Execute setup.py from within the awlsim directory.")

	makedirs(buildDir, 0o755)

	for dirpath, dirnames, filenames in os.walk(modDir):
		subpath = os.path.relpath(dirpath, modDir)
		if subpath == os.curdir:
			subpath = ""

		if subpath.startswith("gui"):
			continue
		for filename in filenames:
			if filename == "__init__.py":
				continue
			if filename.endswith(".py"):
				fromFile = os.path.join(dirpath, filename)
				toDir = os.path.join(buildDir, subpath)
				toFile = os.path.join(toDir, filename.replace(".py", ".pyx"))

				makedirs(toDir, 0o755)
				pyCythonPatch(toFile, fromFile)

				modname = [ "awlsim_cython" ]
				if subpath:
					modname.extend(subpath.split(os.sep))
				modname.append(filename[:-3]) # Strip .py
				modname = ".".join(modname)

				ext_modules.append(
					Extension(modname, [toFile])
				)
	cmdclass["build_ext"] = Cython_build_ext

def tryBuildCythonModules():
	try:
		if int(os.getenv("NOCYTHON", "0")):
			print("Skipping build of CYTHON modules due to "
			      "NOCYTHON environment variable setting.")
			return
	except ValueError:
		pass
	if os.name != "posix":
		print("WARNING: Not building CYTHON modules on '%s' platform." %\
		      os.name)
		return
	try:
		from Cython.Distutils import build_ext as Cython_build_ext
		addCythonModules(Cython_build_ext)
	except ImportError as e:
		print("WARNING: Could not build the CYTHON modules: "
		      "%s" % str(e))
		print("--> Is Cython installed?")

cmdclass = {}
ext_modules = []
# Try to build the Cython modules. This might fail.
tryBuildCythonModules()

setup(	name		= "awlsim",
	version		= "%d.%d" % (VERSION_MAJOR, VERSION_MINOR),
	description	= "Step 7 AWL/STL/PLC simulator",
	author		= "Michael Buesch",
	author_email	= "m@bues.ch",
	url		= "http://bues.ch/cms/hacking/awlsim.html",
	packages	= [ "awlsim",
			    "awlsim/gui",
			    "awlsim/instructions",
			    "awlsimhw_dummy",
			    "awlsimhw_linuxcnc",
			    "awlsimhw_pyprofibus", ],
	scripts		= [ "awlsimcli",
			    "awlsimgui",
			    "awlsim-linuxcnc-hal", ],
	cmdclass	= cmdclass,
	ext_modules	= ext_modules
)
bues.ch cgit interface